From ced4b5ef9772ea6c35ae9984d585d5447e06fba6 Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Sun, 26 Aug 2018 16:28:18 +0900 Subject: [PATCH 1/8] Many API signatures are changed to IEnumerable and IReadOnlyList --- BuildAll.bat | 2 + ChemObjectConfig.ttinclude | 13 +- Config.ttinclude | 18 +- .../Aromaticities/Aromaticity_Example.cs | 12 +- .../Config/XMLIsotopeFactory_Example.cs | 6 +- ExampleCodes/ConformerContainer_Example.cs | 7 +- ExampleCodes/ExampleCodes.csproj | 8 +- .../Fingerprints/Fingerprinter_Example.cs | 2 +- .../HybridizationFingerprinter_Example.cs | 2 +- .../PubchemFingerprinter_Example.cs | 4 +- .../ShortestPathFingerprinter_Example.cs | 2 +- .../MmffAtomTypeMatcher_Example.cs | 6 +- .../MMFF => ForceFields}/Mmff_Example.cs | 6 +- ...FullEnumerationFormulaGenerator_Example.cs | 2 +- .../MolecularFormulaGenerator_Example.cs | 2 +- .../Alignments/KabschAlignment_Example.cs | 8 +- ExampleCodes/Graphs/Cycles_Example.tt | 8 +- ExampleCodes/Graphs/Cycles_Example.tt.cs | 24 +- .../Graphs/InChI/InChIToStructure_Example.cs | 9 +- .../EnumerableMDLConformerReader_Example.cs | 9 +- .../Iterator/EnumerableSDFReader_Example.cs | 9 +- .../IO/Setting/SettingManager_Example.cs | 8 +- .../UniversalIsomorphismTester_Example.cs | 12 +- .../Builder3D/ModelBuilder3D_Example.cs | 8 +- .../PharmacophoreMatcher_Example.cs | 14 +- ExampleCodes/Program.cs | 2 +- ExampleCodes/QSAR/DescriptorEngine_Example.cs | 12 +- .../RingSearches/AllRingsFinder_Example.cs | 8 +- .../RingSearches/RingSearch_Example.cs | 5 +- .../SMARTS/SmartsFragmentExtractor_Example.cs | 33 + .../{RGraph => RGraphs}/CDKMCS_Example.cs | 9 +- ExampleCodes/SMSD/Isomorphism_Example.cs | 11 +- .../Parser/SmartsQueryVisitor_Example.cs | 8 +- .../Smiles/SMARTS/SMARTSQueryTool_Example.cs | 21 +- .../Smiles/SMARTS/SmartsPattern_Example.cs | 9 +- .../Smiles/SmilesGenerator_Example.cs | 28 +- ExampleCodes/Stereo/Stereocenters_Example.cs | 4 +- .../Tools/AtomContainerManipulator_Example.cs | 7 +- ExampleCodes/Tools/DataFeatures_Example.cs | 10 +- IncludeExamples.ttinclude | 2 +- MolViewer/AppearanceViewModel.cs | 7 +- MolViewer/AppearanceViewModel.tt | 24 +- MolViewer/AppearanceViewModel.tt.cs | 14 +- MolViewer/ChemObjectBox.cs | 18 +- MolViewer/ChemObjectBox_Prop.tt | 84 +- MolViewer/ChemObjectBox_Prop.tt.cs | 382 +-- .../ChemObjectChangedEventArgs.cs | 25 +- MolViewer/MolViewer.csproj | 1 + NCDK/Aromaticities/Aromaticity.cs | 27 +- NCDK/Aromaticities/AtomTypeModel.cs | 55 +- NCDK/Aromaticities/DaylightModel.cs | 10 +- NCDK/Aromaticities/ElectronDonation.cs | 4 +- NCDK/Aromaticities/Kekulization.cs | 9 +- NCDK/Aromaticities/PiBondModel.cs | 7 +- NCDK/AtomRef.cs | 6 + NCDK/AtomTypes/CDKAtomTypeMatcher.cs | 476 ++-- NCDK/AtomTypes/EStateAtomTypeMatcher.cs | 12 +- NCDK/AtomTypes/IAtomTypeMatcher.cs | 4 +- NCDK/AtomTypes/Mappers/AtomTypeMapper.cs | 17 +- NCDK/AtomTypes/StructGenMatcher.cs | 8 +- NCDK/AtomTypes/SybylAtomTypeMatcher.cs | 108 +- NCDK/Beam/Core/AtomBuilder.cs | 12 +- NCDK/Beam/Core/AtomImpl.cs | 34 +- NCDK/Beam/Core/BiconnectedComponents.cs | 12 +- NCDK/Beam/Core/Configuration.tt | 138 +- NCDK/Beam/Core/Configuration.tt.cs | 22 +- NCDK/Beam/Core/ElectronDonation.cs | 6 +- NCDK/Beam/Core/Element.cs | 21 +- NCDK/Beam/Core/Generator.cs | 11 +- NCDK/Beam/Core/Graph.cs | 4 +- NCDK/Beam/Core/GraphBuilder.cs | 11 +- NCDK/Beam/Core/{Function.cs => IFunction.cs} | 4 +- NCDK/Beam/Core/InvalidSmilesException.cs | 9 + NCDK/Beam/Func/AbstractFunction.cs | 14 +- NCDK/Beam/Func/FromSubsetAtoms.cs | 3 +- NCDK/Beam/Func/FromTrigonalTopology.cs | 46 +- NCDK/Beam/Func/NormaliseDirectionalLabels.cs | 30 +- NCDK/Beam/Func/RemoveUpDownBonds.cs | 10 +- NCDK/Beam/Func/ToTrigonalTopology.cs | 8 +- NCDK/BondOrder.cs | 8 +- NCDK/BondRef.cs | 6 + NCDK/CDK.cs | 2 + NCDK/CDKConstants.cs | 27 +- NCDK/CDKException.cs | 4 + NCDK/Charges/AtomTypeCharges.cs | 2 +- .../Charges/GasteigerMarsiliPartialCharges.cs | 4 +- NCDK/Charges/GasteigerPEPEPartialCharges.cs | 97 +- NCDK/Charges/InductivePartialCharges.cs | 281 +- NCDK/Charges/MMFF94PartialCharges.cs | 6 +- NCDK/Charges/Polarizability.cs | 53 +- NCDK/Charges/StabilizationCharges.cs | 16 +- NCDK/ChemObjectRef.cs | 18 +- NCDK/Common/Base/Preconditions.cs | 7 +- NCDK/Common/Collections/BitArrays.cs | 25 +- NCDK/Common/Collections/Deque.cs | 2 + NCDK/Common/Collections/Dictionaries.cs | 10 +- .../Collections/DictionaryEqualityComparer.cs | 12 +- NCDK/Common/Collections/EmptyCollections.cs | 38 + NCDK/Common/Collections/EmptyCollections.tt | 80 - .../Common/Collections/EmptyCollections.tt.cs | 80 - NCDK/Common/Collections/Lists.cs | 10 - NCDK/Common/Collections/Maps.cs | 38 - .../{MultiMap.cs => MultiDictionary.cs} | 6 +- NCDK/Common/Collections/Sets.cs | 158 +- NCDK/Common/Hash/Crc32.cs | 8 +- .../Common/Mathematics/BitsStreamGenerator.cs | 28 +- NCDK/Common/Primitives/Primitive.cs | 30 +- NCDK/Common/Primitives/Strings.cs | 11 +- .../Common/Serialization/SerializationTool.cs | 27 + NCDK/Common/Util/StreamTokenizer.cs | 102 +- NCDK/Config/AtomTypeFactory.cs | 4 +- .../{AtomType => AtomTypes}/AtomTypeReader.cs | 24 +- .../OWLAtomTypeMappingHandler.cs | 12 +- .../OWLAtomTypeMappingReader.cs | 12 +- .../OWLAtomTypeReader.cs | 18 +- .../{AtomType => AtomTypes}/OWLConstants.cs | 2 +- NCDK/Config/BODRIsotope.cs | 12 +- .../{Isotopes.cs => BODRIsotopeFactory.cs} | 98 +- NCDK/Config/CDKBasedAtomTypeConfigurator.cs | 22 +- NCDK/Config/ChemicalElement.tt | 139 +- NCDK/Config/ChemicalElement.tt.cs | 303 ++- NCDK/Config/Element.txt | 8 +- NCDK/Config/Fragments/EStateFragments.cs | 24 +- NCDK/Config/IAtomTypeConfigurator.cs | 4 +- NCDK/Config/ImmutableAtomType.cs | 9 +- NCDK/Config/IsotopeFactory.cs | 15 +- .../{Isotope => Isotopes}/IsotopeHandler.cs | 35 +- .../{Isotope => Isotopes}/IsotopeReader.cs | 20 +- NCDK/Config/NaturalElement.cs | 7 +- NCDK/Config/OWLBasedAtomTypeConfigurator.cs | 21 +- NCDK/Config/TXTBasedAtomTypeConfigurator.cs | 33 +- NCDK/Config/XMLIsotopeFactory.cs | 4 +- NCDK/ConformerContainer.cs | 37 +- NCDK/Dict/CDKDictionaryReferences.cs | 82 +- NCDK/Dict/DictRef.cs | 4 +- NCDK/Dict/DictionaryDatabase.cs | 29 +- NCDK/Dict/DictionaryHandler.cs | 19 +- NCDK/Dict/Entry.cs | 4 +- NCDK/Dict/EntryDictionary.cs | 8 +- NCDK/Dict/EntryReact.cs | 33 +- NCDK/Dict/OWLFile.cs | 17 +- NCDK/Dict/OWLReact.cs | 49 +- NCDK/DoubleBondConformation.cs | 17 +- NCDK/FaulonSignatures/AbstractGraphBuilder.cs | 2 +- .../AbstractGraphSignature.cs | 24 +- .../FaulonSignatures/AbstractQuotientGraph.cs | 4 +- .../AbstractVertexSignature.cs | 43 +- .../CanonicalLabellingVisitor.cs | 4 +- .../Chemistry/AtomPermutor.cs | 2 +- .../Chemistry/AtomSignature.cs | 43 +- .../Chemistry/ChiralCenterFinder.cs | 15 +- NCDK/FaulonSignatures/Chemistry/Molecule.cs | 4 +- .../Chemistry/MoleculeBuilder.cs | 32 +- .../Chemistry/MoleculeReader.cs | 13 +- .../Chemistry/SDFToSignatures.cs | 1 - NCDK/FaulonSignatures/ColoredTree.cs | 19 +- NCDK/FaulonSignatures/DAG.cs | 21 +- .../EdgeColored/EdgeColoredGraph.cs | 38 +- .../EdgeColored/EdgeColoredGraphFactory.cs | 2 +- .../EdgeColored/EdgeColoredGraphPermutor.cs | 2 +- .../EdgeColored/EdgeColoredGraphSignature.cs | 5 +- .../EdgeColored/EdgeColoredQuotientGraph.cs | 4 +- .../EdgeColored/EdgeColoredVertexSignature.cs | 15 +- NCDK/FaulonSignatures/InvariantArray.cs | 2 - NCDK/FaulonSignatures/InvariantInt.cs | 1 - NCDK/FaulonSignatures/InvariantIntIntPair.cs | 2 - .../InvariantIntStringPair.cs | 28 +- NCDK/FaulonSignatures/Invariants.cs | 1 - NCDK/FaulonSignatures/Simple/SimpleGraph.cs | 7 +- NCDK/FaulonSignatures/Snap.txt | 2 - NCDK/FaulonSignatures/SymmetryClass.cs | 4 +- NCDK/FaulonSignatures/VirtualGraphBuilder.cs | 2 +- NCDK/Fingerprints/AbstractFingerprinter.cs | 6 +- NCDK/Fingerprints/AtomPairs2DFingerprinter.cs | 25 +- NCDK/Fingerprints/BitSetFingerprint.cs | 30 +- NCDK/Fingerprints/CircularFingerprinter.cs | 571 ++-- NCDK/Fingerprints/EStateFingerprinter.cs | 10 +- NCDK/Fingerprints/ExtendedFingerprinter.cs | 27 +- NCDK/Fingerprints/Fingerprinter.cs | 49 +- NCDK/Fingerprints/FingerprinterTool.cs | 34 +- .../HybridizationFingerprinter.cs | 2 +- NCDK/Fingerprints/IBitFingerprint.cs | 2 +- NCDK/Fingerprints/ICountFingerprint.cs | 4 +- NCDK/Fingerprints/IFingerprinter.cs | 4 +- NCDK/Fingerprints/IntArrayCountFingerprint.cs | 14 +- NCDK/Fingerprints/IntArrayFingerprint.cs | 8 +- NCDK/Fingerprints/LingoFingerprinter.cs | 11 +- NCDK/Fingerprints/MACCSFingerprinter.cs | 49 +- NCDK/Fingerprints/Model/Bayesian.cs | 293 +- NCDK/Fingerprints/PubchemFingerprinter.cs | 46 +- .../Fingerprints/ShortestPathFingerprinter.cs | 22 +- NCDK/Fingerprints/ShortestPathWalker.cs | 33 +- NCDK/Fingerprints/SignatureFingerprinter.cs | 7 +- NCDK/Fingerprints/SimpleAtomCanonicalizer.cs | 12 +- NCDK/Fingerprints/SimpleAtomComparator.cs | 1 - NCDK/Fingerprints/StandardSubstructureSets.cs | 2 +- .../Fingerprints/SubstructureFingerprinter.cs | 4 +- .../MMFF/README => ForceFields/MMFF.README} | 0 .../MMFF => ForceFields}/MMFFCHG.PAR | 0 .../MMFF => ForceFields}/MMFFFORMCHG.PAR | 0 .../MMFF => ForceFields}/MMFFPBCI.PAR | 0 .../MMFF => ForceFields}/MMFFPROP.PAR | 0 .../MMFF => ForceFields}/MMFFSYMB.sma | 0 NCDK/{ForceField/MMFF => ForceFields}/Mmff.cs | 218 +- .../MmffAromaticTypeMapping.cs | 92 +- .../MmffAtomTypeMatcher.cs | 26 +- .../MMFF => ForceFields}/MmffParamSet.cs | 51 +- .../mmff-symb-mapping.tsv | 0 .../FullEnumerationFormulaGenerator.cs | 24 +- NCDK/Formula/IsotopeContainer.cs | 40 +- NCDK/Formula/IsotopePattern.cs | 63 +- NCDK/Formula/IsotopePatternGenerator.cs | 108 +- NCDK/Formula/IsotopePatternManipulator.cs | 44 +- NCDK/Formula/IsotopePatternSimilarity.cs | 6 +- NCDK/Formula/MolecularFormula.cs | 54 +- NCDK/Formula/MolecularFormula.tt.cs | 11 +- NCDK/Formula/MolecularFormulaChecker.cs | 17 +- NCDK/Formula/MolecularFormulaGenerator.cs | 41 +- NCDK/Formula/MolecularFormulaRange.cs | 13 +- NCDK/Formula/MolecularFormulaSet.cs | 3 +- NCDK/Formula/RoundRobinFormulaGenerator.cs | 7 +- NCDK/Formula/Rules/ChargeRule.cs | 9 +- NCDK/Formula/Rules/ElementRule.cs | 5 +- NCDK/Formula/Rules/IRule.cs | 4 +- NCDK/Formula/Rules/IsotopePatternRule.cs | 11 +- NCDK/Formula/Rules/MMElementRule.cs | 13 +- NCDK/Formula/Rules/NitrogenRule.cs | 7 +- NCDK/Formula/Rules/RDBERule.cs | 29 +- NCDK/Formula/Rules/ToleranceRangeRule.cs | 5 +- NCDK/Fragments/ExhaustiveFragmenter.cs | 2 +- NCDK/Fragments/MurckoFragmenter.cs | 25 +- NCDK/Geometries/Alignments/KabschAlignment.cs | 75 +- NCDK/Geometries/AtomTools.cs | 16 +- NCDK/Geometries/BondTools.cs | 37 +- NCDK/Geometries/CIP/CIPTool.cs | 152 +- NCDK/Geometries/CIP/ILigand.cs | 14 +- NCDK/Geometries/CIP/ImmutableHydrogen.cs | 12 +- NCDK/Geometries/CIP/LigancyFourChirality.cs | 65 +- NCDK/Geometries/CIP/Ligand.cs | 29 +- NCDK/Geometries/CIP/Rules/AtomicNumberRule.cs | 9 +- NCDK/Geometries/CIP/Rules/CIPLigandRule.cs | 44 +- .../CIP/Rules/CombinedAtomicMassNumberRule.cs | 10 +- NCDK/Geometries/CIP/Rules/ISequenceSubRule.cs | 2 +- NCDK/Geometries/CIP/Rules/MassNumberRule.cs | 9 +- NCDK/Geometries/GeometryUtil.cs | 282 +- NCDK/Geometries/RDFCalculator.cs | 12 +- NCDK/Geometries/Surface/NeighborList.cs | 5 +- NCDK/Geometries/Surface/NumericalSurface.cs | 33 +- NCDK/Geometries/Surface/Tessellate.cs | 45 +- NCDK/Geometries/Volume/VABCVolume.cs | 17 +- NCDK/Geometries/ZMatrixTools.cs | 40 +- NCDK/GlobalSuppressions.cs | 149 + NCDK/Graphs/AllPairsShortestPaths.cs | 21 +- NCDK/Graphs/AtomContainerAtomPermutor.cs | 6 +- NCDK/Graphs/AtomContainerBondPermutor.cs | 2 +- NCDK/Graphs/AtomContainerPermutor.cs | 6 +- NCDK/Graphs/BitMatrix.cs | 3 +- NCDK/Graphs/ConnectivityChecker.cs | 44 +- NCDK/Graphs/Cycles.cs | 40 +- NCDK/Graphs/EdmondsMaximumMatching.cs | 3 +- NCDK/Graphs/GraphUtil.cs | 147 +- NCDK/Graphs/GreedyBasis.cs | 3 +- NCDK/Graphs/InChI/InChIGenerator.cs | 12 +- NCDK/Graphs/InChI/InChIGeneratorFactory.cs | 42 +- NCDK/Graphs/InChI/InChIToStructure.cs | 85 +- NCDK/Graphs/InChI/NInChIInputAdapter.cs | 4 +- NCDK/Graphs/InChI/NInchiAtom.cs | 3 +- NCDK/Graphs/InChI/NInchiException.cs | 6 +- NCDK/Graphs/InChI/NInchiOutputStructure.cs | 8 +- NCDK/Graphs/InChI/NInchiWrapper.cs | 4 +- NCDK/Graphs/InitialCycles.cs | 53 +- .../Invariant/BadMatrixFormatException.cs | 11 + NCDK/Graphs/Invariant/Canon.cs | 9 +- NCDK/Graphs/Invariant/CanonicalLabeler.cs | 32 +- .../Invariant/ConjugatedPiSystemsDetector.cs | 2 +- .../Invariant/EquivalentClassPartitioner.cs | 60 +- NCDK/Graphs/Invariant/GIMatrix.cs | 219 +- NCDK/Graphs/Invariant/HuLuIndexTool.cs | 10 +- NCDK/Graphs/Invariant/InChINumbersTools.cs | 82 +- .../Invariant/MatrixNotInvertibleException.cs | 13 +- NCDK/Graphs/Invariant/MorganNumbersTools.cs | 4 +- NCDK/Graphs/JumboPathGraph.cs | 6 +- NCDK/Graphs/PathTools.cs | 23 +- NCDK/Graphs/Rebond/Bspt.cs | 6 +- NCDK/Graphs/Rebond/RebondTool.cs | 23 +- NCDK/Graphs/RegularPathGraph.cs | 28 +- NCDK/Graphs/ShortestPaths.cs | 6 +- NCDK/Graphs/SpanningTree.cs | 15 +- .../AbstractDiscretePartitionRefiner.cs | 8 +- NCDK/Groups/AtomDiscretePartitionRefiner.cs | 4 +- NCDK/Groups/BondDiscretePartitionRefiner.cs | 2 +- NCDK/Groups/BondRefinable.cs | 7 +- NCDK/Groups/IntegerInvariant.cs | 4 +- NCDK/Groups/Partition.cs | 7 +- NCDK/Groups/PartitionRefinement.cs | 65 +- NCDK/Groups/Permutation.cs | 81 +- NCDK/Groups/PermutationGroup.cs | 58 +- NCDK/Hash/AbstractAtomHashGenerator.cs | 11 +- NCDK/Hash/AbstractHashGenerator.cs | 8 +- NCDK/Hash/AtomSuppression.cs | 3 +- NCDK/Hash/BasicAtomEncoder.tt | 11 +- NCDK/Hash/BasicAtomEncoder.tt.cs | 27 +- NCDK/Hash/BasicAtomHashGenerator.cs | 14 +- NCDK/Hash/BasicMoleculeHashGenerator.cs | 4 +- NCDK/Hash/ConjugatedAtomEncoder.cs | 26 +- NCDK/Hash/HashGeneratorMaker.cs | 8 +- NCDK/Hash/IAtomHashGenerator.cs | 2 + NCDK/Hash/PerturbedAtomHashGenerator.cs | 8 +- NCDK/Hash/SeedGenerator.cs | 4 +- NCDK/Hash/Stereo/BasicPermutationParity.cs | 3 +- .../GeometricCumulativeDoubleBondFactory.cs | 4 +- NCDK/Hash/Stereo/MultiStereoEncoder.cs | 8 +- NCDK/Hash/Stereo/StereoEncoder.cs | 6 +- NCDK/Hash/Suppressed.cs | 3 +- NCDK/Hash/SuppressedAtomHashGenerator.cs | 15 +- NCDK/Hybridization.cs | 34 +- NCDK/IAdductFormula.cs | 4 +- NCDK/IAtomContainer.cs | 2 +- NCDK/IAtomContainerSet.cs | 2 +- NCDK/IBioPolymer.cs | 2 +- NCDK/IBond.cs | 2 + NCDK/IChemObject.cs | 6 +- NCDK/IChemObjectBuilder.cs | 2 +- NCDK/IChemObjectListener.cs | 6 +- NCDK/IHasProperties.tt | 6 +- NCDK/IHasProperties.tt.cs | 12 +- NCDK/IMolecularFormula.cs | 2 +- NCDK/IMolecularFormulaSet.cs | 7 +- NCDK/IO/CIFReader.cs | 51 +- NCDK/IO/CML/CDKConvention.cs | 7 +- NCDK/IO/CML/CMLCoreModule.cs | 2387 ++++++++--------- NCDK/IO/CML/CMLHandler.cs | 81 +- NCDK/IO/CML/CMLReactionModule.cs | 83 +- NCDK/IO/CML/CMLResolver.cs | 14 +- NCDK/IO/CML/CMLStack.cs | 9 +- NCDK/IO/CML/JMOLANIMATIONConvention.cs | 15 +- NCDK/IO/CML/MDLMolConvention.cs | 19 +- NCDK/IO/CML/PDBConvention.cs | 404 ++- NCDK/IO/CML/PMPConvention.cs | 78 +- NCDK/IO/CML/QSARConvention.cs | 17 +- NCDK/IO/CMLReader.cs | 19 +- NCDK/IO/CMLWriter.cs | 30 +- NCDK/IO/CTXReader.cs | 25 +- NCDK/IO/ChemObjectIO.cs | 4 +- NCDK/IO/CrystClustReader.cs | 19 +- NCDK/IO/CrystClustWriter.cs | 19 +- NCDK/IO/DefaultChemObjectReader.cs | 11 +- NCDK/IO/FormatFactory.cs | 20 +- NCDK/IO/Formats/ABINITFormat.cs | 8 +- NCDK/IO/Formats/ADFFormat.cs | 5 +- NCDK/IO/Formats/AbstractResourceFormat.cs | 3 +- NCDK/IO/Formats/Aces2Format.cs | 5 +- NCDK/IO/Formats/AlchemyFormat.cs | 3 +- NCDK/IO/Formats/BGFFormat.cs | 3 +- NCDK/IO/Formats/BSFormat.cs | 3 +- NCDK/IO/Formats/CACheFormat.cs | 3 +- NCDK/IO/Formats/CDKOWLFormat.cs | 11 +- NCDK/IO/Formats/CIFFormat.cs | 3 +- NCDK/IO/Formats/CMLFormat.cs | 20 +- NCDK/IO/Formats/CMLRSSFormat.cs | 7 +- NCDK/IO/Formats/CRK2DFormat.cs | 3 +- NCDK/IO/Formats/CRK3DFormat.cs | 3 +- NCDK/IO/Formats/CTXFormat.cs | 3 +- NCDK/IO/Formats/CacaoCartesianFormat.cs | 3 +- NCDK/IO/Formats/CacaoInternalFormat.cs | 3 +- NCDK/IO/Formats/Chem3D_Cartesian_1Format.cs | 9 +- NCDK/IO/Formats/Chem3D_Cartesian_2Format.cs | 9 +- NCDK/IO/Formats/ChemDrawFormat.cs | 3 +- NCDK/IO/Formats/ChemtoolFormat.cs | 3 +- NCDK/IO/Formats/CrystClustFormat.cs | 7 +- NCDK/IO/Formats/DMol3Format.cs | 3 +- NCDK/IO/Formats/DOCK5Format.cs | 3 +- NCDK/IO/Formats/DaltonFormat.cs | 5 +- NCDK/IO/Formats/FenskeHall_ZMatrixFormat.cs | 9 +- NCDK/IO/Formats/FingerprintFormat.cs | 3 +- NCDK/IO/Formats/GROMOS96Format.cs | 3 +- NCDK/IO/Formats/GamessFormat.cs | 5 +- NCDK/IO/Formats/Gaussian03Format.cs | 5 +- NCDK/IO/Formats/Gaussian90Format.cs | 5 +- NCDK/IO/Formats/Gaussian92Format.cs | 6 +- NCDK/IO/Formats/Gaussian94Format.cs | 5 +- NCDK/IO/Formats/Gaussian95Format.cs | 5 +- NCDK/IO/Formats/Gaussian98Format.cs | 6 +- NCDK/IO/Formats/GaussianInputFormat.cs | 3 +- NCDK/IO/Formats/GhemicalMMFormat.cs | 3 +- NCDK/IO/Formats/GhemicalSPMFormat.cs | 3 +- NCDK/IO/Formats/HINFormat.cs | 13 +- NCDK/IO/Formats/IChemFormatMatcher.cs | 22 +- NCDK/IO/Formats/IResourceFormat.cs | 4 +- NCDK/IO/Formats/InChIFormat.cs | 5 +- NCDK/IO/Formats/InChIPlainTextFormat.cs | 3 +- NCDK/IO/Formats/JMEFormat.cs | 3 +- NCDK/IO/Formats/JaguarFormat.cs | 5 +- NCDK/IO/Formats/MDLFormat.cs | 19 +- NCDK/IO/Formats/MDLRXNV2000Format.cs | 21 +- NCDK/IO/Formats/MDLRXNV3000Format.cs | 4 +- NCDK/IO/Formats/MDLV2000Format.cs | 15 +- NCDK/IO/Formats/MDLV3000Format.cs | 6 +- NCDK/IO/Formats/MMODFormat.cs | 3 +- NCDK/IO/Formats/MOPAC2002Format.cs | 5 +- NCDK/IO/Formats/MOPAC2007Format.cs | 3 +- NCDK/IO/Formats/MOPAC2009Format.cs | 3 +- NCDK/IO/Formats/MOPAC2012Format.cs | 3 +- NCDK/IO/Formats/MOPAC7Format.cs | 3 +- NCDK/IO/Formats/MOPAC7InputFormat.cs | 3 +- NCDK/IO/Formats/MOPAC93Format.cs | 3 +- NCDK/IO/Formats/MOPAC97Format.cs | 3 +- NCDK/IO/Formats/MPQCFormat.cs | 3 +- NCDK/IO/Formats/MacroModelFormat.cs | 3 +- NCDK/IO/Formats/MoSSOutputFormat.cs | 10 +- NCDK/IO/Formats/Mol2Format.cs | 11 +- NCDK/IO/Formats/NCDKSourceCodeFormat.cs | 7 +- NCDK/IO/Formats/NWChemFormat.cs | 5 +- NCDK/IO/Formats/PCModelFormat.cs | 3 +- NCDK/IO/Formats/PDBFormat.cs | 7 +- NCDK/IO/Formats/PDBMLFormat.cs | 3 +- NCDK/IO/Formats/PMPFormat.cs | 3 +- NCDK/IO/Formats/POVRayFormat.cs | 4 +- NCDK/IO/Formats/PQSChemFormat.cs | 3 +- NCDK/IO/Formats/PubChemASNFormat.cs | 3 +- NCDK/IO/Formats/PubChemCompoundXMLFormat.cs | 17 +- NCDK/IO/Formats/PubChemCompoundsXMLFormat.cs | 3 +- NCDK/IO/Formats/PubChemFormat.cs | 3 +- NCDK/IO/Formats/PubChemSubstanceXMLFormat.cs | 20 +- NCDK/IO/Formats/PubChemSubstancesASNFormat.cs | 6 +- NCDK/IO/Formats/PubChemSubstancesXMLFormat.cs | 3 +- NCDK/IO/Formats/QChemFormat.cs | 5 +- NCDK/IO/Formats/RGroupQueryFormat.cs | 9 +- NCDK/IO/Formats/RawCopyFormat.cs | 3 +- NCDK/IO/Formats/SDFFormat.cs | 12 +- NCDK/IO/Formats/SMARTSFormat.cs | 4 +- NCDK/IO/Formats/SMILESFIXFormat.cs | 3 +- NCDK/IO/Formats/SMILESFormat.cs | 7 +- NCDK/IO/Formats/SVGFormat.cs | 4 +- NCDK/IO/Formats/ShelXFormat.cs | 7 +- NCDK/IO/Formats/SimpleChemFormatMatcher.cs | 13 +- NCDK/IO/Formats/SpartanFormat.cs | 5 +- NCDK/IO/Formats/SybylDescriptorFormat.cs | 3 +- NCDK/IO/Formats/TinkerMM2Format.cs | 3 +- NCDK/IO/Formats/TinkerXYZFormat.cs | 3 +- NCDK/IO/Formats/TurboMoleFormat.cs | 3 +- NCDK/IO/Formats/UniChemXYZFormat.cs | 3 +- NCDK/IO/Formats/VASPFormat.cs | 5 +- NCDK/IO/Formats/ViewmolFormat.cs | 3 +- NCDK/IO/Formats/XEDFormat.cs | 3 +- NCDK/IO/Formats/XYZFormat.cs | 7 +- NCDK/IO/Formats/YasaraFormat.cs | 3 +- NCDK/IO/Formats/ZMatrixFormat.cs | 5 +- NCDK/IO/Formats/ZindoFormat.cs | 3 +- NCDK/IO/GamessReader.cs | 12 +- NCDK/IO/Gaussian03Reader.cs | 48 +- NCDK/IO/Gaussian98Reader.cs | 56 +- NCDK/IO/GaussianInputWriter.cs | 40 +- NCDK/IO/GhemicalMMReader.cs | 53 +- NCDK/IO/HINReader.cs | 23 +- NCDK/IO/HINWriter.cs | 11 +- NCDK/IO/IChemObjectWriter.cs | 4 +- NCDK/IO/ISimpleChemObjectReader.cs | 4 +- NCDK/IO/InChI/InChIContentProcessorTool.cs | 48 +- NCDK/IO/InChI/InChIHandler.cs | 60 +- NCDK/IO/InChIContentProcessorTool.cs | 43 +- NCDK/IO/InChIPlainTextReader.cs | 12 +- NCDK/IO/InChIReader.cs | 38 +- .../Iterator/EnumerableMDLConformerReader.cs | 2 +- .../Iterator/EnumerablePCCompoundASNReader.cs | 10 +- .../Iterator/EnumerablePCCompoundXMLReader.cs | 4 +- NCDK/IO/Iterator/EnumerableSDFReader.cs | 22 +- NCDK/IO/Iterator/EnumerableSMILESReader.cs | 6 +- NCDK/IO/Listener/IReaderListener.cs | 4 +- NCDK/IO/Listener/PropertiesListener.cs | 7 +- NCDK/IO/Listener/TextGUIListener.cs | 17 +- NCDK/IO/MDLRXNReader.cs | 25 +- NCDK/IO/MDLRXNV2000Reader.cs | 27 +- NCDK/IO/MDLRXNV3000Reader.cs | 25 +- NCDK/IO/MDLRXNWriter.cs | 8 +- NCDK/IO/MDLReader.cs | 72 +- NCDK/IO/MDLV2000Reader.cs | 280 +- NCDK/IO/MDLV2000Writer.cs | 65 +- NCDK/IO/MDLV3000Reader.cs | 104 +- NCDK/IO/MDLV3000Writer.cs | 44 +- NCDK/IO/MDMoleculeConvention.cs | 50 +- NCDK/IO/MoSSOutputReader.cs | 2 +- NCDK/IO/Mol2Reader.cs | 83 +- NCDK/IO/Mol2Writer.cs | 40 +- NCDK/IO/Mopac7Reader.cs | 99 +- NCDK/IO/Mopac7Writer.cs | 15 +- NCDK/IO/NCDKSourceCodeWriter.cs | 27 +- NCDK/IO/PCCompoundASNReader.cs | 84 +- NCDK/IO/PDBReader.cs | 85 +- NCDK/IO/PDBWriter.cs | 39 +- NCDK/IO/PMPReader.cs | 128 +- NCDK/IO/PubChemXml/PubChemXMLHelper.cs | 37 +- NCDK/IO/RDF/CDKOWLReader.cs | 6 +- NCDK/IO/RGroupQueryReader.cs | 40 +- NCDK/IO/RGroupQueryWriter.cs | 9 +- .../DefaultRandomAccessChemObjectReader.cs | 4 +- NCDK/IO/RandomAccess/RandomAccessReader.cs | 98 +- NCDK/IO/RandomAccess/RandomAccessSDFReader.cs | 37 +- NCDK/IO/ReaderFactory.cs | 11 +- NCDK/IO/RssWriter.cs | 53 +- NCDK/IO/SDFWriter.cs | 46 +- NCDK/IO/SMILESReader.cs | 4 +- NCDK/IO/SMILESWriter.cs | 6 +- NCDK/IO/Setting/BooleanIOSetting.cs | 37 +- NCDK/IO/Setting/IOSetting.cs | 43 +- NCDK/IO/Setting/IntegerIOSetting.cs | 4 +- NCDK/IO/ShelXReader.cs | 26 +- NCDK/IO/ShelXWriter.cs | 38 +- NCDK/IO/VASPReader.cs | 38 +- NCDK/IO/WriterFactory.cs | 2 +- NCDK/IO/XYZReader.cs | 13 +- NCDK/IO/ZMatrixReader.cs | 29 +- NCDK/IPDBPolymer.cs | 8 +- NCDK/IRing.cs | 2 +- NCDK/IStereoElement.cs | 20 +- NCDK/ITetrahedralChirality.cs | 2 +- NCDK/IncludeExamples.xml | 166 +- NCDK/Indexes/CASNumber.cs | 11 +- NCDK/IntractableException.cs | 9 +- NCDK/InvalidSmilesException.cs | 4 + NCDK/Isomorphisms/AtomMappingTools.cs | 31 +- NCDK/Isomorphisms/AtomMatcher.cs | 2 +- NCDK/Isomorphisms/ComponentGrouping.cs | 3 +- NCDK/Isomorphisms/IsomorphismTester.cs | 5 +- NCDK/Isomorphisms/MCSS/RGraph.cs | 24 +- NCDK/Isomorphisms/MCSS/RNode.cs | 4 +- NCDK/Isomorphisms/Mappings.cs | 32 +- NCDK/Isomorphisms/Matchers/CTFileQueryBond.cs | 4 +- NCDK/Isomorphisms/Matchers/IRGroupQuery.cs | 8 +- .../Matchers/InverseSymbolSetQueryAtom.cs | 10 +- NCDK/Isomorphisms/Matchers/QueryAtom.cs | 7 +- .../Matchers/QueryAtomContainer.cs | 3 +- .../Matchers/QueryAtomContainerCreator.cs | 67 +- NCDK/Isomorphisms/Matchers/QueryBond.cs | 7 +- NCDK/Isomorphisms/Matchers/QueryChemObject.cs | 3 +- NCDK/Isomorphisms/Matchers/RGroupList.cs | 39 +- NCDK/Isomorphisms/Matchers/RGroupQuery.cs | 85 +- .../Matchers/SMARTS/AliphaticSymbolAtom.cs | 4 +- .../Matchers/SMARTS/AromaticSymbolAtom.cs | 4 +- .../Matchers/SMARTS/HydrogenAtom.cs | 6 +- .../Matchers/SMARTS/LogicalOperatorAtom.cs | 38 +- .../Matchers/SMARTS/LogicalOperatorBond.cs | 7 +- .../Matchers/SMARTS/NonCHHeavyAtom.cs | 4 +- .../Matchers/SMARTS/ReactionRoleQueryAtom.cs | 39 +- .../Matchers/SMARTS/SMARTSAtom.cs | 7 +- .../Matchers/SMARTS/SMARTSAtomInvariants.cs | 28 +- .../Matchers/SMARTS/StereoBond.cs | 2 +- .../Matchers/SymbolAndChargeQueryAtom.cs | 5 +- .../Matchers/SymbolChargeIDQueryAtom.cs | 6 +- NCDK/Isomorphisms/Matchers/SymbolQueryAtom.cs | 9 +- .../Matchers/SymbolSetQueryAtom.cs | 2 - NCDK/Isomorphisms/SmartsStereoMatch.cs | 26 +- NCDK/Isomorphisms/StereoMatch.cs | 29 +- NCDK/Isomorphisms/Ullmann.cs | 4 +- NCDK/Isomorphisms/UllmannState.cs | 2 +- NCDK/Isomorphisms/UniqueAtomMatches.cs | 2 +- .../UniversalIsomorphismTester.cs | 391 ++- NCDK/Isomorphisms/VFState.cs | 3 +- NCDK/Isomorphisms/VFSubState.cs | 3 +- NCDK/Layout/AtomPlacer.cs | 272 +- NCDK/Layout/Congestion.cs | 6 +- NCDK/Layout/CorrectGeometricConfiguration.cs | 6 +- NCDK/Layout/HydrogenPlacer.cs | 4 +- NCDK/Layout/IdentityTemplateLibrary.cs | 17 +- NCDK/Layout/LayoutRefiner.cs | 10 +- NCDK/Layout/MacroCycleLayout.cs | 16 +- NCDK/Layout/NonplanarBonds.cs | 334 +-- NCDK/Layout/RingPlacer.cs | 62 +- NCDK/Layout/StructureDiagramGenerator.cs | 834 +++--- NCDK/Layout/TemplateHandler.cs | 3 +- NCDK/LibIO/CML/CMLAtomArray.cs | 31 +- NCDK/LibIO/CML/CMLElement.cs | 11 +- NCDK/LibIO/CML/CMLElementBodies.tt.cs | 58 +- NCDK/LibIO/CML/CMLFormula.cs | 88 +- NCDK/LibIO/CML/CMLMolecule.cs | 6 +- NCDK/LibIO/CML/CMLScalar.cs | 10 +- NCDK/LibIO/CML/ConfigCML.ttinclude | 6 +- NCDK/LibIO/CML/Convertor.cs | 346 ++- NCDK/LibIO/CML/PDBAtomCustomizer.cs | 2 +- NCDK/LibIO/CML/QSARCustomizer.cs | 19 +- NCDK/LibIO/DotNetRDF/Convertor.cs | 15 +- NCDK/Maths/MersenneTwister.cs | 2 +- NCDK/Maths/Primes.cs | 3 +- NCDK/Maths/RandomNumbersTool.cs | 61 +- NCDK/Modelings/Builder3D/AtomPlacer3D.cs | 97 +- .../AtomTetrahedralLigandPlacer3D.cs | 220 +- .../Builder3D/ForceFieldConfigurator.cs | 74 +- .../Builder3D/MM2BasedAtomTypePattern.cs | 2 +- .../Builder3D/MM2BasedParameterSetReader.cs | 677 ++--- .../MMFF94BasedParameterSetReader.cs | 119 +- .../Builder3D/MMFF94ParametersCall.cs | 18 +- NCDK/Modelings/Builder3D/ModelBuilder3D.cs | 50 +- NCDK/Modelings/Builder3D/TemplateExtractor.cs | 150 +- NCDK/Modelings/Builder3D/TemplateHandler3D.cs | 38 +- NCDK/NCDK.csproj | 71 +- NCDK/NCDK.ruleset | 78 + NCDK/NCDKUtil.cs | 2 +- NCDK/NoSuchAtomException.cs | 8 + NCDK/NoSuchAtomTypeException.cs | 8 + NCDK/Normalizers/Normalizer.cs | 6 +- NCDK/Normalizers/SMSDNormalizer.cs | 2 +- NCDK/Numerics/Plane.cs | 3 +- NCDK/Numerics/Vector.tt | 1 + NCDK/Numerics/Vector.tt.cs | 1 + NCDK/ObservableChemObjectCollection.cs | 5 +- NCDK/Pharmacophore/PharmacophoreAtom.cs | 2 +- NCDK/Pharmacophore/PharmacophoreBond.cs | 2 +- NCDK/Pharmacophore/PharmacophoreMatcher.cs | 70 +- NCDK/Pharmacophore/PharmacophoreQuery.cs | 5 +- .../PharmacophoreQueryAngleBond.cs | 2 +- NCDK/Pharmacophore/PharmacophoreQueryAtom.cs | 3 +- NCDK/Pharmacophore/PharmacophoreQueryBond.cs | 5 +- NCDK/Pharmacophore/PharmacophoreUtils.cs | 41 +- NCDK/Proteins/ProteinPocketFinder.cs | 143 +- NCDK/QSAR/AbstractDescriptor.cs | 4 +- NCDK/QSAR/AtomValenceTool.cs | 4 +- NCDK/QSAR/DescriptorEngine.cs | 75 +- NCDK/QSAR/DescriptorException.cs | 8 + NCDK/QSAR/DescriptorValue.cs | 23 +- .../AtomPair/PiContactDetectionDescriptor.cs | 16 +- .../Descriptors/Atomic/$AtomicDescriptor.tt | 42 +- .../Atomic/$AtomicDescriptor.tt.cs | 406 +-- .../Descriptors/Atomic/$ProtonDescriptor.tt | 70 +- .../Atomic/$ProtonDescriptor.tt.cs | 240 +- .../Atomic/AtomDegreeDescriptor.cs | 15 +- .../Atomic/AtomHybridizationDescriptor.cs | 10 +- .../AtomHybridizationVSEPRDescriptor.cs | 16 +- .../Atomic/AtomValenceDescriptor.cs | 8 +- .../Atomic/BondsToAtomDescriptor.cs | 10 +- .../Atomic/CovalentRadiusDescriptor.cs | 12 +- .../Atomic/DistanceToAtomDescriptor.cs | 14 +- .../EffectiveAtomPolarizabilityDescriptor.cs | 22 +- .../Atomic/IPAtomicHOSEDescriptor.cs | 55 +- .../InductiveAtomicHardnessDescriptor.cs | 14 +- .../InductiveAtomicSoftnessDescriptor.cs | 12 +- .../IsProtonInAromaticSystemDescriptor.cs | 15 +- .../IsProtonInConjugatedPiSystemDescriptor.cs | 27 +- .../Atomic/PartialPiChargeDescriptor.cs | 25 +- .../Atomic/PartialSigmaChargeDescriptor.cs | 14 +- .../Atomic/PartialTChargeMMFF94Descriptor.cs | 22 +- .../Atomic/PartialTChargePEOEDescriptor.cs | 41 +- .../Atomic/PeriodicTablePositionDescriptor.cs | 99 +- .../Atomic/PiElectronegativityDescriptor.cs | 31 +- .../Atomic/ProtonAffinityHOSEDescriptor.cs | 37 +- .../ProtonTotalPartialChargeDescriptor.cs | 12 +- .../Atomic/RDFProtonDescriptor_G3R.cs | 15 +- .../Atomic/RDFProtonDescriptor_GDR.cs | 15 +- .../Atomic/RDFProtonDescriptor_GHR.cs | 15 +- .../Atomic/RDFProtonDescriptor_GHR_topol.cs | 15 +- .../Atomic/RDFProtonDescriptor_GSR.cs | 15 +- .../SigmaElectronegativityDescriptor.cs | 16 +- .../StabilizationPlusChargeDescriptor.cs | 22 +- .../Descriptors/Atomic/VdWRadiusDescriptor.cs | 8 +- .../QSAR/Descriptors/Bonds/$BondDescriptor.tt | 42 +- .../Descriptors/Bonds/$BondDescriptor.tt.cs | 62 +- .../Bonds/AtomicNumberDifferenceDescriptor.cs | 14 +- .../Bonds/BondPartialPiChargeDescriptor.cs | 25 +- .../Bonds/BondPartialSigmaChargeDescriptor.cs | 14 +- .../Bonds/BondPartialTChargeDescriptor.cs | 25 +- .../BondSigmaElectronegativityDescriptor.cs | 16 +- .../Descriptors/Moleculars/ALOGPDescriptor.cs | 401 +-- .../Descriptors/Moleculars/APolDescriptor.cs | 12 +- .../Moleculars/AcidicGroupCountDescriptor.cs | 16 +- .../Moleculars/AminoAcidCountDescriptor.cs | 23 +- .../AromaticAtomsCountDescriptor.cs | 14 +- .../AromaticBondsCountDescriptor.cs | 36 +- .../Moleculars/AtomCountDescriptor.cs | 25 +- .../AutocorrelationDescriptorCharge.cs | 12 +- .../AutocorrelationDescriptorMass.cs | 23 +- ...AutocorrelationDescriptorPolarizability.cs | 17 +- .../Descriptors/Moleculars/BCUTDescriptor.cs | 35 +- .../Descriptors/Moleculars/BPolDescriptor.cs | 12 +- .../Moleculars/BasicGroupCountDescriptor.cs | 15 +- .../Moleculars/BondCountDescriptor.cs | 31 +- .../Descriptors/Moleculars/CPSADescriptor.cs | 14 +- .../Moleculars/CarbonTypesDescriptor.cs | 17 +- .../Moleculars/ChiChainDescriptor.cs | 35 +- .../Moleculars/ChiClusterDescriptor.cs | 32 +- .../Descriptors/Moleculars/ChiIndexUtils.cs | 89 +- .../Moleculars/ChiPathClusterDescriptor.cs | 28 +- .../Moleculars/ChiPathDescriptor.cs | 110 +- .../EccentricConnectivityIndexDescriptor.cs | 8 +- .../Descriptors/Moleculars/FMFDescriptor.cs | 8 +- .../Moleculars/FractionalPSADescriptor.cs | 14 +- .../FragmentComplexityDescriptor.cs | 14 +- .../GravitationalIndexDescriptor.cs | 17 +- .../HBondAcceptorCountDescriptor.cs | 29 +- .../Moleculars/HBondDonorCountDescriptor.cs | 54 +- .../HybridizationRatioDescriptor.cs | 12 +- .../Moleculars/KappaShapeIndicesDescriptor.cs | 8 +- .../Moleculars/KierHallSmartsDescriptor.cs | 27 +- .../Moleculars/LargestChainDescriptor.cs | 12 +- .../Moleculars/LargestPiSystemDescriptor.cs | 19 +- .../Moleculars/LengthOverBreadthDescriptor.cs | 14 +- .../LongestAliphaticChainDescriptor.cs | 16 +- .../Descriptors/Moleculars/MDEDescriptor.cs | 14 +- .../Moleculars/MannholdLogPDescriptor.cs | 16 +- .../Moleculars/MomentOfInertiaDescriptor.cs | 12 +- .../Moleculars/PetitjeanNumberDescriptor.cs | 8 +- .../PetitjeanShapeIndexDescriptor.cs | 8 +- .../RotatableBondsCountDescriptor.cs | 27 +- .../Moleculars/RuleOfFiveDescriptor.cs | 14 +- .../Moleculars/SmallRingDescriptor.cs | 64 +- .../Descriptors/Moleculars/TPSADescriptor.cs | 136 +- .../Descriptors/Moleculars/VABCDescriptor.cs | 14 +- .../Moleculars/VAdjMaDescriptor.cs | 8 +- .../Descriptors/Moleculars/WHIMDescriptor.cs | 243 +- .../Moleculars/WeightDescriptor.cs | 30 +- .../Moleculars/WeightedPathDescriptor.cs | 10 +- .../Moleculars/WienerNumbersDescriptor.cs | 14 +- .../Descriptors/Moleculars/XLogPDescriptor.cs | 424 ++- .../Moleculars/ZagrebIndexDescriptor.cs | 13 +- .../Proteins/TaeAminoAcidDescriptor.cs | 20 +- .../Substances/OxygenAtomCountDescriptor.cs | 12 +- NCDK/QSAR/IAtomicDescriptor | 10 +- NCDK/QSAR/IDescriptor.cs | 2 +- NCDK/QSAR/Results/ArrayResult.cs | 4 +- NCDK/QSAR/Results/Result.cs | 12 +- .../Mechanisms/AdductionLPMechanism.cs | 7 +- .../Mechanisms/AdductionPBMechanism.cs | 10 +- .../HeterolyticCleavageMechanism.cs | 7 +- .../Mechanisms/HomolyticCleavageMechanism.cs | 7 +- .../RadicalSiteIonizationMechanism.cs | 10 +- .../RadicalSiteRearrangementMechanism.cs | 7 +- .../RearrangementChargeMechanism.cs | 7 +- .../Mechanisms/RemovingSEofBMechanism.cs | 7 +- .../Mechanisms/RemovingSEofNBMechanism.cs | 4 +- .../Mechanisms/SharingElectronMechanism.cs | 5 +- .../Mechanisms/TautomerizationMechanism.cs | 7 +- NCDK/Reactions/ReactionEngine.cs | 9 +- NCDK/Reactions/Types/$ExampleCodes.tt | 6 +- .../Types/AbstractAdductionLPReaction.cs | 19 +- .../Types/AbstractElectronImpactDBReaction.cs | 4 +- .../AbstractHeterolyticCleavageReaction.cs | 4 +- .../AbstractRadicalSiteInitiationReaction.cs | 10 +- .../Types/AbstractRadicalSiteReaction.cs | 17 +- .../Types/AbstractRearrangementReaction.cs | 4 +- .../Types/AbstractSharingReaction.cs | 4 +- .../Types/AdductionProtonPBReaction.cs | 5 +- .../Types/CarbonylEliminationReaction.cs | 14 +- .../Types/ElectronImpactNBEReaction.cs | 2 +- .../Types/HyperconjugationReaction.cs | 7 +- .../Types/PiBondingMovementReaction.cs | 39 +- .../Types/RadicalSiteHrAlphaReaction.cs | 4 +- .../Types/RadicalSiteHrBetaReaction.cs | 4 +- .../Types/RadicalSiteHrDeltaReaction.cs | 4 +- .../Types/RadicalSiteHrGammaReaction.cs | 4 +- .../Types/SharingChargeDBReaction.cs | 12 +- .../Types/SharingChargeSBReaction.cs | 6 +- .../Types/TautomerizationReaction.cs | 18 +- NCDK/RingSearches/AllRingsFinder.cs | 279 +- NCDK/RingSearches/JumboCyclicVertexSearch.cs | 24 +- .../RingSearches/RegularCyclicVertexSearch.cs | 26 +- NCDK/RingSearches/RingPartitioner.cs | 46 +- NCDK/RingSearches/RingSearch.cs | 30 +- NCDK/SGroups/SgroupTool.cs | 53 + NCDK/SMARTS/SmartsFragmentExtractor.cs | 76 +- NCDK/SMSD/AbstractMCS.cs | 8 +- NCDK/SMSD/Algorithms/MCSPluses/BKKCKCF.cs | 28 +- .../SMSD/Algorithms/MCSPluses/ExactMapping.cs | 4 +- .../MCSPluses/GenerateCompatibilityGraph.cs | 20 +- NCDK/SMSD/Algorithms/MCSPluses/MCSPlus.cs | 32 +- .../Algorithms/MCSPluses/MCSPlusHandler.cs | 43 +- .../Algorithms/Matchers/DefaultBondMatcher.cs | 27 +- .../Matchers/DefaultMCSPlusAtomMatcher.cs | 7 +- .../Algorithms/Matchers/DefaultMatcher.cs | 15 +- .../Matchers/DefaultRGraphAtomMatcher.cs | 24 +- .../Matchers/DefaultVFAtomMatcher.cs | 7 +- .../Matchers/DefaultVFBondMatcher.cs | 16 +- NCDK/SMSD/Algorithms/McGregors/McGregor.cs | 60 +- .../Algorithms/McGregors/McGregorChecks.cs | 46 +- .../Algorithms/McGregors/QueryProcessor.cs | 3 +- .../Algorithms/{RGraph => RGraphs}/CDKMCS.cs | 133 +- .../{RGraph => RGraphs}/CDKMCSHandler.cs | 48 +- .../{RGraph => RGraphs}/CDKRGraph.cs | 14 +- .../Algorithms/{RGraph => RGraphs}/CDKRMap.cs | 2 +- .../{RGraph => RGraphs}/CDKRMapHandler.cs | 153 +- .../{RGraph => RGraphs}/CDKRNode.cs | 28 +- .../{RGraph => RGraphs}/CDKSubGraphHandler.cs | 44 +- .../{Single => Singles}/SingleMapping.cs | 46 +- .../SingleMappingHandler.cs | 56 +- .../Algorithms/VFLib/Builder/NodeBuilder.cs | 9 +- .../VFLib/Builder/TargetProperties.cs | 29 +- NCDK/SMSD/Algorithms/VFLib/IMapper.cs | 8 +- NCDK/SMSD/Algorithms/VFLib/INode.cs | 2 +- NCDK/SMSD/Algorithms/VFLib/IState.cs | 2 +- NCDK/SMSD/Algorithms/VFLib/Map/VFMCSMapper.cs | 28 +- NCDK/SMSD/Algorithms/VFLib/Map/VFMapper.cs | 30 +- NCDK/SMSD/Algorithms/VFLib/Map/VFState.cs | 21 +- .../Algorithms/VFLib/Query/QueryCompiler.cs | 6 +- NCDK/SMSD/Algorithms/VFLib/VFlibMCSHandler.cs | 73 +- .../VFLib/VFlibSubStructureHandler.cs | 63 +- .../Algorithms/VFLib/VFlibTurboHandler.cs | 98 +- NCDK/SMSD/Filters/ChemicalFilters.cs | 191 +- NCDK/SMSD/Filters/PostFilter.cs | 18 +- NCDK/SMSD/{Global => Globals}/TimeOut.cs | 4 +- NCDK/SMSD/Helper/FinalMappings.cs | 12 +- NCDK/SMSD/IFinalMapping.cs | 9 +- NCDK/SMSD/IMCSBase.cs | 8 +- NCDK/SMSD/Isomorphism.cs | 77 +- .../Labelling/AbstractReactionLabeller.cs | 86 +- .../Labelling/AtomContainerAtomPermutor.cs | 2 +- NCDK/SMSD/Labelling/AtomContainerPrinter.cs | 4 +- .../Labelling/CanonicalLabellingAdaptor.cs | 2 +- .../Labelling/ICanonicalMoleculeLabeller.cs | 1 + NCDK/SMSD/{Ring => Rings}/HanserRingFinder.cs | 2 +- NCDK/SMSD/{Ring => Rings}/IRingFinder.cs | 2 +- NCDK/SMSD/{Ring => Rings}/PathEdge.cs | 4 +- NCDK/SMSD/{Ring => Rings}/PathGraph.cs | 4 +- NCDK/SMSD/{Ring => Rings}/RingFilter.cs | 2 +- NCDK/SMSD/Tools/BondEnergies.cs | 23 +- .../SMSD/Tools/ExtAtomContainerManipulator.cs | 6 +- NCDK/SMSD/Tools/MolHandler.cs | 2 +- NCDK/SMSD/Tools/MoleculeSanityCheck.cs | 13 +- NCDK/SMSD/Tools/TimeManager.cs | 2 +- NCDK/Sgroups/SgroupKey.cs | 9 - NCDK/Sgroups/SgroupType.cs | 46 +- NCDK/Signatures/AtomSignature.cs | 32 +- .../MoleculeFromSignatureBuilder.cs | 38 +- NCDK/Signatures/MoleculeSignature.cs | 4 +- NCDK/Signatures/Orbit.cs | 43 +- NCDK/Similarity/LingoSimilarity.cs | 6 +- NCDK/Similarity/Tanimoto.cs | 4 +- NCDK/Smiles/BeamToCDK.cs | 64 +- NCDK/Smiles/CDKToBeam.cs | 44 +- NCDK/Smiles/CxSmilesGenerator.cs | 44 +- NCDK/Smiles/CxSmilesParser.cs | 30 +- NCDK/Smiles/CxSmilesState.cs | 54 +- NCDK/Smiles/DeduceBondSystemTool.cs | 211 +- NCDK/Smiles/FixBondOrdersTool.cs | 63 +- NCDK/Smiles/InvPair.cs | 26 +- NCDK/Smiles/SMARTS/Parser/ASTAliphatic.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTAnyAtom.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTAromatic.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTAtom.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTAtomicMass.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTAtomicNumber.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTCharge.cs | 4 +- NCDK/Smiles/SMARTS/Parser/ASTChirality.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTElement.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTExplicitAtom.cs | 5 +- .../SMARTS/Parser/ASTExplicitConnectivity.cs | 4 +- .../SMARTS/Parser/ASTExplicitHighAndBond.cs | 5 +- .../Parser/ASTExplicitHighAndExpression.cs | 5 +- NCDK/Smiles/SMARTS/Parser/ASTGroup.cs | 19 +- .../SMARTS/Parser/ASTHybrdizationNumber.cs | 4 +- .../Smiles/SMARTS/Parser/ASTImplicitHCount.cs | 4 +- .../SMARTS/Parser/ASTImplicitHighAndBond.cs | 5 +- .../Parser/ASTImplicitHighAndExpression.cs | 5 +- NCDK/Smiles/SMARTS/Parser/ASTLowAndBond.cs | 5 +- .../SMARTS/Parser/ASTLowAndExpression.cs | 8 +- .../Smiles/SMARTS/Parser/ASTNonCHHeavyAtom.cs | 5 +- NCDK/Smiles/SMARTS/Parser/ASTNotBond.cs | 4 +- NCDK/Smiles/SMARTS/Parser/ASTNotExpression.cs | 4 +- NCDK/Smiles/SMARTS/Parser/ASTOrBond.cs | 5 +- NCDK/Smiles/SMARTS/Parser/ASTOrExpression.cs | 5 +- .../SMARTS/Parser/ASTPeriodicGroupNumber.cs | 4 +- .../Parser/ASTPrimitiveAtomExpression.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTReaction.cs | 4 +- .../Parser/ASTRecursiveSmartsExpression.cs | 3 +- .../SMARTS/Parser/ASTRingConnectivity.cs | 4 +- .../Smiles/SMARTS/Parser/ASTRingIdentifier.cs | 4 +- .../Smiles/SMARTS/Parser/ASTRingMembership.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTSimpleBond.cs | 3 +- .../SMARTS/Parser/ASTSmallestRingSize.cs | 32 +- NCDK/Smiles/SMARTS/Parser/ASTSmarts.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTStart.cs | 3 +- .../SMARTS/Parser/ASTTotalConnectivity.cs | 3 +- NCDK/Smiles/SMARTS/Parser/ASTTotalHCount.cs | 31 +- NCDK/Smiles/SMARTS/Parser/ASTValence.cs | 4 +- .../SMARTS/Parser/ISMARTSParserVisitor.cs | 2 +- .../SMARTS/Parser/JJTSMARTSParserState.cs | 26 +- NCDK/Smiles/SMARTS/Parser/Node.cs | 10 +- NCDK/Smiles/SMARTS/Parser/ParseException.cs | 68 +- NCDK/Smiles/SMARTS/Parser/SMARTSParser.cs | 69 +- .../SMARTS/Parser/SMARTSParserConstants.cs | 8 +- .../SMARTS/Parser/SMARTSParserTokenManager.cs | 15 +- NCDK/Smiles/SMARTS/Parser/SimpleCharStream.cs | 70 +- NCDK/Smiles/SMARTS/Parser/SimpleNode.cs | 27 +- .../Smiles/SMARTS/Parser/Smarts2MQLVisitor.cs | 30 +- .../Smiles/SMARTS/Parser/SmartsDumpVisitor.cs | 2 +- .../SMARTS/Parser/SmartsQueryVisitor.cs | 132 +- NCDK/Smiles/SMARTS/Parser/Token.cs | 6 +- NCDK/Smiles/SMARTS/Parser/TokenMgrError.cs | 19 +- NCDK/Smiles/SMARTS/SMARTSQueryTool.cs | 61 +- NCDK/Smiles/SMARTS/SmartsAtomAtomMapFilter.cs | 4 +- NCDK/Smiles/SMARTS/SmartsPattern.cs | 15 +- NCDK/Smiles/SmiFlavor.cs | 12 +- NCDK/Smiles/SmilesGenerator.cs | 127 +- NCDK/Smiles/SmilesParser.cs | 85 +- NCDK/Stereo/AbstractStereo.cs | 36 +- NCDK/Stereo/Atropisomeric.cs | 10 +- NCDK/Stereo/CyclicCarbohydrateRecognition.cs | 116 +- NCDK/Stereo/DoubleBondStereochemistry.cs | 10 +- NCDK/Stereo/ExtendedTetrahedral.cs | 17 +- NCDK/Stereo/FischerRecognition.cs | 76 +- NCDK/Stereo/Octahedral.cs | 11 +- NCDK/Stereo/Projection.cs | 2 +- NCDK/Stereo/SquarePlanar.cs | 52 +- NCDK/Stereo/StereoElementFactory.cs | 173 +- NCDK/Stereo/StereoTool.cs | 13 +- NCDK/Stereo/Stereocenters.cs | 192 +- NCDK/Stereo/TetrahedralChirality.cs | 18 +- NCDK/Stereo/TrigonalBipyramidal.cs | 147 +- NCDK/StereoElement.cs | 180 +- NCDK/StructGen/MathTools.cs | 6 +- NCDK/StructGen/RandomGenerator.cs | 51 +- .../SingleStructureRandomGenerator.cs | 70 +- .../{Operator => Operators}/ChemGraph.cs | 61 +- .../CrossoverMachine.cs | 58 +- .../PartialFilledStructureMerger.cs | 44 +- NCDK/StructGen/VicinitySampler.cs | 2 +- NCDK/TT/AdductFormula.tt | 45 +- NCDK/TT/AdductFormula.tt.cs | 89 +- NCDK/TT/AminoAcid.tt.cs | 1 + NCDK/TT/Association.tt | 12 +- NCDK/TT/Association.tt.cs | 25 +- NCDK/TT/Atom.tt | 202 +- NCDK/TT/Atom.tt.cs | 368 +-- NCDK/TT/AtomContainer.tt | 233 +- NCDK/TT/AtomContainer.tt.cs | 461 ++-- NCDK/TT/AtomContainer2.tt | 195 +- NCDK/TT/AtomContainer2.tt.cs | 351 ++- NCDK/TT/AtomContainerSet.tt | 24 +- NCDK/TT/AtomContainerSet.tt.cs | 47 +- NCDK/TT/AtomType.tt | 72 +- NCDK/TT/AtomType.tt.cs | 142 +- NCDK/TT/BioPolymer.tt | 6 +- NCDK/TT/BioPolymer.tt.cs | 13 +- NCDK/TT/Bond.tt | 59 +- NCDK/TT/Bond.tt.cs | 105 +- NCDK/TT/ChemFile.tt | 6 +- NCDK/TT/ChemFile.tt.cs | 11 +- NCDK/TT/ChemModel.tt.cs | 1 + NCDK/TT/ChemObject.tt | 40 +- NCDK/TT/ChemObject.tt.cs | 98 +- NCDK/TT/ChemObjectBuilder.tt | 46 +- NCDK/TT/ChemObjectBuilder.tt.cs | 93 +- NCDK/TT/ChemSequence.tt | 3 +- NCDK/TT/ChemSequence.tt.cs | 7 +- NCDK/TT/Crystal.tt | 1 + NCDK/TT/Crystal.tt.cs | 3 + NCDK/TT/ElectronContainer.tt | 21 +- NCDK/TT/ElectronContainer.tt.cs | 40 +- NCDK/TT/Element.tt | 28 +- NCDK/TT/Element.tt.cs | 53 +- NCDK/TT/EnzymeResidueLocator.tt.cs | 1 + NCDK/TT/FragmentAtom.tt.cs | 1 + NCDK/TT/Isotope.tt | 49 +- NCDK/TT/Isotope.tt.cs | 97 +- NCDK/TT/LonePair.tt | 4 +- NCDK/TT/LonePair.tt.cs | 9 +- NCDK/TT/Mapping.tt.cs | 1 + NCDK/TT/Monomer.tt | 1 + NCDK/TT/Monomer.tt.cs | 3 + NCDK/TT/PDBAtom.tt | 2 +- NCDK/TT/PDBAtom.tt.cs | 5 +- NCDK/TT/PDBMonomer.tt | 2 +- NCDK/TT/PDBMonomer.tt.cs | 3 +- NCDK/TT/PDBPolymer.tt | 2 +- NCDK/TT/PDBPolymer.tt.cs | 3 +- NCDK/TT/PDBStrand.tt | 2 +- NCDK/TT/PDBStrand.tt.cs | 4 +- NCDK/TT/PDBStructure.tt.cs | 1 + NCDK/TT/Polymer.tt | 10 +- NCDK/TT/Polymer.tt.cs | 21 +- NCDK/TT/PseudoAtom.tt | 1 + NCDK/TT/PseudoAtom.tt.cs | 3 + NCDK/TT/Reaction.tt | 8 +- NCDK/TT/Reaction.tt.cs | 16 +- NCDK/TT/ReactionChain.tt | 1 + NCDK/TT/ReactionChain.tt.cs | 3 + NCDK/TT/ReactionScheme.tt | 1 + NCDK/TT/ReactionScheme.tt.cs | 3 + NCDK/TT/ReactionSet.tt | 1 + NCDK/TT/ReactionSet.tt.cs | 3 + NCDK/TT/Ring.tt | 23 +- NCDK/TT/Ring.tt.cs | 47 +- NCDK/TT/RingSet.tt | 1 + NCDK/TT/RingSet.tt.cs | 3 + NCDK/TT/SingleElectron.tt | 3 +- NCDK/TT/SingleElectron.tt.cs | 7 +- NCDK/TT/Strand.tt | 13 +- NCDK/TT/Strand.tt.cs | 27 +- NCDK/TT/Substance.tt | 1 + NCDK/TT/Substance.tt.cs | 3 + NCDK/Tautomers/InChITautomerGenerator.cs | 50 +- NCDK/Templates/AminoAcids.cs | 34 +- NCDK/TetrahedralStereo.cs | 12 +- NCDK/Tools/AtomTypeAwareSaturationChecker.cs | 70 +- NCDK/Tools/AtomTypeTools.cs | 95 +- NCDK/Tools/AtomicProperties.cs | 59 +- .../BremserOneSphereHOSECodePredictor.cs | 17 +- NCDK/Tools/CDKHydrogenAdder.cs | 2 +- NCDK/Tools/CDKUtilities.cs | 20 +- NCDK/Tools/DataFeatures.cs | 26 +- NCDK/Tools/DataFeaturesTool.cs | 14 +- NCDK/Tools/Diff/AtomContainerDiff.cs | 6 +- NCDK/Tools/Diff/Tree/AbstractDifference.cs | 2 +- .../Tools/Diff/Tree/AbstractDifferenceList.cs | 2 +- .../Tools/Diff/Tree/BooleanArrayDifference.cs | 5 +- NCDK/Tools/Diff/Tree/ChemObjectDifference.cs | 30 +- NCDK/Tools/Diff/Tree/Point2dDifference.cs | 5 +- NCDK/Tools/Diff/Tree/Point3dDifference.cs | 6 +- NCDK/Tools/Diff/Tree/StringDifference.cs | 10 +- NCDK/Tools/ElementComparator.cs | 63 +- NCDK/Tools/GridGenerator.cs | 2 +- NCDK/Tools/HOSECodeAnalyser.cs | 24 +- NCDK/Tools/HOSECodeGenerator.cs | 164 +- NCDK/Tools/IDCreator.cs | 2 + NCDK/Tools/LonePairElectronChecker.cs | 26 +- .../Tools/Manipulator/AminoAcidManipulator.cs | 3 +- .../Manipulator/AtomContainerComparator.cs | 7 +- .../Manipulator/AtomContainerManipulator.cs | 327 +-- .../AtomContainerSetManipulator.cs | 4 +- NCDK/Tools/Manipulator/AtomTypeManipulator.cs | 4 +- NCDK/Tools/Manipulator/BondManipulator.cs | 4 +- NCDK/Tools/Manipulator/ChemFileManipulator.cs | 2 +- .../Tools/Manipulator/ChemModelManipulator.cs | 2 +- .../Manipulator/ChemSequenceManipulator.cs | 2 +- .../MolecularFormulaManipulator.cs | 414 +-- .../MolecularFormulaRangeManipulator.cs | 2 +- NCDK/Tools/Manipulator/ReactionManipulator.cs | 4 +- .../Manipulator/ReactionSetManipulator.cs | 3 +- NCDK/Tools/Manipulator/RingSetManipulator.cs | 43 +- NCDK/Tools/Manipulator/RingSizeComparator.cs | 29 +- NCDK/Tools/Manipulator/SgroupManipulator.cs | 16 +- NCDK/Tools/ProteinBuilderTool.cs | 32 +- NCDK/Tools/SaturationChecker.cs | 248 +- NCDK/Tools/SmilesValencyChecker.cs | 162 +- NCDK/Tools/StructureResonanceGenerator.cs | 112 +- NCDK/UnsupportedChemObjectException.cs | 11 +- NCDK/Validate/BasicValidator.cs | 120 +- NCDK/Validate/CDKValidator.cs | 4 +- NCDK/Validate/DictionaryValidator.cs | 2 +- NCDK/Validate/IValidator.cs | 2 +- NCDK/Validate/ProblemMarker.cs | 22 +- NCDK/Validate/ValidationTest.cs | 10 +- NCDK/io-formats.set | 6 +- NCDK/qsar-descriptors.set | 10 +- NCDKDisplay/Depict/Abbreviations.cs | 70 +- NCDKDisplay/Depict/DepictionGenerator.cs | 18 +- NCDKDisplay/Depict/MolGridDepiction.cs | 18 +- NCDKDisplay/Depict/SvgDrawVisitor.cs | 8 +- NCDKDisplay/IncludeExamples.xml | 166 +- NCDKDisplay/NCDK.Display.csproj | 1 + NCDKDisplay/Properties/AssemblyInfo.cs | 4 +- .../Renderers/Colors/CDK2DAtomColors.cs | 1 - .../Renderers/Generators/AtomMassGenerator.cs | 2 +- .../Generators/BasicBondGenerator.cs | 2 +- .../Generators/ExtendedAtomGenerator.cs | 2 +- .../Generators/HighlightGenerator.cs | 14 - NCDKDisplay/Renderers/Generators/IPalette.cs | 42 + .../Generators/ReactionArrowGenerator.cs | 3 +- .../Standards/StandardAtomGenerator.cs | 11 +- .../Standards/StandardSgroupGenerator.cs | 18 +- NCDKDisplay/Renderers/RendererModelTools.tt | 202 +- .../Renderers/RendererModelTools.tt.cs | 870 +++--- .../Visitors/AbstractWPFDrawVisitor.cs | 6 +- .../Renderers/Visitors/WPFDrawVisitor.cs | 4 +- NCDKDisplayTests/Depict/AbbreviationsTest.cs | 2 +- NCDKDisplayTests/NCDK.DisplayTests.csproj | 20 +- .../Renderers/BoundsCalculatorTest.cs | 2 +- .../Renderers/Colors/CDK2DAtomColorsTest.cs | 2 +- .../Renderers/Colors/CDKAtomColorsTest.cs | 2 +- .../Renderers/Colors/CPKAtomColorsTest.cs | 2 +- .../Colors/PartialAtomicChargeColorsTest.cs | 2 +- .../Renderers/Colors/RasmolColorsTest.cs | 2 +- .../Standards/SelectionVisibilityTest.cs | 3 +- .../Renderers/RendererModelTest.cs | 2 +- .../Renderers/SymbolVisibilityTest.cs | 2 +- .../Visitor/AbstractWPFDrawVisitorTest.cs | 6 +- NCDKTests/AbstractAtomContainerTest.cs | 16 +- NCDKTests/AbstractAtomTest.cs | 45 +- NCDKTests/AbstractMolecularFormulaSetTest.cs | 8 +- NCDKTests/AbstractMolecularFormulaTest.cs | 32 +- NCDKTests/AbstractPDBAtomTest.cs | 10 +- NCDKTests/AbstractPseudoAtomTest.cs | 8 +- NCDKTests/AbstractRingTest.cs | 8 +- NCDKTests/Aromaticities/AromaticityTest.cs | 8 +- NCDKTests/Aromaticities/KekulizationTest.cs | 5 +- NCDKTests/AssociationTest.cs | 3 +- NCDKTests/AtomTypes/AbstractAtomTypeTest.cs | 3 +- .../AtomTypes/AbstractSybylAtomTypeTest.cs | 3 +- .../AtomTypes/CDKAtomTypeMatcherFilesTest.cs | 9 +- .../AtomTypes/CDKAtomTypeMatcherSMILESTest.cs | 71 +- NCDKTests/AtomTypes/CDKAtomTypeMatcherTest.cs | 346 +-- .../CDKAtomTypeMatcherTestFileReposTest.cs | 6 +- .../AtomTypes/EStateAtomTypeMatcherTest.cs | 9 +- NCDKTests/AtomTypes/ReactionStructuresTest.cs | 5 +- .../RepeatedCDKAtomTypeMatcherSMILESTest.cs | 23 +- .../AtomTypes/ResonanceStructuresTest.cs | 2 +- .../AtomTypes/StructGenAtomTypeGuesserTest.cs | 2 +- NCDKTests/AtomTypes/StructGenMatcherTest.cs | 276 +- .../AtomTypes/SybylAtomTypeMatcherTest.cs | 181 +- .../Beam/Core/DaylightDelocalisationTest.cs | 2 +- NCDKTests/Beam/Core/TopologyTest.cs | 10 +- NCDKTests/CDKExceptionTest.cs | 2 +- NCDKTests/Charges/ElectronegativityTest.cs | 7 +- .../GasteigerMarsiliPartialChargesTest.cs | 11 +- .../GasteigerPEPEPartialChargesTest.cs | 23 +- .../Charges/InductivePartialChargesTest.cs | 4 +- NCDKTests/Charges/MMFF94PartialChargesTest.cs | 3 +- NCDKTests/Charges/PiElectronegativityTest.cs | 7 +- NCDKTests/Charges/PolarizabilityTest.cs | 57 +- NCDKTests/Charges/StabilizationChargesTest.cs | 17 +- NCDKTests/ChemObjectChangeEventTest.cs | 2 +- NCDKTests/Config/AtomTypeFactoryTest.cs | 4 +- .../AtomTypeReaderTest.cs | 4 +- .../OWLAtomTypeMappingHandlerTest.cs | 2 +- .../OWLAtomTypeMappingReaderTest.cs | 7 +- .../OWLAtomTypeReaderTest.cs | 4 +- .../CDKBasedAtomTypeConfiguratorTest.cs | 4 +- .../Config/Isotope/IsotopeHandlerTest.cs | 3 +- NCDKTests/Config/Isotope/IsotopeReaderTest.cs | 7 +- NCDKTests/Config/IsotopesTest.cs | 94 +- .../OWLBasedAtomTypeConfiguratorTest.cs | 4 +- .../TXTBasedAtomTypeConfiguratorTest.cs | 4 +- NCDKTests/Config/XMLIsotopeFactoryTest.cs | 40 +- NCDKTests/Dict/AbstractEntryTest.cs | 2 +- .../Simple/CanonicalLabellingTest.cs | 4 +- .../AbstractFixedLengthFingerprinterTest.cs | 13 +- .../CircularFingerprintSmartsTest.cs | 45 +- .../Fingerprints/CircularFingerprinterTest.cs | 147 +- .../Fingerprints/EStateFingerprinterTest.cs | 8 +- .../Fingerprints/ExtendedFingerprinterTest.cs | 23 +- NCDKTests/Fingerprints/FingerprinterTest.cs | 18 +- .../Fingerprints/FingerprinterToolTest.cs | 24 +- .../GraphOnlyFingerprinterTest.cs | 4 +- .../KlekotaRothFingerprinterTest.cs | 4 +- .../Fingerprints/LingoFingerprinterTest.cs | 22 +- .../Fingerprints/MACCSFingerprinterTest.cs | 8 +- NCDKTests/Fingerprints/Model/BayesianTest.cs | 118 +- .../Fingerprints/PubchemFingerprinterTest.cs | 43 +- .../ShortestPathFingerprinterTest.cs | 30 +- .../Fingerprints/ShortestPathWalkerTest.cs | 8 +- .../SignatureFingerprinterTest.cs | 34 +- .../SimpleAtomCanonicalizerTest.cs | 2 +- .../Fingerprints/SimpleAtomComparatorTest.cs | 3 +- .../SubstructureFingerprinterTest.cs | 19 +- ...AbstractMmffAtomTypeValidationSuiteTest.cs | 2 +- .../MmffAromaticTypeMappingTest.cs | 12 +- .../MmffAtomTypeMatcherTest.cs | 4 +- .../MmffAtomTypeValidationSuiteTest.cs | 2 +- .../MMFF => ForceFields}/MmffParamSetTest.cs | 2 +- .../MMFF => ForceFields}/MmffTest.cs | 2 +- NCDKTests/Formula/AdductFormulaTest.cs | 4 +- .../Formula/IsotopePatternGeneratorTest.cs | 29 +- .../Formula/IsotopePatternManipulatorTest.cs | 84 +- .../Formula/IsotopePatternSimilarityTest.cs | 65 +- NCDKTests/Formula/IsotopePatternTest.cs | 73 +- .../Formula/MolecularFormulaCheckerTest.cs | 2 +- .../Formula/MolecularFormulaGeneratorTest.cs | 50 +- NCDKTests/Formula/MolecularFormulaSetTest.cs | 3 +- NCDKTests/Formula/MolecularFormulaTest.cs | 16 +- NCDKTests/Formula/Rules/ChargeRuleTest.cs | 15 +- NCDKTests/Formula/Rules/ElementRuleTest.cs | 12 +- NCDKTests/Formula/Rules/FormulaRuleTest.cs | 4 +- .../Formula/Rules/IsotopePatternRuleTest.cs | 9 +- NCDKTests/Formula/Rules/MMElementRuleTest.cs | 7 +- NCDKTests/Formula/Rules/NitrogenRuleTest.cs | 3 +- NCDKTests/Formula/Rules/RDBERuleTest.cs | 7 +- .../Formula/Rules/ToleranceRangeRuleTest.cs | 7 +- NCDKTests/Fragments/FragmentUtilsTest.cs | 3 +- NCDKTests/Fragments/MurckoFragmenterTest.cs | 72 +- .../Alignments/KabschAlignmentTest.cs | 2 +- NCDKTests/Geometries/BondToolsTest.cs | 2 +- NCDKTests/Geometries/CIP/CIPSMILESTest.cs | 34 +- NCDKTests/Geometries/CIP/CIPToolTest.cs | 502 ++-- .../CIP/ImplicitHydrogenLigandTest.cs | 6 +- .../CIP/LigancyFourChiralityTest.cs | 62 +- NCDKTests/Geometries/CIP/LigandTest.cs | 22 +- .../CIP/Rules/AtomicNumberRuleTest.cs | 8 +- .../Geometries/CIP/Rules/CIPLigandRuleTest.cs | 116 +- .../Rules/CombinedAtomicMassNumberRuleTest.cs | 42 +- .../CIP/Rules/MassNumberRuleTest.cs | 60 +- .../Geometries/CIP/TerminalLigandTest.cs | 12 +- NCDKTests/Geometries/CIP/VisitedAtomsTest.cs | 2 +- .../Geometries/CML/CML23FragmentsTest.cs | 2 +- NCDKTests/Geometries/CML/CMLFragmentsTest.cs | 2 +- NCDKTests/Geometries/CML/JChemPaintTest.cs | 6 +- NCDKTests/Geometries/CML/JmolTest.cs | 10 +- .../Geometries/CML/Jumbo46CMLFragmentsTest.cs | 2 +- NCDKTests/Geometries/CML/JumboTest.cs | 2 +- NCDKTests/Geometries/GeometryUtilTest.cs | 114 +- NCDKTests/Graphs/AllPairsShortestPathsTest.cs | 8 +- .../Graphs/AtomContainerAtomPermutorTest.cs | 2 +- .../Graphs/AtomContainerBondPermutorTest.cs | 2 +- NCDKTests/Graphs/AtomContainerPermutorTest.cs | 2 +- NCDKTests/Graphs/ConnectionMatrixTest.cs | 2 +- NCDKTests/Graphs/ConnectivityCheckerTest.cs | 4 +- NCDKTests/Graphs/CyclesTest.cs | 6 +- NCDKTests/Graphs/EssentialCyclesTest.cs | 3 +- NCDKTests/Graphs/GraphUtilTest.cs | 4 +- NCDKTests/Graphs/GreedyBasisTest.cs | 22 +- .../Graphs/InChi/InChIGeneratorFactoryTest.cs | 16 +- NCDKTests/Graphs/InChi/InChIGeneratorTest.cs | 2 +- .../Graphs/InChi/InChIToStructureTest.cs | 50 +- NCDKTests/Graphs/InitialCyclesTest.cs | 9 +- .../Graphs/Invariant/CanonicalLabelerTest.cs | 42 +- .../ConjugatedPiSystemsDetectorTest.cs | 24 +- .../EquivalentClassPartitionerTest.cs | 8 +- .../Graphs/Invariant/InChINumbersToolsTest.cs | 8 +- .../Invariant/MorganNumbersToolsTest.cs | 3 +- NCDKTests/Graphs/JumboPathGraphTest.cs | 6 +- .../Graphs/Matrix/TopologicalMatrixTest.cs | 2 +- NCDKTests/Graphs/PathToolsTest.cs | 23 +- NCDKTests/Graphs/Rebond/BsptTest.cs | 1 + NCDKTests/Graphs/Rebond/RebondToolTest.cs | 2 +- NCDKTests/Graphs/RegularPathGraphTest.cs | 6 +- NCDKTests/Graphs/ShortestPathsTest.cs | 92 +- NCDKTests/Graphs/SpanningTreeTest.cs | 11 +- NCDKTests/Graphs/TripletShortCyclesTest.cs | 5 +- NCDKTests/Groups/AtomGroupTests.cs | 3 +- NCDKTests/Groups/BondGroupTests.cs | 7 +- NCDKTests/Groups/PermutationGroupTest.cs | 7 +- NCDKTests/Groups/PermutationTest.cs | 58 +- NCDKTests/Hash/AllEquivalentCyclicSetTest.cs | 2 +- NCDKTests/Hash/HashCodeScenariosTest.cs | 4 +- .../MinimumEquivalentCyclicSetUnionTest.cs | 2 +- .../Hash/PerturbedAtomHashGeneratorTest.cs | 2 +- .../Hash/Stereo/BasicPermutationParityTest.cs | 2 +- ...eometricCumulativeDoubleBondFactoryTest.cs | 2 +- NCDKTests/Hash/Stereo/GeometryEncoderTest.cs | 2 +- .../Hash/Stereo/Tetrahedral2DParityTest.cs | 4 +- .../TetrahedralElementEncoderFactoryTest.cs | 10 +- NCDKTests/IO/AbstractReaderFactoryTest.cs | 2 +- NCDKTests/IO/CIFReaderTest.cs | 2 +- NCDKTests/IO/CML/CML2Test.cs | 2 +- NCDKTests/IO/CML/CML2WriterTest.cs | 16 +- NCDKTests/IO/CML/CMLRoundTripTest.cs | 2 +- NCDKTests/IO/CML/CMLRoundTripTool.cs | 2 +- NCDKTests/IO/CML/PDBAtomCustomizerTest.cs | 2 +- NCDKTests/IO/CMLReaderTest.cs | 16 +- NCDKTests/IO/CMLWriterFactoryTest.cs | 4 +- NCDKTests/IO/CTXReaderTest.cs | 2 +- NCDKTests/IO/ChemObjectIOInstantionTests.cs | 4 +- NCDKTests/IO/ChemObjectIOTest.cs | 22 +- NCDKTests/IO/ChemObjectWriterTest.cs | 2 +- NCDKTests/IO/CrystClustReaderTest.cs | 2 +- NCDKTests/IO/CustomFormat.cs | 3 +- NCDKTests/IO/FormatFactoryTest.cs | 13 +- .../Formats/Chem3D_Cartesian_1FormatTest.cs | 2 +- .../Formats/Chem3D_Cartesian_2FormatTest.cs | 2 +- .../Formats/FenskeHall_ZMatrixFormatTest.cs | 2 +- NCDKTests/IO/Formats/ResourceFormatTest.cs | 25 +- NCDKTests/IO/GamessReaderTest.cs | 2 +- NCDKTests/IO/Gaussian98ReaderTest.cs | 2 +- NCDKTests/IO/GaussianInputWriterTest.cs | 3 +- NCDKTests/IO/GhemicalReaderTest.cs | 2 +- NCDKTests/IO/HINReaderTest.cs | 2 +- NCDKTests/IO/InChIPlainTextReaderTest.cs | 2 +- NCDKTests/IO/InChIReaderTest.cs | 2 +- .../EnumerableMDLConformerReaderTest.cs | 5 +- .../EnumerablePCCompoundASNReaderTest.cs | 4 +- .../EnumerablePCCompoundXMLReaderTest.cs | 5 +- .../EnumerablePCSubstancesXMLReaderTest.cs | 5 +- .../IO/Iterator/EnumerableSDFReaderTest.cs | 3 +- .../IO/Iterator/EnumerableSMILESReaderTest.cs | 17 +- NCDKTests/IO/MDLCMLRoundtripTest.cs | 2 +- NCDKTests/IO/MDLRXNReaderTest.cs | 2 +- NCDKTests/IO/MDLRXNV2000ReaderTest.cs | 2 +- NCDKTests/IO/MDLRXNV3000ReaderTest.cs | 2 +- NCDKTests/IO/MDLRXNWriterTest.cs | 4 +- NCDKTests/IO/MDLReaderTest.cs | 8 +- NCDKTests/IO/MDLV2000AtomBlockTest.cs | 18 +- NCDKTests/IO/MDLV2000ReaderTest.cs | 59 +- NCDKTests/IO/MDLV2000WriterTest.cs | 27 +- NCDKTests/IO/MDLV3000ReaderTest.cs | 7 +- NCDKTests/IO/MDLV3000WriterTest.cs | 6 +- NCDKTests/IO/MDLValenceTest.cs | 2 +- NCDKTests/IO/MoSSOutputReaderTest.cs | 2 +- NCDKTests/IO/Mol2ReaderTest.cs | 4 +- NCDKTests/IO/Mol2WriterTest.cs | 4 +- NCDKTests/IO/Mopac7ReaderTest.cs | 2 +- NCDKTests/IO/Mopac7WriterTest.cs | 2 +- NCDKTests/IO/NCDKSourceCodeWriterTest.cs | 7 +- NCDKTests/IO/PCCompoundASNReaderTest.cs | 3 +- NCDKTests/IO/PCCompoundXMLReaderTest.cs | 2 +- NCDKTests/IO/PCSubstanceXMLReaderTest.cs | 2 +- NCDKTests/IO/PDBReaderTest.cs | 2 +- NCDKTests/IO/PDBWriterTest.cs | 4 +- NCDKTests/IO/PMPReaderTest.cs | 2 +- NCDKTests/IO/RDF/CDKOWLReaderTest.cs | 2 +- NCDKTests/IO/RDF/CDKOWLWriterTest.cs | 6 +- NCDKTests/IO/RGroupQueryReaderTest.cs | 71 +- NCDKTests/IO/RGroupQueryWriterTest.cs | 5 +- NCDKTests/IO/RandomAccess/RandomAccessTest.cs | 3 +- NCDKTests/IO/ReaderFactoryTest.cs | 2 +- NCDKTests/IO/SDFReaderTest.cs | 2 +- NCDKTests/IO/SDFWriterTest.cs | 10 +- NCDKTests/IO/SMILESReaderTest.cs | 2 +- NCDKTests/IO/SMILESWriterTest.cs | 2 +- NCDKTests/IO/ShelXReaderTest.cs | 2 +- NCDKTests/IO/ShelXWriterTest.cs | 2 +- NCDKTests/IO/VASPReaderTest.cs | 2 +- NCDKTests/IO/WriterFactoryTest.cs | 4 +- NCDKTests/IO/XYZReaderTest.cs | 2 +- NCDKTests/IO/XYZWriterTest.cs | 2 +- NCDKTests/IO/ZMatrixReaderTest.cs | 2 +- .../Isomorphisms/ComponentGroupingTest.cs | 2 +- .../Isomorphisms/IsomorphismTesterTest.cs | 2 +- NCDKTests/Isomorphisms/MappingsTest.cs | 38 +- .../Isomorphisms/Matchers/RGroupListTest.cs | 2 +- .../Matchers/SMARTS/AnyAtomTest.cs | 2 +- .../Matchers/SMARTS/AnyOrderQueryBondTest.cs | 2 +- .../SMARTS/ExplicitConnectionAtomTest.cs | 3 +- .../Matchers/SMARTS/RingMembershipAtomTest.cs | 9 +- .../SMARTS/TotalConnectionAtomTest.cs | 5 +- .../Matchers/SMARTS/TotalHCountAtomTest.cs | 3 +- .../SMARTS/TotalRingConnectionAtomTest.cs | 3 +- .../Matchers/SMARTS/TotalValencyAtomTest.cs | 3 +- .../Matchers/SymbolSetQueryAtomTest.cs | 4 +- NCDKTests/Isomorphisms/SMARTSTest.cs | 12 +- .../Isomorphisms/SmartsStereoMatchTest.cs | 2 +- NCDKTests/Isomorphisms/StateStreamTest.cs | 8 +- NCDKTests/Isomorphisms/UllmannStateTest.cs | 4 +- NCDKTests/Isomorphisms/UllmannTest.cs | 3 +- .../UniversalIsomorphismTesterTest.cs | 309 +-- NCDKTests/Isomorphisms/VFStateTest.cs | 4 +- NCDKTests/Isomorphisms/VFSubStateTest.cs | 4 +- NCDKTests/Isomorphisms/VentoFoggiaTest.cs | 5 +- NCDKTests/Layout/AtomPlacerTest.cs | 25 +- .../CorrectGeometricConfigurationTest.cs | 2 +- NCDKTests/Layout/HydrogenPlacerTest.cs | 2 +- .../Layout/IdentityTemplateLibraryTest.cs | 2 +- NCDKTests/Layout/NonPlanarBondsTest.cs | 2 +- .../Layout/StructureDiagramGeneratorTest.cs | 38 +- NCDKTests/Layout/TemplateHandlerTest.cs | 29 +- NCDKTests/LibIO/CML/ConvertorTest.cs | 5 +- NCDKTests/LibIO/CML/PDBAtomCustomizerTest.cs | 2 +- NCDKTests/LibIO/MD/MDMoleculeTest.cs | 2 +- NCDKTests/Maths/PrimesTest.cs | 4 +- NCDKTests/MockMolecule.cs | 2 +- .../Modelings/Builder3D/AtomPlacer3DTest.cs | 4 +- .../AtomTetrahedralLigandPlacer3DTest.cs | 41 +- .../Builder3D/ForceFieldConfiguratorTest.cs | 31 +- .../Builder3D/FurtherAtomPlacer3DTest.cs | 41 +- .../Builder3D/FurtherTemplateHandler3DTest.cs | 11 +- .../MMFF94BasedParameterSetReaderTest.cs | 67 +- .../Modelings/Builder3D/ModelBuilder3DTest.cs | 10 +- .../Builder3D/TemplateHandler3DTest.cs | 9 +- NCDKTests/NCDKTests.csproj | 8 +- NCDKTests/NInChI/TestNInchiOutputStructure.cs | 2 +- NCDKTests/Normalizers/NormalizerTest.cs | 2 +- NCDKTests/Normalizers/SMSDNormalizerTest.cs | 17 +- .../Pharmacophore/PharmacophoreUtilityTest.cs | 25 +- NCDKTests/QSAR/DescriptorEngineTest.cs | 49 +- NCDKTests/QSAR/DescriptorNamesTest.cs | 8 +- NCDKTests/QSAR/DescriptorValueTest.cs | 29 +- .../Atomic/AtomDegreeDescriptorTest.cs | 3 +- .../Atomic/AtomHybridizationDescriptorTest.cs | 5 +- .../AtomHybridizationVSEPRDescriptorTest.cs | 12 +- .../Atomic/AtomValenceDescriptorTest.cs | 3 +- .../Atomic/AtomicDescriptorTest.cs | 11 +- .../Atomic/BondsToAtomDescriptorTest.cs | 3 +- .../Atomic/CovalentRadiusDescriptorTest.cs | 3 +- .../Atomic/DistanceToAtomDescriptorTest.cs | 2 +- ...fectiveAtomPolarizabilityDescriptorTest.cs | 15 +- .../Atomic/IPAtomicHOSEDescriptorTest.cs | 71 +- .../InductiveAtomicHardnessDescriptorTest.cs | 2 +- .../InductiveAtomicSoftnessDescriptorTest.cs | 2 +- .../IsProtonInAromaticSystemDescriptorTest.cs | 3 +- ...rotonInConjugatedPiSystemDescriptorTest.cs | 3 +- .../Atomic/PartialPiChargeDescriptorTest.cs | 59 +- .../PartialSigmaChargeDescriptorTest.cs | 41 +- .../PartialTChargePEOEDescriptorTest.cs | 18 +- .../PeriodicTablePositionDescriptorTest.cs | 3 +- .../PiElectronegativityDescriptorTest.cs | 66 +- .../ProtonAffinityHOSEDescriptorTest.cs | 5 +- .../ProtonTotalPartialChargeDescriptorTest.cs | 5 +- .../Atomic/RDFProtonDescriptor_G3RTest.cs | 6 +- .../Atomic/RDFProtonDescriptor_GDRTest.cs | 6 +- .../Atomic/RDFProtonDescriptor_GHRTest.cs | 6 +- .../RDFProtonDescriptor_GHR_topolTest.cs | 6 +- .../Atomic/RDFProtonDescriptor_GSRTest.cs | 6 +- .../SigmaElectronegativityDescriptorTest.cs | 7 +- .../StabilizationPlusChargeDescriptorTest.cs | 19 +- .../Atomic/VdWRadiusDescriptorTest.cs | 3 +- .../AtomicNumberDifferenceDescriptorTest.cs | 5 +- .../Descriptors/Bonds/BondDescriptorTest.cs | 9 +- .../BondPartialPiChargeDescriptorTest.cs | 9 +- .../BondPartialSigmaChargeDescriptorTest.cs | 15 +- .../Bonds/BondPartialTChargeDescriptorTest.cs | 15 +- ...ondSigmaElectronegativityDescriptorTest.cs | 18 +- NCDKTests/QSAR/Descriptors/DescriptorTest.cs | 41 +- .../Moleculars/ALOGPDescriptorTest.cs | 14 +- .../Moleculars/APolDescriptorTest.cs | 3 +- .../AromaticAtomsCountDescriptorTest.cs | 3 +- .../AromaticBondsCountDescriptorTest.cs | 3 +- .../Moleculars/AtomCountDescriptorTest.cs | 5 +- .../AutocorrelationDescriptorChargeTest.cs | 2 +- .../AutocorrelationDescriptorMassTest.cs | 2 +- ...correlationDescriptorPolarizabilityTest.cs | 2 +- .../Moleculars/BCUTDescriptorTest.cs | 6 +- .../Moleculars/BPolDescriptorTest.cs | 3 +- .../BasicGroupCountDescriptorTest.cs | 2 +- .../Moleculars/CPSADescriptorTest.cs | 2 +- .../Moleculars/CarbonTypesDescriptorTest.cs | 7 +- .../Moleculars/ChiChainDescriptorTest.cs | 55 +- .../Moleculars/ChiClusterDescriptorTest.cs | 11 +- .../Moleculars/ChiIndexUtilsTest.cs | 6 +- .../ChiPathClusterDescriptorTest.cs | 11 +- .../Moleculars/ChiPathDescriptorTest.cs | 12 +- ...ccentricConnectivityIndexDescriptorTest.cs | 2 +- .../Moleculars/FMFDescriptorTest.cs | 9 +- .../Moleculars/FractionalPSADescriptorTest.cs | 2 +- .../FragmentComplexityDescriptorTest.cs | 4 +- .../GravitationalIndexDescriptorTest.cs | 2 +- .../HBondAcceptorCountDescriptorTest.cs | 5 +- .../HBondDonorCountDescriptorTest.cs | 5 +- .../HybridizationRatioDescriptorTest.cs | 7 +- .../KappaShapeIndicesDescriptorTest.cs | 3 +- .../KierHallSmartsDescriptorTest.cs | 8 +- .../Moleculars/LargestChainDescriptorTest.cs | 27 +- .../LargestPiSystemDescriptorTest.cs | 15 +- .../LengthOverBreadthDescriptorTest.cs | 10 +- .../LongestAliphaticChainDescriptorTest.cs | 15 +- .../Moleculars/MDEDescriptorTest.cs | 2 +- .../Moleculars/MolecularDescriptorTest.cs | 228 +- .../MomentOfInertiaDescriptorTest.cs | 4 +- .../PetitjeanNumberDescriptorTest.cs | 5 +- .../PetitjeanShapeIndexDescriptorTest.cs | 4 +- .../RotatableBondsCountDescriptorTest.cs | 8 +- .../Moleculars/RuleOfFiveDescriptorTest.cs | 7 +- .../Moleculars/SmallRingDescriptorTest.cs | 16 +- .../Moleculars/TPSADescriptorTest.cs | 3 +- .../Moleculars/VAdjMaDescriptorTest.cs | 7 +- .../Moleculars/WeightDescriptorTest.cs | 9 +- .../Moleculars/WeightedPathDescriptorTest.cs | 4 +- .../Moleculars/WienerNumbersDescriptorTest.cs | 7 +- .../Moleculars/XLogPDescriptorTest.cs | 47 +- .../Moleculars/ZagrebIndexDescriptorTest.cs | 6 +- .../OxygenAtomCountDescriptorTest.cs | 6 +- .../Substances/SubstanceDescriptorTest.cs | 4 +- NCDKTests/Reactions/ReactionMechanismTest.cs | 2 +- NCDKTests/Reactions/ReactionProcessTest.cs | 2 +- .../Types/AdductionProtonLPReactionTest.cs | 8 +- .../Types/AdductionProtonPBReactionTest.cs | 8 +- .../Types/AdductionSodiumLPReactionTest.cs | 8 +- .../Types/CarbonylEliminationReactionTest.cs | 7 +- .../Types/ElectronImpactNBEReactionTest.cs | 32 +- .../Types/ElectronImpactPDBReactionTest.cs | 12 +- .../Types/ElectronImpactSDBReactionTest.cs | 6 +- .../HeterolyticCleavagePBReactionTest.cs | 45 +- .../HeterolyticCleavageSBReactionTest.cs | 46 +- .../Types/HomolyticCleavageReactionTest.cs | 63 +- .../Types/HyperconjugationReactionTest.cs | 5 +- .../Types/PiBondingMovementReactionTest.cs | 7 +- ...adicalChargeSiteInitiationHReactionTest.cs | 4 +- ...RadicalChargeSiteInitiationReactionTest.cs | 4 +- .../Types/RadicalSiteHrAlphaReactionTest.cs | 4 +- .../Types/RadicalSiteHrBetaReactionTest.cs | 4 +- .../Types/RadicalSiteHrDeltaReactionTest.cs | 4 +- .../Types/RadicalSiteHrGammaReactionTest.cs | 4 +- .../RadicalSiteInitiationHReactionTest.cs | 4 +- .../RadicalSiteInitiationReactionTest.cs | 4 +- .../Types/RadicalSiteRrAlphaReactionTest.cs | 4 +- .../Types/RadicalSiteRrBetaReactionTest.cs | 4 +- .../Types/RadicalSiteRrDeltaReactionTest.cs | 4 +- .../Types/RadicalSiteRrGammaReactionTest.cs | 4 +- .../Types/RearrangementAnionReactionTest.cs | 15 +- .../Types/RearrangementCationReactionTest.cs | 3 +- .../RearrangementLonePairReactionTest.cs | 17 +- .../Types/RearrangementRadicalReactionTest.cs | 4 +- .../Types/SharingAnionReactionTest.cs | 14 +- .../Types/SharingChargeDBReactionTest.cs | 8 +- .../Types/SharingChargeSBReactionTest.cs | 27 +- .../Types/SharingLonePairReactionTest.cs | 8 +- .../Types/TautomerizationReactionTest.cs | 7 +- NCDKTests/RingSearches/AllRingsFinderTest.cs | 48 +- .../JumboCyclicVertexSearchTest.cs | 15 +- .../RegularCyclicVertexSearchTest.cs | 8 +- NCDKTests/RingSearches/RingPartitionerTest.cs | 14 +- NCDKTests/RingSearches/RingSearchTest.cs | 13 +- .../RingSearches/RingSearchTest_Benzene.cs | 23 +- .../RingSearchTest_BenzylBenzene.cs | 25 +- .../RingSearches/RingSearchTest_Bicyclo.cs | 25 +- .../RingSearches/RingSearchTest_Biphenyl.cs | 23 +- .../RingSearches/RingSearchTest_Empty.cs | 7 +- .../RingSearches/RingSearchTest_Fused.cs | 25 +- .../RingSearchTest_Hexaphenylene.cs | 27 +- .../RingSearches/RingSearchTest_NonCyclic.cs | 5 +- .../RingSearches/RingSearchTest_SpiroRings.cs | 25 +- .../SMARTS/SmartsFragmentExtractorTest.cs | 39 +- NCDKTests/SMSD/AbstractMCSTest.cs | 9 +- NCDKTests/SMSD/AbstractSubGraphTest.cs | 3 +- .../Algorithms/MCSPluses/ExactMappingTest.cs | 3 +- .../GenerateCompatibilityGraphTest.cs | 2 +- .../MCSPluses/MCSPlusHandlerTest.cs | 16 +- .../SMSD/Algorithms/MCSPluses/MCSPlusTest.cs | 5 +- .../{RGraph => RGraphs}/CDKMCSHandlerTest.cs | 18 +- .../{RGraph => RGraphs}/CDKMCSTest.cs | 34 +- .../{RGraph => RGraphs}/CDKRGraphTest.cs | 2 +- .../{RGraph => RGraphs}/CDKRMapHandlerTest.cs | 34 +- .../{RGraph => RGraphs}/CDKRMapTest.cs | 2 +- .../{RGraph => RGraphs}/CDKRNodeTest.cs | 2 +- .../SingleMappingHandlerTest.cs | 5 +- .../{Single => Singles}/SingleMappingTest.cs | 5 +- NCDKTests/SMSD/Algorithms/VFLib/Molecules.cs | 198 +- NCDKTests/SMSD/Algorithms/VFLib/VFLibTest.cs | 34 +- .../Algorithms/VFLib/VFlibMCSHandlerTest.cs | 16 +- .../Algorithms/VFLib/VFlibTurboHandlerTest.cs | 17 +- .../SubStructureSearchAlgorithmsTest.cs | 35 +- NCDKTests/SMSD/Filters/ChemicalFiltersTest.cs | 13 +- NCDKTests/SMSD/Filters/PostFilterTest.cs | 59 +- .../SMSD/{Global => Globals}/TimeOutTest.cs | 2 +- NCDKTests/SMSD/Helper/FinalMappingsTest.cs | 50 +- NCDKTests/SMSD/Helper/MolHandlerTest.cs | 2 +- .../{Ring => Rings}/HanserRingFinderTest.cs | 2 +- NCDKTests/SMSD/SMSDBondInsensitiveTest.cs | 116 +- NCDKTests/SMSD/SMSDBondSensitiveTest.cs | 9 +- NCDKTests/SMSD/SMSDTest.cs | 54 +- NCDKTests/SMSD/Tools/BondEnergiesTest.cs | 2 +- .../Tools/ExtAtomContainerManipulatorTest.cs | 17 +- .../SMSD/Tools/MoleculeSanityCheckTest.cs | 5 +- NCDKTests/Signatures/MoleculeSignatureTest.cs | 7 +- NCDKTests/Signatures/OrbitTest.cs | 10 +- NCDKTests/Silent/ChemObjectTestHelper.cs | 5 +- NCDKTests/Similarity/DistanceMomentTest.cs | 2 +- NCDKTests/Similarity/LingoSimilarityTest.cs | 12 +- .../SignatureFingerprintTanimotoTest.cs | 69 +- NCDKTests/Similarity/TanimotoTest.cs | 11 +- NCDKTests/Smiles/CDKToBeamTest.cs | 31 +- NCDKTests/Smiles/CxSmilesGeneratorTest.cs | 60 +- NCDKTests/Smiles/CxSmilesParserTest.cs | 13 +- NCDKTests/Smiles/CxSmilesTest.cs | 64 +- NCDKTests/Smiles/DeduceBondSystemToolTest.cs | 10 +- NCDKTests/Smiles/FixBondOrdersToolTest.cs | 45 +- NCDKTests/Smiles/InvPairTest.cs | 16 +- NCDKTests/Smiles/SMARTS/Parser/ParserTest.cs | 25 +- .../Smiles/SMARTS/Parser/RecursiveTest.cs | 16 +- .../Smiles/SMARTS/Parser/SMARTSSearchTest.cs | 52 +- .../SMARTS/Parser/SmartsQueryVisitorTest.cs | 3 +- .../Smiles/SMARTS/Parser/SmartsStereoTest.cs | 3 +- .../Smiles/SMARTS/SMARTSQueryToolTest.cs | 41 +- NCDKTests/Smiles/SmilesGeneratorTest.cs | 121 +- NCDKTests/Smiles/SmilesParserTest.cs | 85 +- .../CyclicCarbohydrateRecognitionTest.cs | 31 +- .../Stereo/DoubleBondStereochemistryTest.cs | 12 +- NCDKTests/Stereo/ExtendedTetrahedralTest.cs | 18 +- NCDKTests/Stereo/FischerRecognitionTest.cs | 25 +- NCDKTests/Stereo/StereoElementFactoryTest.cs | 152 +- NCDKTests/Stereo/StereoToolTest.cs | 2 +- NCDKTests/Stereo/StereocentersTest.cs | 34 +- NCDKTests/Stereo/TetrahedralChiralityTest.cs | 14 +- NCDKTests/Stereo/TrigonalBipyramidalTest.cs | 7 +- .../SingleStructureRandomGeneratorTest.cs | 2 +- .../Stochastic/Operator/ChemGraphTest.cs | 2 +- .../Operator/CrossoverMachineTest.cs | 2 +- .../PartialFilledStructureMergerTest.cs | 25 +- NCDKTests/StructGen/VicinitySamplerTest.cs | 4 +- NCDKTests/TT/AdductFormulaTest.tt.cs | 1 + NCDKTests/TT/AminoAcidTest.tt | 4 +- NCDKTests/TT/AminoAcidTest.tt.cs | 5 +- NCDKTests/TT/AtomContainer2Test.tt | 4 +- NCDKTests/TT/AtomContainer2Test.tt.cs | 5 +- NCDKTests/TT/AtomContainerSetTest.tt | 2 +- NCDKTests/TT/AtomContainerSetTest.tt.cs | 3 +- NCDKTests/TT/AtomContainerTest.tt | 8 +- NCDKTests/TT/AtomContainerTest.tt.cs | 13 +- NCDKTests/TT/AtomTest.tt | 2 +- NCDKTests/TT/AtomTest.tt.cs | 3 +- NCDKTests/TT/AtomTypeTest.tt | 2 +- NCDKTests/TT/AtomTypeTest.tt.cs | 3 +- NCDKTests/TT/BioPolymerTest.tt | 4 +- NCDKTests/TT/BioPolymerTest.tt.cs | 5 +- NCDKTests/TT/BondTest.tt | 2 +- NCDKTests/TT/BondTest.tt.cs | 3 +- NCDKTests/TT/ChemFileTest.tt | 2 +- NCDKTests/TT/ChemFileTest.tt.cs | 3 +- NCDKTests/TT/ChemModelTest.tt | 2 +- NCDKTests/TT/ChemModelTest.tt.cs | 3 +- NCDKTests/TT/ChemObjectBuilderTest.tt.cs | 1 + NCDKTests/TT/ChemObjectTest.tt | 4 +- NCDKTests/TT/ChemObjectTest.tt.cs | 7 +- NCDKTests/TT/ChemSequenceTest.tt | 4 +- NCDKTests/TT/ChemSequenceTest.tt.cs | 7 +- NCDKTests/TT/ConformerContainerTest.tt.cs | 1 + NCDKTests/TT/CrystalTest.tt | 4 +- NCDKTests/TT/CrystalTest.tt.cs | 5 +- NCDKTests/TT/ElectronContainerTest.tt | 2 +- NCDKTests/TT/ElectronContainerTest.tt.cs | 3 +- NCDKTests/TT/ElementTest.tt | 2 +- NCDKTests/TT/ElementTest.tt.cs | 3 +- NCDKTests/TT/FragmentAtomTest.tt | 2 +- NCDKTests/TT/FragmentAtomTest.tt.cs | 3 +- NCDKTests/TT/IsotopeTest.tt | 2 +- NCDKTests/TT/IsotopeTest.tt.cs | 3 +- NCDKTests/TT/LonePairTest.tt | 2 +- NCDKTests/TT/LonePairTest.tt.cs | 3 +- NCDKTests/TT/MappingTest.tt | 2 +- NCDKTests/TT/MappingTest.tt.cs | 3 +- NCDKTests/TT/MolecularFormulaSetTest.tt.cs | 1 + NCDKTests/TT/MolecularFormulaTest.tt | 6 +- NCDKTests/TT/MolecularFormulaTest.tt.cs | 13 +- NCDKTests/TT/MonomerTest.tt | 4 +- NCDKTests/TT/MonomerTest.tt.cs | 5 +- NCDKTests/TT/PDBAtomTest.tt | 2 +- NCDKTests/TT/PDBAtomTest.tt.cs | 3 +- NCDKTests/TT/PDBMonomerTest.tt | 4 +- NCDKTests/TT/PDBMonomerTest.tt.cs | 5 +- NCDKTests/TT/PDBPolymerTest.tt | 8 +- NCDKTests/TT/PDBPolymerTest.tt.cs | 13 +- NCDKTests/TT/PDBStructureTest.tt.cs | 1 + NCDKTests/TT/PolymerTest.tt | 6 +- NCDKTests/TT/PolymerTest.tt.cs | 9 +- NCDKTests/TT/PseudoAtomTest.tt | 2 +- NCDKTests/TT/PseudoAtomTest.tt.cs | 3 +- NCDKTests/TT/ReactionChainTest.tt.cs | 1 + NCDKTests/TT/ReactionSchemeTest.tt | 2 +- NCDKTests/TT/ReactionSchemeTest.tt.cs | 3 +- NCDKTests/TT/ReactionSetTest.tt | 2 +- NCDKTests/TT/ReactionSetTest.tt.cs | 3 +- NCDKTests/TT/ReactionTest.tt | 2 +- NCDKTests/TT/ReactionTest.tt.cs | 3 +- NCDKTests/TT/RingSetTest.tt | 2 +- NCDKTests/TT/RingSetTest.tt.cs | 3 +- NCDKTests/TT/RingTest.tt | 4 +- NCDKTests/TT/RingTest.tt.cs | 5 +- NCDKTests/TT/SingleElectronTest.tt | 2 +- NCDKTests/TT/SingleElectronTest.tt.cs | 3 +- NCDKTests/TT/StrandTest.tt | 4 +- NCDKTests/TT/StrandTest.tt.cs | 5 +- NCDKTests/TT/SubstanceTest.tt | 2 +- NCDKTests/TT/SubstanceTest.tt.cs | 3 +- .../Tautomers/InChITautomerGeneratorTest.cs | 4 +- NCDKTests/Templates/TestMoleculeFactory.cs | 8 +- NCDKTests/Tools/ATASaturationCheckerTest.cs | 146 +- NCDKTests/Tools/BremserPredictorTest.cs | 12 +- NCDKTests/Tools/CDKHydrogenAdderTest.cs | 2 +- NCDKTests/Tools/CDKValencyCheckerTest.cs | 4 +- NCDKTests/Tools/DataFeaturesTest.cs | 2 +- ...educeBondOrderTestFromExplicitHydrogens.cs | 2 +- NCDKTests/Tools/HOSECodeAnalyserTest.cs | 3 +- NCDKTests/Tools/HOSECodeGeneratorTest.cs | 64 +- NCDKTests/Tools/IDCreatorTest.cs | 2 +- .../Tools/LonePairElectronCheckerTest.cs | 26 +- .../AtomContainerComparatorBy2DCenterTest.cs | 2 +- .../AtomContainerComparatorTest.cs | 14 +- .../AtomContainerManipulatorTest.cs | 183 +- .../AtomContainerSetManipulatorTest.cs | 9 +- .../Manipulator/AtomTypeManipulatorTest.cs | 2 +- .../Tools/Manipulator/BondManipulatorTest.cs | 2 +- .../Manipulator/ChemFileManipulatorTest.cs | 2 +- .../Manipulator/ChemModelManipulatorTest.cs | 8 +- .../ChemSequenceManipulatorTest.cs | 4 +- .../MolecularFormulaManipulatorTest.cs | 38 +- .../Manipulator/MoleculeSetManipulatorTest.cs | 2 +- .../Manipulator/ReactionManipulatorTest.cs | 6 +- .../ReactionSchemeManipulatorTest.cs | 3 +- .../Manipulator/ReactionSetManipulatorTest.cs | 4 +- .../Tools/Manipulator/RingManipulatorTest.cs | 2 +- .../Manipulator/RingSetManipulatorTest.cs | 13 +- .../Manipulator/RingSizeComparatorTest.cs | 9 +- NCDKTests/Tools/SaturationCheckerTest.cs | 4 +- .../Tools/StructureResonanceGeneratorTest.cs | 102 +- NCDKTests/Validate/Geometry3DValidatorTest.cs | 2 +- NCDKTests/Validate/ProblemMarkerTest.cs | 6 +- README.md | 4 +- 1660 files changed, 24046 insertions(+), 23835 deletions(-) rename ExampleCodes/{ForceField/MMFF => ForceFields}/MmffAtomTypeMatcher_Example.cs (78%) rename ExampleCodes/{ForceField/MMFF => ForceFields}/Mmff_Example.cs (80%) create mode 100644 ExampleCodes/SMARTS/SmartsFragmentExtractor_Example.cs rename ExampleCodes/SMSD/Algorithms/{RGraph => RGraphs}/CDKMCS_Example.cs (72%) rename NCDK/StructGen/IStructureGenerationListener.cs => MolViewer/ChemObjectChangedEventArgs.cs (65%) rename NCDK/Beam/Core/{Function.cs => IFunction.cs} (95%) create mode 100644 NCDK/Common/Collections/EmptyCollections.cs delete mode 100644 NCDK/Common/Collections/EmptyCollections.tt delete mode 100644 NCDK/Common/Collections/EmptyCollections.tt.cs delete mode 100644 NCDK/Common/Collections/Maps.cs rename NCDK/Common/Collections/{MultiMap.cs => MultiDictionary.cs} (92%) create mode 100644 NCDK/Common/Serialization/SerializationTool.cs rename NCDK/Config/{AtomType => AtomTypes}/AtomTypeReader.cs (91%) rename NCDK/Config/{AtomType => AtomTypes}/OWLAtomTypeMappingHandler.cs (84%) rename NCDK/Config/{AtomType => AtomTypes}/OWLAtomTypeMappingReader.cs (87%) rename NCDK/Config/{AtomType => AtomTypes}/OWLAtomTypeReader.cs (88%) rename NCDK/Config/{AtomType => AtomTypes}/OWLConstants.cs (98%) rename NCDK/Config/{Isotopes.cs => BODRIsotopeFactory.cs} (52%) rename NCDK/Config/{Isotope => Isotopes}/IsotopeHandler.cs (82%) rename NCDK/Config/{Isotope => Isotopes}/IsotopeReader.cs (87%) rename NCDK/{ForceField/MMFF/README => ForceFields/MMFF.README} (100%) rename NCDK/{ForceField/MMFF => ForceFields}/MMFFCHG.PAR (100%) rename NCDK/{ForceField/MMFF => ForceFields}/MMFFFORMCHG.PAR (100%) rename NCDK/{ForceField/MMFF => ForceFields}/MMFFPBCI.PAR (100%) rename NCDK/{ForceField/MMFF => ForceFields}/MMFFPROP.PAR (100%) rename NCDK/{ForceField/MMFF => ForceFields}/MMFFSYMB.sma (100%) rename NCDK/{ForceField/MMFF => ForceFields}/Mmff.cs (68%) rename NCDK/{ForceField/MMFF => ForceFields}/MmffAromaticTypeMapping.cs (89%) rename NCDK/{ForceField/MMFF => ForceFields}/MmffAtomTypeMatcher.cs (93%) rename NCDK/{ForceField/MMFF => ForceFields}/MmffParamSet.cs (87%) rename NCDK/{ForceField/MMFF => ForceFields}/mmff-symb-mapping.tsv (100%) create mode 100644 NCDK/GlobalSuppressions.cs create mode 100644 NCDK/NCDK.ruleset create mode 100644 NCDK/SGroups/SgroupTool.cs rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKMCS.cs (90%) rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKMCSHandler.cs (84%) rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKRGraph.cs (97%) rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKRMap.cs (98%) rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKRMapHandler.cs (82%) rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKRNode.cs (83%) rename NCDK/SMSD/Algorithms/{RGraph => RGraphs}/CDKSubGraphHandler.cs (84%) rename NCDK/SMSD/Algorithms/{Single => Singles}/SingleMapping.cs (83%) rename NCDK/SMSD/Algorithms/{Single => Singles}/SingleMappingHandler.cs (74%) rename NCDK/SMSD/{Global => Globals}/TimeOut.cs (98%) rename NCDK/SMSD/{Ring => Rings}/HanserRingFinder.cs (99%) rename NCDK/SMSD/{Ring => Rings}/IRingFinder.cs (99%) rename NCDK/SMSD/{Ring => Rings}/PathEdge.cs (98%) rename NCDK/SMSD/{Ring => Rings}/PathGraph.cs (98%) rename NCDK/SMSD/{Ring => Rings}/RingFilter.cs (99%) rename NCDK/StructGen/Stochastic/{Operator => Operators}/ChemGraph.cs (75%) rename NCDK/StructGen/Stochastic/{Operator => Operators}/CrossoverMachine.cs (83%) create mode 100644 NCDKDisplay/Renderers/Generators/IPalette.cs rename NCDKTests/Config/{AtomType => AtomTypes}/AtomTypeReaderTest.cs (99%) rename NCDKTests/Config/{AtomType => AtomTypes}/OWLAtomTypeMappingHandlerTest.cs (98%) rename NCDKTests/Config/{AtomType => AtomTypes}/OWLAtomTypeMappingReaderTest.cs (96%) rename NCDKTests/Config/{AtomType => AtomTypes}/OWLAtomTypeReaderTest.cs (98%) rename NCDKTests/{ForceField/MMFF => ForceFields}/AbstractMmffAtomTypeValidationSuiteTest.cs (99%) rename NCDKTests/{ForceField/MMFF => ForceFields}/MmffAromaticTypeMappingTest.cs (95%) rename NCDKTests/{ForceField/MMFF => ForceFields}/MmffAtomTypeMatcherTest.cs (99%) rename NCDKTests/{ForceField/MMFF => ForceFields}/MmffAtomTypeValidationSuiteTest.cs (98%) rename NCDKTests/{ForceField/MMFF => ForceFields}/MmffParamSetTest.cs (98%) rename NCDKTests/{ForceField/MMFF => ForceFields}/MmffTest.cs (99%) rename NCDKTests/SMSD/Algorithms/{RGraph => RGraphs}/CDKMCSHandlerTest.cs (92%) rename NCDKTests/SMSD/Algorithms/{RGraph => RGraphs}/CDKMCSTest.cs (92%) rename NCDKTests/SMSD/Algorithms/{RGraph => RGraphs}/CDKRGraphTest.cs (96%) rename NCDKTests/SMSD/Algorithms/{RGraph => RGraphs}/CDKRMapHandlerTest.cs (86%) rename NCDKTests/SMSD/Algorithms/{RGraph => RGraphs}/CDKRMapTest.cs (97%) rename NCDKTests/SMSD/Algorithms/{RGraph => RGraphs}/CDKRNodeTest.cs (97%) rename NCDKTests/SMSD/Algorithms/{Single => Singles}/SingleMappingHandlerTest.cs (99%) rename NCDKTests/SMSD/Algorithms/{Single => Singles}/SingleMappingTest.cs (97%) rename NCDKTests/SMSD/{Global => Globals}/TimeOutTest.cs (99%) rename NCDKTests/SMSD/{Ring => Rings}/HanserRingFinderTest.cs (99%) diff --git a/BuildAll.bat b/BuildAll.bat index d695aa13..0ea72a51 100644 --- a/BuildAll.bat +++ b/BuildAll.bat @@ -1,4 +1,6 @@ pushd NCDK +dotnet add package MathNet.Numerics.Signed +dotnet add package dotNetRDF call :BuildProject NCDK popd diff --git a/ChemObjectConfig.ttinclude b/ChemObjectConfig.ttinclude index be07ea09..fc1035fd 100644 --- a/ChemObjectConfig.ttinclude +++ b/ChemObjectConfig.ttinclude @@ -1,6 +1,6 @@ <# /* - * Copyright (C) 2017 Kazuya Ujihara + * Copyright (C) 2017-2018 Kazuya Ujihara * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ #> + <#@ template debug="false" hostspecific="false" language="C#" #> <#@ output extension=".tt.cs" #> <#@ Assembly Name="System.Core.dll" #> @@ -75,7 +76,7 @@ /// /// A dictionary for the storage of any kind of properties of this object. /// - IDictionary properties; + private Dictionary properties; private void InitProperties() { @@ -83,7 +84,7 @@ } /// - public virtual void SetProperty(object description, object property) + public virtual void SetProperty(object description, object value) { #if DEBUG if (description != null && !AcceptablePropertyKeyTypes.Contains(description.GetType())) @@ -91,7 +92,7 @@ #endif if (this.properties == null) InitProperties(); - properties[description] = property; + properties[description] = value; <#+ if (addNofityChanged) { #> NotifyChanged(); <#+ } #> @@ -137,10 +138,10 @@ return defaultValue; } - private static readonly IDictionary emptyProperties = new System.Collections.ObjectModel.ReadOnlyDictionary(new Dictionary(0)); + private static readonly IReadOnlyDictionary emptyProperties = NCDK.Common.Collections.Dictionaries.Empty(); /// - public virtual IDictionary GetProperties() + public virtual IReadOnlyDictionary GetProperties() { if (this.properties == null) return emptyProperties; diff --git a/Config.ttinclude b/Config.ttinclude index 1284fc79..190ac302 100644 --- a/Config.ttinclude +++ b/Config.ttinclude @@ -156,15 +156,25 @@ foreach (var s in entities) } public static explicit operator <#= name #>(int ordinal) + { + return To<#= name #>(ordinal); + } + + public static <#= name #> To<#= name #>(int ordinal) { if (!(0 <= ordinal && ordinal < values.Length)) - throw new System.ArgumentOutOfRangeException(); + throw new System.ArgumentOutOfRangeException(nameof(ordinal)); return values[ordinal]; } - public static explicit operator int(<#= name #> obj) + public static explicit operator int(<#= name #> o) + { + return ToInt32(o); + } + + public static int ToInt32(<#= name #> o) { - return obj.Ordinal; + return o.Ordinal; } <#+ @@ -196,7 +206,7 @@ foreach (var s in entities) <#= OName(s) #>, <#+ } #> }; - public static <#= name #>[] Values => values; + public static System.Collections.Generic.IReadOnlyList<<#= name #>> Values => values; <#+ if (isStruct) diff --git a/ExampleCodes/Aromaticities/Aromaticity_Example.cs b/ExampleCodes/Aromaticities/Aromaticity_Example.cs index db0d7115..e3135c7a 100644 --- a/ExampleCodes/Aromaticities/Aromaticity_Example.cs +++ b/ExampleCodes/Aromaticities/Aromaticity_Example.cs @@ -13,7 +13,7 @@ public static void Main(string[] args) var molecules = new Silent.AtomContainerSet(); #region ElectronDonation model = ElectronDonation.DaylightModel; - ICycleFinder cycles = Cycles.Or(Cycles.AllFinder, Cycles.GetAllFinder(6)); + ICycleFinder cycles = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(6)); Aromaticity aromaticity = new Aromaticity(model, cycles); // apply our configured model to each molecule @@ -30,14 +30,14 @@ public static void Main(string[] args) // mimics the DoubleBondAcceptingAromaticityDetector Aromaticity aromaticity_exo = new Aromaticity(ElectronDonation.CDKAllowingExocyclicModel, Cycles.CDKAromaticSetFinder); // a good model for writing SMILES - Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); // a good model for writing MDL/Mol2 - Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllFinder); + Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllSimpleFinder); #endregion } { #region FindBonds - Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); try @@ -53,7 +53,7 @@ public static void Main(string[] args) } { #region Apply - Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); try { @@ -75,7 +75,7 @@ public static void Main(string[] args) } { #region CDKLegacy_AllFinder_RelevantFinder - new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllFinder, Cycles.RelevantFinder)); + new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllSimpleFinder, Cycles.RelevantFinder)); #endregion } } diff --git a/ExampleCodes/Config/XMLIsotopeFactory_Example.cs b/ExampleCodes/Config/XMLIsotopeFactory_Example.cs index 92366f85..8770bb90 100644 --- a/ExampleCodes/Config/XMLIsotopeFactory_Example.cs +++ b/ExampleCodes/Config/XMLIsotopeFactory_Example.cs @@ -2,9 +2,9 @@ namespace NCDK.Config { - public class XMLIsotopeFactory_Example + public static class XMLIsotopeFactory_Example { - public void Main() + public static void Main() { { #region 1 @@ -13,7 +13,7 @@ public void Main() } { #region example - IsotopeFactory factory = XMLIsotopeFactory.GetInstance(Default.ChemObjectBuilder.Instance); + IsotopeFactory factory = XMLIsotopeFactory.GetInstance(ChemObjectBuilder.Instance); IIsotope major = factory.GetMajorIsotope("H"); #endregion } diff --git a/ExampleCodes/ConformerContainer_Example.cs b/ExampleCodes/ConformerContainer_Example.cs index 278908b9..8058e37b 100644 --- a/ExampleCodes/ConformerContainer_Example.cs +++ b/ExampleCodes/ConformerContainer_Example.cs @@ -1,17 +1,18 @@ using NCDK.IO.Iterator; +using NCDK.Silent; using System.IO; namespace NCDK { - public class ConformerContainer_Example + public static class ConformerContainer_Example { - public void Ctor() + public static void Ctor() { string filename = null; #region var reader = new IEnumerableMDLConformerReader( new FileStream(filename, FileMode.Open), - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); foreach (ConformerContainer cc in reader) { foreach (var conformer in cc) diff --git a/ExampleCodes/ExampleCodes.csproj b/ExampleCodes/ExampleCodes.csproj index 524d2278..e7eaff9b 100644 --- a/ExampleCodes/ExampleCodes.csproj +++ b/ExampleCodes/ExampleCodes.csproj @@ -72,8 +72,8 @@ - - + + @@ -135,11 +135,12 @@ + - + @@ -174,7 +175,6 @@ NCDK - " + stack[sp-1].splitValue); + // Debug.WriteLine($"-->{stack[sp-1].splitValue}"); ele = stack[--sp].eleGE; while (ele is Node) { @@ -322,7 +322,7 @@ class Node : IElement public double splitValue; public IElement eleGE; - private Bspt parent; + private readonly Bspt parent; public Node(Bspt parent, int dim, int dimMax, Leaf leafLE) { @@ -464,7 +464,7 @@ public bool IsLeafWithSpace() public interface ITuple { - double GetDimValue(int dim); + double GetDimValue(int dimension); double Distance2 { get; set; } // the dist squared of a found Element; } } diff --git a/NCDK/Graphs/Rebond/RebondTool.cs b/NCDK/Graphs/Rebond/RebondTool.cs index 3347f583..bda18799 100644 --- a/NCDK/Graphs/Rebond/RebondTool.cs +++ b/NCDK/Graphs/Rebond/RebondTool.cs @@ -41,8 +41,8 @@ namespace NCDK.Graphs.Rebond public class RebondTool { private double maxCovalentRadius; - private double minBondDistance; - private double bondTolerance; + private readonly double minBondDistance; + private readonly double bondTolerance; private Bspt bspt; @@ -118,34 +118,31 @@ private bool IsBonded(double covalentRadiusA, double covalentRadiusB, double dis return distance2 <= maxAcceptable2; } - public interface ITupleAtom : ITuple + internal interface ITupleAtom : ITuple { IAtom Atom { get; } } - public class TupleAtom : ITupleAtom + private class TupleAtom : ITupleAtom { - IAtom atom; - public TupleAtom(IAtom atom) { - this.atom = atom; + this.Atom = atom; } public virtual double GetDimValue(int dim) { - if (dim == 0) return atom.Point3D.Value.X; - if (dim == 1) return atom.Point3D.Value.Y; - return atom.Point3D.Value.Z; + if (dim == 0) return Atom.Point3D.Value.X; + if (dim == 1) return Atom.Point3D.Value.Y; + return Atom.Point3D.Value.Z; } - public IAtom Atom => this.atom; - + public IAtom Atom { get; } public double Distance2 { get; set; } public override string ToString() { - return ("<" + atom.Point3D.Value.X + "," + atom.Point3D.Value.Y + "," + atom.Point3D.Value.Z + ">"); + return ("<" + Atom.Point3D.Value.X + "," + Atom.Point3D.Value.Y + "," + Atom.Point3D.Value.Z + ">"); } } } diff --git a/NCDK/Graphs/RegularPathGraph.cs b/NCDK/Graphs/RegularPathGraph.cs index 447732bb..420fbaeb 100644 --- a/NCDK/Graphs/RegularPathGraph.cs +++ b/NCDK/Graphs/RegularPathGraph.cs @@ -49,7 +49,7 @@ sealed class RegularPathGraph private static readonly List EmptyPathEdgeList = new List(); /// Path edges, indexed by their end points (incidence list). - private IList[] graph; + private List[] graph; /// Limit on the maximum Length of cycle to be found. private readonly int limit; @@ -76,11 +76,11 @@ public RegularPathGraph(int[][] mGraph, int[] rank, int limit) // check configuration if (!(ord > 2)) - throw new ArgumentOutOfRangeException(nameof(graph), "graph was acyclic"); + throw new ArgumentOutOfRangeException(nameof(mGraph), "graph was acyclic"); if (!(limit >= 3 && limit <= ord)) throw new ArgumentOutOfRangeException(nameof(limit), "limit should be from 3 to |V|"); if (!(ord < 64)) - throw new ArgumentOutOfRangeException(nameof(graph), "graph has 64 or more atoms, use JumboPathGraph"); + throw new ArgumentOutOfRangeException(nameof(mGraph), "graph has 64 or more atoms, use JumboPathGraph"); for (int v = 0; v < ord; v++) graph[v] = new List(); @@ -120,9 +120,9 @@ public override int Degree(int x) /// /// a vertex /// vertices incident to - private IList Remove(int x) + private IReadOnlyList Remove(int x) { - IList edges = graph[x]; + var edges = graph[x]; graph[x] = EmptyPathEdgeList; return edges; } @@ -133,27 +133,29 @@ private IList Remove(int x) /// edges which are currently incident to /// a vertex in the graph /// reduced edges - private IList Combine(IList edges, int x) + private static List Combine(IReadOnlyList edges, int x) { int n = edges.Count; - IList reduced = new List(); + var reduced = new List(); - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { PathEdge e = edges[i]; - for (int j = i + 1; j < n; j++) { + for (int j = i + 1; j < n; j++) + { PathEdge f = edges[j]; - if (e.Disjoint(f)) reduced.Add(new ReducedEdge(e, f, x)); + if (e.Disjoint(f)) + reduced.Add(new ReducedEdge(e, f, x)); } } - return reduced; } /// public override void Remove(int x, IList cycles) { - IList edges = Remove(x); - IList reduced = Combine(edges, x); + var edges = Remove(x); + var reduced = Combine(edges, x); foreach (PathEdge e in reduced) { diff --git a/NCDK/Graphs/ShortestPaths.cs b/NCDK/Graphs/ShortestPaths.cs index a598d608..0617d84c 100644 --- a/NCDK/Graphs/ShortestPaths.cs +++ b/NCDK/Graphs/ShortestPaths.cs @@ -50,10 +50,10 @@ namespace NCDK.Graphs public sealed class ShortestPaths { /* empty path when no valid path was found */ - private static readonly int[] EmptyPath = new int[0]; + private static readonly int[] EmptyPath = Array.Empty(); /* empty paths when no valid path was found */ - private static readonly int[][] EmptyPaths = new int[0][] { }; + private static readonly int[][] EmptyPaths = Array.Empty(); /* route to each vertex */ private readonly IRoute[] routeTo; @@ -307,7 +307,7 @@ public int[] GetPathTo(IAtom end) /// whether the path to the only passed through vertices preceding the public bool IsPrecedingPathTo(int end) { - return (end >= 0 || end < routeTo.Length) && precedes[end]; + return (end >= 0 && end < routeTo.Length) && precedes[end]; } /// diff --git a/NCDK/Graphs/SpanningTree.cs b/NCDK/Graphs/SpanningTree.cs index b5a17ce9..2e542f6a 100644 --- a/NCDK/Graphs/SpanningTree.cs +++ b/NCDK/Graphs/SpanningTree.cs @@ -22,6 +22,7 @@ */ using NCDK.Common.Collections; +using System.Globalization; namespace NCDK.Graphs { @@ -43,7 +44,7 @@ public class SpanningTree private int[] parent = null; private int[][] cb = null; // what is cb??? cyclic bonds? - protected bool[] bondsInTree; + private bool[] bondsInTree; private int sptSize = 0; private int edrSize = 0; @@ -133,7 +134,7 @@ private void BuildSpanningTree(IAtomContainer atomContainer) FastFindInit(totalVertexCount); for (int i = 0; i < totalVertexCount; i++) { - (atomContainer.Atoms[i]).SetProperty(ATOM_NUMBER, (i + 1).ToString()); + (atomContainer.Atoms[i]).SetProperty(ATOM_NUMBER, (i + 1).ToString(NumberFormatInfo.InvariantInfo)); } IBond bond; int vertex1, vertex2; @@ -143,8 +144,8 @@ private void BuildSpanningTree(IAtomContainer atomContainer) { bondsInTree[b] = false; bond = atomContainer.Bonds[b]; - vertex1 = int.Parse((bond.Begin).GetProperty(ATOM_NUMBER)); - vertex2 = int.Parse((bond.End).GetProperty(ATOM_NUMBER)); + vertex1 = int.Parse((bond.Begin).GetProperty(ATOM_NUMBER), NumberFormatInfo.InvariantInfo); + vertex2 = int.Parse((bond.End).GetProperty(ATOM_NUMBER), NumberFormatInfo.InvariantInfo); //this below is a little bit slower //v1 = atomContainer.Atoms.IndexOf(bond.GetAtomAt(0))+1; //v2 = atomContainer.Atoms.IndexOf(bond.GetAtomAt(1))+1; @@ -200,7 +201,7 @@ public IAtomContainer GetSpanningTree() /// end of path (target) /// a path through the spanning tree from the source to the target /// if the atom is not in the spanning tree - public IAtomContainer GetPath(IAtomContainer spt, IAtom atom1, IAtom atom2) + public static IAtomContainer GetPath(IAtomContainer spt, IAtom atom1, IAtom atom2) { IAtomContainer path = spt.Builder.NewAtomContainer(); PathTools.ResetFlags(spt); @@ -210,7 +211,7 @@ public IAtomContainer GetPath(IAtomContainer spt, IAtom atom1, IAtom atom2) return path; } - private IRing GetRing(IAtomContainer spt, IBond bond) + private static IRing GetRing(IAtomContainer spt, IBond bond) { IRing ring = spt.Builder.NewRing(); PathTools.ResetFlags(spt); @@ -220,7 +221,7 @@ private IRing GetRing(IAtomContainer spt, IBond bond) return ring; } - private void GetBondsInRing(IAtomContainer mol, IRing ring, int[] bonds) + private static void GetBondsInRing(IAtomContainer mol, IRing ring, int[] bonds) { for (int i = 0; i < ring.Bonds.Count; i++) { diff --git a/NCDK/Groups/AbstractDiscretePartitionRefiner.cs b/NCDK/Groups/AbstractDiscretePartitionRefiner.cs index 9099cb3c..35328682 100644 --- a/NCDK/Groups/AbstractDiscretePartitionRefiner.cs +++ b/NCDK/Groups/AbstractDiscretePartitionRefiner.cs @@ -74,7 +74,7 @@ internal enum Result /// /// A refiner - it is necessary to call before use. /// - public AbstractDiscretePartitionRefiner() + protected AbstractDiscretePartitionRefiner() { this.bestExist = false; this.best = null; @@ -145,11 +145,11 @@ public Partition GetAutomorphismPartition() } class AutomorphismPartitionBacktracker - : PermutationGroup.IBacktracker + : IBacktracker { - int n; + private readonly int n; DisjointSetForest forest; - bool[] inOrbit; + private readonly bool[] inOrbit; private int inOrbitCount = 0; private bool isFinished; diff --git a/NCDK/Groups/AtomDiscretePartitionRefiner.cs b/NCDK/Groups/AtomDiscretePartitionRefiner.cs index 64a52878..d53a2db6 100644 --- a/NCDK/Groups/AtomDiscretePartitionRefiner.cs +++ b/NCDK/Groups/AtomDiscretePartitionRefiner.cs @@ -33,13 +33,13 @@ class AtomDiscretePartitionRefiner : AtomContainerDiscretePartitionRefinerImpl /// /// Ignore the elements when creating the initial partition. /// - private bool ignoreElements; + private readonly bool ignoreElements; /// /// Specialised option to allow generating automorphisms /// that ignore the bond order. /// - private bool ignoreBondOrders; + private readonly bool ignoreBondOrders; /// /// Default constructor - does not ignore elements or bond orders diff --git a/NCDK/Groups/BondDiscretePartitionRefiner.cs b/NCDK/Groups/BondDiscretePartitionRefiner.cs index 130d1826..12e06efa 100644 --- a/NCDK/Groups/BondDiscretePartitionRefiner.cs +++ b/NCDK/Groups/BondDiscretePartitionRefiner.cs @@ -39,7 +39,7 @@ internal class BondDiscretePartitionRefiner : AtomContainerDiscretePartitionRefi /// /// Specialised option to allow generating automorphisms that ignore the bond order. /// - private bool ignoreBondOrders; + private readonly bool ignoreBondOrders; /// /// Make a bond partition refiner that takes bond-orders into account. diff --git a/NCDK/Groups/BondRefinable.cs b/NCDK/Groups/BondRefinable.cs index cbe0d639..9e7e8511 100644 --- a/NCDK/Groups/BondRefinable.cs +++ b/NCDK/Groups/BondRefinable.cs @@ -22,6 +22,7 @@ */ using System.Collections.Generic; +using System.Globalization; namespace NCDK.Groups { @@ -119,10 +120,10 @@ public Partition GetInitialPartition() { bool isArom = bond.IsAromatic; int orderNumber = isArom ? 5 : bond.Order.Numeric(); - boS = orderNumber.ToString(); + boS = orderNumber.ToString(NumberFormatInfo.InvariantInfo); } string bondString; - if (el0.CompareTo(el1) < 0) + if (string.CompareOrdinal(el0, el1) < 0) { bondString = el0 + boS + el1; } @@ -180,7 +181,7 @@ private void SetupConnectionTable(IAtomContainer atomContainer) { bool isArom = bond.IsAromatic; int orderNumber = isArom ? 5 : bond.Order.Numeric(); - boS = orderNumber.ToString(); + boS = orderNumber.ToString(NumberFormatInfo.InvariantInfo); } string bondString; if (a0 < a1) diff --git a/NCDK/Groups/IntegerInvariant.cs b/NCDK/Groups/IntegerInvariant.cs index d0da6997..c016700f 100644 --- a/NCDK/Groups/IntegerInvariant.cs +++ b/NCDK/Groups/IntegerInvariant.cs @@ -20,6 +20,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System.Globalization; + namespace NCDK.Groups { // @author maclean @@ -51,7 +53,7 @@ public override bool Equals(object other) public override string ToString() { - return value.ToString(); + return value.ToString(NumberFormatInfo.InvariantInfo); } } } diff --git a/NCDK/Groups/Partition.cs b/NCDK/Groups/Partition.cs index c2d75009..c8f1cafd 100644 --- a/NCDK/Groups/Partition.cs +++ b/NCDK/Groups/Partition.cs @@ -25,6 +25,7 @@ using NCDK.Common.Collections; using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; @@ -492,7 +493,7 @@ public static Partition FromString(string strForm) } else if (c == ',') { - int element = int.Parse(strForm.Substring(numStart, index - numStart)); + int element = int.Parse(strForm.Substring(numStart, index - numStart), NumberFormatInfo.InvariantInfo); if (currentCell == -1) { p.AddCell(element); @@ -506,7 +507,7 @@ public static Partition FromString(string strForm) } else if (c == '|') { - int element = int.Parse(strForm.Substring(numStart, index - numStart)); + int element = int.Parse(strForm.Substring(numStart, index - numStart), NumberFormatInfo.InvariantInfo); if (currentCell == -1) { p.AddCell(element); @@ -522,7 +523,7 @@ public static Partition FromString(string strForm) } index++; } - int lastElement = int.Parse(strForm.Substring(numStart, endIndex + 1 - numStart)); + int lastElement = int.Parse(strForm.Substring(numStart, endIndex + 1 - numStart), NumberFormatInfo.InvariantInfo); p.AddToCell(currentCell, lastElement); return p; } diff --git a/NCDK/Groups/PartitionRefinement.cs b/NCDK/Groups/PartitionRefinement.cs index 94e2e619..ee7b42a2 100644 --- a/NCDK/Groups/PartitionRefinement.cs +++ b/NCDK/Groups/PartitionRefinement.cs @@ -9,7 +9,7 @@ /// switches for ignoring atom types and/or bond orders. /// // @author maclean - public class PartitionRefinement + public static class PartitionRefinement { /// a builder that makes atom refiners public static AtomRefinerBuilder ForAtoms() @@ -17,49 +17,50 @@ public static AtomRefinerBuilder ForAtoms() return new AtomRefinerBuilder(); } - public class AtomRefinerBuilder + /// a builder that makes bond refiners + public static BondRefinerBuilder ForBonds() { - private bool ignoreAtomTypes; - private bool ignoreBondOrders; + return new BondRefinerBuilder(); + } - public AtomRefinerBuilder IgnoringAtomTypes() - { - this.ignoreAtomTypes = true; - return this; - } + } - public AtomRefinerBuilder IgnoringBondOrders() - { - this.ignoreBondOrders = true; - return this; - } + public class AtomRefinerBuilder + { + private bool ignoreAtomTypes; + private bool ignoreBondOrders; - public IAtomContainerDiscretePartitionRefiner Create() - { - return new AtomDiscretePartitionRefiner(ignoreAtomTypes, ignoreBondOrders); - } + public AtomRefinerBuilder IgnoringAtomTypes() + { + this.ignoreAtomTypes = true; + return this; } - /// a builder that makes bond refiners - public BondRefinerBuilder ForBonds() + public AtomRefinerBuilder IgnoringBondOrders() { - return new BondRefinerBuilder(); + this.ignoreBondOrders = true; + return this; } - public class BondRefinerBuilder + public IAtomContainerDiscretePartitionRefiner Create() { - private bool ignoreBondOrders; + return new AtomDiscretePartitionRefiner(ignoreAtomTypes, ignoreBondOrders); + } + } - public BondRefinerBuilder IgnoringBondOrders() - { - this.ignoreBondOrders = true; - return this; - } + public class BondRefinerBuilder + { + private bool ignoreBondOrders; - public IAtomContainerDiscretePartitionRefiner Create() - { - return new BondDiscretePartitionRefiner(ignoreBondOrders); - } + public BondRefinerBuilder IgnoringBondOrders() + { + this.ignoreBondOrders = true; + return this; + } + + public IAtomContainerDiscretePartitionRefiner Create() + { + return new BondDiscretePartitionRefiner(ignoreBondOrders); } } } diff --git a/NCDK/Groups/Permutation.cs b/NCDK/Groups/Permutation.cs index 2419da44..3dd244f5 100644 --- a/NCDK/Groups/Permutation.cs +++ b/NCDK/Groups/Permutation.cs @@ -38,16 +38,18 @@ namespace NCDK.Groups // @cdk.module group public sealed class Permutation : IReadOnlyList { + private readonly int[] values; + /// /// Constructs an identity permutation with elements. /// /// the number of elements in the permutation public Permutation(int size) { - this.Values = new int[size]; + this.values = new int[size]; for (int i = 0; i < size; i++) { - this.Values[i] = i; + this.values[i] = i; } } @@ -57,7 +59,7 @@ public Permutation(int size) /// the elements of the permutation public Permutation(params int[] values) { - this.Values = values; + this.values = values; } /// @@ -66,20 +68,22 @@ public Permutation(params int[] values) /// the other permutation public Permutation(Permutation other) { - this.Values = (int[])other.Values.Clone(); + this.values = (int[])other.values.Clone(); } public override bool Equals(object other) { - if (this == other) return true; - if (other == null || GetType() != other.GetType()) return false; + if (this == other) + return true; + if (other == null || GetType() != other.GetType()) + return false; - return Arrays.AreEqual(Values, ((Permutation)other).Values); + return Arrays.AreEqual(values, ((Permutation)other).values); } public override int GetHashCode() { - return Arrays.GetHashCode(Values); + return Arrays.GetHashCode(values); } /// @@ -88,9 +92,9 @@ public override int GetHashCode() /// if for all i, p[i] = i public bool IsIdentity() { - for (int i = 0; i < this.Values.Length; i++) + for (int i = 0; i < this.values.Length; i++) { - if (this.Values[i] != i) + if (this.values[i] != i) { return false; } @@ -101,7 +105,7 @@ public bool IsIdentity() /// /// The number of elements in the permutation. /// - public int Count => this.Values.Length; + public int Count => this.values.Length; /// /// The permutation value @@ -109,20 +113,14 @@ public bool IsIdentity() /// Index public int this[int index] { - get - { - return this.Values[index]; - } - set - { - this.Values[index] = value; - } + get => this.values[index]; + set => this.values[index] = value; } /// /// All the values as an array. /// - public int[] Values { get; private set; } + public IReadOnlyList Values => values; /// /// Find an r such that this[r] != other[r]. @@ -132,7 +130,7 @@ public int this[int index] public int FirstIndexOfDifference(Permutation other) { int r = 0; - while ((r < Values.Length) && Values[r] == other[r]) + while ((r < values.Length) && values[r] == other[r]) { r++; } @@ -144,17 +142,14 @@ public int FirstIndexOfDifference(Permutation other) /// /// any element in the orbit /// the list of elements reachable in this permutation - public IList GetOrbit(int element) + public IReadOnlyCollection GetOrbit(int element) { - var orbit = new List - { - element - }; - int i = Values[element]; - while (i != element && orbit.Count < Values.Length) + var orbit = new List { element }; + int i = values[element]; + while (i != element && orbit.Count < values.Length) { orbit.Add(i); - i = Values[i]; + i = values[i]; } return orbit; } @@ -166,12 +161,12 @@ public IList GetOrbit(int element) /// if the permutations are of different size public void SetTo(Permutation other) { - if (this.Values.Length != other.Values.Length) + if (this.values.Length != other.values.Length) throw new ArgumentException("permutations are different size"); - for (int i = 0; i < this.Values.Length; i++) + for (int i = 0; i < this.values.Length; i++) { - this.Values[i] = other.Values[i]; + this.values[i] = other.values[i]; } } @@ -182,10 +177,10 @@ public void SetTo(Permutation other) /// a new permutation with the result of multiplying the permutations public Permutation Multiply(Permutation other) { - Permutation newPermutation = new Permutation(Values.Length); - for (int i = 0; i < Values.Length; i++) + Permutation newPermutation = new Permutation(values.Length); + for (int i = 0; i < values.Length; i++) { - newPermutation.Values[i] = this.Values[other.Values[i]]; + newPermutation.values[i] = this.values[other.values[i]]; } return newPermutation; } @@ -196,10 +191,10 @@ public Permutation Multiply(Permutation other) /// the inverse of this permutation public Permutation Invert() { - Permutation inversion = new Permutation(Values.Length); - for (int i = 0; i < Values.Length; i++) + Permutation inversion = new Permutation(values.Length); + for (int i = 0; i < values.Length; i++) { - inversion.Values[this.Values[i]] = i; + inversion.values[this.values[i]] = i; } return inversion; } @@ -210,7 +205,7 @@ public Permutation Invert() /// the cycle form of the permutation as a string public string ToCycleString() { - int n = this.Values.Length; + int n = this.values.Length; bool[] p = new bool[n]; Arrays.Fill(p, true); @@ -224,10 +219,10 @@ public string ToCycleString() sb.Append(i); p[i] = false; j = i; - while (p[Values[j]]) + while (p[values[j]]) { sb.Append(", "); - j = Values[j]; + j = values[j]; sb.Append(j); p[j] = false; } @@ -239,12 +234,12 @@ public string ToCycleString() public IEnumerator GetEnumerator() { - return ((IEnumerable)Values).GetEnumerator(); + return ((IEnumerable)values).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return Values.GetEnumerator(); + return values.GetEnumerator(); } } } diff --git a/NCDK/Groups/PermutationGroup.cs b/NCDK/Groups/PermutationGroup.cs index 9fbfde54..fd5f0d57 100644 --- a/NCDK/Groups/PermutationGroup.cs +++ b/NCDK/Groups/PermutationGroup.cs @@ -68,25 +68,6 @@ namespace NCDK.Groups // @cdk.module group public class PermutationGroup { - /// - /// An interface for use with the apply method, which runs through all the - /// permutations in this group. - /// - public interface IBacktracker - { - /// - /// Do something to the permutation - /// - /// a permutation in the full group - void ApplyTo(Permutation p); - - /// - /// Check to see if the backtracker is finished. - /// - /// true if complete - bool IsFinished(); - } - /// /// The compact list of permutations that make up this group /// @@ -222,9 +203,9 @@ public long Order() /// /// the index of the transversal /// a list of permutations - public IList GetLeftTransversal(int index) + public IReadOnlyCollection GetLeftTransversal(int index) { - List traversal = new List(); + var traversal = new List(); for (int subIndex = 0; subIndex < size; subIndex++) { if (permutations[index][subIndex] != null) @@ -240,11 +221,11 @@ public IList GetLeftTransversal(int index) /// /// the subgroup to use for the transversal /// a list of permutations - public IList Transversal(PermutationGroup subgroup) + public IReadOnlyCollection Transversal(PermutationGroup subgroup) { long m = this.Order() / subgroup.Order(); var results = new List(); - IBacktracker transversalBacktracker = new TransversalBacktracker(this, subgroup, m, results); + var transversalBacktracker = new TransversalBacktracker(this, subgroup, m, results); this.Apply(transversalBacktracker); return results; } @@ -253,7 +234,7 @@ class TransversalBacktracker : IBacktracker { PermutationGroup parent; PermutationGroup subgroup; - long m; + private readonly long m; IList results; private bool finished = false; @@ -311,7 +292,7 @@ private void Backtrack(int l, Permutation g, IBacktracker backtracker) { for (int i = 0; i < size; i++) { - Permutation h = this.permutations[l][i]; + var h = this.permutations[l][i]; if (h != null) { Backtrack(l + 1, g.Multiply(h), backtracker); @@ -324,10 +305,10 @@ private void Backtrack(int l, Permutation g, IBacktracker backtracker) /// Generate the whole group from the compact list of permutations. /// /// a list of permutations - public IList GenerateAll() + public IReadOnlyCollection GenerateAll() { var permutations = new List(); - IBacktracker counter = new CounterBacktracker(permutations); + var counter = new CounterBacktracker(permutations); this.Apply(counter); return permutations; } @@ -358,7 +339,7 @@ public bool IsFinished() /// the new base for the group public void ChangeBase(Permutation newBase) { - PermutationGroup h = new PermutationGroup(newBase); + var h = new PermutationGroup(newBase); int firstDiffIndex = basePermutation.FirstIndexOfDifference(newBase); @@ -448,7 +429,7 @@ public int Test(Permutation permutation) public override string ToString() { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append("Base = ").Append(basePermutation).Append('\n'); for (int i = 0; i < size; i++) { @@ -462,4 +443,23 @@ public override string ToString() return sb.ToString(); } } + + /// + /// An interface for use with the apply method, which runs through all the + /// permutations in this group. + /// + public interface IBacktracker + { + /// + /// Do something to the permutation + /// + /// a permutation in the full group + void ApplyTo(Permutation p); + + /// + /// Check to see if the backtracker is finished. + /// + /// true if complete + bool IsFinished(); + } } diff --git a/NCDK/Hash/AbstractAtomHashGenerator.cs b/NCDK/Hash/AbstractAtomHashGenerator.cs index 5bd3ac30..8fef6ec4 100644 --- a/NCDK/Hash/AbstractAtomHashGenerator.cs +++ b/NCDK/Hash/AbstractAtomHashGenerator.cs @@ -24,6 +24,7 @@ using NCDK.Hash.Stereo; using System.Collections; +using System.Collections.Generic; namespace NCDK.Hash { @@ -36,14 +37,10 @@ namespace NCDK.Hash // @cdk.module hash internal abstract class AbstractAtomHashGenerator : AbstractHashGenerator, IAtomHashGenerator { - /// - /// Empty BitArray for use when the 'suppressed' atoms are ignored. - /// - readonly BitArray EmptyBitSet = new BitArray(0); - public AbstractAtomHashGenerator(Pseudorandom pseudorandom) - : base(pseudorandom) - { } + : base(pseudorandom) + { + } public abstract long[] Generate(IAtomContainer container); diff --git a/NCDK/Hash/AbstractHashGenerator.cs b/NCDK/Hash/AbstractHashGenerator.cs index 8da44739..b61cfe64 100644 --- a/NCDK/Hash/AbstractHashGenerator.cs +++ b/NCDK/Hash/AbstractHashGenerator.cs @@ -47,7 +47,7 @@ internal class AbstractHashGenerator /// the pseudorandom number generator was null public AbstractHashGenerator(Pseudorandom pseudorandom) { - this.pseudorandom = pseudorandom ?? throw new ArgumentNullException("null pseduorandom number generator provided"); + this.pseudorandom = pseudorandom ?? throw new ArgumentNullException(nameof(pseudorandom), "null pseduorandom number generator provided"); } /// @@ -122,13 +122,14 @@ public long Distribute(long value) } /// - /// Convert an IAtomContainer to an adjacency list. + /// Convert an to an adjacency list. /// /// the container to convert /// adjacency list representation public static int[][] ToAdjList(IAtomContainer container) { - if (container == null) throw new ArgumentException("atom container was null"); + if (container == null) + throw new ArgumentNullException(nameof(container), "atom container was null"); int n = container.Atoms.Count; int[][] graph = Arrays.CreateJagged(n, 16); @@ -136,7 +137,6 @@ public static int[][] ToAdjList(IAtomContainer container) foreach (var bond in container.Bonds) { - int v = container.Atoms.IndexOf(bond.Begin); int w = container.Atoms.IndexOf(bond.End); diff --git a/NCDK/Hash/AtomSuppression.cs b/NCDK/Hash/AtomSuppression.cs index b200c071..af57ef7b 100644 --- a/NCDK/Hash/AtomSuppression.cs +++ b/NCDK/Hash/AtomSuppression.cs @@ -22,6 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ +using System; using System.Collections; namespace NCDK.Hash @@ -63,7 +64,7 @@ public override Suppressed Suppress(IAtomContainer container) for (int i = 0; i < container.Atoms.Count; i++) { IAtom atom = container.Atoms[i]; - hydrogens.Set(i, "H".Equals(atom.Symbol)); + hydrogens.Set(i, "H".Equals(atom.Symbol, StringComparison.Ordinal)); } return Suppressed.FromBitSet(hydrogens); } diff --git a/NCDK/Hash/BasicAtomEncoder.tt b/NCDK/Hash/BasicAtomEncoder.tt index 3ac2ce59..3c5523da 100644 --- a/NCDK/Hash/BasicAtomEncoder.tt +++ b/NCDK/Hash/BasicAtomEncoder.tt @@ -43,7 +43,7 @@ namespace NCDK.Hash // @author John May // @cdk.module hash // @cdk.githash - public + public <# GenerateEnumBody( "BasicAtomEncoder", @@ -61,16 +61,16 @@ namespace NCDK.Hash ); #> private delegate int EncodeDelegate(IAtom atom, IAtomContainer container); - private static EncodeDelegate[] listOnEncode; + private static EncodeDelegate[] listOnEncode = MakeListOnEncode(); public int Encode(IAtom atom, IAtomContainer container) { return listOnEncode[Ordinal](atom, container); } - static BasicAtomEncoder() + private static EncodeDelegate[] MakeListOnEncode() { - listOnEncode = new EncodeDelegate[values.Length]; + var listOnEncode = new EncodeDelegate[values.Length]; listOnEncode[O.AtomicNumber] = (atom, container) => atom.AtomicNumber ?? 32451169; listOnEncode[O.MassNumber] = (atom, container) => atom.MassNumber ?? 32451179; listOnEncode[O.FormalCharge] = (atom, container) => atom.FormalCharge ?? 32451193; @@ -82,8 +82,9 @@ namespace NCDK.Hash return !hybridization.IsUnset() ? (int)hybridization : 32451301; }; listOnEncode[O.FreeRadicals] = (atom, container) => container.GetConnectedSingleElectrons(atom).Count(); + return listOnEncode; } <# - EndGenerateEnumBody(); + EndGenerateEnumBody(); #> } diff --git a/NCDK/Hash/BasicAtomEncoder.tt.cs b/NCDK/Hash/BasicAtomEncoder.tt.cs index b41f4298..48424ec3 100644 --- a/NCDK/Hash/BasicAtomEncoder.tt.cs +++ b/NCDK/Hash/BasicAtomEncoder.tt.cs @@ -44,7 +44,7 @@ namespace NCDK.Hash // @author John May // @cdk.module hash // @cdk.githash - public + public partial class BasicAtomEncoder : System.IComparable, System.IComparable , IAtomEncoder { @@ -95,15 +95,25 @@ private BasicAtomEncoder(int ordinal) } public static explicit operator BasicAtomEncoder(int ordinal) + { + return ToBasicAtomEncoder(ordinal); + } + + public static BasicAtomEncoder ToBasicAtomEncoder(int ordinal) { if (!(0 <= ordinal && ordinal < values.Length)) - throw new System.ArgumentOutOfRangeException(); + throw new System.ArgumentOutOfRangeException(nameof(ordinal)); return values[ordinal]; } - public static explicit operator int(BasicAtomEncoder obj) + public static explicit operator int(BasicAtomEncoder o) + { + return ToInt32(o); + } + + public static int ToInt32(BasicAtomEncoder o) { - return obj.Ordinal; + return o.Ordinal; } /// @@ -142,7 +152,7 @@ public static explicit operator int(BasicAtomEncoder obj) FreeRadicals, }; - public static BasicAtomEncoder[] Values => values; + public static System.Collections.Generic.IReadOnlyList Values => values; public static bool operator==(BasicAtomEncoder a, BasicAtomEncoder b) @@ -186,16 +196,16 @@ public int CompareTo(BasicAtomEncoder o) return (Ordinal).CompareTo(o.Ordinal); } private delegate int EncodeDelegate(IAtom atom, IAtomContainer container); - private static EncodeDelegate[] listOnEncode; + private static EncodeDelegate[] listOnEncode = MakeListOnEncode(); public int Encode(IAtom atom, IAtomContainer container) { return listOnEncode[Ordinal](atom, container); } - static BasicAtomEncoder() + private static EncodeDelegate[] MakeListOnEncode() { - listOnEncode = new EncodeDelegate[values.Length]; + var listOnEncode = new EncodeDelegate[values.Length]; listOnEncode[O.AtomicNumber] = (atom, container) => atom.AtomicNumber ?? 32451169; listOnEncode[O.MassNumber] = (atom, container) => atom.MassNumber ?? 32451179; listOnEncode[O.FormalCharge] = (atom, container) => atom.FormalCharge ?? 32451193; @@ -207,6 +217,7 @@ static BasicAtomEncoder() return !hybridization.IsUnset() ? (int)hybridization : 32451301; }; listOnEncode[O.FreeRadicals] = (atom, container) => container.GetConnectedSingleElectrons(atom).Count(); + return listOnEncode; } } } diff --git a/NCDK/Hash/BasicAtomHashGenerator.cs b/NCDK/Hash/BasicAtomHashGenerator.cs index 6cf369b2..e6808908 100644 --- a/NCDK/Hash/BasicAtomHashGenerator.cs +++ b/NCDK/Hash/BasicAtomHashGenerator.cs @@ -24,6 +24,7 @@ using NCDK.Hash.Stereo; using System; +using System.Collections.Generic; namespace NCDK.Hash { @@ -90,8 +91,9 @@ public BasicAtomHashGenerator(IAtomHashGenerator seedGenerator, Pseudorandom pse IStereoEncoderFactory factory, int depth) : base(pseudorandom) { - if (depth < 0) throw new ArgumentOutOfRangeException("depth cannot be less then 0"); - this.seedGenerator = seedGenerator ?? throw new ArgumentNullException("seed generator cannot be null"); + if (depth < 0) + throw new ArgumentOutOfRangeException(nameof(depth), "depth cannot be less then 0"); + this.seedGenerator = seedGenerator ?? throw new ArgumentNullException(nameof(seedGenerator), "seed generator cannot be null"); this.factory = factory; this.depth = depth; } @@ -112,7 +114,7 @@ public BasicAtomHashGenerator(IAtomHashGenerator seedGenerator, Pseudorandom pse public override long[] Generate(IAtomContainer container) { - int[][] graph = ToAdjList(container); + var graph = ToAdjList(container); return Generate(seedGenerator.Generate(container), factory.Create(container, graph), graph, Suppressed.None); } @@ -129,11 +131,11 @@ public override long[] Generate(IAtomContainer container) public override long[] Generate(long[] current, IStereoEncoder encoder, int[][] graph, Suppressed suppressed) { int n = graph.Length; - long[] next = Copy(current); + var next = Copy(current); // buffers for including adjacent invariants - long[] unique = new long[n]; - long[] included = new long[n]; + var unique = new long[n]; + var included = new long[n]; while (encoder.Encode(current, next)) { diff --git a/NCDK/Hash/BasicMoleculeHashGenerator.cs b/NCDK/Hash/BasicMoleculeHashGenerator.cs index ce4499e0..e936af85 100644 --- a/NCDK/Hash/BasicMoleculeHashGenerator.cs +++ b/NCDK/Hash/BasicMoleculeHashGenerator.cs @@ -70,8 +70,8 @@ public BasicMoleculeHashGenerator(IAtomHashGenerator generator) /// no atom hash generator or pseudorandom number generator provided internal BasicMoleculeHashGenerator(IAtomHashGenerator generator, Pseudorandom pseudorandom) { - this.generator = generator ?? throw new ArgumentNullException("no AtomHashGenerator provided"); - this.pseudorandom = pseudorandom ?? throw new ArgumentNullException("no Pseudorandom number generator provided"); + this.generator = generator ?? throw new ArgumentNullException(nameof(generator), "no AtomHashGenerator provided"); + this.pseudorandom = pseudorandom ?? throw new ArgumentNullException(nameof(pseudorandom), "no Pseudorandom number generator provided"); } public long Generate(IAtomContainer container) diff --git a/NCDK/Hash/ConjugatedAtomEncoder.cs b/NCDK/Hash/ConjugatedAtomEncoder.cs index 64f9fd03..6222ccde 100644 --- a/NCDK/Hash/ConjugatedAtomEncoder.cs +++ b/NCDK/Hash/ConjugatedAtomEncoder.cs @@ -24,7 +24,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; namespace NCDK.Hash { @@ -55,7 +54,7 @@ namespace NCDK.Hash internal sealed class ConjugatedAtomEncoder : IAtomEncoder { /* ordered list of encoders */ - private readonly IList encoders; + private readonly List encoders; /// /// Create a new conjugated encoder for the specified list of atom encoders. @@ -64,11 +63,13 @@ internal sealed class ConjugatedAtomEncoder : IAtomEncoder /// non-empty list of encoders /// the list of encoders was null /// the list of encoders was empty - public ConjugatedAtomEncoder(IList encoders) + public ConjugatedAtomEncoder(IEnumerable encoders) { - if (encoders == null) throw new ArgumentNullException("null list of encoders"); - if (encoders.Count == 0) throw new ArgumentException("no encoders provided"); - this.encoders = new ReadOnlyCollection(new List(encoders)); + if (encoders == null) + throw new ArgumentNullException(nameof(encoders), "null list of encoders"); + this.encoders = new List(encoders); + if (this.encoders.Count == 0) + throw new ArgumentException("no encoders provided"); } public int Encode(IAtom atom, IAtomContainer container) @@ -93,13 +94,12 @@ public int Encode(IAtom atom, IAtomContainer container) /// either argument was null public static IAtomEncoder Create(IAtomEncoder encoder, params IAtomEncoder[] encoders) { - if (encoder == null || encoders == null) throw new ArgumentNullException("null encoders provided"); - List tmp = new List(encoders.Length + 1) - { - encoder - }; - foreach (var e in encoders) - tmp.Add(e); + if (encoder == null) + throw new ArgumentNullException(nameof(encoder), "null encoder provided"); + if (encoders == null) + throw new ArgumentNullException(nameof(encoders), "null encoders provided"); + var tmp = new List(encoders.Length + 1) { encoder }; + tmp.AddRange(encoders); return new ConjugatedAtomEncoder(tmp); } } diff --git a/NCDK/Hash/HashGeneratorMaker.cs b/NCDK/Hash/HashGeneratorMaker.cs index 25a7f8a6..ab63fc05 100644 --- a/NCDK/Hash/HashGeneratorMaker.cs +++ b/NCDK/Hash/HashGeneratorMaker.cs @@ -236,7 +236,8 @@ internal HashGeneratorMaker PerturbWith(EquivalentSetFinder equivSetFinder) /// no encoder provided public HashGeneratorMaker Encode(IAtomEncoder encoder) { - if (encoder == null) throw new ArgumentNullException("no encoder provided"); + if (encoder == null) + throw new ArgumentNullException(nameof(encoder), "no encoder provided"); customEncoders.Add(encoder); return this; } @@ -271,7 +272,9 @@ private IStereoEncoderFactory MakeStereoEncoderFactory() /// /// instance of the generator /// no depth or encoders were configured +#pragma warning disable CA1822 // Mark members as static public IEnsembleHashGenerator Ensemble() +#pragma warning restore CA1822 // Mark members as static { throw new NotSupportedException("not yet supported"); } @@ -361,10 +364,9 @@ private sealed class ConjugatedEncoder : IStereoEncoder /// /// Create a new conjugated encoder from a left and right encoder. - /// + /// /// encoder /// encoder - /// public ConjugatedEncoder(IStereoEncoder left, IStereoEncoder right) { this.left = left; diff --git a/NCDK/Hash/IAtomHashGenerator.cs b/NCDK/Hash/IAtomHashGenerator.cs index 1bb28ea4..e57fb11a 100644 --- a/NCDK/Hash/IAtomHashGenerator.cs +++ b/NCDK/Hash/IAtomHashGenerator.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; + namespace NCDK.Hash { public interface IAtomHashGenerator diff --git a/NCDK/Hash/PerturbedAtomHashGenerator.cs b/NCDK/Hash/PerturbedAtomHashGenerator.cs index d807ae37..0b3725ec 100644 --- a/NCDK/Hash/PerturbedAtomHashGenerator.cs +++ b/NCDK/Hash/PerturbedAtomHashGenerator.cs @@ -95,14 +95,14 @@ public PerturbedAtomHashGenerator(SeedGenerator seeds, AbstractAtomHashGenerator { this.finder = finder; this.factory = factory; - this.simple = simple ?? throw new ArgumentNullException("no simple generator provided"); - this.seeds = seeds ?? throw new ArgumentNullException("no seed generator provided"); - this.suppression = suppression ?? throw new ArgumentNullException("no suppression provided, use AtomSuppression.None()"); + this.simple = simple ?? throw new ArgumentNullException(nameof(simple), "no simple generator provided"); + this.seeds = seeds ?? throw new ArgumentNullException(nameof(seeds), "no seed generator provided"); + this.suppression = suppression ?? throw new ArgumentNullException(nameof(suppression), "no suppression provided, use AtomSuppression.None()"); } public long[] Generate(IAtomContainer container) { - int[][] graph = ToAdjList(container); + var graph = ToAdjList(container); return Generate(container, seeds.Generate(container), factory.Create(container, graph), graph); } diff --git a/NCDK/Hash/SeedGenerator.cs b/NCDK/Hash/SeedGenerator.cs index 7d0f1e26..7c7231f0 100644 --- a/NCDK/Hash/SeedGenerator.cs +++ b/NCDK/Hash/SeedGenerator.cs @@ -87,8 +87,8 @@ public SeedGenerator(IAtomEncoder encoder, AtomSuppression suppression) public SeedGenerator(IAtomEncoder encoder, Pseudorandom pseudorandom, AtomSuppression suppression) : base(pseudorandom) { - this.encoder = encoder ?? throw new ArgumentNullException("encoder cannot be null"); - this.suppression = suppression ?? throw new ArgumentNullException("suppression cannot be null, use AtomSuppression.Unsuppressed()"); + this.encoder = encoder ?? throw new ArgumentNullException(nameof(encoder), "encoder cannot be null"); + this.suppression = suppression ?? throw new ArgumentNullException(nameof(suppression), "suppression cannot be null, use AtomSuppression.Unsuppressed()"); } public long[] Generate(IAtomContainer container) diff --git a/NCDK/Hash/Stereo/BasicPermutationParity.cs b/NCDK/Hash/Stereo/BasicPermutationParity.cs index 8de14d6b..f43df2a7 100644 --- a/NCDK/Hash/Stereo/BasicPermutationParity.cs +++ b/NCDK/Hash/Stereo/BasicPermutationParity.cs @@ -45,7 +45,8 @@ internal sealed class BasicPermutationParity : PermutationParity /// less then two indices provided public BasicPermutationParity(int[] indices) { - if (indices == null) throw new ArgumentNullException("no indices[] provided"); + if (indices == null) + throw new ArgumentNullException(nameof(indices), "no indices[] provided"); if (indices.Length < 2) throw new ArgumentException($"at least 2 incides required, use {PermutationParity.Identity} for single neighbors"); this.indices = indices; diff --git a/NCDK/Hash/Stereo/GeometricCumulativeDoubleBondFactory.cs b/NCDK/Hash/Stereo/GeometricCumulativeDoubleBondFactory.cs index 40853f02..e129cfd2 100644 --- a/NCDK/Hash/Stereo/GeometricCumulativeDoubleBondFactory.cs +++ b/NCDK/Hash/Stereo/GeometricCumulativeDoubleBondFactory.cs @@ -376,7 +376,7 @@ private static bool IsDoubleBond(IBond bond) /// private class BondMap { - public IDictionary> bonds; + public Dictionary> bonds; /// /// Create new bond map for the specified number of atoms. @@ -395,7 +395,7 @@ public BondMap(int n) public IEnumerable GetBonds(IAtom a) { if (!bonds.TryGetValue(a, out List bs)) - return new IBond[0]; + return System.Array.Empty(); return bs; } diff --git a/NCDK/Hash/Stereo/MultiStereoEncoder.cs b/NCDK/Hash/Stereo/MultiStereoEncoder.cs index 30a2c4fe..8191369c 100644 --- a/NCDK/Hash/Stereo/MultiStereoEncoder.cs +++ b/NCDK/Hash/Stereo/MultiStereoEncoder.cs @@ -26,7 +26,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.ObjectModel; namespace NCDK.Hash.Stereo { @@ -43,15 +42,16 @@ internal sealed class MultiStereoEncoder : IStereoEncoder private readonly BitArray unconfigured; /* list of encoders */ - private readonly IList encoders; + private readonly IReadOnlyList encoders; /// /// Create a new multiple stereo encoder from a single list of encoders /// public MultiStereoEncoder(IList encoders) { - if (encoders.Count == 0) throw new ArgumentException("no stereo encoders provided"); - this.encoders = new ReadOnlyCollection(new List(encoders)); + if (encoders.Count == 0) + throw new ArgumentException("no stereo encoders provided"); + this.encoders = new List(encoders); this.unconfigured = new BitArray(encoders.Count); BitArrays.Flip(unconfigured, encoders.Count); } diff --git a/NCDK/Hash/Stereo/StereoEncoder.cs b/NCDK/Hash/Stereo/StereoEncoder.cs index e4e3ccd3..623d5199 100644 --- a/NCDK/Hash/Stereo/StereoEncoder.cs +++ b/NCDK/Hash/Stereo/StereoEncoder.cs @@ -36,12 +36,12 @@ public interface IStereoEncoder /// /// Encode one or more stereo elements based on the current invariants. If /// any stereo element are uncovered then the corresponding value in the - /// [] array is modified. + /// array is modified. /// /// current invariants - /// next invariants + /// next invariants /// whether any stereo configurations were encoded - bool Encode(long[] current, long[] next); + bool Encode(long[] current, long[] nextInvariants); /// /// Reset the stereo-encoders, any currently perceived configurations will be diff --git a/NCDK/Hash/Suppressed.cs b/NCDK/Hash/Suppressed.cs index 389e5002..e20de279 100644 --- a/NCDK/Hash/Suppressed.cs +++ b/NCDK/Hash/Suppressed.cs @@ -23,6 +23,7 @@ */ using NCDK.Common.Collections; +using System; using System.Collections; namespace NCDK.Hash @@ -59,7 +60,7 @@ private sealed class Empty : Suppressed { public override bool Contains(int i) => false; public override int Count => 0; - public override int[] ToArray() => new int[0]; + public override int[] ToArray() => Array.Empty(); } /// diff --git a/NCDK/Hash/SuppressedAtomHashGenerator.cs b/NCDK/Hash/SuppressedAtomHashGenerator.cs index b95384ab..87deee26 100644 --- a/NCDK/Hash/SuppressedAtomHashGenerator.cs +++ b/NCDK/Hash/SuppressedAtomHashGenerator.cs @@ -70,12 +70,14 @@ internal sealed class SuppressedAtomHashGenerator : AbstractAtomHashGenerator, I /// depth was less then 0 /// seed generator or pseudo random was null /// - public SuppressedAtomHashGenerator(IAtomHashGenerator seedGenerator, Pseudorandom pseudorandom, - IStereoEncoderFactory factory, AtomSuppression suppression, int depth) - : base(pseudorandom) + public SuppressedAtomHashGenerator( + IAtomHashGenerator seedGenerator, Pseudorandom pseudorandom, + IStereoEncoderFactory factory, AtomSuppression suppression, int depth) + : base(pseudorandom) { - if (depth < 0) throw new ArgumentOutOfRangeException("depth cannot be less then 0"); - this.seedGenerator = seedGenerator ?? throw new ArgumentNullException("seed generator cannot be null"); + if (depth < 0) + throw new ArgumentOutOfRangeException(nameof(depth), "depth cannot be less then 0"); + this.seedGenerator = seedGenerator ?? throw new ArgumentNullException(nameof(seedGenerator), "seed generator cannot be null"); this.factory = factory; this.suppression = suppression; this.depth = depth; @@ -95,7 +97,8 @@ public SuppressedAtomHashGenerator(IAtomHashGenerator seedGenerator, Pseudorando public SuppressedAtomHashGenerator(IAtomHashGenerator seedGenerator, Pseudorandom pseudorandom, AtomSuppression suppression, int depth) : this(seedGenerator, pseudorandom, StereoEncoderFactory.Empty, suppression, depth) - { } + { + } public override long[] Generate(IAtomContainer container) { diff --git a/NCDK/Hybridization.cs b/NCDK/Hybridization.cs index ea421eec..c016d24d 100644 --- a/NCDK/Hybridization.cs +++ b/NCDK/Hybridization.cs @@ -39,11 +39,11 @@ public enum Hybridization /// /// A geometry of neighboring atoms when an s orbital is hybridized with one p orbital. /// - SP1, + SP1, /// /// A geometry of neighboring atoms when an s orbital is hybridized with two p orbitals. /// - SP2, + SP2, /// /// A geometry of neighboring atoms when an s orbital is hybridized with three p orbitals. /// @@ -74,7 +74,7 @@ public enum Hybridization SP3D5, } - public static class HybridizationTools + public static class HybridizationTools { public static bool IsUnset(this Hybridization value) { @@ -86,31 +86,31 @@ internal static Hybridization ToHybridization(string value) if (string.IsNullOrWhiteSpace(value)) return Unset; - switch (value.ToLowerInvariant()) + switch (value.ToUpperInvariant()) { - case "s": + case "S": return S; - case "sp": + case "SP": return SP1; - case "sp1": + case "SP1": return SP1; - case "sp2": + case "SP2": return SP2; - case "sp3": - case "tetrahedral": + case "SP3": + case "TETRAHEDRAL": return SP3; - case "planar": + case "PLANAR": return Planar3; - case "sp3d1": + case "SP3D1": return SP3D1; - case "sp3d2": - case "octahedral": + case "SP3D2": + case "OCTAHEDRAL": return SP3D2; - case "sp3d3": + case "SP3D3": return SP3D3; - case "sp3d4": + case "SP3D4": return SP3D4; - case "sp3d5": + case "SP3D5": return SP3D5; default: break; diff --git a/NCDK/IAdductFormula.cs b/NCDK/IAdductFormula.cs index c87e8b48..586d9375 100644 --- a/NCDK/IAdductFormula.cs +++ b/NCDK/IAdductFormula.cs @@ -19,6 +19,8 @@ using System.Collections.Generic; +#pragma warning disable CA1710 // Identifiers should have correct suffix + namespace NCDK { /// @@ -55,7 +57,7 @@ public interface IAdductFormula /// The partial charge of this Adduct. If the charge /// has not been set the return value is double.NaN. /// - int? Charge { get; set; } + int? Charge { get; } /// /// True, if the AdductFormula contains the given IIsotope object. diff --git a/NCDK/IAtomContainer.cs b/NCDK/IAtomContainer.cs index 594caa0a..1ea14e92 100644 --- a/NCDK/IAtomContainer.cs +++ b/NCDK/IAtomContainer.cs @@ -78,7 +78,7 @@ public interface IAtomContainer /// /// A stereo element to this container. /// - ICollection> StereoElements { get; } + ICollection> StereoElements { get; } /// /// One or several of the bonds have raised (which may indicate aromaticity). diff --git a/NCDK/IAtomContainerSet.cs b/NCDK/IAtomContainerSet.cs index 23bc0bae..4b93e561 100644 --- a/NCDK/IAtomContainerSet.cs +++ b/NCDK/IAtomContainerSet.cs @@ -26,7 +26,7 @@ public interface IAtomContainerSet { } public interface IEnumerableChemObject - : IEnumerable, IChemObject + : IEnumerable, IChemObject where T: IChemObject { } diff --git a/NCDK/IBioPolymer.cs b/NCDK/IBioPolymer.cs index 33c5f61c..6436895f 100644 --- a/NCDK/IBioPolymer.cs +++ b/NCDK/IBioPolymer.cs @@ -69,7 +69,7 @@ public interface IBioPolymer /// Map containing the strands in the Polymer. /// /// containing the strands in the Polymer - IDictionary GetStrandMap(); + IReadOnlyDictionary GetStrandMap(); /// /// Retrieve a Monomer object by specifying its name. diff --git a/NCDK/IBond.cs b/NCDK/IBond.cs index 24b84127..0c98262e 100644 --- a/NCDK/IBond.cs +++ b/NCDK/IBond.cs @@ -59,7 +59,9 @@ public interface IBond /// The end (or second) atom of the bond. /// /// the end atom +#pragma warning disable CA1716 // Identifiers should not match keywords IAtom End { get; } +#pragma warning restore CA1716 // Identifiers should not match keywords int Index { get; } diff --git a/NCDK/IChemObject.cs b/NCDK/IChemObject.cs index 4b099731..7a1bacc9 100644 --- a/NCDK/IChemObject.cs +++ b/NCDK/IChemObject.cs @@ -33,9 +33,9 @@ public partial interface IChemObject /// /// Deep comparator of . /// - /// Object to compare with. - /// if all properties of this object equals to . - bool Compare(object obj); + /// Object to compare with. + /// if all properties of this object equals to . + bool Compare(object o); /// /// Identifier (ID) of this object. diff --git a/NCDK/IChemObjectBuilder.cs b/NCDK/IChemObjectBuilder.cs index fb7a39c9..782407ce 100644 --- a/NCDK/IChemObjectBuilder.cs +++ b/NCDK/IChemObjectBuilder.cs @@ -106,6 +106,6 @@ public interface IChemObjectBuilder ISingleElectron NewSingleElectron(); ISingleElectron NewSingleElectron(IAtom atom); IStrand NewStrand(); - ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IEnumerable ligandAtoms, TetrahedralStereo chirality); + ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligandAtoms, TetrahedralStereo chirality); } } diff --git a/NCDK/IChemObjectListener.cs b/NCDK/IChemObjectListener.cs index 4cee00f4..3f5ac75f 100644 --- a/NCDK/IChemObjectListener.cs +++ b/NCDK/IChemObjectListener.cs @@ -34,9 +34,9 @@ public interface IChemObjectListener { /// /// Called by objects to notify objects that implemented this interface - /// and registered with them as ChemObjectListeners. + /// and registered with them as s. /// - /// a ChemObjectChangeEvent object - void OnStateChanged(ChemObjectChangeEventArgs @event); + /// Event arguments + void OnStateChanged(ChemObjectChangeEventArgs eventArgs); } } diff --git a/NCDK/IHasProperties.tt b/NCDK/IHasProperties.tt index 25490fd8..a7a8f6d4 100644 --- a/NCDK/IHasProperties.tt +++ b/NCDK/IHasProperties.tt @@ -23,10 +23,10 @@ namespace NCDK /// Sets a property for a . /// /// An object description of the property (most likely a unique string) - /// An object with the property itself + /// An object with the property itself /// /// - void SetProperty(object description, object property); + void SetProperty(object description, object value); /// /// Set the properties of this object to the provided map (shallow copy). Any @@ -79,7 +79,7 @@ namespace NCDK /// /// The object's properties as an /// - IDictionary GetProperties(); + IReadOnlyDictionary GetProperties(); } } <# diff --git a/NCDK/IHasProperties.tt.cs b/NCDK/IHasProperties.tt.cs index 8918713c..ec2639d0 100644 --- a/NCDK/IHasProperties.tt.cs +++ b/NCDK/IHasProperties.tt.cs @@ -12,10 +12,10 @@ public partial interface IChemObject /// Sets a property for a . /// /// An object description of the property (most likely a unique string) - /// An object with the property itself + /// An object with the property itself /// /// - void SetProperty(object description, object property); + void SetProperty(object description, object value); /// /// Set the properties of this object to the provided map (shallow copy). Any @@ -68,7 +68,7 @@ public partial interface IChemObject /// /// The object's properties as an /// - IDictionary GetProperties(); + IReadOnlyDictionary GetProperties(); } } namespace NCDK @@ -81,10 +81,10 @@ public partial interface IMolecularFormula /// Sets a property for a . /// /// An object description of the property (most likely a unique string) - /// An object with the property itself + /// An object with the property itself /// /// - void SetProperty(object description, object property); + void SetProperty(object description, object value); /// /// Set the properties of this object to the provided map (shallow copy). Any @@ -137,6 +137,6 @@ public partial interface IMolecularFormula /// /// The object's properties as an /// - IDictionary GetProperties(); + IReadOnlyDictionary GetProperties(); } } diff --git a/NCDK/IMolecularFormula.cs b/NCDK/IMolecularFormula.cs index 40745e64..a1ffda3c 100644 --- a/NCDK/IMolecularFormula.cs +++ b/NCDK/IMolecularFormula.cs @@ -83,7 +83,7 @@ public partial interface IMolecularFormula : ICDKObject /// . /// /// The the number of different isotopes in this - int Count { get; } + int IsotopesCount { get; } /// /// , if the contains the given object. Not diff --git a/NCDK/IMolecularFormulaSet.cs b/NCDK/IMolecularFormulaSet.cs index 7b87891b..f8515b23 100644 --- a/NCDK/IMolecularFormulaSet.cs +++ b/NCDK/IMolecularFormulaSet.cs @@ -21,12 +21,6 @@ namespace NCDK { - /* - *

- * - - * - */ ///

/// Class defining a molecular formula object. It maintains a list of list . /// @@ -43,6 +37,7 @@ namespace NCDK // @cdk.created 2007-11-20 // @cdk.keyword molecular formula // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public interface IMolecularFormulaSet : ICDKObject, IList { diff --git a/NCDK/IO/CIFReader.cs b/NCDK/IO/CIFReader.cs index 332c2947..ee51b7c2 100644 --- a/NCDK/IO/CIFReader.cs +++ b/NCDK/IO/CIFReader.cs @@ -29,6 +29,7 @@ using System.Diagnostics; using System.IO; using System.Text; +using System.Globalization; namespace NCDK.IO { @@ -188,17 +189,17 @@ private IChemFile ReadChemFile(IChemFile file) command = line; } - Debug.WriteLine("command: " + command); + Debug.WriteLine($"command: {command}"); if (command.StartsWith("_cell", StringComparison.Ordinal)) { ProcessCellParameter(command, line); } - else if (command.Equals("loop_")) + else if (string.Equals(command, "loop_", StringComparison.Ordinal)) { line = ProcessLoopBlock(); continue; } - else if (command.Equals("_symmetry_space_group_name_H-M")) + else if (string.Equals(command, "_symmetry_space_group_name_H-M", StringComparison.Ordinal)) { string value = line.Substring(29).Trim(); crystal.SpaceGroup = value; @@ -213,11 +214,11 @@ private IChemFile ReadChemFile(IChemFile file) Debug.WriteLine("Skipping block content"); line = input.ReadLine(); if (line != null) line = line.Trim(); - while (!line.Equals(";")) + while (!string.Equals(line, ";", StringComparison.Ordinal)) { line = input.ReadLine(); if (line != null) line = line.Trim(); - Debug.WriteLine("Skipping block line: " + line); + Debug.WriteLine($"Skipping block line: {line}"); } line = input.ReadLine(); } @@ -235,37 +236,37 @@ private IChemFile ReadChemFile(IChemFile file) private void ProcessCellParameter(string command, string line) { command = command.Substring(6); // skip the "_cell." part - if (command.Equals("length_a")) + if (string.Equals(command, "length_a", StringComparison.Ordinal)) { string value = line.Substring(14).Trim(); a = ParseIntoDouble(value); PossiblySetCellParams(a, b, c, alpha, beta, gamma); } - else if (command.Equals("length_b")) + else if (string.Equals(command, "length_b", StringComparison.Ordinal)) { string value = line.Substring(14).Trim(); b = ParseIntoDouble(value); PossiblySetCellParams(a, b, c, alpha, beta, gamma); } - else if (command.Equals("length_c")) + else if (string.Equals(command, "length_c", StringComparison.Ordinal)) { string value = line.Substring(14).Trim(); c = ParseIntoDouble(value); PossiblySetCellParams(a, b, c, alpha, beta, gamma); } - else if (command.Equals("angle_alpha")) + else if (string.Equals(command, "angle_alpha", StringComparison.Ordinal)) { string value = line.Substring(17).Trim(); alpha = ParseIntoDouble(value); PossiblySetCellParams(a, b, c, alpha, beta, gamma); } - else if (command.Equals("angle_beta")) + else if (string.Equals(command, "angle_beta", StringComparison.Ordinal)) { string value = line.Substring(16).Trim(); beta = ParseIntoDouble(value); PossiblySetCellParams(a, b, c, alpha, beta, gamma); } - else if (command.Equals("angle_gamma")) + else if (string.Equals(command, "angle_gamma", StringComparison.Ordinal)) { string value = line.Substring(17).Trim(); gamma = ParseIntoDouble(value); @@ -322,8 +323,8 @@ private string SkipLoopBody(String line) while (line != null && line.Length > 0 && line[0] != '#' && line[0] != '_' && - !line.StartsWith("loop_") && - !line.StartsWith("data_")) + !line.StartsWith("loop_", StringComparison.Ordinal) && + !line.StartsWith("data_", StringComparison.Ordinal)) { line = input.ReadLine(); if (line != null) @@ -348,11 +349,11 @@ private string ProcessAtomLoopBlock(string firstLine) while (line != null && line[0] == '_') { headerCount++; - if (line.Equals("_atom_site_label") || line.Equals("_atom_site_label_atom_id")) + if (line.Equals("_atom_site_label", StringComparison.Ordinal) || line.Equals("_atom_site_label_atom_id", StringComparison.Ordinal)) { atomLabel = headerCount; hasParsableInformation = true; - Trace.TraceInformation("label found in col: " + atomLabel); + Trace.TraceInformation($"label found in col: {atomLabel}"); } else if (line.StartsWith("_atom_site_fract_x", StringComparison.Ordinal)) { @@ -372,25 +373,25 @@ private string ProcessAtomLoopBlock(string firstLine) hasParsableInformation = true; Trace.TraceInformation("frac z found in col: " + atomFractZ); } - else if (line.Equals("_atom_site.Cartn_x")) + else if (string.Equals(line, "_atom_site.Cartn_x", StringComparison.Ordinal)) { atomRealX = headerCount; hasParsableInformation = true; Trace.TraceInformation("cart x found in col: " + atomRealX); } - else if (line.Equals("_atom_site.Cartn_y")) + else if (string.Equals(line, "_atom_site.Cartn_y", StringComparison.Ordinal)) { atomRealY = headerCount; hasParsableInformation = true; Trace.TraceInformation("cart y found in col: " + atomRealY); } - else if (line.Equals("_atom_site.Cartn_z")) + else if (string.Equals(line, "_atom_site.Cartn_z", StringComparison.Ordinal)) { atomRealZ = headerCount; hasParsableInformation = true; Trace.TraceInformation("cart z found in col: " + atomRealZ); } - else if (line.Equals("_atom_site.type_symbol")) + else if (string.Equals(line, "_atom_site.type_symbol", StringComparison.Ordinal)) { atomSymbol = headerCount; hasParsableInformation = true; @@ -413,8 +414,8 @@ private string ProcessAtomLoopBlock(string firstLine) while (line != null && line.Length > 0 && line[0] != '#' && line[0] != '_' && - !line.StartsWith("loop_") && - !line.StartsWith("data_")) + !line.StartsWith("loop_", StringComparison.Ordinal) && + !line.StartsWith("data_", StringComparison.Ordinal)) { Debug.WriteLine("new row"); var tokenizer = Strings.Tokenize(line); @@ -495,7 +496,7 @@ private string ProcessAtomLoopBlock(string firstLine) { atom.FractionalPoint3D = frac; } - Debug.WriteLine("Adding atom: " + atom); + Debug.WriteLine($"Adding atom: {atom}"); crystal.Atoms.Add(atom); // look up next row @@ -509,7 +510,7 @@ private string ProcessAtomLoopBlock(string firstLine) /// /// Process double in the format: '.071(1)'. /// - private double ParseIntoDouble(string value) + private static double ParseIntoDouble(string value) { double returnVal = 0.0; if (value[0] == '.') value = "0" + value; @@ -520,7 +521,7 @@ private double ParseIntoDouble(string value) } try { - returnVal = double.Parse(value); + returnVal = double.Parse(value, NumberFormatInfo.InvariantInfo); } catch (Exception) { @@ -529,7 +530,7 @@ private double ParseIntoDouble(string value) return returnVal; } - private string ExtractFirstLetters(string value) + private static string ExtractFirstLetters(string value) { StringBuilder result = new StringBuilder(); for (int i = 0; i < value.Length; i++) diff --git a/NCDK/IO/CML/CDKConvention.cs b/NCDK/IO/CML/CDKConvention.cs index 0434b6a4..9c93387c 100644 --- a/NCDK/IO/CML/CDKConvention.cs +++ b/NCDK/IO/CML/CDKConvention.cs @@ -25,6 +25,7 @@ using NCDK.Tools.Manipulator; using System; using System.Diagnostics; +using System.Globalization; using System.Xml.Linq; namespace NCDK.IO.CML @@ -59,7 +60,7 @@ public override void StartElement(CMLStack xpath, XElement element) if (xpath.ToString().EndsWith("string/", StringComparison.Ordinal)) { var a_buildin = element.Attribute("buildin"); - if (a_buildin != null && a_buildin.Value.Equals("order")) + if (a_buildin != null && a_buildin.Value.Equals("order", StringComparison.Ordinal)) { isBond = true; } @@ -75,14 +76,14 @@ public override void CharacterData(CMLStack xpath, XElement element) string s = element.Value; if (isBond) { - Debug.WriteLine("CharData (bond): " + s); + Debug.WriteLine($"CharData (bond): {s}"); var st = Strings.Tokenize(s); foreach (var border in st) { Debug.WriteLine($"new bond order: {border}"); // assume cdk bond object has already started // cdo.SetObjectProperty("Bond", "order", border); - CurrentBond.Order = BondManipulator.CreateBondOrder(double.Parse(border)); + CurrentBond.Order = BondManipulator.CreateBondOrder(double.Parse(border, NumberFormatInfo.InvariantInfo)); } } else diff --git a/NCDK/IO/CML/CMLCoreModule.cs b/NCDK/IO/CML/CMLCoreModule.cs index f4c51784..b2e1c336 100644 --- a/NCDK/IO/CML/CMLCoreModule.cs +++ b/NCDK/IO/CML/CMLCoreModule.cs @@ -33,6 +33,7 @@ using NCDK.Numerics; using System.Xml.Linq; using NCDK.Dict; +using System.Globalization; namespace NCDK.IO.CML { @@ -48,78 +49,77 @@ namespace NCDK.IO.CML public class CMLCoreModule : ICMLModule { protected const string SYSTEMID = "CML-1999-05-15"; - // protected IChemicalDocumentObject cdo; // data model to store things into - protected IChemFile CurrentChemFile{ get; set; } - - protected IAtomContainer CurrentMolecule{ get; set; } - protected IChemObjectSet CurrentMoleculeSet{ get; set; } - protected IChemModel CurrentChemModel{ get; set; } - protected IChemSequence CurrentChemSequence{ get; set; } - protected IReactionSet CurrentReactionSet{ get; set; } - protected IReaction CurrentReaction{ get; set; } - protected IAtom CurrentAtom{ get; set; } - protected IBond CurrentBond{ get; set; } - protected IStrand CurrentStrand{ get; set; } - protected IMonomer CurrentMonomer{ get; set; } - protected IDictionary AtomEnumeration{ get; set; } - protected IList MoleculeCustomProperty{ get; set; } + protected IChemFile CurrentChemFile { get; set; } + + protected IAtomContainer CurrentMolecule { get; set; } + protected IChemObjectSet CurrentMoleculeSet { get; set; } + protected IChemModel CurrentChemModel { get; set; } + protected IChemSequence CurrentChemSequence { get; set; } + protected IReactionSet CurrentReactionSet { get; set; } + protected IReaction CurrentReaction { get; set; } + protected IAtom CurrentAtom { get; set; } + protected IBond CurrentBond { get; set; } + protected IStrand CurrentStrand { get; set; } + protected IMonomer CurrentMonomer { get; set; } + protected IDictionary AtomEnumeration { get; set; } + protected IList MoleculeCustomProperty { get; set; } // helper fields - protected int FormulaCounter{ get; set; } - protected int AtomCounter{ get; set; } - protected IList ElSym{ get; set; } - protected IList ElTitles{ get; set; } - protected IList ElId{ get; set; } - protected IList Formula{ get; set; } - protected IList FormalCharges{ get; set; } - protected IList PartialCharges{ get; set; } - protected IList Isotope{ get; set; } - protected IList AtomicNumbers{ get; set; } - protected IList ExactMasses{ get; set; } - protected IList X3{ get; set; } - protected IList Y3{ get; set; } - protected IList Z3{ get; set; } - protected IList X2{ get; set; } - protected IList Y2{ get; set; } - protected IList XFract{ get; set; } - protected IList YFract{ get; set; } - protected IList ZFract{ get; set; } - protected IList HCounts{ get; set; } - protected IList AtomParities{ get; set; } - protected IList ParityARef1{ get; set; } - protected IList ParityARef2{ get; set; } - protected IList ParityARef3{ get; set; } - protected IList ParityARef4{ get; set; } - protected IList AtomDictRefs{ get; set; } - protected IList AtomAromaticities{ get; set; } - protected IList SpinMultiplicities{ get; set; } - protected IList Occupancies{ get; set; } - protected IDictionary> AtomCustomProperty{ get; set; } - protected bool ParityAtomsGiven{ get; set; } - protected bool ParityGiven{ get; set; } - - protected int BondCounter{ get; set; } - protected IList BondId{ get; set; } - protected IList BondARef1{ get; set; } - protected IList BondARef2{ get; set; } - protected IList Order{ get; set; } - protected IList BondStereo{ get; set; } - protected IList BondDictRefs{ get; set; } - protected IList BondElId{ get; set; } - protected List BondAromaticity{ get; set; } - protected IDictionary> BondCustomProperty{ get; set; } - protected bool StereoGiven{ get; set; } - protected string InChIString{ get; set; } - protected int CurRef{ get; set; } - protected int CurrentElement{ get; set; } - protected string BUILTIN{ get; set; } - protected string DICTREF{ get; set; } - protected string ElementTitle{ get; set; } - - protected double[] UnitCellParams{ get; set; } - protected int CrystalScalar{ get; set; } + protected int FormulaCounter { get; set; } + protected int AtomCounter { get; set; } + protected IList ElSym { get; set; } + protected IList ElTitles { get; set; } + protected IList ElId { get; set; } + protected IList Formula { get; set; } + protected IList FormalCharges { get; set; } + protected IList PartialCharges { get; set; } + protected IList Isotope { get; set; } + protected IList AtomicNumbers { get; set; } + protected IList ExactMasses { get; set; } + protected IList X3 { get; set; } + protected IList Y3 { get; set; } + protected IList Z3 { get; set; } + protected IList X2 { get; set; } + protected IList Y2 { get; set; } + protected IList XFract { get; set; } + protected IList YFract { get; set; } + protected IList ZFract { get; set; } + protected IList HCounts { get; set; } + protected IList AtomParities { get; set; } + protected IList ParityARef1 { get; set; } + protected IList ParityARef2 { get; set; } + protected IList ParityARef3 { get; set; } + protected IList ParityARef4 { get; set; } + protected IList AtomDictRefs { get; set; } + protected IList AtomAromaticities { get; set; } + protected IList SpinMultiplicities { get; set; } + protected IList Occupancies { get; set; } + protected IDictionary> AtomCustomProperty { get; set; } + protected bool ParityAtomsGiven { get; set; } + protected bool ParityGiven { get; set; } + + protected int BondCounter { get; set; } + protected IList BondId { get; set; } + protected IList BondARef1 { get; set; } + protected IList BondARef2 { get; set; } + protected IList Order { get; set; } + protected IList BondStereo { get; set; } + protected IList BondDictRefs { get; set; } + protected IList BondElId { get; set; } + protected IList BondAromaticity { get; set; } + protected IDictionary> BondCustomProperty { get; set; } + protected bool StereoGiven { get; set; } + protected string InChIString { get; set; } + protected int CurRef { get; set; } + protected int CurrentElement { get; set; } + protected string Builtin { get; set; } + protected string DictRef { get; set; } + protected string ElementTitle { get; set; } + + protected IList UnitCellParams { get; set; } + protected int CrystalScalar { get; set; } public CMLCoreModule(IChemFile chemFile) { @@ -150,7 +150,7 @@ public void Inherit(ICMLModule convention) this.MoleculeCustomProperty = conv.MoleculeCustomProperty; // copy the intermediate fields - this.BUILTIN = conv.BUILTIN; + this.Builtin = conv.Builtin; this.AtomCounter = conv.AtomCounter; this.FormulaCounter = conv.FormulaCounter; this.ElSym = conv.ElSym; @@ -292,15 +292,11 @@ protected void NewCrystalData() { UnitCellParams = new double[6]; CrystalScalar = 0; - // aAxis = new Vector3(); - // bAxis = new Vector3(); - // cAxis = new Vector3(); } public virtual void StartDocument() { Trace.TraceInformation("Start XML Doc"); - // cdo.StartDocument(); CurrentChemSequence = CurrentChemFile.Builder.NewChemSequence(); CurrentChemModel = CurrentChemFile.Builder.NewChemModel(); CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); @@ -309,13 +305,12 @@ public virtual void StartDocument() MoleculeCustomProperty = new List(); NewMolecule(); - BUILTIN = ""; + Builtin = ""; CurRef = 0; } public virtual void EndDocument() { - // cdo.EndDocument(); if (CurrentReactionSet != null && CurrentReactionSet.Count == 0 && CurrentReaction != null) { Debug.WriteLine("Adding reaction to ReactionSet"); @@ -357,1160 +352,1105 @@ public virtual void StartElement(CMLStack xpath, XElement element) string name = element.Name.LocalName; Debug.WriteLine("StartElement"); - BUILTIN = ""; - DICTREF = ""; + Builtin = ""; + DictRef = ""; foreach (var att in element.Attributes()) { var qname = att.Name.LocalName; - if (qname.Equals("builtin")) - { - BUILTIN = att.Value; - Debug.WriteLine(name, "->BUILTIN found: ", att.Value); - } - else if (qname.Equals("dictRef")) - { - DICTREF = att.Value; - Debug.WriteLine(name, "->DICTREF found: ", att.Value); - } - else if (qname.Equals("title")) - { - ElementTitle = att.Value; - Debug.WriteLine(name, "->TITLE found: ", att.Value); - } - else - { - Debug.WriteLine("Qname: ", qname); - } - } + switch (qname) + { + case "builtin": + Builtin = att.Value; + Debug.WriteLine(name, "->BUILTIN found: ", att.Value); + break; + case "dictRef": + DictRef = att.Value; + Debug.WriteLine(name, "->DICTREF found: ", att.Value); + break; + case "title": + ElementTitle = att.Value; + Debug.WriteLine(name, "->TITLE found: ", att.Value); + break; + default: + Debug.WriteLine($"Qname: {qname}"); + break; + } + } + + switch (name) + { + case "atom": + AtomCounter++; + foreach (var atti in element.Attributes()) + { + string att = atti.Name.LocalName; + string value = atti.Value; + switch (att) + { + case "id": + // this is supported in CML 1.X + ElId.Add(value); + break; + case "elementType": + // this is supported in CML 2.0 + ElSym.Add(value); + break; + case "title": + // this is supported in CML 2.0 + ElTitles.Add(value); + break; + case "x2": + // this is supported in CML 2.0 + X2.Add(value); + break; + case "xy2": + { + // this is supported in CML 2.0 + var tokens = Strings.Tokenize(value); + X2.Add(tokens[0]); + Y2.Add(tokens[1]); + } + break; + case "xyzFract": + { + // this is supported in CML 2.0 + var tokens = Strings.Tokenize(value); + XFract.Add(tokens[0]); + YFract.Add(tokens[1]); + ZFract.Add(tokens[2]); + } + break; + case "xyz3": + { + // this is supported in CML 2.0 + var tokens = Strings.Tokenize(value); + X3.Add(tokens[0]); + Y3.Add(tokens[1]); + Z3.Add(tokens[2]); + } + break; + case "y2": + // this is supported in CML 2.0 + Y2.Add(value); + break; + case "x3": + // this is supported in CML 2.0 + X3.Add(value); + break; + case "y3": + // this is supported in CML 2.0 + Y3.Add(value); + break; + case "z3": + // this is supported in CML 2.0 + Z3.Add(value); + break; + case "xFract": + // this is supported in CML 2.0 + XFract.Add(value); + break; + case "yFract": + // this is supported in CML 2.0 + YFract.Add(value); + break; + case "zFract": + // this is supported in CML 2.0 + ZFract.Add(value); + break; + case "formalCharge": + // this is supported in CML 2.0 + FormalCharges.Add(value); + break; + case "hydrogenCount": + // this is supported in CML 2.0 + HCounts.Add(value); + break; + case "isotopeNumber": + Isotope.Add(value); + break; + case "dictRef": + Debug.WriteLine($"occupancy: {value}"); + AtomDictRefs.Add(value); + break; + case "spinMultiplicity": + SpinMultiplicities.Add(value); + break; + case "occupancy": + Occupancies.Add(value); + break; + default: + Trace.TraceWarning("Unparsed attribute: " + att); + break; + } - if ("atom".Equals(name)) - { - AtomCounter++; - foreach (var atti in element.Attributes()) - { - string att = atti.Name.LocalName; - string value = atti.Value; - - if (att.Equals("id")) - { // this is supported in CML 1.X - ElId.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("elementType")) - { - ElSym.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("title")) - { - ElTitles.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("x2")) - { - X2.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("xy2")) - { - var tokens = Strings.Tokenize(value); - X2.Add(tokens[0]); - Y2.Add(tokens[1]); - } // this is supported in CML 2.0 - else if (att.Equals("xyzFract")) - { - var tokens = Strings.Tokenize(value); - XFract.Add(tokens[0]); - YFract.Add(tokens[1]); - ZFract.Add(tokens[2]); - } // this is supported in CML 2.0 - else if (att.Equals("xyz3")) - { - var tokens = Strings.Tokenize(value); - X3.Add(tokens[0]); - Y3.Add(tokens[1]); - Z3.Add(tokens[2]); - } // this is supported in CML 2.0 - else if (att.Equals("y2")) - { - Y2.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("x3")) - { - X3.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("y3")) - { - Y3.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("z3")) - { - Z3.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("xFract")) - { - XFract.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("yFract")) - { - YFract.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("zFract")) - { - ZFract.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("formalCharge")) - { - FormalCharges.Add(value); - } // this is supported in CML 2.0 - else if (att.Equals("hydrogenCount")) - { - HCounts.Add(value); + ParityAtomsGiven = false; + ParityGiven = false; } - else if (att.Equals("isotopeNumber")) + break; + case "atomArray": + if (!xpath.EndsWith("formula", "atomArray")) { - Isotope.Add(value); - } - else if (att.Equals("dictRef")) - { - Debug.WriteLine("occupancy: " + value); - AtomDictRefs.Add(value); - } - else if (att.Equals("spinMultiplicity")) - { - SpinMultiplicities.Add(value); - } - else if (att.Equals("occupancy")) - { - Occupancies.Add(value); - } - - else - { - Trace.TraceWarning("Unparsed attribute: " + att); - } - - ParityAtomsGiven = false; - ParityGiven = false; - } - } - else if ("atomArray".Equals(name) && !xpath.EndsWith("formula", "atomArray")) - { - bool atomsCounted = false; - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - int count = 0; - if (att.Equals("atomID")) - { - count = AddArrayElementsTo(ElId, attribute.Value); - } - else if (att.Equals("elementType")) - { - count = AddArrayElementsTo(ElSym, attribute.Value); - } - else if (att.Equals("x2")) - { - count = AddArrayElementsTo(X2, attribute.Value); - } - else if (att.Equals("y2")) - { - count = AddArrayElementsTo(Y2, attribute.Value); - } - else if (att.Equals("x3")) - { - count = AddArrayElementsTo(X3, attribute.Value); - } - else if (att.Equals("y3")) - { - count = AddArrayElementsTo(Y3, attribute.Value); - } - else if (att.Equals("z3")) - { - count = AddArrayElementsTo(Z3, attribute.Value); - } - else if (att.Equals("xFract")) - { - count = AddArrayElementsTo(XFract, attribute.Value); - } - else if (att.Equals("yFract")) - { - count = AddArrayElementsTo(YFract, attribute.Value); - } - else if (att.Equals("zFract")) - { - count = AddArrayElementsTo(ZFract, attribute.Value); - } - else - { - Trace.TraceWarning("Unparsed attribute: " + att); - } - if (!atomsCounted) - { - AtomCounter += count; - atomsCounted = true; - } - } - } - else if ("atomParity".Equals(name)) - { - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("atomRefs4") && !ParityAtomsGiven) - { - //Expect exactly four references - try + bool atomsCounted = false; + foreach (var attribute in element.Attributes()) { - var tokens = Strings.Tokenize(attribute.Value); - ParityARef1.Add(tokens[0]); - ParityARef2.Add(tokens[1]); - ParityARef3.Add(tokens[2]); - ParityARef4.Add(tokens[3]); - ParityAtomsGiven = true; - } - catch (Exception e) - { - Trace.TraceError("Error in CML file: ", e.Message); - Debug.WriteLine(e); + var xname = attribute.Name; + int count = 0; + string att = xname.LocalName; + switch (att) + { + case "atomID": + count = AddArrayElementsTo(ElId, attribute.Value); + break; + case "elementType": + count = AddArrayElementsTo(ElSym, attribute.Value); + break; + case "x2": + count = AddArrayElementsTo(X2, attribute.Value); + break; + case "y2": + count = AddArrayElementsTo(Y2, attribute.Value); + break; + case "x3": + count = AddArrayElementsTo(X3, attribute.Value); + break; + case "y3": + count = AddArrayElementsTo(Y3, attribute.Value); + break; + case "z3": + count = AddArrayElementsTo(Z3, attribute.Value); + break; + case "xFract": + count = AddArrayElementsTo(XFract, attribute.Value); + break; + case "yFract": + count = AddArrayElementsTo(YFract, attribute.Value); + break; + case "zFract": + count = AddArrayElementsTo(ZFract, attribute.Value); + break; + default: + Trace.TraceWarning("Unparsed attribute: " + att); + break; + } + if (!atomsCounted) + { + AtomCounter += count; + atomsCounted = true; + } } } - } - } - else if ("bond".Equals(name)) - { - BondCounter++; - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - Debug.WriteLine("B2 ", att, "=", attribute.Value); - - if (att.Equals("id")) + break; + case "atomParity": + foreach (var attribute in element.Attributes()) { - BondId.Add(attribute.Value); - Debug.WriteLine("B3 ", BondId); - } - else if (att.Equals("atomRefs") || // this is CML 1.X support - att.Equals("atomRefs2")) - { // this is CML 2.0 support - - // expect exactly two references - try - { - var tokens = Strings.Tokenize(attribute.Value, ' '); - BondARef1.Add(tokens[0]); - BondARef2.Add(tokens[1]); - } - catch (Exception e) + var xname = attribute.Name; + string att = xname.LocalName; + switch (att) { - Trace.TraceError("Error in CML file: ", e.Message); - Debug.WriteLine(e); + case "atomRefs4": + if (!ParityAtomsGiven) + { + //Expect exactly four references + try + { + var tokens = Strings.Tokenize(attribute.Value); + ParityARef1.Add(tokens[0]); + ParityARef2.Add(tokens[1]); + ParityARef3.Add(tokens[2]); + ParityARef4.Add(tokens[3]); + ParityAtomsGiven = true; + } + catch (Exception e) + { + Trace.TraceError("Error in CML file: ", e.Message); + Debug.WriteLine(e); + } + } + break; } } - else if (att.Equals("order")) - { // this is CML 2.0 support - Order.Add(attribute.Value.Trim()); - } - else if (att.Equals("dictRef")) + break; + case "bond": + BondCounter++; + foreach (var attribute in element.Attributes()) { - BondDictRefs.Add(attribute.Value.Trim()); - } - } + var xname = attribute.Name; + string att = xname.LocalName; + Debug.WriteLine("B2 ", att, "=", attribute.Value); - StereoGiven = false; - CurRef = 0; - } - else if ("bondArray".Equals(name)) - { - bool bondsCounted = false; - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - int count = 0; - if (att.Equals("bondID")) - { - count = AddArrayElementsTo(BondId, attribute.Value); - } - else if (att.Equals("atomRefs1")) - { - count = AddArrayElementsTo(BondARef1, attribute.Value); - } - else if (att.Equals("atomRefs2")) - { - count = AddArrayElementsTo(BondARef2, attribute.Value); - } - else if (att.Equals("atomRef1")) - { - count = AddArrayElementsTo(BondARef1, attribute.Value); - } - else if (att.Equals("atomRef2")) - { - count = AddArrayElementsTo(BondARef2, attribute.Value); - } - else if (att.Equals("order")) - { - count = AddArrayElementsTo(Order, attribute.Value); - } - else - { - Trace.TraceWarning("Unparsed attribute: " + att); - } - if (!bondsCounted) - { - BondCounter += count; - bondsCounted = true; - } - } - CurRef = 0; - } - else if ("bondStereo".Equals(name)) - { - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("dictRef")) - { - string value = attribute.Value; - if (value.StartsWith("cml:", StringComparison.Ordinal) && value.Length > 4) + switch (att) { - BondStereo.Add(value.Substring(4)); - StereoGiven = true; + case "id": + BondId.Add(attribute.Value); + Debug.WriteLine($"B3 {BondId}"); + break; + case "atomRefs": // this is CML 1.X support + case "atomRefs2": // this is CML 2.0 support + // expect exactly two references + try + { + var tokens = Strings.Tokenize(attribute.Value, ' '); + BondARef1.Add(tokens[0]); + BondARef2.Add(tokens[1]); + } + catch (Exception e) + { + Trace.TraceError("Error in CML file: ", e.Message); + Debug.WriteLine(e); + } + break; + case "order": + // this is CML 2.0 support + Order.Add(attribute.Value.Trim()); + break; + case "dictRef": + BondDictRefs.Add(attribute.Value.Trim()); + break; + default: + break; } } - } - } - else if ("bondType".Equals(name)) - { - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("dictRef")) - { - if (attribute.Value.Equals("cdk:aromaticBond")) BondAromaticity.Add(true); - } - } - } - else if ("molecule".Equals(name)) - { - NewMolecule(); - BUILTIN = ""; - // cdo.StartObject("Molecule"); - if (CurrentChemModel == null) - CurrentChemModel = CurrentChemFile.Builder.NewChemModel(); - if (CurrentMoleculeSet == null) - CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); - CurrentMolecule = CurrentChemFile.Builder.NewAtomContainer(); - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("id")) - { - // cdo.SetObjectProperty("Molecule", "id", attribute.Value); - CurrentMolecule.Id = attribute.Value; - } - else if (att.Equals("dictRef")) - { - // cdo.SetObjectProperty("Molecule", "dictRef", attribute.Value); - CurrentMolecule.SetProperty(new DictRef(DICTREF, attribute.Value), attribute.Value); - } - } - } - else if ("crystal".Equals(name)) - { - NewCrystalData(); - // cdo.StartObject("Crystal"); - CurrentMolecule = CurrentChemFile.Builder.NewCrystal(CurrentMolecule); - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("z")) - { - // cdo.SetObjectProperty("Crystal", "z", attribute.Value); - ((ICrystal)CurrentMolecule).Z = int.Parse(attribute.Value); - } - } - } - else if ("symmetry".Equals(name)) - { - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("spaceGroup")) - { - // cdo.SetObjectProperty("Crystal", "spacegroup", attribute.Value); - ((ICrystal)CurrentMolecule).SpaceGroup = attribute.Value; - } - } - } - else if ("identifier".Equals(name)) - { - var convention_value = AttGetValue(element.Attributes(), "convention"); - if ("iupac:inchi".Equals(convention_value)) - { - // cdo.SetObjectProperty("Molecule", "inchi", atts.GetValue("value")); - if (element.Attribute("value") != null) - CurrentMolecule.SetProperty(CDKPropertyName.InChI, element.Attribute("value").Value); - } - } - else if ("scalar".Equals(name)) - { - if (xpath.EndsWith("crystal", "scalar")) CrystalScalar++; - } - else if ("label".Equals(name)) - { - if (xpath.EndsWith("atomType", "label")) - { - // cdo.SetObjectProperty("Atom", "atomTypeLabel", atts.GetValue("value")); - CurrentAtom.AtomTypeName = AttGetValue(element.Attributes(), "value"); - } - } - else if ("list".Equals(name)) - { - // cdo.StartObject("MoleculeSet"); - if (DICTREF.Equals("cdk:model")) - { - CurrentChemModel = CurrentChemFile.Builder.NewChemModel(); - // see if there is an ID attribute - foreach (var attribute in element.Attributes()) + StereoGiven = false; + CurRef = 0; + break; + case "bondArray": { - var xname = attribute.Name; - string att = xname.LocalName; - if (att.Equals("id")) + bool bondsCounted = false; + foreach (var attribute in element.Attributes()) { - CurrentChemModel.Id = attribute.Value; + var xname = attribute.Name; + int count = 0; + string att = xname.LocalName; + switch (att) + { + case "bondID": + count = AddArrayElementsTo(BondId, attribute.Value); + break; + case "atomRefs1": + count = AddArrayElementsTo(BondARef1, attribute.Value); + break; + case "atomRefs2": + count = AddArrayElementsTo(BondARef2, attribute.Value); + break; + case "atomRef1": + count = AddArrayElementsTo(BondARef1, attribute.Value); + break; + case "atomRef2": + count = AddArrayElementsTo(BondARef2, attribute.Value); + break; + case "order": + count = AddArrayElementsTo(Order, attribute.Value); + break; + default: + Trace.TraceWarning("Unparsed attribute: " + att); + break; + } + if (!bondsCounted) + { + BondCounter += count; + bondsCounted = true; + } } + CurRef = 0; } - } - else if (DICTREF.Equals("cdk:moleculeSet")) - { - CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); - // see if there is an ID attribute + break; + case "bondStereo": foreach (var attribute in element.Attributes()) { var xname = attribute.Name; string att = xname.LocalName; - if (att.Equals("id")) + switch (att) { - CurrentMoleculeSet.Id = attribute.Value; + case "dictRef": + string value = attribute.Value; + if (value.StartsWith("cml:", StringComparison.Ordinal) && value.Length > 4) + { + BondStereo.Add(value.Substring(4)); + StereoGiven = true; + } + break; + default: + break; } } - CurrentMolecule = CurrentChemFile.Builder.NewAtomContainer(); - } - else - { - // the old default - CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); - // see if there is an ID attribute + break; + case "bondType": foreach (var attribute in element.Attributes()) { var xname = attribute.Name; string att = xname.LocalName; - if (att.Equals("id")) + switch (att) { - CurrentMoleculeSet.Id = attribute.Value; + case "dictRef": + if (string.Equals(attribute.Value, "cdk:aromaticBond", StringComparison.Ordinal)) + BondAromaticity.Add(true); + break; + default: + break; } } - CurrentMolecule = CurrentChemFile.Builder.NewAtomContainer(); - } - } - else if ("formula".Equals(name)) - { - FormulaCounter++; - foreach (var attribute in element.Attributes()) - { - var xname = attribute.Name; - string att = xname.LocalName; - string value = attribute.Value; - if (att.Equals("concise")) - { - Formula.Add(value); - } - } - } - } - - public virtual void EndElement(CMLStack xpath, XElement element) - { - var name = element.Name.LocalName; - - Debug.WriteLine("EndElement: ", name); - - string cData = element.Value; - if ("bond".Equals(name)) - { - if (!StereoGiven) BondStereo.Add(""); - if (BondCounter > BondDictRefs.Count) BondDictRefs.Add(null); - if (BondCounter > BondAromaticity.Count) BondAromaticity.Add(null); - } - else if ("atom".Equals(name)) - { - if (AtomCounter > ElTitles.Count) - { - ElTitles.Add(null); - } - if (AtomCounter > HCounts.Count) - { - HCounts.Add(null); - } - if (AtomCounter > AtomDictRefs.Count) - { - AtomDictRefs.Add(null); - } - if (AtomCounter > AtomAromaticities.Count) - { - AtomAromaticities.Add(null); - } - if (AtomCounter > Isotope.Count) - { - Isotope.Add(null); - } - if (AtomCounter > AtomicNumbers.Count) - { - AtomicNumbers.Add(null); - } - if (AtomCounter > ExactMasses.Count) - { - ExactMasses.Add(null); - } - if (AtomCounter > SpinMultiplicities.Count) - { - SpinMultiplicities.Add(null); - } - if (AtomCounter > Occupancies.Count) - { - Occupancies.Add(null); - } - if (AtomCounter > FormalCharges.Count) - { - // while strictly undefined, assume zero formal charge when no - // number is given - FormalCharges.Add("0"); - } - if (!ParityGiven) - { - AtomParities.Add(""); - } - if (!ParityAtomsGiven) - { - ParityARef1.Add(""); - ParityARef2.Add(""); - ParityARef3.Add(""); - ParityARef4.Add(""); - } - // It may happen that not all atoms have associated 2D or 3D - // coordinates. accept that - if (AtomCounter > X2.Count && X2.Count != 0) - { - // apparently, the previous atoms had atomic coordinates, add - // 'null' for this atom - X2.Add(null); - Y2.Add(null); - } - if (AtomCounter > X3.Count && X3.Count != 0) - { - // apparently, the previous atoms had atomic coordinates, add - // 'null' for this atom - X3.Add(null); - Y3.Add(null); - Z3.Add(null); - } - - if (AtomCounter > XFract.Count && XFract.Count != 0) - { - // apparently, the previous atoms had atomic coordinates, add - // 'null' for this atom - XFract.Add(null); - YFract.Add(null); - ZFract.Add(null); - } - } - else if ("molecule".Equals(name)) - { - StoreData(); - // cdo.EndObject("Molecule"); - if (CurrentMolecule is ICrystal) - { - Debug.WriteLine("Adding crystal to chemModel"); - CurrentChemModel.Crystal = (ICrystal)CurrentMolecule; - CurrentChemSequence.Add(CurrentChemModel); - } - else if (CurrentMolecule is IAtomContainer) - { - Debug.WriteLine("Adding molecule to set"); - CurrentMoleculeSet.Add(CurrentMolecule); - Debug.WriteLine("#mols in set: " + CurrentMoleculeSet.Count()); - } - } - else if ("crystal".Equals(name)) - { - if (CrystalScalar > 0) - { - // convert unit cell parameters to cartesians - Vector3[] axes = CrystalGeometryTools.NotionalToCartesian(UnitCellParams[0], UnitCellParams[1], - UnitCellParams[2], UnitCellParams[3], UnitCellParams[4], UnitCellParams[5]); - // cdo.StartObject("a-axis"); - // cdo.SetObjectProperty("a-axis", "x", new Double(aAxis.X).ToString()); - // cdo.SetObjectProperty("a-axis", "y", new Double(aAxis.Y).ToString()); - // cdo.SetObjectProperty("a-axis", "z", new Double(aAxis.Z).ToString()); - // cdo.EndObject("a-axis"); - // cdo.StartObject("b-axis"); - // cdo.SetObjectProperty("b-axis", "x", new Double(bAxis.X).ToString()); - // cdo.SetObjectProperty("b-axis", "y", new Double(bAxis.Y).ToString()); - // cdo.SetObjectProperty("b-axis", "z", new Double(bAxis.Z).ToString()); - // cdo.EndObject("b-axis"); - // cdo.StartObject("c-axis"); - // cdo.SetObjectProperty("c-axis", "x", new Double(cAxis.X).ToString()); - // cdo.SetObjectProperty("c-axis", "y", new Double(cAxis.Y).ToString()); - // cdo.SetObjectProperty("c-axis", "z", new Double(cAxis.Z).ToString()); - // cdo.EndObject("c-axis"); - ((ICrystal)CurrentMolecule).A = axes[0]; - ((ICrystal)CurrentMolecule).B = axes[1]; - ((ICrystal)CurrentMolecule).C = axes[2]; - } - else - { - Trace.TraceError("Could not find crystal unit cell parameters"); - } - // cdo.EndObject("Crystal"); - } - else if ("list".Equals(name)) - { - // cdo.EndObject("MoleculeSet"); - // FIXME: I really should check the DICTREF, but there is currently - // no mechanism for storing these for use with EndTag() :( - // So, instead, for now, just see if it already has done the setting - // to work around duplication - if (CurrentChemModel.MoleculeSet != CurrentMoleculeSet) - { - CurrentChemModel.MoleculeSet = CurrentMoleculeSet; - CurrentChemSequence.Add(CurrentChemModel); - } - } - else if ("coordinate3".Equals(name)) - { - if (BUILTIN.Equals("xyz3")) - { - Debug.WriteLine("New coord3 xyz3 found: ", element.Value); - - try - { - var tokens = Strings.Tokenize(element.Value); - X3.Add(tokens[0]); - Y3.Add(tokens[1]); - Z3.Add(tokens[2]); - Debug.WriteLine("coord3 x3.Length: ", X3.Count); - Debug.WriteLine("coord3 y3.Length: ", Y3.Count); - Debug.WriteLine("coord3 z3.Length: ", Z3.Count); - } - catch (Exception exception) - { - Trace.TraceError("CMLParsing error while setting coordinate3!"); - Debug.WriteLine(exception); - } - } - else - { - Trace.TraceWarning("Unknown coordinate3 BUILTIN: " + BUILTIN); - } - } - else if ("string".Equals(name)) - { - if (BUILTIN.Equals("elementType")) - { - Debug.WriteLine("Element: ", cData.Trim()); - ElSym.Add(cData); - } - else if (BUILTIN.Equals("atomRef")) - { - CurRef++; - Debug.WriteLine("Bond: ref #", CurRef); - - if (CurRef == 1) - { - BondARef1.Add(cData.Trim()); - } - else if (CurRef == 2) - { - BondARef2.Add(cData.Trim()); - } - } - else if (BUILTIN.Equals("order")) - { - Debug.WriteLine("Bond: order ", cData.Trim()); - Order.Add(cData.Trim()); - } - else if (BUILTIN.Equals("formalCharge")) - { - // NOTE: this combination is in violation of the CML DTD!!! - Trace.TraceWarning("formalCharge BUILTIN accepted but violating CML DTD"); - Debug.WriteLine("Charge: ", cData.Trim()); - string charge = cData.Trim(); - if (charge.StartsWithChar('+') && charge.Length > 1) - { - charge = charge.Substring(1); - } - FormalCharges.Add(charge); - } - } - else if ("bondStereo".Equals(name)) - { - if (!string.IsNullOrEmpty(element.Value) && !StereoGiven) - { - BondStereo.Add(element.Value); - StereoGiven = true; - } - } - else if ("atomParity".Equals(name)) - { - if (!string.IsNullOrEmpty(element.Value) && !ParityGiven && ParityAtomsGiven) - { - AtomParities.Add(element.Value); - ParityGiven = true; - } - } - else if ("float".Equals(name)) - { - if (BUILTIN.Equals("x3")) - { - X3.Add(cData.Trim()); - } - else if (BUILTIN.Equals("y3")) - { - Y3.Add(cData.Trim()); - } - else if (BUILTIN.Equals("z3")) - { - Z3.Add(cData.Trim()); - } - else if (BUILTIN.Equals("x2")) - { - X2.Add(cData.Trim()); - } - else if (BUILTIN.Equals("y2")) - { - Y2.Add(cData.Trim()); - } - else if (BUILTIN.Equals("order")) - { - // NOTE: this combination is in violation of the CML DTD!!! - Order.Add(cData.Trim()); - } - else if (BUILTIN.Equals("charge") || BUILTIN.Equals("partialCharge")) - { - PartialCharges.Add(cData.Trim()); - } - } - else if ("integer".Equals(name)) - { - if (BUILTIN.Equals("formalCharge")) - { - FormalCharges.Add(cData.Trim()); - } - } - else if ("coordinate2".Equals(name)) - { - if (BUILTIN.Equals("xy2")) - { - Debug.WriteLine("New coord2 xy2 found.", cData); - - try - { - var tokens = Strings.Tokenize(cData); - X2.Add(tokens[0]); - Y2.Add(tokens[1]); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 175, 1); - } - } - } - else if ("stringArray".Equals(name)) - { - if (BUILTIN.Equals("id") || BUILTIN.Equals("atomId") || BUILTIN.Equals("atomID")) - { // invalid according to CML1 DTD but found in OpenBabel 1.X output - - try - { - bool countAtoms = (AtomCounter == 0) ? true : false; - var tokens = Strings.Tokenize(cData); - foreach (var token in tokens) + break; + case "molecule": + { + NewMolecule(); + Builtin = ""; + if (CurrentChemModel == null) + CurrentChemModel = CurrentChemFile.Builder.NewChemModel(); + if (CurrentMoleculeSet == null) + CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); + CurrentMolecule = CurrentChemFile.Builder.NewAtomContainer(); + foreach (var attribute in element.Attributes()) { - if (countAtoms) + var xname = attribute.Name; + string att = xname.LocalName; + switch (att) { - AtomCounter++; + case "id": + CurrentMolecule.Id = attribute.Value; + break; + case "dictRef": + CurrentMolecule.SetProperty(new DictRef(DictRef, attribute.Value), attribute.Value); + break; + default: + break; } - Debug.WriteLine("StringArray (Token): ", token); - ElId.Add(token); } } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 186, 1); - } - } - else if (BUILTIN.Equals("elementType")) - { - - try + break; + case "crystal": + NewCrystalData(); + CurrentMolecule = CurrentChemFile.Builder.NewCrystal(CurrentMolecule); + foreach (var attribute in element.Attributes()) { - bool countAtoms = (AtomCounter == 0) ? true : false; - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) + var xname = attribute.Name; + string att = xname.LocalName; + switch (att) { - if (countAtoms) - { - AtomCounter++; - } - ElSym.Add(token); + case "z": + ((ICrystal)CurrentMolecule).Z = int.Parse(attribute.Value, NumberFormatInfo.InvariantInfo); + break; + default: + break; } } - catch (Exception e) + break; + case "symmetry": + foreach (var attribute in element.Attributes()) { - Notify("CMLParsing error: " + e, SYSTEMID, 194, 1); - } - } - else if (BUILTIN.Equals("atomRefs")) - { - CurRef++; - Debug.WriteLine("New atomRefs found: ", CurRef); - - try + var xname = attribute.Name; + string att = xname.LocalName; + if (string.Equals(att, "spaceGroup", StringComparison.Ordinal)) + { + ((ICrystal)CurrentMolecule).SpaceGroup = attribute.Value; + } + } + break; + case "identifier": { - bool countBonds = (BondCounter == 0) ? true : false; - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) + var convention_value = AttGetValue(element.Attributes(), "convention"); + if (string.Equals("iupac:inchi", convention_value, StringComparison.Ordinal)) { - if (countBonds) - { - BondCounter++; - } - Debug.WriteLine("Token: ", token); - - if (CurRef == 1) - { - BondARef1.Add(token); - } - else if (CurRef == 2) - { - BondARef2.Add(token); - } + if (element.Attribute("value") != null) + CurrentMolecule.SetProperty(CDKPropertyName.InChI, element.Attribute("value").Value); } } - catch (Exception e) + break; + case "scalar": + if (xpath.EndsWith("crystal", "scalar")) + CrystalScalar++; + break; + case "label": + if (xpath.EndsWith("atomType", "label")) { - Notify("CMLParsing error: " + e, SYSTEMID, 194, 1); + CurrentAtom.AtomTypeName = AttGetValue(element.Attributes(), "value"); } - } - else if (BUILTIN.Equals("atomRef")) - { - CurRef++; - Debug.WriteLine("New atomRef found: ", CurRef); // this is CML1 stuff, we get things like: - // a2 a2 a2 a2 a3 a3 - // a4 a4 a5 a6 a7 a9 a9 a11 a12 a13 a5 a4 a6 a9 a7 a8 a8 - // a10 1 1 1 1 2 1 2 - // 1 1 1 2 2 - - try + break; + case "list": { - bool countBonds = (BondCounter == 0) ? true : false; - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) + if (string.Equals(DictRef, "cdk:model", StringComparison.Ordinal)) { - if (countBonds) + CurrentChemModel = CurrentChemFile.Builder.NewChemModel(); + foreach (var attribute in element.Attributes()) { - BondCounter++; + var xname = attribute.Name; + string att = xname.LocalName; + if (string.Equals(att, "id", StringComparison.Ordinal)) + { + CurrentChemModel.Id = attribute.Value; + } } - Debug.WriteLine("Token: ", token); - - if (CurRef == 1) + } + else if (string.Equals(DictRef, "cdk:moleculeSet", StringComparison.Ordinal)) + { + CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); + // see if there is an ID attribute + foreach (var attribute in element.Attributes()) { - BondARef1.Add(token); + var xname = attribute.Name; + string att = xname.LocalName; + if (string.Equals(att, "id", StringComparison.Ordinal)) + { + CurrentMoleculeSet.Id = attribute.Value; + } } - else if (CurRef == 2) + CurrentMolecule = CurrentChemFile.Builder.NewAtomContainer(); + } + else + { + // the old default + CurrentMoleculeSet = CurrentChemFile.Builder.NewAtomContainerSet(); + // see if there is an ID attribute + foreach (var attribute in element.Attributes()) { - BondARef2.Add(token); + var xname = attribute.Name; + string att = xname.LocalName; + if (string.Equals(att, "id", StringComparison.Ordinal)) + { + CurrentMoleculeSet.Id = attribute.Value; + } } + CurrentMolecule = CurrentChemFile.Builder.NewAtomContainer(); } } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 194, 1); - } - } - else if (BUILTIN.Equals("order")) - { - Debug.WriteLine("New bond order found."); - - try + break; + case "formula": + FormulaCounter++; + foreach (var attribute in element.Attributes()) { - - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) + var xname = attribute.Name; + string att = xname.LocalName; + string value = attribute.Value; + if (string.Equals(att, "concise", StringComparison.Ordinal)) { - Debug.WriteLine("Token: ", token); - Order.Add(token); + Formula.Add(value); } } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 194, 1); - } - } + break; + default: + break; } - else if ("integerArray".Equals(name)) - { - Debug.WriteLine("IntegerArray: builtin = ", BUILTIN); - - if (BUILTIN.Equals("formalCharge")) - { + } - try - { + public virtual void EndElement(CMLStack xpath, XElement element) + { + var name = element.Name.LocalName; - var tokens = Strings.Tokenize(cData); + Debug.WriteLine($"EndElement: {name}"); - foreach (var token in tokens) - { - Debug.WriteLine("Charge added: ", token); - FormalCharges.Add(token); - } + string cData = element.Value; + switch (name) + { + case "bond": + if (!StereoGiven) + BondStereo.Add(""); + if (BondCounter > BondDictRefs.Count) + BondDictRefs.Add(null); + if (BondCounter > BondAromaticity.Count) + BondAromaticity.Add(null); + break; + case "atom": + if (AtomCounter > ElTitles.Count) + ElTitles.Add(null); + if (AtomCounter > HCounts.Count) + HCounts.Add(null); + if (AtomCounter > AtomDictRefs.Count) + AtomDictRefs.Add(null); + if (AtomCounter > AtomAromaticities.Count) + AtomAromaticities.Add(null); + if (AtomCounter > Isotope.Count) + Isotope.Add(null); + if (AtomCounter > AtomicNumbers.Count) + AtomicNumbers.Add(null); + if (AtomCounter > ExactMasses.Count) + ExactMasses.Add(null); + if (AtomCounter > SpinMultiplicities.Count) + SpinMultiplicities.Add(null); + if (AtomCounter > Occupancies.Count) + Occupancies.Add(null); + if (AtomCounter > FormalCharges.Count) + { + // while strictly undefined, assume zero formal charge when no + // number is given + FormalCharges.Add("0"); + } + if (!ParityGiven) + AtomParities.Add(""); + if (!ParityAtomsGiven) + { + ParityARef1.Add(""); + ParityARef2.Add(""); + ParityARef3.Add(""); + ParityARef4.Add(""); + } + // It may happen that not all atoms have associated 2D or 3D + // coordinates. accept that + if (AtomCounter > X2.Count && X2.Count != 0) + { + // apparently, the previous atoms had atomic coordinates, add + // 'null' for this atom + X2.Add(null); + Y2.Add(null); + } + if (AtomCounter > X3.Count && X3.Count != 0) + { + // apparently, the previous atoms had atomic coordinates, add + // 'null' for this atom + X3.Add(null); + Y3.Add(null); + Z3.Add(null); + } + + if (AtomCounter > XFract.Count && XFract.Count != 0) + { + // apparently, the previous atoms had atomic coordinates, add + // 'null' for this atom + XFract.Add(null); + YFract.Add(null); + ZFract.Add(null); + } + break; + case "molecule": + StoreData(); + if (CurrentMolecule is ICrystal) + { + Debug.WriteLine("Adding crystal to chemModel"); + CurrentChemModel.Crystal = (ICrystal)CurrentMolecule; + CurrentChemSequence.Add(CurrentChemModel); + } + else if (CurrentMolecule is IAtomContainer) + { + Debug.WriteLine("Adding molecule to set"); + CurrentMoleculeSet.Add(CurrentMolecule); + Debug.WriteLine("#mols in set: " + CurrentMoleculeSet.Count()); + } + break; + case "crystal": + if (CrystalScalar > 0) + { + // convert unit cell parameters to cartesians + Vector3[] axes = CrystalGeometryTools.NotionalToCartesian(UnitCellParams[0], UnitCellParams[1], + UnitCellParams[2], UnitCellParams[3], UnitCellParams[4], UnitCellParams[5]); + ((ICrystal)CurrentMolecule).A = axes[0]; + ((ICrystal)CurrentMolecule).B = axes[1]; + ((ICrystal)CurrentMolecule).C = axes[2]; } - catch (Exception e) + else { - Notify("CMLParsing error: " + e, SYSTEMID, 205, 1); + Trace.TraceError("Could not find crystal unit cell parameters"); } - } - } - else if ("scalar".Equals(name)) - { - if (xpath.EndsWith("crystal", "scalar")) - { - Debug.WriteLine("Going to set a crystal parameter: " + CrystalScalar, " to ", cData); - try + break; + case "list": + // FIXME: I really should check the DICTREF, but there is currently + // no mechanism for storing these for use with EndTag() :( + // So, instead, for now, just see if it already has done the setting + // to work around duplication + if (CurrentChemModel.MoleculeSet != CurrentMoleculeSet) { - UnitCellParams[CrystalScalar - 1] = double.Parse(cData.Trim()); + CurrentChemModel.MoleculeSet = CurrentMoleculeSet; + CurrentChemSequence.Add(CurrentChemModel); } - catch (FormatException) + break; + case "coordinate3": + switch (Builtin) { - Trace.TraceError("Content must a float: " + cData); + case "xyz3": + Debug.WriteLine($"New coord3 xyz3 found: {element.Value}"); + try + { + var tokens = Strings.Tokenize(element.Value); + X3.Add(tokens[0]); + Y3.Add(tokens[1]); + Z3.Add(tokens[2]); + Debug.WriteLine($"coord3 x3.Length: {X3.Count}"); + Debug.WriteLine($"coord3 y3.Length: {Y3.Count}"); + Debug.WriteLine($"coord3 z3.Length: {Z3.Count}"); + } + catch (Exception exception) + { + Trace.TraceError("CMLParsing error while setting coordinate3!"); + Debug.WriteLine(exception); + } + break; + default: + Trace.TraceWarning("Unknown coordinate3 BUILTIN: " + Builtin); + break; + } + break; + case "string": + switch (Builtin) + { + case "elementType": + Debug.WriteLine($"Element: {cData.Trim()}"); + ElSym.Add(cData); + break; + case "atomRef": + CurRef++; + Debug.WriteLine($"Bond: ref #{CurRef}"); + + if (CurRef == 1) + { + BondARef1.Add(cData.Trim()); + } + else if (CurRef == 2) + { + BondARef2.Add(cData.Trim()); + } + break; + case "order": + Debug.WriteLine($"Bond: order {cData.Trim()}"); + Order.Add(cData.Trim()); + break; + case "formalCharge": + // NOTE: this combination is in violation of the CML DTD!!! + Trace.TraceWarning("formalCharge BUILTIN accepted but violating CML DTD"); + Debug.WriteLine($"Charge: {cData.Trim()}"); + string charge = cData.Trim(); + if (charge.StartsWithChar('+') && charge.Length > 1) + { + charge = charge.Substring(1); + } + FormalCharges.Add(charge); + break; + default: + break; } - } - else if (xpath.EndsWith("bond", "scalar")) - { - if (DICTREF.Equals("mdl:stereo")) + break; + case "bondStereo": + if (!string.IsNullOrEmpty(element.Value) && !StereoGiven) { - BondStereo.Add(cData.Trim()); + BondStereo.Add(element.Value); StereoGiven = true; } - else + break; + case "atomParity": { - if (!BondCustomProperty.TryGetValue(BondId[BondId.Count - 1], out IDictionary bp)) + if (!string.IsNullOrEmpty(element.Value) && !ParityGiven && ParityAtomsGiven) { - bp = new Dictionary(); - BondCustomProperty[BondId[BondId.Count - 1]] = bp; + AtomParities.Add(element.Value); + ParityGiven = true; } - bp[ElementTitle] = cData.Trim(); - } - } - else if (xpath.EndsWith("atom", "scalar")) - { - if (DICTREF.Equals("cdk:partialCharge")) - { - PartialCharges.Add(cData.Trim()); } - else if (DICTREF.Equals("cdk:atomicNumber")) - { - AtomicNumbers.Add(cData.Trim()); + break; + case "float": + switch (Builtin) + { + case "x3": + X3.Add(cData.Trim()); + break; + case "y3": + Y3.Add(cData.Trim()); + break; + case "z3": + Z3.Add(cData.Trim()); + break; + case "x2": + X2.Add(cData.Trim()); + break; + case "y2": + Y2.Add(cData.Trim()); + break; + case "order": + // NOTE: this combination is in violation of the CML DTD!!! + Order.Add(cData.Trim()); + break; + case "charge": + case "partialCharge": + PartialCharges.Add(cData.Trim()); + break; + default: + break; + } + break; + case "integer": + if (string.Equals(Builtin, "formalCharge", StringComparison.Ordinal)) + { + FormalCharges.Add(cData.Trim()); + } + break; + case "coordinate2": + switch (Builtin) + { + case "xy2": + Debug.WriteLine($"New coord2 xy2 found.{cData}"); + try + { + var tokens = Strings.Tokenize(cData); + X2.Add(tokens[0]); + Y2.Add(tokens[1]); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 175, 1); + } + break; + default: + break; + } + break; + case "stringArray": + switch (Builtin) + { + case "id": + case "atomId": + case "atomID": + // invalid according to CML1 DTD but found in OpenBabel 1.X output + try + { + bool countAtoms = (AtomCounter == 0) ? true : false; + var tokens = Strings.Tokenize(cData); + foreach (var token in tokens) + { + if (countAtoms) + { + AtomCounter++; + } + Debug.WriteLine($"StringArray (Token): {token}"); + ElId.Add(token); + } + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 186, 1); + } + break; + case "elementType": + try + { + bool countAtoms = (AtomCounter == 0) ? true : false; + var tokens = Strings.Tokenize(cData); + + foreach (var token in tokens) + { + if (countAtoms) + { + AtomCounter++; + } + ElSym.Add(token); + } + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 194, 1); + } + break; + case "atomRefs": + CurRef++; + Debug.WriteLine($"New atomRefs found: {CurRef}"); + + try + { + bool countBonds = (BondCounter == 0) ? true : false; + var tokens = Strings.Tokenize(cData); + + foreach (var token in tokens) + { + if (countBonds) + { + BondCounter++; + } + Debug.WriteLine($"Token: {token}"); + + if (CurRef == 1) + { + BondARef1.Add(token); + } + else if (CurRef == 2) + { + BondARef2.Add(token); + } + } + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 194, 1); + } + break; + case "atomRef": + CurRef++; + Debug.WriteLine($"New atomRef found: {CurRef}"); + // this is CML1 stuff, we get things like: + // a2 a2 a2 a2 a3 a3 + // a4 a4 a5 a6 a7 a9 a9 a11 a12 a13 a5 a4 a6 a9 a7 a8 a8 + // a10 1 1 1 1 2 1 2 + // 1 1 1 2 2 + try + { + bool countBonds = (BondCounter == 0) ? true : false; + var tokens = Strings.Tokenize(cData); + + foreach (var token in tokens) + { + if (countBonds) + { + BondCounter++; + } + Debug.WriteLine($"Token: {token}"); + + if (CurRef == 1) + { + BondARef1.Add(token); + } + else if (CurRef == 2) + { + BondARef2.Add(token); + } + } + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 194, 1); + } + break; + case "order": + Debug.WriteLine("New bond order found."); + + try + { + var tokens = Strings.Tokenize(cData); + + foreach (var token in tokens) + { + Debug.WriteLine($"Token: {token}"); + Order.Add(token); + } + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 194, 1); + } + break; + default: + break; } - else if (DICTREF.Equals("cdk:aromaticAtom")) + break; + case "integerArray": + Debug.WriteLine($"IntegerArray: builtin = {Builtin}"); + + switch (Builtin) { - AtomAromaticities.Add(cData.Trim()); + case "formalCharge": + try + { + var tokens = Strings.Tokenize(cData); + foreach (var token in tokens) + { + Debug.WriteLine($"Charge added: {token}"); + FormalCharges.Add(token); + } + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 205, 1); + } + break; + default: + break; + } + break; + case "scalar": + if (xpath.EndsWith("crystal", "scalar")) + { + Debug.WriteLine($"Going to set a crystal parameter: {CrystalScalar} to {cData}"); + try + { + UnitCellParams[CrystalScalar - 1] = double.Parse(cData.Trim(), NumberFormatInfo.InvariantInfo); + } + catch (FormatException) + { + Trace.TraceError($"Content must a float: {cData}"); + } } - else if (DICTREF.Equals("cdk:isotopicMass")) + else if (xpath.EndsWith("bond", "scalar")) { - ExactMasses.Add(cData.Trim()); + switch (DictRef) + { + case "mdl:stereo": + BondStereo.Add(cData.Trim()); + StereoGiven = true; + break; + default: + if (!BondCustomProperty.TryGetValue(BondId[BondId.Count - 1], out IDictionary bp)) + { + bp = new Dictionary(); + BondCustomProperty[BondId[BondId.Count - 1]] = bp; + } + bp[ElementTitle] = cData.Trim(); + break; + } } - else + else if (xpath.EndsWith("atom", "scalar")) { - if(!AtomCustomProperty.ContainsKey(AtomCounter - 1)) - AtomCustomProperty[AtomCounter - 1] = new List(); - AtomCustomProperty[AtomCounter - 1].Add(ElementTitle); - AtomCustomProperty[AtomCounter - 1].Add(cData.Trim()); + switch (DictRef) + { + case "cdk:partialCharge": + PartialCharges.Add(cData.Trim()); + break; + case "cdk:atomicNumber": + AtomicNumbers.Add(cData.Trim()); + break; + case "cdk:aromaticAtom": + AtomAromaticities.Add(cData.Trim()); + break; + case "cdk:isotopicMass": + ExactMasses.Add(cData.Trim()); + break; + default: + if (!AtomCustomProperty.ContainsKey(AtomCounter - 1)) + AtomCustomProperty[AtomCounter - 1] = new List(); + AtomCustomProperty[AtomCounter - 1].Add(ElementTitle); + AtomCustomProperty[AtomCounter - 1].Add(cData.Trim()); + break; + } } - } - else if (xpath.EndsWith("molecule", "scalar")) - { - if (DICTREF.Equals("pdb:id")) + else if (xpath.EndsWith("molecule", "scalar")) { - // cdo.SetObjectProperty("Molecule", DICTREF, cData); - CurrentMolecule.SetProperty(new DictRef(DICTREF, cData), cData); + switch (DictRef) + { + case "pdb:id": + CurrentMolecule.SetProperty(new DictRef(DictRef, cData), cData); + break; + case "cdk:molecularProperty": + CurrentMolecule.SetProperty(ElementTitle, cData); + break; + default: + MoleculeCustomProperty.Add(ElementTitle); + MoleculeCustomProperty.Add(cData.Trim()); + break; + } } - else if (DICTREF.Equals("cdk:molecularProperty")) + else if (xpath.EndsWith("reaction", "scalar")) { - CurrentMolecule.SetProperty(ElementTitle, cData); + switch (DictRef) + { + case "cdk:reactionProperty": + CurrentReaction.SetProperty(ElementTitle, cData); + break; + default: + break; + } } else { - MoleculeCustomProperty.Add(ElementTitle); - MoleculeCustomProperty.Add(cData.Trim()); - } - } - else if (xpath.EndsWith("reaction", "scalar")) - { - if (DICTREF.Equals("cdk:reactionProperty")) - { - CurrentReaction.SetProperty(ElementTitle, cData); - } - } - else - { - Trace.TraceWarning("Ignoring scalar: " + xpath); - } - } - else if ("floatArray".Equals(name)) - { - if (BUILTIN.Equals("x3")) - { - - try - { - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) - X3.Add(token); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 205, 1); - } - } - else if (BUILTIN.Equals("y3")) - { - - try - { - - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) - Y3.Add(token); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 213, 1); + Trace.TraceWarning("Ignoring scalar: " + xpath); } - } - else if (BUILTIN.Equals("z3")) - { - - try + break; + case "floatArray": + switch (Builtin) { + case "x3": + try + { + var tokens = Strings.Tokenize(cData); - var tokens = Strings.Tokenize(cData); - - foreach (var token in tokens) - Z3.Add(token); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 221, 1); - } - } - else if (BUILTIN.Equals("x2")) - { - Debug.WriteLine("New floatArray found."); + foreach (var token in tokens) + X3.Add(token); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 205, 1); + } + break; + case "y3": + try + { + var tokens = Strings.Tokenize(cData); - try - { - var tokens = Strings.Tokenize(cData); + foreach (var token in tokens) + Y3.Add(token); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 213, 1); + } + break; + case "z3": + try + { + var tokens = Strings.Tokenize(cData); - foreach (var token in tokens) - X2.Add(token); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 205, 1); - } - } - else if (BUILTIN.Equals("y2")) - { - Debug.WriteLine("New floatArray found."); + foreach (var token in tokens) + Z3.Add(token); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 221, 1); + } + break; + case "x2": + Debug.WriteLine("New floatArray found."); - try - { + try + { + var tokens = Strings.Tokenize(cData); - var tokens = Strings.Tokenize(cData); + foreach (var token in tokens) + X2.Add(token); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 205, 1); + } + break; + case "y2": + Debug.WriteLine("New floatArray found."); - foreach (var token in tokens) - Y2.Add(token); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 454, 1); - } - } - else if (BUILTIN.Equals("partialCharge")) - { - Debug.WriteLine("New floatArray with partial charges found."); + try + { + var tokens = Strings.Tokenize(cData); - try - { + foreach (var token in tokens) + Y2.Add(token); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 454, 1); + } + break; + case "partialCharge": + Debug.WriteLine("New floatArray with partial charges found."); - var tokens = Strings.Tokenize(cData); + try + { + var tokens = Strings.Tokenize(cData); - foreach (var token in tokens) - PartialCharges.Add(token); - } - catch (Exception e) - { - Notify("CMLParsing error: " + e, SYSTEMID, 462, 1); - } - } - } - else if ("basic".Equals(name)) - { - // assuming this is the child element of - this.InChIString = cData; - } - else if ("name".Equals(name)) - { - if (xpath.EndsWith("molecule", "name")) - { - if (DICTREF.Length > 0) - { - // cdo.SetObjectProperty("Molecule", DICTREF, cData); - CurrentMolecule.SetProperty(new DictRef(DICTREF, cData), cData); + foreach (var token in tokens) + PartialCharges.Add(token); + } + catch (Exception e) + { + Notify($"CMLParsing error: {e}", SYSTEMID, 462, 1); + } + break; } - else + break; + case "basic": + // assuming this is the child element of + this.InChIString = cData; + break; + case "name": + if (xpath.EndsWith("molecule", "name")) { - // cdo.SetObjectProperty("Molecule", "Name", cData); - CurrentMolecule.Title = cData; + if (DictRef.Length > 0) + { + CurrentMolecule.SetProperty(new DictRef(DictRef, cData), cData); + } + else + { + CurrentMolecule.Title = cData; + } } - } - } - else if ("formula".Equals(name)) - { - CurrentMolecule.SetProperty(CDKPropertyName.Formula, cData); - } - else - { - - Trace.TraceWarning("Skipping element: " + name); + break; + case "formula": + CurrentMolecule.SetProperty(CDKPropertyName.Formula, cData); + break; + default: + Trace.TraceWarning($"Skipping element: {name}"); + break; } - BUILTIN = ""; + Builtin = ""; ElementTitle = ""; } @@ -1519,19 +1459,18 @@ public virtual void CharacterData(CMLStack xpath, XElement element) Debug.WriteLine($"CD: {element.Value}"); } - protected void Notify(string message, string systemId, int line, int column) + protected virtual void Notify(string message, string systemId, int line, int column) { - Debug.WriteLine("Message: ", message); - Debug.WriteLine("SystemId: ", systemId); - Debug.WriteLine("Line: ", line); - Debug.WriteLine("Column: ", column); + Debug.WriteLine($"Message: {message}"); + Debug.WriteLine($"SystemId: {systemId}"); + Debug.WriteLine($"Line: {line}"); + Debug.WriteLine($"Column: {column}"); } protected virtual void StoreData() { if (InChIString != null) { - // cdo.SetObjectProperty("Molecule", "inchi", inchi); CurrentMolecule.SetProperty(CDKPropertyName.InChI, InChIString); } if (Formula != null && Formula.Count > 0) @@ -1571,7 +1510,7 @@ private void ConvertCMLToCDKHydrogenCounts() protected virtual void StoreAtomData() { - Debug.WriteLine("No atoms: ", AtomCounter); + Debug.WriteLine($"No atoms: {AtomCounter}"); if (AtomCounter == 0) { return; @@ -1637,8 +1576,7 @@ protected virtual void StoreAtomData() } else { - Debug.WriteLine("No 3D fractional info: " + XFract.Count, " " + YFract.Count, " " + ZFract.Count, " != " - + AtomCounter); + Debug.WriteLine("No 3D fractional info: " + XFract.Count, " " + YFract.Count, " " + ZFract.Count, " != " + AtomCounter); } if ((X2.Count == AtomCounter) && (Y2.Count == AtomCounter)) @@ -1750,13 +1688,11 @@ protected virtual void StoreAtomData() for (int i = 0; i < AtomCounter; i++) { Trace.TraceInformation("Storing atom: ", i); - // cdo.StartObject("Atom"); CurrentAtom = CurrentChemFile.Builder.NewAtom("H"); - Debug.WriteLine("Atom # " + AtomCounter); + Debug.WriteLine($"Atom # {AtomCounter}"); if (hasID) { - // cdo.SetObjectProperty("Atom", "id", (string)elid[i]); - Debug.WriteLine("id: ", (string)ElId[i]); + Debug.WriteLine($"id: {(string)ElId[i]}"); CurrentAtom.Id = (string)ElId[i]; AtomEnumeration[(string)ElId[i]] = CurrentAtom; } @@ -1765,28 +1701,25 @@ protected virtual void StoreAtomData() if (hasSymbols) { string symbol = (string)ElSym[i]; - if (symbol.Equals("Du") || symbol.Equals("Dummy")) - { - // cdo.SetObjectProperty("PseudoAtom", "label", (string)eltitles[i]); - if (!(CurrentAtom is IPseudoAtom)) - { - CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); - if (hasID) AtomEnumeration[(string)ElId[i]] = CurrentAtom; - } - ((IPseudoAtom)CurrentAtom).Label = (string)ElTitles[i]; - } - else + switch (symbol) { - // cdo.SetObjectProperty("Atom", "title", (string)eltitles[i]); - // FIXME: huh? - if (ElTitles[i] != null) - CurrentAtom.SetProperty(CDKPropertyName.Title, (string)ElTitles[i]); + case "Du": + case "Dummy": + if (!(CurrentAtom is IPseudoAtom)) + { + CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); + if (hasID) AtomEnumeration[(string)ElId[i]] = CurrentAtom; + } + ((IPseudoAtom)CurrentAtom).Label = (string)ElTitles[i]; + break; + default: + if (ElTitles[i] != null) + CurrentAtom.SetProperty(CDKPropertyName.Title, (string)ElTitles[i]); + break; } } else { - // cdo.SetObjectProperty("Atom", "title", (string)eltitles[i]); - // FIXME: huh? if (ElTitles[i] != null) CurrentAtom.SetProperty(CDKPropertyName.Title, (string)ElTitles[i]); } @@ -1796,16 +1729,23 @@ protected virtual void StoreAtomData() if (hasSymbols) { string symbol = (string)ElSym[i]; - if (symbol.Equals("Du") || symbol.Equals("Dummy")) - { - symbol = "R"; - } - // cdo.SetObjectProperty("Atom", "type", symbol); - if (symbol.Equals("R") && !(CurrentAtom is IPseudoAtom)) + switch (symbol) { - CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); - ((IPseudoAtom)CurrentAtom).Label = "R"; - if (hasID) AtomEnumeration[(string)ElId[i]] = CurrentAtom; + case "Du": + case "Dummy": + symbol = "R"; + break; + case "R": + if (!(CurrentAtom is IPseudoAtom)) + { + CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); + ((IPseudoAtom)CurrentAtom).Label = "R"; + if (hasID) + AtomEnumeration[(string)ElId[i]] = CurrentAtom; + } + break; + default: + break; } CurrentAtom.Symbol = symbol; if (!hasAtomicNumbers || AtomicNumbers[i] == null) @@ -1814,35 +1754,26 @@ protected virtual void StoreAtomData() if (has3D) { - // cdo.SetObjectProperty("Atom", "x3", (string)x3[i]); - // cdo.SetObjectProperty("Atom", "y3", (string)y3[i]); - // cdo.SetObjectProperty("Atom", "z3", (string)z3[i]); if (X3[i] != null && Y3[i] != null && Z3[i] != null) { CurrentAtom.Point3D = new Vector3( - double.Parse((string)X3[i]), - double.Parse((string)Y3[i]), - double.Parse((string)Z3[i])); + double.Parse((string)X3[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)Y3[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)Z3[i], NumberFormatInfo.InvariantInfo)); } } if (has3Dfract) { - // ok, need to convert fractional into eucledian coordinates - // cdo.SetObjectProperty("Atom", "xFract", (string)xfract[i]); - // cdo.SetObjectProperty("Atom", "yFract", (string)yfract[i]); - // cdo.SetObjectProperty("Atom", "zFract", (string)zfract[i]); CurrentAtom.FractionalPoint3D = new Vector3( - double.Parse((string)XFract[i]), - double.Parse((string)YFract[i]), - double.Parse((string)ZFract[i])); + double.Parse((string)XFract[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)YFract[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)ZFract[i], NumberFormatInfo.InvariantInfo)); } if (hasFormalCharge) { - // cdo.SetObjectProperty("Atom", "formalCharge", - // (string)formalCharges[i]); - CurrentAtom.FormalCharge = int.Parse((string)FormalCharges[i]); + CurrentAtom.FormalCharge = int.Parse((string)FormalCharges[i], NumberFormatInfo.InvariantInfo); } if (hasAtomAromaticities) @@ -1853,19 +1784,15 @@ protected virtual void StoreAtomData() if (hasPartialCharge) { Debug.WriteLine("Storing partial atomic charge..."); - // cdo.SetObjectProperty("Atom", "partialCharge", - // (string)partialCharges[i]); - CurrentAtom.Charge = double.Parse((string)PartialCharges[i]); + CurrentAtom.Charge = double.Parse((string)PartialCharges[i], NumberFormatInfo.InvariantInfo); } if (hasHCounts) { - // cdo.SetObjectProperty("Atom", "hydrogenCount", (string)hCounts[i]); - // ConvertCMLToCDKHydrogenCounts() is called to update hydrogen counts when molecule is stored string hCount = HCounts[i]; if (hCount != null) { - CurrentAtom.ImplicitHydrogenCount = int.Parse(hCount); + CurrentAtom.ImplicitHydrogenCount = int.Parse(hCount, NumberFormatInfo.InvariantInfo); } else { @@ -1877,25 +1804,21 @@ protected virtual void StoreAtomData() { if (X2[i] != null && Y2[i] != null) { - // cdo.SetObjectProperty("Atom", "x2", (string)x2[i]); - // cdo.SetObjectProperty("Atom", "y2", (string)y2[i]); CurrentAtom.Point2D = new Vector2( - double.Parse((string)X2[i]), - double.Parse((string)Y2[i])); + double.Parse((string)X2[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)Y2[i], NumberFormatInfo.InvariantInfo)); } } if (hasDictRefs) { - // cdo.SetObjectProperty("Atom", "dictRef", (string)atomDictRefs[i]); if (AtomDictRefs[i] != null) CurrentAtom.SetProperty("org.openscience.cdk.dict", (string)AtomDictRefs[i]); } if (hasSpinMultiplicities && SpinMultiplicities[i] != null) { - // cdo.SetObjectProperty("Atom", "spinMultiplicity", (string)spinMultiplicities[i]); - int unpairedElectrons = int.Parse((string)SpinMultiplicities[i]) - 1; + int unpairedElectrons = int.Parse((string)SpinMultiplicities[i], NumberFormatInfo.InvariantInfo) - 1; for (int sm = 0; sm < unpairedElectrons; sm++) { CurrentMolecule.SingleElectrons.Add(CurrentChemFile.Builder.NewSingleElectron(CurrentAtom)); @@ -1904,25 +1827,23 @@ protected virtual void StoreAtomData() if (hasOccupancies && Occupancies[i] != null) { - // cdo.SetObjectProperty("Atom", "occupanciy", (string)occupancies[i]); // FIXME: this has no ChemFileCDO equivalent, not even if spelled correctly } if (hasIsotopes) { - // cdo.SetObjectProperty("Atom", "massNumber", (string)isotope[i]); if (Isotope[i] != null) - CurrentAtom.MassNumber = (int)double.Parse((string)Isotope[i]); + CurrentAtom.MassNumber = (int)double.Parse((string)Isotope[i], NumberFormatInfo.InvariantInfo); } if (hasAtomicNumbers) { - if (AtomicNumbers[i] != null) CurrentAtom.AtomicNumber = int.Parse(AtomicNumbers[i]); + if (AtomicNumbers[i] != null) CurrentAtom.AtomicNumber = int.Parse(AtomicNumbers[i], NumberFormatInfo.InvariantInfo); } if (hasExactMasses) { - if (ExactMasses[i] != null) CurrentAtom.ExactMass = double.Parse(ExactMasses[i]); + if (ExactMasses[i] != null) CurrentAtom.ExactMass = double.Parse(ExactMasses[i], NumberFormatInfo.InvariantInfo); } if (AtomCustomProperty.TryGetValue(i, out IList property)) @@ -1936,9 +1857,6 @@ protected virtual void StoreAtomData() CurrentAtom.SetProperty(p1, p2); } } - - // cdo.EndObject("Atom"); - CurrentMolecule.Atoms.Add(CurrentAtom); } @@ -1948,7 +1866,7 @@ protected virtual void StoreAtomData() { try { - int parity = (int)Math.Round(double.Parse(AtomParities[i])); + int parity = (int)Math.Round(double.Parse(AtomParities[i], NumberFormatInfo.InvariantInfo)); //currentAtom.StereoParity = parity; IAtom ligandAtom1 = AtomEnumeration[ParityARef1[i]]; IAtom ligandAtom2 = AtomEnumeration[ParityARef2[i]]; @@ -1962,7 +1880,7 @@ protected virtual void StoreAtomData() } catch (FormatException e) { - if (!e.Message.Equals("empty string")) + if (!string.Equals(e.Message, "empty string", StringComparison.Ordinal)) { Trace.TraceWarning("Cannot interpret stereo information: " + AtomParities[i]); } @@ -1979,8 +1897,7 @@ protected virtual void StoreAtomData() protected virtual void StoreBondData() { - Debug.WriteLine("Testing a1,a2,stereo,order = count: " + BondARef1.Count, "," + BondARef2.Count, "," - + BondStereo.Count, "," + Order.Count, "=" + BondCounter); + Debug.WriteLine($"Testing a1,a2,stereo,order = count: {BondARef1.Count}, {BondARef2.Count}, {BondStereo.Count}, {Order.Count} = {BondCounter}"); if ((BondARef1.Count == BondCounter) && (BondARef2.Count == BondCounter)) { @@ -1996,16 +1913,6 @@ protected virtual void StoreBondData() while (bar1s.MoveNext()) { bar2s.MoveNext(); - // cdo.StartObject("Bond"); - // if (ids.HasNext()) { - // cdo.SetObjectProperty("Bond", "id", (string)ids.Next()); - // } - // cdo.SetObjectProperty("Bond", "atom1", - // int.Parse(bondElid.IndexOf( - // (string)bar1s.Next())).ToString()); - // cdo.SetObjectProperty("Bond", "atom2", - // int.Parse(bondElid.IndexOf( - // (string)bar2s.Next())).ToString()); IAtom a1 = (IAtom)AtomEnumeration[(string)bar1s.Current]; IAtom a2 = (IAtom)AtomEnumeration[(string)bar2s.Current]; CurrentBond = CurrentChemFile.Builder.NewBond(a1, a2); @@ -2018,50 +1925,44 @@ protected virtual void StoreBondData() { string bondOrder = (string)orders.Current; - if ("S".Equals(bondOrder)) - { - // cdo.SetObjectProperty("Bond", "order", "1"); - CurrentBond.Order = BondOrder.Single; - } - else if ("D".Equals(bondOrder)) - { - // cdo.SetObjectProperty("Bond", "order", "2"); - CurrentBond.Order = BondOrder.Double; - } - else if ("T".Equals(bondOrder)) - { - // cdo.SetObjectProperty("Bond", "order", "3"); - CurrentBond.Order = BondOrder.Triple; - } - else if ("A".Equals(bondOrder)) - { - // cdo.SetObjectProperty("Bond", "order", "1.5"); - CurrentBond.Order = BondOrder.Single; - CurrentBond.IsAromatic = true; - } - else + switch (bondOrder) { - // cdo.SetObjectProperty("Bond", "order", bondOrder); - CurrentBond.Order = BondManipulator.CreateBondOrder(double.Parse(bondOrder)); + case "S": + CurrentBond.Order = BondOrder.Single; + break; + case "D": + CurrentBond.Order = BondOrder.Double; + break; + case "T": + CurrentBond.Order = BondOrder.Triple; + break; + case "A": + CurrentBond.Order = BondOrder.Single; + CurrentBond.IsAromatic = true; + break; + default: + CurrentBond.Order = BondManipulator.CreateBondOrder(double.Parse(bondOrder, NumberFormatInfo.InvariantInfo)); + break; } } if (stereos.MoveNext()) { - // cdo.SetObjectProperty("Bond", "stereo", - // (string)stereos.Next()); string nextStereo = (string)stereos.Current; - if ("H".Equals(nextStereo)) - { - CurrentBond.Stereo = NCDK.BondStereo.Down; - } - else if ("W".Equals(nextStereo)) - { - CurrentBond.Stereo = NCDK.BondStereo.Up; - } - else if (nextStereo != null) + switch (nextStereo) { - Trace.TraceWarning("Cannot interpret stereo information: " + nextStereo); + case "H": + CurrentBond.Stereo = NCDK.BondStereo.Down; + break; + case "W": + CurrentBond.Stereo = NCDK.BondStereo.Up; + break; + default: + if (nextStereo != null) + { + Trace.TraceWarning("Cannot interpret stereo information: " + nextStereo); + } + break; } } @@ -2086,13 +1987,12 @@ protected virtual void StoreBondData() } } - // cdo.EndObject("Bond"); CurrentMolecule.Bonds.Add(CurrentBond); } } } - protected int AddArrayElementsTo(IList toAddto, string array) + protected virtual int AddArrayElementsTo(IList toAddto, string array) { int i = 0; var tokens = Strings.Tokenize(array); @@ -2105,4 +2005,3 @@ protected int AddArrayElementsTo(IList toAddto, string array) } } } - diff --git a/NCDK/IO/CML/CMLHandler.cs b/NCDK/IO/CML/CMLHandler.cs index 1ffc02f5..cce3ffb9 100644 --- a/NCDK/IO/CML/CMLHandler.cs +++ b/NCDK/IO/CML/CMLHandler.cs @@ -75,7 +75,7 @@ public override void CharacterData(XElement element) conv.CharacterData(xpath, element); } - public void DoctypeDecl(string name, string publicId, string systemId) { } + public static void DoctypeDecl(string name, string publicId, string systemId) { } /// /// Calling this procedure signals the end of the XML document. @@ -114,7 +114,7 @@ public override void StartElement(XElement element) { // e.g. reactionList, reaction -> CRML module Trace.TraceInformation("Detected CRML module"); - if (!conventionStack.Peek().Equals("CMLR")) + if (!string.Equals(conventionStack.Peek(), "CMLR", StringComparison.Ordinal)) { conv = new CMLReactionModule(conv); } @@ -130,7 +130,7 @@ public override void StartElement(XElement element) { convName = element.Attribute(Attribute_convention).Value; } - if (convName == "") + if (convName.Length == 0) { // no convention set/reset: take convention of parent conventionStack.Push(conventionStack.Peek()); @@ -138,51 +138,50 @@ public override void StartElement(XElement element) else if (convName.Length > 0) { - if (convName.Equals(conventionStack.Peek())) + if (convName.Equals(conventionStack.Peek(), StringComparison.Ordinal)) { Debug.WriteLine("Same convention as parent"); } else { Trace.TraceInformation("New Convention: ", convName); - if (convName.Equals("CML")) + switch (convName) { - // Don't reset the convention handler to CMLCore, - // becuase all handlers should extend this handler, and - // use it for any content other then specifically put - // into the specific convention - } - else if (convName.Equals("PDB")) - { - conv = new PDBConvention(conv); - } - else if (convName.Equals("PMP")) - { - conv = new PMPConvention(conv); - } - else if (convName.Equals("MDLMol")) - { - Debug.WriteLine("MDLMolConvention instantiated..."); - conv = new MDLMolConvention(conv); - } - else if (convName.Equals("JMOL-ANIMATION")) - { - conv = new JMOLANIMATIONConvention(conv); - } - else if (convName.Equals("qsar:DescriptorValue")) - { - conv = new QSARConvention(conv); - } - else if (userConventions.ContainsKey(convName)) - { - //unknown convention. userConvention? - ICMLModule newconv = (ICMLModule)userConventions[convName]; - newconv.Inherit(conv); - conv = newconv; - } - else - { - Trace.TraceWarning($"Detected unknown convention: {convName}"); + case "CML": + // Don't reset the convention handler to CMLCore, + // becuase all handlers should extend this handler, and + // use it for any content other then specifically put + // into the specific convention + break; + case "PDB": + conv = new PDBConvention(conv); + break; + case "PMP": + conv = new PMPConvention(conv); + break; + case "MDLMol": + Debug.WriteLine("MDLMolConvention instantiated..."); + conv = new MDLMolConvention(conv); + break; + case "JMOL-ANIMATION": + conv = new JMOLANIMATIONConvention(conv); + break; + case "qsar:DescriptorValue": + conv = new QSARConvention(conv); + break; + default: + if (userConventions.ContainsKey(convName)) + { + //unknown convention. userConvention? + ICMLModule newconv = (ICMLModule)userConventions[convName]; + newconv.Inherit(conv); + conv = newconv; + } + else + { + Trace.TraceWarning($"Detected unknown convention: {convName}"); + } + break; } } conventionStack.Push(convName); diff --git a/NCDK/IO/CML/CMLReactionModule.cs b/NCDK/IO/CML/CMLReactionModule.cs index 00f63bd6..93adb543 100644 --- a/NCDK/IO/CML/CMLReactionModule.cs +++ b/NCDK/IO/CML/CMLReactionModule.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml.Linq; @@ -48,7 +49,7 @@ public CMLReactionModule(ICMLModule conv) public override void StartElement(CMLStack xpath, XElement element) { - if ("reaction".Equals(element.Name.LocalName)) + if (string.Equals("reaction", element.Name.LocalName, StringComparison.Ordinal)) { // cdo.StartObject("Reaction"); if (CurrentReactionSet == null) @@ -58,7 +59,7 @@ public override void StartElement(CMLStack xpath, XElement element) if (id != null) CurrentReaction.Id = id; // cdo.SetObjectProperty("Reaction", "id", id); } - else if ("reactionList".Equals(element.Name.LocalName)) + else if (string.Equals("reactionList", element.Name.LocalName, StringComparison.Ordinal)) { // cdo.StartObject("ReactionSet"); CurrentReactionSet = CurrentChemFile.Builder.NewReactionSet(); @@ -66,7 +67,7 @@ public override void StartElement(CMLStack xpath, XElement element) if (id != null) CurrentReactionSet.Id = id; // cdo.SetObjectProperty("reactionList", "id", id); } - else if ("reactant".Equals(element.Name.LocalName)) + else if (string.Equals("reactant", element.Name.LocalName, StringComparison.Ordinal)) { // cdo.StartObject("Reactant"); if (CurrentReaction == null) @@ -89,7 +90,7 @@ public override void StartElement(CMLStack xpath, XElement element) } // cdo.SetObjectProperty("Reactant", "id", id); } - else if ("product".Equals(element.Name.LocalName)) + else if (string.Equals("product", element.Name.LocalName, StringComparison.Ordinal)) { // cdo.StartObject("Product"); if (CurrentReaction == null) @@ -112,7 +113,7 @@ public override void StartElement(CMLStack xpath, XElement element) } // cdo.SetObjectProperty("Product", "id", id); } - else if ("substance".Equals(element.Name.LocalName)) + else if (string.Equals("substance", element.Name.LocalName, StringComparison.Ordinal)) { // cdo.StartObject("Agent"); if (CurrentReaction == null) @@ -135,7 +136,7 @@ public override void StartElement(CMLStack xpath, XElement element) } // cdo.SetObjectProperty("Agent", "id", id); } - else if ("molecule".Equals(element.Name.LocalName)) + else if (string.Equals("molecule", element.Name.LocalName, StringComparison.Ordinal)) { // clear existing molecule data base.NewMolecule(); @@ -183,44 +184,35 @@ public override void EndElement(CMLStack xpath, XElement element) { var local = element.Name.LocalName; - if ("reaction".Equals(local)) + switch (local) { - // cdo.EndObject("Reaction"); - CurrentReactionSet.Add(CurrentReaction); - CurrentChemModel.ReactionSet = CurrentReactionSet; - } - else if ("reactionList".Equals(local)) - { - // cdo.EndObject("ReactionSet"); - CurrentChemModel.ReactionSet = CurrentReactionSet; - /* FIXME: this should be when document is closed! */ - } - else if ("reactant".Equals(local)) - { - // cdo.EndObject("Reactant"); - CurrentReaction.Reactants.Add(CurrentMolecule); - } - else if ("product".Equals(local)) - { - // cdo.EndObject("Product"); - CurrentReaction.Products.Add(CurrentMolecule); - } - else if ("substance".Equals(local)) - { - // cdo.EndObject("Agent"); - CurrentReaction.Agents.Add(CurrentMolecule); - } - else if ("molecule".Equals(local)) - { - Debug.WriteLine("Storing Molecule"); - //if the current molecule exists in the currentMoleculeSet means that is a reference in these. - if (CurrentMoleculeSet.GetMultiplier(CurrentMolecule) == -1) base.StoreData(); - // do nothing else but store atom/bond information - } - else - { - base.EndElement(xpath, element); - } + case "reaction": + CurrentReactionSet.Add(CurrentReaction); + CurrentChemModel.ReactionSet = CurrentReactionSet; + break; + case "reactionList": + CurrentChemModel.ReactionSet = CurrentReactionSet; + /* FIXME: this should be when document is closed! */ + break; + case "reactant": + CurrentReaction.Reactants.Add(CurrentMolecule); + break; + case "product": + CurrentReaction.Products.Add(CurrentMolecule); + break; + case "substance": + CurrentReaction.Agents.Add(CurrentMolecule); + break; + case "molecule": + Debug.WriteLine("Storing Molecule"); + //if the current molecule exists in the currentMoleculeSet means that is a reference in these. + if (CurrentMoleculeSet.GetMultiplier(CurrentMolecule) == -1) base.StoreData(); + // do nothing else but store atom/bond information + break; + default: + base.EndElement(xpath, element); + break; + } } /// @@ -229,11 +221,12 @@ public override void EndElement(CMLStack xpath, XElement element) /// Molecules /// The ID the look /// The IAtomContainer with the ID - private IAtomContainer GetMoleculeFromID(IEnumerable molSet, string id) + private static IAtomContainer GetMoleculeFromID(IEnumerable molSet, string id) { foreach (var mol in molSet) { - if (mol.Id.Equals(id)) return mol; + if (string.Equals(mol.Id, id, StringComparison.Ordinal)) + return mol; } return null; } diff --git a/NCDK/IO/CML/CMLResolver.cs b/NCDK/IO/CML/CMLResolver.cs index c5cefcaa..7beaa027 100644 --- a/NCDK/IO/CML/CMLResolver.cs +++ b/NCDK/IO/CML/CMLResolver.cs @@ -37,15 +37,19 @@ public class CMLResolver : XmlResolver public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { Debug.WriteLine(nameof(CMLResolver) + ": resolving " + absoluteUri); +#pragma warning disable CA1308 // Normalize strings to uppercase var systemId = absoluteUri.AbsolutePath.ToLowerInvariant(); - if ((systemId.IndexOf("cml-1999-05-15.dtd") != -1) || (systemId.IndexOf("cml.dtd") != -1) - || (systemId.IndexOf("cml1_0.dtd") != -1)) +#pragma warning restore CA1308 // Normalize strings to uppercase + if (systemId.Contains("cml-1999-05-15.dtd") + || systemId.Contains("cml.dtd") + || systemId.Contains("cml1_0.dtd")) { Trace.TraceInformation("File has CML 1.0 DTD"); return GetCMLType("cml1_0.dtd"); } - else if ((systemId.IndexOf("cml-2001-04-06.dtd") != -1) || (systemId.IndexOf("cml1_0_1.dtd") != -1) - || (systemId.IndexOf("cml_1_0_1.dtd") != -1)) + else if (systemId.Contains("cml-2001-04-06.dtd") + || systemId.Contains("cml1_0_1.dtd") + || systemId.Contains("cml_1_0_1.dtd")) { Trace.TraceInformation("File has CML 1.0.1 DTD"); return GetCMLType("cml1_0_1.dtd"); @@ -64,7 +68,7 @@ public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToRe /// /// the name of the CML DTD version /// the InputSource to the CML DTD - private Stream GetCMLType(string type) + private static Stream GetCMLType(string type) { try { diff --git a/NCDK/IO/CML/CMLStack.cs b/NCDK/IO/CML/CMLStack.cs index c0c1f231..8511467b 100644 --- a/NCDK/IO/CML/CMLStack.cs +++ b/NCDK/IO/CML/CMLStack.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -33,7 +34,9 @@ namespace NCDK.IO.CML // @cdk.module io // @cdk.githash // @cdk.keyword stack +#pragma warning disable CA1010 // Collections should implement generic interface public sealed class CMLStack : Stack +#pragma warning restore CA1010 // Collections should implement generic interface { /// A string representation of the stack. public override string ToString() @@ -55,7 +58,7 @@ public override string ToString() /// internal bool EndsWith(string lastElement) { - return Peek().Equals(lastElement); + return string.Equals(Peek(), lastElement, StringComparison.Ordinal); } /// @@ -66,7 +69,7 @@ internal bool EndsWith(string lastElement) /// internal bool EndsWith(string oneButLast, string lastElement) { - return EndsWith(lastElement) && this.ElementAt(1).Equals(oneButLast); + return EndsWith(lastElement) && string.Equals(this.ElementAt(1), oneButLast, StringComparison.Ordinal); } /// @@ -74,7 +77,7 @@ internal bool EndsWith(string oneButLast, string lastElement) /// internal bool EndsWith(string twoButLast, string oneButLast, string lastElement) { - return EndsWith(oneButLast, lastElement) && this.ElementAt(2).Equals(twoButLast); + return EndsWith(oneButLast, lastElement) && string.Equals(this.ElementAt(2), twoButLast, StringComparison.Ordinal); } } } \ No newline at end of file diff --git a/NCDK/IO/CML/JMOLANIMATIONConvention.cs b/NCDK/IO/CML/JMOLANIMATIONConvention.cs index 91a47d28..de99eaaa 100644 --- a/NCDK/IO/CML/JMOLANIMATIONConvention.cs +++ b/NCDK/IO/CML/JMOLANIMATIONConvention.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Diagnostics; using System.Xml.Linq; @@ -50,28 +51,28 @@ public JMOLANIMATIONConvention(ICMLModule conv) public override void StartElement(CMLStack xpath, XElement element) { string name = element.Name.LocalName; - if (name.Equals("list")) + if (string.Equals(name, "list", StringComparison.Ordinal)) { Debug.WriteLine("Oke, JMOLANIMATION seems to be kicked in :)"); // cdo.StartObject("Animation"); CurrentChemSequence = CurrentChemFile.Builder.NewChemSequence(); base.StartElement(xpath, element); } - else if (name.Equals("molecule")) + else if (string.Equals(name, "molecule", StringComparison.Ordinal)) { // cdo.StartObject("Frame"); CurrentChemModel = CurrentChemFile.Builder.NewChemModel(); Debug.WriteLine("New frame being parsed."); base.StartElement(xpath, element); } - else if (name.Equals("float")) + else if (string.Equals(name, "float", StringComparison.Ordinal)) { bool isEnergy = false; Debug.WriteLine("FLOAT found!"); foreach (var att in element.Attributes()) { - Debug.WriteLine(" att: ", att.Name.LocalName, " -> ", att.Value); - if (att.Name.LocalName.Equals("title") && att.Value.Equals("FRAME_ENERGY")) + Debug.WriteLine($" att: {att.Name.LocalName} -> {att.Value}"); + if (att.Name.LocalName.Equals("title", StringComparison.Ordinal) && att.Value.Equals("FRAME_ENERGY", StringComparison.Ordinal)) { isEnergy = true; } @@ -103,13 +104,13 @@ public override void EndElement(CMLStack xpath, XElement element) current = Unknown; frame_energy = ""; } - else if (name.Equals("list")) + else if (string.Equals(name, "list", StringComparison.Ordinal)) { base.EndElement(xpath, element); // cdo.EndObject("Animation"); CurrentChemFile.Add(CurrentChemSequence); } - else if (name.Equals("molecule")) + else if (string.Equals(name, "molecule", StringComparison.Ordinal)) { base.EndElement(xpath, element); // cdo.EndObject("Frame"); diff --git a/NCDK/IO/CML/MDLMolConvention.cs b/NCDK/IO/CML/MDLMolConvention.cs index 610b8660..c8c0ac88 100644 --- a/NCDK/IO/CML/MDLMolConvention.cs +++ b/NCDK/IO/CML/MDLMolConvention.cs @@ -59,18 +59,19 @@ public override void StartElement(CMLStack xpath, XElement element) public override void CharacterData(CMLStack xpath, XElement element) { string s = element.Value.Trim(); - if (xpath.ToString().EndsWith("string/", StringComparison.Ordinal) && BUILTIN.Equals("stereo")) + if (xpath.ToString().EndsWith("string/", StringComparison.Ordinal) && Builtin.Equals("stereo", StringComparison.Ordinal)) { StereoGiven = true; - if (s.Trim().Equals("W")) + switch (s.Trim()) { - Debug.WriteLine("CML W stereo found"); - BondStereo.Add("1"); - } - else if (s.Trim().Equals("H")) - { - Debug.WriteLine("CML H stereo found"); - BondStereo.Add("6"); + case "W": + Debug.WriteLine("CML W stereo found"); + BondStereo.Add("1"); + break; + case "H": + Debug.WriteLine("CML H stereo found"); + BondStereo.Add("6"); + break; } } else diff --git a/NCDK/IO/CML/PDBConvention.cs b/NCDK/IO/CML/PDBConvention.cs index 57d10f7d..16fb1258 100644 --- a/NCDK/IO/CML/PDBConvention.cs +++ b/NCDK/IO/CML/PDBConvention.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Xml.Linq; namespace NCDK.IO.CML @@ -95,103 +96,120 @@ public override void StartElement(CMLStack xpath, XElement element) { string name = element.Name.LocalName; isELSYM = false; - if ("molecule".Equals(name)) + if (string.Equals("molecule", name, StringComparison.Ordinal)) { foreach (var attj in element.Attributes()) { Debug.WriteLine("StartElement"); - BUILTIN = ""; - DICTREF = ""; + Builtin = ""; + DictRef = ""; foreach (var atti in element.Attributes()) { string qname = atti.Name.LocalName; - if (qname.Equals("builtin")) + switch (qname) { - BUILTIN = atti.Value; - Debug.WriteLine(name, "->BUILTIN found: ", atti.Value); + case "builtin": + Builtin = atti.Value; + Debug.WriteLine($"{name}->BUILTIN found: {atti.Value}"); + break; + case "dictRef": + DictRef = atti.Value; + Debug.WriteLine($"{name}->DICTREF found: {atti.Value}"); + break; + case "title": + ElementTitle = atti.Value; + Debug.WriteLine($"{name}->TITLE found: {atti.Value}"); + break; + default: + Debug.WriteLine($"Qname: {qname}"); + break; } - else if (qname.Equals("dictRef")) - { - DICTREF = atti.Value; - Debug.WriteLine(name, "->DICTREF found: ", atti.Value); - } - else if (qname.Equals("title")) - { - ElementTitle = atti.Value; - Debug.WriteLine(name, "->TITLE found: ", atti.Value); - } - else - { - Debug.WriteLine("Qname: ", qname); - } - } - if (attj.Name.LocalName.Equals("convention") && attj.Value.Equals("PDB")) - { - // cdo.StartObject("PDBPolymer"); - CurrentStrand = CurrentChemFile.Builder.NewStrand(); - CurrentStrand.StrandName = "A"; - CurrentMolecule = CurrentChemFile.Builder.NewPDBPolymer(); } - else if (attj.Name.LocalName.Equals("dictRef") && attj.Value.Equals("pdb:sequence")) - { - NewSequence(); - BUILTIN = ""; - foreach (var atti in element.Attributes()) - { - if (atti.Name.LocalName.Equals("id")) + switch (attj.Name.LocalName) + { + case "convention": + if (string.Equals(attj.Value, "PDB", StringComparison.Ordinal)) { - // cdo.SetObjectProperty("Molecule", "id", atts.GetValue(i)); - CurrentMolecule.Id = atti.Value; + // cdo.StartObject("PDBPolymer"); + CurrentStrand = CurrentChemFile.Builder.NewStrand(); + CurrentStrand.StrandName = "A"; + CurrentMolecule = CurrentChemFile.Builder.NewPDBPolymer(); } - else if (atti.Name.LocalName.Equals("dictRef")) + break; + case "dictRef": + if (string.Equals(attj.Value, "pdb:sequence", StringComparison.Ordinal)) { - // cdo.SetObjectProperty("Molecule", "dictRef", atts.GetValue(i)); - // FIXME: has no equivalent in ChemFileCDO + NewSequence(); + Builtin = ""; + foreach (var atti in element.Attributes()) + { + if (string.Equals(atti.Name.LocalName, "id", StringComparison.Ordinal)) + { + // cdo.SetObjectProperty("Molecule", "id", atts.GetValue(i)); + CurrentMolecule.Id = atti.Value; + } + else if (string.Equals(atti.Name.LocalName, "dictRef", StringComparison.Ordinal)) + { + // cdo.SetObjectProperty("Molecule", "dictRef", atts.GetValue(i)); + // FIXME: has no equivalent in ChemFileCDO + } + } } - } - - } - else if (attj.Name.LocalName.Equals("title") && attj.Value.Equals("connections")) - { - // assume that Atom's have been read - Debug.WriteLine("Assuming that Atom's have been read: storing them"); - base.StoreAtomData(); - connectionTable = true; - Debug.WriteLine("Start Connection Table"); - } - else if (attj.Name.LocalName.Equals("title") && attj.Value.Equals("connect")) - { - Debug.WriteLine("New connection"); - isBond = true; - } - else if (attj.Name.LocalName.Equals("id") && isBond) - { - connect_root = attj.Value; + break; + case "title": + switch (attj.Value) + { + case "connections": + { + // assume that Atom's have been read + Debug.WriteLine("Assuming that Atom's have been read: storing them"); + base.StoreAtomData(); + connectionTable = true; + Debug.WriteLine("Start Connection Table"); + } + break; + case "connect": + { + Debug.WriteLine("New connection"); + isBond = true; + } + break; + default: + break; + } + break; + case "id": + if (isBond) + { + connect_root = attj.Value; + } + break; + default: + // ignore other list items at this moment + break; } - - // ignore other list items at this moment } } - else if ("scalar".Equals(name)) + else if (string.Equals("scalar", name, StringComparison.Ordinal)) { hasScalar = true; foreach (var atti in element.Attributes()) { - if (atti.Name.LocalName.Equals("dictRef")) idValue = atti.Value; + if (string.Equals(atti.Name.LocalName, "dictRef", StringComparison.Ordinal)) idValue = atti.Value; } } - else if ("label".Equals(name)) + else if (string.Equals("label", name, StringComparison.Ordinal)) { hasScalar = true; foreach (var atti in element.Attributes()) { - if (atti.Name.LocalName.Equals("dictRef")) idValue = atti.Value; + if (string.Equals(atti.Name.LocalName, "dictRef", StringComparison.Ordinal)) idValue = atti.Value; } } - else if ("atom".Equals(name)) + else if (string.Equals("atom", name, StringComparison.Ordinal)) { base.StartElement(xpath, element); } @@ -219,32 +237,36 @@ public override void EndElement(CMLStack xpath, XElement element) string name = element.Name.LocalName; // OLD +++++++++++++++++++++++++++++++++++++++++++++ - if (name.Equals("list") && connectionTable && !isBond) - { - Debug.WriteLine("End Connection Table"); - connectionTable = false; - // OLD +++++++++++++++++++++++++++++++++++++++++++++ - - } - else if (name.Equals("molecule")) + switch (name) { - StoreData(); - if (xpath.Count == 1) - { - // cdo.EndObject("Molecule"); - if (CurrentMolecule is IAtomContainer) + case "list": + if (connectionTable && !isBond) { - Debug.WriteLine("Adding molecule to set"); - CurrentMoleculeSet.Add(CurrentMolecule); - Debug.WriteLine("#mols in set: " + CurrentMoleculeSet.Count); + Debug.WriteLine("End Connection Table"); + connectionTable = false; + // OLD +++++++++++++++++++++++++++++++++++++++++++++ + } - else if (CurrentMolecule is ICrystal) + break; + case "molecule": + StoreData(); + if (xpath.Count == 1) { - Debug.WriteLine("Adding crystal to chemModel"); - CurrentChemModel.Crystal = (ICrystal)CurrentMolecule; - CurrentChemSequence.Add(CurrentChemModel); + // cdo.EndObject("Molecule"); + if (CurrentMolecule is IAtomContainer) + { + Debug.WriteLine("Adding molecule to set"); + CurrentMoleculeSet.Add(CurrentMolecule); + Debug.WriteLine($"#mols in set: {CurrentMoleculeSet.Count}"); + } + else if (CurrentMolecule is ICrystal) + { + Debug.WriteLine("Adding crystal to chemModel"); + CurrentChemModel.Crystal = (ICrystal)CurrentMolecule; + CurrentChemSequence.Add(CurrentChemModel); + } } - } + break; } isELSYM = false; isBond = false; @@ -262,33 +284,48 @@ public override void CharacterData(CMLStack xpath, XElement element) dictpdb += st1token; dictpdb += " "; } - if (dictpdb.Length > 0 && !idValue.Equals("pdb:record")) + if (dictpdb.Length > 0 && !idValue.Equals("pdb:record", StringComparison.Ordinal)) dictpdb = dictpdb.Substring(0, dictpdb.Length - 1); - if (idValue.Equals("pdb:altLoc")) - altLocV.Add(dictpdb); - else if (idValue.Equals("pdb:chainID")) - chainIDV.Add(dictpdb); - else if (idValue.Equals("pdb:hetAtom")) - hetAtomV.Add(dictpdb); - else if (idValue.Equals("pdb:iCode")) - iCodeV.Add(dictpdb); - else if (idValue.Equals("pdb:name")) - nameV.Add(dictpdb); - else if (idValue.Equals("pdb:oxt")) - oxtV.Add(dictpdb); - else if (idValue.Equals("pdb:record")) - recordV.Add(dictpdb); - else if (idValue.Equals("pdb:resName")) - resNameV.Add(dictpdb); - else if (idValue.Equals("pdb:resSeq")) - resSeqV.Add(dictpdb); - else if (idValue.Equals("pdb:segID")) - segIDV.Add(dictpdb); - else if (idValue.Equals("pdb:serial")) - serialV.Add(dictpdb); - else if (idValue.Equals("pdb:tempFactor")) tempFactorV.Add(dictpdb); - + switch (idValue) + { + case "pdb:altLoc": + altLocV.Add(dictpdb); + break; + case "pdb:chainID": + chainIDV.Add(dictpdb); + break; + case "pdb:hetAtom": + hetAtomV.Add(dictpdb); + break; + case "pdb:iCode": + iCodeV.Add(dictpdb); + break; + case "pdb:name": + nameV.Add(dictpdb); + break; + case "pdb:oxt": + oxtV.Add(dictpdb); + break; + case "pdb:record": + recordV.Add(dictpdb); + break; + case "pdb:resName": + resNameV.Add(dictpdb); + break; + case "pdb:resSeq": + resSeqV.Add(dictpdb); + break; + case "pdb:segID": + segIDV.Add(dictpdb); + break; + case "pdb:serial": + serialV.Add(dictpdb); + break; + case "pdb:tempFactor": + tempFactorV.Add(dictpdb); + break; + } idValue = ""; if (isELSYM) @@ -297,24 +334,17 @@ public override void CharacterData(CMLStack xpath, XElement element) } else if (isBond) { - Debug.WriteLine("CD (bond): " + s); + Debug.WriteLine($"CD (bond): {s}"); if (connect_root.Length > 0) { var tokens = s.Split(' '); foreach (var atom in tokens) { - if (!atom.Equals("0")) + if (!string.Equals(atom, "0", StringComparison.Ordinal)) { Debug.WriteLine("new bond: " + connect_root + "-" + atom); - // cdo.StartObject("Bond"); - // int atom1 = int.Parse(connect_root) - 1; - // int atom2 = int.Parse(atom) - 1; - // cdo.SetObjectProperty("Bond", "atom1", - // (new Integer(atom1)).ToString()); - // cdo.SetObjectProperty("Bond", "atom2", - // (new Integer(atom2)).ToString()); - CurrentBond = CurrentMolecule.Builder.NewBond(CurrentMolecule.Atoms[int.Parse(connect_root) - 1], - CurrentMolecule.Atoms[int.Parse(atom) - 1], BondOrder.Single); + CurrentBond = CurrentMolecule.Builder.NewBond(CurrentMolecule.Atoms[int.Parse(connect_root, NumberFormatInfo.InvariantInfo) - 1], + CurrentMolecule.Atoms[int.Parse(atom, NumberFormatInfo.InvariantInfo) - 1], BondOrder.Single); CurrentMolecule.Bonds.Add(CurrentBond); } } @@ -335,7 +365,7 @@ protected override void StoreData() protected override void StoreAtomData() { - Debug.WriteLine("No atoms: ", AtomCounter); + Debug.WriteLine($"No atoms: {AtomCounter}"); if (AtomCounter == 0) { return; @@ -474,18 +504,15 @@ protected override void StoreAtomData() } if (AtomCounter > 0) { - // cdo.StartObject("PDBMonomer"); CurrentMonomer = CurrentChemFile.Builder.NewPDBMonomer(); } for (int i = 0; i < AtomCounter; i++) { Trace.TraceInformation("Storing atom: ", i); - // cdo.StartObject("PDBAtom"); CurrentAtom = CurrentChemFile.Builder.NewPDBAtom("H"); if (hasID) { - // cdo.SetObjectProperty("Atom", "id", (string)elid[i]); CurrentAtom.Id = (string)ElId[i]; } if (hasTitles) @@ -493,26 +520,25 @@ protected override void StoreAtomData() if (hasSymbols) { string symbol = (string)ElSym[i]; - if (symbol.Equals("Du") || symbol.Equals("Dummy")) - { - // cdo.SetObjectProperty("PseudoAtom", "label", (string)eltitles[i]); - if (!(CurrentAtom is IPseudoAtom)) - { - CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); - } - ((IPseudoAtom)CurrentAtom).Label = (string)ElTitles[i]; - } - else + switch (symbol) { - // cdo.SetObjectProperty("Atom", "title", (string)eltitles[i]); - // FIXME: is a guess, Atom.title is not found in ChemFileCDO - CurrentAtom.SetProperty(CDKPropertyName.Title, (string)ElTitles[i]); + case "Du": + case "Dummy": + if (!(CurrentAtom is IPseudoAtom)) + { + CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); + } + ((IPseudoAtom)CurrentAtom).Label = (string)ElTitles[i]; + break; + default: + // FIXME: is a guess, Atom.title is not found in ChemFileCDO + CurrentAtom.SetProperty(CDKPropertyName.Title, (string)ElTitles[i]); + break; } } else { - // cdo.SetObjectProperty("Atom", "title", (string)eltitles[i]); - // FIXME: is a guess, Atom.title is not found in ChemFileCDO + // FIXME: is a guess, Atom.title is not found in ChemFileCDO CurrentAtom.SetProperty(CDKPropertyName.Title, (string)ElTitles[i]); } } @@ -521,81 +547,70 @@ protected override void StoreAtomData() if (hasSymbols) { string symbol = (string)ElSym[i]; - if (symbol.Equals("Du") || symbol.Equals("Dummy")) + switch (symbol) { - symbol = "R"; + case "Du": + case "Dummy": + symbol = "R"; + break; } - // cdo.SetObjectProperty("Atom", "type", symbol); - if (symbol.Equals("R") && !(CurrentAtom is IPseudoAtom)) + if (symbol.Equals("R", StringComparison.Ordinal) && !(CurrentAtom is IPseudoAtom)) { CurrentAtom = CurrentChemFile.Builder.NewPseudoAtom(CurrentAtom); } CurrentAtom.Symbol = symbol; try { - Isotopes.Instance.Configure(CurrentAtom); + BODRIsotopeFactory.Instance.Configure(CurrentAtom); } catch (Exception e) { - Trace.TraceError("Could not configure atom: " + CurrentAtom); + Trace.TraceError($"Could not configure atom: {CurrentAtom}"); Debug.WriteLine(e); } } if (has3D) { - // cdo.SetObjectProperty("Atom", "x3", (string)x3[i]); - // cdo.SetObjectProperty("Atom", "y3", (string)y3[i]); - // cdo.SetObjectProperty("Atom", "z3", (string)z3[i]); CurrentAtom.Point3D = new Vector3( - double.Parse((string)X3[i]), - double.Parse((string)Y3[i]), - double.Parse((string)Z3[i])); + double.Parse((string)X3[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)Y3[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)Z3[i], NumberFormatInfo.InvariantInfo)); } if (has3Dfract) { // ok, need to convert fractional into eucledian coordinates - // cdo.SetObjectProperty("Atom", "xFract", (string)xfract[i]); - // cdo.SetObjectProperty("Atom", "yFract", (string)yfract[i]); - // cdo.SetObjectProperty("Atom", "zFract", (string)zfract[i]); CurrentAtom.FractionalPoint3D = new Vector3( - double.Parse((string)XFract[i]), - double.Parse((string)YFract[i]), - double.Parse((string)ZFract[i])); + double.Parse((string)XFract[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)YFract[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)ZFract[i], NumberFormatInfo.InvariantInfo)); } if (hasFormalCharge) { - // cdo.SetObjectProperty("Atom", "formalCharge", - // (string)formalCharges[i]); - CurrentAtom.FormalCharge = int.Parse((string)FormalCharges[i]); + CurrentAtom.FormalCharge = int.Parse((string)FormalCharges[i], NumberFormatInfo.InvariantInfo); } if (hasPartialCharge) { Debug.WriteLine("Storing partial atomic charge..."); - // cdo.SetObjectProperty("Atom", "partialCharge", - // (string)partialCharges[i]); - CurrentAtom.Charge = double.Parse((string)PartialCharges[i]); + CurrentAtom.Charge = double.Parse((string)PartialCharges[i], NumberFormatInfo.InvariantInfo); } if (hasHCounts) { - // cdo.SetObjectProperty("Atom", "hydrogenCount", (string)hCounts[i]); // FIXME: the hCount in CML is the total of implicit *and* explicit - CurrentAtom.ImplicitHydrogenCount = int.Parse((string)HCounts[i]); + CurrentAtom.ImplicitHydrogenCount = int.Parse((string)HCounts[i], NumberFormatInfo.InvariantInfo); } if (has2D) { if (X2[i] != null && Y2[i] != null) { - // cdo.SetObjectProperty("Atom", "x2", (string)x2[i]); - // cdo.SetObjectProperty("Atom", "y2", (string)y2[i]); CurrentAtom.Point2D = new Vector2( - double.Parse((string)X2[i]), - double.Parse((string)Y2[i])); + double.Parse((string)X2[i], NumberFormatInfo.InvariantInfo), + double.Parse((string)Y2[i], NumberFormatInfo.InvariantInfo)); } } @@ -607,8 +622,7 @@ protected override void StoreAtomData() if (hasSpinMultiplicities && SpinMultiplicities[i] != null) { - // cdo.SetObjectProperty("Atom", "spinMultiplicity", (string)spinMultiplicities[i]); - int unpairedElectrons = int.Parse((string)SpinMultiplicities[i]) - 1; + int unpairedElectrons = int.Parse((string)SpinMultiplicities[i], NumberFormatInfo.InvariantInfo) - 1; for (int sm = 0; sm < unpairedElectrons; sm++) { CurrentMolecule.SingleElectrons.Add(CurrentChemFile.Builder.NewSingleElectron(CurrentAtom)); @@ -617,47 +631,32 @@ protected override void StoreAtomData() if (hasOccupancies && Occupancies[i] != null) { - // cdo.SetObjectProperty("PDBAtom", "occupancy", (string)occupancies[i]); - double occ = double.Parse((string)Occupancies[i]); + double occ = double.Parse((string)Occupancies[i], NumberFormatInfo.InvariantInfo); if (occ >= 0.0) ((IPDBAtom)CurrentAtom).Occupancy = occ; } if (hasIsotopes) { - // cdo.SetObjectProperty("Atom", "massNumber", (string)isotope[i]); - CurrentAtom.MassNumber = int.Parse((string)Isotope[i]); + CurrentAtom.MassNumber = int.Parse((string)Isotope[i], NumberFormatInfo.InvariantInfo); } if (hasScalar) { IPDBAtom pdbAtom = (IPDBAtom)CurrentAtom; - // cdo.SetObjectProperty("PDBAtom", "altLoc", altLocV[i].ToString()); - if (altLocV.Count > 0) pdbAtom.AltLoc = altLocV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "chainID", chainIDV[i].ToString()); - if (chainIDV.Count > 0) pdbAtom.ChainID = chainIDV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "hetAtom", hetAtomV[i].ToString()); - if (hetAtomV.Count > 0) pdbAtom.HetAtom = hetAtomV[i].ToString().Equals("true"); - // cdo.SetObjectProperty("PDBAtom", "iCode", iCodeV[i].ToString()); - if (iCodeV.Count > 0) pdbAtom.ICode = iCodeV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "name", nameV[i].ToString()); - if (nameV.Count > 0) pdbAtom.Name = nameV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "oxt", oxtV[i].ToString()); - if (oxtV.Count > 0) pdbAtom.Oxt = oxtV[i].ToString().Equals("true"); - // cdo.SetObjectProperty("PDBAtom", "resSeq", resSeqV[i].ToString()); - if (resSeqV.Count > 0) pdbAtom.ResSeq = resSeqV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "record", recordV[i].ToString()); - if (recordV.Count > 0) pdbAtom.Record = recordV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "resName", resNameV[i].ToString()); - if (resNameV.Count > 0) pdbAtom.ResName = resNameV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "segID", segIDV[i].ToString()); - if (segIDV.Count > 0) pdbAtom.SegID = segIDV[i].ToString(); - // cdo.SetObjectProperty("PDBAtom", "serial", serialV[i].ToString()); - if (serialV.Count > 0) pdbAtom.Serial = int.Parse(serialV[i].ToString()); - // cdo.SetObjectProperty("PDBAtom", "tempFactor", tempFactorV[i].ToString()); - if (tempFactorV.Count > 0) pdbAtom.TempFactor = double.Parse(tempFactorV[i].ToString()); + if (altLocV.Count > 0) pdbAtom.AltLoc = altLocV[i].ToString(NumberFormatInfo.InvariantInfo); + if (chainIDV.Count > 0) pdbAtom.ChainID = chainIDV[i].ToString(NumberFormatInfo.InvariantInfo); + if (hetAtomV.Count > 0) pdbAtom.HetAtom = string.Equals(hetAtomV[i].ToString(NumberFormatInfo.InvariantInfo), "true", StringComparison.Ordinal); + if (iCodeV.Count > 0) pdbAtom.ICode = iCodeV[i].ToString(NumberFormatInfo.InvariantInfo); + if (nameV.Count > 0) pdbAtom.Name = nameV[i].ToString(NumberFormatInfo.InvariantInfo); + if (oxtV.Count > 0) pdbAtom.Oxt = string.Equals(oxtV[i].ToString(NumberFormatInfo.InvariantInfo), "true", StringComparison.Ordinal); + if (resSeqV.Count > 0) pdbAtom.ResSeq = resSeqV[i].ToString(NumberFormatInfo.InvariantInfo); + if (recordV.Count > 0) pdbAtom.Record = recordV[i].ToString(NumberFormatInfo.InvariantInfo); + if (resNameV.Count > 0) pdbAtom.ResName = resNameV[i].ToString(NumberFormatInfo.InvariantInfo); + if (segIDV.Count > 0) pdbAtom.SegID = segIDV[i].ToString(NumberFormatInfo.InvariantInfo); + if (serialV.Count > 0) pdbAtom.Serial = int.Parse(serialV[i].ToString(NumberFormatInfo.InvariantInfo), NumberFormatInfo.InvariantInfo); + if (tempFactorV.Count > 0) pdbAtom.TempFactor = double.Parse(tempFactorV[i].ToString(NumberFormatInfo.InvariantInfo), NumberFormatInfo.InvariantInfo); } - // cdo.EndObject("PDBAtom"); string cResidue = ((IPDBAtom)CurrentAtom).ResName + "A" + ((IPDBAtom)CurrentAtom).ResSeq; ((IPDBMonomer)CurrentMonomer).MonomerName = cResidue; ((IPDBMonomer)CurrentMonomer).MonomerType = ((IPDBAtom)CurrentAtom).ResName; @@ -665,7 +664,6 @@ protected override void StoreAtomData() ((IPDBMonomer)CurrentMonomer).ICode = ((IPDBAtom)CurrentAtom).ICode; ((IPDBPolymer)CurrentMolecule).AddAtom(((IPDBAtom)CurrentAtom), CurrentMonomer, CurrentStrand); } - // cdo.EndObject("PDBMonomer"); // nothing done in the CDO for this event if (ElId.Count > 0) { diff --git a/NCDK/IO/CML/PMPConvention.cs b/NCDK/IO/CML/PMPConvention.cs index a90062a2..bd4d8930 100644 --- a/NCDK/IO/CML/PMPConvention.cs +++ b/NCDK/IO/CML/PMPConvention.cs @@ -24,15 +24,17 @@ using NCDK.Numerics; using System; using System.Diagnostics; +using System.Globalization; using System.Xml.Linq; namespace NCDK.IO.CML { /// - /// Implementation of the PMPMol Covention for CML. - /// PMP stands for PolyMorph Predictor and is a module - /// of Cerius2 (tm). + /// Implementation of the PMPMol Convention for CML. /// + /// PMP stands for PolyMorph Predictor and is a module of Cerius2 (tm). + /// + /// // @cdk.module io // @cdk.githash // @author Egon Willighagen @@ -67,50 +69,54 @@ public override void CharacterData(CMLStack xpath, XElement element) string s = element.Value.Trim(); Debug.WriteLine($"Start PMP chardata ({CurrentElement}) :{s}"); Debug.WriteLine($" ElTitle: {ElementTitle}"); - if (xpath.ToString().EndsWith("string/", StringComparison.Ordinal) && BUILTIN.Equals("spacegroup")) + if (xpath.ToString().EndsWith("string/", StringComparison.Ordinal) && Builtin.Equals("spacegroup", StringComparison.Ordinal)) { string sg = "P1"; // standardize space group names (see Crystal.java) - if ("P 21 21 21 (1)".Equals(s)) + if (string.Equals("P 21 21 21 (1)", s, StringComparison.Ordinal)) { sg = "P 2_1 2_1 2_1"; } - // cdo.SetObjectProperty("Crystal", "spacegroup", sg); ((ICrystal)CurrentMolecule).SpaceGroup = sg; } - else if (xpath.ToString().EndsWith("floatArray/", StringComparison.Ordinal) - && (ElementTitle.Equals("a") || ElementTitle.Equals("b") || ElementTitle.Equals("c"))) + else if (xpath.ToString().EndsWith("floatArray/", StringComparison.Ordinal)) { - var tokens = s.Split(' '); - if (tokens.Length > 2) + switch (ElementTitle) { - if (ElementTitle.Equals("a")) - { - ((ICrystal)CurrentMolecule).A = new Vector3( - double.Parse(tokens[0]), - double.Parse(tokens[1]), - double.Parse(tokens[2])); - } - else if (ElementTitle.Equals("b")) - { - ((ICrystal)CurrentMolecule).B = new Vector3( - double.Parse(tokens[0]), - double.Parse(tokens[1]), - double.Parse(tokens[2])); - } - else if (ElementTitle.Equals("c")) - { - ((ICrystal)CurrentMolecule).C = new Vector3( - double.Parse(tokens[0]), - double.Parse(tokens[1]), - double.Parse(tokens[2])); - } + case "a": + case "b": + case "c": + var tokens = s.Split(' '); + if (tokens.Length > 2) + { + if (string.Equals(ElementTitle, "a", StringComparison.Ordinal)) + { + ((ICrystal)CurrentMolecule).A = new Vector3( + double.Parse(tokens[0], NumberFormatInfo.InvariantInfo), + double.Parse(tokens[1], NumberFormatInfo.InvariantInfo), + double.Parse(tokens[2], NumberFormatInfo.InvariantInfo)); + } + else if (string.Equals(ElementTitle, "b", StringComparison.Ordinal)) + { + ((ICrystal)CurrentMolecule).B = new Vector3( + double.Parse(tokens[0], NumberFormatInfo.InvariantInfo), + double.Parse(tokens[1], NumberFormatInfo.InvariantInfo), + double.Parse(tokens[2], NumberFormatInfo.InvariantInfo)); + } + else if (string.Equals(ElementTitle, "c", StringComparison.Ordinal)) + { + ((ICrystal)CurrentMolecule).C = new Vector3( + double.Parse(tokens[0], NumberFormatInfo.InvariantInfo), + double.Parse(tokens[1], NumberFormatInfo.InvariantInfo), + double.Parse(tokens[2], NumberFormatInfo.InvariantInfo)); + } + } + else + { + Debug.WriteLine("PMP Convention error: incorrect number of cell axis fractions!"); + } + break; } - else - { - Debug.WriteLine("PMP Convention error: incorrect number of cell axis fractions!"); - } - // cdo.EndObject(axis); } else { diff --git a/NCDK/IO/CML/QSARConvention.cs b/NCDK/IO/CML/QSARConvention.cs index 466f6434..88fdc96e 100644 --- a/NCDK/IO/CML/QSARConvention.cs +++ b/NCDK/IO/CML/QSARConvention.cs @@ -25,6 +25,7 @@ using NCDK.QSAR; using NCDK.QSAR.Results; using System; +using System.Globalization; using System.Xml.Linq; namespace NCDK.IO.CML @@ -85,22 +86,22 @@ public override void StartElement(CMLStack xpath, XElement element) else if (xpath.EndsWith("property", "metadataList", "metadata")) { base.StartElement(xpath, element); - if (DICTREF.Equals("qsar:specificationReference")) + if (string.Equals(DictRef, "qsar:specificationReference", StringComparison.Ordinal)) { // cdo.SetObjectProperty("MolecularDescriptor", "SpecificationReference", atts.GetValue("content")); currentDescriptorAlgorithmSpecification = AttGetValue(element.Attributes(), "content"); } - else if (DICTREF.Equals("qsar:implementationTitle")) + else if (string.Equals(DictRef, "qsar:implementationTitle", StringComparison.Ordinal)) { // cdo.SetObjectProperty("MolecularDescriptor", "ImplementationTitle", atts.GetValue("content")); currentDescriptorImplementationTitel = AttGetValue(element.Attributes(), "content"); } - else if (DICTREF.Equals("qsar:implementationIdentifier")) + else if (string.Equals(DictRef, "qsar:implementationIdentifier", StringComparison.Ordinal)) { // cdo.SetObjectProperty("MolecularDescriptor", "ImplementationIdentifier", atts.GetValue("content")); currentDescriptorImplementationIdentifier = AttGetValue(element.Attributes(), "content"); } - else if (DICTREF.Equals("qsar:implementationVendor")) + else if (string.Equals(DictRef, "qsar:implementationVendor", StringComparison.Ordinal)) { // cdo.SetObjectProperty("MolecularDescriptor", "ImplementationVendor", atts.GetValue("content")); currentDescriptorImplementationVendor = AttGetValue(element.Attributes(), "content"); @@ -153,7 +154,7 @@ private IDescriptorValue NewDescriptorValue(DescriptorSpecification specificatio { var result = new ArrayResult(); foreach (var token in descriptorValue.Split(' ')) - result.Add(double.Parse(token)); + result.Add(double.Parse(token, NumberFormatInfo.InvariantInfo)); return new DescriptorValue>( specification, Array.Empty(), Array.Empty(), @@ -163,7 +164,7 @@ private IDescriptorValue NewDescriptorValue(DescriptorSpecification specificatio { var result = new ArrayResult(); foreach (var token in descriptorValue.Split(' ')) - result.Add(int.Parse(token)); + result.Add(int.Parse(token, NumberFormatInfo.InvariantInfo)); return new DescriptorValue>( specification, Array.Empty(), Array.Empty(), @@ -181,13 +182,13 @@ private IDescriptorValue NewDescriptorValue(DescriptorSpecification specificatio return new DescriptorValue>( specification, Array.Empty(), Array.Empty(), - new Result(double.Parse(descriptorValue)), + new Result(double.Parse(descriptorValue, NumberFormatInfo.InvariantInfo)), Array.Empty()); case "xsd:integer": return new DescriptorValue>( specification, Array.Empty(), Array.Empty(), - new Result(int.Parse(descriptorValue)), + new Result(int.Parse(descriptorValue, NumberFormatInfo.InvariantInfo)), Array.Empty()); case "xsd:boolean": return new DescriptorValue>( diff --git a/NCDK/IO/CMLReader.cs b/NCDK/IO/CMLReader.cs index 9c6e6ebb..521c35ef 100644 --- a/NCDK/IO/CMLReader.cs +++ b/NCDK/IO/CMLReader.cs @@ -45,10 +45,10 @@ namespace NCDK.IO // @cdk.keyword file format, CML // @cdk.bug 1544406 // @cdk.iooptions - public class CMLReader : DefaultChemObjectReader, IDisposable + public class CMLReader : DefaultChemObjectReader { private Stream input; - private string url; + private readonly string url; private IDictionary userConventions = new Dictionary(); @@ -75,6 +75,11 @@ public CMLReader(string url) this.url = url; } + public CMLReader(Uri uri) + : this(uri.AbsoluteUri) + { + } + public override IResourceFormat Format => CMLFormat.Instance; public override bool Accepts(Type type) @@ -117,7 +122,7 @@ private IChemFile ReadChemFile(IChemFile file) XmlReader parser; if (input == null) { - Debug.WriteLine("Parsing from URL: ", url); + Debug.WriteLine($"Parsing from URL: {url}"); parser = XmlReader.Create(url, setting); } else @@ -133,16 +138,14 @@ private IChemFile ReadChemFile(IChemFile file) handler.RegisterConvention(conv, userConventions[conv]); } - var reader = new XReader - { - Handler = handler - }; + var reader = new XReader { Handler = handler }; try { XDocument doc = XDocument.Load(parser); reader.Read(doc); } - catch (IOException e) { + catch (IOException e) + { string error = "Error while reading file: " + e.Message; Trace.TraceError(error); Debug.WriteLine(e); diff --git a/NCDK/IO/CMLWriter.cs b/NCDK/IO/CMLWriter.cs index 2e4f0f94..3ff44a99 100644 --- a/NCDK/IO/CMLWriter.cs +++ b/NCDK/IO/CMLWriter.cs @@ -197,7 +197,7 @@ public override void Write(IChemObject obj) throw new CDKException("Cannot write this unsupported IChemObject: " + obj.GetType().Name); } - Debug.WriteLine("Writing obj in CML of type: ", obj.GetType().Name); + Debug.WriteLine($"Writing obj in CML of type: {obj.GetType().Name}"); CustomizeJob(); @@ -289,43 +289,43 @@ public override void Write(IChemObject obj) private void InitIOSettings() { - cmlIds = Add(new BooleanIOSetting("CMLIDs", IOSetting.Importance.Low, + cmlIds = Add(new BooleanIOSetting("CMLIDs", Importance.Low, "Should the output use CML identifiers?", "true")); - namespacedOutput = Add(new BooleanIOSetting("NamespacedOutput", IOSetting.Importance.Low, + namespacedOutput = Add(new BooleanIOSetting("NamespacedOutput", Importance.Low, "Should the output use namespaced output?", "true")); - namespacePrefix = Add(new StringIOSetting("NamespacePrefix", IOSetting.Importance.Low, + namespacePrefix = Add(new StringIOSetting("NamespacePrefix", Importance.Low, "What should the namespace prefix be? [empty is no prefix]", "")); - schemaInstanceOutput = Add(new BooleanIOSetting("SchemaInstance", IOSetting.Importance.Low, + schemaInstanceOutput = Add(new BooleanIOSetting("SchemaInstance", Importance.Low, "Should the output use the Schema-Instance attribute?", "false")); - instanceLocation = Add(new StringIOSetting("InstanceLocation", IOSetting.Importance.Low, + instanceLocation = Add(new StringIOSetting("InstanceLocation", Importance.Low, "Where is the schema found?", "")); - indent = Add(new BooleanIOSetting("Indenting", IOSetting.Importance.Low, + indent = Add(new BooleanIOSetting("Indenting", Importance.Low, "Should the output be indented?", "true")); - xmlDeclaration = Add(new BooleanIOSetting("XMLDeclaration", IOSetting.Importance.Low, + xmlDeclaration = Add(new BooleanIOSetting("XMLDeclaration", Importance.Low, "Should the output contain an XML declaration?", "true")); } private void CustomizeJob() { - FireIOSettingQuestion(cmlIds); - FireIOSettingQuestion(namespacedOutput); + ProcessIOSettingQuestion(cmlIds); + ProcessIOSettingQuestion(namespacedOutput); if (namespacedOutput.IsSet) { - FireIOSettingQuestion(namespacePrefix); + ProcessIOSettingQuestion(namespacePrefix); } - FireIOSettingQuestion(schemaInstanceOutput); + ProcessIOSettingQuestion(schemaInstanceOutput); if (schemaInstanceOutput.IsSet) { - FireIOSettingQuestion(instanceLocation); + ProcessIOSettingQuestion(instanceLocation); } - FireIOSettingQuestion(indent); - FireIOSettingQuestion(xmlDeclaration); + ProcessIOSettingQuestion(indent); + ProcessIOSettingQuestion(xmlDeclaration); } } } diff --git a/NCDK/IO/CTXReader.cs b/NCDK/IO/CTXReader.cs index c87548df..1ee52e08 100644 --- a/NCDK/IO/CTXReader.cs +++ b/NCDK/IO/CTXReader.cs @@ -22,6 +22,7 @@ using NCDK.Tools.Manipulator; using System; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -88,19 +89,19 @@ private IChemFile ReadChemFile() { command = GetCommand(line); int lineCount = GetContentLinesCount(line); - if ("ATOMS".Equals(command)) + if (string.Equals("ATOMS", command, StringComparison.Ordinal)) { ProcessAtomsBlock(lineCount, container); } - else if ("BONDS".Equals(command)) + else if (string.Equals("BONDS", command, StringComparison.Ordinal)) { ProcessBondsBlock(lineCount, container); } - else if ("IDENT".Equals(command)) + else if (string.Equals("IDENT", command, StringComparison.Ordinal)) { ProcessIdentBlock(lineCount, container); } - else if ("NAME".Equals(command)) + else if (string.Equals("NAME", command, StringComparison.Ordinal)) { ProcessNameBlock(lineCount, container); } @@ -158,7 +159,7 @@ private void ProcessAtomsBlock(int lineCount, IAtomContainer container) for (int i = 0; i < lineCount; i++) { string line = input.ReadLine(); - int atomicNumber = int.Parse(line.Substring(7, 3).Trim()); + int atomicNumber = int.Parse(line.Substring(7, 3).Trim(), NumberFormatInfo.InvariantInfo); IAtom atom = container.Builder.NewAtom(); atom.AtomicNumber = atomicNumber; atom.Symbol = PeriodicTable.GetSymbol(atomicNumber); @@ -171,30 +172,30 @@ private void ProcessBondsBlock(int lineCount, IAtomContainer container) for (int i = 0; i < lineCount; i++) { string line = input.ReadLine(); - int atom1 = int.Parse(line.Substring(10, 3).Trim()) - 1; - int atom2 = int.Parse(line.Substring(16, 3).Trim()) - 1; + int atom1 = int.Parse(line.Substring(10, 3).Trim(), NumberFormatInfo.InvariantInfo) - 1; + int atom2 = int.Parse(line.Substring(16, 3).Trim(), NumberFormatInfo.InvariantInfo) - 1; if (container.GetBond(container.Atoms[atom1], container.Atoms[atom2]) == null) { IBond bond = container.Builder.NewBond(container.Atoms[atom1], container.Atoms[atom2]); - int order = int.Parse(line.Substring(23).Trim()); + int order = int.Parse(line.Substring(23).Trim(), NumberFormatInfo.InvariantInfo); bond.Order = BondManipulator.CreateBondOrder((double)order); container.Bonds.Add(bond); } // else: bond already present; CTX store the bonds twice } } - private int GetContentLinesCount(string line) + private static int GetContentLinesCount(string line) { - return int.Parse(line.Substring(18, 3).Trim()); + return int.Parse(line.Substring(18, 3).Trim(), NumberFormatInfo.InvariantInfo); } - private string GetCommand(string line) + private static string GetCommand(string line) { return line.Substring(2, 8).Trim(); } - private bool IsCommand(string line) + private static bool IsCommand(string line) { return (line.Length > 1 && line[0] == ' ' && line[1] == '/'); } diff --git a/NCDK/IO/ChemObjectIO.cs b/NCDK/IO/ChemObjectIO.cs index 29c1f5e3..6e027824 100644 --- a/NCDK/IO/ChemObjectIO.cs +++ b/NCDK/IO/ChemObjectIO.cs @@ -46,7 +46,7 @@ public abstract class ChemObjectIO : IChemObjectIO /// /// Holder of reader event listeners. /// - private List listeners = new List(2); + private readonly List listeners = new List(2); private SettingManager settings = new SettingManager(); public virtual ICollection Listeners => listeners; public virtual SettingManager IOSettings => settings; @@ -83,7 +83,7 @@ public void AddSettings(IEnumerable settings) /// Fires for all managed listeners. /// /// the setting to process - protected void FireIOSettingQuestion(IOSetting setting) + protected void ProcessIOSettingQuestion(IOSetting setting) { foreach (var listener in listeners) { diff --git a/NCDK/IO/CrystClustReader.cs b/NCDK/IO/CrystClustReader.cs index 2ced7675..d7fe34e9 100644 --- a/NCDK/IO/CrystClustReader.cs +++ b/NCDK/IO/CrystClustReader.cs @@ -23,6 +23,7 @@ using NCDK.Numerics; using System; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -129,7 +130,7 @@ private IChemFile ReadChemFile(IChemFile file) Debug.WriteLine($"{lineNumber++}: {line}"); axis.Z = FortranFormat.Atof(line); crystal.C = axis; - Debug.WriteLine("Crystal: ", crystal); + Debug.WriteLine($"Crystal: {crystal}"); a = crystal.A; b = crystal.B; c = crystal.C; @@ -137,12 +138,12 @@ private IChemFile ReadChemFile(IChemFile file) Debug.WriteLine("Reading number of atoms"); line = input.ReadLine(); Debug.WriteLine($"{lineNumber++}: {line}"); - int atomsToRead = int.Parse(line); + int atomsToRead = int.Parse(line, NumberFormatInfo.InvariantInfo); Debug.WriteLine("Reading no molecules in assym unit cell"); line = input.ReadLine(); Debug.WriteLine($"{lineNumber++}: {line}"); - int Z = int.Parse(line); + int Z = int.Parse(line, NumberFormatInfo.InvariantInfo); crystal.Z = Z; string symbol; @@ -154,23 +155,23 @@ private IChemFile ReadChemFile(IChemFile file) line = input.ReadLine(); Debug.WriteLine($"{lineNumber++}: {line}"); symbol = line.Substring(0, line.IndexOf(':')); - charge = double.Parse(line.Substring(line.IndexOf(':') + 1)); + charge = double.Parse(line.Substring(line.IndexOf(':') + 1), NumberFormatInfo.InvariantInfo); line = input.ReadLine(); Debug.WriteLine($"{lineNumber++}: {line}"); - cart.X = double.Parse(line); // x + cart.X = double.Parse(line, NumberFormatInfo.InvariantInfo); // x line = input.ReadLine(); Debug.WriteLine($"{lineNumber++}: {line}"); - cart.Y = double.Parse(line); // y + cart.Y = double.Parse(line, NumberFormatInfo.InvariantInfo); // y line = input.ReadLine(); Debug.WriteLine($"{lineNumber++}: {line}"); - cart.Z = double.Parse(line); // z + cart.Z = double.Parse(line, NumberFormatInfo.InvariantInfo); // z IAtom atom = file.Builder.NewAtom(symbol); atom.Charge = charge; - // convert cartesian coords to fractional + // convert Cartesian coords to fractional Vector3 frac = CrystalGeometryTools.CartesianToFractional(a, b, c, cart); atom.FractionalPoint3D = frac; crystal.Atoms.Add(atom); - Debug.WriteLine("Added atom: ", atom); + Debug.WriteLine($"Added atom: {atom}"); } model.Crystal = crystal; diff --git a/NCDK/IO/CrystClustWriter.cs b/NCDK/IO/CrystClustWriter.cs index e451dc72..0e37d0bc 100644 --- a/NCDK/IO/CrystClustWriter.cs +++ b/NCDK/IO/CrystClustWriter.cs @@ -20,6 +20,7 @@ using NCDK.IO.Formats; using NCDK.Numerics; using System; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -138,7 +139,7 @@ private void WriteChemSequence(IChemSequence cs) private void WriteCrystal(ICrystal crystal) { string sg = crystal.SpaceGroup; - if ("P 2_1 2_1 2_1".Equals(sg)) + if (string.Equals("P 2_1 2_1 2_1", sg, StringComparison.Ordinal)) { Writeln("P 21 21 21 (1)"); } @@ -154,11 +155,11 @@ private void WriteCrystal(ICrystal crystal) // output number of atoms int noatoms = crystal.Atoms.Count; - Write(noatoms.ToString()); + Write(noatoms.ToString(NumberFormatInfo.InvariantInfo)); Writeln(""); // output number of asym. units (Z) - if (sg.Equals("P1")) + if (string.Equals(sg, "P1", StringComparison.Ordinal)) { Writeln("1"); } @@ -178,9 +179,9 @@ private void WriteCrystal(ICrystal crystal) // output atom charge Writeln(atom.Charge.ToString()); // output coordinates - Writeln(atom.Point3D.Value.X.ToString()); - Writeln(atom.Point3D.Value.Y.ToString()); - Writeln(atom.Point3D.Value.Z.ToString()); + Writeln(atom.Point3D.Value.X.ToString(NumberFormatInfo.InvariantInfo)); + Writeln(atom.Point3D.Value.Y.ToString(NumberFormatInfo.InvariantInfo)); + Writeln(atom.Point3D.Value.Z.ToString(NumberFormatInfo.InvariantInfo)); } } @@ -211,11 +212,11 @@ private void Writeln(string s) private void WriteVector3d(Vector3 vector) { - Write(vector.X.ToString()); + Write(vector.X.ToString(NumberFormatInfo.InvariantInfo)); Writeln(""); - Write(vector.Y.ToString()); + Write(vector.Y.ToString(NumberFormatInfo.InvariantInfo)); Writeln(""); - Write(vector.Z.ToString()); + Write(vector.Z.ToString(NumberFormatInfo.InvariantInfo)); Writeln(""); } } diff --git a/NCDK/IO/DefaultChemObjectReader.cs b/NCDK/IO/DefaultChemObjectReader.cs index 7329147b..6e2f635b 100644 --- a/NCDK/IO/DefaultChemObjectReader.cs +++ b/NCDK/IO/DefaultChemObjectReader.cs @@ -41,7 +41,7 @@ public abstract class DefaultChemObjectReader : ChemObjectIO, ISimpleChemObjectR /// /// Sends a frame read event to the registered ReaderListeners. /// - protected void FireFrameRead() + protected void FrameRead() { foreach (var listener in Listeners) { @@ -69,7 +69,8 @@ public void HandleError(string message) public void HandleError(string message, Exception exception) { - if (this.ErrorHandler != null) this.ErrorHandler.HandleError(message, exception); + if (this.ErrorHandler != null) + this.ErrorHandler.HandleError(message, exception); if (this.ReaderMode == ChemObjectReaderMode.Strict) { throw new CDKException(message, exception); @@ -78,13 +79,15 @@ public void HandleError(string message, Exception exception) public void HandleError(string message, int row, int colStart, int colEnd) { - if (this.ErrorHandler != null) this.ErrorHandler.HandleError(message, row, colStart, colEnd); + if (this.ErrorHandler != null) + this.ErrorHandler.HandleError(message, row, colStart, colEnd); if (this.ReaderMode == ChemObjectReaderMode.Strict) throw new CDKException(message); } public void HandleError(string message, int row, int colStart, int colEnd, Exception exception) { - if (this.ErrorHandler != null) this.ErrorHandler.HandleError(message, row, colStart, colEnd, exception); + if (this.ErrorHandler != null) + this.ErrorHandler.HandleError(message, row, colStart, colEnd, exception); if (this.ReaderMode == ChemObjectReaderMode.Strict) { throw new CDKException(message, exception); diff --git a/NCDK/IO/FormatFactory.cs b/NCDK/IO/FormatFactory.cs index 2f542ac8..b986db2b 100644 --- a/NCDK/IO/FormatFactory.cs +++ b/NCDK/IO/FormatFactory.cs @@ -22,6 +22,7 @@ using NCDK.IO.Formats; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; @@ -40,7 +41,7 @@ namespace NCDK.IO // @author Bradley A. Smith public class FormatFactory { - private int headerLength; + private readonly int headerLength; private List formats = new List(100); @@ -78,10 +79,9 @@ public void RegisterFormat(IChemFormatMatcher format) } /// - /// Returns the list of recognizable formats. + /// The list of recognizable formats. /// - /// of s. - public IList Formats => formats; + public IReadOnlyList Formats => formats; /// /// Creates a string of the Class name of the reader @@ -100,12 +100,12 @@ internal IChemFormat GuessFormat(TextReader input) { if (input == null) { - throw new ArgumentNullException("input cannot be null"); + throw new ArgumentNullException(nameof(input)); } // make a copy of the header /* Search file for a line containing an identifying keyword */ - List lines = new List(); + var lines = new List(); { long nRead = 0; string line; @@ -144,14 +144,14 @@ internal IChemFormat GuessFormat(TextReader input) int tokenCount = tokens.Count; if (tokenCount == 1) { - int.Parse(tokens[0]); + int.Parse(tokens[0], NumberFormatInfo.InvariantInfo); // if not failed, then it is a XYZ file return (IChemFormat)XYZFormat.Instance; } else if (tokenCount == 2) { - int.Parse(tokens[0]); - if ("bohr".Equals(tokens[1].ToLowerInvariant(), StringComparison.Ordinal)) + int.Parse(tokens[0], NumberFormatInfo.InvariantInfo); + if (string.Equals("BOHR", tokens[1].ToUpperInvariant(), StringComparison.Ordinal)) { return (IChemFormat)XYZFormat.Instance; } @@ -179,7 +179,7 @@ public IChemFormat GuessFormat(Stream input) var position = input.Position; var reader = new StreamReader(input); - IChemFormat format = GuessFormat(reader); + var format = GuessFormat(reader); input.Seek(position, SeekOrigin.Begin); diff --git a/NCDK/IO/Formats/ABINITFormat.cs b/NCDK/IO/Formats/ABINITFormat.cs index bc9bf02c..5f625102 100644 --- a/NCDK/IO/Formats/ABINITFormat.cs +++ b/NCDK/IO/Formats/ABINITFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -34,7 +35,8 @@ public static IResourceFormat Instance { get { - if (myself == null) myself = new ABINITFormat(); + if (myself == null) + myself = new ABINITFormat(); return myself; } } @@ -49,7 +51,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +62,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("natom") >= 0 || line.IndexOf("ABINIT") >= 0) + if (line.IndexOf("natom", StringComparison.Ordinal) >= 0 || line.IndexOf("ABINIT", StringComparison.Ordinal) >= 0) { return true; } diff --git a/NCDK/IO/Formats/ADFFormat.cs b/NCDK/IO/Formats/ADFFormat.cs index 25d62f7d..5eaf1f2a 100644 --- a/NCDK/IO/Formats/ADFFormat.cs +++ b/NCDK/IO/Formats/ADFFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Amsterdam Density Functional") >= 0) + if (line.Contains("Amsterdam Density Functional")) { return true; } diff --git a/NCDK/IO/Formats/AbstractResourceFormat.cs b/NCDK/IO/Formats/AbstractResourceFormat.cs index bcb8fa9c..c2c85018 100644 --- a/NCDK/IO/Formats/AbstractResourceFormat.cs +++ b/NCDK/IO/Formats/AbstractResourceFormat.cs @@ -23,6 +23,7 @@ */ using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -54,7 +55,7 @@ public override bool Equals(Object that) public abstract string PreferredNameExtension { get; } /// - public abstract string[] NameExtensions { get; } + public abstract IReadOnlyList NameExtensions { get; } /// public abstract string MIMEType { get; } diff --git a/NCDK/IO/Formats/Aces2Format.cs b/NCDK/IO/Formats/Aces2Format.cs index 5fba1ba3..798b8e8a 100644 --- a/NCDK/IO/Formats/Aces2Format.cs +++ b/NCDK/IO/Formats/Aces2Format.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("ACES2") >= 0) + if (line.Contains("ACES2")) { return true; } diff --git a/NCDK/IO/Formats/AlchemyFormat.cs b/NCDK/IO/Formats/AlchemyFormat.cs index 9feb2ca4..69874918 100644 --- a/NCDK/IO/Formats/AlchemyFormat.cs +++ b/NCDK/IO/Formats/AlchemyFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "alc" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "alc" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/BGFFormat.cs b/NCDK/IO/Formats/BGFFormat.cs index 6e584a89..5df724ce 100644 --- a/NCDK/IO/Formats/BGFFormat.cs +++ b/NCDK/IO/Formats/BGFFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -50,7 +51,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/BSFormat.cs b/NCDK/IO/Formats/BSFormat.cs index 3796f75c..693444d4 100644 --- a/NCDK/IO/Formats/BSFormat.cs +++ b/NCDK/IO/Formats/BSFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "bs" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "bs" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/CACheFormat.cs b/NCDK/IO/Formats/CACheFormat.cs index 932c7b39..868983c1 100644 --- a/NCDK/IO/Formats/CACheFormat.cs +++ b/NCDK/IO/Formats/CACheFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cache" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cache" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/CDKOWLFormat.cs b/NCDK/IO/Formats/CDKOWLFormat.cs index f7f2dfb2..86e03fb7 100644 --- a/NCDK/IO/Formats/CDKOWLFormat.cs +++ b/NCDK/IO/Formats/CDKOWLFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions => new string[] { "n3" }; + public override IReadOnlyList NameExtensions => new string[] { "n3" }; /// public override string ReaderClassName { get; } = typeof(RDF.CDKOWLReader).FullName; @@ -74,10 +75,10 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures SupportedDataFeatures => - DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_ATOM_PARTIAL_CHARGES | DataFeatures.HAS_ATOM_FORMAL_CHARGES - | DataFeatures.HAS_ATOM_MASS_NUMBERS | DataFeatures.HAS_ATOM_ISOTOPE_NUMBERS - | DataFeatures.HAS_GRAPH_REPRESENTATION | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasAtomPartialCharges | DataFeatures.HasAtomFormalCharges + | DataFeatures.HasAtomMassNumbers | DataFeatures.HasAtomIsotopeNumbers + | DataFeatures.HasGraphRepresentation | DataFeatures.HasAtomElementSymbol; /// public override DataFeatures RequiredDataFeatures => DataFeatures.None; diff --git a/NCDK/IO/Formats/CIFFormat.cs b/NCDK/IO/Formats/CIFFormat.cs index 8a8ea144..43a804c0 100644 --- a/NCDK/IO/Formats/CIFFormat.cs +++ b/NCDK/IO/Formats/CIFFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cif" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cif" }; /// public override string ReaderClassName => "NCDK.IO.CIFReader"; diff --git a/NCDK/IO/Formats/CMLFormat.cs b/NCDK/IO/Formats/CMLFormat.cs index a8c56ffb..dbb0db36 100644 --- a/NCDK/IO/Formats/CMLFormat.cs +++ b/NCDK/IO/Formats/CMLFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cml", "xml" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cml", "xml" }; /// public override string ReaderClassName { get; } = typeof(CMLReader).FullName; @@ -62,9 +63,12 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if ((line.IndexOf("http://www.xml-cml.org/schema") != -1) || (line.IndexOf(" true; /// - public override DataFeatures SupportedDataFeatures => DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_ATOM_PARTIAL_CHARGES | DataFeatures.HAS_ATOM_FORMAL_CHARGES - | DataFeatures.HAS_ATOM_MASS_NUMBERS | DataFeatures.HAS_ATOM_ISOTOPE_NUMBERS - | DataFeatures.HAS_GRAPH_REPRESENTATION | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public override DataFeatures SupportedDataFeatures => DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasAtomPartialCharges | DataFeatures.HasAtomFormalCharges + | DataFeatures.HasAtomMassNumbers | DataFeatures.HasAtomIsotopeNumbers + | DataFeatures.HasGraphRepresentation | DataFeatures.HasAtomElementSymbol; /// public override DataFeatures RequiredDataFeatures => DataFeatures.None; diff --git a/NCDK/IO/Formats/CMLRSSFormat.cs b/NCDK/IO/Formats/CMLRSSFormat.cs index 3c58903b..47844e19 100644 --- a/NCDK/IO/Formats/CMLRSSFormat.cs +++ b/NCDK/IO/Formats/CMLRSSFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public string ReaderClassName => null; @@ -62,8 +63,8 @@ public static IResourceFormat Instance /// public DataFeatures SupportedDataFeatures => - DataFeatures.HAS_3D_COORDINATES | DataFeatures.HAS_GRAPH_REPRESENTATION - | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.Has3DCoordinates | DataFeatures.HasGraphRepresentation + | DataFeatures.HasAtomElementSymbol; /// public DataFeatures RequiredDataFeatures => DataFeatures.None; diff --git a/NCDK/IO/Formats/CRK2DFormat.cs b/NCDK/IO/Formats/CRK2DFormat.cs index 5c6106b4..3a14baac 100644 --- a/NCDK/IO/Formats/CRK2DFormat.cs +++ b/NCDK/IO/Formats/CRK2DFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "crk2d" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "crk2d" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/CRK3DFormat.cs b/NCDK/IO/Formats/CRK3DFormat.cs index 2d2e9147..8ba1510d 100644 --- a/NCDK/IO/Formats/CRK3DFormat.cs +++ b/NCDK/IO/Formats/CRK3DFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "crk3d" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "crk3d" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/CTXFormat.cs b/NCDK/IO/Formats/CTXFormat.cs index 0219dc78..e7ab406e 100644 --- a/NCDK/IO/Formats/CTXFormat.cs +++ b/NCDK/IO/Formats/CTXFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "ctx" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "ctx" }; /// public override string ReaderClassName => "NCDK.IO.CTXReader"; diff --git a/NCDK/IO/Formats/CacaoCartesianFormat.cs b/NCDK/IO/Formats/CacaoCartesianFormat.cs index 48277f9c..b30ffeee 100644 --- a/NCDK/IO/Formats/CacaoCartesianFormat.cs +++ b/NCDK/IO/Formats/CacaoCartesianFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "caccrt" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "caccrt" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/CacaoInternalFormat.cs b/NCDK/IO/Formats/CacaoInternalFormat.cs index 6ccdcd79..d631df12 100644 --- a/NCDK/IO/Formats/CacaoInternalFormat.cs +++ b/NCDK/IO/Formats/CacaoInternalFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cacint" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cacint" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/Chem3D_Cartesian_1Format.cs b/NCDK/IO/Formats/Chem3D_Cartesian_1Format.cs index fa47559d..fc178c11 100644 --- a/NCDK/IO/Formats/Chem3D_Cartesian_1Format.cs +++ b/NCDK/IO/Formats/Chem3D_Cartesian_1Format.cs @@ -17,23 +17,24 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { // @author Miguel Rojas // @cdk.module ioformats // @cdk.githash - public class Chem3D_Cartesian_1Format : AbstractResourceFormat, IChemFormat + public class Chem3DCartesian1Format : AbstractResourceFormat, IChemFormat { private static IResourceFormat myself = null; - public Chem3D_Cartesian_1Format() { } + public Chem3DCartesian1Format() { } public static IResourceFormat Instance { get { - if (myself == null) myself = new Chem3D_Cartesian_1Format(); + if (myself == null) myself = new Chem3DCartesian1Format(); return myself; } } @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "c3d1" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "c3d1" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/Chem3D_Cartesian_2Format.cs b/NCDK/IO/Formats/Chem3D_Cartesian_2Format.cs index 5cb70bcc..d0042a9e 100644 --- a/NCDK/IO/Formats/Chem3D_Cartesian_2Format.cs +++ b/NCDK/IO/Formats/Chem3D_Cartesian_2Format.cs @@ -18,23 +18,24 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { // @author Miguel Rojas // @cdk.module ioformats // @cdk.githash - public class Chem3D_Cartesian_2Format : AbstractResourceFormat, IChemFormat + public class Chem3DCartesian2Format : AbstractResourceFormat, IChemFormat { private static IResourceFormat myself = null; - public Chem3D_Cartesian_2Format() { } + public Chem3DCartesian2Format() { } public static IResourceFormat Instance { get { - if (myself == null) myself = new Chem3D_Cartesian_2Format(); + if (myself == null) myself = new Chem3DCartesian2Format(); return myself; } } @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "c3d2" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "c3d2" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/ChemDrawFormat.cs b/NCDK/IO/Formats/ChemDrawFormat.cs index 4f349872..ecbe7fb5 100644 --- a/NCDK/IO/Formats/ChemDrawFormat.cs +++ b/NCDK/IO/Formats/ChemDrawFormat.cs @@ -17,6 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cdx" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cdx" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/ChemtoolFormat.cs b/NCDK/IO/Formats/ChemtoolFormat.cs index abdca478..ffd941f5 100644 --- a/NCDK/IO/Formats/ChemtoolFormat.cs +++ b/NCDK/IO/Formats/ChemtoolFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cht" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cht" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/CrystClustFormat.cs b/NCDK/IO/Formats/CrystClustFormat.cs index 173b66ec..2a66a108 100644 --- a/NCDK/IO/Formats/CrystClustFormat.cs +++ b/NCDK/IO/Formats/CrystClustFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "crystclust" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "crystclust" }; /// public override string ReaderClassName => "NCDK.IO.CrystClustReader"; @@ -75,7 +76,7 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures RequiredDataFeatures => - DataFeatures.HAS_3D_COORDINATES | DataFeatures.HAS_UNITCELL_PARAMETERS - | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.Has3DCoordinates | DataFeatures.HasUnitcellParameters + | DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/DMol3Format.cs b/NCDK/IO/Formats/DMol3Format.cs index 2ea718fc..da11edd6 100644 --- a/NCDK/IO/Formats/DMol3Format.cs +++ b/NCDK/IO/Formats/DMol3Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "dmol" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "dmol" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/DOCK5Format.cs b/NCDK/IO/Formats/DOCK5Format.cs index f705939a..0acb3156 100644 --- a/NCDK/IO/Formats/DOCK5Format.cs +++ b/NCDK/IO/Formats/DOCK5Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "bgf" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "bgf" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/DaltonFormat.cs b/NCDK/IO/Formats/DaltonFormat.cs index 821ec9b3..ff25bd6a 100644 --- a/NCDK/IO/Formats/DaltonFormat.cs +++ b/NCDK/IO/Formats/DaltonFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("DALTON") >= 0) + if (line.Contains("DALTON")) { return true; } diff --git a/NCDK/IO/Formats/FenskeHall_ZMatrixFormat.cs b/NCDK/IO/Formats/FenskeHall_ZMatrixFormat.cs index d678c2b5..dfea61bb 100644 --- a/NCDK/IO/Formats/FenskeHall_ZMatrixFormat.cs +++ b/NCDK/IO/Formats/FenskeHall_ZMatrixFormat.cs @@ -18,23 +18,24 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { // @author Miguel Rojas // @cdk.module ioformats // @cdk.githash - public class FenskeHall_ZMatrixFormat : AbstractResourceFormat, IChemFormat + public class FenskeHallZMatrixFormat : AbstractResourceFormat, IChemFormat { private static IResourceFormat myself = null; - public FenskeHall_ZMatrixFormat() { } + public FenskeHallZMatrixFormat() { } public static IResourceFormat Instance { get { - if (myself == null) myself = new FenskeHall_ZMatrixFormat(); + if (myself == null) myself = new FenskeHallZMatrixFormat(); return myself; } } @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "fh" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "fh" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/FingerprintFormat.cs b/NCDK/IO/Formats/FingerprintFormat.cs index 7508ea1a..111a949d 100644 --- a/NCDK/IO/Formats/FingerprintFormat.cs +++ b/NCDK/IO/Formats/FingerprintFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "fpt" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "fpt" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/GROMOS96Format.cs b/NCDK/IO/Formats/GROMOS96Format.cs index 6b402752..ac40f005 100644 --- a/NCDK/IO/Formats/GROMOS96Format.cs +++ b/NCDK/IO/Formats/GROMOS96Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "gr96 " }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "gr96 " }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/GamessFormat.cs b/NCDK/IO/Formats/GamessFormat.cs index a8120599..f0680fec 100644 --- a/NCDK/IO/Formats/GamessFormat.cs +++ b/NCDK/IO/Formats/GamessFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "gam", "gamin", "inp", "gamout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "gam", "gamin", "inp", "gamout" }; /// public override string ReaderClassName => "NCDK.IO.GamessReader"; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("GAMESS execution script") >= 0 || line.IndexOf("GAMESS VERSION") >= 0) + if (line.Contains("GAMESS execution script") || line.Contains("GAMESS VERSION")) { return true; } diff --git a/NCDK/IO/Formats/Gaussian03Format.cs b/NCDK/IO/Formats/Gaussian03Format.cs index 15965c5c..874be42d 100644 --- a/NCDK/IO/Formats/Gaussian03Format.cs +++ b/NCDK/IO/Formats/Gaussian03Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName { get; } = typeof(Gaussian03Reader).FullName; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Gaussian(R) 03") >= 0) + if (line.Contains("Gaussian(R) 03")) { return true; } diff --git a/NCDK/IO/Formats/Gaussian90Format.cs b/NCDK/IO/Formats/Gaussian90Format.cs index 34abc49a..f1af00e5 100644 --- a/NCDK/IO/Formats/Gaussian90Format.cs +++ b/NCDK/IO/Formats/Gaussian90Format.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Gaussian G90") >= 0) + if (line.Contains("Gaussian G90")) { return true; } diff --git a/NCDK/IO/Formats/Gaussian92Format.cs b/NCDK/IO/Formats/Gaussian92Format.cs index 2409e058..473a03e7 100644 --- a/NCDK/IO/Formats/Gaussian92Format.cs +++ b/NCDK/IO/Formats/Gaussian92Format.cs @@ -18,6 +18,8 @@ */ using NCDK.Tools; +using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => new string[0]; + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; @@ -59,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Gaussian 92") >= 0) + if (line.IndexOf("Gaussian 92", StringComparison.Ordinal) >= 0) { return true; } diff --git a/NCDK/IO/Formats/Gaussian94Format.cs b/NCDK/IO/Formats/Gaussian94Format.cs index ddd92231..4c4018c4 100644 --- a/NCDK/IO/Formats/Gaussian94Format.cs +++ b/NCDK/IO/Formats/Gaussian94Format.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Gaussian 94") >= 0) + if (line.Contains("Gaussian 94")) { return true; } diff --git a/NCDK/IO/Formats/Gaussian95Format.cs b/NCDK/IO/Formats/Gaussian95Format.cs index 8af495b2..c130a4cd 100644 --- a/NCDK/IO/Formats/Gaussian95Format.cs +++ b/NCDK/IO/Formats/Gaussian95Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public override string ReaderClassName => null; @@ -59,7 +60,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Gaussian 95") >= 0) + if (line.Contains("Gaussian 95")) { return true; } diff --git a/NCDK/IO/Formats/Gaussian98Format.cs b/NCDK/IO/Formats/Gaussian98Format.cs index 94f2f5a7..b16dbceb 100644 --- a/NCDK/IO/Formats/Gaussian98Format.cs +++ b/NCDK/IO/Formats/Gaussian98Format.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Tools; +using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -47,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = new string[0]; + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public override string ReaderClassName { get; } = typeof(Gaussian98Reader).FullName; @@ -58,7 +60,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Gaussian(R) 98") >= 0 || line.IndexOf("Gaussian 98") >= 0) + if (line.Contains("Gaussian(R) 98") || line.Contains("Gaussian 98")) { return true; } diff --git a/NCDK/IO/Formats/GaussianInputFormat.cs b/NCDK/IO/Formats/GaussianInputFormat.cs index 629d5a68..e5b3bf72 100644 --- a/NCDK/IO/Formats/GaussianInputFormat.cs +++ b/NCDK/IO/Formats/GaussianInputFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "gau", "com" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "gau", "com" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/GhemicalMMFormat.cs b/NCDK/IO/Formats/GhemicalMMFormat.cs index 2e4b6417..ffc80ba4 100644 --- a/NCDK/IO/Formats/GhemicalMMFormat.cs +++ b/NCDK/IO/Formats/GhemicalMMFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "gpr" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "gpr" }; /// public override string ReaderClassName { get; } = typeof(GhemicalMMReader).FullName; diff --git a/NCDK/IO/Formats/GhemicalSPMFormat.cs b/NCDK/IO/Formats/GhemicalSPMFormat.cs index f257e433..9a5de698 100644 --- a/NCDK/IO/Formats/GhemicalSPMFormat.cs +++ b/NCDK/IO/Formats/GhemicalSPMFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName { get; } = typeof(GhemicalMMReader).FullName; diff --git a/NCDK/IO/Formats/HINFormat.cs b/NCDK/IO/Formats/HINFormat.cs index 609964fd..636b79a5 100644 --- a/NCDK/IO/Formats/HINFormat.cs +++ b/NCDK/IO/Formats/HINFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -29,11 +30,9 @@ namespace NCDK.IO.Formats // @cdk.githash public class HINFormat : SimpleChemFormatMatcher, IChemFormatMatcher { - private static IResourceFormat myself = new HINFormat(); - public HINFormat() { } - public static IResourceFormat Instance => myself; + public static IResourceFormat Instance { get; } = new HINFormat(); /// public override string FormatName => "HyperChem HIN"; @@ -45,7 +44,7 @@ public HINFormat() { } public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions => new string[] { "hin" }; + public override IReadOnlyList NameExtensions => new string[] { "hin" }; /// public override string ReaderClassName => typeof(HINReader).FullName; @@ -73,10 +72,10 @@ public override bool Matches(int lineNumber, string line) public override bool IsXmlBased => false; /// - public override DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HAS_GRAPH_REPRESENTATION; + public override DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HasGraphRepresentation; /// - public override DataFeatures RequiredDataFeatures => DataFeatures.HAS_3D_COORDINATES | DataFeatures.HAS_ATOM_PARTIAL_CHARGES - | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public override DataFeatures RequiredDataFeatures => DataFeatures.Has3DCoordinates | DataFeatures.HasAtomPartialCharges + | DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/IChemFormatMatcher.cs b/NCDK/IO/Formats/IChemFormatMatcher.cs index 795dfb10..70909639 100644 --- a/NCDK/IO/Formats/IChemFormatMatcher.cs +++ b/NCDK/IO/Formats/IChemFormatMatcher.cs @@ -25,6 +25,8 @@ using System; using System.Collections.Generic; +#pragma warning disable CA1036 // Override methods on comparable types + namespace NCDK.IO.Formats { /// @@ -43,7 +45,7 @@ public interface IChemFormatMatcher : IChemFormat /// /// lines of the input to be checked /// whether the format matched and when it matched - MatchResult Matches(IList lines); + MatchResult Matches(IEnumerable lines); } /// @@ -54,29 +56,26 @@ public interface IChemFormatMatcher : IChemFormat public sealed class MatchResult : IComparable { /// Convenience method for indicating a format did not match. - public static MatchResult NO_MATCH = new MatchResult(false, null, int.MaxValue); - - /// Did the format match. - private readonly bool matched; + public static MatchResult NoMatch { get; } = new MatchResult(false, null, int.MaxValue); /// When did the format match. - private readonly int position; + public int Position { get; private set; } /// Which format matched. private readonly IChemFormat format; public MatchResult(bool matched, IChemFormat format, int position) { - this.matched = matched; + this.IsMatched = matched; this.format = format; - this.position = position; + this.Position = position; } /// /// Did the chem format match. /// /// whether the format matched - public bool IsMatched => matched; + public bool IsMatched { get; private set; } /// /// What was the format which matched if there was a match . @@ -87,7 +86,8 @@ public IChemFormat Format { get { - if (!matched) throw new InvalidOperationException("result did not match"); + if (!IsMatched) + throw new InvalidOperationException("result did not match"); return format; } } @@ -98,7 +98,7 @@ public IChemFormat Format /// public int CompareTo(MatchResult that) { - return Ints.Compare(this.position, that.position); + return Ints.Compare(this.Position, that.Position); } } } diff --git a/NCDK/IO/Formats/IResourceFormat.cs b/NCDK/IO/Formats/IResourceFormat.cs index 0f4d5321..ec689810 100644 --- a/NCDK/IO/Formats/IResourceFormat.cs +++ b/NCDK/IO/Formats/IResourceFormat.cs @@ -21,6 +21,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System.Collections.Generic; + namespace NCDK.IO.Formats { /// @@ -47,7 +49,7 @@ public interface IResourceFormat /// /// Returns an array of common resource name extensions. /// - string[] NameExtensions { get; } + IReadOnlyList NameExtensions { get; } /// /// Returns the accepted MIME type for this format. diff --git a/NCDK/IO/Formats/InChIFormat.cs b/NCDK/IO/Formats/InChIFormat.cs index 75a7e948..50fea98d 100644 --- a/NCDK/IO/Formats/InChIFormat.cs +++ b/NCDK/IO/Formats/InChIFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions => new string[] { "inchi" }; + public override IReadOnlyList NameExtensions => new string[] { "inchi" }; /// public override string ReaderClassName => "NCDK.IO.InChIReader"; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf(" null; /// - public override string[] NameExtensions => new string[0]; + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName { get; } = typeof(InChIPlainTextReader).FullName; diff --git a/NCDK/IO/Formats/JMEFormat.cs b/NCDK/IO/Formats/JMEFormat.cs index 6f5631c0..6ce8f37e 100644 --- a/NCDK/IO/Formats/JMEFormat.cs +++ b/NCDK/IO/Formats/JMEFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/JaguarFormat.cs b/NCDK/IO/Formats/JaguarFormat.cs index 64fda9a6..5de07c5e 100644 --- a/NCDK/IO/Formats/JaguarFormat.cs +++ b/NCDK/IO/Formats/JaguarFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "j", "jin", "jout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "j", "jin", "jout" }; /// public override string ReaderClassName => null; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Jaguar") >= 0 && line.IndexOf("Schrodinger") >= 0) + if (line.Contains("Jaguar") && line.Contains("Schrodinger")) { return true; } diff --git a/NCDK/IO/Formats/MDLFormat.cs b/NCDK/IO/Formats/MDLFormat.cs index d436f2ea..81e94a47 100644 --- a/NCDK/IO/Formats/MDLFormat.cs +++ b/NCDK/IO/Formats/MDLFormat.cs @@ -20,6 +20,8 @@ using NCDK.Common.Primitives; using NCDK.Tools; using System; +using System.Collections.Generic; +using System.Globalization; namespace NCDK.IO.Formats { @@ -53,7 +55,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mol" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mol" }; /// public override string ReaderClassName => typeof(MDLReader).ToString(); @@ -64,8 +66,9 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (lineNumber == 4 && line.Length > 7 && (line.IndexOf("2000") == -1) && // MDL Mol V2000 format - (line.IndexOf("3000") == -1)) // MDL Mol V3000 format + if (lineNumber == 4 && line.Length > 7 + && !line.Contains("2000") // MDL Mol V2000 format + && !line.Contains("3000")) // MDL Mol V3000 format { // possibly a MDL mol file try @@ -73,8 +76,8 @@ public override bool Matches(int lineNumber, string line) string atomCountString = Strings.Substring(line, 0, 3).Trim(); string bondCountString = Strings.Substring(line, 3, 3).Trim(); - int.Parse(atomCountString); - int.Parse(bondCountString); + int.Parse(atomCountString, NumberFormatInfo.InvariantInfo); + int.Parse(bondCountString, NumberFormatInfo.InvariantInfo); if (line.Length > 6) { string remainder = Strings.Substring(line, 6).Trim(); @@ -103,11 +106,11 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures SupportedDataFeatures - => RequiredDataFeatures | DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_GRAPH_REPRESENTATION; + => RequiredDataFeatures | DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasGraphRepresentation; /// public override DataFeatures RequiredDataFeatures - => DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + => DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/MDLRXNV2000Format.cs b/NCDK/IO/Formats/MDLRXNV2000Format.cs index c82dcfda..deeed0ff 100644 --- a/NCDK/IO/Formats/MDLRXNV2000Format.cs +++ b/NCDK/IO/Formats/MDLRXNV2000Format.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System.Collections.Generic; +using System.Linq; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions => new string[] { "rxn" }; + public override IReadOnlyList NameExtensions => new string[] { "rxn" }; /// public string ReaderClassName { get; } = typeof(MDLRXNV2000Reader).FullName; @@ -61,19 +62,23 @@ public static IResourceFormat Instance public string WriterClassName => null; /// - public MatchResult Matches(IList lines) + public MatchResult Matches(IEnumerable lines) { + var _lines = lines.ToList(); + // if the first line doesn't have '$RXN' then it can't match - if (lines.Count < 1 || lines[0].Trim() != "$RXN") - return MatchResult.NO_MATCH; + if (_lines.Count < 1 || _lines[0].Trim() != "$RXN") + return MatchResult.NoMatch; // check the header (fifth line) - string header = lines.Count > 4 ? lines[4] : ""; + string header = _lines.Count > 4 ? _lines[4] : ""; // atom count - if (header.Length < 3 || !char.IsDigit(header[2])) return MatchResult.NO_MATCH; + if (header.Length < 3 || !char.IsDigit(header[2])) + return MatchResult.NoMatch; // bond count - if (header.Length < 6 || !char.IsDigit(header[5])) return MatchResult.NO_MATCH; + if (header.Length < 6 || !char.IsDigit(header[5])) + return MatchResult.NoMatch; // check the rest of the header is only spaces and digits if (header.Length > 6) @@ -84,7 +89,7 @@ public MatchResult Matches(IList lines) char c = remainder[i]; if (!(char.IsDigit(c) || char.IsWhiteSpace(c))) { - return MatchResult.NO_MATCH; + return MatchResult.NoMatch; } } } diff --git a/NCDK/IO/Formats/MDLRXNV3000Format.cs b/NCDK/IO/Formats/MDLRXNV3000Format.cs index 2d3e04ec..f38147e2 100644 --- a/NCDK/IO/Formats/MDLRXNV3000Format.cs +++ b/NCDK/IO/Formats/MDLRXNV3000Format.cs @@ -53,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "rxn" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "rxn" }; /// public override string ReaderClassName { get; } = typeof(MDLRXNV3000Reader).FullName; @@ -64,7 +64,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.StartsWith("$RXN V3000")) + if (line.StartsWith("$RXN V3000", StringComparison.Ordinal)) { return true; } diff --git a/NCDK/IO/Formats/MDLV2000Format.cs b/NCDK/IO/Formats/MDLV2000Format.cs index 80969162..ce360639 100644 --- a/NCDK/IO/Formats/MDLV2000Format.cs +++ b/NCDK/IO/Formats/MDLV2000Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -25,11 +26,9 @@ namespace NCDK.IO.Formats // @cdk.githash public class MDLV2000Format : SimpleChemFormatMatcher, IChemFormatMatcher { - private static IResourceFormat myself = new MDLV2000Format(); - public MDLV2000Format() { } - public static IResourceFormat Instance => myself; + public static IResourceFormat Instance { get; } = new MDLV2000Format(); /// public override string FormatName => "MDL Molfile V2000"; @@ -41,7 +40,7 @@ public MDLV2000Format() { } public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions => new string[] { "mol" }; + public override IReadOnlyList NameExtensions => new string[] { "mol" }; /// public override string ReaderClassName => typeof(NCDK.IO.MDLV2000Reader).ToString(); @@ -52,7 +51,7 @@ public MDLV2000Format() { } /// public override bool Matches(int lineNumber, string line) { - if (lineNumber == 4 && (line.IndexOf("v2000") >= 0 || line.IndexOf("V2000") >= 0)) + if (lineNumber == 4 && (line.Contains("v2000") || line.Contains("V2000"))) { return true; } @@ -64,11 +63,11 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures SupportedDataFeatures - => RequiredDataFeatures | DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_GRAPH_REPRESENTATION; + => RequiredDataFeatures | DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasGraphRepresentation; /// public override DataFeatures RequiredDataFeatures - => DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + => DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/MDLV3000Format.cs b/NCDK/IO/Formats/MDLV3000Format.cs index f6c91526..6423aab5 100644 --- a/NCDK/IO/Formats/MDLV3000Format.cs +++ b/NCDK/IO/Formats/MDLV3000Format.cs @@ -18,6 +18,8 @@ */ using NCDK.Tools; +using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = new string[0]; + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public override string ReaderClassName { get; } = typeof(MDLV3000Reader).FullName; @@ -59,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (lineNumber == 4 && (line.IndexOf("v3000") >= 0 || line.IndexOf("V3000") >= 0)) + if (lineNumber == 4 && (line.Contains("v3000")|| line.Contains("V3000"))) { return true; } diff --git a/NCDK/IO/Formats/MMODFormat.cs b/NCDK/IO/Formats/MMODFormat.cs index 27d7813a..7a46f41d 100644 --- a/NCDK/IO/Formats/MMODFormat.cs +++ b/NCDK/IO/Formats/MMODFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -53,7 +54,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC2002Format.cs b/NCDK/IO/Formats/MOPAC2002Format.cs index 03e6aaac..b40f1fba 100644 --- a/NCDK/IO/Formats/MOPAC2002Format.cs +++ b/NCDK/IO/Formats/MOPAC2002Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; @@ -59,7 +60,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("MOPAC2002") >= 0) + if (line.Contains("MOPAC2002")) { return true; } diff --git a/NCDK/IO/Formats/MOPAC2007Format.cs b/NCDK/IO/Formats/MOPAC2007Format.cs index 814bfbcf..f846e9f7 100644 --- a/NCDK/IO/Formats/MOPAC2007Format.cs +++ b/NCDK/IO/Formats/MOPAC2007Format.cs @@ -18,6 +18,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC2009Format.cs b/NCDK/IO/Formats/MOPAC2009Format.cs index 8b805bd4..7f2d638d 100644 --- a/NCDK/IO/Formats/MOPAC2009Format.cs +++ b/NCDK/IO/Formats/MOPAC2009Format.cs @@ -19,6 +19,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC2012Format.cs b/NCDK/IO/Formats/MOPAC2012Format.cs index e087e639..256517a2 100644 --- a/NCDK/IO/Formats/MOPAC2012Format.cs +++ b/NCDK/IO/Formats/MOPAC2012Format.cs @@ -19,6 +19,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC7Format.cs b/NCDK/IO/Formats/MOPAC7Format.cs index 3130c376..5673b33d 100644 --- a/NCDK/IO/Formats/MOPAC7Format.cs +++ b/NCDK/IO/Formats/MOPAC7Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC7InputFormat.cs b/NCDK/IO/Formats/MOPAC7InputFormat.cs index 28aefb1e..3026a6a7 100644 --- a/NCDK/IO/Formats/MOPAC7InputFormat.cs +++ b/NCDK/IO/Formats/MOPAC7InputFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC93Format.cs b/NCDK/IO/Formats/MOPAC93Format.cs index 1d635eff..f25ee7b8 100644 --- a/NCDK/IO/Formats/MOPAC93Format.cs +++ b/NCDK/IO/Formats/MOPAC93Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MOPAC97Format.cs b/NCDK/IO/Formats/MOPAC97Format.cs index c036dd48..34ac86bb 100644 --- a/NCDK/IO/Formats/MOPAC97Format.cs +++ b/NCDK/IO/Formats/MOPAC97Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mop", "mopcrt", "mopout" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MPQCFormat.cs b/NCDK/IO/Formats/MPQCFormat.cs index 2f522396..386addd6 100644 --- a/NCDK/IO/Formats/MPQCFormat.cs +++ b/NCDK/IO/Formats/MPQCFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mpqcin" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mpqcin" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MacroModelFormat.cs b/NCDK/IO/Formats/MacroModelFormat.cs index dcc76970..f2eb0a90 100644 --- a/NCDK/IO/Formats/MacroModelFormat.cs +++ b/NCDK/IO/Formats/MacroModelFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mmd", "mmod" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mmd", "mmod" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/MoSSOutputFormat.cs b/NCDK/IO/Formats/MoSSOutputFormat.cs index 510a35f5..e6ea6db7 100644 --- a/NCDK/IO/Formats/MoSSOutputFormat.cs +++ b/NCDK/IO/Formats/MoSSOutputFormat.cs @@ -21,6 +21,8 @@ */ using NCDK.Tools; +using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mossoutput" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mossoutput" }; /// public override string ReaderClassName => null; @@ -62,7 +64,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (lineNumber == 1 && line.Equals("id,description,nodes,edges,s_abs,s_rel,c_abs,c_rel")) + if (lineNumber == 1 && line.Equals("id,description,nodes,edges,s_abs,s_rel,c_abs,c_rel", StringComparison.Ordinal)) { return true; } @@ -73,9 +75,9 @@ public override bool Matches(int lineNumber, string line) public override bool IsXmlBased => false; /// - public override DataFeatures SupportedDataFeatures => DataFeatures.HAS_GRAPH_REPRESENTATION; + public override DataFeatures SupportedDataFeatures => DataFeatures.HasGraphRepresentation; /// - public override DataFeatures RequiredDataFeatures => DataFeatures.HAS_GRAPH_REPRESENTATION; + public override DataFeatures RequiredDataFeatures => DataFeatures.HasGraphRepresentation; } } diff --git a/NCDK/IO/Formats/Mol2Format.cs b/NCDK/IO/Formats/Mol2Format.cs index 525d6dc6..cc89ba07 100644 --- a/NCDK/IO/Formats/Mol2Format.cs +++ b/NCDK/IO/Formats/Mol2Format.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mol2" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mol2" }; /// public override string ReaderClassName { get; } = typeof(Mol2Reader).FullName; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("") >= 0) + if (line.Contains("")) { return true; } @@ -73,10 +74,10 @@ public override bool Matches(int lineNumber, string line) public override bool IsXmlBased => false; /// - public override DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_GRAPH_REPRESENTATION; + public override DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasGraphRepresentation; /// - public override DataFeatures RequiredDataFeatures => DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public override DataFeatures RequiredDataFeatures => DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/NCDKSourceCodeFormat.cs b/NCDK/IO/Formats/NCDKSourceCodeFormat.cs index b30dd577..1d37148a 100644 --- a/NCDK/IO/Formats/NCDKSourceCodeFormat.cs +++ b/NCDK/IO/Formats/NCDKSourceCodeFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "cs" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "cs" }; /// public string ReaderClassName => null; @@ -60,10 +61,10 @@ public static IResourceFormat Instance public override bool IsXmlBased => false; /// - public DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HAS_GRAPH_REPRESENTATION; + public DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HasGraphRepresentation; /// - public DataFeatures RequiredDataFeatures => DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public DataFeatures RequiredDataFeatures => DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/NWChemFormat.cs b/NCDK/IO/Formats/NWChemFormat.cs index 9bfaae9a..4ad387be 100644 --- a/NCDK/IO/Formats/NWChemFormat.cs +++ b/NCDK/IO/Formats/NWChemFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "nw", "nwo" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "nw", "nwo" }; /// public override string ReaderClassName => null; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Northwest Computational Chemistry Package") >= 0) + if (line.Contains("Northwest Computational Chemistry Package")) { return true; } diff --git a/NCDK/IO/Formats/PCModelFormat.cs b/NCDK/IO/Formats/PCModelFormat.cs index 9c516e85..efa5e306 100644 --- a/NCDK/IO/Formats/PCModelFormat.cs +++ b/NCDK/IO/Formats/PCModelFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "pcm" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "pcm" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/PDBFormat.cs b/NCDK/IO/Formats/PDBFormat.cs index 6c3db3ca..c76ea032 100644 --- a/NCDK/IO/Formats/PDBFormat.cs +++ b/NCDK/IO/Formats/PDBFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "pdb", "ent" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "pdb", "ent" }; /// public override string ReaderClassName { get; } = typeof(PDBReader).FullName; @@ -75,10 +76,10 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures SupportedDataFeatures => - DataFeatures.HAS_FRACTIONAL_CRYSTAL_COORDINATES | RequiredDataFeatures; + DataFeatures.HasFractionalCrystalCoordinates | RequiredDataFeatures; /// public override DataFeatures RequiredDataFeatures => - DataFeatures.HAS_3D_COORDINATES | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.Has3DCoordinates | DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/PDBMLFormat.cs b/NCDK/IO/Formats/PDBMLFormat.cs index 4c116b80..7195aa29 100644 --- a/NCDK/IO/Formats/PDBMLFormat.cs +++ b/NCDK/IO/Formats/PDBMLFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -53,7 +54,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/PMPFormat.cs b/NCDK/IO/Formats/PMPFormat.cs index 792685f8..56eb9d61 100644 --- a/NCDK/IO/Formats/PMPFormat.cs +++ b/NCDK/IO/Formats/PMPFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "pmp" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "pmp" }; /// public override string ReaderClassName { get; } = typeof(PMPReader).FullName; diff --git a/NCDK/IO/Formats/POVRayFormat.cs b/NCDK/IO/Formats/POVRayFormat.cs index 8818381a..5017e5c1 100644 --- a/NCDK/IO/Formats/POVRayFormat.cs +++ b/NCDK/IO/Formats/POVRayFormat.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System.Collections.Generic; + namespace NCDK.IO.Formats { /// @@ -50,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "pov" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "pov" }; /// public override bool IsXmlBased => false; diff --git a/NCDK/IO/Formats/PQSChemFormat.cs b/NCDK/IO/Formats/PQSChemFormat.cs index 21aa9869..9ce5bc32 100644 --- a/NCDK/IO/Formats/PQSChemFormat.cs +++ b/NCDK/IO/Formats/PQSChemFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { /// @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "pqs" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "pqs" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/PubChemASNFormat.cs b/NCDK/IO/Formats/PubChemASNFormat.cs index ebc1889c..eae99bed 100644 --- a/NCDK/IO/Formats/PubChemASNFormat.cs +++ b/NCDK/IO/Formats/PubChemASNFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "asn" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "asn" }; /// public override string ReaderClassName { get; } = typeof(PCCompoundASNReader).FullName; diff --git a/NCDK/IO/Formats/PubChemCompoundXMLFormat.cs b/NCDK/IO/Formats/PubChemCompoundXMLFormat.cs index aaf969f4..5868c8d5 100644 --- a/NCDK/IO/Formats/PubChemCompoundXMLFormat.cs +++ b/NCDK/IO/Formats/PubChemCompoundXMLFormat.cs @@ -49,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "xml" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "xml" }; /// public string ReaderClassName { get; } = typeof(PCCompoundXMLReader).FullName; @@ -66,14 +66,17 @@ public static IResourceFormat Instance /// public DataFeatures RequiredDataFeatures => DataFeatures.None; - public MatchResult Matches(IList lines) + public MatchResult Matches(IEnumerable lines) { - MatchResult result = MatchResult.NO_MATCH; - for (int i = 0; i < lines.Count; i++) + MatchResult result = MatchResult.NoMatch; + int i = 0; + foreach (var line in lines) { - string line = lines[i]; - if (line.Contains(" NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "xml" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "xml" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/PubChemFormat.cs b/NCDK/IO/Formats/PubChemFormat.cs index ef7279e9..ab21a7fe 100644 --- a/NCDK/IO/Formats/PubChemFormat.cs +++ b/NCDK/IO/Formats/PubChemFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "pc" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "pc" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/PubChemSubstanceXMLFormat.cs b/NCDK/IO/Formats/PubChemSubstanceXMLFormat.cs index 53d28d8c..1f6a2afd 100644 --- a/NCDK/IO/Formats/PubChemSubstanceXMLFormat.cs +++ b/NCDK/IO/Formats/PubChemSubstanceXMLFormat.cs @@ -34,7 +34,8 @@ public static IResourceFormat Instance { get { - if (myself == null) myself = new PubChemSubstanceXMLFormat(); + if (myself == null) + myself = new PubChemSubstanceXMLFormat(); return myself; } } @@ -50,7 +51,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "xml" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "xml" }; /// public string ReaderClassName { get; } = typeof(PCSubstanceXMLReader).FullName; @@ -68,14 +69,17 @@ public static IResourceFormat Instance public DataFeatures RequiredDataFeatures => DataFeatures.None; /// - public MatchResult Matches(IList lines) + public MatchResult Matches(IEnumerable lines) { - MatchResult result = MatchResult.NO_MATCH; - for (int i = 0; i < lines.Count; i++) + MatchResult result = MatchResult.NoMatch; + int i = 0; + foreach (var line in lines) { - var line = lines[i]; - if (line.Contains(" NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "asn" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "asn" }; /// public override string ReaderClassName => null; @@ -69,7 +70,8 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (lineNumber == 1 && line.StartsWith("PC-Substances", StringComparison.Ordinal)) return true; + if (lineNumber == 1 && line.StartsWith("PC-Substances", StringComparison.Ordinal)) + return true; return false; } } diff --git a/NCDK/IO/Formats/PubChemSubstancesXMLFormat.cs b/NCDK/IO/Formats/PubChemSubstancesXMLFormat.cs index 11deb24d..47f34554 100644 --- a/NCDK/IO/Formats/PubChemSubstancesXMLFormat.cs +++ b/NCDK/IO/Formats/PubChemSubstancesXMLFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "xml" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "xml" }; /// public override string ReaderClassName => null; diff --git a/NCDK/IO/Formats/QChemFormat.cs b/NCDK/IO/Formats/QChemFormat.cs index bbc71ff6..6f32f953 100644 --- a/NCDK/IO/Formats/QChemFormat.cs +++ b/NCDK/IO/Formats/QChemFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "qc" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "qc" }; /// public override string ReaderClassName => null; @@ -62,7 +63,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Welcome to Q-Chem") != -1) + if (line.Contains("Welcome to Q-Chem")) { return true; } diff --git a/NCDK/IO/Formats/RGroupQueryFormat.cs b/NCDK/IO/Formats/RGroupQueryFormat.cs index 57c95144..82420703 100644 --- a/NCDK/IO/Formats/RGroupQueryFormat.cs +++ b/NCDK/IO/Formats/RGroupQueryFormat.cs @@ -23,6 +23,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -57,7 +58,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mol", "rgp" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mol", "rgp" }; /// public override string ReaderClassName { get; } = typeof(RGroupQueryReader).FullName; @@ -68,7 +69,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("$RGP") >= 0) + if (line.Contains("$RGP")) return true; else return false; @@ -78,9 +79,9 @@ public override bool Matches(int lineNumber, string line) public override bool IsXmlBased => false; /// - public override DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HAS_2D_COORDINATES; + public override DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.Has2DCoordinates; /// - public override DataFeatures RequiredDataFeatures => DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public override DataFeatures RequiredDataFeatures => DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/RawCopyFormat.cs b/NCDK/IO/Formats/RawCopyFormat.cs index bbedcd53..1a147695 100644 --- a/NCDK/IO/Formats/RawCopyFormat.cs +++ b/NCDK/IO/Formats/RawCopyFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "copy" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "copy" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/SDFFormat.cs b/NCDK/IO/Formats/SDFFormat.cs index 524a966a..278e9731 100644 --- a/NCDK/IO/Formats/SDFFormat.cs +++ b/NCDK/IO/Formats/SDFFormat.cs @@ -18,6 +18,8 @@ */ using NCDK.Tools; +using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "sdf", "sd" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "sdf", "sd" }; /// public override string ReaderClassName { get; } = typeof(MDLV2000Reader).FullName; @@ -62,7 +64,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.Equals("$$$$")) + if (string.Equals(line, "$$$$", StringComparison.Ordinal)) { return true; } @@ -74,11 +76,11 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures SupportedDataFeatures => - RequiredDataFeatures | DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_GRAPH_REPRESENTATION; + RequiredDataFeatures | DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasGraphRepresentation; /// public override DataFeatures RequiredDataFeatures => - DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/SMARTSFormat.cs b/NCDK/IO/Formats/SMARTSFormat.cs index 1bb4198b..15ed2c11 100644 --- a/NCDK/IO/Formats/SMARTSFormat.cs +++ b/NCDK/IO/Formats/SMARTSFormat.cs @@ -18,6 +18,8 @@ */ using NCDK.Tools; +using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +54,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = new string[0]; + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/SMILESFIXFormat.cs b/NCDK/IO/Formats/SMILESFIXFormat.cs index ae620fa8..9b0953bc 100644 --- a/NCDK/IO/Formats/SMILESFIXFormat.cs +++ b/NCDK/IO/Formats/SMILESFIXFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "fix" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "fix" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/SMILESFormat.cs b/NCDK/IO/Formats/SMILESFormat.cs index 47084acb..e23ac0a7 100644 --- a/NCDK/IO/Formats/SMILESFormat.cs +++ b/NCDK/IO/Formats/SMILESFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "smi" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "smi" }; /// public string ReaderClassName { get; } = typeof(SMILESReader).FullName; @@ -65,10 +66,10 @@ public static IResourceFormat Instance /// public DataFeatures SupportedDataFeatures => - RequiredDataFeatures | DataFeatures.HAS_GRAPH_REPRESENTATION; + RequiredDataFeatures | DataFeatures.HasGraphRepresentation; /// public DataFeatures RequiredDataFeatures => - DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/SVGFormat.cs b/NCDK/IO/Formats/SVGFormat.cs index 704c7023..9064443d 100644 --- a/NCDK/IO/Formats/SVGFormat.cs +++ b/NCDK/IO/Formats/SVGFormat.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System.Collections.Generic; + namespace NCDK.IO.Formats { // @cdk.module ioformats @@ -46,7 +48,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "svg" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "svg" }; /// public override bool IsXmlBased => true; diff --git a/NCDK/IO/Formats/ShelXFormat.cs b/NCDK/IO/Formats/ShelXFormat.cs index bee23418..90296a81 100644 --- a/NCDK/IO/Formats/ShelXFormat.cs +++ b/NCDK/IO/Formats/ShelXFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "ins", "res" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "ins", "res" }; /// public override string ReaderClassName { get; } = typeof(ShelXReader).FullName; @@ -78,7 +79,7 @@ public override bool Matches(int lineNumber, string line) /// public override DataFeatures RequiredDataFeatures => - DataFeatures.HAS_3D_COORDINATES | DataFeatures.HAS_UNITCELL_PARAMETERS - | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + DataFeatures.Has3DCoordinates | DataFeatures.HasUnitcellParameters + | DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/SimpleChemFormatMatcher.cs b/NCDK/IO/Formats/SimpleChemFormatMatcher.cs index 51dcc103..f9a6975a 100644 --- a/NCDK/IO/Formats/SimpleChemFormatMatcher.cs +++ b/NCDK/IO/Formats/SimpleChemFormatMatcher.cs @@ -23,7 +23,6 @@ */ using NCDK.Tools; -using System; using System.Collections.Generic; namespace NCDK.IO.Formats @@ -55,14 +54,16 @@ public abstract class SimpleChemFormatMatcher : AbstractResourceFormat, IChemFor /// /// lines of the input to be checked /// runs the lines - public MatchResult Matches(IList lines) + public MatchResult Matches(IEnumerable lines) { - for (int i = 0; i < lines.Count; i++) - { - if (Matches(i + 1, lines[i])) + int i = 0; + foreach (var line in lines) + { + if (Matches(i + 1, line)) return new MatchResult(true, this, i); + i++; } - return MatchResult.NO_MATCH; + return MatchResult.NoMatch; } } } diff --git a/NCDK/IO/Formats/SpartanFormat.cs b/NCDK/IO/Formats/SpartanFormat.cs index 8fd51abd..821ad306 100644 --- a/NCDK/IO/Formats/SpartanFormat.cs +++ b/NCDK/IO/Formats/SpartanFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName => null; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("Spartan") != -1 && line.IndexOf("Quantum Mechanics Program") != -1) + if (line.Contains("Spartan") && line.Contains("Quantum Mechanics Program")) { return true; } diff --git a/NCDK/IO/Formats/SybylDescriptorFormat.cs b/NCDK/IO/Formats/SybylDescriptorFormat.cs index 0b3ba871..3db8f6ff 100644 --- a/NCDK/IO/Formats/SybylDescriptorFormat.cs +++ b/NCDK/IO/Formats/SybylDescriptorFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -51,7 +52,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "mpd" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "mpd" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/TinkerMM2Format.cs b/NCDK/IO/Formats/TinkerMM2Format.cs index 67cba7d7..81223f65 100644 --- a/NCDK/IO/Formats/TinkerMM2Format.cs +++ b/NCDK/IO/Formats/TinkerMM2Format.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -53,7 +54,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/TinkerXYZFormat.cs b/NCDK/IO/Formats/TinkerXYZFormat.cs index 4c609e8e..dc450468 100644 --- a/NCDK/IO/Formats/TinkerXYZFormat.cs +++ b/NCDK/IO/Formats/TinkerXYZFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "txyz" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "txyz" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/TurboMoleFormat.cs b/NCDK/IO/Formats/TurboMoleFormat.cs index 4217a560..4737b758 100644 --- a/NCDK/IO/Formats/TurboMoleFormat.cs +++ b/NCDK/IO/Formats/TurboMoleFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "tmol" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "tmol" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/UniChemXYZFormat.cs b/NCDK/IO/Formats/UniChemXYZFormat.cs index b8664647..dd004ae5 100644 --- a/NCDK/IO/Formats/UniChemXYZFormat.cs +++ b/NCDK/IO/Formats/UniChemXYZFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "unixyz" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "unixyz" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/VASPFormat.cs b/NCDK/IO/Formats/VASPFormat.cs index 4b0a9feb..35a61567 100644 --- a/NCDK/IO/Formats/VASPFormat.cs +++ b/NCDK/IO/Formats/VASPFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions => Array.Empty(); + public override IReadOnlyList NameExtensions => Array.Empty(); /// public override string ReaderClassName { get; } = typeof(VASPReader).FullName; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (line.IndexOf("NCLASS=") >= 0) + if (line.Contains("NCLASS=")) { return true; } diff --git a/NCDK/IO/Formats/ViewmolFormat.cs b/NCDK/IO/Formats/ViewmolFormat.cs index ec9e859d..f8bc2dbb 100644 --- a/NCDK/IO/Formats/ViewmolFormat.cs +++ b/NCDK/IO/Formats/ViewmolFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "vmol" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "vmol" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/XEDFormat.cs b/NCDK/IO/Formats/XEDFormat.cs index ccb73445..aca569c6 100644 --- a/NCDK/IO/Formats/XEDFormat.cs +++ b/NCDK/IO/Formats/XEDFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "xed" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "xed" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/XYZFormat.cs b/NCDK/IO/Formats/XYZFormat.cs index 116b33de..76dee28d 100644 --- a/NCDK/IO/Formats/XYZFormat.cs +++ b/NCDK/IO/Formats/XYZFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -48,7 +49,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "xyz" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "xyz" }; /// public string ReaderClassName { get; } = typeof(XYZReader).FullName; @@ -60,9 +61,9 @@ public static IResourceFormat Instance public override bool IsXmlBased => false; /// - public DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HAS_ATOM_PARTIAL_CHARGES; + public DataFeatures SupportedDataFeatures => RequiredDataFeatures | DataFeatures.HasAtomPartialCharges; /// - public DataFeatures RequiredDataFeatures => DataFeatures.HAS_3D_COORDINATES | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public DataFeatures RequiredDataFeatures => DataFeatures.Has3DCoordinates | DataFeatures.HasAtomElementSymbol; } } diff --git a/NCDK/IO/Formats/YasaraFormat.cs b/NCDK/IO/Formats/YasaraFormat.cs index d539ad2f..1ecf4dcf 100644 --- a/NCDK/IO/Formats/YasaraFormat.cs +++ b/NCDK/IO/Formats/YasaraFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "yob" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "yob" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/Formats/ZMatrixFormat.cs b/NCDK/IO/Formats/ZMatrixFormat.cs index a1d6145d..36bcbacc 100644 --- a/NCDK/IO/Formats/ZMatrixFormat.cs +++ b/NCDK/IO/Formats/ZMatrixFormat.cs @@ -19,6 +19,7 @@ using NCDK.Tools; using System; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -49,7 +50,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => null; /// - public override string[] NameExtensions { get; } = Array.Empty(); + public override IReadOnlyList NameExtensions { get; } = Array.Empty(); /// public override string ReaderClassName { get; } = typeof(ZMatrixReader).FullName; @@ -60,7 +61,7 @@ public static IResourceFormat Instance /// public override bool Matches(int lineNumber, string line) { - if (lineNumber == 4 && line.IndexOf("Z Matrix") != -1) + if (lineNumber == 4 && line.Contains("Z Matrix")) { return true; } diff --git a/NCDK/IO/Formats/ZindoFormat.cs b/NCDK/IO/Formats/ZindoFormat.cs index 89716d8c..d0abc9a4 100644 --- a/NCDK/IO/Formats/ZindoFormat.cs +++ b/NCDK/IO/Formats/ZindoFormat.cs @@ -18,6 +18,7 @@ */ using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO.Formats { @@ -52,7 +53,7 @@ public static IResourceFormat Instance public override string PreferredNameExtension => NameExtensions[0]; /// - public override string[] NameExtensions { get; } = new string[] { "zin" }; + public override IReadOnlyList NameExtensions { get; } = new string[] { "zin" }; /// public string ReaderClassName => null; diff --git a/NCDK/IO/GamessReader.cs b/NCDK/IO/GamessReader.cs index 7b12c0ba..6d739d5e 100644 --- a/NCDK/IO/GamessReader.cs +++ b/NCDK/IO/GamessReader.cs @@ -170,7 +170,7 @@ private IChemFile ReadChemFile(IChemFile file) while (currentReadLine != null) { // There are 2 types of coordinate sets: - bohr coordinates sets (if statement) - angstr???m coordinates sets (else statement) - if (currentReadLine.IndexOf("COORDINATES (BOHR)") >= 0) + if (currentReadLine.Contains("COORDINATES (BOHR)")) { // The following line do no contain data, so it is ignored. this.input.ReadLine(); @@ -178,7 +178,7 @@ private IChemFile ReadChemFile(IChemFile file) GamessReader.BohrUnit)); //break; //<- stops when the first set of coordinates is found. } - else if (currentReadLine.IndexOf(" COORDINATES OF ALL ATOMS ARE (ANGS)") >= 0) + else if (currentReadLine.Contains(" COORDINATES OF ALL ATOMS ARE (ANGS)")) { // The following 2 lines do no contain data, so it are ignored. this.input.ReadLine(); @@ -237,10 +237,10 @@ private IAtomContainer ReadCoordinates(IAtomContainer molecule, bool coordinates // be concatenated with a number. token.NextToken(); - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { atomicNumber = (int)token.NumberValue; - atomicSymbol = this.IdentifyAtomicSymbol(atomicNumber); + atomicSymbol = IdentifyAtomicSymbol(atomicNumber); // Dummy atoms are assumed to be given with an atomic number set // to zero. We will do not add them to the molecule. @@ -258,7 +258,7 @@ private IAtomContainer ReadCoordinates(IAtomContainer molecule, bool coordinates double[] coordinates = new double[3]; for (int i = 0; i < coordinates.Length; i++) { - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { coordinates[i] = token.NumberValue * unitScaling; } @@ -286,7 +286,7 @@ private IAtomContainer ReadCoordinates(IAtomContainer molecule, bool coordinates /// The atomic number of an atom. /// The Symbol corresponding to the atom or "null" is the atom was not recognised. //TODO Update method comments with appropriate information. - private string IdentifyAtomicSymbol(int atomicNumber) + private static string IdentifyAtomicSymbol(int atomicNumber) { string symbol; switch (atomicNumber) diff --git a/NCDK/IO/Gaussian03Reader.cs b/NCDK/IO/Gaussian03Reader.cs index ad038e49..29b99be7 100644 --- a/NCDK/IO/Gaussian03Reader.cs +++ b/NCDK/IO/Gaussian03Reader.cs @@ -132,7 +132,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) // Find first set of coordinates while (line != null) { - if (line.IndexOf("Standard orientation:") >= 0) + if (line.Contains("Standard orientation:")) { // Found a set of coordinates @@ -155,46 +155,35 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) line = input.ReadLine(); while (line != null) { - if (line.IndexOf("Standard orientation:") >= 0) + if (line.Contains("Standard orientation:")) { // Found a set of coordinates // Add current frame to file and create a new one. sequence.Add(model); - FireFrameRead(); + FrameRead(); model = sequence.Builder.NewChemModel(); ReadCoordinates(model); } - else if (line.IndexOf("SCF Done:") >= 0) + else if (line.Contains("SCF Done:")) { // Found an energy model.SetProperty("NCDK.IO.Gaussian03Reaer:SCF Done", line.Trim()); } - else if (line.IndexOf("Harmonic frequencies") >= 0) + else if (line.Contains("Harmonic frequencies")) { // Found a set of vibrations - // try { - // ReadFrequencies(model); - // } catch (IOException exception) { - // throw new CDKException("Error while reading frequencies: " + exception.ToString(), exception); - // } } - else if (line.IndexOf("Mulliken atomic charges") >= 0) + else if (line.Contains("Mulliken atomic charges")) { ReadPartialCharges(model); } - else if (line.IndexOf("Magnetic shielding") >= 0) + else if (line.Contains("Magnetic shielding")) { // Found NMR data - // try { - // ReadNMRData(model, line); - // } catch (IOException exception) { - // throw new CDKException("Error while reading NMR data: " + exception.ToString(), exception); - // } } - else if (line.IndexOf("GINC") >= 0) + else if (line.Contains("GINC")) { // Found calculation level of theory - //levelOfTheory = ParseLevelOfTheory(line); // FIXME: is doing anything with it? } line = input.ReadLine(); @@ -202,7 +191,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) // Add current frame to file sequence.Add(model); - FireFrameRead(); + FrameRead(); } } catch (IOException exception) @@ -227,7 +216,7 @@ private void ReadCoordinates(IChemModel model) while (true) { line = input.ReadLine(); - if ((line == null) || (line.IndexOf("-----") >= 0)) + if ((line == null) || (line.Contains("-----"))) { break; } @@ -237,12 +226,11 @@ private void ReadCoordinates(IChemModel model) token.NextToken(); // ignore first token - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { atomicNumber = (int)token.NumberValue; if (atomicNumber == 0) { - // Skip dummy atoms. Dummy atoms must be skipped // if frequencies are to be read because Gaussian // does not report dummy atoms in frequencies, and @@ -260,7 +248,7 @@ private void ReadCoordinates(IChemModel model) double x = 0.0; double y = 0.0; double z = 0.0; - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { x = token.NumberValue; } @@ -268,7 +256,7 @@ private void ReadCoordinates(IChemModel model) { throw new IOException("Error reading coordinates"); } - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { y = token.NumberValue; } @@ -276,7 +264,7 @@ private void ReadCoordinates(IChemModel model) { throw new IOException("Error reading coordinates"); } - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { z = token.NumberValue; } @@ -307,22 +295,22 @@ private void ReadPartialCharges(IChemModel model) while (true) { line = input.ReadLine(); - Debug.WriteLine("Read charge block line: " + line); - if ((line == null) || (line.IndexOf("Sum of Mulliken charges") >= 0)) + Debug.WriteLine($"Read charge block line: {line}"); + if ((line == null) || line.Contains("Sum of Mulliken charges")) { Debug.WriteLine("End of charge block found"); break; } StringReader sr = new StringReader(line); StreamTokenizer tokenizer = new StreamTokenizer(sr); - if (tokenizer.NextToken() == StreamTokenizer.TT_NUMBER) + if (tokenizer.NextToken() == StreamTokenizer.TTypeNumber) { int atomCounter = (int)tokenizer.NumberValue; tokenizer.NextToken(); // ignore the symbol double charge = 0.0; - if (tokenizer.NextToken() == StreamTokenizer.TT_NUMBER) + if (tokenizer.NextToken() == StreamTokenizer.TTypeNumber) { charge = (double)tokenizer.NumberValue; Debug.WriteLine("Found charge for atom " + atomCounter + ": " + charge); diff --git a/NCDK/IO/Gaussian98Reader.cs b/NCDK/IO/Gaussian98Reader.cs index b386ea5b..e67673f9 100644 --- a/NCDK/IO/Gaussian98Reader.cs +++ b/NCDK/IO/Gaussian98Reader.cs @@ -28,6 +28,7 @@ using NCDK.Tools.Manipulator; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -149,7 +150,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) // Find first set of coordinates by skipping all before "Standard orientation" while (line != null) { - if (line.IndexOf("Standard orientation:") >= 0) + if (line.Contains("Standard orientation:")) { // Found a set of coordinates @@ -173,7 +174,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) modelCounter = 0; } - else if (line.IndexOf("Standard orientation:") >= 0) + else if (line.Contains("Standard orientation:")) { // Found a set of coordinates @@ -186,49 +187,48 @@ private IChemFile ReadChemFile(IChemFile chemFile) { Trace.TraceInformation("Skipping frame, because I was told to do"); } - FireFrameRead(); + FrameRead(); model = chemFile.Builder.NewChemModel(); modelCounter++; ReadCoordinates(model); } - else if (line.IndexOf("SCF Done:") >= 0) + else if (line.Contains("SCF Done:")) { // Found an energy model.SetProperty(CDKPropertyName.Remark, line.Trim()); } - else if (line.IndexOf("Harmonic frequencies") >= 0) + else if (line.Contains("Harmonic frequencies")) { // Found a set of vibrations // ReadFrequencies(frame); } - else if (line.IndexOf("Total atomic charges") >= 0) + else if (line.Contains("Total atomic charges")) { ReadPartialCharges(model); } - else if (line.IndexOf("Magnetic shielding") >= 0) + else if (line.Contains("Magnetic shielding")) { // Found NMR data ReadNMRData(model, line); } - else if (line.IndexOf("GINC") >= 0) + else if (line.Contains("GINC")) { // Found calculation level of theory levelOfTheory = ParseLevelOfTheory(line); - Debug.WriteLine("Level of Theory for this model: " + levelOfTheory); + Debug.WriteLine($"Level of Theory for this model: {levelOfTheory}"); description = lastRoute + ", model no. " + modelCounter; model.SetProperty(CDKPropertyName.Description, description); } else { - //Debug.WriteLine("Skipping line: " + line); } line = input.ReadLine(); } // Add last frame to file sequence.Add(model); - FireFrameRead(); + FrameRead(); } chemFile.Add(sequence); @@ -250,7 +250,7 @@ private void ReadCoordinates(IChemModel model) while (true) { line = input.ReadLine(); - if ((line == null) || (line.IndexOf("-----") >= 0)) + if ((line == null) || (line.Contains("-----"))) { break; } @@ -260,7 +260,7 @@ private void ReadCoordinates(IChemModel model) token.NextToken(); // ignore first token - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { atomicNumber = (int)token.NumberValue; if (atomicNumber == 0) @@ -282,7 +282,7 @@ private void ReadCoordinates(IChemModel model) double x; double y; double z; - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { x = token.NumberValue; } @@ -290,7 +290,7 @@ private void ReadCoordinates(IChemModel model) { throw new IOException("Error reading x coordinate"); } - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { y = token.NumberValue; } @@ -298,7 +298,7 @@ private void ReadCoordinates(IChemModel model) { throw new IOException("Error reading y coordinate"); } - if (token.NextToken() == StreamTokenizer.TT_NUMBER) + if (token.NextToken() == StreamTokenizer.TTypeNumber) { z = token.NumberValue; } @@ -334,15 +334,15 @@ private void ReadPartialCharges(IChemModel model) while (true) { line = input.ReadLine(); - Debug.WriteLine("Read charge block line: " + line); - if ((line == null) || (line.IndexOf("Sum of Mulliken charges") >= 0)) + Debug.WriteLine($"Read charge block line: {line}"); + if ((line == null) || line.Contains("Sum of Mulliken charges")) { Debug.WriteLine("End of charge block found"); break; } StringReader sr = new StringReader(line); StreamTokenizer tokenizer = new StreamTokenizer(sr); - if (tokenizer.NextToken() == StreamTokenizer.TT_NUMBER) + if (tokenizer.NextToken() == StreamTokenizer.TTypeNumber) { int atomCounter = (int)tokenizer.NumberValue; @@ -350,7 +350,7 @@ private void ReadPartialCharges(IChemModel model) // ignore the symbol double charge; - if (tokenizer.NextToken() == StreamTokenizer.TT_NUMBER) + if (tokenizer.NextToken() == StreamTokenizer.TTypeNumber) { charge = tokenizer.NumberValue; Debug.WriteLine("Found charge for atom " + atomCounter + ": " + charge); @@ -382,11 +382,11 @@ private void ReadNMRData(IChemModel model, string labelLine) IAtomContainer ac = containers[0]; // Determine label for properties string label; - if (labelLine.IndexOf("Diamagnetic") >= 0) + if (labelLine.Contains("Diamagnetic")) { label = "Diamagnetic Magnetic shielding (Isotropic)"; } - else if (labelLine.IndexOf("Paramagnetic") >= 0) + else if (labelLine.Contains("Paramagnetic")) { label = "Paramagnetic Magnetic shielding (Isotropic)"; } @@ -400,7 +400,7 @@ private void ReadNMRData(IChemModel model, string labelLine) try { string line = input.ReadLine().Trim(); - while (line.IndexOf("Isotropic") < 0) + while (!line.Contains("Isotropic")) { if (line == null) { @@ -413,7 +413,7 @@ private void ReadNMRData(IChemModel model, string labelLine) // Find Isotropic label while (st1.MoveNext()) { - if (st1.Current.Equals("Isotropic")) + if (string.Equals(st1.Current, "Isotropic", StringComparison.Ordinal)) { break; } @@ -422,10 +422,10 @@ private void ReadNMRData(IChemModel model, string labelLine) // Find Isotropic value while (st1.MoveNext()) { - if (st1.Current.Equals("=")) break; + if (string.Equals(st1.Current, "=", StringComparison.Ordinal)) break; } st1.MoveNext(); - double shielding = double.Parse(st1.Current); + double shielding = double.Parse(st1.Current, NumberFormatInfo.InvariantInfo); Trace.TraceInformation("Type of shielding: " + label); ac.Atoms[atomIndex].SetProperty(CDKPropertyName.IsotropicShielding, shielding); ++atomIndex; @@ -476,13 +476,13 @@ private string ParseLevelOfTheory(string line) private void InitIOSettings() { readOptimizedStructureOnly = Add(new BooleanIOSetting("ReadOptimizedStructureOnly", - IOSetting.Importance.Low, "Should I only read the optimized structure from a geometry optimization?", + Importance.Low, "Should I only read the optimized structure from a geometry optimization?", "false")); } private void CustomizeJob() { - FireIOSettingQuestion(readOptimizedStructureOnly); + ProcessIOSettingQuestion(readOptimizedStructureOnly); } } } diff --git a/NCDK/IO/GaussianInputWriter.cs b/NCDK/IO/GaussianInputWriter.cs index 4dc985c4..2b234a59 100644 --- a/NCDK/IO/GaussianInputWriter.cs +++ b/NCDK/IO/GaussianInputWriter.cs @@ -21,7 +21,9 @@ using NCDK.IO.Setting; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; +using System.Text; namespace NCDK.IO { @@ -120,7 +122,7 @@ public void WriteMolecule(IAtomContainer mol) writer.Write("%nprocl=" + proccount.GetSettingValue()); writer.Write('\n'); } - if (!memory.Setting.Equals("unset")) + if (!string.Equals(memory.Setting, "unset", StringComparison.Ordinal)) { writer.Write("%Mem=" + memory.Setting); writer.Write('\n'); @@ -142,19 +144,19 @@ public void WriteMolecule(IAtomContainer mol) // write the command line writer.Write("# " + method.Setting + "/" + basis.Setting + " "); string commandString = command.Setting; - if (commandString.Equals("energy calculation")) + if (string.Equals(commandString, "energy calculation", StringComparison.Ordinal)) { // ok, no special command needed } - else if (commandString.Equals("geometry optimization")) + else if (string.Equals(commandString, "geometry optimization", StringComparison.Ordinal)) { writer.Write("opt"); } - else if (commandString.Equals("IR frequency calculation")) + else if (string.Equals(commandString, "IR frequency calculation", StringComparison.Ordinal)) { writer.Write("freq"); } - else if (commandString.Equals("IR frequency calculation (with Raman)")) + else if (string.Equals(commandString, "IR frequency calculation (with Raman)", StringComparison.Ordinal)) { writer.Write("freq=noraman"); } @@ -192,19 +194,21 @@ public void WriteMolecule(IAtomContainer mol) // Loop through the atoms and write them out: foreach (var a in mol.Atoms) { - string st = a.Symbol; + var sb = new StringBuilder(a.Symbol); // export Eucledian coordinates (indicated by the 0) - st = st + " 0 "; + sb.Append(" 0 "); // export the 3D coordinates var p3 = a.Point3D; if (p3 != null) { - st = st + p3.Value.X.ToString() + " " + p3.Value.Y.ToString() + " " - + p3.Value.Z.ToString(); + sb.Append(p3.Value.X.ToString(NumberFormatInfo.InvariantInfo)).Append(" ") + .Append(p3.Value.Y.ToString(NumberFormatInfo.InvariantInfo)).Append(" ") + .Append(p3.Value.Z.ToString(NumberFormatInfo.InvariantInfo)); } + var st = sb.ToString(); writer.Write(st, 0, st.Length); writer.Write('\n'); } @@ -223,7 +227,7 @@ private void InitIOSettings() "6-311g", "6-311+g**" }; - basis = new OptionIOSetting("Basis", IOSetting.Importance.Medium, "Which basis set do you want to use?", + basis = new OptionIOSetting("Basis", Importance.Medium, "Which basis set do you want to use?", basisOptions, "6-31g"); var methodOptions = new List @@ -232,7 +236,7 @@ private void InitIOSettings() "b3lyp", "rhf" }; - method = new OptionIOSetting("Method", IOSetting.Importance.Medium, "Which method do you want to use?", + method = new OptionIOSetting("Method", Importance.Medium, "Which method do you want to use?", methodOptions, "b3lyp"); var commandOptions = new List @@ -242,22 +246,22 @@ private void InitIOSettings() "IR frequency calculation", "IR frequency calculation (with Raman)" }; - command = IOSettings.Add(new OptionIOSetting("Command", IOSetting.Importance.High, + command = IOSettings.Add(new OptionIOSetting("Command", Importance.High, "What kind of job do you want to perform?", commandOptions, "energy calculation")); - comment = IOSettings.Add(new StringIOSetting("Comment", IOSetting.Importance.Low, + comment = IOSettings.Add(new StringIOSetting("Comment", Importance.Low, "What comment should be put in the file?", "Created with CDK (http://cdk.sf.net/)")); - memory = IOSettings.Add(new StringIOSetting("Memory", IOSetting.Importance.Low, + memory = IOSettings.Add(new StringIOSetting("Memory", Importance.Low, "How much memory do you want to use?", "unset")); - shell = IOSettings.Add(new BooleanIOSetting("OpenShell", IOSetting.Importance.Medium, + shell = IOSettings.Add(new BooleanIOSetting("OpenShell", Importance.Medium, "Should the calculation be open shell?", "false")); - proccount = IOSettings.Add(new IntegerIOSetting("ProcessorCount", IOSetting.Importance.Low, + proccount = IOSettings.Add(new IntegerIOSetting("ProcessorCount", Importance.Low, "How many processors should be used by Gaussian?", "1")); - usecheckpoint = new BooleanIOSetting("UseCheckPointFile", IOSetting.Importance.Low, + usecheckpoint = new BooleanIOSetting("UseCheckPointFile", Importance.Low, "Should a check point file be saved?", "false"); } @@ -265,7 +269,7 @@ private void CustomizeJob() { foreach (var setting in IOSettings.Settings) { - FireIOSettingQuestion(setting); + ProcessIOSettingQuestion(setting); } } } diff --git a/NCDK/IO/GhemicalMMReader.cs b/NCDK/IO/GhemicalMMReader.cs index 9d084ca9..e60526bc 100644 --- a/NCDK/IO/GhemicalMMReader.cs +++ b/NCDK/IO/GhemicalMMReader.cs @@ -24,6 +24,7 @@ using NCDK.Numerics; using System; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -117,22 +118,22 @@ private IChemModel ReadChemModel(IChemModel model) { var st = Strings.Tokenize(line); string command = st[0]; - if ("!Header".Equals(command)) + if (string.Equals("!Header", command, StringComparison.Ordinal)) { Trace.TraceWarning("Ignoring header"); } - else if ("!Info".Equals(command)) + else if (string.Equals("!Info", command, StringComparison.Ordinal)) { Trace.TraceWarning("Ignoring info"); } - else if ("!Atoms".Equals(command)) + else if (string.Equals("!Atoms", command, StringComparison.Ordinal)) { Trace.TraceInformation("Reading atom block"); // determine number of atoms to read try { - numberOfAtoms = int.Parse(st[1]); - Debug.WriteLine(" #atoms: " + numberOfAtoms); + numberOfAtoms = int.Parse(st[1], NumberFormatInfo.InvariantInfo); + Debug.WriteLine($" #atoms: {numberOfAtoms}"); atoms = new int[numberOfAtoms]; atomxs = new double[numberOfAtoms]; atomys = new double[numberOfAtoms]; @@ -143,8 +144,8 @@ private IChemModel ReadChemModel(IChemModel model) { line = input.ReadLine(); var atomInfoFields = Strings.Tokenize(line); - int atomID = int.Parse(atomInfoFields[0]); - atoms[atomID] = int.Parse(atomInfoFields[1]); + int atomID = int.Parse(atomInfoFields[0], NumberFormatInfo.InvariantInfo); + atoms[atomID] = int.Parse(atomInfoFields[1], NumberFormatInfo.InvariantInfo); Debug.WriteLine("Set atomic number of atom (" + atomID + ") to: " + atoms[atomID]); } } @@ -156,13 +157,13 @@ private IChemModel ReadChemModel(IChemModel model) Debug.WriteLine(exception); } } - else if ("!Bonds".Equals(command)) + else if (string.Equals("!Bonds", command, StringComparison.Ordinal)) { Trace.TraceInformation("Reading bond block"); try { // determine number of bonds to read - numberOfBonds = int.Parse(st[1]); + numberOfBonds = int.Parse(st[1], NumberFormatInfo.InvariantInfo); bondatomid1 = new int[numberOfAtoms]; bondatomid2 = new int[numberOfAtoms]; bondorder = new BondOrder[numberOfAtoms]; @@ -171,18 +172,18 @@ private IChemModel ReadChemModel(IChemModel model) { line = input.ReadLine(); var bondInfoFields = Strings.Tokenize(line); - bondatomid1[i] = int.Parse(bondInfoFields[0]); - bondatomid2[i] = int.Parse(bondInfoFields[1]); + bondatomid1[i] = int.Parse(bondInfoFields[0], NumberFormatInfo.InvariantInfo); + bondatomid2[i] = int.Parse(bondInfoFields[1], NumberFormatInfo.InvariantInfo); string order = bondInfoFields[2]; - if ("D".Equals(order)) + if (string.Equals("D", order, StringComparison.Ordinal)) { bondorder[i] = BondOrder.Double; } - else if ("S".Equals(order)) + else if (string.Equals("S", order, StringComparison.Ordinal)) { bondorder[i] = BondOrder.Single; } - else if ("T".Equals(order)) + else if (string.Equals("T", order, StringComparison.Ordinal)) { bondorder[i] = BondOrder.Triple; } @@ -202,7 +203,7 @@ private IChemModel ReadChemModel(IChemModel model) Debug.WriteLine(exception); } } - else if ("!Coord".Equals(command)) + else if (string.Equals("!Coord", command, StringComparison.Ordinal)) { Trace.TraceInformation("Reading coordinate block"); try @@ -211,10 +212,10 @@ private IChemModel ReadChemModel(IChemModel model) { line = input.ReadLine(); var atomInfoFields = Strings.Tokenize(line); - int atomID = int.Parse(atomInfoFields[0]); - double x = double.Parse(atomInfoFields[1]); - double y = double.Parse(atomInfoFields[2]); - double z = double.Parse(atomInfoFields[3]); + int atomID = int.Parse(atomInfoFields[0], NumberFormatInfo.InvariantInfo); + double x = double.Parse(atomInfoFields[1], NumberFormatInfo.InvariantInfo); + double y = double.Parse(atomInfoFields[2], NumberFormatInfo.InvariantInfo); + double z = double.Parse(atomInfoFields[3], NumberFormatInfo.InvariantInfo); atomxs[atomID] = x; atomys[atomID] = y; atomzs[atomID] = z; @@ -228,7 +229,7 @@ private IChemModel ReadChemModel(IChemModel model) Debug.WriteLine(exception); } } - else if ("!Charges".Equals(command)) + else if (string.Equals("!Charges", command, StringComparison.Ordinal)) { Trace.TraceInformation("Reading charges block"); try @@ -237,8 +238,8 @@ private IChemModel ReadChemModel(IChemModel model) { line = input.ReadLine(); var atomInfoFields = Strings.Tokenize(line); - int atomID = int.Parse(atomInfoFields[0]); - double charge = double.Parse(atomInfoFields[1]); + int atomID = int.Parse(atomInfoFields[0], NumberFormatInfo.InvariantInfo); + double charge = double.Parse(atomInfoFields[1], NumberFormatInfo.InvariantInfo); atomcharges[atomID] = charge; } } @@ -250,7 +251,7 @@ private IChemModel ReadChemModel(IChemModel model) Debug.WriteLine(exception); } } - else if ("!End".Equals(command)) + else if (string.Equals("!End", command, StringComparison.Ordinal)) { Trace.TraceInformation("Found end of file"); // Store atoms @@ -259,18 +260,18 @@ private IChemModel ReadChemModel(IChemModel model) { try { - IAtom atom = model.Builder.NewAtom(Isotopes.Instance.GetElementSymbol(atoms[i])); + IAtom atom = model.Builder.NewAtom(BODRIsotopeFactory.Instance.GetElementSymbol(atoms[i])); atom.AtomicNumber = atoms[i]; atom.Point3D = new Vector3(atomxs[i], atomys[i], atomzs[i]); atom.Charge = atomcharges[i]; container.Atoms.Add(atom); - Debug.WriteLine("Stored atom: " + atom); + Debug.WriteLine($"Stored atom: {atom}"); } catch (Exception exception) { if (!(exception is IOException || exception is ArgumentException)) throw; - Trace.TraceError("Cannot create an atom with atomic number: " + atoms[i]); + Trace.TraceError($"Cannot create an atom with atomic number: {atoms[i]}"); Debug.WriteLine(exception); } } diff --git a/NCDK/IO/HINReader.cs b/NCDK/IO/HINReader.cs index fa4042f2..a738dabb 100644 --- a/NCDK/IO/HINReader.cs +++ b/NCDK/IO/HINReader.cs @@ -24,6 +24,7 @@ using System.IO; using NCDK.Numerics; using NCDK.Common.Primitives; +using System.Globalization; namespace NCDK.IO { @@ -100,7 +101,7 @@ public override T Read(T obj) } } - private string GetMolName(string line) + private static string GetMolName(string line) { if (line == null) return (""); var toks = line.Split(' '); @@ -178,11 +179,11 @@ private IChemFile ReadChemFile(IChemFile file) string[] toks = line.Split(' '); string sym = toks[3]; - double charge = double.Parse(toks[6]); - double x = double.Parse(toks[7]); - double y = double.Parse(toks[8]); - double z = double.Parse(toks[9]); - int nbond = int.Parse(toks[10]); + double charge = double.Parse(toks[6], NumberFormatInfo.InvariantInfo); + double x = double.Parse(toks[7], NumberFormatInfo.InvariantInfo); + double y = double.Parse(toks[8], NumberFormatInfo.InvariantInfo); + double z = double.Parse(toks[9], NumberFormatInfo.InvariantInfo); + int nbond = int.Parse(toks[10], NumberFormatInfo.InvariantInfo); IAtom atom = file.Builder.NewAtom(sym, new Vector3(x, y, z)); atom.Charge = charge; @@ -191,7 +192,7 @@ private IChemFile ReadChemFile(IChemFile file) for (int j = 11; j < (11 + nbond * 2); j += 2) { - int s = int.Parse(toks[j]) - 1; // since atoms start from 1 in the file + int s = int.Parse(toks[j], NumberFormatInfo.InvariantInfo) - 1; // since atoms start from 1 in the file char bt = toks[j + 1][0]; switch (bt) { @@ -263,12 +264,12 @@ private IChemFile ReadChemFile(IChemFile file) foreach (var line in aroringText) { string[] toks = line.Split(' '); - int natom = int.Parse(toks[1]); + int natom = int.Parse(toks[1], NumberFormatInfo.InvariantInfo); int n = 0; for (int i = 2; i < toks.Length; i += 2) { - int molnum = int.Parse(toks[i]); // starts from 1 - int atnum = int.Parse(toks[i + 1]); // starts from 1 + int molnum = int.Parse(toks[i], NumberFormatInfo.InvariantInfo); // starts from 1 + int atnum = int.Parse(toks[i + 1], NumberFormatInfo.InvariantInfo); // starts from 1 mols[molnum - 1].Atoms[atnum - 1].IsAromatic = true; n++; } @@ -285,7 +286,7 @@ private IChemFile ReadChemFile(IChemFile file) return file; } - private bool IsConnected(IAtomContainer atomContainer, IAtom atom1, IAtom atom2) + private static bool IsConnected(IAtomContainer atomContainer, IAtom atom1, IAtom atom2) { foreach (var bond in atomContainer.Bonds) { diff --git a/NCDK/IO/HINWriter.cs b/NCDK/IO/HINWriter.cs index 0cf08436..49251209 100644 --- a/NCDK/IO/HINWriter.cs +++ b/NCDK/IO/HINWriter.cs @@ -21,6 +21,7 @@ using System.IO; using System; using NCDK.Numerics; +using System.Globalization; namespace NCDK.IO { @@ -153,9 +154,9 @@ private void WriteAtomContainer(IEnumerableChemObject som) chrg = atom.Charge.Value; Vector3 point = atom.Point3D.Value; - line = line + (i + 1).ToString() + " - " + sym + " ** - " + chrg.ToString() + " " - + point.X.ToString() + " " + point.Y.ToString() + " " - + point.Z.ToString() + " "; + line = line + (i + 1).ToString(NumberFormatInfo.InvariantInfo) + " - " + sym + " ** - " + chrg.ToString(NumberFormatInfo.InvariantInfo) + " " + + point.X.ToString(NumberFormatInfo.InvariantInfo) + " " + point.Y.ToString(NumberFormatInfo.InvariantInfo) + " " + + point.Z.ToString(NumberFormatInfo.InvariantInfo) + " "; string abuf = ""; int ncon = 0; @@ -179,11 +180,11 @@ private void WriteAtomContainer(IEnumerableChemObject som) else if (bondOrder == BondOrder.Triple) bondType = "t"; else if (bond.IsAromatic) bondType = "a"; - abuf = abuf + (serial + 1).ToString() + " " + bondType + " "; + abuf = abuf + (serial + 1).ToString(NumberFormatInfo.InvariantInfo) + " " + bondType + " "; ncon++; } } - line = line + " " + ncon.ToString() + " " + abuf; + line = line + " " + ncon.ToString(NumberFormatInfo.InvariantInfo) + " " + abuf; writer.Write(line, 0, line.Length); writer.Write('\n'); i++; diff --git a/NCDK/IO/IChemObjectWriter.cs b/NCDK/IO/IChemObjectWriter.cs index 43806f0d..53486a20 100644 --- a/NCDK/IO/IChemObjectWriter.cs +++ b/NCDK/IO/IChemObjectWriter.cs @@ -36,8 +36,8 @@ public interface IChemObjectWriter : IChemObjectIO /// /// Writes the content of "object" to output. /// - /// the object of which the content is outputted + /// the object of which the content is outputted /// is thrown if the output does not support the data in the object - void Write(IChemObject obj); + void Write(IChemObject o); } } diff --git a/NCDK/IO/ISimpleChemObjectReader.cs b/NCDK/IO/ISimpleChemObjectReader.cs index 3d80560b..34e012cd 100644 --- a/NCDK/IO/ISimpleChemObjectReader.cs +++ b/NCDK/IO/ISimpleChemObjectReader.cs @@ -48,9 +48,9 @@ public interface ISimpleChemObjectReader : IChemObjectReader /// of the actual implementation may take a Reader as input to get /// a very flexible reader that can read from string, files, etc. /// - /// the type of object to return + /// the type of object to return /// returns an object of that contains the content (or part) of the input content /// it is thrown if the type of information is not available from the input - T Read(T obj) where T : IChemObject; + T Read(T o) where T : IChemObject; } } diff --git a/NCDK/IO/InChI/InChIContentProcessorTool.cs b/NCDK/IO/InChI/InChIContentProcessorTool.cs index 1a4f8292..6082ce15 100644 --- a/NCDK/IO/InChI/InChIContentProcessorTool.cs +++ b/NCDK/IO/InChI/InChIContentProcessorTool.cs @@ -19,6 +19,7 @@ using System; using System.Diagnostics; +using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -30,10 +31,8 @@ namespace NCDK.IO.InChI // @cdk.module extra // @cdk.githash [Obsolete] - public class InChIContentProcessorTool + public static class InChIContentProcessorTool { - public InChIContentProcessorTool() { } - private static readonly Regex pattern1 = new Regex("([A-Z][a-z]?)(\\d+)?(.*)", RegexOptions.Compiled); private static readonly Regex pattern2 = new Regex("^(\\d+)-?(.*)", RegexOptions.Compiled); @@ -41,47 +40,48 @@ public InChIContentProcessorTool() { } /// Processes the content from the formula field of the INChI. /// Typical values look like C6H6, from INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H. /// - public IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsEncoding) + public static IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsEncoding) { - Debug.WriteLine("Parsing atom data: ", atomsEncoding); + Debug.WriteLine($"Parsing atom data: {atomsEncoding}"); - string remainder = atomsEncoding; + var remainder = atomsEncoding; while (remainder.Length > 0) { - Debug.WriteLine("Remaining: ", remainder); + Debug.WriteLine($"Remaining: {remainder}"); var match = pattern1.Match(remainder); if (match.Success) { - string symbol = match.Groups[1].Value; - Debug.WriteLine("Atom symbol: ", symbol); - if (symbol.Equals("H")) + var symbol = match.Groups[1].Value; + Debug.WriteLine($"Atom symbol: {symbol}"); + if (string.Equals(symbol, "H", StringComparison.Ordinal)) { // don't add explicit hydrogens } else { - string occurenceStr = match.Groups[2].Value; + var occurenceStr = match.Groups[2].Value; int occurence = 1; if (!string.IsNullOrEmpty(occurenceStr)) { - occurence = int.Parse(occurenceStr); + occurence = int.Parse(occurenceStr, NumberFormatInfo.InvariantInfo); } - Debug.WriteLine(" occurence: ", occurence); + Debug.WriteLine($" occurence: {occurence}"); for (int i = 1; i <= occurence; i++) { parsedContent.Atoms.Add(parsedContent.Builder.NewAtom(symbol)); } } remainder = match.Groups[3].Value; - if (remainder == null) remainder = ""; - Debug.WriteLine(" Remaining: ", remainder); + if (remainder == null) + remainder = ""; + Debug.WriteLine($" Remaining: {remainder}"); } else { Trace.TraceError("No match found!"); remainder = ""; } - Debug.WriteLine("NO atoms: ", parsedContent.Atoms.Count); + Debug.WriteLine($"NO atoms: {parsedContent.Atoms.Count}"); } return parsedContent; } @@ -94,16 +94,16 @@ public IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsE /// the atomContainer parsed from the formula field /// the atom to build the path upon. If -1, then start new path /// - public void ProcessConnections(string bondsEncoding, IAtomContainer container, int source) + public static void ProcessConnections(string bondsEncoding, IAtomContainer container, int source) { - Debug.WriteLine("Parsing bond data: ", bondsEncoding); + Debug.WriteLine($"Parsing bond data: {bondsEncoding}"); IBond bondToAdd = null; /* Fixme: treatment of branching is too limited! */ string remainder = bondsEncoding; while (remainder.Length > 0) { - Debug.WriteLine("Bond part: ", remainder); + Debug.WriteLine($"Bond part: {remainder}"); if (remainder[0] == '(') { string branch = ChopBranch(remainder); @@ -123,9 +123,9 @@ public void ProcessConnections(string bondsEncoding, IAtomContainer container, i if (matcher.Success) { string targetStr = matcher.Groups[1].Value; - int target = int.Parse(targetStr); - Debug.WriteLine("Source atom: ", source); - Debug.WriteLine("Target atom: ", targetStr); + int target = int.Parse(targetStr, NumberFormatInfo.InvariantInfo); + Debug.WriteLine($"Source atom: {source}"); + Debug.WriteLine($"Target atom: {targetStr}"); IAtom targetAtom = container.Atoms[target - 1]; if (source != -1) { @@ -136,7 +136,7 @@ public void ProcessConnections(string bondsEncoding, IAtomContainer container, i } remainder = matcher.Groups[2].Value; source = target; - Debug.WriteLine(" remainder: ", remainder); + Debug.WriteLine($" remainder: {remainder}"); } else { @@ -151,7 +151,7 @@ public void ProcessConnections(string bondsEncoding, IAtomContainer container, i /// Extracts the first full branch. It extracts everything between the first /// '(' and the corresponding ')' char. /// - private string ChopBranch(string remainder) + private static string ChopBranch(string remainder) { bool doChop = false; int branchLevel = 0; diff --git a/NCDK/IO/InChI/InChIHandler.cs b/NCDK/IO/InChI/InChIHandler.cs index a341c1c6..bf9ff6fe 100644 --- a/NCDK/IO/InChI/InChIHandler.cs +++ b/NCDK/IO/InChI/InChIHandler.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Default; +using NCDK.Silent; using NCDK.Utils.Xml; using System; using System.Diagnostics; @@ -29,48 +29,39 @@ namespace NCDK.IO.InChI /// XReader handler for INChI XML fragment parsing. /// /// - /// The supported elements are: identifier, formula and + /// + /// The supported elements are: identifier, formula and /// connections. All other elements are not parsed (at this moment). /// This parser is written based on the INChI files in data/ichi /// for version 1.1Beta. /// /// The returned ChemFile contains a ChemSequence in - /// which the ChemModel represents the molecule. + /// which the ChemModel represents the molecule. + /// /// /// // @cdk.module extra // @cdk.githash - [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] + [Obsolete] public class InChIHandler : XContentHandler { - private InChIContentProcessorTool inchiTool; - - private ChemFile chemFile; private ChemSequence chemSequence; private ChemModel chemModel; private IChemObjectSet setOfMolecules; private IAtomContainer tautomer; - /// - /// Constructor for the IChIHandler. - /// - public InChIHandler() - { - inchiTool = new InChIContentProcessorTool(); - } - public override void DoctypeDecl(XDocumentType docType) { if (docType == null) return; - Trace.TraceInformation("DocType root element: " + docType.Name); - Trace.TraceInformation("DocType root PUBLIC: " + docType.PublicId); - Trace.TraceInformation("DocType root SYSTEM: " + docType.SystemId); + Trace.TraceInformation($"DocType root element: {docType.Name}"); + Trace.TraceInformation($"DocType root PUBLIC: {docType.PublicId}"); + Trace.TraceInformation($"DocType root SYSTEM: {docType.SystemId}"); } public override void StartDocument() { - chemFile = new ChemFile(); + ChemFile = new ChemFile(); chemSequence = new ChemSequence(); chemModel = new ChemModel(); setOfMolecules = new ChemObjectSet(); @@ -78,13 +69,13 @@ public override void StartDocument() public override void EndDocument() { - chemFile.Add(chemSequence); + ChemFile.Add(chemSequence); } public override void EndElement(XElement element) { - Debug.WriteLine("end element: ", element.ToString()); - if ("identifier".Equals(element.Name.LocalName)) + Debug.WriteLine($"end element: {element.ToString()}"); + if (string.Equals("identifier", element.Name.LocalName, StringComparison.Ordinal)) { if (tautomer != null) { @@ -94,12 +85,12 @@ public override void EndElement(XElement element) chemSequence.Add(chemModel); } } - else if ("formula".Equals(element.Name.LocalName)) + else if (string.Equals("formula", element.Name.LocalName, StringComparison.Ordinal)) { if (tautomer != null) { Trace.TraceInformation("Parsing chars: ", element.Value); - tautomer = new AtomContainer(inchiTool.ProcessFormula( + tautomer = new AtomContainer(InChIContentProcessorTool.ProcessFormula( setOfMolecules.Builder.NewAtomContainer(), element.Value)); } else @@ -107,12 +98,12 @@ public override void EndElement(XElement element) Trace.TraceWarning("Cannot set atom info for empty tautomer"); } } - else if ("connections".Equals(element.Name.LocalName)) + else if (string.Equals("connections", element.Name.LocalName, StringComparison.Ordinal)) { if (tautomer != null) { Trace.TraceInformation("Parsing chars: ", element.Value); - inchiTool.ProcessConnections(element.Value, tautomer, -1); + InChIContentProcessorTool.ProcessConnections(element.Value, tautomer, -1); } else { @@ -131,19 +122,20 @@ public override void EndElement(XElement element) /// public override void StartElement(XElement element) { - Debug.WriteLine("startElement: ", element.ToString()); - Debug.WriteLine("uri: ", element.Name.NamespaceName); - Debug.WriteLine("local: ", element.Name.LocalName); - Debug.WriteLine("raw: ", element.ToString()); - if ("INChI".Equals(element.Name.LocalName)) + Debug.WriteLine($"startElement: {element.ToString()}"); + Debug.WriteLine($"uri: {element.Name.NamespaceName}"); + Debug.WriteLine($"local: {element.Name.LocalName}"); + Debug.WriteLine($"raw: {element.ToString()}"); + if (string.Equals("INChI", element.Name.LocalName, StringComparison.Ordinal)) { // check version foreach (var att in element.Attributes()) { - if (att.Name.LocalName.Equals("version")) Trace.TraceInformation("INChI version: ", att.Value); + if (string.Equals(att.Name.LocalName, "version", StringComparison.Ordinal)) + Trace.TraceInformation("INChI version: ", att.Value); } } - else if ("structure".Equals(element.Name.LocalName)) + else if (string.Equals("structure", element.Name.LocalName, StringComparison.Ordinal)) { tautomer = new AtomContainer(); } @@ -153,6 +145,6 @@ public override void StartElement(XElement element) } } - public ChemFile ChemFile => chemFile; + public ChemFile ChemFile { get; private set; } } } diff --git a/NCDK/IO/InChIContentProcessorTool.cs b/NCDK/IO/InChIContentProcessorTool.cs index 4ed250fa..ba6c7466 100644 --- a/NCDK/IO/InChIContentProcessorTool.cs +++ b/NCDK/IO/InChIContentProcessorTool.cs @@ -21,7 +21,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +using System; using System.Diagnostics; +using System.Globalization; using System.Text; using System.Text.RegularExpressions; @@ -32,10 +34,8 @@ namespace NCDK.IO /// // @cdk.module extra // @cdk.githash - public class InChIContentProcessorTool + public static class InChIContentProcessorTool { - public InChIContentProcessorTool() { } - private static readonly Regex pattern1 = new Regex("([A-Z][a-z]?)(\\d+)?(.*)", RegexOptions.Compiled); private static readonly Regex pattern2 = new Regex("^(\\d+)-?(.*)", RegexOptions.Compiled); @@ -43,20 +43,20 @@ public InChIContentProcessorTool() { } /// Processes the content from the formula field of the INChI. /// Typical values look like C6H6, from INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H. /// - public IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsEncoding) + public static IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsEncoding) { - Debug.WriteLine("Parsing atom data: ", atomsEncoding); + Debug.WriteLine($"Parsing atom data: {atomsEncoding}"); string remainder = atomsEncoding; while (remainder.Length > 0) { - Debug.WriteLine("Remaining: ", remainder); + Debug.WriteLine($"Remaining: {remainder}"); var match = pattern1.Match(remainder); if (match.Success) { string symbol = match.Groups[1].Value; - Debug.WriteLine("Atom symbol: ", symbol); - if (symbol.Equals("H")) + Debug.WriteLine($"Atom symbol: {symbol}"); + if (string.Equals(symbol, "H", StringComparison.Ordinal)) { // don't add explicit hydrogens } @@ -66,9 +66,9 @@ public IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsE int occurence = 1; if (!string.IsNullOrEmpty(occurenceStr)) { - occurence = int.Parse(occurenceStr); + occurence = int.Parse(occurenceStr, NumberFormatInfo.InvariantInfo); } - Debug.WriteLine(" occurence: ", occurence); + Debug.WriteLine($" occurence: {occurence}"); for (int i = 1; i <= occurence; i++) { parsedContent.Atoms.Add(parsedContent.Builder.NewAtom(symbol)); @@ -76,14 +76,14 @@ public IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsE } remainder = match.Groups[3].Value; if (remainder == null) remainder = ""; - Debug.WriteLine(" Remaining: ", remainder); + Debug.WriteLine($" Remaining: {remainder}"); } else { Trace.TraceError("No match found!"); remainder = ""; } - Debug.WriteLine("NO atoms: ", parsedContent.Atoms.Count); + Debug.WriteLine($"NO atoms: {parsedContent.Atoms.Count}"); } return parsedContent; } @@ -96,16 +96,16 @@ public IAtomContainer ProcessFormula(IAtomContainer parsedContent, string atomsE /// the atomContainer parsed from the formula field /// the atom to build the path upon. If -1, then start new path /// - public void ProcessConnections(string bondsEncoding, IAtomContainer container, int source) + public static void ProcessConnections(string bondsEncoding, IAtomContainer container, int source) { - Debug.WriteLine("Parsing bond data: ", bondsEncoding); + Debug.WriteLine($"Parsing bond data: {bondsEncoding}"); IBond bondToAdd = null; /* Fixme: treatment of branching is too limited! */ string remainder = bondsEncoding; while (remainder.Length > 0) { - Debug.WriteLine("Bond part: ", remainder); + Debug.WriteLine($"Bond part: {remainder}"); if (remainder[0] == '(') { string branch = ChopBranch(remainder); @@ -125,20 +125,19 @@ public void ProcessConnections(string bondsEncoding, IAtomContainer container, i if (matcher.Success) { string targetStr = matcher.Groups[1].Value; - int target = int.Parse(targetStr); - Debug.WriteLine("Source atom: ", source); - Debug.WriteLine("Target atom: ", targetStr); + int target = int.Parse(targetStr, NumberFormatInfo.InvariantInfo); + Debug.WriteLine($"Source atom: {source}"); + Debug.WriteLine($"Target atom: {targetStr}"); IAtom targetAtom = container.Atoms[target - 1]; if (source != -1) { IAtom sourceAtom = container.Atoms[source - 1]; - bondToAdd = container.Builder.NewBond(sourceAtom, targetAtom, - BondOrder.Single); + bondToAdd = container.Builder.NewBond(sourceAtom, targetAtom, BondOrder.Single); container.Bonds.Add(bondToAdd); } remainder = matcher.Groups[2].Value; source = target; - Debug.WriteLine(" remainder: ", remainder); + Debug.WriteLine($" remainder: {remainder}"); } else { @@ -153,7 +152,7 @@ public void ProcessConnections(string bondsEncoding, IAtomContainer container, i /// Extracts the first full branch. It extracts everything between the first /// '(' and the corresponding ')' char. /// - private string ChopBranch(string remainder) + private static string ChopBranch(string remainder) { bool doChop = false; int branchLevel = 0; diff --git a/NCDK/IO/InChIPlainTextReader.cs b/NCDK/IO/InChIPlainTextReader.cs index 034a93c9..f9c6d83a 100644 --- a/NCDK/IO/InChIPlainTextReader.cs +++ b/NCDK/IO/InChIPlainTextReader.cs @@ -51,7 +51,6 @@ namespace NCDK.IO public class InChIPlainTextReader : DefaultChemObjectReader { private TextReader input; - private InChIContentProcessorTool inchiTool; /// /// Construct a INChI reader from a Reader object. @@ -59,9 +58,7 @@ public class InChIPlainTextReader : DefaultChemObjectReader /// the Reader with the content public InChIPlainTextReader(TextReader input) { - this.Init(); this.input = input; - inchiTool = new InChIContentProcessorTool(); } public InChIPlainTextReader(Stream input) @@ -70,11 +67,6 @@ public InChIPlainTextReader(Stream input) public override IResourceFormat Format => InChIPlainTextFormat.Instance; - /// - /// Initializes this reader. - /// - private void Init() { } - public override bool Accepts(Type type) { if (typeof(IChemFile).IsAssignableFrom(type)) return true; @@ -129,10 +121,10 @@ private IChemFile ReadChemFile(IChemFile cf) connections = tok[2].Substring(1); // 1-2-4-6-5-3-1 //final string hydrogens = tokenizer.NextToken().Substring(1); // 1-6H - IAtomContainer parsedContent = inchiTool.ProcessFormula( + IAtomContainer parsedContent = InChIContentProcessorTool.ProcessFormula( cf.Builder.NewAtomContainer(), formula); if (connections != null) - inchiTool.ProcessConnections(connections, parsedContent, -1); + InChIContentProcessorTool.ProcessConnections(connections, parsedContent, -1); var moleculeSet = cf.Builder.NewAtomContainerSet(); moleculeSet.Add(cf.Builder.NewAtomContainer(parsedContent)); diff --git a/NCDK/IO/InChIReader.cs b/NCDK/IO/InChIReader.cs index f9f8913f..6424be3e 100644 --- a/NCDK/IO/InChIReader.cs +++ b/NCDK/IO/InChIReader.cs @@ -148,9 +148,6 @@ protected override void Dispose(bool disposing) private class InChIHandler : XContentHandler { - private InChIContentProcessorTool inchiTool; - - private IChemFile chemFile; private IChemSequence chemSequence; private IChemModel chemModel; private IChemObjectSet setOfMolecules; @@ -163,7 +160,6 @@ private class InChIHandler : XContentHandler public InChIHandler(IChemObjectBuilder builder) { this.builder = builder; - inchiTool = new InChIContentProcessorTool(); } public override void DoctypeDecl(XDocumentType docType) @@ -177,7 +173,7 @@ public override void DoctypeDecl(XDocumentType docType) public override void StartDocument() { - chemFile = builder.NewChemFile(); + ChemFile = builder.NewChemFile(); chemSequence = builder.NewChemSequence(); chemModel = builder.NewChemModel(); setOfMolecules = builder.NewChemObjectSet(); @@ -185,13 +181,13 @@ public override void StartDocument() public override void EndDocument() { - chemFile.Add(chemSequence); + ChemFile.Add(chemSequence); } public override void EndElement(XElement element) { - Debug.WriteLine("end element: ", element.ToString()); - if ("identifier".Equals(element.Name.LocalName)) + Debug.WriteLine($"end element: {element.ToString()}"); + if (string.Equals("identifier", element.Name.LocalName, StringComparison.Ordinal)) { if (tautomer != null) { @@ -201,25 +197,25 @@ public override void EndElement(XElement element) chemSequence.Add(chemModel); } } - else if ("formula".Equals(element.Name.LocalName)) + else if (string.Equals("formula", element.Name.LocalName, StringComparison.Ordinal)) { if (tautomer != null) { Trace.TraceInformation("Parsing chars: ", element.Value); - tautomer = builder.NewAtomContainer(inchiTool.ProcessFormula( - setOfMolecules.Builder.NewAtomContainer(), element.Value)); + tautomer = builder.NewAtomContainer( + InChIContentProcessorTool.ProcessFormula(setOfMolecules.Builder.NewAtomContainer(), element.Value)); } else { Trace.TraceWarning("Cannot set atom info for empty tautomer"); } } - else if ("connections".Equals(element.Name.LocalName)) + else if (string.Equals("connections", element.Name.LocalName, StringComparison.Ordinal)) { if (tautomer != null) { Trace.TraceInformation("Parsing chars: ", element.Value); - inchiTool.ProcessConnections(element.Value, tautomer, -1); + InChIContentProcessorTool.ProcessConnections(element.Value, tautomer, -1); } else { @@ -238,19 +234,19 @@ public override void EndElement(XElement element) /// public override void StartElement(XElement element) { - Debug.WriteLine("startElement: ", element.ToString()); - Debug.WriteLine("uri: ", element.Name.NamespaceName); - Debug.WriteLine("local: ", element.Name.LocalName); - Debug.WriteLine("raw: ", element.ToString()); - if ("INChI".Equals(element.Name.LocalName)) + Debug.WriteLine($"startElement: {element.ToString()}"); + Debug.WriteLine($"uri: {element.Name.NamespaceName}"); + Debug.WriteLine($"local: {element.Name.LocalName}"); + Debug.WriteLine($"raw: {element.ToString()}"); + if (string.Equals("INChI", element.Name.LocalName, StringComparison.Ordinal)) { // check version foreach (var att in element.Attributes()) { - if (att.Name.LocalName.Equals("version")) Trace.TraceInformation("INChI version: ", att.Value); + if (string.Equals(att.Name.LocalName, "version", StringComparison.Ordinal)) Trace.TraceInformation("INChI version: ", att.Value); } } - else if ("structure".Equals(element.Name.LocalName)) + else if (string.Equals("structure", element.Name.LocalName, StringComparison.Ordinal)) { tautomer = builder.NewAtomContainer(); } @@ -260,7 +256,7 @@ public override void StartElement(XElement element) } } - public IChemFile ChemFile => chemFile; + public IChemFile ChemFile { get; private set; } } } } diff --git a/NCDK/IO/Iterator/EnumerableMDLConformerReader.cs b/NCDK/IO/Iterator/EnumerableMDLConformerReader.cs index b0ed516b..07ac9d13 100644 --- a/NCDK/IO/Iterator/EnumerableMDLConformerReader.cs +++ b/NCDK/IO/Iterator/EnumerableMDLConformerReader.cs @@ -59,7 +59,7 @@ public IEnumerator GetEnumerator() container = new ConformerContainer(mol); else { - if (container.Title.Equals(mol.Title)) + if (container.Title.Equals(mol.Title, StringComparison.Ordinal)) container.Add(mol); else { diff --git a/NCDK/IO/Iterator/EnumerablePCCompoundASNReader.cs b/NCDK/IO/Iterator/EnumerablePCCompoundASNReader.cs index 2fbc625a..2488e6ca 100644 --- a/NCDK/IO/Iterator/EnumerablePCCompoundASNReader.cs +++ b/NCDK/IO/Iterator/EnumerablePCCompoundASNReader.cs @@ -89,7 +89,7 @@ public override IEnumerator GetEnumerator() if (depthDiff > 0 && depth == 3) { string command = GetCommand(currentLine); - if (command.Equals("compound")) + if (string.Equals(command, "compound", StringComparison.Ordinal)) { buffer.Append("PC-Compound ::= {\n"); currentLine = input.ReadLine(); @@ -118,7 +118,7 @@ public override IEnumerator GetEnumerator() } using (PCCompoundASNReader asnReader = new PCCompoundASNReader(new StringReader(buffer.ToString()))) { - IChemFile cFile = (IChemFile)asnReader.Read(builder.NewChemFile()); + var cFile = asnReader.Read(builder.NewChemFile()); ac = ChemFileManipulator.GetAllAtomContainers(cFile).First(); } } @@ -135,7 +135,7 @@ public override IEnumerator GetEnumerator() yield break; } - private int CountChars(string copy, char character) + private static int CountChars(string copy, char character) { int occurences = 0; for (int i = 0; i < copy.Length; i++) @@ -145,7 +145,7 @@ private int CountChars(string copy, char character) return occurences; } - private int CountBrackets(string currentLine) + private static int CountBrackets(string currentLine) { int bracketsOpen = CountChars(currentLine, '{'); int bracketsClose = CountChars(currentLine, '}'); @@ -172,7 +172,7 @@ protected override void Dispose(bool disposing) } #endregion - private string GetCommand(string line) + private static string GetCommand(string line) { StringBuilder buffer = new StringBuilder(); int i = 0; diff --git a/NCDK/IO/Iterator/EnumerablePCCompoundXMLReader.cs b/NCDK/IO/Iterator/EnumerablePCCompoundXMLReader.cs index f2981cf2..e572aee0 100644 --- a/NCDK/IO/Iterator/EnumerablePCCompoundXMLReader.cs +++ b/NCDK/IO/Iterator/EnumerablePCCompoundXMLReader.cs @@ -75,8 +75,8 @@ public EnumerablePCCompoundXMLReader(TextReader input, IChemObjectBuilder builde /// Constructs a new EnumerablePCCompoundXLReader that can read Molecule from a given Stream and IChemObjectBuilder. /// /// The input stream - /// The builder. In general, use - /// if there is a problem creating an InputStreamReader + /// The builder + /// if there is a problem creating a public EnumerablePCCompoundXMLReader(Stream ins, IChemObjectBuilder builder) : this(new StreamReader(ins), builder) { } diff --git a/NCDK/IO/Iterator/EnumerableSDFReader.cs b/NCDK/IO/Iterator/EnumerableSDFReader.cs index e0649c4b..4959091e 100644 --- a/NCDK/IO/Iterator/EnumerableSDFReader.cs +++ b/NCDK/IO/Iterator/EnumerableSDFReader.cs @@ -61,8 +61,6 @@ public class EnumerableSDFReader : DefaultEnumerableChemObjectReader GetEnumerator() while ((currentLine = input.ReadLine()) != null) { // still in a molecule - buffer.Append(currentLine).Append(LINE_SEPARATOR); + buffer.Append(currentLine).Append('\n'); lineNum++; // do MDL molfile version checking @@ -174,14 +172,15 @@ public override IEnumerator GetEnumerator() var versionMatcher = MDL_Version.Match(currentLine); if (versionMatcher.Success) { - currentFormat = "2000".Equals(versionMatcher.Groups[1].Value) ? (IChemFormat)MDLV2000Format.Instance - : (IChemFormat)MDLV3000Format.Instance; + currentFormat = string.Equals("2000", versionMatcher.Groups[1].Value, StringComparison.Ordinal) + ? (IChemFormat)MDLV2000Format.Instance + : (IChemFormat)MDLV3000Format.Instance; } } if (currentLine.StartsWith(M_END, StringComparison.Ordinal)) { - Debug.WriteLine("MDL file part read: ", buffer); + Debug.WriteLine($"MDL file part read: {buffer}"); IAtomContainer molecule = null; @@ -192,7 +191,7 @@ public override IEnumerator GetEnumerator() } catch (Exception exception) { - Trace.TraceError("Error while reading next molecule: " + exception.Message); + Trace.TraceError($"Error while reading next molecule: {exception.Message}"); Debug.WriteLine(exception); } @@ -245,7 +244,7 @@ private void ReadDataBlockInto(IAtomContainer m) { if (currentLine.StartsWith(SDF_RECORD_SEPARATOR, StringComparison.Ordinal)) break; - Debug.WriteLine("looking for data header: ", currentLine); + Debug.WriteLine($"looking for data header: {currentLine}"); string str = currentLine; if (str.StartsWith(SDF_DATA_HEADER, StringComparison.Ordinal)) { @@ -303,7 +302,7 @@ private string SkipOtherFieldHeaderLines(string str) return str; } - private string ExtractFieldName(string str) + private static string ExtractFieldName(string str) { int index = str.IndexOf('<'); if (index != -1) @@ -339,14 +338,13 @@ protected override void Dispose(bool disposing) private void InitIOSettings() { - forceReadAs3DCoords = new BooleanIOSetting("ForceReadAs3DCoordinates", IOSetting.Importance.Low, - "Should coordinates always be read as 3D?", "false"); + forceReadAs3DCoords = new BooleanIOSetting("ForceReadAs3DCoordinates", Importance.Low, "Should coordinates always be read as 3D?", "false"); Add(forceReadAs3DCoords); } public void CustomizeJob() { - FireIOSettingQuestion(forceReadAs3DCoords); + ProcessIOSettingQuestion(forceReadAs3DCoords); } } } diff --git a/NCDK/IO/Iterator/EnumerableSMILESReader.cs b/NCDK/IO/Iterator/EnumerableSMILESReader.cs index 4d1afd57..f3f75ee6 100644 --- a/NCDK/IO/Iterator/EnumerableSMILESReader.cs +++ b/NCDK/IO/Iterator/EnumerableSMILESReader.cs @@ -57,12 +57,10 @@ public class EnumerableSMILESReader : DefaultEnumerableChemObjectReader - /// Constructs a new EnumerableSMILESReader that can read Molecule from a given Reader. + /// Constructs a new that can read molecule from a given reader. /// /// The Reader to read from /// The builder to use - /// - /// public EnumerableSMILESReader(TextReader input, IChemObjectBuilder builder) { sp = new SmilesParser(builder); @@ -119,7 +117,7 @@ public override IEnumerator GetEnumerator() /// /// input line /// the suffix - or an empty line - private string Suffix(string line) + private static string Suffix(string line) { for (int i = 0; i < line.Length; i++) { diff --git a/NCDK/IO/Listener/IReaderListener.cs b/NCDK/IO/Listener/IReaderListener.cs index e20f00cc..92558861 100644 --- a/NCDK/IO/Listener/IReaderListener.cs +++ b/NCDK/IO/Listener/IReaderListener.cs @@ -30,7 +30,7 @@ public interface IReaderListener : IChemObjectIOListener /// /// Indicates that a new frame has been read. /// - /// information about the event. - void FrameRead(ReaderEvent @event); + /// information about the event. + void FrameRead(ReaderEvent readerEvent); } } diff --git a/NCDK/IO/Listener/PropertiesListener.cs b/NCDK/IO/Listener/PropertiesListener.cs index 9a8589e1..ba00093f 100644 --- a/NCDK/IO/Listener/PropertiesListener.cs +++ b/NCDK/IO/Listener/PropertiesListener.cs @@ -43,12 +43,12 @@ namespace NCDK.IO.Listener // @author Egon Willighagen public class PropertiesListener : IReaderListener, IWriterListener { - private NameValueCollection props; + private readonly NameValueCollection props; /// /// Overwrites the default writer to which the output is directed. /// - public TextWriter OutputWriter { private get; set; } + public TextWriter OutputWriter { get; set; } public PropertiesListener(NameValueCollection props) { @@ -77,8 +77,7 @@ public void ProcessIOSettingQuestion(IOSetting setting) } catch (CDKException) { - string message = "Submitted Value (" + propValue + ") is not valid!"; - OutputWriter.WriteLine(message); + OutputWriter.WriteLine($"Submitted Value ({propValue}) is not valid!"); } } } diff --git a/NCDK/IO/Listener/TextGUIListener.cs b/NCDK/IO/Listener/TextGUIListener.cs index 45e804b4..4d60eb0f 100644 --- a/NCDK/IO/Listener/TextGUIListener.cs +++ b/NCDK/IO/Listener/TextGUIListener.cs @@ -19,6 +19,7 @@ using NCDK.IO.Setting; using System; +using System.Globalization; using System.IO; using static NCDK.IO.Setting.IOSetting; @@ -106,9 +107,9 @@ public void ProcessIOSettingQuestion(IOSetting setting) for (int i = 0; i < settings.Count; i++) { this.output.Write('\n'); - string option = (string)settings[i]; + string option = settings[i]; this.output.Write((i + 1) + ". " + option); - if (option.Equals(setting.Setting)) + if (string.Equals(option, setting.Setting, StringComparison.Ordinal)) { this.output.Write(" (Default)"); } @@ -144,18 +145,18 @@ public void ProcessIOSettingQuestion(IOSetting setting) } else if (setting is OptionIOSetting) { - ((OptionIOSetting)setting).SetSetting(int.Parse(answer)); + ((OptionIOSetting)setting).SetSetting(int.Parse(answer, NumberFormatInfo.InvariantInfo)); } else if (setting is BooleanIOSetting) { - switch (answer.ToLowerInvariant()) + switch (answer.ToUpperInvariant()) { - case "n": - case "no": + case "N": + case "NO": answer = "false"; break; - case "y": - case "yes": + case "Y": + case "YES": answer = "true"; break; } diff --git a/NCDK/IO/MDLRXNReader.cs b/NCDK/IO/MDLRXNReader.cs index bd698d34..cde9476c 100644 --- a/NCDK/IO/MDLRXNReader.cs +++ b/NCDK/IO/MDLRXNReader.cs @@ -26,6 +26,7 @@ using NCDK.IO.Formats; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text; @@ -113,21 +114,21 @@ public override T Read(T obj) } } - public bool Accepts(IChemObject obj) + public static bool Accepts(IChemObject o) { - if (obj is IReaction) + if (o is IReaction) { return true; } - else if (obj is IChemModel) + else if (o is IChemModel) { return true; } - else if (obj is IChemFile) + else if (o is IChemFile) { return true; } - else if (obj is IReactionSet) + else if (o is IReactionSet) { return true; } @@ -185,10 +186,10 @@ private IReactionSet ReadReactionSet(IReactionSet setOfReactions) string line; while ((line = input.ReadLine()) != null) { - Debug.WriteLine("line: ", line); + Debug.WriteLine($"line: {line}"); // apparently, this is a SDF file, continue with // reading mol files - if (line.Equals("$$$$")) + if (string.Equals(line, "$$$$", StringComparison.Ordinal)) { r = ReadReaction(setOfReactions.Builder); @@ -229,7 +230,7 @@ private IReactionSet ReadReactionSet(IReactionSet setOfReactions) string data = line; while ((line = input.ReadLine()) != null && line.Trim().Length > 0) { - if (line.Equals("$$$$")) + if (string.Equals(line, "$$$$", StringComparison.Ordinal)) { Trace.TraceError($"Expecting data line here, but found end of molecule: {line}"); break; @@ -306,9 +307,9 @@ private IReaction ReadReaction(IChemObjectBuilder builder) // this line contains the number of reactants and products var tokens = Strings.Tokenize(countsLine); - reactantCount = int.Parse(tokens[0]); + reactantCount = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo); Trace.TraceInformation("Expecting " + reactantCount + " reactants in file"); - productCount = int.Parse(tokens[1]); + productCount = int.Parse(tokens[1], NumberFormatInfo.InvariantInfo); Trace.TraceInformation("Expecting " + productCount + " products in file"); } catch (Exception exception) @@ -334,7 +335,7 @@ private IReaction ReadReaction(IChemObjectBuilder builder) molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append('\n'); - } while (!molFileLine.Equals("M END")); + } while (!string.Equals(molFileLine, "M END", StringComparison.Ordinal)); // read MDL molfile content MDLReader reader = new MDLReader(new StringReader(molFile.ToString())); @@ -373,7 +374,7 @@ private IReaction ReadReaction(IChemObjectBuilder builder) molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append('\n'); - } while (!molFileLine.Equals("M END")); + } while (!string.Equals(molFileLine, "M END", StringComparison.Ordinal)); // read MDL molfile content MDLReader reader = new MDLReader(new StringReader(molFile.ToString()), base.ReaderMode); diff --git a/NCDK/IO/MDLRXNV2000Reader.cs b/NCDK/IO/MDLRXNV2000Reader.cs index d52235aa..ed4d35c2 100644 --- a/NCDK/IO/MDLRXNV2000Reader.cs +++ b/NCDK/IO/MDLRXNV2000Reader.cs @@ -25,6 +25,7 @@ using NCDK.IO.Formats; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text; @@ -120,21 +121,21 @@ public override T Read(T obj) } } - public bool Accepts(IChemObject obj) + public virtual bool Accepts(IChemObject o) { - if (obj is IReaction) + if (o is IReaction) { return true; } - else if (obj is IChemModel) + else if (o is IChemModel) { return true; } - else if (obj is IChemFile) + else if (o is IChemFile) { return true; } - else if (obj is IReactionSet) + else if (o is IReactionSet) { return true; } @@ -171,14 +172,14 @@ private IReaction ReadReaction(IChemObjectBuilder builder) // this line contains the number of reactants and products var tokenizer = Strings.Tokenize(countsLine).GetEnumerator(); tokenizer.MoveNext(); - reactantCount = int.Parse(tokenizer.Current); + reactantCount = int.Parse(tokenizer.Current, NumberFormatInfo.InvariantInfo); Trace.TraceInformation("Expecting " + reactantCount + " reactants in file"); tokenizer.MoveNext(); - productCount = int.Parse(tokenizer.Current); + productCount = int.Parse(tokenizer.Current, NumberFormatInfo.InvariantInfo); if (tokenizer.MoveNext()) { - agentCount = int.Parse(tokenizer.Current); + agentCount = int.Parse(tokenizer.Current, NumberFormatInfo.InvariantInfo); // ChemAxon extension, technically BIOVIA now support this but // not documented yet if (ReaderMode == ChemObjectReaderMode.Strict && agentCount > 0) @@ -209,7 +210,7 @@ private IReaction ReadReaction(IChemObjectBuilder builder) molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append('\n'); - } while (!molFileLine.Equals("M END")); + } while (!string.Equals(molFileLine, "M END", StringComparison.Ordinal)); // read MDL molfile content // Changed this to mdlv2000 reader @@ -221,10 +222,10 @@ private IReaction ReadReaction(IChemObjectBuilder builder) reaction.Reactants.Add(reactant); } } - catch (CDKException exception) + catch (CDKException) { // rethrow exception from MDLReader - throw exception; + throw; } catch (Exception exception) { @@ -249,7 +250,7 @@ private IReaction ReadReaction(IChemObjectBuilder builder) molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append('\n'); - } while (!molFileLine.Equals("M END")); + } while (!string.Equals(molFileLine, "M END", StringComparison.Ordinal)); // read MDL molfile content MDLV2000Reader reader = new MDLV2000Reader(new StringReader(molFile.ToString())); @@ -288,7 +289,7 @@ private IReaction ReadReaction(IChemObjectBuilder builder) molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append('\n'); - } while (!molFileLine.Equals("M END")); + } while (!string.Equals(molFileLine, "M END", StringComparison.Ordinal)); // read MDL molfile content MDLV2000Reader reader = new MDLV2000Reader(new StringReader(molFile.ToString())); diff --git a/NCDK/IO/MDLRXNV3000Reader.cs b/NCDK/IO/MDLRXNV3000Reader.cs index e307d801..ada83698 100644 --- a/NCDK/IO/MDLRXNV3000Reader.cs +++ b/NCDK/IO/MDLRXNV3000Reader.cs @@ -21,6 +21,7 @@ using NCDK.IO.Formats; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text; @@ -65,8 +66,10 @@ public MDLRXNV3000Reader(Stream input, ChemObjectReaderMode mode) public override bool Accepts(Type type) { - if (typeof(IChemModel).IsAssignableFrom(type)) return true; - if (typeof(IReaction).IsAssignableFrom(type)) return true; + if (typeof(IChemModel).IsAssignableFrom(type)) + return true; + if (typeof(IReaction).IsAssignableFrom(type)) + return true; return false; } @@ -120,7 +123,7 @@ private string ReadLine() try { line = input.ReadLine(); - Debug.WriteLine("read line: " + line); + Debug.WriteLine($"read line: {line}"); } catch (Exception exception) { @@ -151,9 +154,9 @@ private IReaction ReadReaction(IChemObjectBuilder builder) var tokenizer = Strings.Tokenize(command); try { - reactantCount = int.Parse(tokenizer[1]); + reactantCount = int.Parse(tokenizer[1], NumberFormatInfo.InvariantInfo); Trace.TraceInformation($"Expecting {reactantCount} reactants in file"); - productCount = int.Parse(tokenizer[2]); + productCount = int.Parse(tokenizer[2], NumberFormatInfo.InvariantInfo); Trace.TraceInformation($"Expecting {productCount } products in file"); } catch (Exception exception) @@ -174,7 +177,7 @@ private IReaction ReadReaction(IChemObjectBuilder builder) { StringBuilder molFile = new StringBuilder(); string announceMDLFileLine = ReadCommand(); - if (!announceMDLFileLine.Equals("BEGIN REACTANT")) + if (!string.Equals(announceMDLFileLine, "BEGIN REACTANT", StringComparison.Ordinal)) { string error = "Excepted start of reactant, but found: " + announceMDLFileLine; Trace.TraceError(error); @@ -216,7 +219,7 @@ exception is CDKException || { StringBuilder molFile = new StringBuilder(); string announceMDLFileLine = ReadCommand(); - if (!announceMDLFileLine.Equals("BEGIN PRODUCT")) + if (!string.Equals(announceMDLFileLine, "BEGIN PRODUCT", StringComparison.Ordinal)) { string error = "Excepted start of product, but found: " + announceMDLFileLine; Trace.TraceError(error); @@ -256,13 +259,13 @@ exception is CDKException || return reaction; } - public bool Accepts(IChemObject obj) + public virtual bool Accepts(IChemObject o) { - if (obj is IReaction) + if (o is IReaction) { return true; } - else if (obj is IChemModel) + else if (o is IChemModel) { return true; } @@ -289,6 +292,6 @@ protected override void Dispose(bool disposing) } #endregion - private void InitIOSettings() { } + private static void InitIOSettings() { } } } diff --git a/NCDK/IO/MDLRXNWriter.cs b/NCDK/IO/MDLRXNWriter.cs index 8baf1903..dd64a470 100644 --- a/NCDK/IO/MDLRXNWriter.cs +++ b/NCDK/IO/MDLRXNWriter.cs @@ -49,7 +49,7 @@ public class MDLRXNWriter : DefaultChemObjectWriter { private TextWriter writer; private int reactionNumber; - public IDictionary rdFields = null; + private IReadOnlyDictionary rdFields = null; /// /// Constructs a new MDLWriter that can write an array of @@ -83,7 +83,7 @@ public MDLRXNWriter(Stream output) /// /// /// The map to be used, map of string-string pairs - public void SetRdFields(IDictionary map) + public void SetRdFields(IReadOnlyDictionary map) { rdFields = map; } @@ -208,7 +208,7 @@ private void WriteReaction(IReaction reaction) //write sdfields, if any if (rdFields != null) { - ICollection set = rdFields.Keys; + var set = rdFields.Keys; foreach (var element in set) { writer.Write("> <" + (string)element + ">"); @@ -274,7 +274,7 @@ private void WriteAtomContainerSet(IChemObjectSet som) /// The int to be formated /// Length of the string /// The string to be written into the connectiontable - private string FormatMDLInt(int i, int l) + private static string FormatMDLInt(int i, int l) { var s = i.ToString(CultureInfo.InvariantCulture.NumberFormat); l = Math.Max(s.Length, l); diff --git a/NCDK/IO/MDLReader.cs b/NCDK/IO/MDLReader.cs index 2952eb22..448d893a 100644 --- a/NCDK/IO/MDLReader.cs +++ b/NCDK/IO/MDLReader.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text.RegularExpressions; @@ -185,9 +186,9 @@ private IChemFile ReadChemFile(IChemFile chemFile) // apparently, this is a SDF file, continue with // reading mol files str = line; - if (line.Equals("M END")) + if (string.Equals(line, "M END", StringComparison.Ordinal)) continue; - if (str.Equals("$$$$")) + if (string.Equals(str, "$$$$", StringComparison.Ordinal)) { m = ReadMolecule(chemFile.Builder.NewAtomContainer()); @@ -213,8 +214,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) if (str.StartsWith("> ", StringComparison.Ordinal)) { // ok, should extract the field name - str.Substring(2); // string content = - int index = str.IndexOf('<'); + int index = str.IndexOf('<', 2); if (index != -1) { int index2 = str.Substring(index).IndexOf('>'); @@ -236,7 +236,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) string data = line; while ((line = input.ReadLine()) != null && line.Trim().Length > 0) { - if (line.Equals("$$$$")) + if (string.Equals(line, "$$$$", StringComparison.Ordinal)) { Trace.TraceError($"Expecting data line here, but found end of molecule: {line}"); break; @@ -306,14 +306,14 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) double totalX = 0.0; double totalY = 0.0; double totalZ = 0.0; - //int[][] conMat = new int[0][0]; + //int[][] conMat = Array.Empty()[0]; //string help; IAtom atom; string line = ""; try { - IsotopeFactory isotopeFactory = Isotopes.Instance; + IsotopeFactory isotopeFactory = BODRIsotopeFactory.Instance; Trace.TraceInformation("Reading header"); line = input.ReadLine(); @@ -359,10 +359,10 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) throw new CDKException("This file must be read with the MDLV3000Reader."); } } - atoms = int.Parse(Strings.Substring(line, 0, 3).Trim()); - Debug.WriteLine("Atomcount: " + atoms); - bonds = int.Parse(Strings.Substring(line, 3, 3).Trim()); - Debug.WriteLine("Bondcount: " + bonds); + atoms = int.Parse(Strings.Substring(line, 0, 3).Trim(), NumberFormatInfo.InvariantInfo); + Debug.WriteLine($"Atomcount: {atoms}"); + bonds = int.Parse(Strings.Substring(line, 3, 3).Trim(), NumberFormatInfo.InvariantInfo); + Debug.WriteLine($"Bondcount: {bonds}"); // read ATOM block Trace.TraceInformation("Reading atom block"); @@ -376,9 +376,9 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) HandleError("Trailing space found", linecount, trailingSpaceMatcher.Index, trailingSpaceMatcher.Index + trailingSpaceMatcher.Length); line = Strings.Substring(line, 0, trailingSpaceMatcher.Index); } - x = double.Parse(Strings.Substring(line, 0, 10).Trim()); - y = double.Parse(Strings.Substring(line, 10, 10).Trim()); - z = double.Parse(Strings.Substring(line, 20, 10).Trim()); + x = double.Parse(Strings.Substring(line, 0, 10).Trim(), NumberFormatInfo.InvariantInfo); + y = double.Parse(Strings.Substring(line, 10, 10).Trim(), NumberFormatInfo.InvariantInfo); + z = double.Parse(Strings.Substring(line, 20, 10).Trim(), NumberFormatInfo.InvariantInfo); // *all* values should be zero, not just the sum totalX += Math.Abs(x); totalY += Math.Abs(y); @@ -391,28 +391,28 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) + " and padded with space if required", linecount, 31, 34); } - Debug.WriteLine("Atom type: ", element); + Debug.WriteLine($"Atom type: {element}"); if (isotopeFactory.IsElement(element)) { atom = isotopeFactory.Configure(molecule.Builder.NewAtom(element)); } - else if ("A".Equals(element)) + else if (string.Equals("A", element, StringComparison.Ordinal)) { atom = molecule.Builder.NewPseudoAtom(element); } - else if ("Q".Equals(element)) + else if (string.Equals("Q", element, StringComparison.Ordinal)) { atom = molecule.Builder.NewPseudoAtom(element); } - else if ("*".Equals(element)) + else if (string.Equals("*", element, StringComparison.Ordinal)) { atom = molecule.Builder.NewPseudoAtom(element); } - else if ("LP".Equals(element)) + else if (string.Equals("LP", element, StringComparison.Ordinal)) { atom = molecule.Builder.NewPseudoAtom(element); } - else if ("L".Equals(element)) + else if (string.Equals("L", element, StringComparison.Ordinal)) { atom = molecule.Builder.NewPseudoAtom(element); } @@ -450,15 +450,15 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) if (line.Length >= 36) { string massDiffString = Strings.Substring(line, 34, 2).Trim(); - Debug.WriteLine("Mass difference: ", massDiffString); + Debug.WriteLine($"Mass difference: {massDiffString}"); if (!(atom is IPseudoAtom)) { try { - int massDiff = int.Parse(massDiffString); + int massDiff = int.Parse(massDiffString, NumberFormatInfo.InvariantInfo); if (massDiff != 0) { - IIsotope major = Isotopes.Instance.GetMajorIsotope(element); + IIsotope major = BODRIsotopeFactory.Instance.GetMajorIsotope(element); atom.AtomicNumber = major.AtomicNumber + massDiff; } } @@ -482,8 +482,8 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) if (line.Length >= 39) { string chargeCodeString = Strings.Substring(line, 36, 3).Trim(); - Debug.WriteLine("Atom charge code: ", chargeCodeString); - int chargeCode = int.Parse(chargeCodeString); + Debug.WriteLine($"Atom charge code: {chargeCodeString}"); + int chargeCode = int.Parse(chargeCodeString, NumberFormatInfo.InvariantInfo); if (chargeCode == 0) { // uncharged species @@ -525,10 +525,10 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) { // read the mmm field as position 61-63 string reactionAtomIDString = Strings.Substring(line, 60, 3).Trim(); - Debug.WriteLine("Parsing mapping id: ", reactionAtomIDString); + Debug.WriteLine($"Parsing mapping id: {reactionAtomIDString}"); try { - int reactionAtomID = int.Parse(reactionAtomIDString); + int reactionAtomID = int.Parse(reactionAtomIDString, NumberFormatInfo.InvariantInfo); if (reactionAtomID != 0) { atom.SetProperty(CDKPropertyName.AtomAtomMapping, reactionAtomID); @@ -549,12 +549,12 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) //shk3: This reads shifts from after the molecule. I don't think this is an official format, but I saw it frequently 80=>78 for alk if (line.Length >= 78) { - double shift = double.Parse(Strings.Substring(line, 69, 11).Trim()); + double shift = double.Parse(Strings.Substring(line, 69, 11).Trim(), NumberFormatInfo.InvariantInfo); atom.SetProperty("first shift", shift); } if (line.Length >= 87) { - double shift = double.Parse(Strings.Substring(line, 79, 8).Trim()); + double shift = double.Parse(Strings.Substring(line, 79, 8).Trim(), NumberFormatInfo.InvariantInfo); atom.SetProperty("second shift", shift); } @@ -589,12 +589,12 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) { line = input.ReadLine(); linecount++; - atom1 = int.Parse(Strings.Substring(line, 0, 3).Trim()); - atom2 = int.Parse(Strings.Substring(line, 3, 3).Trim()); - order = int.Parse(Strings.Substring(line, 6, 3).Trim()); + atom1 = int.Parse(Strings.Substring(line, 0, 3).Trim(), NumberFormatInfo.InvariantInfo); + atom2 = int.Parse(Strings.Substring(line, 3, 3).Trim(), NumberFormatInfo.InvariantInfo); + order = int.Parse(Strings.Substring(line, 6, 3).Trim(), NumberFormatInfo.InvariantInfo); if (line.Length > 12) { - int mdlStereo = int.Parse(Strings.Substring(line, 9, 3).Trim()); + int mdlStereo = int.Parse(Strings.Substring(line, 9, 3).Trim(), NumberFormatInfo.InvariantInfo); if (mdlStereo == 1) { // MDL up bond @@ -700,13 +700,13 @@ protected override void Dispose(bool disposing) private void InitIOSettings() { - forceReadAs3DCoords = IOSettings.Add(new BooleanIOSetting("ForceReadAs3DCoordinates", IOSetting.Importance.Low, - "Should coordinates always be read as 3D?", "false")); + forceReadAs3DCoords = IOSettings.Add(new BooleanIOSetting("ForceReadAs3DCoordinates", Importance.Low, + "Should coordinates always be read as 3D?", "false")); } public void CustomizeJob() { - FireIOSettingQuestion(forceReadAs3DCoords); + ProcessIOSettingQuestion(forceReadAs3DCoords); } } } diff --git a/NCDK/IO/MDLV2000Reader.cs b/NCDK/IO/MDLV2000Reader.cs index 9b899bfc..fa1e97ae 100644 --- a/NCDK/IO/MDLV2000Reader.cs +++ b/NCDK/IO/MDLV2000Reader.cs @@ -36,6 +36,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -94,23 +95,26 @@ public class MDLV2000Reader : DefaultChemObjectReader private const string RECORD_DELIMITER = "$$$$"; /// Valid pseudo labels. - private static readonly ICollection PseudoLabels = - new ReadOnlyCollection(new[] { - "*", "A", "Q", - "L", "LP", "R", // XXX: not in spec - "R#"}); + private static readonly string[] PseudoLabels = new[] + { + "*", "A", "Q", + "L", "LP", "R", // XXX: not in spec + "R#" + }; /// /// Constructs a new that can read Molecule from a given . /// /// The Stream to read from - public MDLV2000Reader(Stream input) + public MDLV2000Reader(Stream input) : this(new StreamReader(input)) - { } + { + } public MDLV2000Reader(Stream input, ChemObjectReaderMode mode) : this(new StreamReader(input), mode) - { } + { + } /// /// Constructs a new that can read Molecule from a given . @@ -118,7 +122,8 @@ public MDLV2000Reader(Stream input, ChemObjectReaderMode mode) /// The Reader to read from public MDLV2000Reader(TextReader input) : this(input, ChemObjectReaderMode.Relaxed) - { } + { + } public MDLV2000Reader(TextReader input, ChemObjectReaderMode mode) { @@ -372,7 +377,7 @@ private IAtomContainer ReadAtomContainer(IAtomContainer molecule) { //' CDK 09251712073D' // 0123456789012345678901 - if (!(program.Length >= 22 && program.Substring(20, 2).Equals("3D")) + if (!(program.Length >= 22 && program.Substring(20, 2).Equals("3D", StringComparison.Ordinal)) && !forceReadAs3DCoords.IsSet) { foreach (var atomToUpdate in atoms) @@ -533,7 +538,7 @@ private IAtomContainer ReadAtomContainer(IAtomContainer molecule) /// /// the atom to apply the model to /// the explicit valence (bond order sum) - private void ApplyMDLValenceModel(IAtom atom, int explicitValence, int unpaired) + private static void ApplyMDLValenceModel(IAtom atom, int explicitValence, int unpaired) { if (atom.Valency != null) { @@ -562,27 +567,34 @@ private void ApplyMDLValenceModel(IAtom atom, int explicitValence, int unpaired) } } - private void FixHydrogenIsotopes(IAtomContainer molecule, IsotopeFactory isotopeFactory) + private static void FixHydrogenIsotopes(IAtomContainer molecule, IsotopeFactory isotopeFactory) { - foreach (var atom in AtomContainerManipulator.GetAtomArray(molecule)) + foreach (var atom in molecule.Atoms) { if (atom is IPseudoAtom pseudo) { - if ("D".Equals(pseudo.Label)) + switch (pseudo.Label) { - IAtom newAtom = molecule.Builder.NewAtom(atom); - newAtom.Symbol = "H"; - newAtom.AtomicNumber = 1; - isotopeFactory.Configure(newAtom, isotopeFactory.GetIsotope("H", 2)); - AtomContainerManipulator.ReplaceAtomByAtom(molecule, atom, newAtom); - } - else if ("T".Equals(pseudo.Label)) - { - IAtom newAtom = molecule.Builder.NewAtom(atom); - newAtom.Symbol = "H"; - newAtom.AtomicNumber = 1; - isotopeFactory.Configure(newAtom, isotopeFactory.GetIsotope("H", 3)); - AtomContainerManipulator.ReplaceAtomByAtom(molecule, atom, newAtom); + case "D": + { + IAtom newAtom = molecule.Builder.NewAtom(atom); + newAtom.Symbol = "H"; + newAtom.AtomicNumber = 1; + isotopeFactory.Configure(newAtom, isotopeFactory.GetIsotope("H", 2)); + AtomContainerManipulator.ReplaceAtomByAtom(molecule, atom, newAtom); + } + break; + case "T": + { + IAtom newAtom = molecule.Builder.NewAtom(atom); + newAtom.Symbol = "H"; + newAtom.AtomicNumber = 1; + isotopeFactory.Configure(newAtom, isotopeFactory.GetIsotope("H", 3)); + AtomContainerManipulator.ReplaceAtomByAtom(molecule, atom, newAtom); + } + break; + default: + break; } } } @@ -610,23 +622,23 @@ protected override void Dispose(bool disposing) private void InitIOSettings() { - forceReadAs3DCoords = IOSettings.Add(new BooleanIOSetting("ForceReadAs3DCoordinates", IOSetting.Importance.Low, - "Should coordinates always be read as 3D?", "false")); - interpretHydrogenIsotopes = IOSettings.Add((new BooleanIOSetting("InterpretHydrogenIsotopes", - IOSetting.Importance.Low, "Should D and T be interpreted as hydrogen isotopes?", "true"))); - addStereoElements = IOSettings.Add((new BooleanIOSetting("AddStereoElements", IOSetting.Importance.Low, - "Detect and create IStereoElements for the input.", "true"))); + forceReadAs3DCoords = IOSettings.Add(new BooleanIOSetting("ForceReadAs3DCoordinates", Importance.Low, + "Should coordinates always be read as 3D?", "false")); + interpretHydrogenIsotopes = IOSettings.Add((new BooleanIOSetting("InterpretHydrogenIsotopes", Importance.Low, + "Should D and T be interpreted as hydrogen isotopes?", "true"))); + addStereoElements = IOSettings.Add((new BooleanIOSetting("AddStereoElements", Importance.Low, + "Detect and create IStereoElements for the input.", "true"))); } public void CustomizeJob() { foreach (var setting in IOSettings.Settings) { - FireIOSettingQuestion(setting); + ProcessIOSettingQuestion(setting); } } - private string RemoveNonDigits(string input) + private static string RemoveNonDigits(string input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.Length; i++) @@ -732,7 +744,7 @@ internal IAtom ReadAtomFast(string line, IChemObjectBuilder builder, IDictionary // if there was a mass difference, set the mass number if (massDiff != 0 && atom.AtomicNumber > 0) { - IIsotope majorIsotope = Isotopes.Instance.GetMajorIsotope(atom.AtomicNumber.Value); + IIsotope majorIsotope = BODRIsotopeFactory.Instance.GetMajorIsotope(atom.AtomicNumber.Value); if (majorIsotope == null) atom.MassNumber = -1; // checked after M ISO is processed else @@ -858,7 +870,7 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int // already had atoms present before reading the file int offset = container.Atoms.Count - nAtoms; - IDictionary sgroups = new SortedDictionary(); + var sgroups = new SortedDictionary(); while ((line = input.ReadLine()) != null) { @@ -1045,7 +1057,7 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int sgroup = new Sgroup(); sgroups[index] = sgroup; - SgroupType type = SgroupTypeTools.Parse(Strings.Substring(line, lnOffset + 4, 3)); + var type = SgroupTool.ToSgroupType(Strings.Substring(line, lnOffset + 4, 3)); if (type != SgroupType.Nil) sgroup.Type = type; } @@ -1065,9 +1077,19 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int string sst = Strings.Substring(line, st + 4, 3); - if (ReaderMode == ChemObjectReaderMode.Strict && !("ALT".Equals(sst) || "RAN".Equals(sst) || "BLO".Equals(sst))) - HandleError("Invalid sgroup subtype: " + sst + " expected (ALT, RAN, or BLO)"); - + if (ReaderMode == ChemObjectReaderMode.Strict) + { + switch (sst) + { + case "ALT": + case "RAN": + case "BLO": + break; + default: + HandleError("Invalid sgroup subtype: " + sst + " expected (ALT, RAN, or BLO)"); + break; + } + } sgroup.PutValue(SgroupKey.CtabSubType, sst); } } @@ -1125,10 +1147,20 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int sgroup = EnsureSgroup(sgroups, ReadMolfileInt(line, st)); string con = Strings.Substring(line, st + 4, 3).Trim(); - if (ReaderMode == ChemObjectReaderMode.Strict && !("HH".Equals(con) || "HT".Equals(con) || "EU".Equals(con))) - HandleError("Unknown SCN type (expected: HH, HT, or EU) was " + con); - sgroup.PutValue(SgroupKey.CtabConnectivity, - con); + if (ReaderMode == ChemObjectReaderMode.Strict) + { + switch (con) + { + case "HH": + case "HT": + case "EU": + break; + default: + HandleError($"Unknown SCN type (expected: HH, HT, or EU) was {con}"); + break; + } + } + sgroup.PutValue(SgroupKey.CtabConnectivity, con); } } else if (key == PropertyKey.M_SDI) @@ -1179,7 +1211,7 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int // Sgroup Expansion // M SDS EXPn15 sss ... // sss: Sgroup index of expanded abbreviation Sgroups - if ("EXP".Equals(Strings.Substring(line, 7, 3))) + if (string.Equals("EXP", Strings.Substring(line, 7, 3), StringComparison.Ordinal)) { count = ReadMolfileInt(line, 10); for (int i = 0, st = 14; i < count && st + 3 <= length; i++, st += 4) @@ -1255,8 +1287,8 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int if (sgroups.Any()) { // load Sgroups into molecule, first we downcast - List sgroupOrgList = new List(sgroups.Values); - List sgroupCpyList = new List(sgroupOrgList.Count); + var sgroupOrgList = new List(sgroups.Values); + var sgroupCpyList = new List(sgroupOrgList.Count); for (int i = 0; i < sgroupOrgList.Count; i++) { Sgroup cpy = sgroupOrgList[i].Downcast(); @@ -1273,7 +1305,7 @@ internal void ReadPropertiesFast(TextReader input, IAtomContainer container, int newSgroup.AddParent(sgroupCpyList[sgroupOrgList.IndexOf(parent)]); } } - container.SetProperty(CDKPropertyName.CtabSgroups, sgroupCpyList); + container.SetCtabSgroups(sgroupCpyList); } } @@ -1360,21 +1392,27 @@ private IAtom CreateAtom(string symbol, IChemObjectBuilder builder, int lineNum) atom.AtomicNumber = elem.AtomicNumber; return atom; } - if (symbol.Equals("D") && interpretHydrogenIsotopes.IsSet) - { - if (ReaderMode == ChemObjectReaderMode.Strict) throw new CDKException("invalid symbol: " + symbol); - IAtom atom = builder.NewAtom("H"); - atom.MassNumber = 2; - return atom; - } - if (symbol.Equals("T") && interpretHydrogenIsotopes.IsSet) + switch (symbol) { - if (ReaderMode == ChemObjectReaderMode.Strict) throw new CDKException("invalid symbol: " + symbol); - IAtom atom = builder.NewAtom("H"); - atom.MassNumber = 3; - return atom; + case "D": + if (interpretHydrogenIsotopes.IsSet) + { + if (ReaderMode == ChemObjectReaderMode.Strict) throw new CDKException("invalid symbol: " + symbol); + IAtom atom = builder.NewAtom("H"); + atom.MassNumber = 2; + return atom; + } + break; + case "T": + if (interpretHydrogenIsotopes.IsSet) + { + if (ReaderMode == ChemObjectReaderMode.Strict) throw new CDKException("invalid symbol: " + symbol); + IAtom atom = builder.NewAtom("H"); + atom.MassNumber = 3; + return atom; + } + break; } - if (!IsPseudoElement(symbol)) { HandleError("invalid symbol: " + symbol, lineNum, 31, 34); @@ -1384,7 +1422,8 @@ private IAtom CreateAtom(string symbol, IChemObjectBuilder builder, int lineNum) { // will be renumbered later by RGP if R1, R2 etc. if not renumbered then // 'R' is a better label than 'R#' if now RGP is specified - if (symbol.Equals("R#")) symbol = "R"; + if (string.Equals(symbol, "R#", StringComparison.Ordinal)) + symbol = "R"; IAtom atom = builder.NewPseudoAtom(symbol); atom.Symbol = symbol; @@ -1421,7 +1460,7 @@ internal double ReadMDLCoordinate(string line, int offset) // to be valid the decimal should be at the fifth index (4 sig fig) if (line[offset + 5] != '.') { - HandleError("Bad coordinate format specified, expected 4 decimal places: " + line.Substring(offset)); + HandleError($"Bad coordinate format specified, expected 4 decimal places: {line.Substring(offset)}"); int start = offset; while (line[start] == ' ' && start < offset + 9) start++; @@ -1440,14 +1479,15 @@ internal double ReadMDLCoordinate(string line, int offset) else if (dot != -1) { int sign = Sign(line[start]); - if (sign < 0) start++; + if (sign < 0) + start++; int integral = ReadUInt(line, start, dot - start - 1); int fraction = ReadUInt(line, dot, end - dot); return sign * (integral * 10000L + fraction) / 10000d; } else { - return double.Parse(line.Substring(start, end - start)); + return double.Parse(line.Substring(start, end - start), NumberFormatInfo.InvariantInfo); } } else @@ -1457,7 +1497,8 @@ internal double ReadMDLCoordinate(string line, int offset) start++; int sign = Sign(line[start]); - if (sign < 0) start++; + if (sign < 0) + start++; int integral = ReadUInt(line, start, (offset + 5) - start); int fraction = ReadUInt(line, offset + 6, 4); @@ -1671,9 +1712,9 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun HandleError("Trailing space found", linecount, match.Index, match.Index + match.Length); return ""; }); - double x = double.Parse(Strings.Substring(line, 0, 10).Trim()); - double y = double.Parse(Strings.Substring(line, 10, 10).Trim()); - double z = double.Parse(Strings.Substring(line, 20, 10).Trim()); + double x = double.Parse(Strings.Substring(line, 0, 10).Trim(), NumberFormatInfo.InvariantInfo); + double y = double.Parse(Strings.Substring(line, 10, 10).Trim(), NumberFormatInfo.InvariantInfo); + double z = double.Parse(Strings.Substring(line, 20, 10).Trim(), NumberFormatInfo.InvariantInfo); string element = Strings.Substring(line, 31, 3).Trim(); if (line.Length < 34) @@ -1682,33 +1723,33 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun + " and padded with space if required", linecount, 31, 34); } - Debug.WriteLine("Atom type: ", element); - IsotopeFactory isotopeFactory = Isotopes.Instance; + Debug.WriteLine($"Atom type: {element}"); + IsotopeFactory isotopeFactory = BODRIsotopeFactory.Instance; if (isotopeFactory.IsElement(element)) { atom = isotopeFactory.Configure(builder.NewAtom(element)); } - else if ("A".Equals(element)) + else if (string.Equals("A", element, StringComparison.Ordinal)) { atom = builder.NewPseudoAtom(element); } - else if ("Q".Equals(element)) + else if (string.Equals("Q", element, StringComparison.Ordinal)) { atom = builder.NewPseudoAtom(element); } - else if ("*".Equals(element)) + else if (string.Equals("*", element, StringComparison.Ordinal)) { atom = builder.NewPseudoAtom(element); } - else if ("LP".Equals(element)) + else if (string.Equals("LP", element, StringComparison.Ordinal)) { atom = builder.NewPseudoAtom(element); } - else if ("L".Equals(element)) + else if (string.Equals("L", element, StringComparison.Ordinal)) { atom = builder.NewPseudoAtom(element); } - else if (element.Equals("R") || (element.Length > 0 && element[0] == 'R')) + else if (string.Equals(element, "R", StringComparison.Ordinal) || (element.Length > 0 && element[0] == 'R')) { Debug.WriteLine("Atom ", element, " is not an regular element. Creating a PseudoAtom."); //check if the element is R @@ -1716,7 +1757,7 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun { try { - element = "R" + int.Parse(element.Substring(1)); + element = "R" + int.Parse(element.Substring(1), NumberFormatInfo.InvariantInfo); atom = builder.NewPseudoAtom(element); } catch (Exception) @@ -1746,15 +1787,15 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun if (line.Length >= 36) { string massDiffString = Strings.Substring(line, 34, 2).Trim(); - Debug.WriteLine("Mass difference: ", massDiffString); + Debug.WriteLine($"Mass difference: {massDiffString}"); if (!(atom is IPseudoAtom)) { try { - int massDiff = int.Parse(massDiffString); + int massDiff = int.Parse(massDiffString, NumberFormatInfo.InvariantInfo); if (massDiff != 0) { - IIsotope major = Isotopes.Instance.GetMajorIsotope(element); + IIsotope major = BODRIsotopeFactory.Instance.GetMajorIsotope(element); atom.MassNumber = major.MassNumber + massDiff; } } @@ -1778,18 +1819,18 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun } // set the stereo partiy - var parity = line.Length > 41 ? int.Parse(line[41].ToString()) : 0; + var parity = line.Length > 41 ? int.Parse(new string(new[] { line[41] }), NumberFormatInfo.InvariantInfo) : 0; atom.StereoParity = parity; if (line.Length >= 51) { string valenceString = RemoveNonDigits(Strings.Substring(line, 48, 3)); - Debug.WriteLine("Valence: ", valenceString); + Debug.WriteLine($"Valence: {valenceString}"); if (!(atom is IPseudoAtom)) { try { - int valence = int.Parse(valenceString); + int valence = int.Parse(valenceString, NumberFormatInfo.InvariantInfo); if (valence != 0) { //15 is defined as 0 in mol files @@ -1813,8 +1854,8 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun if (line.Length >= 39) { string chargeCodeString = Strings.Substring(line, 36, 3).Trim(); - Debug.WriteLine("Atom charge code: ", chargeCodeString); - int chargeCode = int.Parse(chargeCodeString); + Debug.WriteLine($"Atom charge code: {chargeCodeString}"); + int chargeCode = int.Parse(chargeCodeString, NumberFormatInfo.InvariantInfo); if (chargeCode == 0) { // uncharged species @@ -1856,10 +1897,10 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun { // read the mmm field as position 61-63 string reactionAtomIDString = Strings.Substring(line, 60, 3).Trim(); - Debug.WriteLine("Parsing mapping id: ", reactionAtomIDString); + Debug.WriteLine($"Parsing mapping id: {reactionAtomIDString}"); try { - int reactionAtomID = int.Parse(reactionAtomIDString); + int reactionAtomID = int.Parse(reactionAtomIDString, NumberFormatInfo.InvariantInfo); if (reactionAtomID != 0) { atom.SetProperty(CDKPropertyName.AtomAtomMapping, reactionAtomID); @@ -1880,12 +1921,12 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun //shk3: This reads shifts from after the molecule. I don't think this is an official format, but I saw it frequently 80=>78 for alk if (line.Length >= 78) { - double shift = double.Parse(Strings.Substring(line, 69, 11).Trim()); + double shift = double.Parse(Strings.Substring(line, 69, 11).Trim(), NumberFormatInfo.InvariantInfo); atom.SetProperty("first shift", shift); } if (line.Length >= 87) { - double shift = double.Parse(Strings.Substring(line, 79, 8).Trim()); + double shift = double.Parse(Strings.Substring(line, 79, 8).Trim(), NumberFormatInfo.InvariantInfo); atom.SetProperty("second shift", shift); } @@ -1905,14 +1946,15 @@ private IAtom ReadAtomSlow(string line, IChemObjectBuilder builder, int linecoun /// the bond line could not be parsed private IBond ReadBondSlow(string line, IChemObjectBuilder builder, IAtom[] atoms, int[] explicitValence, int linecount) { - int atom1 = int.Parse(Strings.Substring(line, 0, 3).Trim()); - int atom2 = int.Parse(Strings.Substring(line, 3, 3).Trim()); - int order = int.Parse(Strings.Substring(line, 6, 3).Trim()); + int atom1 = int.Parse(Strings.Substring(line, 0, 3).Trim(), NumberFormatInfo.InvariantInfo); + int atom2 = int.Parse(Strings.Substring(line, 3, 3).Trim(), NumberFormatInfo.InvariantInfo); + int order = int.Parse(Strings.Substring(line, 6, 3).Trim(), NumberFormatInfo.InvariantInfo); BondStereo stereo = BondStereo.None; if (line.Length >= 12) { - int mdlStereo = line.Length > 12 ? int.Parse(Strings.Substring(line, 9, 3).Trim()) : int.Parse(line - .Substring(9).Trim()); + int mdlStereo = line.Length > 12 + ? int.Parse(Strings.Substring(line, 9, 3).Trim(), NumberFormatInfo.InvariantInfo) + : int.Parse(line.Substring(9).Trim(), NumberFormatInfo.InvariantInfo); if (mdlStereo == 1) { // MDL up bond @@ -2021,7 +2063,6 @@ private IBond ReadBondSlow(string line, IChemObjectBuilder builder, IAtom[] atom } private static readonly Regex Regex_A_d = new Regex("A\\s{1,4}\\d+", RegexOptions.Compiled); - private static readonly Regex Regex_A_ = new Regex("A\\s{1,4}", RegexOptions.Compiled); /// /// Read the properties from the V2000 block (slow). @@ -2051,17 +2092,17 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int { // FIXME: if this is encountered for the first time, all // atom charges should be set to zero first! - int infoCount = int.Parse(Strings.Substring(line, 6, 3).Trim()); + int infoCount = int.Parse(Strings.Substring(line, 6, 3).Trim(), NumberFormatInfo.InvariantInfo); var st = ((IEnumerable)Strings.Substring(line, 9).Split(' ', '\t')).GetEnumerator(); for (int i = 1; i <= infoCount; i++) { st.MoveNext(); string token = st.Current; - int atomNumber = int.Parse(token.Trim()); + int atomNumber = int.Parse(token.Trim(), NumberFormatInfo.InvariantInfo); st.MoveNext(); token = st.Current; - int charge = int.Parse(token.Trim()); + int charge = int.Parse(token.Trim(), NumberFormatInfo.InvariantInfo); container.Atoms[atomNumber - 1].FormalCharge = charge; } } @@ -2070,7 +2111,7 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int // Reads the pseudo atom property from the mol file // The atom number of the to replaced atom - int aliasAtomNumber = int.Parse(Regex_A_d.Replace(line, "", 1)); + int aliasAtomNumber = int.Parse(Regex_A_d.Replace(line, "", 1), NumberFormatInfo.InvariantInfo); string alias = input.ReadLine(); linecount++; IAtom aliasAtom = container.Atoms[aliasAtomNumber - 1]; @@ -2092,14 +2133,14 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int try { string countString = Strings.Substring(line, 6, 4).Trim(); - int infoCount = int.Parse(countString); + int infoCount = int.Parse(countString, NumberFormatInfo.InvariantInfo); var st = ((IEnumerable)Strings.Substring(line, 10).Split(' ', '\t')).GetEnumerator(); for (int i = 1; i <= infoCount; i++) { st.MoveNext(); - int atomNumber = int.Parse(st.Current.Trim()); + int atomNumber = int.Parse(st.Current.Trim(), NumberFormatInfo.InvariantInfo); st.MoveNext(); - int absMass = int.Parse(st.Current.Trim()); + int absMass = int.Parse(st.Current.Trim(), NumberFormatInfo.InvariantInfo); if (absMass != 0) { IAtom isotope = container.Atoms[atomNumber - 1]; @@ -2120,14 +2161,14 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int try { string countString = Strings.Substring(line, 6, 3).Trim(); - int infoCount = int.Parse(countString); + int infoCount = int.Parse(countString, NumberFormatInfo.InvariantInfo); var st = ((IEnumerable)Strings.Substring(line, 9).Split(' ', '\t')).GetEnumerator(); for (int i = 1; i <= infoCount; i++) { st.MoveNext(); - int atomNumber = int.Parse(st.Current.Trim()); + int atomNumber = int.Parse(st.Current.Trim(), NumberFormatInfo.InvariantInfo); st.MoveNext(); - int rad = int.Parse(st.Current.Trim()); + int rad = int.Parse(st.Current.Trim(), NumberFormatInfo.InvariantInfo); MDLV2000Writer.SpinMultiplicity spin = MDLV2000Writer.SpinMultiplicity.None; if (rad > 0) { @@ -2153,7 +2194,7 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int try { string atomNumberString = Strings.Substring(line, 3, 3).Trim(); - int atomNumber = int.Parse(atomNumberString); + int atomNumber = int.Parse(atomNumberString, NumberFormatInfo.InvariantInfo); //string whatIsThisString = line.Substring(6,9).Trim(); string atomName = input.ReadLine(); @@ -2189,9 +2230,9 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int //Process the R group numbers as defined in RGP line. while (st.MoveNext()) { - int position = int.Parse(st.Current); + int position = int.Parse(st.Current, NumberFormatInfo.InvariantInfo); st.MoveNext(); - int rNumber = int.Parse(st.Current); + int rNumber = int.Parse(st.Current, NumberFormatInfo.InvariantInfo); // the container may have already had atoms before the new atoms were read int index = container.Atoms.Count - nAtoms + position - 1; IPseudoAtom pseudoAtom = (IPseudoAtom)container.Atoms[index]; @@ -2203,7 +2244,7 @@ private void ReadPropertiesSlow(TextReader input, IAtomContainer container, int } if (line.StartsWith("V ", StringComparison.Ordinal)) { - int atomNumber = int.Parse(Strings.Substring(line, 3, 3).Trim()); + int atomNumber = int.Parse(Strings.Substring(line, 3, 3).Trim(), NumberFormatInfo.InvariantInfo); IAtom atomWithComment = container.Atoms[atomNumber - 1]; atomWithComment.SetProperty(CDKPropertyName.Comment, Strings.Substring(line, 7)); } @@ -2264,18 +2305,22 @@ internal static void ReadNonStructuralData(TextReader input, IAtomContainer cont } else { - if (data.Length > 0 || !line.Equals(" ")) line = line.Trim(); + if (data.Length > 0 || !line.Equals(" ", StringComparison.Ordinal)) + line = line.Trim(); - if (string.IsNullOrEmpty(line)) continue; + if (string.IsNullOrEmpty(line)) + continue; - if (!wrap && data.Length > 0) data.Append('\n'); + if (!wrap && data.Length > 0) + data.Append('\n'); data.Append(line); wrap = line.Length == 80; } } - if (header != null) container.SetProperty(header, data.ToString()); + if (header != null) + container.SetProperty(header, data.ToString()); } /// @@ -2287,7 +2332,8 @@ internal static void ReadNonStructuralData(TextReader input, IAtomContainer cont /// the field name internal static string DataHeader(string line) { - if (line.Length > 2 && line[0] != '>' && line[1] != ' ') return null; + if (line.Length > 2 && line[0] != '>' && line[1] != ' ') + return null; if (line.Length < 2) return null; int i = line.IndexOf('<', 2); @@ -2305,7 +2351,7 @@ internal static string DataHeader(string line) /// the line indicates the end of a record was reached private static bool EndOfRecord(string line) { - return line == null || line.Equals(RECORD_DELIMITER); + return line == null || line.Equals(RECORD_DELIMITER, StringComparison.Ordinal); } /// diff --git a/NCDK/IO/MDLV2000Writer.cs b/NCDK/IO/MDLV2000Writer.cs index 1fe4cb41..7ae6cba7 100644 --- a/NCDK/IO/MDLV2000Writer.cs +++ b/NCDK/IO/MDLV2000Writer.cs @@ -66,7 +66,7 @@ public class MDLV2000Writer : DefaultChemObjectWriter /// /// Enumeration of all valid radical values. /// - public class SpinMultiplicity + internal class SpinMultiplicity { public static readonly SpinMultiplicity None = new SpinMultiplicity(0, 0); public static readonly SpinMultiplicity Monovalent = new SpinMultiplicity(2, 1); @@ -229,14 +229,14 @@ public override void Write(IChemObject obj) { Trace.TraceError(ex.Message); Debug.WriteLine(ex); - throw new CDKException("Exception while writing MDL file: " + ex.Message, ex); + throw new CDKException($"Exception while writing MDL file: {ex.Message}", ex); } - throw new CDKException("Only supported is writing of IChemFile, " + "IChemModel, and IAtomContainer objects."); + throw new CDKException("Only supported is writing of IChemFile, IChemModel, and IAtomContainer objects."); } private void WriteChemFile(IChemFile file) { - IAtomContainer bigPile = file.Builder.NewAtomContainer(); + var bigPile = file.Builder.NewAtomContainer(); foreach (var container in ChemFileManipulator.GetAllAtomContainers(file)) { bigPile.Add(container); @@ -250,8 +250,7 @@ private void WriteChemFile(IChemFile file) if (container.GetProperty(CDKPropertyName.Remark) != null) { if (bigPile.GetProperty(CDKPropertyName.Remark) != null) - bigPile.SetProperty(CDKPropertyName.Remark, bigPile.GetProperty(CDKPropertyName.Remark) + "; " - + container.GetProperty(CDKPropertyName.Remark)); + bigPile.SetProperty(CDKPropertyName.Remark, bigPile.GetProperty(CDKPropertyName.Remark) + "; " + container.GetProperty(CDKPropertyName.Remark)); else bigPile.SetProperty(CDKPropertyName.Remark, container.GetProperty(CDKPropertyName.Remark)); } @@ -272,8 +271,10 @@ public void WriteMolecule(IAtomContainer container) // write header block // lines get shortened to 80 chars, that's in the spec string title = container.Title; - if (title == null) title = ""; - if (title.Length > 80) title = title.Substring(0, 80); + if (title == null) + title = ""; + if (title.Length > 80) + title = title.Substring(0, 80); writer.Write(title); writer.Write('\n'); @@ -285,23 +286,25 @@ public void WriteMolecule(IAtomContainer container) // program input, internal registry number (R) if input through MDL // form. A blank line can be substituted for line 2. writer.Write(" CDK "); - writer.Write(DateTime.Now.ToUniversalTime().ToString("MMddyyHHmm")); + writer.Write(DateTime.Now.ToUniversalTime().ToString("MMddyyHHmm", DateTimeFormatInfo.InvariantInfo)); if (dim != 0) { - writer.Write(dim.ToString()); + writer.Write(dim.ToString(NumberFormatInfo.InvariantInfo)); writer.Write('D'); } writer.Write('\n'); string comment = container.GetProperty(CDKPropertyName.Remark); - if (comment == null) comment = ""; - if (comment.Length > 80) comment = comment.Substring(0, 80); + if (comment == null) + comment = ""; + if (comment.Length > 80) + comment = comment.Substring(0, 80); writer.Write(comment); writer.Write('\n'); // index stereo elements for setting atom parity values - IDictionary atomstereo = new Dictionary(); - IDictionary atomindex = new Dictionary(); + var atomstereo = new Dictionary(); + var atomindex = new Dictionary(); foreach (var element in container.StereoElements) if (element is ITetrahedralChirality) atomstereo[((ITetrahedralChirality)element).ChiralAtom] = (ITetrahedralChirality)element; @@ -364,7 +367,7 @@ public void WriteMolecule(IAtomContainer container) // firstly check if it's a numbered R group Match matcher = NUMERED_R_GROUP.Match(label); - if (pseudoAtom.Symbol.Equals("R") && !string.IsNullOrEmpty(label) && matcher.Success) + if (pseudoAtom.Symbol.Equals("R", StringComparison.Ordinal) && !string.IsNullOrEmpty(label) && matcher.Success) { line += "R# "; @@ -373,7 +376,7 @@ public void WriteMolecule(IAtomContainer container) // we use a tree map to ensure the output order is always the same rgroups = new SortedDictionary(); } - rgroups[f + 1] = int.Parse(matcher.Groups[1].Value); + rgroups[f + 1] = int.Parse(matcher.Groups[1].Value, NumberFormatInfo.InvariantInfo); } // not a numbered R group - note the symbol may still be R else @@ -538,7 +541,7 @@ public void WriteMolecule(IAtomContainer container) { try { - int value = int.Parse((string)atomAtomMapping); + int value = int.Parse((string)atomAtomMapping, NumberFormatInfo.InvariantInfo); line += FormatMDLInt(value, 3); } catch (FormatException) @@ -680,7 +683,7 @@ public void WriteMolecule(IAtomContainer container) IAtom atom = container.Atoms[i]; if (atom.GetProperty(CDKPropertyName.Comment) != null && atom.GetProperty(CDKPropertyName.Comment) is string - && !atom.GetProperty(CDKPropertyName.Comment).Trim().Equals("")) + && atom.GetProperty(CDKPropertyName.Comment).Trim().Length != 0) { writer.Write("V "); writer.Write(FormatMDLInt(i + 1, 3)); @@ -724,7 +727,7 @@ public void WriteMolecule(IAtomContainer container) atomIndexSpinMap[i] = SpinMultiplicity.DivalentSinglet; break; default: - Debug.WriteLine("Invalid number of radicals found: " + eCount); + Debug.WriteLine($"Invalid number of radicals found: {eCount}"); break; } } @@ -756,7 +759,7 @@ public void WriteMolecule(IAtomContainer container) int? atomicMass = atom.MassNumber; if (atomicMass != null) { - int majorMass = Isotopes.Instance.GetMajorIsotope(atom.Symbol).MassNumber.Value; + int majorMass = BODRIsotopeFactory.Instance.GetMajorIsotope(atom.Symbol).MassNumber.Value; if (atomicMass != majorMass) { writer.Write("M ISO 1 "); @@ -828,9 +831,9 @@ public void WriteMolecule(IAtomContainer container) writer.Flush(); } - private void WriteSgroups(IAtomContainer container, TextWriter writer, IDictionary atomidxs) + private static void WriteSgroups(IAtomContainer container, TextWriter writer, IReadOnlyDictionary atomidxs) { - IList sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = container.GetCtabSgroups(); if (sgroups == null) return; @@ -1004,7 +1007,7 @@ private void WriteSgroups(IAtomContainer container, TextWriter writer, IDictiona } } - private IList> Wrap(ICollection set, int lim) + private static IList> Wrap(ICollection set, int lim) { IList> wrapped = new List>(); List list = new List(set); @@ -1099,12 +1102,12 @@ protected static string FormatMDLString(string s, int le) /// private void InitIOSettings() { - ForceWriteAs2DCoords = IOSettings.Add(new BooleanIOSetting("ForceWriteAs2DCoordinates", IOSetting.Importance.Low, - "Should coordinates always be written as 2D?", "false")); - WriteAromaticBondTypes = IOSettings.Add(new BooleanIOSetting("WriteAromaticBondTypes", IOSetting.Importance.Low, - "Should aromatic bonds be written as bond type 4?", "false")); - WriteQueryFormatValencies = IOSettings.Add(new BooleanIOSetting("WriteQueryFormatValencies", - IOSetting.Importance.Low, "Should valencies be written in the MDL Query format? (deprecated)", "false")); + ForceWriteAs2DCoords = IOSettings.Add(new BooleanIOSetting("ForceWriteAs2DCoordinates", Importance.Low, + "Should coordinates always be written as 2D?", "false")); + WriteAromaticBondTypes = IOSettings.Add(new BooleanIOSetting("WriteAromaticBondTypes", Importance.Low, + "Should aromatic bonds be written as bond type 4?", "false")); + WriteQueryFormatValencies = IOSettings.Add(new BooleanIOSetting("WriteQueryFormatValencies", Importance.Low, + "Should valencies be written in the MDL Query format? (deprecated)", "false")); } /// @@ -1115,7 +1118,7 @@ public void SetWriteAromaticBondTypes(bool val) { try { - WriteAromaticBondTypes.Setting = val.ToString(); + WriteAromaticBondTypes.Setting = val.ToString(NumberFormatInfo.InvariantInfo); } catch (CDKException) { @@ -1127,7 +1130,7 @@ public void CustomizeJob() { foreach (var setting in IOSettings.Settings) { - FireIOSettingQuestion(setting); + ProcessIOSettingQuestion(setting); } } } diff --git a/NCDK/IO/MDLV3000Reader.cs b/NCDK/IO/MDLV3000Reader.cs index e8c098e4..0edbefdc 100644 --- a/NCDK/IO/MDLV3000Reader.cs +++ b/NCDK/IO/MDLV3000Reader.cs @@ -27,6 +27,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -108,28 +109,28 @@ public IAtomContainer ReadConnectionTable(IChemObjectBuilder builder) while (!foundEND) { string command = ReadCommand(lastLine); - Debug.WriteLine("command found: " + command); - if ("END CTAB".Equals(command)) + Debug.WriteLine($"command found: {command}"); + if (string.Equals("END CTAB", command, StringComparison.Ordinal)) { foundEND = true; } - else if ("BEGIN CTAB".Equals(command)) + else if (string.Equals("BEGIN CTAB", command, StringComparison.Ordinal)) { // that's fine } - else if (command.Equals("COUNTS")) + else if (string.Equals(command, "COUNTS", StringComparison.Ordinal)) { // don't think I need to parse this } - else if ("BEGIN ATOM".Equals(command)) + else if (string.Equals("BEGIN ATOM", command, StringComparison.Ordinal)) { ReadAtomBlock(readData); } - else if ("BEGIN BOND".Equals(command)) + else if (string.Equals("BEGIN BOND", command, StringComparison.Ordinal)) { ReadBondBlock(readData); } - else if ("BEGIN SGROUP".Equals(command)) + else if (string.Equals("BEGIN SGROUP", command, StringComparison.Ordinal)) { ReadSgroup(readData); } @@ -212,7 +213,7 @@ public void ReadAtomBlock(IAtomContainer readData) IsotopeFactory isotopeFactory; try { - isotopeFactory = Isotopes.Instance; + isotopeFactory = BODRIsotopeFactory.Instance; } catch (IOException exception) { @@ -227,14 +228,14 @@ public void ReadAtomBlock(IAtomContainer readData) while (!foundEND) { string command = ReadCommand(ReadLine()); - if ("END ATOM".Equals(command)) + if (string.Equals("END ATOM", command, StringComparison.Ordinal)) { // FIXME: should check whether 3D is really 2D foundEND = true; } else { - Debug.WriteLine("Parsing atom from: " + command); + Debug.WriteLine($"Parsing atom from: {command}"); IAtom atom = readData.Builder.NewAtom(); var tokenizer = Strings.Tokenize(command).GetEnumerator(); // parse the index @@ -258,23 +259,23 @@ public void ReadAtomBlock(IAtomContainer readData) atom.Symbol = element; isotopeFactory.Configure(atom); // ? } - else if ("A".Equals(element)) + else if (string.Equals("A", element, StringComparison.Ordinal)) { atom = readData.Builder.NewPseudoAtom(element); } - else if ("Q".Equals(element)) + else if (string.Equals("Q", element, StringComparison.Ordinal)) { atom = readData.Builder.NewPseudoAtom(element); } - else if ("*".Equals(element)) + else if (string.Equals("*", element, StringComparison.Ordinal)) { atom = readData.Builder.NewPseudoAtom(element); } - else if ("LP".Equals(element)) + else if (string.Equals("LP", element, StringComparison.Ordinal)) { atom = readData.Builder.NewPseudoAtom(element); } - else if ("L".Equals(element)) + else if (string.Equals("L", element, StringComparison.Ordinal)) { atom = readData.Builder.NewPseudoAtom(element); } @@ -286,7 +287,7 @@ public void ReadAtomBlock(IAtomContainer readData) { try { - Rnumber = int.Parse(rGroup[(rGroup.Length - 1)]); + Rnumber = int.Parse(rGroup[(rGroup.Length - 1)], NumberFormatInfo.InvariantInfo); RGroupCounter = Rnumber; } catch (Exception) @@ -318,9 +319,9 @@ public void ReadAtomBlock(IAtomContainer readData) string yString = tokenizer.Current; tokenizer.MoveNext(); string zString = tokenizer.Current; - double x = double.Parse(xString); - double y = double.Parse(yString); - double z = double.Parse(zString); + double x = double.Parse(xString, NumberFormatInfo.InvariantInfo); + double y = double.Parse(yString, NumberFormatInfo.InvariantInfo); + double z = double.Parse(zString, NumberFormatInfo.InvariantInfo); atom.Point3D = new Vector3(x, y, z); atom.Point2D = new Vector2(x, y); // FIXME: dirty! } @@ -334,7 +335,7 @@ public void ReadAtomBlock(IAtomContainer readData) // atom-atom mapping tokenizer.MoveNext(); string mapping = tokenizer.Current; - if (!mapping.Equals("0")) + if (!string.Equals(mapping, "0", StringComparison.Ordinal)) { Trace.TraceWarning("Skipping atom-atom mapping: " + mapping); } // else: default 0 is no mapping defined @@ -352,14 +353,14 @@ public void ReadAtomBlock(IAtomContainer readData) switch (key) { case "CHG": - int charge = int.Parse(value); + int charge = int.Parse(value, NumberFormatInfo.InvariantInfo); if (charge != 0) { // zero is no charge specified atom.FormalCharge = charge; } break; case "RAD": - int numElectons = MDLV2000Writer.SpinMultiplicity.OfValue(int.Parse(value)).SingleElectrons; + int numElectons = MDLV2000Writer.SpinMultiplicity.OfValue(int.Parse(value, NumberFormatInfo.InvariantInfo)).SingleElectrons; while (numElectons-- > 0) { readData.SingleElectrons.Add(readData.Builder.NewSingleElectron(atom)); @@ -370,7 +371,7 @@ public void ReadAtomBlock(IAtomContainer readData) { try { - int valence = int.Parse(value); + int valence = int.Parse(value, NumberFormatInfo.InvariantInfo); if (valence != 0) { //15 is defined as 0 in mol files @@ -408,7 +409,7 @@ public void ReadAtomBlock(IAtomContainer readData) // store atom readData.Atoms.Add(atom); - Debug.WriteLine("Added atom: " + atom); + Debug.WriteLine($"Added atom: {atom}"); } } } @@ -423,13 +424,13 @@ public void ReadBondBlock(IAtomContainer readData) while (!foundEND) { string command = ReadCommand(ReadLine()); - if ("END BOND".Equals(command)) + if (string.Equals("END BOND", command, StringComparison.Ordinal)) { foundEND = true; } else { - Debug.WriteLine("Parsing bond from: " + command); + Debug.WriteLine($"Parsing bond from: {command}"); var tokenizer = Strings.Tokenize(command).GetEnumerator(); IBond bond = readData.Builder.NewBond(); // parse the index @@ -451,7 +452,7 @@ public void ReadBondBlock(IAtomContainer readData) { tokenizer.MoveNext(); string orderString = tokenizer.Current; - int order = int.Parse(orderString); + int order = int.Parse(orderString, NumberFormatInfo.InvariantInfo); if (order >= 4) { Trace.TraceWarning("Query order types are not supported (yet). File a bug if you need it"); @@ -473,7 +474,7 @@ public void ReadBondBlock(IAtomContainer readData) { tokenizer.MoveNext(); string indexAtom1String = tokenizer.Current; - int indexAtom1 = int.Parse(indexAtom1String); + int indexAtom1 = int.Parse(indexAtom1String, NumberFormatInfo.InvariantInfo); IAtom atom1 = readData.Atoms[indexAtom1 - 1]; bond.Atoms.Add(atom1); // bond.Atoms[0] } @@ -489,7 +490,7 @@ public void ReadBondBlock(IAtomContainer readData) { tokenizer.MoveNext(); string indexAtom2String = tokenizer.Current; - int indexAtom2 = int.Parse(indexAtom2String); + int indexAtom2 = int.Parse(indexAtom2String, NumberFormatInfo.InvariantInfo); IAtom atom2 = readData.Atoms[indexAtom2 - 1]; bond.Atoms.Add(atom2); // bond.Atoms[1] } @@ -516,7 +517,7 @@ public void ReadBondBlock(IAtomContainer readData) switch (key) { case "CFG": - int configuration = int.Parse(value); + int configuration = int.Parse(value, NumberFormatInfo.InvariantInfo); if (configuration == 0) { bond.Stereo = BondStereo.None; @@ -539,7 +540,7 @@ public void ReadBondBlock(IAtomContainer readData) // skip first value that is count for (int i = 1; i < endptStr.Length; i++) { - endpts.Add(readData.Atoms[int.Parse(endptStr[i]) - 1]); + endpts.Add(readData.Atoms[int.Parse(endptStr[i], NumberFormatInfo.InvariantInfo) - 1]); } break; case "ATTACH": @@ -565,24 +566,21 @@ public void ReadBondBlock(IAtomContainer readData) readData.Bonds.Add(bond); // storing positional variation - if ("ANY".Equals(attach)) + if (string.Equals("ANY", attach, StringComparison.Ordinal)) { - Sgroup sgroup = new Sgroup - { - Type = SgroupType.ExtMulticenter - }; + Sgroup sgroup = new Sgroup { Type = SgroupType.ExtMulticenter }; sgroup.Atoms.Add(bond.Begin); // could be other end? sgroup.Bonds.Add(bond); foreach (var endpt in endpts) sgroup.Atoms.Add(endpt); - IList sgroups = readData.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = readData.GetCtabSgroups(); if (sgroups == null) - readData.SetProperty(CDKPropertyName.CtabSgroups, sgroups = new List(4)); + readData.SetCtabSgroups(sgroups = new List(4)); sgroups.Add(sgroup); } - Debug.WriteLine("Added bond: " + bond); + Debug.WriteLine($"Added bond: {bond}"); } } } @@ -596,13 +594,13 @@ public void ReadSgroup(IAtomContainer readData) while (!foundEND) { string command = ReadCommand(ReadLine()); - if ("END SGROUP".Equals(command)) + if (string.Equals("END SGROUP", command, StringComparison.Ordinal)) { foundEND = true; } else { - Debug.WriteLine("Parsing Sgroup line: " + command); + Debug.WriteLine($"Parsing Sgroup line: {command}"); var tokenizer = Strings.Tokenize(command).GetEnumerator(); // parse the index tokenizer.MoveNext(); @@ -634,15 +632,15 @@ public void ReadSgroup(IAtomContainer readData) string value = options[key]; try { - if (key.Equals("ATOMS")) + if (string.Equals(key, "ATOMS", StringComparison.Ordinal)) { var atomsTokenizer = Strings.Tokenize(value).GetEnumerator(); atomsTokenizer.MoveNext(); - int.Parse(atomsTokenizer.Current); // should be 1, int atomCount = + int.Parse(atomsTokenizer.Current, NumberFormatInfo.InvariantInfo); // should be 1, int atomCount = atomsTokenizer.MoveNext(); - atomID = int.Parse(atomsTokenizer.Current); + atomID = int.Parse(atomsTokenizer.Current, NumberFormatInfo.InvariantInfo); } - else if (key.Equals("LABEL")) + else if (string.Equals(key, "LABEL", StringComparison.Ordinal)) { label = value; } @@ -709,15 +707,15 @@ private IDictionary ParseOptions(string str) IDictionary keyValueTuples = new Dictionary(); while (str.Length >= 3) { - Debug.WriteLine("Matching remaining option string: " + str); + Debug.WriteLine($"Matching remaining option string: {str}"); var tuple1Matcher = keyValueTuple2.Match(str); if (tuple1Matcher.Success) { string key = tuple1Matcher.Groups[1].Value; string value = tuple1Matcher.Groups[2].Value; str = tuple1Matcher.Groups[3].Value; - Debug.WriteLine("Found key: " + key); - Debug.WriteLine("Found value: " + value); + Debug.WriteLine($"Found key: {key}"); + Debug.WriteLine($"Found value: {value}"); keyValueTuples[key] = value; } else @@ -728,8 +726,8 @@ private IDictionary ParseOptions(string str) string key = tuple2Matcher.Groups[1].Value; string value = tuple2Matcher.Groups[2].Value; str = tuple2Matcher.Groups[3].Value; - Debug.WriteLine("Found key: " + key); - Debug.WriteLine("Found value: " + value); + Debug.WriteLine($"Found key: {key}"); + Debug.WriteLine($"Found value: {value}"); keyValueTuples[key] = value; } else @@ -742,7 +740,7 @@ private IDictionary ParseOptions(string str) return keyValueTuples; } - public string ExhaustStringTokenizer(IEnumerator tokenizer) + public static string ExhaustStringTokenizer(IEnumerator tokenizer) { StringBuilder buffer = new StringBuilder(); buffer.Append(' '); @@ -793,7 +791,7 @@ protected override void Dispose(bool disposing) } #endregion - private void InitIOSettings() { } + private static void InitIOSettings() { } /// /// Applies the MDL valence model to atoms using the explicit valence (bond @@ -803,7 +801,7 @@ private void InitIOSettings() { } /// /// the atom to apply the model to /// the explicit valence (bond order sum) - private void ApplyMDLValenceModel(IAtom atom, int explicitValence, int unpaired) + private static void ApplyMDLValenceModel(IAtom atom, int explicitValence, int unpaired) { if (atom.Valency != null) diff --git a/NCDK/IO/MDLV3000Writer.cs b/NCDK/IO/MDLV3000Writer.cs index 1b2fb419..d697039d 100644 --- a/NCDK/IO/MDLV3000Writer.cs +++ b/NCDK/IO/MDLV3000Writer.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -97,7 +98,7 @@ private static int NullAsZero(int? x) /// index map /// the object /// index or -1 if not found - private static int FindIdx(IDictionary idxs, T obj) + private static int FindIdx(IReadOnlyDictionary idxs, T obj) { if (!idxs.TryGetValue(obj, out int idx)) return -1; @@ -124,11 +125,11 @@ private void WriteHeader(IAtomContainer mol) // program input, internal registry number (R) if input through MDL // form. A blank line can be substituted for line 2. writer.WriteDirect(" CDK "); - writer.WriteDirect(DateTime.UtcNow.ToString("MMddyyHHmm")); + writer.WriteDirect(DateTime.UtcNow.ToString("MMddyyHHmm", DateTimeFormatInfo.InvariantInfo)); int dim = GetNumberOfDimensions(mol); if (dim != 0) { - writer.WriteDirect(dim.ToString()); + writer.WriteDirect(dim.ToString(NumberFormatInfo.InvariantInfo)); writer.WriteDirect('D'); } writer.WriteDirect('\n'); @@ -236,7 +237,7 @@ private void WriteAtomBlock(IAtomContainer mol, IAtom[] atoms, IDictionaryatom /// atomic number /// atom symbol - private string GetSymbol(IAtom atom, int elem) + private static string GetSymbol(IAtom atom, int elem) { if (atom is IPseudoAtom) return ((IPseudoAtom)atom).Label; @@ -343,13 +344,13 @@ private string GetSymbol(IAtom atom, int elem) /// index lookup /// low-level IO error /// inconsistent state etc - private void WriteBondBlock(IAtomContainer mol, IDictionary idxs) + private void WriteBondBlock(IAtomContainer mol, IReadOnlyDictionary idxs) { if (mol.Bonds.Count == 0) return; // collect multicenter Sgroups before output - var sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); var multicenterSgroups = new Dictionary(); if (sgroups != null) { @@ -366,8 +367,8 @@ private void WriteBondBlock(IAtomContainer mol, IDictionary id int bondIdx = 0; foreach (var bond in mol.Bonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; if (beg == null || end == null) throw new InvalidOperationException($"Bond {bondIdx} had one or more atoms."); int begIdx = FindIdx(idxs, beg); @@ -448,7 +449,7 @@ private void WriteBondBlock(IAtomContainer mol, IDictionary id /// molecule /// mapping that will be filled with the output index /// the output order of atoms - private IAtom[] PushHydrogensToBack(IAtomContainer mol, IDictionary atomToIdx) + private static IAtom[] PushHydrogensToBack(IAtomContainer mol, IDictionary atomToIdx) { Trace.Assert(atomToIdx.Count == 0); IAtom[] atoms = new IAtom[mol.Atoms.Count]; @@ -475,9 +476,9 @@ private IAtom[] PushHydrogensToBack(IAtomContainer mol, IDictionary /// molecule /// the sgroups - private IList GetSgroups(IAtomContainer mol) + private static IList GetSgroups(IAtomContainer mol) { - var sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); if (sgroups == null) sgroups = Array.Empty(); return sgroups; @@ -490,7 +491,8 @@ public int Compare(Sgroup o1, Sgroup o2) { // empty parents come first int cmp = -(o1.Parents.Count == 0).CompareTo(o2.Parents.Count == 0); - if (cmp != 0 || o1.Parents.Count == 0) return cmp; + if (cmp != 0 || o1.Parents.Count == 0) + return cmp; // non-empty parents, if one contains the other we have an ordering if (o1.Parents.Contains(o2)) return +1; @@ -501,7 +503,7 @@ public int Compare(Sgroup o1, Sgroup o2) } } - private int GetNumberOfDimensions(IAtomContainer mol) + private static int GetNumberOfDimensions(IAtomContainer mol) { foreach (IAtom atom in mol.Atoms) { @@ -520,7 +522,7 @@ private int GetNumberOfDimensions(IAtomContainer mol) /// index map for looking up atom and bond indexes /// low-level IO error /// unsupported format feature or invalid state - private void WriteSgroupBlock(IEnumerable sgroups, IDictionary idxs) + private void WriteSgroupBlock(IEnumerable sgroups, IReadOnlyDictionary idxs) { // Short of building a full dependency graph we write the parents // first, this sort is good for three levels of nesting. Not perfect @@ -540,7 +542,7 @@ private void WriteSgroupBlock(IEnumerable sgroups, IDictionary idxs = new Dictionary(); - IDictionary atomToStereo = new Dictionary(); + var idxs = new Dictionary(); + var atomToStereo = new Dictionary(); // work around specification ambiguities but reordering atom output // order, we also insert the index into a map for lookup - IAtom[] atoms = PushHydrogensToBack(mol, idxs); + var atoms = PushHydrogensToBack(mol, idxs); // bonds are in molecule order foreach (var bond in mol.Bonds) @@ -836,7 +838,7 @@ public V30LineWriter Write(double num) /// low-level IO error public V30LineWriter Write(int num) { - return Write(num.ToString()); + return Write(num.ToString(NumberFormatInfo.InvariantInfo)); } /// @@ -890,7 +892,7 @@ public V30LineWriter Write(char c) /// index map /// self-reference for chaining. /// low-level IO error - public V30LineWriter Write(IEnumerable chemObjects, IDictionary idxs) + public V30LineWriter Write(IEnumerable chemObjects, IReadOnlyDictionary idxs) { var chemObjectList = chemObjects.ToList(); this.Write(chemObjectList.Count); diff --git a/NCDK/IO/MDMoleculeConvention.cs b/NCDK/IO/MDMoleculeConvention.cs index ca9059ea..67c0bf50 100644 --- a/NCDK/IO/MDMoleculeConvention.cs +++ b/NCDK/IO/MDMoleculeConvention.cs @@ -24,6 +24,7 @@ using NCDK.LibIO.MD; using System; using System.Diagnostics; +using System.Globalization; using System.Xml.Linq; using static NCDK.LibIO.CML.CMLElement; @@ -103,23 +104,25 @@ public override void StartElement(CMLStack xpath, XElement element) if (element.Name == XName_CML_molecule) { // the copy the parsed content into a new MDMolecule - if (element.Attribute(Attribute_convention) != null && element.Attribute(Attribute_convention).Value.Equals("md:mdMolecule")) + if (element.Attribute(Attribute_convention) != null && string.Equals(element.Attribute(Attribute_convention).Value, "md:mdMolecule", StringComparison.Ordinal)) { base.StartElement(xpath, element); CurrentMolecule = new MDMolecule(CurrentMolecule); } else { - DICTREF = element.Attribute(Attribute_dictRef) != null ? element.Attribute(Attribute_dictRef).Value : ""; + DictRef = element.Attribute(Attribute_dictRef) != null ? element.Attribute(Attribute_dictRef).Value : ""; //If residue or chargeGroup, set up a new one - if (DICTREF.Equals("md:chargeGroup")) + switch (DictRef) { - currentChargeGroup = new ChargeGroup(); - } - else if (DICTREF.Equals("md:residue")) - { - currentResidue = new Residue(); - if (element.Attribute(Attribute_title) != null) currentResidue.Name = element.Attribute(Attribute_title).Value; + case "md:chargeGroup": + currentChargeGroup = new ChargeGroup(); + break; + case "md:residue": + currentResidue = new Residue(); + if (element.Attribute(Attribute_title) != null) + currentResidue.Name = element.Attribute(Attribute_title).Value; + break; } } } @@ -127,16 +130,17 @@ public override void StartElement(CMLStack xpath, XElement element) //We have a scalar element. Now check who it belongs to if (element.Name == XName_CML_scalar) { - DICTREF = element.Attribute(Attribute_dictRef).Value; + DictRef = element.Attribute(Attribute_dictRef).Value; //Switching Atom - if ("md:switchingAtom".Equals(DICTREF)) - { - //Set current atom as switching atom - currentChargeGroup.SetSwitchingAtom(CurrentAtom); - } - else + switch (DictRef) { - base.StartElement(xpath, element); + case "md:switchingAtom": + //Set current atom as switching atom + currentChargeGroup.SetSwitchingAtom(CurrentAtom); + break; + default: + base.StartElement(xpath, element); + break; } } else if (element.Name == XName_CML_atom) @@ -150,7 +154,7 @@ public override void StartElement(CMLStack xpath, XElement element) CurrentAtom = null; foreach (var nextAtom in CurrentMolecule.Atoms) { - if (nextAtom.Id.Equals(id)) + if (string.Equals(nextAtom.Id, id, StringComparison.Ordinal)) { CurrentAtom = nextAtom; } @@ -174,7 +178,7 @@ public override void StartElement(CMLStack xpath, XElement element) IAtom referencedAtom = null; foreach (var nextAtom in CurrentMolecule.Atoms) { - if (nextAtom.Id.Equals(id)) + if (string.Equals(nextAtom.Id, id, StringComparison.Ordinal)) { referencedAtom = nextAtom; } @@ -272,15 +276,15 @@ public override void EndElement(CMLStack xpath, XElement element) else if (element.Name == XName_CML_scalar) { //Residue number - if ("md:resNumber".Equals(DICTREF)) + if (string.Equals("md:resNumber", DictRef, StringComparison.Ordinal)) { - int myInt = int.Parse(element.Value); + int myInt = int.Parse(element.Value, NumberFormatInfo.InvariantInfo); currentResidue.SetNumber(myInt); } //ChargeGroup number - else if ("md:cgNumber".Equals(DICTREF)) + else if (string.Equals("md:cgNumber", DictRef, StringComparison.Ordinal)) { - int myInt = int.Parse(element.Value); + int myInt = int.Parse(element.Value, NumberFormatInfo.InvariantInfo); currentChargeGroup.SetNumber(myInt); } } diff --git a/NCDK/IO/MoSSOutputReader.cs b/NCDK/IO/MoSSOutputReader.cs index e9067896..cc5b5951 100644 --- a/NCDK/IO/MoSSOutputReader.cs +++ b/NCDK/IO/MoSSOutputReader.cs @@ -147,7 +147,7 @@ private IChemObjectSet ReadAtomContainerSet(IChemObjectSet parameters = new[] {"NO. OF FILLED LEVELS", "TOTAL ENERGY", "FINAL HEAT OF FORMATION", "IONIZATION POTENTIAL", "ELECTRONIC ENERGY", "CORE-CORE REPULSION", "MOLECULAR WEIGHT", "EHOMO", "ELUMO"}; - private static string[] units = { "", "EV", "KJ", "", "EV", "EV", "", "EV", "EV" }; - private static string eigenvalues = "EIGENVALUES"; - private static string filledLevels = "NO. OF FILLED LEVELS"; + private static readonly IReadOnlyList units = new[] { "", "EV", "KJ", "", "EV", "EV", "", "EV", "EV" }; + private const string eigenvalues = "EIGENVALUES"; + private const string filledLevels = "NO. OF FILLED LEVELS"; /// /// Constructs a new Mopac7reader that can read a molecule from a given . @@ -73,7 +75,7 @@ public Mopac7Reader(Stream input) // -1618.31024 EV ELECTRONIC ENERGY = -6569.42640 EV POINT GROUP: C1 // CORE-CORE REPULSION = 4951.11615 EV IONIZATION POTENTIAL = 10.76839 NO. // OF FILLED LEVELS = 23 MOLECULAR WEIGHT = 122.123 - + private static readonly string[] expected_columns = { "NO.", "ATOM", "X", "Y", "Z" }; public override T Read(T obj) { @@ -85,11 +87,12 @@ public override T Read(T obj) string line = input.ReadLine(); while (line != null) { - if (line.IndexOf("**** MAX. NUMBER OF ATOMS ALLOWED") > -1) throw new CDKException(line); - if (line.IndexOf("TO CONTINUE CALCULATION SPECIFY \"GEO-OK\"") > -1) throw new CDKException(line); - if ("CARTESIAN COORDINATES".Equals(line.Trim())) + if (line.IndexOf("**** MAX. NUMBER OF ATOMS ALLOWED", StringComparison.Ordinal) > -1) + throw new CDKException(line); + if (line.IndexOf("TO CONTINUE CALCULATION SPECIFY \"GEO-OK\"", StringComparison.Ordinal) > -1) + throw new CDKException(line); + if (string.Equals("CARTESIAN COORDINATES", line.Trim(), StringComparison.Ordinal)) { - IAtomContainer atomcontainer = ((IAtomContainer)obj); input.ReadLine(); //reads blank line line = input.ReadLine(); @@ -98,14 +101,14 @@ public override T Read(T obj) int okCols = 0; if (columns.Count == expected_columns.Length) for (int i = 0; i < expected_columns.Length; i++) - okCols += (columns[i].Equals(expected_columns[i])) ? 1 : 0; + okCols += (string.Equals(columns[i], expected_columns[i], StringComparison.Ordinal)) ? 1 : 0; - if (okCols < expected_columns.Length) continue; - //if (!" NO. ATOM X Y Z".Equals(line)) continue; + if (okCols < expected_columns.Length) + continue; input.ReadLine(); //reads blank line int atomIndex = 0; - while (line.Trim() != "") + while (line.Trim().Length != 0) { line = input.ReadLine(); var tokens = Strings.Tokenize(line); @@ -118,52 +121,42 @@ public override T Read(T obj) switch (token) { case 0: + atomIndex = int.Parse(tokenStr, NumberFormatInfo.InvariantInfo) - 1; + if (atomIndex < atomcontainer.Atoms.Count) { - atomIndex = int.Parse(tokenStr) - 1; - if (atomIndex < atomcontainer.Atoms.Count) - { - atom = atomcontainer.Atoms[atomIndex]; - } - else - atom = null; - break; + atom = atomcontainer.Atoms[atomIndex]; } + else + atom = null; + break; case 1: - { - if ((atom != null) && (!tokenStr.Equals(atom.Symbol))) atom = null; - break; - } + if ((atom != null) && (!string.Equals(tokenStr, atom.Symbol, StringComparison.Ordinal))) + atom = null; + break; case 2: - { - point3d[0] = double.Parse(tokenStr); - break; - } + point3d[0] = double.Parse(tokenStr, NumberFormatInfo.InvariantInfo); + break; case 3: - { - point3d[1] = double.Parse(tokenStr); - break; - } + point3d[1] = double.Parse(tokenStr, NumberFormatInfo.InvariantInfo); + break; case 4: - { - point3d[2] = double.Parse(tokenStr); - if (atom != null) atom.Point3D = new Vector3(point3d[0], point3d[1], point3d[2]); - break; - } - + point3d[2] = double.Parse(tokenStr, NumberFormatInfo.InvariantInfo); + if (atom != null) + atom.Point3D = new Vector3(point3d[0], point3d[1], point3d[2]); + break; } token++; if (atom == null) break; } - if ((atom == null) || ((atomIndex + 1) >= atomcontainer.Atoms.Count)) break; - + if ((atom == null) || ((atomIndex + 1) >= atomcontainer.Atoms.Count)) + break; } - } - else if (line.IndexOf(Mopac7Reader.eigenvalues) >= 0) + else if (line.IndexOf(Mopac7Reader.eigenvalues, StringComparison.Ordinal) >= 0) { line = input.ReadLine(); line = input.ReadLine(); - while (!line.Trim().Equals("")) + while (line.Trim().Length != 0) { eigenvalues.Append(line); line = input.ReadLine(); @@ -171,8 +164,8 @@ public override T Read(T obj) container.SetProperty(Mopac7Reader.eigenvalues, eigenvalues.ToString()); } else - for (int i = 0; i < parameters.Length; i++) - if (line.IndexOf(parameters[i]) >= 0) + for (int i = 0; i < parameters.Count; i++) + if (line.IndexOf(parameters[i], StringComparison.Ordinal) >= 0) { string value = line.Substring(line.LastIndexOf('=') + 1).Trim(); @@ -200,34 +193,35 @@ public override T Read(T obj) return default(T); } - private void CalcHomoLumo(IAtomContainer mol) + private static void CalcHomoLumo(IAtomContainer mol) { var eigenProp = mol.GetProperty(eigenvalues); if (eigenProp == null) return; //mol.GetProperties().Remove(eigenvalues); var filledLevelsProp = mol.GetProperty(filledLevels); //mol.GetProperties().Remove(filledLevels); - if (filledLevelsProp == null) return; + if (filledLevelsProp == null) + return; int nFilledLevels = 0; try { - nFilledLevels = int.Parse(filledLevelsProp.ToString()); + nFilledLevels = int.Parse(filledLevelsProp, NumberFormatInfo.InvariantInfo); } catch (FormatException) { return; } - var eigenVals = Strings.Tokenize(eigenProp.ToString()); + var eigenVals = Strings.Tokenize(eigenProp); int levelCounter = 0; foreach (var eigenVal in eigenVals) { - if (eigenVal.Trim() == "") + if (string.IsNullOrWhiteSpace(eigenVal)) continue; else try { // check if the value is an proper double: - double.Parse(eigenVal); + double.Parse(eigenVal, NumberFormatInfo.InvariantInfo); levelCounter++; if (levelCounter == nFilledLevels) { @@ -274,3 +268,4 @@ public override bool Accepts(Type type) public override IResourceFormat Format => MOPAC7Format.Instance; } } + diff --git a/NCDK/IO/Mopac7Writer.cs b/NCDK/IO/Mopac7Writer.cs index 4bfa9cc1..09b9fc77 100644 --- a/NCDK/IO/Mopac7Writer.cs +++ b/NCDK/IO/Mopac7Writer.cs @@ -28,6 +28,7 @@ using NCDK.Tools.Manipulator; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Runtime.CompilerServices; @@ -117,15 +118,15 @@ private void WriteAtom(IAtom atom, double xCoord, double yCoord, double zCoord, { writer.Write(atom.Symbol); writer.Write(BLANK); - writer.Write(xCoord.ToString("F4")); + writer.Write(xCoord.ToString("F4", NumberFormatInfo.InvariantInfo)); writer.Write(BLANK); writer.Write(optimize); writer.Write(BLANK); - writer.Write(yCoord.ToString("F4")); + writer.Write(yCoord.ToString("F4", NumberFormatInfo.InvariantInfo)); writer.Write(BLANK); writer.Write(optimize); writer.Write(BLANK); - writer.Write(zCoord.ToString("F4")); + writer.Write(zCoord.ToString("F4", NumberFormatInfo.InvariantInfo)); writer.Write(BLANK); writer.Write(optimize); writer.Write(BLANK); @@ -167,16 +168,16 @@ public override bool Accepts(Type type) private void InitIOSettings() { - optimize = Add(new BooleanIOSetting("Optimize", IOSetting.Importance.Medium, + optimize = Add(new BooleanIOSetting("Optimize", Importance.Medium, "Should the structure be optimized?", "true")); - mopacCommands = Add(new StringIOSetting("Commands", IOSetting.Importance.Low, + mopacCommands = Add(new StringIOSetting("Commands", Importance.Low, "What Mopac commands should be used (overwrites other choices)?", "PM3 NOINTER NOMM BONDS MULLIK PRECISE")); } private void CustomizeJob() { - FireIOSettingQuestion(optimize); + ProcessIOSettingQuestion(optimize); try { if (optimize.IsSet) @@ -192,7 +193,7 @@ private void CustomizeJob() { throw new ArgumentException(exception.Message); } - FireIOSettingQuestion(mopacCommands); + ProcessIOSettingQuestion(mopacCommands); } } } diff --git a/NCDK/IO/NCDKSourceCodeWriter.cs b/NCDK/IO/NCDKSourceCodeWriter.cs index 4fe810b1..2dd606fc 100644 --- a/NCDK/IO/NCDKSourceCodeWriter.cs +++ b/NCDK/IO/NCDKSourceCodeWriter.cs @@ -196,30 +196,29 @@ private void WriteBond(IBond bond) writer.Write('\n'); } - public DataFeatures SupportedDataFeatures => - DataFeatures.HAS_2D_COORDINATES | DataFeatures.HAS_3D_COORDINATES - | DataFeatures.HAS_GRAPH_REPRESENTATION | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public virtual DataFeatures SupportedDataFeatures => + DataFeatures.Has2DCoordinates | DataFeatures.Has3DCoordinates + | DataFeatures.HasGraphRepresentation | DataFeatures.HasAtomElementSymbol; - public DataFeatures RequiredDataFeatures => - DataFeatures.HAS_GRAPH_REPRESENTATION | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; + public virtual DataFeatures RequiredDataFeatures => + DataFeatures.HasGraphRepresentation | DataFeatures.HasAtomElementSymbol; private void InitIOSettings() { - write2DCoordinates = IOSettings.Add(new BooleanIOSetting("write2DCoordinates", IOSetting.Importance.Low, + write2DCoordinates = IOSettings.Add(new BooleanIOSetting("write2DCoordinates", Importance.Low, "Should 2D coordinates be added?", "true")); - - write3DCoordinates = IOSettings.Add(new BooleanIOSetting("write3DCoordinates", IOSetting.Importance.Low, + write3DCoordinates = IOSettings.Add(new BooleanIOSetting("write3DCoordinates", Importance.Low, "Should 3D coordinates be added?", "true")); - - builder = IOSettings.Add(new StringIOSetting("builder", IOSetting.Importance.Low, - "Which IChemObjectBuilder should be used?", "Default.ChemObjectBuilder")); + builder = IOSettings.Add(new StringIOSetting("builder", Importance.Low, + $"Which {nameof(IChemObjectBuilder)} should be used?", + "NCDK.Silent.ChemObjectBuilder")); } private void CustomizeJob() { - FireIOSettingQuestion(write2DCoordinates); - FireIOSettingQuestion(write3DCoordinates); - FireIOSettingQuestion(builder); + ProcessIOSettingQuestion(write2DCoordinates); + ProcessIOSettingQuestion(write3DCoordinates); + ProcessIOSettingQuestion(builder); } } } diff --git a/NCDK/IO/PCCompoundASNReader.cs b/NCDK/IO/PCCompoundASNReader.cs index 9415bf54..400d6cc5 100644 --- a/NCDK/IO/PCCompoundASNReader.cs +++ b/NCDK/IO/PCCompoundASNReader.cs @@ -150,25 +150,25 @@ private IChemFile ReadChemFile(IChemFile file) private void ProcessBlock(string line) { string command = GetCommand(line); - if (command.Equals("atoms")) + if (string.Equals(command, "atoms", StringComparison.Ordinal)) { // parse frame by frame Debug.WriteLine("ASN atoms found"); ProcessAtomBlock(); } - else if (command.Equals("bonds")) + else if (string.Equals(command, "bonds", StringComparison.Ordinal)) { // ok, that fine Debug.WriteLine("ASN bonds found"); ProcessBondBlock(); } - else if (command.Equals("props")) + else if (string.Equals(command, "props", StringComparison.Ordinal)) { // ok, that fine Debug.WriteLine("ASN props found"); ProcessPropsBlock(); } - else if (command.Equals("PC-Compound ::=")) + else if (string.Equals(command, "PC-Compound ::=", StringComparison.Ordinal)) { // ok, that fine Debug.WriteLine("ASN PC-Compound found"); @@ -207,26 +207,32 @@ private void ProcessPropsBlockBlock() URN urn = new URN(); while (line != null) { - if (line.IndexOf("urn") != -1) + if (line.Contains("urn")) { urn = ExtractURN(); } - else if (line.IndexOf("value") != -1) + else if (line.Contains("value")) { - Debug.WriteLine("Found a prop value line: " + line); - if (line.IndexOf(" sval") != -1) + Debug.WriteLine($"Found a prop value line: {line}"); + if (line.Contains(" sval")) { - Debug.WriteLine("Label: " + urn.Label); - Debug.WriteLine("Name: " + urn.Name); - if ("InChI".Equals(urn.Label)) + Debug.WriteLine($"Label: {urn.Label}"); + Debug.WriteLine($"Name: {urn.Name}"); + switch (urn.Label) { - string value = GetQuotedValue(line.Substring(line.IndexOf("value sval") + 10)); - molecule.SetProperty(CDKPropertyName.InChI, value); - } - else if ("SMILES".Equals(urn.Label) && "Canonical".Equals(urn.Name)) - { - string value = GetQuotedValue(line.Substring(line.IndexOf("value sval") + 10)); - molecule.SetProperty(CDKPropertyName.SMILES, value); + case "InChI": + { + string value = GetQuotedValue(line.Substring(line.IndexOf("value sval", StringComparison.Ordinal) + 10)); + molecule.SetProperty(CDKPropertyName.InChI, value); + } + break; + case "SMILES": + if ("Canonical".Equals(urn.Name, StringComparison.Ordinal)) + { + string value = GetQuotedValue(line.Substring(line.IndexOf("value sval", StringComparison.Ordinal) + 10)); + molecule.SetProperty(CDKPropertyName.SMILES, value); + } + break; } } } @@ -248,14 +254,11 @@ private URN ExtractURN() string line = input.ReadLine(); while (line != null) { - if (line.IndexOf("name") != -1) - { - urn.Name = GetQuotedValue(line.Substring(line.IndexOf("name") + 4)); - } - else if (line.IndexOf("label") != -1) - { - urn.Label = GetQuotedValue(line.Substring(line.IndexOf("label") + 4)); - } + int n; + if ((n = line.IndexOf("name", StringComparison.Ordinal)) != -1) + urn.Name = GetQuotedValue(line.Substring(n + 4)); + else if ((n = line.IndexOf("label", StringComparison.Ordinal)) != -1) + urn.Label = GetQuotedValue(line.Substring(n + 5)); else if (line.IndexOf('}') != -1 && line.IndexOf('\"') == -1) { // ok, don't return if it also has a " @@ -342,13 +345,13 @@ private void SetBondAtoms(int i, IAtom atom1, IAtom atom2) private void ProcessAtomBlockBlock(string line) { string command = GetCommand(line); - if (command.Equals("aid")) + if (string.Equals(command, "aid", StringComparison.Ordinal)) { // assume this is the first block in the atom block Debug.WriteLine("ASN atoms aid found"); ProcessAtomAIDs(); } - else if (command.Equals("element")) + else if (string.Equals(command, "element", StringComparison.Ordinal)) { // assume this is the first block in the atom block Debug.WriteLine("ASN atoms element found"); @@ -364,13 +367,13 @@ private void ProcessAtomBlockBlock(string line) private void ProcessBondBlockBlock(string line, NewBondInfo newBondInfo) { string command = GetCommand(line); - if (command.Equals("aid1")) + if (string.Equals(command, "aid1", StringComparison.Ordinal)) { // assume this is the first block in the atom block Debug.WriteLine("ASN bonds aid1 found"); ProcessBondAtomIDs(0, newBondInfo); } - else if (command.Equals("aid2")) + else if (string.Equals(command, "aid2", StringComparison.Ordinal)) { // assume this is the first block in the atom block Debug.WriteLine("ASN bonds aid2 found"); @@ -419,8 +422,8 @@ private void ProcessBondAtomIDs(int pos, NewBondInfo newBondInfo) } else { - // Debug.WriteLine("Found an atom ID: " + line); - // Debug.WriteLine(" index: " + atomIndex); + // Debug.WriteLine($"Found an atom ID: {line}"); + // Debug.WriteLine($" index: {atomIndex}"); // IBond bond = GetBond(bondIndex); //string id = GetValue(line); //IAtom atom = (IAtom)atomIDs[id]; @@ -462,7 +465,7 @@ private void ProcessAtomElements() else { // Debug.WriteLine("Found symbol: " + ToSymbol(GetValue(line))); - // Debug.WriteLine(" index: " + atomIndex); + // Debug.WriteLine($" index: {atomIndex}"); IAtom atom = GetAtom(atomIndex); atom.Symbol = ToSymbol(GetValue(line)); atomIndex++; @@ -471,9 +474,10 @@ private void ProcessAtomElements() } } - private string ToSymbol(string value) + private static string ToSymbol(string value) { - if (value.Length == 1) return value.ToUpperInvariant(); + if (value.Length == 1) + return value.ToUpperInvariant(); return value.Substring(0, 1).ToUpperInvariant() + value.Substring(1); } @@ -483,12 +487,12 @@ private void SkipBlock() int openBrackets = 0; while (line != null) { - // Debug.WriteLine("SkipBlock: line=" + line); + // Debug.WriteLine($"SkipBlock: line={line}"); if (line.IndexOf('{') != -1) { openBrackets++; } - // Debug.WriteLine(" #open brackets: " + openBrackets); + // Debug.WriteLine($" #open brackets: {openBrackets}"); if (line.IndexOf('}') != -1) { if (openBrackets == 0) return; @@ -498,7 +502,7 @@ private void SkipBlock() } } - private string GetCommand(string line) + private static string GetCommand(string line) { StringBuilder buffer = new StringBuilder(); int i = 0; @@ -519,7 +523,7 @@ private string GetCommand(string line) return foundBracket ? buffer.ToString().Trim() : null; } - private string GetValue(string line) + private static string GetValue(string line) { StringBuilder buffer = new StringBuilder(); int i = 0; @@ -550,7 +554,7 @@ private string GetQuotedValue(string line) { StringBuilder buffer = new StringBuilder(); int i = 0; - // Debug.WriteLine("QV line: " + line); + // Debug.WriteLine($"QV line: {line}"); bool startQuoteFound = false; while (line != null) { diff --git a/NCDK/IO/PDBReader.cs b/NCDK/IO/PDBReader.cs index 2d48a6de..10973c02 100644 --- a/NCDK/IO/PDBReader.cs +++ b/NCDK/IO/PDBReader.cs @@ -24,15 +24,16 @@ using NCDK.Common.Primitives; using NCDK.Config; -using NCDK.Default; using NCDK.Graphs.Rebond; using NCDK.IO.Formats; using NCDK.IO.Setting; using NCDK.Numerics; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -175,7 +176,7 @@ private IChemFile ReadChemFile(IChemFile oFile) do { cRead = oInput.ReadLine(); - Debug.WriteLine("Read line: ", cRead); + Debug.WriteLine($"Read line: {cRead}"); if (cRead != null) { lineLength = cRead.Length; @@ -230,7 +231,7 @@ private IChemFile ReadChemFile(IChemFile oFile) string strandName = oAtom.ChainID; if (strandName == null || strandName.Length == 0) { - strandName = chain.ToString(); + strandName = chain.ToString(NumberFormatInfo.InvariantInfo); } oStrand = oBP.GetStrand(strandName); if (oStrand == null) @@ -238,12 +239,12 @@ private IChemFile ReadChemFile(IChemFile oFile) oStrand = new PDBStrand { StrandName = strandName, - Id = chain.ToString() + Id = chain.ToString(NumberFormatInfo.InvariantInfo) }; } // search for an existing monomer or create a new one. - oMonomer = oBP.GetMonomer(cResidue.ToString(), chain.ToString()); + oMonomer = oBP.GetMonomer(cResidue.ToString(), chain.ToString(NumberFormatInfo.InvariantInfo)); if (oMonomer == null) { PDBMonomer monomer = new PDBMonomer @@ -272,7 +273,7 @@ private IChemFile ReadChemFile(IChemFile oFile) if (isDup) Trace.TraceWarning("Duplicate serial ID found for atom: ", oAtom); } - Debug.WriteLine("Added ATOM: ", oAtom); + Debug.WriteLine($"Added ATOM: {oAtom}"); // As HETATMs cannot be considered to either belong to a certain monomer or strand, // they are dealt with seperately. @@ -309,7 +310,7 @@ private IChemFile ReadChemFile(IChemFile oFile) chain++; oStrand = new PDBStrand { - StrandName = chain.ToString() + StrandName = chain.ToString(NumberFormatInfo.InvariantInfo) }; Debug.WriteLine("Added new STRAND"); #endregion @@ -412,16 +413,15 @@ private IChemFile ReadChemFile(IChemFile oFile) case "CONECT": { #region - // *********************************************************** // Read connectivity information from CONECT records. Only // covalent bonds are dealt with. Perhaps salt bridges // should be dealt with in the same way..? if (!readConnect.IsSet) break; - cRead.Trim(); + cRead = cRead.Trim(); if (cRead.Length < 16) { - Debug.WriteLine("Skipping unexpected empty CONECT line! : ", cRead); + Debug.WriteLine($"Skipping unexpected empty CONECT line! : {cRead}"); } else { @@ -436,7 +436,7 @@ private IChemFile ReadChemFile(IChemFile oFile) { try { - atomFromNumber = int.Parse(part); + atomFromNumber = int.Parse(part, NumberFormatInfo.InvariantInfo); } catch (FormatException) { @@ -446,7 +446,7 @@ private IChemFile ReadChemFile(IChemFile oFile) { try { - atomToNumber = int.Parse(part); + atomToNumber = int.Parse(part, NumberFormatInfo.InvariantInfo); } catch (FormatException) { @@ -461,7 +461,6 @@ private IChemFile ReadChemFile(IChemFile oFile) lineIndex += 5; } } - // ********************************************************** #endregion } break; @@ -475,10 +474,10 @@ private IChemFile ReadChemFile(IChemFile oFile) { StructureType = PDBStructure.Helix, StartChainID = cRead[19], - StartSequenceNumber = int.Parse(cRead.Substring(21, 4).Trim()), + StartSequenceNumber = int.Parse(cRead.Substring(21, 4).Trim(), NumberFormatInfo.InvariantInfo), StartInsertionCode = cRead[25], EndChainID = cRead[31], - EndSequenceNumber = int.Parse(cRead.Substring(33, 4).Trim()), + EndSequenceNumber = int.Parse(cRead.Substring(33, 4).Trim(), NumberFormatInfo.InvariantInfo), EndInsertionCode = cRead[37] }; oBP.Add(structure); @@ -492,10 +491,10 @@ private IChemFile ReadChemFile(IChemFile oFile) { StructureType = PDBStructure.Sheet, StartChainID = cRead[21], - StartSequenceNumber = int.Parse(cRead.Substring(22, 4).Trim()), + StartSequenceNumber = int.Parse(cRead.Substring(22, 4).Trim(), NumberFormatInfo.InvariantInfo), StartInsertionCode = cRead[26], EndChainID = cRead[32], - EndSequenceNumber = int.Parse(cRead.Substring(33, 4).Trim()), + EndSequenceNumber = int.Parse(cRead.Substring(33, 4).Trim(), NumberFormatInfo.InvariantInfo), EndInsertionCode = cRead[37] }; oBP.Add(structure); @@ -509,10 +508,10 @@ private IChemFile ReadChemFile(IChemFile oFile) { StructureType = PDBStructure.Turn, StartChainID = cRead[19], - StartSequenceNumber = int.Parse(cRead.Substring(20, 4).Trim()), + StartSequenceNumber = int.Parse(cRead.Substring(20, 4).Trim(), NumberFormatInfo.InvariantInfo), StartInsertionCode = cRead[24], EndChainID = cRead[30], - EndSequenceNumber = int.Parse(cRead.Substring(31, 4).Trim()), + EndSequenceNumber = int.Parse(cRead.Substring(31, 4).Trim(), NumberFormatInfo.InvariantInfo), EndInsertionCode = cRead[35] }; oBP.Add(structure); @@ -533,7 +532,7 @@ private IChemFile ReadChemFile(IChemFile oFile) Trace.TraceError(cRead); Trace.TraceError("01234567890123456789012345678901234567890123456789012345678901234567890123456789"); Trace.TraceError(" 1 2 3 4 5 6 7 "); - Trace.TraceError(" error: " + e.Message); + Trace.TraceError($" error: {e.Message}"); Debug.WriteLine(e); Console.Error.WriteLine(e.StackTrace); } @@ -581,14 +580,13 @@ private void AddBond(IAtomContainer molecule, int bondAtomNo, int bondedAtomNo) molecule.Bonds.Add(bond); } - private bool CreateBondsWithRebondTool(IAtomContainer molecule) + private static bool CreateBondsWithRebondTool(IAtomContainer molecule) { RebondTool tool = new RebondTool(2.0, 0.5, 0.5); try { - // configure atoms - AtomTypeFactory factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", - molecule.Builder); + // configure atoms + AtomTypeFactory factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", molecule.Builder); foreach (var atom in molecule.Atoms) { try @@ -615,7 +613,7 @@ private bool CreateBondsWithRebondTool(IAtomContainer molecule) } catch (Exception e) { - Trace.TraceError("Could not rebond the polymer: " + e.Message); + Trace.TraceError($"Could not rebond the polymer: {e.Message}"); Debug.WriteLine(e); } return true; @@ -625,16 +623,18 @@ private static bool IsUpper(char c) { return c >= 'A' && c <= 'Z'; } + private static bool IsLower(char c) { return c >= 'a' && c <= 'z'; } + private static bool IsDigit(char c) { return c >= '0' && c <= '9'; } - private string ParseAtomSymbol(string str) + private static string ParseAtomSymbol(string str) { if (string.IsNullOrEmpty(str)) return null; @@ -725,16 +725,16 @@ private PDBAtom ReadAtom(string cLine, int lineLength) throw new InvalidDataException("PDBReader error during ReadAtom(): line too short"); } - bool isHetatm = cLine.Substring(0, 6).Equals("HETATM"); + bool isHetatm = cLine.StartsWith("HETATM", StringComparison.Ordinal); string atomName = cLine.Substring(12, 4).Trim(); string resName = cLine.Substring(17, 3).Trim(); string symbol = ParseAtomSymbol(cLine); if (symbol == null) - HandleError("Cannot parse symbol from " + atomName); + HandleError($"Cannot parse symbol from {atomName}"); - PDBAtom oAtom = new PDBAtom(symbol, new Vector3(double.Parse(cLine.Substring(30, 8)), - double.Parse(cLine.Substring(38, 8)), double.Parse(cLine.Substring(46, 8)))); + PDBAtom oAtom = new PDBAtom(symbol, new Vector3(double.Parse(cLine.Substring(30, 8), NumberFormatInfo.InvariantInfo), + double.Parse(cLine.Substring(38, 8), NumberFormatInfo.InvariantInfo), double.Parse(cLine.Substring(46, 8), NumberFormatInfo.InvariantInfo))); if (useHetDictionary.IsSet && isHetatm) { string cdkType = TypeHetatm(resName, atomName); @@ -753,7 +753,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) } oAtom.Record = cLine; - oAtom.Serial = int.Parse(cLine.Substring(6, 5).Trim()); + oAtom.Serial = int.Parse(cLine.Substring(6, 5).Trim(), NumberFormatInfo.InvariantInfo); oAtom.Name = atomName.Trim(); oAtom.AltLoc = cLine.Substring(16, 1).Trim(); oAtom.ResName = resName; @@ -773,7 +773,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) string frag = cLine.Substring(54, Math.Min(lineLength - 54, 6)).Trim(); if (frag.Length > 0) { - oAtom.Occupancy = double.Parse(frag); + oAtom.Occupancy = double.Parse(frag, NumberFormatInfo.InvariantInfo); } } if (lineLength >= 65) @@ -781,7 +781,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) string frag = cLine.Substring(60, Math.Min(lineLength - 60, 6)).Trim(); if (frag.Length > 0) { - oAtom.TempFactor = double.Parse(frag); + oAtom.TempFactor = double.Parse(frag, NumberFormatInfo.InvariantInfo); } } if (lineLength >= 75) @@ -809,11 +809,11 @@ private PDBAtom ReadAtom(string cLine, int lineLength) { var aa = frag.ToCharArray(); Array.Reverse(aa); - oAtom.Charge = double.Parse(new string(aa)); + oAtom.Charge = double.Parse(new string(aa), NumberFormatInfo.InvariantInfo); } else { - oAtom.Charge = double.Parse(frag); + oAtom.Charge = double.Parse(frag, NumberFormatInfo.InvariantInfo); } } } @@ -824,7 +824,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) // special treatment. string oxt = cLine.Substring(13, 3).Trim(); - if (oxt.Equals("OXT")) + if (string.Equals(oxt, "OXT", StringComparison.Ordinal)) { oAtom.Oxt = true; } @@ -842,8 +842,7 @@ private string TypeHetatm(string resName, string atomName) if (hetDictionary == null) { ReadHetDictionary(); - cdkAtomTypeFactory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", - Default.ChemObjectBuilder.Instance); + cdkAtomTypeFactory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", ChemObjectBuilder.Instance); } string key = resName + "." + atomName; if (hetDictionary.ContainsKey(key)) @@ -867,7 +866,7 @@ private void ReadHetDictionary() if (colonIndex == -1) continue; string typeKey = line.Substring(0, colonIndex); string typeValue = line.Substring(colonIndex + 1); - if (typeValue.Equals("null")) + if (string.Equals(typeValue, "null", StringComparison.Ordinal)) { hetDictionary[typeKey] = null; } @@ -906,11 +905,11 @@ protected override void Dispose(bool disposing) private void InitIOSettings() { - useRebondTool = IOSettings.Add(new BooleanIOSetting("UseRebondTool", IOSetting.Importance.Low, + useRebondTool = IOSettings.Add(new BooleanIOSetting("UseRebondTool", Importance.Low, "Should the PDBReader deduce bonding patterns?", "false")); - readConnect = IOSettings.Add(new BooleanIOSetting("ReadConnectSection", IOSetting.Importance.Low, + readConnect = IOSettings.Add(new BooleanIOSetting("ReadConnectSection", Importance.Low, "Should the CONECT be read?", "true")); - useHetDictionary = IOSettings.Add(new BooleanIOSetting("UseHetDictionary", IOSetting.Importance.Low, + useHetDictionary = IOSettings.Add(new BooleanIOSetting("UseHetDictionary", Importance.Low, "Should the PDBReader use the HETATM dictionary for atom types?", "false")); } @@ -918,7 +917,7 @@ public void CustomizeJob() { foreach (var setting in IOSettings.Settings) { - FireIOSettingQuestion(setting); + ProcessIOSettingQuestion(setting); } } } diff --git a/NCDK/IO/PDBWriter.cs b/NCDK/IO/PDBWriter.cs index 5c8ec9a5..2f0949ed 100644 --- a/NCDK/IO/PDBWriter.cs +++ b/NCDK/IO/PDBWriter.cs @@ -24,6 +24,7 @@ using NCDK.Numerics; using NCDK.Tools.Manipulator; using System; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -40,10 +41,10 @@ namespace NCDK.IO // @cdk.githash public class PDBWriter : DefaultChemObjectWriter { - public static string F_SERIAL_FORMAT(int serial) => serial.ToString().PadLeft(5); - public static string F_ATOM_NAME_FORMAT(string atomName) => atomName.PadRight(5); - public static string F_POSITION_FORMAT(double f) => f.ToString("F3").PadLeft(8); - public static string F_RESIDUE_FORMAT(string residue) => residue; + private static string F_SERIAL_FORMAT(int serial) => serial.ToString(NumberFormatInfo.InvariantInfo).PadLeft(5); + private static string F_ATOM_NAME_FORMAT(string atomName) => atomName.PadRight(5); + private static string F_POSITION_FORMAT(double f) => f.ToString("F3", NumberFormatInfo.InvariantInfo).PadLeft(8); + private static string F_RESIDUE_FORMAT(string residue) => residue; private BooleanIOSetting writeAsHET; private BooleanIOSetting useElementSymbolAsAtomName; @@ -60,16 +61,16 @@ public class PDBWriter : DefaultChemObjectWriter public PDBWriter(TextWriter output) { writer = output; - writeAsHET = IOSettings.Add(new BooleanIOSetting("WriteAsHET", IOSetting.Importance.Low, - "Should the output file use HETATM", "false")); - useElementSymbolAsAtomName = IOSettings.Add(new BooleanIOSetting("UseElementSymbolAsAtomName", - IOSetting.Importance.Low, "Should the element symbol be written as the atom name", "false")); - writeCONECTRecords = IOSettings.Add(new BooleanIOSetting("WriteCONECT", IOSetting.Importance.Low, - "Should the bonds be written as CONECT records?", "true")); - writeTERRecord = IOSettings.Add(new BooleanIOSetting("WriteTER", IOSetting.Importance.Low, - "Should a TER record be put at the end of the atoms?", "false")); - writeENDRecord = IOSettings.Add(new BooleanIOSetting("WriteEND", IOSetting.Importance.Low, - "Should an END record be put at the end of the file?", "true")); + writeAsHET = IOSettings.Add(new BooleanIOSetting("WriteAsHET", Importance.Low, + "Should the output file use HETATM", "false")); + useElementSymbolAsAtomName = IOSettings.Add(new BooleanIOSetting("UseElementSymbolAsAtomName", Importance.Low, + "Should the element symbol be written as the atom name", "false")); + writeCONECTRecords = IOSettings.Add(new BooleanIOSetting("WriteCONECT", Importance.Low, + "Should the bonds be written as CONECT records?", "true")); + writeTERRecord = IOSettings.Add(new BooleanIOSetting("WriteTER", Importance.Low, + "Should a TER record be put at the end of the atoms?", "false")); + writeENDRecord = IOSettings.Add(new BooleanIOSetting("WriteEND", Importance.Low, + "Should an END record be put at the end of the file?", "true")); } public PDBWriter(Stream output) @@ -139,7 +140,7 @@ public void WriteMolecule(IAtomContainer molecule) string hetatmRecordName = (writeAsHET.IsSet) ? "HETATM" : "ATOM "; string id = molecule.Id; - string residueName = (id == null || id.Equals("")) ? "MOL" : id; + string residueName = string.IsNullOrEmpty(id) ? "MOL" : id; string terRecordName = "TER"; // Loop through the atoms and write them out: @@ -161,7 +162,7 @@ public void WriteMolecule(IAtomContainer molecule) } else { - if (atom.Id == null || atom.Id.Equals("")) + if (string.IsNullOrEmpty(atom.Id)) { name = atom.Symbol; } @@ -256,8 +257,8 @@ private void WriteHeader() writer.Write('\n'); } - private static string F_LENGTH_FORMAT(double length) => length.ToString("F3").PadLeft(8); //"%4.3f"; - private static string F_ANGLE_FORMAT(double angle) => angle.ToString("F3").PadLeft(7); //"%3.3f"; + private static string F_LENGTH_FORMAT(double length) => length.ToString("F3", NumberFormatInfo.InvariantInfo).PadLeft(8); //"%4.3f"; + private static string F_ANGLE_FORMAT(double angle) => angle.ToString("F3", NumberFormatInfo.InvariantInfo).PadLeft(7); //"%3.3f"; public void WriteCrystal(ICrystal crystal) { @@ -278,7 +279,7 @@ public void WriteCrystal(ICrystal crystal) // before saving the atoms, we need to create cartesian coordinates foreach (var atom in crystal.Atoms) { - // Debug.WriteLine("PDBWriter: atom -> " + atom); + // Debug.WriteLine($"PDBWriter: atom -> {atom}"); // if it got 3D coordinates, use that. If not, try fractional coordinates if (atom.Point3D == null && atom.FractionalPoint3D != null) { diff --git a/NCDK/IO/PMPReader.cs b/NCDK/IO/PMPReader.cs index 63f2be42..17b86013 100644 --- a/NCDK/IO/PMPReader.cs +++ b/NCDK/IO/PMPReader.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text.RegularExpressions; @@ -54,13 +55,13 @@ public class PMPReader : DefaultChemObjectReader private IAtomContainer modelStructure; private IChemObject chemObject; /* Keep an index of PMP id -> AtomCountainer id */ - private IDictionary atomids = new Dictionary(); - private IDictionary atomGivenIds = new Dictionary(); - private IDictionary atomZOrders = new Dictionary(); - private IDictionary bondids = new Dictionary(); - private IDictionary bondAtomOnes = new Dictionary(); - private IDictionary bondAtomTwos = new Dictionary(); - private IDictionary bondOrders = new Dictionary(); + private readonly Dictionary atomids = new Dictionary(); + private readonly Dictionary atomGivenIds = new Dictionary(); + private readonly Dictionary atomZOrders = new Dictionary(); + private Dictionary bondids = new Dictionary(); + private Dictionary bondAtomOnes = new Dictionary(); + private Dictionary bondAtomTwos = new Dictionary(); + private Dictionary bondOrders = new Dictionary(); /* Often used patterns */ Regex objHeader; @@ -155,7 +156,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) if (line.StartsWith("%%Version Number", StringComparison.Ordinal)) { string version = ReadLine().Trim(); - if (!version.Equals("3.00")) + if (!string.Equals(version, "3.00", StringComparison.Ordinal)) { Trace.TraceError("The PMPReader only supports PMP files with version 3.00"); return null; @@ -175,10 +176,10 @@ private IChemFile ReadChemFile(IChemFile chemFile) { string obj = objHeaderMatcher.Groups[2].Value; ConstructObject(chemFile.Builder, obj); - int id = int.Parse(objHeaderMatcher.Groups[1].Value); + int id = int.Parse(objHeaderMatcher.Groups[1].Value, NumberFormatInfo.InvariantInfo); // Debug.WriteLine(object + " id: " + id); line = ReadLine(); - while (line != null && !(line.Trim().Equals(")"))) + while (line != null && !(string.Equals(line.Trim(), ")", StringComparison.Ordinal))) { // parse object command (or new object header) var objCommandMatcher = objCommand.Match(line); @@ -187,7 +188,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) { // ok, forget about nesting and hope for the best obj = objHeaderMatcher.Groups[2].Value; - id = int.Parse(objHeaderMatcher.Groups[1].Value); + id = int.Parse(objHeaderMatcher.Groups[1].Value, NumberFormatInfo.InvariantInfo); ConstructObject(chemFile.Builder, obj); } else if (objCommandMatcher.Success) @@ -207,18 +208,14 @@ private IChemFile ReadChemFile(IChemFile chemFile) if (chemObject is IAtom) { atomids[id] = modelStructure.Atoms.Count; - atomZOrders[int.Parse(chemObject.GetProperty(PMP_ZORDER))] = id; - atomGivenIds[int.Parse(chemObject.GetProperty(PMP_ID))] = id; + atomZOrders[int.Parse(chemObject.GetProperty(PMP_ZORDER), NumberFormatInfo.InvariantInfo)] = id; + atomGivenIds[int.Parse(chemObject.GetProperty(PMP_ID), NumberFormatInfo.InvariantInfo)] = id; modelStructure.Atoms.Add((IAtom)chemObject); - // } else if (chemObject is IBond) { - // bondids[new int(id)] = new int(molecule.Atoms.Count); - // molecule.Bonds.Add((IBond)chemObject); } else { Trace.TraceError("chemObject is not initialized or of bad class type"); } - // Debug.WriteLine(molecule.ToString()); } line = ReadLine(); } @@ -228,19 +225,17 @@ private IChemFile ReadChemFile(IChemFile chemFile) // define bonds *before* the involved atoms :( // the next lines dump the cache into the atom container - // bondids[new int(id)] = new int(molecule.Atoms.Count); - // molecule.Bonds.Add((IBond)chemObject); int bondsFound = bondids.Count; - Debug.WriteLine("Found #bonds: ", bondsFound); - Debug.WriteLine("#atom ones: ", bondAtomOnes.Count); - Debug.WriteLine("#atom twos: ", bondAtomTwos.Count); - Debug.WriteLine("#orders: ", bondOrders.Count); + Debug.WriteLine($"Found #bonds: {bondsFound}"); + Debug.WriteLine($"#atom ones: {bondAtomOnes.Count}"); + Debug.WriteLine($"#atom twos: {bondAtomTwos.Count}"); + Debug.WriteLine($"#orders: {bondOrders.Count}"); foreach (var index in bondids.Keys) { if (!bondOrders.TryGetValue(index, out double order)) order = 1; - Debug.WriteLine("index: ", index); - Debug.WriteLine("ones: ", bondAtomOnes[index]); + Debug.WriteLine($"index: {index}"); + Debug.WriteLine($"ones: {bondAtomOnes[index]}"); IAtom atom1 = modelStructure.Atoms[atomids[bondAtomOnes[index]]]; IAtom atom2 = modelStructure.Atoms[atomids[bondAtomTwos[index]]]; IBond bond = modelStructure.Builder.NewBond(atom1, atom2); @@ -286,7 +281,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) if (energyFragment != 0.0 && energyTotal != 0.0) { Z = (int)Math.Round(energyTotal / energyFragment); - Debug.WriteLine("Z derived from energies: ", Z); + Debug.WriteLine($"Z derived from energies: {Z}"); } // add atomC as atoms to crystal int expatoms = modelStructure.Atoms.Count; @@ -298,7 +293,7 @@ private IChemFile ReadChemFile(IChemFile chemFile) line = ReadLine(); IAtom a = clone.Builder.NewAtom(); var st = Strings.Tokenize(line, ' '); - a.Point3D = new Vector3(double.Parse(st[0]), double.Parse(st[1]), double.Parse(st[2])); + a.Point3D = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo)); a.CovalentRadius = 0.6; IAtom modelAtom = modelStructure.Atoms[atomids[atomGivenIds[i + 1]]]; a.Symbol = modelAtom.Symbol; @@ -311,32 +306,32 @@ private IChemFile ReadChemFile(IChemFile chemFile) else if (line.StartsWith("%%E/Frag", StringComparison.Ordinal)) { line = ReadLine().Trim(); - energyFragment = double.Parse(line); + energyFragment = double.Parse(line, NumberFormatInfo.InvariantInfo); } else if (line.StartsWith("%%Tot E", StringComparison.Ordinal)) { line = ReadLine().Trim(); - energyTotal = double.Parse(line); + energyTotal = double.Parse(line, NumberFormatInfo.InvariantInfo); } else if (line.StartsWith("%%Lat Vects", StringComparison.Ordinal)) { line = ReadLine(); IList st; st = Strings.Tokenize(line, ' '); - crystal.A = new Vector3(double.Parse(st[0]), double.Parse(st[1]), double.Parse(st[2])); + crystal.A = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo)); line = ReadLine(); st = Strings.Tokenize(line, ' '); - crystal.B = new Vector3(double.Parse(st[0]), double.Parse(st[1]), double.Parse(st[2])); + crystal.B = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo)); line = ReadLine(); st = Strings.Tokenize(line, ' '); - crystal.C = new Vector3(double.Parse(st[0]), double.Parse(st[1]), double.Parse(st[2])); + crystal.C = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo)); } else if (line.StartsWith("%%Space Group", StringComparison.Ordinal)) { line = ReadLine().Trim(); // standardize space group name. See Crystal.SetSpaceGroup() - if ("P 21 21 21 (1)".Equals(line)) + if (string.Equals("P 21 21 21 (1)", line, StringComparison.Ordinal)) { crystal.SpaceGroup = "P 2_1 2_1 2_1"; } @@ -384,18 +379,18 @@ private IChemFile ReadChemFile(IChemFile chemFile) private void ProcessModelCommand(string obj, string command, string format, string field) { Debug.WriteLine(obj + "->" + command + " (" + format + "): " + field); - if ("Model".Equals(obj)) + if (string.Equals("Model", obj, StringComparison.Ordinal)) { Trace.TraceWarning("Unkown PMP Model command: " + command); } - else if ("Atom".Equals(obj)) + else if (string.Equals("Atom", obj, StringComparison.Ordinal)) { - if ("ACL".Equals(command)) + if (string.Equals("ACL", command, StringComparison.Ordinal)) { var atomTypeMatcher = atomTypePattern.Match(field); if (atomTypeMatcher.Success) { - int atomicnum = int.Parse(atomTypeMatcher.Groups[1].Value); + int atomicnum = int.Parse(atomTypeMatcher.Groups[1].Value, NumberFormatInfo.InvariantInfo); string type = atomTypeMatcher.Groups[2].Value; ((IAtom)chemObject).AtomicNumber = atomicnum; ((IAtom)chemObject).Symbol = type; @@ -405,11 +400,11 @@ private void ProcessModelCommand(string obj, string command, string format, stri Trace.TraceError("Incorrectly formated field value: " + field + "."); } } - else if ("Charge".Equals(command)) + else if (string.Equals("Charge", command, StringComparison.Ordinal)) { try { - double charge = double.Parse(field); + double charge = double.Parse(field, NumberFormatInfo.InvariantInfo); ((IAtom)chemObject).Charge = charge; } catch (FormatException) @@ -417,24 +412,24 @@ private void ProcessModelCommand(string obj, string command, string format, stri Trace.TraceError("Incorrectly formated float field: " + field + "."); } } - else if ("CMAPPINGS".Equals(command)) + else if (string.Equals("CMAPPINGS", command, StringComparison.Ordinal)) { } - else if ("FFType".Equals(command)) + else if (string.Equals("FFType", command, StringComparison.Ordinal)) { } - else if ("Id".Equals(command)) + else if (string.Equals("Id", command, StringComparison.Ordinal)) { // ok, should take this into account too chemObject.SetProperty(PMP_ID, field); } - else if ("Mass".Equals(command)) + else if (string.Equals("Mass", command, StringComparison.Ordinal)) { } - else if ("XYZ".Equals(command)) + else if (string.Equals("XYZ", command, StringComparison.Ordinal)) { } - else if ("ZOrder".Equals(command)) + else if (string.Equals("ZOrder", command, StringComparison.Ordinal)) { // ok, should take this into account too chemObject.SetProperty(PMP_ZORDER, field); @@ -444,49 +439,44 @@ private void ProcessModelCommand(string obj, string command, string format, stri Trace.TraceWarning("Unkown PMP Atom command: " + command); } } - else if ("Bond".Equals(obj)) + else if (string.Equals("Bond", obj, StringComparison.Ordinal)) { - if ("Atom1".Equals(command)) + if (string.Equals("Atom1", command, StringComparison.Ordinal)) { - int atomid = int.Parse(field); + int atomid = int.Parse(field, NumberFormatInfo.InvariantInfo); // this assumes that the atoms involved in this bond are // already added, which seems the case in the PMP files bondAtomOnes[bondCounter] = atomid; - // IAtom a = molecule.Atoms[realatomid]; - // ((IBond)chemObject).SetAtomAt(a, 0); } - else if ("Atom2".Equals(command)) + else if (string.Equals("Atom2", command, StringComparison.Ordinal)) { - int atomid = int.Parse(field); + int atomid = int.Parse(field, NumberFormatInfo.InvariantInfo); // this assumes that the atoms involved in this bond are // already added, which seems the case in the PMP files - Debug.WriteLine("atomids: " + atomids); - Debug.WriteLine("atomid: " + atomid); + Debug.WriteLine($"atomids: {atomids}"); + Debug.WriteLine($"atomid: {atomid}"); bondAtomTwos[bondCounter] = atomid; - // IAtom a = molecule.Atoms[realatomid]; - // ((IBond)chemObject).SetAtomAt(a, 1); } - else if ("Order".Equals(command)) + else if (string.Equals("Order", command, StringComparison.Ordinal)) { - double order = double.Parse(field); + double order = double.Parse(field, NumberFormatInfo.InvariantInfo); bondOrders[bondCounter] = order; - // ((IBond)chemObject).Order = order; } - else if ("Id".Equals(command)) + else if (string.Equals("Id", command, StringComparison.Ordinal)) { - int bondid = int.Parse(field); + int bondid = int.Parse(field, NumberFormatInfo.InvariantInfo); bondids[bondCounter] = bondid; } - else if ("Label".Equals(command)) + else if (string.Equals("Label", command, StringComparison.Ordinal)) { } - else if ("3DGridOrigin".Equals(command)) + else if (string.Equals("3DGridOrigin", command, StringComparison.Ordinal)) { } - else if ("3DGridMatrix".Equals(command)) + else if (string.Equals("3DGridMatrix", command, StringComparison.Ordinal)) { } - else if ("3DGridDivision".Equals(command)) + else if (string.Equals("3DGridDivision", command, StringComparison.Ordinal)) { } else @@ -502,22 +492,22 @@ private void ProcessModelCommand(string obj, string command, string format, stri private void ConstructObject(IChemObjectBuilder builder, string obj) { - if ("Atom".Equals(obj)) + if (string.Equals("Atom", obj, StringComparison.Ordinal)) { chemObject = builder.NewAtom("C"); } - else if ("Bond".Equals(obj)) + else if (string.Equals("Bond", obj, StringComparison.Ordinal)) { bondCounter++; chemObject = builder.NewBond(); } - else if ("Model".Equals(obj)) + else if (string.Equals("Model", obj, StringComparison.Ordinal)) { modelStructure = builder.NewAtomContainer(); } else { - Trace.TraceError("Cannot construct PMP object type: " + obj); + Trace.TraceError($"Cannot construct PMP object type: {obj}"); } } diff --git a/NCDK/IO/PubChemXml/PubChemXMLHelper.cs b/NCDK/IO/PubChemXml/PubChemXMLHelper.cs index 5999e3c3..8a3be565 100644 --- a/NCDK/IO/PubChemXml/PubChemXMLHelper.cs +++ b/NCDK/IO/PubChemXml/PubChemXMLHelper.cs @@ -25,6 +25,7 @@ using NCDK.Config; using NCDK.Numerics; using System.Collections.Generic; +using System.Globalization; using System.Xml.Linq; namespace NCDK.IO.PubChemXml @@ -36,7 +37,7 @@ namespace NCDK.IO.PubChemXml // @cdk.githash // @author Egon Willighagen // @cdk.created 2008-05-05 - public class PubChemXMLHelper + internal class PubChemXMLHelper { private IChemObjectBuilder builder; private IsotopeFactory factory; @@ -49,7 +50,7 @@ public class PubChemXMLHelper public PubChemXMLHelper(IChemObjectBuilder builder) { this.builder = builder; - factory = Isotopes.Instance; + factory = BODRIsotopeFactory.Instance; } // general elements @@ -192,7 +193,7 @@ public IChemModel ParseSubstance(XElement parser) return model; } - public string GetSID(XElement parser) + public static string GetSID(XElement parser) { string sid = "unknown"; if (!parser.Name.Equals(Name_EL_PCSUBSTANCE_SID)) @@ -207,7 +208,7 @@ public string GetSID(XElement parser) return sid; } - public string GetCID(XElement parser) + public static string GetCID(XElement parser) { string cid = "unknown"; if (!parser.Name.Equals(Name_EL_PCCOMPOUND_ID)) @@ -227,7 +228,7 @@ public void ParseAtomElements(XElement parser, IAtomContainer molecule) { if (Name_EL_ELEMENT.Equals(elm.Name)) { - int atomicNumber = int.Parse(elm.Value); + int atomicNumber = int.Parse(elm.Value, NumberFormatInfo.InvariantInfo); IElement element = factory.GetElement(atomicNumber); if (element == null) { @@ -254,7 +255,7 @@ public void ParserAtomBlock(XElement parser, IAtomContainer molecule) ParseAtomCharges(elm, molecule); } - public void ParserCompoundInfoData(XElement parser, IAtomContainer molecule) + public static void ParserCompoundInfoData(XElement parser, IAtomContainer molecule) { string urnLabel = null; string urnName = null; @@ -281,7 +282,7 @@ public void ParserCompoundInfoData(XElement parser, IAtomContainer molecule) } } - public void ParseAtomCharges(XElement parser, IAtomContainer molecule) + public static void ParseAtomCharges(XElement parser, IAtomContainer molecule) { if (!Name_EL_ATOMSCHARGE.Equals(parser.Name)) return; @@ -294,9 +295,9 @@ public void ParseAtomCharges(XElement parser, IAtomContainer molecule) foreach (var aie in elm.Descendants()) { if (Name_EL_ATOMINT_AID.Equals(aie.Name)) - aid = int.Parse(aie.Value); + aid = int.Parse(aie.Value, NumberFormatInfo.InvariantInfo); else if (Name_EL_ATOMINT_VALUE.Equals(aie.Name)) - charge = int.Parse(aie.Value); + charge = int.Parse(aie.Value, NumberFormatInfo.InvariantInfo); } molecule.Atoms[aid - 1].FormalCharge = charge; } @@ -325,7 +326,7 @@ public IAtomContainer ParseMolecule(XElement parser, IChemObjectBuilder builder) return molecule; } - public void ParserBondBlock(XElement parser, IAtomContainer molecule) + public static void ParserBondBlock(XElement parser, IAtomContainer molecule) { List id1s = new List(); List id2s = new List(); @@ -346,10 +347,10 @@ public void ParserBondBlock(XElement parser, IAtomContainer molecule) throw new CDKException("Number of bond orders does not match number of bonds in bond block."); for (int i = 0; i < id1s.Count; i++) { - IAtom atom1 = molecule.Atoms[int.Parse(id1s[i]) - 1]; - IAtom atom2 = molecule.Atoms[int.Parse(id2s[i]) - 1]; + IAtom atom1 = molecule.Atoms[int.Parse(id1s[i], NumberFormatInfo.InvariantInfo) - 1]; + IAtom atom2 = molecule.Atoms[int.Parse(id2s[i], NumberFormatInfo.InvariantInfo) - 1]; IBond bond = molecule.Builder.NewBond(atom1, atom2); - int order = int.Parse(orders[i]); + int order = int.Parse(orders[i], NumberFormatInfo.InvariantInfo); if (order == 1) { bond.Order = BondOrder.Single; @@ -372,7 +373,7 @@ public void ParserBondBlock(XElement parser, IAtomContainer molecule) } } - public void ParserCoordBlock(XElement parser, IAtomContainer molecule) + public static void ParserCoordBlock(XElement parser, IAtomContainer molecule) { List ids = new List(); List xs = new List(); @@ -403,21 +404,21 @@ public void ParserCoordBlock(XElement parser, IAtomContainer molecule) for (int i = 0; i < ids.Count; i++) { - IAtom atom = molecule.Atoms[int.Parse(ids[i]) - 1]; + IAtom atom = molecule.Atoms[int.Parse(ids[i], NumberFormatInfo.InvariantInfo) - 1]; if (has3dCoords) { - Vector3 coord = new Vector3(double.Parse(xs[i]), double.Parse(ys[i]), double.Parse(zs[i])); + Vector3 coord = new Vector3(double.Parse(xs[i], NumberFormatInfo.InvariantInfo), double.Parse(ys[i], NumberFormatInfo.InvariantInfo), double.Parse(zs[i], NumberFormatInfo.InvariantInfo)); atom.Point3D = coord; } else if (has2dCoords) { - Vector2 coord = new Vector2(double.Parse(xs[i]), double.Parse(ys[i])); + Vector2 coord = new Vector2(double.Parse(xs[i], NumberFormatInfo.InvariantInfo), double.Parse(ys[i], NumberFormatInfo.InvariantInfo)); atom.Point2D = coord; } } } - private List ParseValues(XElement parser, XName fieldTag) + private static List ParseValues(XElement parser, XName fieldTag) { List values = new List(); foreach (var elm in parser.Descendants()) diff --git a/NCDK/IO/RDF/CDKOWLReader.cs b/NCDK/IO/RDF/CDKOWLReader.cs index ea5c3537..79e48bc7 100644 --- a/NCDK/IO/RDF/CDKOWLReader.cs +++ b/NCDK/IO/RDF/CDKOWLReader.cs @@ -71,9 +71,9 @@ public override T Read(T obj) return (T)Read((IAtomContainer)obj); } - public IAtomContainer Read(IAtomContainer obj) + public IAtomContainer Read(IAtomContainer o) { - IAtomContainer result = obj; + IAtomContainer result = o; // do the actual parsing @@ -82,7 +82,7 @@ public IAtomContainer Read(IAtomContainer obj) parser.Load(model, input); var convertor = new Convertor(model); - IAtomContainer mol = convertor.Model2Molecule(obj.Builder); + IAtomContainer mol = convertor.Model2Molecule(o.Builder); result.Add(mol); return result; } diff --git a/NCDK/IO/RGroupQueryReader.cs b/NCDK/IO/RGroupQueryReader.cs index e0dd51b1..6d5a9e36 100644 --- a/NCDK/IO/RGroupQueryReader.cs +++ b/NCDK/IO/RGroupQueryReader.cs @@ -28,6 +28,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text; @@ -152,7 +153,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) // atom (Rgroup) - map with (integer,bond) meaning "bond" has attachment // order "integer" (1,2,3) for the Rgroup The order is based on the atom // block, unless there is an AAL line for the pseudo atom. - IDictionary> attachmentPoints = new Dictionary>(); + var attachmentPoints = new Dictionary>(); try { @@ -184,7 +185,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) StringBuilder sb = new StringBuilder(RGroup.RootLabelKey + "\n\n\n"); line = input.ReadLine(); ++lineCount; - while (line != null && !line.Equals("$END CTAB")) + while (line != null && !string.Equals(line, "$END CTAB", StringComparison.Ordinal)) { sb.Append(line).Append('\n'); @@ -195,10 +196,10 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) RGroupLogic log = null; log = new RGroupLogic(); - int rgroupNumber = int.Parse(tokens[3]); + int rgroupNumber = int.Parse(tokens[3], NumberFormatInfo.InvariantInfo); string tok = tokens[4]; - log.rgoupNumberRequired = tok.Equals("0") ? 0 : int.Parse(tok); - log.restH = tokens[5].Equals("1") ? true : false; + log.rgoupNumberRequired = string.Equals(tok, "0", StringComparison.Ordinal) ? 0 : int.Parse(tok, NumberFormatInfo.InvariantInfo); + log.restH = string.Equals(tokens[5], "1", StringComparison.Ordinal) ? true : false; tok = ""; for (int i = 6; i < tokens.Count; i++) { @@ -227,18 +228,17 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) if (line.StartsWith("M AAL", StringComparison.Ordinal)) { var stAAL = Strings.Tokenize(line); - int pos = int.Parse(stAAL[2]); + int pos = int.Parse(stAAL[2], NumberFormatInfo.InvariantInfo); IAtom rGroup = root.Atoms[pos - 1]; - IDictionary bondMap = new Dictionary(); + var bondMap = new Dictionary(); for (int i = 4; i < stAAL.Count; i += 2) { - pos = int.Parse(stAAL[i]); + pos = int.Parse(stAAL[i], NumberFormatInfo.InvariantInfo); IAtom partner = root.Atoms[pos - 1]; IBond bond = root.GetBond(rGroup, partner); - int order = int.Parse(stAAL[i + 1]); + int order = int.Parse(stAAL[i + 1], NumberFormatInfo.InvariantInfo); bondMap[order] = bond; - Trace.TraceInformation("AAL " + order + " " + ((IPseudoAtom)rGroup).Label + "-" - + partner.Symbol); + Trace.TraceInformation($"AAL {order} {((IPseudoAtom)rGroup).Label}-{partner.Symbol}"); } if (bondMap.Count != 0) { @@ -252,12 +252,12 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) { if (atom is IPseudoAtom rGroup) { - if (rGroup.Label.StartsWithChar('R') && !rGroup.Label.Equals("R") && // only numbered ones + if (rGroup.Label.StartsWithChar('R') && !string.Equals(rGroup.Label, "R", StringComparison.Ordinal) && // only numbered ones !attachmentPoints.ContainsKey(rGroup)) { //Order reflects the order of atoms in the Atom Block int order = 0; - IDictionary bondMap = new Dictionary(); + var bondMap = new Dictionary(); foreach (var atom2 in root.Atoms) { if (!atom.Equals(atom2)) @@ -288,7 +288,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) //__________________________________________________________________ //Set up the RgroupLists, one for each unique R# (# = 1..32 max) - IDictionary rGroupDefinitions = new Dictionary(); + var rGroupDefinitions = new Dictionary(); foreach (var atom in root.Atoms) { @@ -296,7 +296,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) { if (RGroupQuery.IsValidRgroupQueryLabel(rGroup.Label)) { - int rgroupNum = int.Parse(rGroup.Label.Substring(1)); + int rgroupNum = int.Parse(rGroup.Label.Substring(1), NumberFormatInfo.InvariantInfo); RGroupList rgroupList = new RGroupList(rgroupNum); if (!rGroupDefinitions.ContainsKey(rgroupNum)) { @@ -332,7 +332,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) line = input.ReadLine(); ++lineCount; Trace.TraceInformation("line for num is " + line); - int rgroupNum = int.Parse(line.Trim()); + int rgroupNum = int.Parse(line.Trim(), NumberFormatInfo.InvariantInfo); line = input.ReadLine(); ++lineCount; @@ -367,8 +367,8 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) var stAPO = Strings.Tokenize(line); for (int i = 3; i < stAPO.Count; i += 2) { - int pos = int.Parse(stAPO[i]); - int apo = int.Parse(stAPO[i + 1]); + var pos = int.Parse(stAPO[i], NumberFormatInfo.InvariantInfo); + var apo = int.Parse(stAPO[i + 1], NumberFormatInfo.InvariantInfo); IAtom at = group.Atoms[pos - 1]; switch (apo) { @@ -389,7 +389,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) } } } - RGroupList rList = rGroupDefinitions[rgroupNum]; + var rList = rGroupDefinitions[rgroupNum]; if (rList == null) { throw new CDKException("R" + rgroupNum + " not defined but referenced in $RGP."); @@ -445,7 +445,7 @@ private RGroupQuery ParseRGFile(RGroupQuery rGroupQuery) /// /// /// - private void CheckLineBeginsWith(string line, string expect, int lineCount) + private static void CheckLineBeginsWith(string line, string expect, int lineCount) { if (line == null) { diff --git a/NCDK/IO/RGroupQueryWriter.cs b/NCDK/IO/RGroupQueryWriter.cs index fa41ae3c..1e571140 100644 --- a/NCDK/IO/RGroupQueryWriter.cs +++ b/NCDK/IO/RGroupQueryWriter.cs @@ -26,6 +26,7 @@ using NCDK.Isomorphisms.Matchers; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text; @@ -104,7 +105,7 @@ protected override void Dispose(bool disposing) /// /// /// CTAB block - private string GetCTAB(IAtomContainer atomContainer) + private static string GetCTAB(IAtomContainer atomContainer) { StringWriter strWriter = new StringWriter(); MDLV2000Writer mdlWriter = new MDLV2000Writer(strWriter); @@ -121,7 +122,7 @@ private string GetCTAB(IAtomContainer atomContainer) //strip of the individual header, as we have one super header instead. for (int line = 1; line <= 3; line++) { - ctab = ctab.Substring(ctab.IndexOf(LSEP) + (LSEP.Length)); + ctab = ctab.Substring(ctab.IndexOf(LSEP, StringComparison.Ordinal) + (LSEP.Length)); } return ctab; } @@ -145,7 +146,7 @@ public override void Write(IChemObject obj) try { IRGroupQuery rGroupQuery = (IRGroupQuery)obj; - string now = DateTime.UtcNow.ToString("MMddyyHHmm"); + string now = DateTime.UtcNow.ToString("MMddyyHHmm", DateTimeFormatInfo.InvariantInfo); IAtomContainer rootAtc = rGroupQuery.RootStructure; //Construct header @@ -176,7 +177,7 @@ public override void Write(IChemObject obj) //from the order in the atom block. See CT spec for more on that. foreach (var rgroupAtom in rGroupQuery.RootAttachmentPoints.Keys) { - IDictionary rApo = rGroupQuery.RootAttachmentPoints[rgroupAtom]; + var rApo = rGroupQuery.RootAttachmentPoints[rgroupAtom]; if (rApo.Count > 1) { int prevPos = -1; diff --git a/NCDK/IO/RandomAccess/DefaultRandomAccessChemObjectReader.cs b/NCDK/IO/RandomAccess/DefaultRandomAccessChemObjectReader.cs index a3bcd455..0cad94f5 100644 --- a/NCDK/IO/RandomAccess/DefaultRandomAccessChemObjectReader.cs +++ b/NCDK/IO/RandomAccess/DefaultRandomAccessChemObjectReader.cs @@ -52,7 +52,7 @@ public virtual void RemoveChemObjectIOListener(IChemObjectIOListener listener) /* Extra convenience methods */ - protected void FireIOSettingQuestion(IOSetting setting) + protected void ProcessIOSettingQuestion(IOSetting setting) { for (int i = 0; i < listenerList.Count; ++i) { @@ -61,7 +61,7 @@ protected void FireIOSettingQuestion(IOSetting setting) } } - public IOSetting[] IOSettings { get; } = Array.Empty(); + public IReadOnlyList IOSettings { get; } = Array.Empty(); public abstract int Count { get; } public abstract bool IsReadOnly { get; } diff --git a/NCDK/IO/RandomAccess/RandomAccessReader.cs b/NCDK/IO/RandomAccess/RandomAccessReader.cs index 63bac9f9..ee696848 100644 --- a/NCDK/IO/RandomAccess/RandomAccessReader.cs +++ b/NCDK/IO/RandomAccess/RandomAccessReader.cs @@ -27,6 +27,7 @@ using NCDK.IO.Setting; using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Text; @@ -46,19 +47,16 @@ namespace NCDK.IO.RandomAccess public abstract class RandomAccessReader : DefaultRandomAccessChemObjectReader, IDisposable { - protected Stream raFile; - protected IOSetting[] headerOptions = null; + private Stream raFile; private readonly string filename; - protected ISimpleChemObjectReader chemObjectReader = null; - protected int indexVersion = 1; + private int indexVersion = 1; // index[record][0] - record offset in file index[record][1] - record length // index[record][2] - number of atoms (if available) - protected long[][] index = null; - protected int records; - protected int currentRecord = 0; - protected byte[] b; - protected IChemObjectBuilder builder; - protected bool indexCreated = false; + private long[][] index = null; + private int records; + private int currentRecord = 0; + private byte[] b; + private bool indexCreated = false; /// /// Reads the file and builds an index file, if the index file doesn't already exist. @@ -66,7 +64,7 @@ public abstract class RandomAccessReader /// the file object containing the molecules to be indexed /// a chem object builder /// if there is an error during reading - public RandomAccessReader(string file, IChemObjectBuilder builder) + protected RandomAccessReader(string file, IChemObjectBuilder builder) : this(file, builder, null) { } @@ -77,11 +75,11 @@ public RandomAccessReader(string file, IChemObjectBuilder builder) /// builder a chem object builder /// listen for read event /// if there is an error during reading - public RandomAccessReader(string file, IChemObjectBuilder builder, IReaderListener listener) + protected RandomAccessReader(string file, IChemObjectBuilder builder, IReaderListener listener) : base() { this.filename = Path.GetFullPath(file); - this.builder = builder; + this.Builder = builder; if (listener != null) AddChemObjectIOListener(listener); raFile = new FileStream(filename, FileMode.Open, FileAccess.Read); records = 0; @@ -98,28 +96,26 @@ public RandomAccessReader(string file, IChemObjectBuilder builder, IReaderListen public IChemObject ReadRecord(int record) { string buffer = ReadContent(record); - chemObjectReader = CreateChemObjectReader(new StringReader(buffer)); + ChemObjectReader = CreateChemObjectReader(new StringReader(buffer)); currentRecord = record; return ProcessContent(); } /// /// Reads the record text content into a string. - /// + /// /// The record number /// A string representation of the record /// if error occurs during reading /// if the record number is invalid - /// protected string ReadContent(int record) { - Debug.WriteLine("Current record ", record); + Debug.WriteLine($"Current record {record}"); if ((record < 0) || (record >= records)) { - throw new CDKException("No such record " + record); + throw new CDKException($"No such record {record}"); } - //FireFrameRead(); raFile.Seek(index[record][0], SeekOrigin.Begin); int length = (int)index[record][1]; @@ -134,10 +130,10 @@ protected string ReadContent(int record) /// an error occurred whilst reading the file protected virtual IChemObject ProcessContent() { - return chemObjectReader.Read(builder.NewChemFile()); + return ChemObjectReader.Read(Builder.NewChemFile()); } - protected long[][] Resize(long[][] index, int newLength) + internal static long[][] Resize(long[][] index, int newLength) { long[][] newIndex = Arrays.CreateJagged(newLength, 3); for (int i = 0; i < index.Length; i++) @@ -161,24 +157,24 @@ protected void SaveIndex(string file) } using (var o = new StreamWriter(file)) { - o.Write(indexVersion.ToString()); + o.Write(indexVersion.ToString(NumberFormatInfo.InvariantInfo)); o.Write('\n'); o.Write(filename); o.Write('\n'); - o.Write(raFile.Length.ToString()); + o.Write(raFile.Length.ToString(NumberFormatInfo.InvariantInfo)); o.Write('\n'); - o.Write(records.ToString()); + o.Write(records.ToString(NumberFormatInfo.InvariantInfo)); o.Write('\n'); for (int i = 0; i < records; i++) { - o.Write(index[i][0].ToString()); + o.Write(index[i][0].ToString(NumberFormatInfo.InvariantInfo)); o.Write("\t"); - o.Write(index[i][1].ToString()); + o.Write(index[i][1].ToString(NumberFormatInfo.InvariantInfo)); o.Write("\t"); - o.Write(index[i][2].ToString()); + o.Write(index[i][2].ToString(NumberFormatInfo.InvariantInfo)); o.Write("\t"); } - o.Write(records.ToString()); + o.Write(records.ToString(NumberFormatInfo.InvariantInfo)); o.Write('\n'); o.Write(filename); o.Write('\n'); @@ -193,20 +189,20 @@ protected void LoadIndex(string file) string version = ins.ReadLine(); if (!int.TryParse(version, out int iv)) throw new Exception($"Invalid index version {version}"); - if (int.Parse(version) != indexVersion) + if (int.Parse(version, NumberFormatInfo.InvariantInfo) != indexVersion) throw new Exception($"Expected index version {indexVersion} instead of {version}"); string fileIndexed = ins.ReadLine(); - if (!filename.Equals(fileIndexed)) + if (!string.Equals(filename, fileIndexed, StringComparison.Ordinal)) throw new Exception($"Index for {fileIndexed} found instead of {filename}. Creating new index."); string line = ins.ReadLine(); - int fileLength = int.Parse(line); + int fileLength = int.Parse(line, NumberFormatInfo.InvariantInfo); if (fileLength != raFile.Length) throw new Exception($"Index for file of size {fileLength} found instead of {raFile.Length}"); line = ins.ReadLine(); - int indexLength = int.Parse(line); + int indexLength = int.Parse(line, NumberFormatInfo.InvariantInfo); if (indexLength <= 0) throw new Exception($"Index of zero length! {Path.GetFullPath(file)}"); index = Arrays.CreateJagged(indexLength, 3); @@ -219,7 +215,7 @@ protected void LoadIndex(string file) for (int j = 0; j < 3; j++) try { - index[i][j] = long.Parse(result[j]); + index[i][j] = long.Parse(result[j], NumberFormatInfo.InvariantInfo); } catch (Exception x) { @@ -231,7 +227,7 @@ protected void LoadIndex(string file) } line = ins.ReadLine(); - int indexLength2 = int.Parse(line); + int indexLength2 = int.Parse(line, NumberFormatInfo.InvariantInfo); if (indexLength2 <= 0) { throw new Exception("Index of zero length!"); @@ -241,9 +237,9 @@ protected void LoadIndex(string file) throw new Exception("Wrong index length!"); } line = ins.ReadLine(); - if (!line.Equals(filename)) + if (!string.Equals(line, filename, StringComparison.Ordinal)) { - throw new Exception("Index for " + line + " found instead of " + filename); + throw new Exception($"Index for {line} found instead of {filename}"); } b = new byte[maxRecordLength]; } @@ -288,19 +284,17 @@ protected void MakeIndex() if (start == -1) start = raFile.Position; if (IsRecordEnd(s)) { - //FireFrameRead(); if (records >= maxRecords) { index = Resize(index, - records - + (int)(records + (raFile.Length - records * raFile.Position) - / recordLength)); + records + (int)(records + (raFile.Length - records * raFile.Position) / recordLength)); } end += 4; index[records][0] = start; index[records][1] = end - start; index[records][2] = -1; - if (maxRecordLength < index[records][1]) maxRecordLength = (int)index[records][1]; + if (maxRecordLength < index[records][1]) + maxRecordLength = (int)index[records][1]; records++; recordLength += (int)(end - start); @@ -312,7 +306,7 @@ protected void MakeIndex() } } b = new byte[maxRecordLength]; - //FireFrameRead(); + Trace.TraceInformation($"Index created in {(DateTime.Now.Ticks - now) / 10000} ms."); try { @@ -358,12 +352,6 @@ public static string GetIndexFile(string filename) return indexFile; } - [MethodImpl(MethodImplOptions.Synchronized)] - public IChemObjectReader GetChemObjectReader() - { - return chemObjectReader; - } - public abstract ISimpleChemObjectReader CreateChemObjectReader(TextReader reader); public bool HasNext() @@ -428,34 +416,34 @@ public IChemObject Previous() } } - public void Set(IChemObject arg0) - { } - public override void Add(IChemObject arg0) { } - public int PreviousIndex() + public virtual int PreviousIndex() { return currentRecord - 1; } - public int NextIndex() + public virtual int NextIndex() { return currentRecord + 1; } public override int Count => records; + protected ISimpleChemObjectReader ChemObjectReader { get; set; } = null; + protected IChemObjectBuilder Builder { get; set; } + public override void AddChemObjectIOListener(IChemObjectIOListener listener) { AddChemObjectIOListener(listener); - if (chemObjectReader != null) chemObjectReader.Listeners.Add(listener); + if (ChemObjectReader != null) ChemObjectReader.Listeners.Add(listener); } public override void RemoveChemObjectIOListener(IChemObjectIOListener listener) { base.RemoveChemObjectIOListener(listener); - if (chemObjectReader != null) chemObjectReader.Listeners.Remove(listener); + if (ChemObjectReader != null) ChemObjectReader.Listeners.Remove(listener); } [MethodImpl(MethodImplOptions.Synchronized)] public int GetCurrentRecord() diff --git a/NCDK/IO/RandomAccess/RandomAccessSDFReader.cs b/NCDK/IO/RandomAccess/RandomAccessSDFReader.cs index fd24209f..2c7a448e 100644 --- a/NCDK/IO/RandomAccess/RandomAccessSDFReader.cs +++ b/NCDK/IO/RandomAccess/RandomAccessSDFReader.cs @@ -54,32 +54,27 @@ public override ISimpleChemObjectReader CreateChemObjectReader(TextReader reader protected override bool IsRecordEnd(string line) { - return line.Equals("$$$$"); + return string.Equals(line, "$$$$", StringComparison.Ordinal); } /// - public IResourceFormat Format => MDLFormat.Instance; + public virtual IResourceFormat Format => MDLFormat.Instance; public override bool IsReadOnly => true; public override IChemObject this[int index] { - get - { - throw new NotImplementedException(); - } - - set - { - throw new NotImplementedException(); - } +#pragma warning disable CA1065 // Do not raise exceptions in unexpected locations + get => throw new NotImplementedException(); +#pragma warning restore CA1065 // Do not raise exceptions in unexpected locations + set => throw new NotImplementedException(); } protected override IChemObject ProcessContent() { // return chemObjectReader.Read(builder.NewAtomContainer()); //Read(IAtomContainer) doesn't read properties ... - IChemObject co = chemObjectReader.Read(builder.NewChemFile()); + IChemObject co = ChemObjectReader.Read(Builder.NewChemFile()); if (co is IChemFile) { var cm = ((IChemFile)co).FirstOrDefault(); @@ -97,25 +92,9 @@ protected override IChemObject ProcessContent() return co; } - public void SetReader(TextReader reader) - { - throw new NotSupportedException(); - } - - public void SetReader(Stream reader) - { - throw new NotSupportedException(); - - } - public bool Accepts(Type classObject) { - return chemObjectReader.Accepts(classObject); - } - - public void Remove() - { - throw new NotSupportedException("Cannot remove entries with " + "the " + nameof(RandomAccessSDFReader)); + return ChemObjectReader.Accepts(classObject); } public override int IndexOf(IChemObject item) diff --git a/NCDK/IO/ReaderFactory.cs b/NCDK/IO/ReaderFactory.cs index 9224433c..ca0418d1 100644 --- a/NCDK/IO/ReaderFactory.cs +++ b/NCDK/IO/ReaderFactory.cs @@ -42,7 +42,7 @@ namespace NCDK.IO public class ReaderFactory { private FormatFactory formatFactory = null; - private int headerLength = 8192; + private readonly int headerLength = 8192; /// /// Constructs a ReaderFactory which tries to detect the format in the @@ -50,7 +50,8 @@ public class ReaderFactory /// public ReaderFactory() : this(8192) - { } + { + } /// /// Constructs a ReaderFactory which tries to detect the format in the @@ -71,7 +72,7 @@ public void RegisterFormat(IChemFormatMatcher format) formatFactory.RegisterFormat(format); } - public IList Formats => formatFactory.Formats; + public IReadOnlyList Formats => formatFactory.Formats; /// /// Detects the format of the Reader input, and if known, it will return @@ -197,7 +198,7 @@ public Type GetReaderType(IChemFormat format) /// public ISimpleChemObjectReader CreateReader(TextReader input) { - IChemFormat format = formatFactory.GuessFormat(input); + var format = formatFactory.GuessFormat(input); return CreateReader(format, input); } @@ -206,7 +207,7 @@ public ISimpleChemObjectReader CreateReader(IChemFormat format, TextReader input var type = GetReaderType(format); try { - ISimpleChemObjectReader coReader = (ISimpleChemObjectReader)type.GetConstructor(new Type[] { typeof(TextReader) }).Invoke(new object[] { input }); + var coReader = (ISimpleChemObjectReader)type.GetConstructor(new Type[] { typeof(TextReader) }).Invoke(new object[] { input }); return coReader; } catch (Exception exception) diff --git a/NCDK/IO/RssWriter.cs b/NCDK/IO/RssWriter.cs index dd2c03d7..74c170df 100644 --- a/NCDK/IO/RssWriter.cs +++ b/NCDK/IO/RssWriter.cs @@ -2,6 +2,7 @@ using NCDK.LibIO.CML; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Xml.Linq; @@ -28,44 +29,44 @@ public class RssWriter : DefaultChemObjectWriter /// /// the link map. If you put a string in this map with one of the objects you want to write as key, it will be added as a link to this object (no validity check is done) /// - public IDictionary LinkMap { get; set; } = new Dictionary(); + public IReadOnlyDictionary LinkMap { get; set; } = new Dictionary(); /// /// the date map. If you put a in this map with one of the objects you want to write as key, it will be added as a date to this object (no validity check is done) /// - public IDictionary DateMap { get; set; } = new Dictionary(); + public IReadOnlyDictionary DateMap { get; set; } = new Dictionary(); /// /// the title map. If you put a string in this map with one of the objects you want to write as key, it will be added as a title to this object (no validity check is done) /// - public IDictionary TitleMap { get; set; } = new Dictionary(); + public IReadOnlyDictionary TitleMap { get; set; } = new Dictionary(); /// /// the creator map. If you put a string in this map with one of the objects you want to write as key, it will be added as a creator to this object (no validity check is done) /// - public IDictionary CreatorMap { get; set; } = new Dictionary(); + public IReadOnlyDictionary CreatorMap { get; set; } = new Dictionary(); /// /// InChI map If you put any number of strings in this map with one of the objects you want to write as key, it will be added as a child to the same node as the cml code of the object /// - public IDictionary InChIMap { get; set; } = new Dictionary(); + public IReadOnlyDictionary InChIMap { get; set; } = new Dictionary(); - private string Creator = ""; + public string Creator { get; set; } = ""; /// /// This will be the title for the rss feed /// - private string Title = ""; + public string Title { get; set; } = ""; /// /// This will be the link for the rss feed /// - private string Link = ""; + public string Link { get; set; } = ""; /// /// This will be the description for the rss feed /// - private string Description = ""; + public string Description { get; set; } = ""; /// /// This will be the Publisher for the rss feed @@ -75,34 +76,22 @@ public class RssWriter : DefaultChemObjectWriter /// /// This will be the ImageLink for the rss feed /// - private string ImageLink = ""; + public string ImageLink { get; set; } = ""; /// /// This will be the About for the rss feed /// - private string About = ""; + public string About { get; set; } = ""; /// /// This will be added to the data as TimeZone. format according to 23c. Examples "+01:00" "-05:00" /// - private string TimeZone = "+01:00"; - private IDictionary> multiMap = new Dictionary>(); + public string TimeZone { get; set; } = "+01:00"; /// - /// the multi map. If you put any number of nu.xom.Elements in this map with one of the objects you want to write as key, it will be added as a child to the same node as the cml code of the object + /// If you put any number of nu.xom.Elements in this map with one of the objects you want to write as key, it will be added as a child to the same node as the cml code of the object /// - public IDictionary> GetMultiMap() - { - return multiMap; - } - - /// - /// the multi map. If you put any number of nu.xom.Elements in this map with one of the objects you want to write as key, it will be added as a child to the same node as the cml code of the object - /// - public void SetMultiMap(IDictionary> value) - { - multiMap = value; - } + public IReadOnlyDictionary> MultiMap { get; set; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls @@ -153,7 +142,7 @@ public override void Write(IChemObject obj) rdfElement.SetAttributeValue(XNamespace.Xmlns + "rdf", NS_RSS10); rdfElement.SetAttributeValue(XNamespace.Xmlns + "mn", "http://usefulinc.com/rss/manifest/"); rdfElement.SetAttributeValue(XNamespace.Xmlns + "dc", NS_DCELEMENTS); - rdfElement.SetAttributeValue(XNamespace.Xmlns + "cml", Convertor.NS_CML); + rdfElement.SetAttributeValue(XNamespace.Xmlns + "cml", Convertor.NamespaceCML); doc.Add(rdfElement); var channelElement = new XElement(NS_RSS10 + "channel"); var titleElement = new XElement(NS_RSS10 + "title") @@ -239,7 +228,7 @@ public override void Write(IChemObject obj) { var dateElement = new XElement(NS_DCELEMENTS + "date") { - Value = DateMap[chemObject].ToString("yyyy-MM-dd'T'HH:mm:ss") + TimeZone + Value = DateMap[chemObject].ToString("yyyy-MM-dd'T'HH:mm:ss", DateTimeFormatInfo.InvariantInfo) + TimeZone }; itemElement.Add(dateElement); } @@ -258,7 +247,7 @@ public override void Write(IChemObject obj) itemElement.Add(inchiElement); } CMLElement root = null; - Convertor convertor = new Convertor(true, null); + var convertor = new Convertor(true, null); obj = (IChemObject)list[i]; if (obj is IAtomContainer) { @@ -302,12 +291,12 @@ public override void Write(IChemObject obj) } else { - throw new CDKException("Unsupported chemObject: " + obj.GetType().Name); + throw new CDKException($"Unsupported chemObject: {obj.GetType().Name}"); } itemElement.Add(root); - if (GetMultiMap()[chemObject] != null) + if (MultiMap[chemObject] != null) { - var coll = GetMultiMap()[chemObject]; + var coll = MultiMap[chemObject]; foreach (var e in coll) { itemElement.Add(e); diff --git a/NCDK/IO/SDFWriter.cs b/NCDK/IO/SDFWriter.cs index 264bdda1..be00daf2 100644 --- a/NCDK/IO/SDFWriter.cs +++ b/NCDK/IO/SDFWriter.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text.RegularExpressions; @@ -233,7 +234,7 @@ private void WriteMolecule(IAtomContainer container) if (writeAllProperties || propertiesToWrite.Contains(headerKey)) { string cleanHeaderKey = ReplaceInvalidHeaderChars(headerKey); - if (!cleanHeaderKey.Equals(headerKey)) + if (!cleanHeaderKey.Equals(headerKey, StringComparison.Ordinal)) Trace.TraceInformation("Replaced characters in SDfile data header: ", headerKey, " written as: ", cleanHeaderKey); Object val = sdFields[propKey]; @@ -279,7 +280,7 @@ private bool WriteV3000(IAtomContainer container) if (container.Bonds.Count > 999) return true; // check for positional variation, this can be output in base V3000 and not V2000 - var sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = container.GetCtabSgroups(); if (sgroups != null) { foreach (Sgroup sgroup in sgroups) @@ -293,35 +294,30 @@ private bool WriteV3000(IAtomContainer container) /// A list of properties used by CDK algorithms which must never be /// serialized into the SD file format. /// - private static List cdkInternalProperties = new List(); - - static SDFWriter() - { - cdkInternalProperties.Add(InvPair.CanonicalLabelKey); - cdkInternalProperties.Add(InvPair.InvariancePairKey); - cdkInternalProperties.Add(CDKPropertyName.CtabSgroups); - // TITLE/REMARK written in Molfile header - cdkInternalProperties.Add(CDKPropertyName.Remark); - cdkInternalProperties.Add(CDKPropertyName.Title); - // I think there are a few more, but cannot find them right now - } + private static List cdkInternalProperties = new List() + { + InvPair.CanonicalLabelPropertyKey, + InvPair.InvariancePairPropertyKey, + SgroupTool.CtabSgroupsPropertyKey, + // TITLE/REMARK written in Molfile header + CDKPropertyName.Remark, + CDKPropertyName.Title, + // I think there are a few more, but cannot find them right now + }; - private bool IsCDKInternalProperty(object propKey) + private static bool IsCDKInternalProperty(object propKey) { - var stringKey = propKey as string; - if (stringKey == null) + if (!(propKey is string stringKey)) return false; return cdkInternalProperties.Contains(stringKey); } private void InitIOSettings() { - paramWriteData = Add(new BooleanIOSetting("writeProperties", - IOSetting.Importance.Low, - "Should molecule properties be written as non-structural data", "true")); - paramWriteV3000 = Add(new BooleanIOSetting("writeV3000", - IOSetting.Importance.Low, - "Write all records as V3000", "false")); + paramWriteData = Add(new BooleanIOSetting("writeProperties", Importance.Low, + "Should molecule properties be written as non-structural data", "true")); + paramWriteV3000 = Add(new BooleanIOSetting("writeV3000", Importance.Low, + "Write all records as V3000", "false")); AddSettings(new MDLV2000Writer().IOSettings.Settings); AddSettings(new MDLV3000Writer().IOSettings.Settings); } @@ -330,7 +326,7 @@ public void SetAlwaysV3000(bool val) { try { - paramWriteV3000.Setting = val.ToString(); + paramWriteV3000.Setting = val.ToString(NumberFormatInfo.InvariantInfo); } catch (CDKException e) { @@ -343,7 +339,7 @@ public void CustomizeJob() { foreach (var setting in IOSettings.Settings) { - FireIOSettingQuestion(setting); + ProcessIOSettingQuestion(setting); } } } diff --git a/NCDK/IO/SMILESReader.cs b/NCDK/IO/SMILESReader.cs index b8c14883..bf34c32a 100644 --- a/NCDK/IO/SMILESReader.cs +++ b/NCDK/IO/SMILESReader.cs @@ -124,7 +124,7 @@ private IChemObjectSet ReadAtomContainerSet(IChemObjectSet /// input line /// the suffix - or an empty line - private string Suffix(string line) + private static string Suffix(string line) { for (int i = 0; i < line.Length; i++) { diff --git a/NCDK/IO/SMILESWriter.cs b/NCDK/IO/SMILESWriter.cs index 1001693a..9cf883fe 100644 --- a/NCDK/IO/SMILESWriter.cs +++ b/NCDK/IO/SMILESWriter.cs @@ -141,7 +141,7 @@ public void WriteAtomContainer(IAtomContainer molecule) try { smiles = sg.Create(molecule); - Debug.WriteLine("Generated SMILES: " + smiles); + Debug.WriteLine($"Generated SMILES: {smiles}"); writer.Write(smiles); writer.Write('\n'); writer.Flush(); @@ -161,13 +161,13 @@ public void WriteAtomContainer(IAtomContainer molecule) private void InitIOSettings() { - useAromaticityFlag = Add(new BooleanIOSetting("UseAromaticity", IOSetting.Importance.Low, + useAromaticityFlag = Add(new BooleanIOSetting("UseAromaticity", Importance.Low, "Should aromaticity information be stored in the SMILES?", "false")); } public void CustomizeJob() { - FireIOSettingQuestion(useAromaticityFlag); + ProcessIOSettingQuestion(useAromaticityFlag); } } } diff --git a/NCDK/IO/Setting/BooleanIOSetting.cs b/NCDK/IO/Setting/BooleanIOSetting.cs index a51f36a7..bbf4c5c1 100644 --- a/NCDK/IO/Setting/BooleanIOSetting.cs +++ b/NCDK/IO/Setting/BooleanIOSetting.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.IO.Setting { /// @@ -35,7 +37,7 @@ public BooleanIOSetting(string name, Importance level, string question, string d /// /// Sets the setting for a certain question. The setting - /// is a bool, and it accepts only "true" and "false". + /// is a boolean, and it accepts only "true" and "false". /// public override string Setting { @@ -46,25 +48,28 @@ public override string Setting set { - if (value.Equals("true") || value.Equals("false")) - { - this.setting = value; - } - else if (value.Equals("True") || value.Equals("yes") || value.Equals("y")) - { - this.setting = "true"; - } - else if (value.Equals("False") || value.Equals("no") || value.Equals("n")) - { - this.setting = "false"; - } - else + switch (value) { - throw new CDKException("Setting " + value + " is not a bool."); + case "true": + case "false": + this.setting = value; + break; + case "True": + case "yes": + case "y": + this.setting = "true"; + break; + case "False": + case "no": + case "n": + this.setting = "false"; + break; + default: + throw new CDKException($"Setting {value} is not a boolean."); } } } - public bool IsSet => string.Equals(setting, "true"); + public bool IsSet => string.Equals(setting, "true", StringComparison.Ordinal); } } diff --git a/NCDK/IO/Setting/IOSetting.cs b/NCDK/IO/Setting/IOSetting.cs index 55ddb08d..c7356569 100644 --- a/NCDK/IO/Setting/IOSetting.cs +++ b/NCDK/IO/Setting/IOSetting.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.IO.Setting { /// @@ -28,19 +30,6 @@ namespace NCDK.IO.Setting // @author Egon Willighagen public abstract class IOSetting : ISetting { - public struct Importance - { - private int ordinal; - public int Ordinal => ordinal; - public Importance(int ordinal) - { - this.ordinal = ordinal; - } - public static readonly Importance High = new Importance(0); - public static readonly Importance Medium = new Importance(1); - public static readonly Importance Low = new Importance(2); - } - /// /// The default constructor that sets this field. All textual /// information is supposed to be English. Localization is taken care @@ -50,7 +39,7 @@ public Importance(int ordinal) /// Level at which question is asked /// Question that is popped to the user when the ReaderSetting needs setting /// The default setting, used if not overwritten by a user - public IOSetting(string name, Importance level, string question, string defaultSetting) + protected IOSetting(string name, Importance level, string question, string defaultSetting) { this.Level = level; this.Name = name; @@ -68,4 +57,30 @@ public IOSetting(string name, Importance level, string question, string defaultS /// public virtual string Setting { get; set; } // by default, except all input, so no setting checking } + + public struct Importance : IEquatable + { + public int Ordinal { get; } + + public Importance(int ordinal) + { + this.Ordinal = ordinal; + } + + public static readonly Importance High = new Importance(0); + public static readonly Importance Medium = new Importance(1); + public static readonly Importance Low = new Importance(2); + + public override bool Equals(object obj) + { + if (!(obj is Importance)) + return false; + return Ordinal == ((Importance)obj).Ordinal; + } + + public override int GetHashCode() => Ordinal; + public static bool operator ==(Importance left, Importance right) => left.Ordinal == right.Ordinal; + public static bool operator !=(Importance left, Importance right) => left.Ordinal == right.Ordinal; + public bool Equals(Importance other) => Ordinal == other.Ordinal; + } } diff --git a/NCDK/IO/Setting/IntegerIOSetting.cs b/NCDK/IO/Setting/IntegerIOSetting.cs index f6f385c4..d9834384 100644 --- a/NCDK/IO/Setting/IntegerIOSetting.cs +++ b/NCDK/IO/Setting/IntegerIOSetting.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System.Globalization; + namespace NCDK.IO.Setting { /// @@ -52,7 +54,7 @@ public override string Setting public virtual int GetSettingValue() { - return int.Parse(this.Setting); + return int.Parse(this.Setting, NumberFormatInfo.InvariantInfo); } } } diff --git a/NCDK/IO/ShelXReader.cs b/NCDK/IO/ShelXReader.cs index c2f602c8..5bd1ca63 100644 --- a/NCDK/IO/ShelXReader.cs +++ b/NCDK/IO/ShelXReader.cs @@ -90,7 +90,7 @@ public override T Read(T obj) } catch (IOException e) { - Trace.TraceError("Input/Output error while reading from input: " + e.Message); + Trace.TraceError($"Input/Output error while reading from input: {e.Message}"); throw new CDKException(e.Message, e); } } @@ -102,7 +102,7 @@ public override T Read(T obj) } catch (IOException e) { - Trace.TraceError("Input/Output error while reading from input: " + e.Message); + Trace.TraceError($"Input/Output error while reading from input: {e.Message}"); throw new CDKException(e.Message, e); } } @@ -135,7 +135,7 @@ private ICrystal ReadCrystal(ICrystal crystal) while (line != null && !end_found) { /* is line continued? */ - if (line.Length > 0 && line.Substring(line.Length - 1).Equals("=")) + if (line.Length > 0 && line.Substring(line.Length - 1).Equals("=", StringComparison.Ordinal)) { /* yes, line is continued */ line = line + input.ReadLine(); @@ -153,7 +153,7 @@ private ICrystal ReadCrystal(ICrystal crystal) break; } - Debug.WriteLine("command: " + command); + Debug.WriteLine($"command: {command}"); var u_command = command.ToUpperInvariant(); if (u_command.StartsWith("REM", StringComparison.Ordinal)) { @@ -183,12 +183,12 @@ private ICrystal ReadCrystal(ICrystal crystal) string salpha = st[5]; string sbeta = st[6]; string sgamma = st[7]; - Debug.WriteLine("a: " + sa); - Debug.WriteLine("b: " + sb); - Debug.WriteLine("c: " + sc); - Debug.WriteLine("alpha: " + salpha); - Debug.WriteLine("beta : " + sbeta); - Debug.WriteLine("gamma: " + sgamma); + Debug.WriteLine($"a: {sa}"); + Debug.WriteLine($"b: {sb}"); + Debug.WriteLine($"c: {sc}"); + Debug.WriteLine($"alpha: {salpha}"); + Debug.WriteLine($"beta : {sbeta}"); + Debug.WriteLine($"gamma: {sgamma}"); double a = FortranFormat.Atof(sa); double b = FortranFormat.Atof(sb); @@ -294,14 +294,14 @@ private ICrystal ReadCrystal(ICrystal crystal) break; case " ": { - Debug.WriteLine("Disrgarding line assumed to be added by PLATON: " + line); + Debug.WriteLine($"Disrgarding line assumed to be added by PLATON: {line}"); /* All other is atom */ } break; default: { - //Debug.WriteLine("Assumed to contain an atom: " + line); + //Debug.WriteLine($"Assumed to contain an atom: {line}"); // this line gives an atom, because all lines not starting with // a ShelX command is an atom (that sucks!) @@ -341,7 +341,7 @@ private ICrystal ReadCrystal(ICrystal crystal) IAtom atom = crystal.Builder.NewAtom(atype); atom.FractionalPoint3D = new Vector3(frac[0], frac[1], frac[2]); crystal.Atoms.Add(atom); - Debug.WriteLine("Atom added: ", atom); + Debug.WriteLine($"Atom added: {atom}"); } } break; diff --git a/NCDK/IO/ShelXWriter.cs b/NCDK/IO/ShelXWriter.cs index e61751f4..ea101b47 100644 --- a/NCDK/IO/ShelXWriter.cs +++ b/NCDK/IO/ShelXWriter.cs @@ -25,6 +25,7 @@ using NCDK.Numerics; using NCDK.Tools.Manipulator; using System; +using System.Globalization; using System.IO; using System.Linq; @@ -107,7 +108,7 @@ private void WriteCrystal(ICrystal crystal) var title = crystal.Title; if (title != null && title.Trim().Length > 0) { - Writeln("TITL " + title.ToString().Trim()); + Writeln($"TITL {title.Trim()}"); } else { @@ -122,28 +123,27 @@ private void WriteCrystal(ICrystal crystal) double alpha = Vectors.RadianToDegree(Vectors.Angle(b, c)); double beta = Vectors.RadianToDegree(Vectors.Angle(a, c)); double gamma = Vectors.RadianToDegree(Vectors.Angle(a, b)); - Write("CELL " + 1.54184.ToString("F5") + " "); - Write(alength.ToString("F5") + " "); - Write(blength.ToString("F5") + " "); - Write(clength.ToString("F5") + " "); - Write(alpha.ToString("F4") + " "); - Write(beta.ToString("F4") + " "); - Write(gamma.ToString("F4") + " "); - Writeln("ZERR " + ((double)crystal.Z).ToString("F5") + Write("CELL " + 1.54184.ToString("F5", NumberFormatInfo.InvariantInfo) + " "); + Write(alength.ToString("F5", NumberFormatInfo.InvariantInfo) + " "); + Write(blength.ToString("F5", NumberFormatInfo.InvariantInfo) + " "); + Write(clength.ToString("F5", NumberFormatInfo.InvariantInfo) + " "); + Write(alpha.ToString("F4", NumberFormatInfo.InvariantInfo) + " "); + Write(beta.ToString("F4", NumberFormatInfo.InvariantInfo) + " "); + Write(gamma.ToString("F4", NumberFormatInfo.InvariantInfo) + " "); + Writeln("ZERR " + ((double)crystal.Z).ToString("F5", NumberFormatInfo.InvariantInfo) + " 0.01000 0.01000 0.01000 0.0100 0.0100 0.0100"); string spaceGroup = crystal.SpaceGroup; - if ("P1".Equals(spaceGroup)) + if (string.Equals("P1", spaceGroup, StringComparison.Ordinal)) { Writeln("LATT -1"); } - else if ("P 2_1 2_1 2_1".Equals(spaceGroup)) + else if (string.Equals("P 2_1 2_1 2_1", spaceGroup, StringComparison.Ordinal)) { Writeln("LATT -1"); Writeln("SYMM 1/2+X , 1/2-Y , -Z"); Writeln("SYMM -X , 1/2+Y , 1/2-Z"); Writeln("SYMM 1/2-X , -Y , 1/2+Z"); } - // MFAnalyser mfa = new MFAnalyser(crystal); string elemNames = ""; string elemCounts = ""; IMolecularFormula formula = MolecularFormulaManipulator.GetMolecularFormula(crystal); @@ -152,7 +152,7 @@ private void WriteCrystal(ICrystal crystal) { string symbol = element.Symbol; elemNames += symbol + " ".Substring(symbol.Length); - string countS = MolecularFormulaManipulator.GetElementCount(formula, element).ToString(); + string countS = MolecularFormulaManipulator.GetElementCount(formula, element).ToString(NumberFormatInfo.InvariantInfo); elemCounts += countS + " ".Substring(countS.Length); } Writeln("SFAC " + elemNames); @@ -175,17 +175,17 @@ private void WriteCrystal(ICrystal crystal) for (int elemidx = 0; elemidx < asortedElements.Count; elemidx++) { IElement elem = asortedElements[elemidx]; - if (elem.Symbol.Equals(symbol)) + if (elem.Symbol.Equals(symbol, StringComparison.Ordinal)) { - elemID = (elemidx + 1).ToString(); + elemID = (elemidx + 1).ToString(NumberFormatInfo.InvariantInfo); break; } } Write(elemID); Write(" ".Substring(elemID.Length)); - Write(fracCoord.X.ToString("F5") + " "); - Write(fracCoord.Y.ToString("F5") + " "); - Writeln(fracCoord.Y.ToString("F5") + " 11.00000 0.05000"); + Write(fracCoord.X.ToString("F5", NumberFormatInfo.InvariantInfo) + " "); + Write(fracCoord.Y.ToString("F5", NumberFormatInfo.InvariantInfo) + " "); + Writeln(fracCoord.Y.ToString("F5", NumberFormatInfo.InvariantInfo) + " 11.00000 0.05000"); } Writeln("END"); } @@ -211,7 +211,7 @@ private void Writeln(string s) } catch (IOException e) { - Console.Error.WriteLine("CMLWriter IOException while printing \"" + s + "\":" + e.ToString()); + Console.Error.WriteLine($"CMLWriter IOException while printing \"{s}\":{e.ToString()}"); } } } diff --git a/NCDK/IO/VASPReader.cs b/NCDK/IO/VASPReader.cs index a11a7b1b..cfe2fd3c 100644 --- a/NCDK/IO/VASPReader.cs +++ b/NCDK/IO/VASPReader.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -40,17 +41,16 @@ namespace NCDK.IO public class VASPReader : DefaultChemObjectReader { // This variable is used to parse the input file - protected string fieldVal; - protected int repVal = 0; - protected TextReader inputBuffer; + private string fieldVal; + private TextReader inputBuffer; IEnumerator st = new List().GetEnumerator(); // VASP VARIABLES int natom = 1; int ntype = 1; - double[] acell = new double[3]; - double[][] rprim = Arrays.CreateJagged(3, 3); + readonly double[] acell = new double[3]; + readonly double[][] rprim = Arrays.CreateJagged(3, 3); string info = ""; /// size is ntype. Contains the names of the atoms string[] anames; @@ -124,8 +124,8 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) // Get the number of different atom "NCLASS=X" NextVASPTokenFollowing("NCLASS"); - ntype = int.Parse(fieldVal); - //Debug.WriteLine("NCLASS= " + ntype); + ntype = int.Parse(fieldVal, NumberFormatInfo.InvariantInfo); + //Debug.WriteLine($"NCLASS= {ntype}"); inputBuffer = new StringReader(buf); // Get the different atom names @@ -143,7 +143,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) natom = 0; for (int i = 0; i < ntype; i++) { - natom_type[i] = int.Parse(fieldVal); + natom_type[i] = int.Parse(fieldVal, NumberFormatInfo.InvariantInfo); NextVASPToken(false); natom = natom + natom_type[i]; } @@ -151,7 +151,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) // Get the representation type of the primitive vectors // only "Direct" is recognize now. representation = fieldVal; - if (representation.Equals("Direct")) + if (string.Equals(representation, "Direct", StringComparison.Ordinal)) { Trace.TraceInformation("Direct representation"); // DO NOTHING @@ -172,7 +172,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) for (int i = 0; i < 3; i++) { // TODO: supoort FORTRA format - acell[i] = double.Parse(fieldVal); //all the same FIX? + acell[i] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo); //all the same FIX? } // Get primitive vectors @@ -181,7 +181,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) { NextVASPToken(false); // TODO: supoort FORTRA format - rprim[i][j] = double.Parse(fieldVal); + rprim[i][j] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo); } // Get atomic position @@ -195,21 +195,21 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) { try { - atomType[atomIndex] = Isotopes.Instance.GetElement(anames[i]).AtomicNumber.Value; + atomType[atomIndex] = BODRIsotopeFactory.Instance.GetElement(anames[i]).AtomicNumber.Value; } catch (Exception exception) { throw new CDKException("Could not determine atomic number!", exception); } - Debug.WriteLine("aname: " + anames[i]); - Debug.WriteLine("atomType: " + atomType[atomIndex]); + Debug.WriteLine($"aname: {anames[i]}"); + Debug.WriteLine($"atomType: {atomType[atomIndex]}"); NextVASPToken(false); - xred[atomIndex][0] = double.Parse(fieldVal); + xred[atomIndex][0] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo); NextVASPToken(false); - xred[atomIndex][1] = double.Parse(fieldVal); + xred[atomIndex][1] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo); NextVASPToken(false); - xred[atomIndex][2] = double.Parse(fieldVal); + xred[atomIndex][2] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo); atomIndex = atomIndex + 1; // FIXME: store atom @@ -224,7 +224,7 @@ private IChemSequence ReadChemSequence(IChemSequence sequence) string symbol = "Du"; try { - symbol = Isotopes.Instance.GetElement(atomType[i]).Symbol; + symbol = BODRIsotopeFactory.Instance.GetElement(atomType[i]).Symbol; } catch (Exception exception) { @@ -303,7 +303,7 @@ public string NextVASPTokenFollowing(string str) string line; while ((line = inputBuffer.ReadLine()) != null) { - index = line.IndexOf(str); + index = line.IndexOf(str, StringComparison.Ordinal); if (index > 0) { index = index + str.Length; diff --git a/NCDK/IO/WriterFactory.cs b/NCDK/IO/WriterFactory.cs index e74c3536..bac9ca8a 100644 --- a/NCDK/IO/WriterFactory.cs +++ b/NCDK/IO/WriterFactory.cs @@ -51,7 +51,7 @@ public WriterFactory() registeredReaders = new Dictionary(); // Type is IChemObjectWriter } - public void RegisterWriter(System.Type writer) + public static void RegisterWriter(System.Type writer) { if (writer == null) return; if (typeof(IChemObjectWriter).IsAssignableFrom(writer)) diff --git a/NCDK/IO/XYZReader.cs b/NCDK/IO/XYZReader.cs index 31b469c0..07c12593 100644 --- a/NCDK/IO/XYZReader.cs +++ b/NCDK/IO/XYZReader.cs @@ -26,6 +26,7 @@ using NCDK.Numerics; using System; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -101,7 +102,7 @@ private IChemFile ReadChemFile(IChemFile file) { // parse frame by frame string token = line.Split('\t', ' ', ',', ';')[0]; - number_of_atoms = int.Parse(token); + number_of_atoms = int.Parse(token, NumberFormatInfo.InvariantInfo); string info = input.ReadLine(); IChemModel chemModel = file.Builder.NewChemModel(); @@ -119,7 +120,7 @@ private IChemFile ReadChemFile(IChemFile file) var comment = m.GetProperty(CDKPropertyName.Comment, ""); comment = comment + line.Substring(1).Trim(); m.SetProperty(CDKPropertyName.Comment, comment); - Debug.WriteLine("Found and set comment: ", comment); + Debug.WriteLine($"Found and set comment: {comment}"); i--; // a comment line does not count as an atom } else @@ -136,10 +137,10 @@ private IChemFile ReadChemFile(IChemFile file) else { string atomtype = tokenizer[0]; - x = double.Parse(tokenizer[1]); - y = double.Parse(tokenizer[2]); - z = double.Parse(tokenizer[3]); - if (fields == 8) charge = double.Parse(tokenizer[4]); + x = double.Parse(tokenizer[1], NumberFormatInfo.InvariantInfo); + y = double.Parse(tokenizer[2], NumberFormatInfo.InvariantInfo); + z = double.Parse(tokenizer[3], NumberFormatInfo.InvariantInfo); + if (fields == 8) charge = double.Parse(tokenizer[4], NumberFormatInfo.InvariantInfo); IAtom atom = file.Builder.NewAtom(atomtype, new Vector3(x, y, z)); atom.Charge = charge; diff --git a/NCDK/IO/ZMatrixReader.cs b/NCDK/IO/ZMatrixReader.cs index ce433e6b..6d8223dc 100644 --- a/NCDK/IO/ZMatrixReader.cs +++ b/NCDK/IO/ZMatrixReader.cs @@ -25,6 +25,7 @@ using NCDK.Geometries; using NCDK.IO.Formats; using System; +using System.Globalization; using System.IO; namespace NCDK.IO @@ -100,7 +101,7 @@ private IChemFile ReadChemFile(IChemFile file) // Debug.WriteLine("lauf"); // parse frame by frame string token = Strings.Tokenize(line, '\t', ' ', ',', ';')[0]; - number_of_atoms = int.Parse(token); + number_of_atoms = int.Parse(token, NumberFormatInfo.InvariantInfo); string info = input.ReadLine(); IChemModel chemModel = file.Builder.NewChemModel(); @@ -138,7 +139,7 @@ private IChemFile ReadChemFile(IChemFile file) da_atom[i] = -1; var tokens = Strings.Tokenize(line, '\t', ' ', ',', ';'); - int fields = int.Parse(tokens[0]); + int fields = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo); if (fields < Math.Min(i * 2 + 1, 7)) { @@ -152,28 +153,28 @@ private IChemFile ReadChemFile(IChemFile file) else if (i == 1) { types[i] = tokens[1]; - d_atom[i] = int.Parse(tokens[2]) - 1; - d[i] = double.Parse(tokens[3]); + d_atom[i] = int.Parse(tokens[2], NumberFormatInfo.InvariantInfo) - 1; + d[i] = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo); i++; } else if (i == 2) { types[i] = tokens[1]; - d_atom[i] = int.Parse(tokens[2]) - 1; - d[i] = double.Parse(tokens[3]); - a_atom[i] = int.Parse(tokens[4]) - 1; - a[i] = double.Parse(tokens[5]); + d_atom[i] = int.Parse(tokens[2], NumberFormatInfo.InvariantInfo) - 1; + d[i] = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo); + a_atom[i] = int.Parse(tokens[4], NumberFormatInfo.InvariantInfo) - 1; + a[i] = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo); i++; } else { types[i] = tokens[1]; - d_atom[i] = int.Parse(tokens[2]) - 1; - d[i] = double.Parse(tokens[3]); - a_atom[i] = int.Parse(tokens[4]) - 1; - a[i] = double.Parse(tokens[5]); - da_atom[i] = int.Parse(tokens[6]) - 1; - da[i] = double.Parse(tokens[7]); + d_atom[i] = int.Parse(tokens[2], NumberFormatInfo.InvariantInfo) - 1; + d[i] = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo); + a_atom[i] = int.Parse(tokens[4], NumberFormatInfo.InvariantInfo) - 1; + a[i] = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo); + da_atom[i] = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo) - 1; + da[i] = double.Parse(tokens[7], NumberFormatInfo.InvariantInfo); i++; } } diff --git a/NCDK/IPDBPolymer.cs b/NCDK/IPDBPolymer.cs index 5f8ef248..4de5ec10 100644 --- a/NCDK/IPDBPolymer.cs +++ b/NCDK/IPDBPolymer.cs @@ -37,7 +37,7 @@ namespace NCDK // @cdk.keyword biopolymer // @cdk.keyword pdbpolymer public interface IPDBPolymer - : IBioPolymer + : IBioPolymer { /// /// Adds the atom oAtom without specifying a Monomer or a Strand. Therefore the @@ -56,10 +56,10 @@ public interface IPDBPolymer void AddAtom(IPDBAtom oAtom, IMonomer oMonomer, IStrand oStrand); /// - /// Adds the PDBStructure structure a this PDBPolymer. + /// Adds the structure a this . /// - /// The PDBStructure to add - void Add(IPDBStructure structure); + /// The to add + void Add(IPDBStructure structureToAdd); /// /// Returns a Collection containing the PDBStructure in the PDBPolymer. diff --git a/NCDK/IRing.cs b/NCDK/IRing.cs index 2de4ec25..f34e41da 100644 --- a/NCDK/IRing.cs +++ b/NCDK/IRing.cs @@ -50,6 +50,6 @@ public interface IRing /// /// The sum of all bond orders in the ring. /// - int BondOrderSum { get; } + int GetBondOrderSum(); } } diff --git a/NCDK/IStereoElement.cs b/NCDK/IStereoElement.cs index df3f5aa5..4d000b60 100644 --- a/NCDK/IStereoElement.cs +++ b/NCDK/IStereoElement.cs @@ -43,20 +43,10 @@ namespace NCDK // @author Egon Willighagen // @author John Mayfield // @cdk.keyword stereochemistry - public interface IStereoElement - : IReadOnlyStereoElement - where TFocus : IChemObject - where TCarriers : IChemObject - { - /// - /// The carriers of the stereochemistry - /// - IList Carriers { get; } - } - - public interface IReadOnlyStereoElement + public interface IStereoElement : ICDKObject where TFocus : IChemObject + where TCarriers : IChemObject { /// /// Does the stereo element contain the provided atom. @@ -73,16 +63,16 @@ public interface IReadOnlyStereoElement /// /// The carriers of the stereochemistry /// - IReadOnlyList ReadOnlyCarriers { get; } + IReadOnlyList Carriers { get; } /// /// The configuration class of the stereochemistry. /// - StereoElement.Classes Class { get; } + StereoClass Class { get; } /// /// The configuration of the stereochemistry. /// - StereoElement.Configuration Configure { get; set; } + StereoConfigurations Configure { get; set; } } } diff --git a/NCDK/ITetrahedralChirality.cs b/NCDK/ITetrahedralChirality.cs index ce2f06e1..a30d5cc6 100644 --- a/NCDK/ITetrahedralChirality.cs +++ b/NCDK/ITetrahedralChirality.cs @@ -48,7 +48,7 @@ public interface ITetrahedralChirality /// the chiral atom (). /// /// an array of four s. - IList Ligands { get; } + IReadOnlyList Ligands { get; set; } IAtom ChiralAtom { get; } TetrahedralStereo Stereo { get; set; } } diff --git a/NCDK/IncludeExamples.xml b/NCDK/IncludeExamples.xml index d22da048..1c52cb8b 100644 --- a/NCDK/IncludeExamples.xml +++ b/NCDK/IncludeExamples.xml @@ -2,7 +2,7 @@ ElectronDonation model = ElectronDonation.DaylightModel; - ICycleFinder cycles = Cycles.Or(Cycles.AllFinder, Cycles.GetAllFinder(6)); + ICycleFinder cycles = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(6)); Aromaticity aromaticity = new Aromaticity(model, cycles); // apply our configured model to each molecule @@ -18,13 +18,13 @@ // mimics the DoubleBondAcceptingAromaticityDetector Aromaticity aromaticity_exo = new Aromaticity(ElectronDonation.CDKAllowingExocyclicModel, Cycles.CDKAromaticSetFinder); // a good model for writing SMILES - Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); // a good model for writing MDL/Mol2 - Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllFinder); + Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllSimpleFinder); - Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); try @@ -39,7 +39,7 @@ - Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); try { @@ -59,7 +59,7 @@ - new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllFinder, Cycles.RelevantFinder)); + new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllSimpleFinder, Cycles.RelevantFinder)); @@ -106,7 +106,7 @@ - IsotopeFactory factory = XMLIsotopeFactory.GetInstance(Default.ChemObjectBuilder.Instance); + IsotopeFactory factory = XMLIsotopeFactory.GetInstance(ChemObjectBuilder.Instance); IIsotope major = factory.GetMajorIsotope("H"); @@ -193,21 +193,21 @@ var molecule = new AtomContainer(); var fingerprinter = new Fingerprinter(); var fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 1024 by default + Console.WriteLine(fingerprint.Length); // returns 1024 by default var molecule = new AtomContainer(); var fingerprinter = new HybridizationFingerprinter(); var fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 1024 by default + Console.WriteLine(fingerprint.Length); // returns 1024 by default var molecule = new AtomContainer(); IFingerprinter fingerprinter = new PubchemFingerprinter(Silent.ChemObjectBuilder.Instance); IBitFingerprint fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 881 + Console.WriteLine(fingerprint.Length); // returns 881 @@ -215,10 +215,10 @@ AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); var fingerprinter = new ShortestPathFingerprinter(); var fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 1024 by default + Console.WriteLine(fingerprint.Length); // returns 1024 by default - + MmffAtomTypeMatcher mmffAtomTypes = new MmffAtomTypeMatcher(); foreach (var container in containers) { @@ -226,7 +226,7 @@ } - + IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); Mmff mmff = new Mmff(); mmff.AssignAtomTypes(mol); @@ -235,7 +235,7 @@ - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -258,7 +258,7 @@ - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -282,8 +282,8 @@ - AtomContainer ac1 = new AtomContainer(); // molecule 1 - AtomContainer ac2 = new AtomContainer(); // molecule 2 + var ac1 = new AtomContainer(); // molecule 1 + var ac2 = new AtomContainer(); // molecule 2 try { KabschAlignment sa = new KabschAlignment(ac1.Atoms, ac2.Atoms); @@ -347,10 +347,8 @@ - // Generate factory - if native code does not load - InChIGeneratorFactory factory = new InChIGeneratorFactory(); - // Get InChIToStructure - InChIToStructure intostruct = factory.GetInChIToStructure(inchi, Default.ChemObjectBuilder.Instance); + // Get InChIToStructure + InChIToStructure intostruct = InChIToStructure.FromInChI(inchi, ChemObjectBuilder.Instance); InChIReturnCode ret = intostruct.ReturnStatus; if (ret == InChIReturnCode.Warning) @@ -522,8 +520,8 @@ namespace NCDK.Graphs int fragmentCount = fragments.Count; - - ICycleFinder cf = Cycles.AllFinder; + + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -539,7 +537,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -555,7 +553,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -571,7 +569,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -587,7 +585,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -603,7 +601,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -619,7 +617,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -635,7 +633,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -651,7 +649,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -668,12 +666,12 @@ namespace NCDK.Graphs // all cycles or all cycles size <= 6 - ICycleFinder cf = Cycles.Or(Cycles.AllFinder, Cycles.GetAllFinder(6)); + ICycleFinder cf = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(6)); // all cycles or relevant or essential - ICycleFinder cf = Cycles.Or(Cycles.AllFinder, Cycles.Or(Cycles.RelevantFinder, Cycles.EssentialFinder)); + ICycleFinder cf = Cycles.Or(Cycles.AllSimpleFinder, Cycles.Or(Cycles.RelevantFinder, Cycles.EssentialFinder)); @@ -1039,7 +1037,7 @@ namespace NCDK.Graphs string filename = "/Users/rguha/conf2.sdf"; using (var srm = new FileStream(filename, FileMode.Open)) { - IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(srm, Default.ChemObjectBuilder.Instance); + IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(srm, ChemObjectBuilder.Instance); foreach (var cc in reader) { // do something @@ -1051,7 +1049,7 @@ namespace NCDK.Graphs using (var srm = new FileStream("../zinc-structures/ZINC_subset3_3D_charged_wH_maxmin1000.sdf", FileMode.Open)) { - EnumerableSDFReader reader = new EnumerableSDFReader(srm, Default.ChemObjectBuilder.Instance); + EnumerableSDFReader reader = new EnumerableSDFReader(srm, ChemObjectBuilder.Instance); foreach (var molecule in reader) { // do something @@ -1062,7 +1060,7 @@ namespace NCDK.Graphs // create the manager and add a setting var manager = new SettingManager<BooleanIOSetting>(); - manager.Add(new BooleanIOSetting("Sample", IOSetting.Importance.Medium, "This is a sample?", "true")); + manager.Add(new BooleanIOSetting("Sample", Importance.Medium, "This is a sample?", "true")); // check the setting is present (case insensitive) if (manager.Has("sample")) @@ -1444,7 +1442,7 @@ namespace NCDK.Graphs - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride IAtomContainer SMILESquery = sp.ParseSmiles("CC"); // ethylene IQueryAtomContainer query = QueryAtomContainerCreator.CreateBasicQueryContainer(SMILESquery); @@ -1488,12 +1486,12 @@ namespace NCDK.Graphs - ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(Default.ChemObjectBuilder.Instance); + ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(ChemObjectBuilder.Instance); IAtomContainer molecule = mb3d.Generate3DCoordinates(mol, false); - QueryAtomContainer query = new QueryAtomContainer(Default.ChemObjectBuilder.Instance); + QueryAtomContainer query = new QueryAtomContainer(ChemObjectBuilder.Instance); PharmacophoreQueryAtom o = new PharmacophoreQueryAtom("D", "[OX1]"); PharmacophoreQueryAtom n1 = new PharmacophoreQueryAtom("A", "[N]"); @@ -1514,7 +1512,7 @@ namespace NCDK.Graphs string filename = "/Users/rguha/pcore1.sdf"; using (var srm = new FileStream(filename, FileMode.Open)) { - foreach (var conformers in new IEnumerableMDLConformerReader(srm, Default.ChemObjectBuilder.Instance)) + foreach (var conformers in new IEnumerableMDLConformerReader(srm, ChemObjectBuilder.Instance)) { bool firstTime = true; foreach (var conf in conformers) @@ -1553,9 +1551,9 @@ namespace NCDK.Graphs var classNames = DescriptorEngine.GetDescriptorClassNameByPackage("NCDK.QSRA.Descriptors.Moleculars", null); - DescriptorEngine engine = new DescriptorEngine(classNames, Default.ChemObjectBuilder.Instance); - var instances = engine.InstantiateDescriptors(classNames); - var specs = engine.InitializeSpecifications(instances); + DescriptorEngine engine = new DescriptorEngine(classNames, ChemObjectBuilder.Instance); + var instances = DescriptorEngine.InstantiateDescriptors(classNames); + var specs = instances.Select(n => n.Specification).ToList(); engine.SetDescriptorInstances(instances); engine.SetDescriptorSpecifications(specs); @@ -1585,7 +1583,7 @@ namespace NCDK.Graphs // using static NCDK.RingSearches.AllRingsFinder.Threshold; - AllRingsFinder arf = AllRingsFinder.UsingThreshold(PubChem_99); + AllRingsFinder arf = AllRingsFinder.UsingThreshold(Threshold.PubChem99); @@ -1660,7 +1658,7 @@ namespace NCDK.Graphs - IAtomContainer mol = new Smiles.SmilesParser(Default.ChemObjectBuilder.Instance).ParseSmiles("c1cc(cc2cc(ccc12)C3C4CC34)C6CC5CCC6(C5)"); + IAtomContainer mol = new Smiles.SmilesParser(ChemObjectBuilder.Instance).ParseSmiles("c1cc(cc2cc(ccc12)C3C4CC34)C6CC5CCC6(C5)"); RingSearch ringSearch = new RingSearch(mol); int[][] fused = ringSearch.Fused(); @@ -1686,6 +1684,24 @@ namespace NCDK.Graphs BitArray fingerprint1 = fingerprinter.GetBitFingerprint(molecule1).AsBitSet(); BitArray fingerprint2 = fingerprinter.GetBitFingerprint(molecule2).AsBitSet(); double tanimoto_coefficient = Tanimoto.Calculate(fingerprint1, fingerprint2); + + + + IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; + var smipar = new SmilesParser(bldr); + + IAtomContainer mol = smipar.ParseSmiles("[nH]1ccc2c1cccc2"); + var subsmarts = new SmartsFragmentExtractor(mol); + + string smarts; + // smarts=[nH1v3X3+0][cH1v4X3+0][cH1v4X3+0][cH0v4X3+0] + // hits =1 + smarts = subsmarts.Generate(new int[]{0,1,3,4}); + + subsmarts.SetMode(SubstructureSelectionMode.JCompoundMapper); + // smarts=n(ccc(a)a)a + // hits = 0 - one of the 'a' atoms needs to match the nitrogen + smarts = subsmarts.Generate(new int[]{0,1,3,4}); @@ -1701,14 +1717,14 @@ namespace NCDK.Graphs - SMARTSParser parser = new SMARTSParser(new StringReader("C*C")); - ASTStart ast = parser.Start(); - SmartsQueryVisitor visitor = new SmartsQueryVisitor(Silent.ChemObjectBuilder.Instance); + SMARTSParser parser = new SMARTSParser(new StringReader("C*C")); + ASTStart ast = parser.Start(); + SmartsQueryVisitor visitor = new SmartsQueryVisitor(Silent.ChemObjectBuilder.Instance); QueryAtomContainer query = (QueryAtomContainer)visitor.Visit(ast, null); - Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", Default.ChemObjectBuilder.Instance); + Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", ChemObjectBuilder.Instance); foreach (var ac in acs) { @@ -1720,7 +1736,7 @@ namespace NCDK.Graphs - Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", Default.ChemObjectBuilder.Instance); + Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", ChemObjectBuilder.Instance); foreach (var ac in acs) { @@ -1729,7 +1745,7 @@ namespace NCDK.Graphs - Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", Default.ChemObjectBuilder.Instance); + Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", ChemObjectBuilder.Instance); int nUniqueHits = 0; foreach (var ac in acs) { @@ -1738,23 +1754,23 @@ namespace NCDK.Graphs - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); - SMARTSQueryTool querytool = new SMARTSQueryTool("O=CO", Silent.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("O=CO", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); if (status) { int nmatch = querytool.MatchesCount; - IList<IList<int>> mappings = querytool.GetMatchingAtoms(); - for (int i = 0; i < nmatch; i++) + var mappings = querytool.GetMatchingAtoms(); + foreach (var atomIndices in mappings) { - IList<int> atomIndices = mappings[i]; + // do something } } - SMARTSQueryTool sqt = new SMARTSQueryTool(someSmartsPattern, Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool(someSmartsPattern, ChemObjectBuilder.Instance); sqt.SetAromaticity(new Aromaticity(ElectronDonation.CDKModel, Cycles.CDKAromaticSetFinder)); foreach (var molecule in molecules) { @@ -1786,17 +1802,17 @@ namespace NCDK.Smiles } - - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Isomeric); + + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Isomeric); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo | SmiFlavor.AtomicMass); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo | SmiFlavors.AtomicMass); IAtomContainer ethanol = TestMoleculeFactory.MakeEthanol(); - sg = new SmilesGenerator(SmiFlavor.Generic); + sg = new SmilesGenerator(SmiFlavors.Generic); smi = sg.Create(ethanol); // CCO, C(C)O, C(O)C, or OCC sg = SmilesGenerator.Unique(); @@ -1807,10 +1823,10 @@ namespace NCDK.Smiles IAtomContainer benzene = TestMoleculeFactory.MakeBenzene(); // 'benzene' molecule has no arom flags, we always get Kekulé output - sg = new SmilesGenerator(SmiFlavor.Generic); + sg = new SmilesGenerator(SmiFlavors.Generic); smi = sg.Create(benzene); // C1=CC=CC=C1 - sg = new SmilesGenerator(SmiFlavor.Generic | SmiFlavor.UseAromaticSymbols); + sg = new SmilesGenerator(SmiFlavors.Generic | SmiFlavors.UseAromaticSymbols); smi = sg.Create(benzene); // C1=CC=CC=C1 flags not set! // Note, in practice we'd use an aromaticity algorithm @@ -1820,16 +1836,16 @@ namespace NCDK.Smiles b.IsAromatic = true; // 'benzene' molecule now has arom flags, we always get aromatic SMILES if we request it - sg = new SmilesGenerator(SmiFlavor.Generic); + sg = new SmilesGenerator(SmiFlavors.Generic); smi = sg.Create(benzene); // C1=CC=CC=C1 - sg = new SmilesGenerator(SmiFlavor.Generic | SmiFlavor.UseAromaticSymbols); + sg = new SmilesGenerator(SmiFlavors.Generic | SmiFlavors.UseAromaticSymbols); smi = sg.Create(benzene); // c1ccccc1 IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); - SmilesGenerator sg = new SmilesGenerator(SmiFlavor.Generic); + SmilesGenerator sg = new SmilesGenerator(SmiFlavors.Generic); int n = mol.Atoms.Count; int[] order = new int[n]; @@ -1848,11 +1864,11 @@ namespace NCDK.Smiles - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.UseAromaticSymbols); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.UseAromaticSymbols); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.AtomAtomMap); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.AtomAtomMap); smigen.CreateSMILES(container); // C[CH2:4]O second atom has class = 4 @@ -1916,8 +1932,8 @@ namespace NCDK.Smiles var c2 = m.Atoms[2].GetProperty<int>(CDKPropertyName.AtomAtomMapping); // null - - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride IAtomContainer SMILESquery = sp.ParseSmiles("CC"); // acetic acid anhydride IQueryAtomContainer query = QueryAtomContainerCreator.CreateBasicQueryContainer(SMILESquery); @@ -1925,7 +1941,7 @@ namespace NCDK.Smiles - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // Benzene IAtomContainer A1 = sp.ParseSmiles("C1=CC=CC=C1"); // Napthalene @@ -1960,7 +1976,7 @@ namespace NCDK.Smiles - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // Benzene IAtomContainer A1 = sp.ParseSmiles("C1=CC=CC=C1"); // Napthalene @@ -2082,7 +2098,7 @@ namespace NCDK.Smiles - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); parser.IsPreservingAromaticity = true; IAtomContainer biphenyl = parser.ParseSmiles("c1cccc(c1)c1ccccc1"); @@ -2119,7 +2135,7 @@ namespace NCDK.Smiles var features = new XYZFormat().SupportedDataFeatures; - bool has3DCoords = (features & HAS_3D_COORDINATES) == HAS_3D_COORDINATES; + bool has3DCoords = (features & DataFeatures.Has3DCoordinates) == DataFeatures.Has3DCoordinates; @@ -2162,7 +2178,7 @@ namespace NCDK.Smiles var reader = new IEnumerableMDLConformerReader( new FileStream(filename, FileMode.Open), - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); foreach (ConformerContainer cc in reader) { foreach (var conformer in cc) diff --git a/NCDK/Indexes/CASNumber.cs b/NCDK/Indexes/CASNumber.cs index 660ea5ea..41683fea 100644 --- a/NCDK/Indexes/CASNumber.cs +++ b/NCDK/Indexes/CASNumber.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System.Globalization; using System.Text.RegularExpressions; namespace NCDK.Indexes @@ -67,7 +68,7 @@ public static bool IsValid(string casNumber) string part1 = matcher.Groups[1].Value; string part2 = matcher.Groups[2].Value; string part3 = matcher.Groups[3].Value; - int part1value = int.Parse(part1); + int part1value = int.Parse(part1, NumberFormatInfo.InvariantInfo); if (part1value < 50) { overall = false; @@ -76,7 +77,7 @@ public static bool IsValid(string casNumber) else { int digit = CASNumber.CalculateCheckDigit(part1, part2); - overall = overall && (digit == int.Parse(part3)); + overall = overall && (digit == int.Parse(part3, NumberFormatInfo.InvariantInfo)); } } @@ -86,12 +87,12 @@ public static bool IsValid(string casNumber) private static int CalculateCheckDigit(string part1, string part2) { int total = 0; - total = total + 1 * int.Parse(part2.Substring(1, 1)); - total = total + 2 * int.Parse(part2.Substring(0, 1)); + total = total + 1 * int.Parse(part2.Substring(1, 1), NumberFormatInfo.InvariantInfo); + total = total + 2 * int.Parse(part2.Substring(0, 1), NumberFormatInfo.InvariantInfo); int length = part1.Length; for (int i = 0; i < length; i++) { - total = total + (3 + i) * int.Parse(part1.Substring(length - 1 - i, 1)); + total = total + (3 + i) * int.Parse(part1.Substring(length - 1 - i, 1), NumberFormatInfo.InvariantInfo); } return total % 10; } diff --git a/NCDK/IntractableException.cs b/NCDK/IntractableException.cs index 1bc0313b..8420041e 100644 --- a/NCDK/IntractableException.cs +++ b/NCDK/IntractableException.cs @@ -3,6 +3,10 @@ namespace NCDK public sealed class IntractableException : CDKException { + public IntractableException() + { + } + public IntractableException(string message) : base(message) { @@ -17,6 +21,9 @@ public IntractableException(string desc, long t) : this(desc + " did not finish after " + t + " ms.") { } + + public IntractableException(string message, System.Exception innerException) : base(message, innerException) + { + } } } - diff --git a/NCDK/InvalidSmilesException.cs b/NCDK/InvalidSmilesException.cs index 6bf2fc93..fa6a9853 100644 --- a/NCDK/InvalidSmilesException.cs +++ b/NCDK/InvalidSmilesException.cs @@ -33,6 +33,10 @@ namespace NCDK // @cdk.githash public class InvalidSmilesException : CDKException { + public InvalidSmilesException() + { + } + /// /// Constructs a new exception with a custom message. /// diff --git a/NCDK/Isomorphisms/AtomMappingTools.cs b/NCDK/Isomorphisms/AtomMappingTools.cs index 90d46bff..820cda76 100644 --- a/NCDK/Isomorphisms/AtomMappingTools.cs +++ b/NCDK/Isomorphisms/AtomMappingTools.cs @@ -22,6 +22,7 @@ */ using NCDK.Isomorphisms.MCSS; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -42,23 +43,20 @@ public static class AtomMappingTools /// /// a IDictionary of the mapped atoms /// if there is an error in the UniversalIsomorphismTester - public static IDictionary MapAtomsOfAlignedStructures(IAtomContainer firstAtomContainer, + public static void MapAtomsOfAlignedStructures(IAtomContainer firstAtomContainer, IAtomContainer secondAtomContainer, IDictionary mappedAtoms) { - //Debug.WriteLine("**** GT MAP ATOMS ****"); //IDictionary atoms onto each other if (firstAtomContainer.Atoms.Count < 1 & secondAtomContainer.Atoms.Count < 1) { - return mappedAtoms; + return; } RMap map; IAtom atom1; IAtom atom2; - IList list; try { - list = new UniversalIsomorphismTester().GetSubgraphAtomsMap(firstAtomContainer, secondAtomContainer); - //Debug.WriteLine("ListSize:"+list.Count); + var list = new UniversalIsomorphismTester().GetSubgraphAtomsMap(firstAtomContainer, secondAtomContainer); for (int i = 0; i < list.Count; i++) { map = list[i]; @@ -67,9 +65,7 @@ public static IDictionary MapAtomsOfAlignedStructures(IAtomContainer f if (CheckAtomMapping(firstAtomContainer, secondAtomContainer, firstAtomContainer.Atoms.IndexOf(atom1), secondAtomContainer.Atoms.IndexOf(atom2))) { - mappedAtoms.Add(firstAtomContainer.Atoms.IndexOf(atom1), - secondAtomContainer.Atoms.IndexOf(atom2)); - // Debug.WriteLine("#:"+countMappedAtoms+" Atom:"+firstAtomContainer.Atoms.IndexOf(atom1)+" is mapped to Atom:"+secondAtomContainer.Atoms.IndexOf(atom2)); + mappedAtoms.Add(firstAtomContainer.Atoms.IndexOf(atom1), secondAtomContainer.Atoms.IndexOf(atom2)); } else { @@ -79,20 +75,19 @@ public static IDictionary MapAtomsOfAlignedStructures(IAtomContainer f } catch (CDKException e) { - throw new CDKException("Error in UniversalIsomorphismTester due to:" + e.ToString(), e); + throw new CDKException($"Error in UniversalIsomorphismTester due to: {e.Message}", e); } - return mappedAtoms; } private static bool CheckAtomMapping(IAtomContainer firstAC, IAtomContainer secondAC, int posFirstAtom, int posSecondAtom) { - IAtom firstAtom = firstAC.Atoms[posFirstAtom]; - IAtom secondAtom = secondAC.Atoms[posSecondAtom]; - // XXX: floating point comparision! - if (firstAtom.Symbol.Equals(secondAtom.Symbol) - && firstAC.GetConnectedAtoms(firstAtom).Count() == secondAC.GetConnectedAtoms(secondAtom).Count() - && firstAtom.BondOrderSum == secondAtom.BondOrderSum - && firstAtom.MaxBondOrder == secondAtom.MaxBondOrder) + var firstAtom = firstAC.Atoms[posFirstAtom]; + var secondAtom = secondAC.Atoms[posSecondAtom]; + // XXX: floating point comparison! + if (firstAtom.Symbol.Equals(secondAtom.Symbol, StringComparison.Ordinal) + && firstAC.GetConnectedAtoms(firstAtom).Count() == secondAC.GetConnectedAtoms(secondAtom).Count() + && firstAtom.BondOrderSum == secondAtom.BondOrderSum + && firstAtom.MaxBondOrder == secondAtom.MaxBondOrder) { return true; } diff --git a/NCDK/Isomorphisms/AtomMatcher.cs b/NCDK/Isomorphisms/AtomMatcher.cs index f66f2fd6..11851834 100644 --- a/NCDK/Isomorphisms/AtomMatcher.cs +++ b/NCDK/Isomorphisms/AtomMatcher.cs @@ -110,7 +110,7 @@ public override bool Matches(IAtom atom1, IAtom atom2) /// /// an atom /// the atomic number - private int GetAtomicNumber(IAtom atom) + private static int GetAtomicNumber(IAtom atom) { int? elem = atom.AtomicNumber; if (elem != null) return elem.Value; diff --git a/NCDK/Isomorphisms/ComponentGrouping.cs b/NCDK/Isomorphisms/ComponentGrouping.cs index d62d03c6..f09ad40e 100644 --- a/NCDK/Isomorphisms/ComponentGrouping.cs +++ b/NCDK/Isomorphisms/ComponentGrouping.cs @@ -23,6 +23,7 @@ */ using NCDK.Graphs; +using System; namespace NCDK.Isomorphisms { @@ -72,7 +73,7 @@ private static int[] DetermineComponents(IAtomContainer target) int[] components = null; // no atoms -> no components if (target.IsEmpty()) - components = new int[0]; + components = Array.Empty(); // defined by reaction grouping if (components == null && target.Atoms[0].GetProperty(CDKPropertyName.ReactionGroup) != null) { diff --git a/NCDK/Isomorphisms/IsomorphismTester.cs b/NCDK/Isomorphisms/IsomorphismTester.cs index fcffee98..855a6679 100644 --- a/NCDK/Isomorphisms/IsomorphismTester.cs +++ b/NCDK/Isomorphisms/IsomorphismTester.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Graphs.Canon; +using NCDK.Graphs.Invariant; using System; namespace NCDK.Isomorphisms @@ -37,7 +37,6 @@ namespace NCDK.Isomorphisms // @author steinbeck // @cdk.created 2001-09-10 // @cdk.keyword isomorphism - [Serializable] public class IsomorphismTester { long[] baseTable; @@ -102,7 +101,7 @@ public bool IsIsomorphic(IAtomContainer mol2) { atom1 = base_.Atoms[f]; atom2 = compare.Atoms[g]; - if (!(atom1.Symbol.Equals(atom2.Symbol)) + if (!(atom1.Symbol.Equals(atom2.Symbol, StringComparison.Ordinal)) && atom1.ImplicitHydrogenCount == atom2.ImplicitHydrogenCount) { return false; diff --git a/NCDK/Isomorphisms/MCSS/RGraph.cs b/NCDK/Isomorphisms/MCSS/RGraph.cs index 81c8d429..89539c9e 100644 --- a/NCDK/Isomorphisms/MCSS/RGraph.cs +++ b/NCDK/Isomorphisms/MCSS/RGraph.cs @@ -110,7 +110,7 @@ public class RGraph // an RGraph is a list of RGraph nodes // each node keeping track of its // neighbors. - IList graph = null; + private List graph = null; // maximal number of iterations before // search break @@ -126,14 +126,14 @@ public class RGraph /// /// The size of the second of the two compared graphs /// - public int SecondGraphSize = 0; + public int SecondGraphSize { get; set; } = 0; // constrains BitArray c1 = null; BitArray c2 = null; // current solution list - IList solutionList = null; + List solutionList = null; // flag to define if we want to get all possible 'mappings' bool findAllMap = false; @@ -180,7 +180,7 @@ public void Clear() /// Returns the graph object of this RGraph. /// /// The graph object, a list - public IList Graph => this.graph; + public IReadOnlyList Graph => this.graph; /// /// Adds a new node to the RGraph. @@ -340,11 +340,11 @@ private void Solution(BitArray traversed) break; BitArray sol = solutionList[pp]; - if (!BitArrays.AreEqual(sol, traversed)) + if (!BitArrays.Equals(sol, traversed)) { // if we asked to save all 'mappings' then keep this mapping if (findAllMap - && (BitArrays.AreEqual(projG1, ProjectG1(sol)) || BitArrays.AreEqual(projG2, ProjectG2(sol)))) + && (BitArrays.Equals(projG1, ProjectG1(sol)) || BitArrays.Equals(projG2, ProjectG2(sol)))) { // do nothing } @@ -419,7 +419,7 @@ private bool MustContinue(BitArray potentialNode) break; // if we want every 'mappings' do not stop - if (findAllMap && (BitArrays.AreEqual(projG1, ProjectG1(sol)) || BitArrays.AreEqual(projG2, ProjectG2(sol)))) + if (findAllMap && (BitArrays.Equals(projG1, ProjectG1(sol)) || BitArrays.Equals(projG2, ProjectG2(sol)))) { // do nothing } @@ -466,7 +466,7 @@ private BitArray BuildB(BitArray c1, BitArray c2) /// Returns the list of solutions. /// /// The solution list - public IList Solutions => solutionList; + public IReadOnlyList Solutions => solutionList; /// /// Converts a RGraph bitset (set of RNode) @@ -477,9 +477,9 @@ private BitArray BuildB(BitArray c1, BitArray c2) /// /// the BitArray /// the RMap list - public IList BitSetToRMap(BitArray set) + public IReadOnlyList BitSetToRMap(BitArray set) { - IList rMapList = new List(); + var rMapList = new List(); for (int x = BitArrays.NextSetBit(set, 0); x >= 0; x = BitArrays.NextSetBit(set, x + 1)) { @@ -585,7 +585,7 @@ public BitArray ProjectG2(BitArray set) /// a bitSet /// a bitSet /// true if A is contained in B - private bool IsContainedIn(BitArray A, BitArray B) + private static bool IsContainedIn(BitArray A, BitArray B) { bool result = false; @@ -597,7 +597,7 @@ private bool IsContainedIn(BitArray A, BitArray B) BitArray setA = (BitArray)A.Clone(); setA.And(B); - if (BitArrays.AreEqual(setA, A)) + if (BitArrays.Equals(setA, A)) { result = true; } diff --git a/NCDK/Isomorphisms/MCSS/RNode.cs b/NCDK/Isomorphisms/MCSS/RNode.cs index 7c04f961..c57e75ef 100644 --- a/NCDK/Isomorphisms/MCSS/RNode.cs +++ b/NCDK/Isomorphisms/MCSS/RNode.cs @@ -52,12 +52,12 @@ public class RNode /// /// The extension attribute of the RNode object. /// - public BitArray Extension { get; set; } = null; + public BitArray Extension { get; private set; } = null; /// /// The extension attribute of the RNode object. /// - public BitArray Forbidden { get; set; } = null; + public BitArray Forbidden { get; private set; } = null; /// /// Constructor for the RNode object. diff --git a/NCDK/Isomorphisms/Mappings.cs b/NCDK/Isomorphisms/Mappings.cs index 235c3a43..8d2d60c3 100644 --- a/NCDK/Isomorphisms/Mappings.cs +++ b/NCDK/Isomorphisms/Mappings.cs @@ -198,7 +198,7 @@ public int[][] ToArray() /// /// /// iterable of atom-atom mappings - public IEnumerable> ToAtomMap() + public IEnumerable> ToAtomMap() { var mapper = new AtomMaper(query, target); return GetMapping(n => mapper.Apply(n)); @@ -211,7 +211,7 @@ public IEnumerable> ToAtomMap() /// /// /// iterable of bond-bond mappings - public IEnumerable> ToBondMap() + public IEnumerable> ToBondMap() { var mapper = new BondMaper(query, target); return GetMapping(n => mapper.Apply(n)); @@ -224,7 +224,7 @@ public IEnumerable> ToBondMap() /// /// /// iterable of atom-atom and bond-bond mappings - public IEnumerable> ToAtomBondMap() + public IEnumerable> ToAtomBondMap() { var map = new AtomBondMaper(query, target); return GetMapping(n => map.Apply(n)); @@ -289,7 +289,7 @@ public bool AtLeast(int n) public int[] First() { var f = iterable.FirstOrDefault(); - return f ?? new int[0]; + return f ?? Array.Empty(); } /// @@ -348,23 +348,23 @@ public AtomMaper(IAtomContainer query, IAtomContainer target) } /// - public IDictionary Apply(int[] mapping) + public IReadOnlyDictionary Apply(int[] mapping) { var map = new Dictionary(); for (int i = 0; i < mapping.Length; i++) map.Add(query.Atoms[i], target.Atoms[mapping[i]]); - return new ReadOnlyDictionary(map); + return map; } } /// Utility to transform a permutation into the bond-bond map. - public sealed class BondMaper + private sealed class BondMaper { /// The query graph - indicates a presence of edges. private readonly int[][] g1; /// Bond look ups for the query and target. - private readonly GraphUtil.EdgeToBondMap bonds1, bonds2; + private readonly EdgeToBondMap bonds1, bonds2; /// /// Use the provided query and target to obtain the bond instances. @@ -373,14 +373,14 @@ public sealed class BondMaper /// the structure being searched public BondMaper(IAtomContainer query, IAtomContainer target) { - this.bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(query); - this.bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(target); + this.bonds1 = EdgeToBondMap.WithSpaceFor(query); + this.bonds2 = EdgeToBondMap.WithSpaceFor(target); this.g1 = GraphUtil.ToAdjList(query, bonds1); GraphUtil.ToAdjList(target, bonds2); } /// - public IDictionary Apply(int[] mapping) + public IReadOnlyDictionary Apply(int[] mapping) { var map = new Dictionary(); for (int u = 0; u < g1.Length; u++) @@ -393,7 +393,7 @@ public IDictionary Apply(int[] mapping) } } } - return new ReadOnlyDictionary(map); + return map; } } @@ -404,7 +404,7 @@ private sealed class AtomBondMaper private readonly int[][] g1; /// Bond look ups for the query and target. - private readonly GraphUtil.EdgeToBondMap bonds1, bonds2; + private readonly EdgeToBondMap bonds1, bonds2; private IAtomContainer query; private IAtomContainer target; @@ -418,14 +418,14 @@ public AtomBondMaper(IAtomContainer query, IAtomContainer target) { this.query = query; this.target = target; - this.bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(query); - this.bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(target); + this.bonds1 = EdgeToBondMap.WithSpaceFor(query); + this.bonds2 = EdgeToBondMap.WithSpaceFor(target); this.g1 = GraphUtil.ToAdjList(query, bonds1); GraphUtil.ToAdjList(target, bonds2); } /// - public IDictionary Apply(int[] mapping) + public IReadOnlyDictionary Apply(int[] mapping) { var map = new Dictionary(); for (int u = 0; u < g1.Length; u++) diff --git a/NCDK/Isomorphisms/Matchers/CTFileQueryBond.cs b/NCDK/Isomorphisms/Matchers/CTFileQueryBond.cs index 17771829..f966a252 100644 --- a/NCDK/Isomorphisms/Matchers/CTFileQueryBond.cs +++ b/NCDK/Isomorphisms/Matchers/CTFileQueryBond.cs @@ -38,8 +38,10 @@ public class CTFileQueryBond : Silent.Bond, IQueryBond // use Default.Bond inste public enum BondType { Unset = 0, +#pragma warning disable CA1720 // Identifier contains type name Single = 1, Double = 2, +#pragma warning restore CA1720 // Identifier contains type name Triple = 3, Aromatic = 4, SingleOrDouble = 5, @@ -48,7 +50,7 @@ public enum BondType Any = 8, } - private IChemObjectBuilder builder; + private readonly IChemObjectBuilder builder; /// public override IChemObjectBuilder Builder => builder; diff --git a/NCDK/Isomorphisms/Matchers/IRGroupQuery.cs b/NCDK/Isomorphisms/Matchers/IRGroupQuery.cs index 365f9ad2..e9d62c23 100644 --- a/NCDK/Isomorphisms/Matchers/IRGroupQuery.cs +++ b/NCDK/Isomorphisms/Matchers/IRGroupQuery.cs @@ -46,12 +46,12 @@ public interface IRGroupQuery : IChemObject /// /// Root attachment points = bonds that connect R pseudo-atoms to the scaffold. /// - IDictionary> RootAttachmentPoints { get; set; } + IReadOnlyDictionary> RootAttachmentPoints { get; set; } /// /// the R-group definitions (substituents). /// - IDictionary RGroupDefinitions { get; set; } + IReadOnlyDictionary RGroupDefinitions { get; set; } /// /// the total number of atom containers (count the root plus all substituents). @@ -62,7 +62,7 @@ public interface IRGroupQuery : IChemObject /// All the substituent atom containers, in other words the atom containers /// defined in this except for the root structure. /// - IList GetSubstituents(); + IEnumerable GetSubstituents(); /// /// Checks validity of the RGroupQuery. @@ -85,6 +85,6 @@ public interface IRGroupQuery : IChemObject /// Produces all combinations of the root structure (scaffold) with the R-groups /// substituted in valid ways, using each R-group's definitions and conditions. /// - IList GetAllConfigurations(); + IEnumerable GetAllConfigurations(); } } diff --git a/NCDK/Isomorphisms/Matchers/InverseSymbolSetQueryAtom.cs b/NCDK/Isomorphisms/Matchers/InverseSymbolSetQueryAtom.cs index ff1f1c5a..dea24457 100644 --- a/NCDK/Isomorphisms/Matchers/InverseSymbolSetQueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/InverseSymbolSetQueryAtom.cs @@ -24,10 +24,10 @@ namespace NCDK.Isomorphisms.Matchers { /// - /// A QueryAtom that matches all symbols but those in this container. You may - /// add symbols to this container. This QueryAtom will only give a match if it - /// does NOT contain the symbol of the Atom to match (example: add "C" to get a - /// match for all non-"C"-Atoms). + /// A QueryAtom that matches all symbols but those in this container. You may + /// add symbols to this container. This QueryAtom will only give a match if it + /// does NOT contain the symbol of the Atom to match (example: add "C" to get a + /// match for all non-"C"-Atoms). /// // @author kha // @cdk.githash @@ -45,8 +45,6 @@ public InverseSymbolSetQueryAtom(IChemObjectBuilder builder) : base(builder) { } - public void SetOperator(string str) { } - /// /// The matches implementation of the interface. /// diff --git a/NCDK/Isomorphisms/Matchers/QueryAtom.cs b/NCDK/Isomorphisms/Matchers/QueryAtom.cs index a117b0c4..820f9327 100644 --- a/NCDK/Isomorphisms/Matchers/QueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/QueryAtom.cs @@ -28,18 +28,19 @@ public abstract class QueryAtom : Silent.Atom, IQueryAtom { public abstract bool Matches(IAtom atom); - public QueryAtom(string symbol, IChemObjectBuilder builder) + protected QueryAtom(string symbol, IChemObjectBuilder builder) : this(builder) { this.symbol = symbol; this.atomicNumber = PeriodicTable.GetAtomicNumber(symbol); } - private IChemObjectBuilder builder; + private readonly IChemObjectBuilder builder; + /// public override IChemObjectBuilder Builder => builder; - public QueryAtom(IChemObjectBuilder builder) + protected QueryAtom(IChemObjectBuilder builder) { this.builder = builder; } diff --git a/NCDK/Isomorphisms/Matchers/QueryAtomContainer.cs b/NCDK/Isomorphisms/Matchers/QueryAtomContainer.cs index a4c2ef55..a250c4a5 100644 --- a/NCDK/Isomorphisms/Matchers/QueryAtomContainer.cs +++ b/NCDK/Isomorphisms/Matchers/QueryAtomContainer.cs @@ -34,7 +34,8 @@ public override string ToString() return sb.ToString(); } - private IChemObjectBuilder builder; + private readonly IChemObjectBuilder builder; + /// public override IChemObjectBuilder Builder => builder; diff --git a/NCDK/Isomorphisms/Matchers/QueryAtomContainerCreator.cs b/NCDK/Isomorphisms/Matchers/QueryAtomContainerCreator.cs index f1df3919..e0019adb 100644 --- a/NCDK/Isomorphisms/Matchers/QueryAtomContainerCreator.cs +++ b/NCDK/Isomorphisms/Matchers/QueryAtomContainerCreator.cs @@ -21,11 +21,11 @@ namespace NCDK.Isomorphisms.Matchers { // @cdk.module isomorphism // @cdk.githash - public class QueryAtomContainerCreator + public static class QueryAtomContainerCreator { /// /// Creates a with 's, 's and - /// 's. If a IBond of the input is flagged + /// 's. If a of the input is flagged /// aromatic, then it disregards bond order information and only match against /// an aromatic target atom instead. /// @@ -33,7 +33,7 @@ public class QueryAtomContainerCreator /// The new created from container. public static QueryAtomContainer CreateBasicQueryContainer(IAtomContainer container) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { queryContainer.Atoms.Add(new SymbolQueryAtom(container.Atoms[i])); @@ -50,7 +50,7 @@ public static QueryAtomContainer CreateBasicQueryContainer(IAtomContainer contai else { queryContainer.Bonds.Add(new OrderQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); } } return queryContainer; @@ -64,7 +64,7 @@ public static QueryAtomContainer CreateBasicQueryContainer(IAtomContainer contai /// The new QueryAtomContainer created from container. public static QueryAtomContainer CreateSymbolAndBondOrderQueryContainer(IAtomContainer container) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { queryContainer.Atoms.Add(new SymbolQueryAtom(container.Atoms[i])); @@ -74,20 +74,20 @@ public static QueryAtomContainer CreateSymbolAndBondOrderQueryContainer(IAtomCon int index1 = container.Atoms.IndexOf(bond.Begin); int index2 = container.Atoms.IndexOf(bond.End); queryContainer.Bonds.Add(new OrderQueryBondOrderOnly((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); } return queryContainer; } /// - /// Creates a with 's and - /// 's. + /// Creates a with 's and + /// 's. /// /// The that stands as model /// The new created from container. public static QueryAtomContainer CreateSymbolAndChargeQueryContainer(IAtomContainer container) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { queryContainer.Atoms.Add(new SymbolAndChargeQueryAtom(container.Atoms[i])); @@ -99,12 +99,12 @@ public static QueryAtomContainer CreateSymbolAndChargeQueryContainer(IAtomContai if (bond.IsAromatic) { queryContainer.Bonds.Add(new AromaticQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); } else { queryContainer.Bonds.Add(new OrderQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); } } return queryContainer; @@ -112,7 +112,7 @@ public static QueryAtomContainer CreateSymbolAndChargeQueryContainer(IAtomContai public static QueryAtomContainer CreateSymbolChargeIDQueryContainer(IAtomContainer container) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { queryContainer.Atoms.Add(new SymbolChargeIDQueryAtom(container.Atoms[i])); @@ -124,27 +124,27 @@ public static QueryAtomContainer CreateSymbolChargeIDQueryContainer(IAtomContain if (bond.IsAromatic) { queryContainer.Bonds.Add(new AromaticQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); } else { queryContainer.Bonds.Add(new OrderQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); } } return queryContainer; } /// - /// Creates a QueryAtomContainer with AnyAtoms / Aromatic Atoms and OrderQueryBonds / AromaticQueryBonds. - /// It uses the CDKConstants.ISAROMATIC flag to determine the aromaticity of container. + /// Creates a with AnyAtoms / Aromatic Atoms and OrderQueryBonds / AromaticQueryBonds. + /// It uses the CDKConstants.ISAROMATIC flag to determine the aromaticity of container. /// - /// The AtomContainer that stands as model + /// The that stands as model /// True = use aromaticity flags to create AtomaticAtoms and AromaticQueryBonds - /// The new QueryAtomContainer created from container + /// The new created from container public static QueryAtomContainer CreateAnyAtomContainer(IAtomContainer container, bool aromaticity) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { @@ -165,12 +165,12 @@ public static QueryAtomContainer CreateAnyAtomContainer(IAtomContainer container if (aromaticity && bond.IsAromatic) { queryContainer.Bonds.Add(new AromaticQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); } else { queryContainer.Bonds.Add(new OrderQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); } } return queryContainer; @@ -178,15 +178,16 @@ public static QueryAtomContainer CreateAnyAtomContainer(IAtomContainer container /// /// Creates a with wildcard atoms and wildcard bonds. - /// - /// This method thus allows the user to search based only on connectivity. /// + /// + /// This method thus allows the user to search based only on connectivity. + /// /// The AtomContainer that stands as the model /// If True, aromaticity flags are checked to create AromaticAtoms and AromaticQueryBonds /// The new QueryAtomContainer public static QueryAtomContainer CreateAnyAtomAnyBondContainer(IAtomContainer container, bool aromaticity) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { @@ -204,8 +205,7 @@ public static QueryAtomContainer CreateAnyAtomAnyBondContainer(IAtomContainer co { int index1 = container.Atoms.IndexOf(bond.Begin); int index2 = container.Atoms.IndexOf(bond.End); - queryContainer.Bonds.Add(new AnyOrderBond(queryContainer.Atoms[index1], queryContainer.Atoms[index2], - container.Builder)); + queryContainer.Bonds.Add(new AnyOrderBond(queryContainer.Atoms[index1], queryContainer.Atoms[index2], container.Builder)); } return queryContainer; } @@ -219,7 +219,7 @@ public static QueryAtomContainer CreateAnyAtomAnyBondContainer(IAtomContainer co /// The new QueryAtomContainer created from container. public static QueryAtomContainer CreateAnyAtomForPseudoAtomQueryContainer(IAtomContainer container) { - QueryAtomContainer queryContainer = new QueryAtomContainer(container.Builder); + var queryContainer = new QueryAtomContainer(container.Builder); for (int i = 0; i < container.Atoms.Count; i++) { if (container.Atoms[i] is IPseudoAtom) @@ -230,7 +230,6 @@ public static QueryAtomContainer CreateAnyAtomForPseudoAtomQueryContainer(IAtomC { queryContainer.Atoms.Add(new SymbolQueryAtom(container.Atoms[i])); } - } foreach (var bond in container.Bonds) { @@ -239,12 +238,12 @@ public static QueryAtomContainer CreateAnyAtomForPseudoAtomQueryContainer(IAtomC if (bond.IsAromatic) { queryContainer.Bonds.Add(new AromaticQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], container.Builder)); } else { queryContainer.Bonds.Add(new OrderQueryBond((IQueryAtom)queryContainer.Atoms[index1], - (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); + (IQueryAtom)queryContainer.Atoms[index2], bond.Order, container.Builder)); } } return queryContainer; @@ -268,8 +267,9 @@ public override bool Matches(IAtom atom) private sealed class AromaticAtom : QueryAtom { public AromaticAtom(IChemObjectBuilder builder) - : base(builder) - { } + : base(builder) + { + } /// @@ -298,7 +298,8 @@ private sealed class AromaticQueryBond : QueryBond { public AromaticQueryBond(IAtom either, IAtom other, IChemObjectBuilder builder) : base(either, other, BondOrder.Unset, builder) - { } + { + } /// public override bool Matches(IBond bond) diff --git a/NCDK/Isomorphisms/Matchers/QueryBond.cs b/NCDK/Isomorphisms/Matchers/QueryBond.cs index a60fe6d2..1d0e37f0 100644 --- a/NCDK/Isomorphisms/Matchers/QueryBond.cs +++ b/NCDK/Isomorphisms/Matchers/QueryBond.cs @@ -28,16 +28,17 @@ namespace NCDK.Isomorphisms.Matchers // @cdk.created 2010-12-16 public abstract class QueryBond : Silent.Bond, IQueryBond { - private IChemObjectBuilder builder; + private readonly IChemObjectBuilder builder; + /// public override IChemObjectBuilder Builder => builder; - public QueryBond(IChemObjectBuilder builder) + protected QueryBond(IChemObjectBuilder builder) { this.builder = builder; } - public QueryBond(IAtom atom1, IAtom atom2, BondOrder order, IChemObjectBuilder builder) + protected QueryBond(IAtom atom1, IAtom atom2, BondOrder order, IChemObjectBuilder builder) : base(atom1, atom2, order) { this.builder = builder; diff --git a/NCDK/Isomorphisms/Matchers/QueryChemObject.cs b/NCDK/Isomorphisms/Matchers/QueryChemObject.cs index e04f28c6..79e43286 100644 --- a/NCDK/Isomorphisms/Matchers/QueryChemObject.cs +++ b/NCDK/Isomorphisms/Matchers/QueryChemObject.cs @@ -22,7 +22,8 @@ namespace NCDK.Isomorphisms.Matchers { public class QueryChemObject : Silent.ChemObject, IChemObject { - private IChemObjectBuilder builder; + private readonly IChemObjectBuilder builder; + /// public override IChemObjectBuilder Builder => builder; diff --git a/NCDK/Isomorphisms/Matchers/RGroupList.cs b/NCDK/Isomorphisms/Matchers/RGroupList.cs index 356741d0..b0e5c791 100644 --- a/NCDK/Isomorphisms/Matchers/RGroupList.cs +++ b/NCDK/Isomorphisms/Matchers/RGroupList.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Text.RegularExpressions; namespace NCDK.Isomorphisms.Matchers @@ -44,7 +45,7 @@ public class RGroupList /// /// Default value for occurrence field. /// - public const string DEFAULT_OCCURRENCE = ">0"; + internal const string DefaultOccurence = ">0"; /// /// Unique number to identify the Rgroup. @@ -55,7 +56,7 @@ public class RGroupList /// Indicates that sites labeled with this Rgroup may only be /// substituted with a member of the Rgroup or with hydrogen. /// - public bool IsRestH; + public bool IsRestH { get; set; } private string occurrence; @@ -78,7 +79,7 @@ public RGroupList(int rGroupNumber) { this.RGroupNumber = rGroupNumber; this.IsRestH = false; - this.Occurrence = DEFAULT_OCCURRENCE; + this.Occurrence = DefaultOccurence; this.RequiredRGroupNumber = 0; } @@ -107,7 +108,7 @@ public int RGroupNumber { if (value < 1 || value > 32) { - throw new ArgumentOutOfRangeException("Rgroup number must be between 1 and 32."); + throw new InvalidOperationException("Rgroup number must be between 1 and 32."); } this.rGroupNumber = value; } @@ -131,7 +132,7 @@ public string Occurrence set { - if (value == null || value.Equals("")) + if (string.IsNullOrEmpty(value)) { value = ">0"; //revert to default } @@ -143,7 +144,7 @@ public string Occurrence this.occurrence = value; } else - throw new CDKException("Invalid occurence line: " + value); + throw new CDKException("Invalid occurrence line: " + value); } } } @@ -173,7 +174,7 @@ public static bool IsValidOccurrenceSyntax(string occ) //Number: "n" if (Match("^\\d+$", cond)) { - if (int.Parse(cond) < 0) // not allowed + if (int.Parse(cond, NumberFormatInfo.InvariantInfo) < 0) // not allowed return false; break; } @@ -181,8 +182,8 @@ public static bool IsValidOccurrenceSyntax(string occ) if (Match("^\\d+-\\d+$", cond)) { var index_of_cond_m = cond.IndexOf('-'); - int from = int.Parse(cond.Substring(0, index_of_cond_m)); - int to = int.Parse(cond.Substring(index_of_cond_m + 1, cond.Length - (index_of_cond_m + 1))); + int from = int.Parse(cond.Substring(0, index_of_cond_m), NumberFormatInfo.InvariantInfo); + int to = int.Parse(cond.Substring(index_of_cond_m + 1, cond.Length - (index_of_cond_m + 1)), NumberFormatInfo.InvariantInfo); if (from < 0 || to < 0 || to < from) // not allowed return false; break; @@ -191,7 +192,7 @@ public static bool IsValidOccurrenceSyntax(string occ) if (Match("^<\\d+$", cond)) { var index_of_cond_m = cond.IndexOf('<'); - int n = int.Parse(cond.Substring(index_of_cond_m + 1, cond.Length - (index_of_cond_m + 1))); + int n = int.Parse(cond.Substring(index_of_cond_m + 1, cond.Length - (index_of_cond_m + 1)), NumberFormatInfo.InvariantInfo); if (n == 0) // not allowed return false; break; @@ -237,10 +238,8 @@ private static bool Match(string regExp, string userInput) /// /// number of attachments /// valid values by combining a max for R# with the occurrence cond. - public IList MatchOccurence(int maxAttachments) + public IEnumerable MatchOccurence(int maxAttachments) { - List validValues = new List(); - for (int val = 0; val <= maxAttachments; val++) { bool addVal = false; @@ -254,13 +253,13 @@ public IList MatchOccurence(int maxAttachments) string cond = token.Trim().Replace(" ", ""); if (Match("^\\d+$", cond)) { // n - if (int.Parse(cond) == val) addVal = true; + if (int.Parse(cond, NumberFormatInfo.InvariantInfo) == val) addVal = true; } if (Match("^\\d+-\\d+$", cond)) { // n-m var cond_index_of_m = cond.IndexOf('-'); - int from = int.Parse(cond.Substring(0, cond_index_of_m)); - int to = int.Parse(cond.Substring(cond_index_of_m + 1, cond.Length - (cond_index_of_m + 1))); + int from = int.Parse(cond.Substring(0, cond_index_of_m), NumberFormatInfo.InvariantInfo); + int to = int.Parse(cond.Substring(cond_index_of_m + 1, cond.Length - (cond_index_of_m + 1)), NumberFormatInfo.InvariantInfo); if (val >= from && val <= to) { addVal = true; @@ -269,7 +268,7 @@ public IList MatchOccurence(int maxAttachments) if (Match("^>\\d+$", cond)) { // '); - int n = int.Parse(cond.Substring(cond_index_of_gt + 1, cond.Length - (cond_index_of_gt + 1))); + int n = int.Parse(cond.Substring(cond_index_of_gt + 1, cond.Length - (cond_index_of_gt + 1)), NumberFormatInfo.InvariantInfo); if (val > n) { addVal = true; @@ -278,7 +277,7 @@ public IList MatchOccurence(int maxAttachments) if (Match("^<\\d+$", cond)) { // >n var cond_index_of_lt = cond.IndexOf('<'); - int n = int.Parse(cond.Substring(cond_index_of_lt + 1, cond.Length - (cond_index_of_lt + 1))); + int n = int.Parse(cond.Substring(cond_index_of_lt + 1, cond.Length - (cond_index_of_lt + 1)), NumberFormatInfo.InvariantInfo); if (val < n) { addVal = true; @@ -286,12 +285,12 @@ public IList MatchOccurence(int maxAttachments) } if (addVal) { - validValues.Add(val); + yield return val; } } } - return validValues; + yield break; } public override bool Equals(object obj) diff --git a/NCDK/Isomorphisms/Matchers/RGroupQuery.cs b/NCDK/Isomorphisms/Matchers/RGroupQuery.cs index f70730c3..e2f297e7 100644 --- a/NCDK/Isomorphisms/Matchers/RGroupQuery.cs +++ b/NCDK/Isomorphisms/Matchers/RGroupQuery.cs @@ -28,6 +28,8 @@ using NCDK.Numerics; using System.Text.RegularExpressions; using NCDK.Common.Primitives; +using System.Globalization; +using System.Linq; namespace NCDK.Isomorphisms.Matchers { @@ -65,7 +67,6 @@ namespace NCDK.Isomorphisms.Matchers // @cdk.keyword R group // @cdk.keyword R-group // @author Mark Rijnbeek - [Serializable] public class RGroupQuery : QueryChemObject, IChemObject, IRGroupQuery { /// @@ -77,13 +78,13 @@ public class RGroupQuery : QueryChemObject, IChemObject, IRGroupQuery /// Rgroup definitions, each a list of possible substitutes for the /// given R number. /// - public IDictionary RGroupDefinitions { get; set; } + public IReadOnlyDictionary RGroupDefinitions { get; set; } /// /// For each Rgroup Atom there may be a map containing (number,bond), /// being the attachment order (1,2) and the bond to attach to. /// - public IDictionary> RootAttachmentPoints { get; set; } + public IReadOnlyDictionary> RootAttachmentPoints { get; set; } public RGroupQuery(IChemObjectBuilder builder) : base(builder) @@ -96,9 +97,9 @@ public RGroupQuery(IChemObjectBuilder builder) /// /// R# number, 1..32 /// list of (pseudo) atoms with the provided rgroupNumber as label - public IList GetRgroupQueryAtoms(int? rgroupNumber) + public IReadOnlyList GetRgroupQueryAtoms(int? rgroupNumber) { - IList rGroupQueryAtoms = null; + List rGroupQueryAtoms = null; if (RootStructure != null) { @@ -109,11 +110,12 @@ public IList GetRgroupQueryAtoms(int? rgroupNumber) IAtom atom = RootStructure.Atoms[i]; if (atom is IPseudoAtom rGroup) { - if (!rGroup.Label.Equals("R") + if (!string.Equals(rGroup.Label, "R", StringComparison.Ordinal) && // just "R" is not a proper query atom rGroup.Label.StartsWithChar('R') - && (rgroupNumber == null || int.Parse(rGroup.Label.Substring(1)).Equals( - rgroupNumber))) rGroupQueryAtoms.Add(atom); + && (rgroupNumber == null + || int.Parse(rGroup.Label.Substring(1), NumberFormatInfo.InvariantInfo).Equals(rgroupNumber))) + rGroupQueryAtoms.Add(atom); } } } @@ -124,12 +126,12 @@ public IList GetRgroupQueryAtoms(int? rgroupNumber) /// Returns all R# type atoms (pseudo atoms) found in the root structure. /// /// list of (pseudo) R# atoms - public IList GetAllRgroupQueryAtoms() + public IReadOnlyList GetAllRgroupQueryAtoms() { return GetRgroupQueryAtoms(null); } - private static Regex validLabelPattern = new Regex("^R\\d+$", RegexOptions.Compiled); + private static readonly Regex validLabelPattern = new Regex("^R\\d+$", RegexOptions.Compiled); /// /// Validates a Pseudo atom's label to be valid RGroup query label (R1..R32). @@ -141,7 +143,7 @@ public static bool IsValidRgroupQueryLabel(string Rxx) var match = validLabelPattern.Match(Rxx); if (match.Success) { - int groupNumber = int.Parse(Rxx.Substring(1)); + int groupNumber = int.Parse(Rxx.Substring(1), NumberFormatInfo.InvariantInfo); if (groupNumber >= 1 && groupNumber <= 32) { return true; @@ -153,14 +155,14 @@ public static bool IsValidRgroupQueryLabel(string Rxx) public bool AreSubstituentsDefined() { - IList allRgroupAtoms = GetAllRgroupQueryAtoms(); + var allRgroupAtoms = GetAllRgroupQueryAtoms(); if (allRgroupAtoms == null) return false; foreach (var rgp in allRgroupAtoms) { if (RGroupQuery.IsValidRgroupQueryLabel(((IPseudoAtom)rgp).Label)) { - int groupNum = int.Parse(((IPseudoAtom)rgp).Label.Substring(1)); + int groupNum = int.Parse(((IPseudoAtom)rgp).Label.Substring(1), NumberFormatInfo.InvariantInfo); if (RGroupDefinitions == null || !RGroupDefinitions.ContainsKey(groupNum) || RGroupDefinitions[groupNum].RGroups == null || RGroupDefinitions[groupNum].RGroups.Count == 0) @@ -172,7 +174,6 @@ public bool AreSubstituentsDefined() return true; } - public bool AreRootAtomsDefined() { foreach (var rgpNum in RGroupDefinitions.Keys) @@ -185,7 +186,7 @@ public bool AreRootAtomsDefined() IPseudoAtom pseudo = (IPseudoAtom)rootAtom; if (pseudo.Label.Length > 1) { - int rootAtomRgrpNumber = int.Parse(pseudo.Label.Substring(1)); + int rootAtomRgrpNumber = int.Parse(pseudo.Label.Substring(1), NumberFormatInfo.InvariantInfo); if (rootAtomRgrpNumber == rgpNum) { represented = true; @@ -203,8 +204,8 @@ public bool AreRootAtomsDefined() } return true; } - - public IList GetAllConfigurations() + + public IEnumerable GetAllConfigurations() { if (!AreSubstituentsDefined()) { @@ -212,38 +213,36 @@ public IList GetAllConfigurations() } //result = a list of concrete atom containers that are valid interpretations of the RGroup query - List result = new List(); + var result = new List(); //rGroupNumbers = list holding each R# number for this RGroup query - List rGroupNumbers = new List(); + var rGroupNumbers = new List(); //distributions = a list of valid distributions, that is a one/zero representation // indicating which atom in an atom series belonging to a particular // R# group is present (1) or absent (0). - List distributions = new List(); - - List> substitutes = new List>(); + var distributions = new List(); + var substitutes = new List>(); //Valid occurrences for each R# group - List> occurrences = new List>(); - List occurIndexes = new List(); + var occurrences = new List>(); + var occurIndexes = new List(); //Build up each R# group data before recursively finding configurations. - if (RGroupDefinitions.Keys.Count > 0) + foreach (var r in RGroupDefinitions.Keys) { - foreach (var r in RGroupDefinitions.Keys) + rGroupNumbers.Add(r); + var validOcc = RGroupDefinitions[r].MatchOccurence(GetRgroupQueryAtoms(r).Count).ToList(); + if (validOcc.Count == 0) { - rGroupNumbers.Add(r); - IList validOcc = RGroupDefinitions[r].MatchOccurence(GetRgroupQueryAtoms(r).Count); - if (validOcc.Count == 0) - { - throw new CDKException("Occurrence '" + RGroupDefinitions[r].Occurrence - + "' defined for Rgroup " + r + " results in no subsititute options for this R-group."); - } - occurrences.Add(validOcc); - occurIndexes.Add(0); + throw new CDKException($"Occurrence '{RGroupDefinitions[r].Occurrence}' defined for Rgroup {r} results in no subsititute options for this R-group."); } + occurrences.Add(validOcc); + occurIndexes.Add(0); + } + if (rGroupNumbers.Count > 0) + { //Init distributions: empty and with the right list size for (int i = 0; i < rGroupNumbers.Count; i++) { @@ -309,7 +308,7 @@ private void FindConfigurationsRecursively(IList rGroupNumbers, IList rAttachmentPoints)) + if (this.RootAttachmentPoints.TryGetValue(rAtom, out IReadOnlyDictionary rAttachmentPoints)) { // Loop over attachment points of the R# atom for (int apo = 0; apo < rAttachmentPoints.Count; apo++) @@ -549,7 +548,7 @@ private void MapSubstitutes(RGroupList rgpList, int listOffset, int[] distributi /// /// /// the array position of atom in container - private int GetAtomPosition(IAtom atom, IAtomContainer container) + private static int GetAtomPosition(IAtom atom, IAtomContainer container) { for (int i = 0; i < container.Atoms.Count; i++) { @@ -567,7 +566,7 @@ private int GetAtomPosition(IAtom atom, IAtomContainer container) /// /// /// the array position of the bond in the container - private int GetBondPosition(IBond bond, IAtomContainer container) + private static int GetBondPosition(IBond bond, IAtomContainer container) { for (int i = 0; i < container.Bonds.Count; i++) { @@ -586,7 +585,7 @@ private int GetBondPosition(IBond bond, IAtomContainer container) /// /// /// true if arr's values are all zero. - private bool AllZeroArray(int[] arr) + private static bool AllZeroArray(int[] arr) { foreach (var flag in arr) if (flag != 0) return false; @@ -652,18 +651,18 @@ public int Count } } - public IList GetSubstituents() + public IEnumerable GetSubstituents() { - List substitutes = new List(); foreach (var r in RGroupDefinitions.Keys) { foreach (var rgrp in RGroupDefinitions[r].RGroups) { IAtomContainer subst = rgrp.Group; - if (subst != null) substitutes.Add(subst); + if (subst != null) + yield return subst; } } - return substitutes; + yield break; } } } diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/AliphaticSymbolAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/AliphaticSymbolAtom.cs index 4d80f3e6..51e8d087 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/AliphaticSymbolAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/AliphaticSymbolAtom.cs @@ -16,6 +16,8 @@ * (or see http://www.gnu.org/copyleft/lesser.html) */ +using System; + namespace NCDK.Isomorphisms.Matchers.SMARTS { /// @@ -40,7 +42,7 @@ public AliphaticSymbolAtom(string symbol, IChemObjectBuilder builder) public override bool Matches(IAtom atom) { - return !atom.IsAromatic && atom.Symbol.Equals(this.Symbol); + return !atom.IsAromatic && atom.Symbol.Equals(this.Symbol, StringComparison.Ordinal); } public override string ToString() diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/AromaticSymbolAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/AromaticSymbolAtom.cs index fbec6bab..3997df26 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/AromaticSymbolAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/AromaticSymbolAtom.cs @@ -16,6 +16,8 @@ * (or see http://www.gnu.org/copyleft/lesser.html) */ +using System; + namespace NCDK.Isomorphisms.Matchers.SMARTS { /// @@ -35,7 +37,7 @@ public AromaticSymbolAtom(string symbol, IChemObjectBuilder builder) public override bool Matches(IAtom atom) { - return atom.IsAromatic && atom.Symbol.Equals(this.Symbol); + return atom.IsAromatic && atom.Symbol.Equals(this.Symbol, StringComparison.Ordinal); } public override string ToString() diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/HydrogenAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/HydrogenAtom.cs index 69aee12d..b8f7e4a1 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/HydrogenAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/HydrogenAtom.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Isomorphisms.Matchers.SMARTS { /// @@ -34,7 +36,7 @@ public HydrogenAtom(IChemObjectBuilder builder) public override bool Matches(IAtom atom) { - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return false; } @@ -48,7 +50,7 @@ public override bool Matches(IAtom atom) var list = Invariants(atom).Target.GetConnectedAtoms(atom); foreach (var connAtom in list) { - if (connAtom.Symbol.Equals("H")) + if (string.Equals(connAtom.Symbol, "H", StringComparison.Ordinal)) { return true; } diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorAtom.cs index ce9c7144..08be870e 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorAtom.cs @@ -52,7 +52,9 @@ public virtual IQueryAtom Left } [Obsolete("use static utility methods to create logical atom matcher, " + nameof(And) + ", " + nameof(Or) + " or " + nameof(Not) + ".")] +#pragma warning disable CA1716 // Identifiers should not match keywords public virtual string Operator +#pragma warning restore CA1716 // Identifiers should not match keywords { get { return operator_; } set { operator_ = value; } @@ -76,26 +78,32 @@ public override bool Matches(IAtom atom) bool matchesLeft = left.Matches(atom); if (right != null) { - if ("and".Equals(operator_) && matchesLeft) + switch (operator_) { - bool matchesRight = right.Matches(atom); - val = matchesLeft && matchesRight; - } - else if ("or".Equals(operator_)) - { - bool matchesRight = right.Matches(atom); - val = matchesLeft || matchesRight; + case "and": + { + bool matchesRight = right.Matches(atom); + val = matchesLeft && matchesRight; + } + break; + case "or": + { + bool matchesRight = right.Matches(atom); + val = matchesLeft || matchesRight; + } + break; } } else { - if ("not".Equals(operator_)) - { - val = (!matchesLeft); - } - else + switch (operator_) { - val = matchesLeft; + case "not": + val = (!matchesLeft); + break; + default: + val = matchesLeft; + break; } } return val; @@ -261,7 +269,7 @@ private class Negation : LogicalOperatorAtom private SMARTSAtom expression; /// Is the expression chiral - if so, always true! - private bool chiral; + private readonly bool chiral; /// /// Create a negation of . diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorBond.cs b/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorBond.cs index 1fad8128..b59725b8 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorBond.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/LogicalOperatorBond.cs @@ -16,6 +16,7 @@ * (or see http://www.gnu.org/copyleft/lesser.html) */ +using System; using System.Collections.Generic; namespace NCDK.Isomorphisms.Matchers.SMARTS @@ -72,11 +73,11 @@ public override bool Matches(IBond bond) if (right != null) { bool matchesRight = right.Matches(bond); - if ("and".Equals(operator_)) + if (string.Equals("and", operator_, StringComparison.Ordinal)) { return matchesLeft && matchesRight; } - else if ("or".Equals(operator_)) + else if (string.Equals("or", operator_, StringComparison.Ordinal)) { return matchesLeft || matchesRight; } @@ -87,7 +88,7 @@ public override bool Matches(IBond bond) } else { - if ("not".Equals(operator_)) + if (string.Equals("not", operator_, StringComparison.Ordinal)) { return (!matchesLeft); } diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/NonCHHeavyAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/NonCHHeavyAtom.cs index 798db165..a2a6a0e7 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/NonCHHeavyAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/NonCHHeavyAtom.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Isomorphisms.Matchers.SMARTS { /// @@ -38,7 +40,7 @@ public NonCHHeavyAtom(IChemObjectBuilder builder) public override bool Matches(IAtom atom) { string symbol = atom.Symbol; - return !(symbol.Equals("C") || symbol.Equals("H")); + return !(symbol.Equals("C", StringComparison.Ordinal) || symbol.Equals("H", StringComparison.Ordinal)); } public override string ToString() diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/ReactionRoleQueryAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/ReactionRoleQueryAtom.cs index 80e7d053..e7e68fb9 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/ReactionRoleQueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/ReactionRoleQueryAtom.cs @@ -21,27 +21,32 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ +using System; using System.Text; namespace NCDK.Isomorphisms.Matchers.SMARTS { + [Flags] + public enum ReactionRoles + { + Reactant = 0x1, + Agent = 0x2, + Product = 0x4, + Any = Reactant | Agent | Product, + } + /// /// Matches atoms with a particular role in a reaction. /// public class ReactionRoleQueryAtom : SMARTSAtom { - public const int ROLE_REACTANT = 0x1; - public const int ROLE_AGENT = 0x2; - public const int ROLE_PRODUCT = 0x4; - public const int ROLE_ANY = ROLE_REACTANT | ROLE_PRODUCT | ROLE_AGENT; - - private readonly int role; + private readonly ReactionRoles role; - public readonly static ReactionRoleQueryAtom RoleReactant = new ReactionRoleQueryAtom(null, ROLE_REACTANT); - public readonly static ReactionRoleQueryAtom RoleAgent = new ReactionRoleQueryAtom(null, ROLE_AGENT); - public readonly static ReactionRoleQueryAtom RoleProduct = new ReactionRoleQueryAtom(null, ROLE_PRODUCT); + public readonly static ReactionRoleQueryAtom RoleReactant = new ReactionRoleQueryAtom(null, ReactionRoles.Reactant); + public readonly static ReactionRoleQueryAtom RoleAgent = new ReactionRoleQueryAtom(null, ReactionRoles.Agent); + public readonly static ReactionRoleQueryAtom RoleProduct = new ReactionRoleQueryAtom(null, ReactionRoles.Product); - public ReactionRoleQueryAtom(IChemObjectBuilder builder, int role) + public ReactionRoleQueryAtom(IChemObjectBuilder builder, ReactionRoles role) : base(builder) { this.role = role; @@ -51,15 +56,15 @@ public override bool Matches(IAtom atom) { ReactionRole? atomRole = atom.GetProperty(CDKPropertyName.ReactionRole); if (atomRole == null) - return this.role == ROLE_ANY; + return this.role == ReactionRoles.Any; switch (atomRole.Value) { case ReactionRole.Reactant: - return (this.role & ROLE_REACTANT) != 0; + return (this.role & ReactionRoles.Reactant) != 0; case ReactionRole.Agent: - return (this.role & ROLE_AGENT) != 0; + return (this.role & ReactionRoles.Agent) != 0; case ReactionRole.Product: - return (this.role & ROLE_PRODUCT) != 0; + return (this.role & ReactionRoles.Product) != 0; default: return false; } @@ -68,11 +73,11 @@ public override bool Matches(IAtom atom) public override string ToString() { StringBuilder sb = new StringBuilder(); - if ((role & ROLE_REACTANT) != 0) + if ((role & ReactionRoles.Reactant) != 0) sb.Append("Reactant"); - if ((role & ROLE_AGENT) != 0) + if ((role & ReactionRoles.Agent) != 0) sb.Append("Agent"); - if ((role & ROLE_PRODUCT) != 0) + if ((role & ReactionRoles.Product) != 0) sb.Append("Product"); return "ReactionRole(" + sb.ToString() + ")"; } diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtom.cs b/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtom.cs index 0f15e22c..f58c9e92 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtom.cs @@ -28,7 +28,7 @@ namespace NCDK.Isomorphisms.Matchers.SMARTS // @cdk.keyword SMARTS public abstract class SMARTSAtom : QueryAtom, IQueryAtom { - public SMARTSAtom(IChemObjectBuilder builder) + protected SMARTSAtom(IChemObjectBuilder builder) : base(builder) { } @@ -39,12 +39,11 @@ public SMARTSAtom(IChemObjectBuilder builder) /// the atom to obtain the invariants of /// the atom invariants for the atom /// thrown if the invariants were not set - internal SMARTSAtomInvariants Invariants(IAtom atom) + internal static SMARTSAtomInvariants Invariants(IAtom atom) { SMARTSAtomInvariants inv = atom.GetProperty(SMARTSAtomInvariants.Key); if (inv == null) - throw new NullReferenceException( - "Missing SMARTSAtomInvariants - please compute these values before matching."); + throw new NullReferenceException("Missing SMARTSAtomInvariants - please compute these values before matching."); return inv; } diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtomInvariants.cs b/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtomInvariants.cs index 183ee46d..3c2b1469 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtomInvariants.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/SMARTSAtomInvariants.cs @@ -190,8 +190,8 @@ public SMARTSAtomInvariants(IAtomContainer target, int valence, int ringNumber, /// the container to configure public static void ConfigureDaylightWithoutRingInfo(IAtomContainer container) { - EdgeToBondMap map = EdgeToBondMap.WithSpaceFor(container); - int[][] graph = GraphUtil.ToAdjList(container, map); + var map = EdgeToBondMap.WithSpaceFor(container); + var graph = GraphUtil.ToAdjList(container, map); ConfigureDaylight(container, graph, map, false); } @@ -215,8 +215,8 @@ public static void ConfigureDaylightWithoutRingInfo(IAtomContainer container) /// the container to configure public static void ConfigureDaylightWithRingInfo(IAtomContainer container) { - EdgeToBondMap map = EdgeToBondMap.WithSpaceFor(container); - int[][] graph = GraphUtil.ToAdjList(container, map); + var map = EdgeToBondMap.WithSpaceFor(container); + var graph = GraphUtil.ToAdjList(container, map); ConfigureDaylight(container, graph, map, true); } @@ -230,10 +230,10 @@ public static void ConfigureDaylightWithRingInfo(IAtomContainer container) /// logical condition as whether ring info should be included private static void ConfigureDaylight(IAtomContainer container, int[][] graph, EdgeToBondMap bondMap, bool ringInfo) { - int nAtoms = container.Atoms.Count; + var nAtoms = container.Atoms.Count; - int[] ringNumber = new int[nAtoms]; - int[] ringSize = new int[nAtoms]; + var ringNumber = new int[nAtoms]; + var ringSize = new int[nAtoms]; Arrays.Fill(ringSize, nAtoms + 1); @@ -242,10 +242,10 @@ private static void ConfigureDaylight(IAtomContainer container, int[][] graph, E // non-unique but used by daylight foreach (var cycle in Cycles.FindSSSR(container).GetPaths()) { - int size = cycle.Length - 1; + var size = cycle.Length - 1; for (int i = 1; i < cycle.Length; i++) { - int v = cycle[i]; + var v = cycle[i]; if (size < ringSize[v]) ringSize[v] = size; ringNumber[v]++; bondMap[cycle[i], cycle[i - 1]].IsInRing = true; @@ -263,7 +263,7 @@ private static void ConfigureDaylight(IAtomContainer container, int[][] graph, E for (int v = 0; v < nAtoms; v++) { - IAtom atom = container.Atoms[v]; + var atom = container.Atoms[v]; int implHCount = CheckNotNull(atom.ImplicitHydrogenCount, "Implicit hydrogen count was not set."); @@ -275,8 +275,8 @@ private static void ConfigureDaylight(IAtomContainer container, int[][] graph, E // traverse bonds foreach (var w in graph[v]) { - IBond bond = bondMap[v, w]; - BondOrder order = bond.Order; + var bond = bondMap[v, w]; + var order = bond.Order; if (order.IsUnset()) throw new NullReferenceException("Bond order was not set."); @@ -297,8 +297,8 @@ private static void ConfigureDaylight(IAtomContainer container, int[][] graph, E } - SMARTSAtomInvariants inv = new SMARTSAtomInvariants(container, valence, ringNumber[v], - ringSize[v] <= nAtoms ? new int[] { ringSize[v] } : new int[0], + var inv = new SMARTSAtomInvariants(container, valence, ringNumber[v], + ringSize[v] <= nAtoms ? new int[] { ringSize[v] } : Array.Empty(), ringConnections, degree, degree + implHCount, totalHCount); // if there was no properties a default size LinkedHashMap is created diff --git a/NCDK/Isomorphisms/Matchers/SMARTS/StereoBond.cs b/NCDK/Isomorphisms/Matchers/SMARTS/StereoBond.cs index c772abc3..7b35ade1 100644 --- a/NCDK/Isomorphisms/Matchers/SMARTS/StereoBond.cs +++ b/NCDK/Isomorphisms/Matchers/SMARTS/StereoBond.cs @@ -59,7 +59,7 @@ public Direction GetDirection(IAtom atom) throw new ArgumentException("atom is not a memeber of this bond"); } - private Direction Inv(Direction direction) + private static Direction Inv(Direction direction) { return direction == Direction.Up ? Direction.Down : Direction.Up; } diff --git a/NCDK/Isomorphisms/Matchers/SymbolAndChargeQueryAtom.cs b/NCDK/Isomorphisms/Matchers/SymbolAndChargeQueryAtom.cs index 8b160dd7..1a94bf32 100644 --- a/NCDK/Isomorphisms/Matchers/SymbolAndChargeQueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SymbolAndChargeQueryAtom.cs @@ -36,14 +36,11 @@ public SymbolAndChargeQueryAtom(IAtom atom) FormalCharge = atom.FormalCharge; } - public void SetOperator(string str) { } - - public override bool Matches(IAtom atom) { int requiredCharge = this.FormalCharge ?? 0; int foundCharge = atom.FormalCharge ?? 0; - return this.Symbol.Equals(atom.Symbol) && requiredCharge == foundCharge; + return this.Symbol.Equals(atom.Symbol, StringComparison.Ordinal) && requiredCharge == foundCharge; } public override string ToString() diff --git a/NCDK/Isomorphisms/Matchers/SymbolChargeIDQueryAtom.cs b/NCDK/Isomorphisms/Matchers/SymbolChargeIDQueryAtom.cs index 28f102a3..c92de29a 100644 --- a/NCDK/Isomorphisms/Matchers/SymbolChargeIDQueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SymbolChargeIDQueryAtom.cs @@ -37,12 +37,10 @@ public SymbolChargeIDQueryAtom(IAtom atom) Id = atom.Id; } - public void SetOperator(string str) { } - public override bool Matches(IAtom atom) { - return this.Symbol.Equals(atom.Symbol) && this.FormalCharge == atom.FormalCharge - && this.Id.Equals(atom.Id); + return this.Symbol.Equals(atom.Symbol, StringComparison.Ordinal) && this.FormalCharge == atom.FormalCharge + && this.Id.Equals(atom.Id, StringComparison.Ordinal); } public override string ToString() diff --git a/NCDK/Isomorphisms/Matchers/SymbolQueryAtom.cs b/NCDK/Isomorphisms/Matchers/SymbolQueryAtom.cs index 0eddd166..5adb7d67 100644 --- a/NCDK/Isomorphisms/Matchers/SymbolQueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SymbolQueryAtom.cs @@ -27,7 +27,7 @@ namespace NCDK.Isomorphisms.Matchers public class SymbolQueryAtom : QueryAtom, IQueryAtom { private string ID; - private int HCount = 0; + public int HCount { get; set; } = 0; public SymbolQueryAtom(IChemObjectBuilder builder) : base(builder) @@ -37,11 +37,6 @@ public SymbolQueryAtom(IAtom atom) : base(atom.Symbol, atom.Builder) { } - public void SetHCount(int m_HCount) - { - HCount = m_HCount; - } - public override bool Matches(IAtom atom) { if (ID != null && HCount == 0) @@ -51,7 +46,7 @@ public override bool Matches(IAtom atom) return (this.ImplicitHydrogenCount == HCount); } else - return this.Symbol.Equals(atom.Symbol); + return this.Symbol.Equals(atom.Symbol, StringComparison.Ordinal); } public void SetOperator(string str) diff --git a/NCDK/Isomorphisms/Matchers/SymbolSetQueryAtom.cs b/NCDK/Isomorphisms/Matchers/SymbolSetQueryAtom.cs index 86c77cb5..1b6dff85 100644 --- a/NCDK/Isomorphisms/Matchers/SymbolSetQueryAtom.cs +++ b/NCDK/Isomorphisms/Matchers/SymbolSetQueryAtom.cs @@ -49,8 +49,6 @@ public SymbolSetQueryAtom(IChemObjectBuilder builder) : base(builder) { } - public void SetOperator(string str) { } - /// /// The matches implementation of the interface. /// diff --git a/NCDK/Isomorphisms/SmartsStereoMatch.cs b/NCDK/Isomorphisms/SmartsStereoMatch.cs index 1f03c89e..bb39f11a 100644 --- a/NCDK/Isomorphisms/SmartsStereoMatch.cs +++ b/NCDK/Isomorphisms/SmartsStereoMatch.cs @@ -48,10 +48,10 @@ public sealed class SmartsStereoMatch private readonly IAtomContainer query, target; /// Atom to atom index lookup. - private readonly IDictionary queryMap, targetMap; + private readonly Dictionary queryMap, targetMap; /// Indexed array of stereo elements. - private readonly IReadOnlyStereoElement[] queryElements, targetElements; + private readonly IStereoElement[] queryElements, targetElements; /// Indexed array of stereo element types. private readonly StereoType[] queryTypes, targetTypes; @@ -77,8 +77,8 @@ public SmartsStereoMatch(IAtomContainer query, IAtomContainer target) this.queryMap = IndexAtoms(query); this.targetMap = IndexAtoms(target); - this.queryElements = new IReadOnlyStereoElement[query.Atoms.Count]; - this.targetElements = new IReadOnlyStereoElement[target.Atoms.Count]; + this.queryElements = new IStereoElement[query.Atoms.Count]; + this.targetElements = new IStereoElement[target.Atoms.Count]; this.queryTypes = new StereoType[query.Atoms.Count]; this.targetTypes = new StereoType[target.Atoms.Count]; @@ -156,7 +156,7 @@ private bool CheckTetrahedral(int u, int[] mapping) /// neighboring vertices of ( plural) /// mapping from the query to the target /// the neighbors us, transformed into the neighbors around v - private int[] Map(int u, int v, int[] us, int[] mapping) + private static int[] Map(int u, int v, int[] us, int[] mapping) { for (int i = 0; i < us.Length; i++) us[i] = mapping[us[i]]; @@ -239,7 +239,7 @@ private bool CheckGeometric(int u1, int u2, int[] mapping) /// tetrahedral element /// atom index lookup /// the neighbors - private int[] Neighbors(ITetrahedralChirality element, IDictionary map) + private static int[] Neighbors(ITetrahedralChirality element, IDictionary map) { var atoms = element.Ligands; int[] vs = new int[atoms.Count]; @@ -255,7 +255,7 @@ private int[] Neighbors(ITetrahedralChirality element, IDictionary m /// /// values /// parity of the permutation (odd = -1, even = +1) - private int PermutationParity(int[] vs) + private static int PermutationParity(int[] vs) { int n = 0; for (int i = 0; i < vs.Length; i++) @@ -281,9 +281,9 @@ private int OtherIndex(int i) /// /// the container to index the atoms of /// the index/lookup of atoms to the index they appear - private static IDictionary IndexAtoms(IAtomContainer container) + private static Dictionary IndexAtoms(IAtomContainer container) { - IDictionary map = new Dictionary(container.Atoms.Count); + var map = new Dictionary(container.Atoms.Count); for (int i = 0; i < container.Atoms.Count; i++) map[container.Atoms[i]] = i; return map; @@ -299,9 +299,9 @@ private static IDictionary IndexAtoms(IAtomContainer container) /// type of stereo element indexed /// the container to index the elements of /// indices of atoms involved in stereo configurations - private static int[] IndexElements(IDictionary map, IReadOnlyStereoElement[] elements, StereoType[] types, IAtomContainer container) + private static int[] IndexElements(Dictionary map, IStereoElement[] elements, StereoType[] types, IAtomContainer container) { - int[] indices = new int[container.Atoms.Count]; + var indices = new int[container.Atoms.Count]; int nElements = 0; foreach (var element in container.StereoElements) { @@ -329,7 +329,7 @@ private static int[] IndexElements(IDictionary map, IReadOnlyStereoE /// /// configuration /// the parity - private int Parity(TetrahedralStereo stereo) + private static int Parity(TetrahedralStereo stereo) { return stereo == TetrahedralStereo.Clockwise ? 1 : -1; } @@ -339,7 +339,7 @@ private int Parity(TetrahedralStereo stereo) /// /// configuration /// the parity - private int Parity(DoubleBondConformation conformation) + private static int Parity(DoubleBondConformation conformation) { return conformation == DoubleBondConformation.Together ? 1 : -1; } diff --git a/NCDK/Isomorphisms/StereoMatch.cs b/NCDK/Isomorphisms/StereoMatch.cs index 05c2dcfc..7b4cef8f 100644 --- a/NCDK/Isomorphisms/StereoMatch.cs +++ b/NCDK/Isomorphisms/StereoMatch.cs @@ -46,10 +46,13 @@ internal sealed class StereoMatch private readonly IAtomContainer query, target; /// Atom to atom index lookup. - private readonly IDictionary queryMap, targetMap; + private readonly Dictionary queryMap; + + /// Atom to atom index lookup. + private readonly Dictionary targetMap; /// Indexed array of stereo elements. - private readonly IReadOnlyStereoElement[] queryElements, targetElements; + private readonly IStereoElement[] queryElements, targetElements; /// Indexed array of stereo element types. private readonly Types[] queryTypes, targetTypes; @@ -69,8 +72,8 @@ internal StereoMatch(IAtomContainer query, IAtomContainer target) this.target = target; this.queryMap = IndexAtoms(query); this.targetMap = IndexAtoms(target); - this.queryElements = new IReadOnlyStereoElement[query.Atoms.Count]; - this.targetElements = new IReadOnlyStereoElement[target.Atoms.Count]; + this.queryElements = new IStereoElement[query.Atoms.Count]; + this.targetElements = new IStereoElement[target.Atoms.Count]; this.queryTypes = new Types[query.Atoms.Count]; this.targetTypes = new Types[target.Atoms.Count]; @@ -231,9 +234,9 @@ private bool CheckGeometric(int u1, int u2, int[] mapping) /// tetrahedral element /// atom index lookup /// the neighbors - private int[] Neighbors(ITetrahedralChirality element, IDictionary map) + private static int[] Neighbors(ITetrahedralChirality element, IReadOnlyDictionary map) { - IList atoms = element.Ligands; + var atoms = element.Ligands; int[] vs = new int[atoms.Count]; for (int i = 0; i < atoms.Count; i++) vs[i] = map[atoms[i]]; @@ -245,7 +248,7 @@ private int[] Neighbors(ITetrahedralChirality element, IDictionary m /// /// array of non-null atoms. /// a hydrogen atom - private IAtom FindHydrogen(IEnumerable atoms) + private static IAtom FindHydrogen(IEnumerable atoms) { foreach (var a in atoms) { @@ -261,7 +264,7 @@ private IAtom FindHydrogen(IEnumerable atoms) /// /// values /// parity of the permutation (odd = -1, even = +1) - private int PermutationParity(int[] vs) + private static int PermutationParity(int[] vs) { int n = 0; for (int i = 0; i < vs.Length; i++) @@ -287,9 +290,9 @@ private int OtherIndex(int i) /// /// the container to index the atoms of /// the index/lookup of atoms to the index they appear - private static IDictionary IndexAtoms(IAtomContainer container) + private static Dictionary IndexAtoms(IAtomContainer container) { - IDictionary map = new Dictionary(container.Atoms.Count); + var map = new Dictionary(container.Atoms.Count); for (int i = 0; i < container.Atoms.Count; i++) map.Add(container.Atoms[i], i); return map; @@ -305,7 +308,7 @@ private static IDictionary IndexAtoms(IAtomContainer container) /// type of stereo element indexed /// the container to index the elements of /// indices of atoms involved in stereo configurations - private static int[] IndexElements(IDictionary map, IReadOnlyStereoElement[] elements, Types[] types, IAtomContainer container) + private static int[] IndexElements(IDictionary map, IStereoElement[] elements, Types[] types, IAtomContainer container) { int[] indices = new int[container.Atoms.Count]; int nElements = 0; @@ -335,7 +338,7 @@ private static int[] IndexElements(IDictionary map, IReadOnlyStereoE /// /// configuration /// the parity - private int Parity(TetrahedralStereo stereo) + private static int Parity(TetrahedralStereo stereo) { return stereo == TetrahedralStereo.Clockwise ? 1 : -1; } @@ -345,7 +348,7 @@ private int Parity(TetrahedralStereo stereo) /// /// configuration /// the parity - private int Parity(DoubleBondConformation conformation) + private static int Parity(DoubleBondConformation conformation) { return conformation == DoubleBondConformation.Together ? 1 : -1; } diff --git a/NCDK/Isomorphisms/Ullmann.cs b/NCDK/Isomorphisms/Ullmann.cs index e0db0611..48c5daf4 100644 --- a/NCDK/Isomorphisms/Ullmann.cs +++ b/NCDK/Isomorphisms/Ullmann.cs @@ -87,8 +87,8 @@ public override int[] Match(IAtomContainer target) public override Mappings MatchAll(IAtomContainer target) { - EdgeToBondMap bonds2 = EdgeToBondMap.WithSpaceFor(target); - int[][] g2 = GraphUtil.ToAdjList(target, bonds2); + var bonds2 = EdgeToBondMap.WithSpaceFor(target); + var g2 = GraphUtil.ToAdjList(target, bonds2); var iterable = new UllmannIterable(query, target, g1, g2, bonds1, bonds2, atomMatcher, bondMatcher); return new Mappings(query, target, iterable); } diff --git a/NCDK/Isomorphisms/UllmannState.cs b/NCDK/Isomorphisms/UllmannState.cs index 00b45160..76c0cbc6 100644 --- a/NCDK/Isomorphisms/UllmannState.cs +++ b/NCDK/Isomorphisms/UllmannState.cs @@ -23,7 +23,7 @@ */ using NCDK.Common.Collections; -using static NCDK.Graphs.GraphUtil; +using NCDK.Graphs; namespace NCDK.Isomorphisms { diff --git a/NCDK/Isomorphisms/UniqueAtomMatches.cs b/NCDK/Isomorphisms/UniqueAtomMatches.cs index 41337671..9126e9d0 100644 --- a/NCDK/Isomorphisms/UniqueAtomMatches.cs +++ b/NCDK/Isomorphisms/UniqueAtomMatches.cs @@ -75,7 +75,7 @@ public bool Apply(int[] input) /// /// an atom mapping /// a bit set of the mapped vertices (values in array) - private BitArray ToBitArray(int[] mapping) + private static BitArray ToBitArray(int[] mapping) { BitArray hits = new BitArray(0); foreach (var v in mapping) diff --git a/NCDK/Isomorphisms/UniversalIsomorphismTester.cs b/NCDK/Isomorphisms/UniversalIsomorphismTester.cs index 25697782..8771a9e2 100644 --- a/NCDK/Isomorphisms/UniversalIsomorphismTester.cs +++ b/NCDK/Isomorphisms/UniversalIsomorphismTester.cs @@ -94,9 +94,11 @@ namespace NCDK.Isomorphisms // @cdk.githash public class UniversalIsomorphismTester { - const int ID1 = 0; - const int ID2 = 1; - private long start; + private enum IdType + { + Id1 = 0, + Id2 = 1, + }; /// /// Sets the time in milliseconds until the substructure search will be breaked. @@ -131,59 +133,57 @@ public bool IsIsomorph(IAtomContainer g1, IAtomContainer g2) if (g1 is IQueryAtomContainer) throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); - if (g2.Atoms.Count != g1.Atoms.Count) return false; + if (g2.Atoms.Count != g1.Atoms.Count) + return false; // check single atom case if (g2.Atoms.Count == 1) { - IAtom atom = g1.Atoms[0]; - IAtom atom2 = g2.Atoms[0]; + var atom = g1.Atoms[0]; + var atom2 = g2.Atoms[0]; if (atom is IQueryAtom qAtom) return qAtom.Matches(g2.Atoms[0]); else if (atom2 is IQueryAtom qAtom2) return qAtom2.Matches(g1.Atoms[0]); else { - string atomSymbol = atom2.Symbol; - return g1.Atoms[0].Symbol.Equals(atomSymbol); + var atomSymbol = atom2.Symbol; + return g1.Atoms[0].Symbol.Equals(atomSymbol, StringComparison.Ordinal); } } return (GetIsomorphMap(g1, g2) != null); } /// - /// Returns the first isomorph mapping found or null. + /// Returns the first isomorph mapping found or . /// /// first molecule. Must not be an . /// second molecule. May be an . - /// the first isomorph mapping found projected of g1. This is a List of RMap objects containing Ids of matching bonds. - public IList GetIsomorphMap(IAtomContainer g1, IAtomContainer g2) + /// + /// the first isomorph mapping found projected of . + /// This is a enumerable of objects containing Ids of matching bonds. + /// + public IReadOnlyList GetIsomorphMap(IAtomContainer g1, IAtomContainer g2) { if (g1 is IQueryAtomContainer) throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); - IList result = null; - - IList> rMapsList = Search(g1, g2, GetBitSet(g1), GetBitSet(g2), false, false); - - if (!(rMapsList.Count == 0)) - result = rMapsList[0]; - - return result; + var rMapsList = Search(g1, g2, GetBitSet(g1), GetBitSet(g2), false, false); + return rMapsList.FirstOrDefault(); } /// - /// Returns the first isomorph 'atom mapping' found for g2 in g1. + /// Returns the first isomorph 'atom mapping' found for in . /// /// first molecule. Must not be an . /// second molecule. May be an . /// the first isomorph atom mapping found projected on g1. This is a List of RMap objects containing Ids of matching atoms. /// if the first molecules is not an instance of - public IList GetIsomorphAtomsMap(IAtomContainer g1, IAtomContainer g2) + public IReadOnlyList GetIsomorphAtomsMap(IAtomContainer g1, IAtomContainer g2) { if (g1 is IQueryAtomContainer) throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); - IList list = CheckSingleAtomCases(g1, g2); + var list = CheckSingleAtomCases(g1, g2); if (list == null) { return MakeAtomsMapOfBondsMap(GetIsomorphMap(g1, g2), g1, g2); @@ -204,8 +204,8 @@ public IList GetIsomorphAtomsMap(IAtomContainer g1, IAtomContainer g2) /// /// first molecule. Must not be an . /// second molecule. May be an . - /// the list of all the 'mappings' - public IList> GetIsomorphMaps(IAtomContainer g1, IAtomContainer g2) + /// the enumerable of all the 'mappings' + public IEnumerable> GetIsomorphMaps(IAtomContainer g1, IAtomContainer g2) { return Search(g1, g2, GetBitSet(g1), GetBitSet(g2), true, true); } @@ -223,15 +223,15 @@ public IList> GetIsomorphMaps(IAtomContainer g1, IAtomContainer g2) /// atom - atom mappings. Thus RMap.id1 is the index of the target atom /// and RMap.id2 is the index of the matching query atom (in this case, /// it will always be 0). Note that in such a case, there is no need - /// to call , + /// to call , /// though if it is called, then the /// return value is simply the same as the return value of this method. /// /// first molecule. Must not be an . /// second molecule. May be an . /// the list of all the 'mappings' found projected of g1 - /// - public IList> GetSubgraphMaps(IAtomContainer g1, IAtomContainer g2) + /// + public IEnumerable> GetSubgraphMaps(IAtomContainer g1, IAtomContainer g2) { return Search(g1, g2, new BitArray(g1.Bonds.Count), GetBitSet(g2), true, true); } @@ -241,18 +241,11 @@ public IList> GetSubgraphMaps(IAtomContainer g1, IAtomContainer g2) /// /// first molecule. Must not be an . /// second molecule. May be an . - /// the first subgraph bond mapping found projected on g1. This is a of objects containing Ids of matching bonds. - public IList GetSubgraphMap(IAtomContainer g1, IAtomContainer g2) + /// the first subgraph bond mapping found projected on g1. This is a of objects containing Ids of matching bonds. + public IReadOnlyList GetSubgraphMap(IAtomContainer g1, IAtomContainer g2) { - IList result = null; - IList> rMapsList = Search(g1, g2, new BitArray(g1.Bonds.Count), GetBitSet(g2), false, false); - - if (!(rMapsList.Count == 0)) - { - result = rMapsList[0]; - } - - return result; + var rMapsList = Search(g1, g2, new BitArray(g1.Bonds.Count), GetBitSet(g2), false, false); + return rMapsList.FirstOrDefault(); } /// @@ -263,19 +256,16 @@ public IList GetSubgraphMap(IAtomContainer g1, IAtomContainer g2) /// first molecule. Must not be an . /// substructure to be mapped. May be an . /// all subgraph atom mappings found projected on g1. This is a of objects containing Ids of matching atoms. - public IList> GetSubgraphAtomsMaps(IAtomContainer g1, IAtomContainer g2) + public IEnumerable> GetSubgraphAtomsMaps(IAtomContainer g1, IAtomContainer g2) { - IList list = CheckSingleAtomCases(g1, g2); + var list = CheckSingleAtomCases(g1, g2); if (list == null) { return MakeAtomsMapsOfBondsMaps(GetSubgraphMaps(g1, g2), g1, g2); } else { - IList> atomsMap = new List> - { - list - }; + var atomsMap = new[] { list }; return atomsMap; } } @@ -287,9 +277,9 @@ public IList> GetSubgraphAtomsMaps(IAtomContainer g1, IAtomContainer /// first molecule. Must not be an . /// substructure to be mapped. May be an . /// the first subgraph atom mapping found projected on g1. This is a of objects containing Ids of matching atoms. - public IList GetSubgraphAtomsMap(IAtomContainer g1, IAtomContainer g2) + public IReadOnlyList GetSubgraphAtomsMap(IAtomContainer g1, IAtomContainer g2) { - IList list = CheckSingleAtomCases(g1, g2); + var list = CheckSingleAtomCases(g1, g2); if (list == null) { return MakeAtomsMapOfBondsMap(GetSubgraphMap(g1, g2), g1, g2); @@ -337,7 +327,7 @@ public bool IsSubgraph(IAtomContainer g1, IAtomContainer g2) } else { - if (atom2.Symbol.Equals(atom.Symbol)) + if (atom2.Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) return true; } } @@ -357,13 +347,12 @@ public bool IsSubgraph(IAtomContainer g1, IAtomContainer g2) /// first molecule. Must not be an . /// second molecule. May be an . /// the list of all the maximal common substructure found projected of g1 (list of ) - public IList GetOverlaps(IAtomContainer g1, IAtomContainer g2) + public IReadOnlyList GetOverlaps(IAtomContainer g1, IAtomContainer g2) { - start = DateTime.Now.Ticks / 10000; - IList> rMapsList = Search(g1, g2, new BitArray(g1.Bonds.Count), new BitArray(g2.Bonds.Count), true, false); + var rMapsList = Search(g1, g2, new BitArray(g1.Bonds.Count), new BitArray(g2.Bonds.Count), true, false); // projection on G1 - IList graphList = ProjectList(rMapsList, g1, ID1); + var graphList = ProjectList(rMapsList, g1, IdType.Id1); // reduction of set of solution (isomorphism and substructure // with different 'mappings' @@ -426,16 +415,15 @@ public static RGraph BuildRGraph(IAtomContainer g1, IAtomContainer g2) /// if false stop at the first structure found /// if true search all the 'mappings' for one same structure /// a List of Lists of objects that represent the search solutions - public IList> Search(IAtomContainer g1, IAtomContainer g2, BitArray c1, BitArray c2, bool findAllStructure, bool findAllMap) + public IEnumerable> Search(IAtomContainer g1, IAtomContainer g2, BitArray c1, BitArray c2, bool findAllStructure, bool findAllMap) { // remember start time - start = DateTime.Now.Ticks /10000; + var start = DateTime.Now.Ticks / 10000; // handle single query atom case separately if (g2.Atoms.Count == 1) { - List> matches = new List>(); - IAtom queryAtom = g2.Atoms[0]; + var queryAtom = g2.Atoms[0]; // we can have a IQueryAtomContainer *or* an IAtomContainer if (queryAtom is IQueryAtom qAtom) @@ -444,11 +432,8 @@ public IList> Search(IAtomContainer g1, IAtomContainer g2, BitArray { if (qAtom.Matches(atom)) { - List lmap = new List - { - new RMap(g1.Atoms.IndexOf(atom), 0) - }; - matches.Add(lmap); + var lmap = new[] { new RMap(g1.Atoms.IndexOf(atom), 0) }; + yield return lmap; } } } @@ -456,39 +441,34 @@ public IList> Search(IAtomContainer g1, IAtomContainer g2, BitArray { foreach (var atom in g1.Atoms) { - if (queryAtom.Symbol.Equals(atom.Symbol)) + if (queryAtom.Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) { - List lmap = new List - { - new RMap(g1.Atoms.IndexOf(atom), 0) - }; - matches.Add(lmap); + var lmap = new[] { new RMap(g1.Atoms.IndexOf(atom), 0) }; + yield return lmap; } } } - return matches; } - - // reset result - List> rMapsList = new List>(); - - // build the RGraph corresponding to this problem - RGraph rGraph = BuildRGraph(g1, g2); - // Set time data - rGraph.Timeout = Timeout; - rGraph.Start = start; - // parse the RGraph with the given constrains and options - rGraph.Parse(c1, c2, findAllStructure, findAllMap); - IList solutionList = rGraph.Solutions; - - // conversions of RGraph's internal solutions to G1/G2 mappings - foreach (var set in solutionList) + else { - IList rmap = rGraph.BitSetToRMap(set); - if (CheckQueryAtoms(rmap, g1, g2)) rMapsList.Add(rmap); + // build the RGraph corresponding to this problem + var rGraph = BuildRGraph(g1, g2); + // Set time data + rGraph.Timeout = Timeout; + rGraph.Start = start; + // parse the RGraph with the given constrains and options + rGraph.Parse(c1, c2, findAllStructure, findAllMap); + var solutionList = rGraph.Solutions; + + // conversions of RGraph's internal solutions to G1/G2 mappings + foreach (var set in solutionList) + { + var rmap = rGraph.BitSetToRMap(set); + if (CheckQueryAtoms(rmap, g1, g2)) + yield return rmap; + } } - - return rMapsList; + yield break; } /// @@ -498,17 +478,19 @@ public IList> Search(IAtomContainer g1, IAtomContainer g2, BitArray /// target graph /// query graph /// the atom matches are consistent - private bool CheckQueryAtoms(IList bondmap, IAtomContainer g1, IAtomContainer g2) + private static bool CheckQueryAtoms(IReadOnlyList bondmap, IAtomContainer g1, IAtomContainer g2) { - if (!(g2 is IQueryAtomContainer)) return true; - IList atommap = MakeAtomsMapOfBondsMap(bondmap, g1, g2); + if (!(g2 is IQueryAtomContainer)) + return true; + var atommap = MakeAtomsMapOfBondsMap(bondmap, g1, g2); foreach (var rmap in atommap) { - IAtom a1 = g1.Atoms[rmap.Id1]; - IAtom a2 = g2.Atoms[rmap.Id2]; - if (a2 is IQueryAtom) + var a1 = g1.Atoms[rmap.Id1]; + var a2 = g2.Atoms[rmap.Id2]; + if (a2 is IQueryAtom qa) { - if (!((IQueryAtom)a2).Matches(a1)) return false; + if (!qa.Matches(a1)) + return false; } } return true; @@ -522,19 +504,19 @@ private bool CheckQueryAtoms(IList bondmap, IAtomContainer g1, IAtomContai /// /// the list to project /// the molecule on which project - /// the id in the of the molecule g + /// the id in the of the molecule /// an AtomContainer - public static IAtomContainer Project(IList rMapList, IAtomContainer g, int id) + private static IAtomContainer Project(IReadOnlyList rMapList, IAtomContainer g, IdType id) { - IAtomContainer ac = g.Builder.NewAtomContainer(); + var ac = g.Builder.NewAtomContainer(); - IDictionary table = new Dictionary(); + var table = new Dictionary(); IAtom a; IBond bond; foreach (var rMap in rMapList) { - if (id == UniversalIsomorphismTester.ID1) + if (id == IdType.Id1) { bond = g.Bonds[rMap.Id1]; } @@ -558,7 +540,7 @@ public static IAtomContainer Project(IList rMapList, IAtomContainer g, int ac.Atoms.Add(a2); table.Add(a, a2); } - IBond newBond = g.Builder.NewBond(a1, a2, bond.Order); + var newBond = g.Builder.NewBond(a1, a2, bond.Order); newBond.IsAromatic = bond.IsAromatic; ac.Bonds.Add(newBond); } @@ -568,17 +550,17 @@ public static IAtomContainer Project(IList rMapList, IAtomContainer g, int /// /// Projects a list of RMapsList on a molecule. /// - /// list of RMapsList to project + /// lists of to project /// the molecule on which project - /// the id in the RMap of the molecule g - /// a list of AtomContainer - public static IList ProjectList(IList> rMapsList, IAtomContainer g, int id) + /// the id in the of the molecule + /// s + private static IReadOnlyList ProjectList(IEnumerable> rMapsList, IAtomContainer g, IdType id) { - List graphList = new List(); + var graphList = new List(); foreach (var rMapList in rMapsList) { - IAtomContainer ac = Project(rMapList, g, id); + var ac = Project(rMapList, g, id); graphList.Add(ac); } return graphList; @@ -590,18 +572,18 @@ public static IList ProjectList(IList> rMapsList, IA /// the list of structure to clean /// the list cleaned /// if there is a problem in obtaining subgraphs - private IList GetMaximum(IList graphList) + private List GetMaximum(IReadOnlyList graphList) { - List reducedGraphList = new List(); + var reducedGraphList = new List(); reducedGraphList.AddRange(graphList); for (int i = 0; i < graphList.Count; i++) { - IAtomContainer gi = graphList[i]; + var gi = graphList[i]; for (int j = i + 1; j < graphList.Count; j++) { - IAtomContainer gj = graphList[j]; + var gj = graphList[j]; // Gi included in Gj or Gj included in Gi then // reduce the irrelevant solution @@ -625,15 +607,15 @@ private IList GetMaximum(IList graphList) /// AtomContainer as query. May be an . /// of of objects for the Atoms (not Bonds!), null if no single atom case /// if the first molecule is an instance of IQueryAtomContainer - public static IList CheckSingleAtomCases(IAtomContainer g1, IAtomContainer g2) + public static IReadOnlyList CheckSingleAtomCases(IAtomContainer g1, IAtomContainer g2) { if (g1 is IQueryAtomContainer) throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); if (g2.Atoms.Count == 1) { - List arrayList = new List(); - IAtom atom = g2.Atoms[0]; + var arrayList = new List(); + var atom = g2.Atoms[0]; if (atom is IQueryAtom qAtom) { for (int i = 0; i < g1.Atoms.Count; i++) @@ -644,10 +626,10 @@ public static IList CheckSingleAtomCases(IAtomContainer g1, IAtomContainer } else { - string atomSymbol = atom.Symbol; + var atomSymbol = atom.Symbol; for (int i = 0; i < g1.Atoms.Count; i++) { - if (g1.Atoms[i].Symbol.Equals(atomSymbol)) + if (g1.Atoms[i].Symbol.Equals(atomSymbol, StringComparison.Ordinal)) arrayList.Add(new RMap(i, 0)); } } @@ -655,11 +637,11 @@ public static IList CheckSingleAtomCases(IAtomContainer g1, IAtomContainer } else if (g1.Atoms.Count == 1) { - List arrayList = new List(); - IAtom atom = g1.Atoms[0]; + var arrayList = new List(); + var atom = g1.Atoms[0]; for (int i = 0; i < g2.Atoms.Count; i++) { - IAtom atom2 = g2.Atoms[i]; + var atom2 = g2.Atoms[i]; if (atom2 is IQueryAtom qAtom) { if (qAtom.Matches(atom)) @@ -669,7 +651,7 @@ public static IList CheckSingleAtomCases(IAtomContainer g1, IAtomContainer } else { - if (atom2.Symbol.Equals(atom.Symbol)) + if (atom2.Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) arrayList.Add(new RMap(0, i)); } } @@ -685,23 +667,20 @@ public static IList CheckSingleAtomCases(IAtomContainer g1, IAtomContainer /// This makes maps of matching atoms out of a maps of matching bonds as produced by the /// Get(Subgraph|Ismorphism)Maps methods. /// - /// The list produced by the getMap method. + /// The list produced by method. /// The first atom container. Must not be a . /// The second one (first and second as in getMap). May be an . /// A List of s of objects of matching Atoms. - public static IList> MakeAtomsMapsOfBondsMaps(IList> l, IAtomContainer g1, IAtomContainer g2) + public static IEnumerable> MakeAtomsMapsOfBondsMaps(IEnumerable> l, IAtomContainer g1, IAtomContainer g2) { - if (l == null) - { - return l; - } - if (g2.Atoms.Count == 1) return l; // since the RMap is already an atom-atom mapping - IList> result = new List>(); foreach (var l2 in l) { - result.Add(MakeAtomsMapOfBondsMap(l2, g1, g2)); + if (g2.Atoms.Count == 1) + yield return l2; // since the RMap is already an atom-atom mapping + else + yield return MakeAtomsMapOfBondsMap(l2, g1, g2); } - return result; + yield break; } /// @@ -712,16 +691,17 @@ public static IList> MakeAtomsMapsOfBondsMaps(IList> l, /// first molecule. Must not be an . /// second molecule. May be an . /// The mapping found projected on g1. This is a of objects containing Ids of matching atoms. - public static IList MakeAtomsMapOfBondsMap(IList l, IAtomContainer g1, IAtomContainer g2) + public static IReadOnlyList MakeAtomsMapOfBondsMap(IReadOnlyList l, IAtomContainer g1, IAtomContainer g2) { - if (l == null) return (l); - List result = new List(); + if (l == null) + return l; + var result = new List(); for (int i = 0; i < l.Count; i++) { - IBond bond1 = g1.Bonds[l[i].Id1]; - IBond bond2 = g2.Bonds[l[i].Id2]; - IAtom[] atom1 = BondManipulator.GetAtomArray(bond1); - IAtom[] atom2 = BondManipulator.GetAtomArray(bond2); + var bond1 = g1.Bonds[l[i].Id1]; + var bond2 = g2.Bonds[l[i].Id2]; + var atom1 = BondManipulator.GetAtomArray(bond1); + var atom2 = BondManipulator.GetAtomArray(bond2); for (int j = 0; j < 2; j++) { var bondsConnectedToAtom1j = g1.GetConnectedBonds(atom1[j]); @@ -729,40 +709,27 @@ public static IList MakeAtomsMapOfBondsMap(IList l, IAtomContainer g { if (kbond != bond1) { - IBond testBond = kbond; + var testBond = kbond; for (int m = 0; m < l.Count; m++) { - IBond testBond2; if ((l[m]).Id1 == g1.Bonds.IndexOf(testBond)) { - testBond2 = g2.Bonds[(l[m]).Id2]; + var testBond2 = g2.Bonds[(l[m]).Id2]; for (int n = 0; n < 2; n++) { var bondsToTest = g2.GetConnectedBonds(atom2[n]); if (bondsToTest.Contains(testBond2)) { - RMap map; - if (j == n) - { - map = new RMap(g1.Atoms.IndexOf(atom1[0]), g2.Atoms.IndexOf(atom2[0])); - } - else - { - map = new RMap(g1.Atoms.IndexOf(atom1[1]), g2.Atoms.IndexOf(atom2[0])); - } + var map = j == n + ? new RMap(g1.Atoms.IndexOf(atom1[0]), g2.Atoms.IndexOf(atom2[0])) + : new RMap(g1.Atoms.IndexOf(atom1[1]), g2.Atoms.IndexOf(atom2[0])); if (!result.Contains(map)) { result.Add(map); } - RMap map2; - if (j == n) - { - map2 = new RMap(g1.Atoms.IndexOf(atom1[1]), g2.Atoms.IndexOf(atom2[1])); - } - else - { - map2 = new RMap(g1.Atoms.IndexOf(atom1[0]), g2.Atoms.IndexOf(atom2[1])); - } + var map2 = j == n + ? new RMap(g1.Atoms.IndexOf(atom1[1]), g2.Atoms.IndexOf(atom2[1])) + : new RMap(g1.Atoms.IndexOf(atom1[0]), g2.Atoms.IndexOf(atom2[1])); if (!result.Contains(map2)) { result.Add(map2); @@ -779,8 +746,8 @@ public static IList MakeAtomsMapOfBondsMap(IList l, IAtomContainer g } /// - /// Builds the nodes of the ( resolution graph ), from - /// two atom containers (description of the two molecules to compare) + /// Builds the nodes of the ( resolution graph ), from + /// two atom containers (description of the two molecules to compare) /// /// the target RGraph /// first molecule. Must not be an . @@ -799,19 +766,19 @@ private static void NodeConstructor(RGraph gr, IAtomContainer ac1, IAtomContaine { for (int j = 0; j < ac2.Bonds.Count; j++) { - IBond bondA2 = ac2.Bonds[j]; + var bondA2 = ac2.Bonds[j]; if (bondA2 is IQueryBond queryBond) { - IQueryAtom atom1 = (IQueryAtom)(bondA2.Begin); - IQueryAtom atom2 = (IQueryAtom)(bondA2.End); - IBond bond = ac1.Bonds[i]; + var atom1 = (IQueryAtom)(bondA2.Begin); + var atom2 = (IQueryAtom)(bondA2.End); + var bond = ac1.Bonds[i]; if (queryBond.Matches(bond)) { var bondAtom0 = bond.Begin; var bondAtom1 = bond.End; // ok, bonds match if (atom1.Matches(bondAtom0) && atom2.Matches(bondAtom1) - || atom1.Matches(bondAtom1) && atom2.Matches(bondAtom0)) + || atom1.Matches(bondAtom1) && atom2.Matches(bondAtom0)) { // ok, atoms match in either order gr.AddNode(new RNode(i, j)); @@ -826,7 +793,8 @@ private static void NodeConstructor(RGraph gr, IAtomContainer ac1, IAtomContaine var ac2Bondj = ac2.Bonds[j]; // bond type conditions if (( // same bond order and same aromaticity flag (either both on or off) - ac1Bondi.Order == ac2Bondj.Order && ac1Bondi.IsAromatic == ac2Bondj.IsAromatic) || ( // both bond are aromatic + ac1Bondi.Order == ac2Bondj.Order && ac1Bondi.IsAromatic == ac2Bondj.IsAromatic) + || ( // both bond are aromatic ac1Bondi.IsAromatic && ac2Bondj.IsAromatic)) { var ac1Bondi0 = ac1Bondi.Begin; @@ -836,9 +804,9 @@ private static void NodeConstructor(RGraph gr, IAtomContainer ac1, IAtomContaine // atom type conditions if ( // a1 = a2 && b1 = b2 - (ac1Bondi0.Symbol.Equals(ac2Bondj0.Symbol) && ac1Bondi1.Symbol.Equals(ac2Bondj1.Symbol)) || + (ac1Bondi0.Symbol.Equals(ac2Bondj0.Symbol, StringComparison.Ordinal) && ac1Bondi1.Symbol.Equals(ac2Bondj1.Symbol, StringComparison.Ordinal)) // a1 = b2 && b1 = a2 - (ac1Bondi0.Symbol.Equals(ac2Bondj1.Symbol) && ac1Bondi1.Symbol.Equals(ac2Bondj0.Symbol))) + || (ac1Bondi0.Symbol.Equals(ac2Bondj1.Symbol, StringComparison.Ordinal) && ac1Bondi1.Symbol.Equals(ac2Bondj0.Symbol, StringComparison.Ordinal))) { gr.AddNode(new RNode(i, j)); } @@ -851,10 +819,10 @@ private static void NodeConstructor(RGraph gr, IAtomContainer ac1, IAtomContaine } /// - /// Build edges of the s. - /// This method create the edge of the RGraph and - /// calculates the incompatibility and neighborhood - /// relationships between RGraph nodes. + /// Build edges of the s. + /// This method create the edge of the RGraph and + /// calculates the incompatibility and neighborhood + /// relationships between RGraph nodes. /// /// the rGraph /// first molecule. Must not be an . @@ -865,38 +833,34 @@ private static void ArcConstructor(RGraph gr, IAtomContainer ac1, IAtomContainer // each node is incompatible with himself for (int i = 0; i < gr.Graph.Count; i++) { - RNode x = (RNode)gr.Graph[i]; + var x = gr.Graph[i]; x.Forbidden.Set(i, true); } - IBond a1; - IBond a2; - IBond b1; - IBond b2; - gr.FirstGraphSize = ac1.Bonds.Count; gr.SecondGraphSize = ac2.Bonds.Count; for (int i = 0; i < gr.Graph.Count; i++) { - RNode x = gr.Graph[i]; + var x = gr.Graph[i]; // two nodes are neighbors if their adjacency // relationship in are equivalent in G1 and G2 // else they are incompatible. for (int j = i + 1; j < gr.Graph.Count; j++) { - RNode y = gr.Graph[j]; + var y = gr.Graph[j]; - a1 = ac1.Bonds[x.RMap.Id1]; - a2 = ac2.Bonds[x.RMap.Id2]; + var a1 = ac1.Bonds[x.RMap.Id1]; + var a2 = ac2.Bonds[x.RMap.Id2]; - b1 = ac1.Bonds[y.RMap.Id1]; - b2 = ac2.Bonds[y.RMap.Id2]; + var b1 = ac1.Bonds[y.RMap.Id1]; + var b2 = ac2.Bonds[y.RMap.Id2]; if (a2 is IQueryBond) { - if (a1.Equals(b1) || a2.Equals(b2) || !QueryAdjacencyAndOrder(a1, b1, a2, b2)) + if (a1.Equals(b1) || a2.Equals(b2) + || !QueryAdjacencyAndOrder(a1, b1, a2, b2)) { x.Forbidden.Set(j, true); y.Forbidden.Set(i, true); @@ -909,7 +873,8 @@ private static void ArcConstructor(RGraph gr, IAtomContainer ac1, IAtomContainer } else { - if (a1.Equals(b1) || a2.Equals(b2) || (!GetCommonSymbol(a1, b1).Equals(GetCommonSymbol(a2, b2)))) + if (a1.Equals(b1) || a2.Equals(b2) + || (!GetCommonSymbol(a1, b1).Equals(GetCommonSymbol(a2, b2), StringComparison.Ordinal))) { x.Forbidden.Set(j, true); y.Forbidden.Set(i, true); @@ -1029,14 +994,15 @@ private static bool QueryAdjacencyAndOrder(IBond bond1, IBond bond2, IBond query centralQueryAtom = queryBond2.End; } - if (centralAtom != null && centralQueryAtom != null && ((IQueryAtom)centralQueryAtom).Matches(centralAtom)) + if (centralAtom != null && centralQueryAtom != null + && ((IQueryAtom)centralQueryAtom).Matches(centralAtom)) { - IQueryAtom queryAtom1 = (IQueryAtom)queryBond1.GetConnectedAtom(centralQueryAtom); - IQueryAtom queryAtom2 = (IQueryAtom)queryBond2.GetConnectedAtom(centralQueryAtom); - IAtom atom1 = bond1.GetConnectedAtom(centralAtom); - IAtom atom2 = bond2.GetConnectedAtom(centralAtom); - if (queryAtom1.Matches(atom1) && queryAtom2.Matches(atom2) || queryAtom1.Matches(atom2) - && queryAtom2.Matches(atom1)) + var queryAtom1 = (IQueryAtom)queryBond1.GetConnectedAtom(centralQueryAtom); + var queryAtom2 = (IQueryAtom)queryBond2.GetConnectedAtom(centralQueryAtom); + var atom1 = bond1.GetConnectedAtom(centralAtom); + var atom2 = bond2.GetConnectedAtom(centralAtom); + if (queryAtom1.Matches(atom1) && queryAtom2.Matches(atom2) + || queryAtom1.Matches(atom2) && queryAtom2.Matches(atom1)) { return true; } @@ -1100,19 +1066,22 @@ private static bool TestSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac ac1SingleBondCount++; else if (bond.Order == BondOrder.Double) ac1DoubleBondCount++; - else if (bond.Order == BondOrder.Triple) ac1TripleBondCount++; + else if (bond.Order == BondOrder.Triple) + ac1TripleBondCount++; } for (int i = 0; i < ac2.Bonds.Count; i++) { bond = ac2.Bonds[i]; - if (bond is IQueryBond) continue; + if (bond is IQueryBond) + continue; if (bond.IsAromatic) ac2AromaticBondCount++; else if (bond.Order == BondOrder.Single) ac2SingleBondCount++; else if (bond.Order == BondOrder.Double) ac2DoubleBondCount++; - else if (bond.Order == BondOrder.Triple) ac2TripleBondCount++; + else if (bond.Order == BondOrder.Triple) + ac2TripleBondCount++; } if (ac2SingleBondCount > ac1SingleBondCount) return false; @@ -1123,41 +1092,43 @@ private static bool TestSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac for (int i = 0; i < ac1.Atoms.Count; i++) { atom = ac1.Atoms[i]; - if (atom.Symbol.Equals("S")) + if (string.Equals(atom.Symbol, "S", StringComparison.Ordinal)) ac1SCount++; - else if (atom.Symbol.Equals("N")) + else if (string.Equals(atom.Symbol, "N", StringComparison.Ordinal)) ac1NCount++; - else if (atom.Symbol.Equals("O")) + else if (string.Equals(atom.Symbol, "O", StringComparison.Ordinal)) ac1OCount++; - else if (atom.Symbol.Equals("F")) + else if (string.Equals(atom.Symbol, "F", StringComparison.Ordinal)) ac1FCount++; - else if (atom.Symbol.Equals("Cl")) + else if (string.Equals(atom.Symbol, "Cl", StringComparison.Ordinal)) ac1ClCount++; - else if (atom.Symbol.Equals("Br")) + else if (string.Equals(atom.Symbol, "Br", StringComparison.Ordinal)) ac1BrCount++; - else if (atom.Symbol.Equals("I")) + else if (string.Equals(atom.Symbol, "I", StringComparison.Ordinal)) ac1ICount++; - else if (atom.Symbol.Equals("C")) ac1CCount++; + else if (string.Equals(atom.Symbol, "C", StringComparison.Ordinal)) + ac1CCount++; } for (int i = 0; i < ac2.Atoms.Count; i++) { atom = ac2.Atoms[i]; if (atom is IQueryAtom) continue; - if (atom.Symbol.Equals("S")) + if (string.Equals(atom.Symbol, "S", StringComparison.Ordinal)) ac2SCount++; - else if (atom.Symbol.Equals("N")) + else if (string.Equals(atom.Symbol, "N", StringComparison.Ordinal)) ac2NCount++; - else if (atom.Symbol.Equals("O")) + else if (string.Equals(atom.Symbol, "O", StringComparison.Ordinal)) ac2OCount++; - else if (atom.Symbol.Equals("F")) + else if (string.Equals(atom.Symbol, "F", StringComparison.Ordinal)) ac2FCount++; - else if (atom.Symbol.Equals("Cl")) + else if (string.Equals(atom.Symbol, "Cl", StringComparison.Ordinal)) ac2ClCount++; - else if (atom.Symbol.Equals("Br")) + else if (string.Equals(atom.Symbol, "Br", StringComparison.Ordinal)) ac2BrCount++; - else if (atom.Symbol.Equals("I")) + else if (string.Equals(atom.Symbol, "I", StringComparison.Ordinal)) ac2ICount++; - else if (atom.Symbol.Equals("C")) ac2CCount++; + else if (string.Equals(atom.Symbol, "C", StringComparison.Ordinal)) + ac2CCount++; } if (ac1SCount < ac2SCount) return false; diff --git a/NCDK/Isomorphisms/VFState.cs b/NCDK/Isomorphisms/VFState.cs index 8cecc195..218b5a36 100644 --- a/NCDK/Isomorphisms/VFState.cs +++ b/NCDK/Isomorphisms/VFState.cs @@ -21,7 +21,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ -using static NCDK.Graphs.GraphUtil; + +using NCDK.Graphs; namespace NCDK.Isomorphisms { diff --git a/NCDK/Isomorphisms/VFSubState.cs b/NCDK/Isomorphisms/VFSubState.cs index 2044aed3..dc314b91 100644 --- a/NCDK/Isomorphisms/VFSubState.cs +++ b/NCDK/Isomorphisms/VFSubState.cs @@ -21,7 +21,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ -using static NCDK.Graphs.GraphUtil; + +using NCDK.Graphs; namespace NCDK.Isomorphisms { diff --git a/NCDK/Layout/AtomPlacer.cs b/NCDK/Layout/AtomPlacer.cs index 1517063d..08ef37dd 100644 --- a/NCDK/Layout/AtomPlacer.cs +++ b/NCDK/Layout/AtomPlacer.cs @@ -35,9 +35,9 @@ namespace NCDK.Layout { /// - /// Methods for generating coordinates for atoms in various situations. They can - /// be used for Automated Structure Diagram Generation or in the interactive - /// buildup of molecules by the user. + /// Methods for generating coordinates for atoms in various situations. They can + /// be used for Automated Structure Diagram Generation or in the interactive + /// buildup of molecules by the user. /// // @author steinbeck // @cdk.created 2003-08-29 @@ -72,32 +72,28 @@ public AtomPlacer() { } /// The partners to be placed /// The standard bond length for the newly placed atoms /// The 2D centre of the placed atoms - public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vector2 sharedAtomsCenter, - IAtomContainer unplacedNeighbours, double bondLength) + public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vector2 sharedAtomsCenter, IAtomContainer unplacedNeighbours, double bondLength) { double occupiedAngle = 0; - //double smallestDistance = double.MaxValue; - //IAtom[] nearestAtoms = new IAtom[2]; IAtom[] sortedAtoms = null; double startAngle = 0.0; double addAngle = 0.0; double radius = 0.0; double remainingAngle = 0.0; // calculate the direction away from the already placed partners of atom - //Vector2 sharedAtomsCenter = sharedAtoms.Get2DCenter(); - Vector2 sharedAtomsCenterVector = sharedAtomsCenter; + var sharedAtomsCenterVector = sharedAtomsCenter; - Vector2 newDirection = atom.Point2D.Value; - Vector2 occupiedDirection = sharedAtomsCenter; + var newDirection = atom.Point2D.Value; + var occupiedDirection = sharedAtomsCenter; occupiedDirection = Vector2.Subtract(occupiedDirection, newDirection); // if the placing on the centre atom we get NaNs just give a arbitrary direction the // rest works it's self out if (Math.Abs(occupiedDirection.Length()) < 0.001) occupiedDirection = new Vector2(0, 1); Debug.WriteLine("distributePartners->occupiedDirection.Lenght(): " + occupiedDirection.Length()); - List atomsToDraw = new List(); + var atomsToDraw = new List(); - Debug.WriteLine("Number of shared atoms: ", placedNeighbours.Atoms.Count); + Debug.WriteLine($"Number of shared atoms: {placedNeighbours.Atoms.Count}"); // IMPORTANT: This method is not supposed to handle the case of one or // no place neighbor. In the case of one placed neighbor, the chain @@ -114,15 +110,12 @@ public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vect // IMPORTANT: At this point we need a calculation of the start // angle. Not done yet. IAtom placedAtom = placedNeighbours.Atoms[0]; - // double xDiff = atom.GetX2d() - placedAtom.GetX2d(); - // double yDiff = atom.GetY2d() - placedAtom.GetY2d(); double xDiff = placedAtom.Point2D.Value.X - atom.Point2D.Value.X; double yDiff = placedAtom.Point2D.Value.Y - atom.Point2D.Value.Y; Debug.WriteLine("distributePartners->xdiff: " + Vectors.RadianToDegree(xDiff)); Debug.WriteLine("distributePartners->ydiff: " + Vectors.RadianToDegree(yDiff)); startAngle = GeometryUtil.GetAngle(xDiff, yDiff); - //- (Math.PI / 2.0); Debug.WriteLine("distributePartners->angle: " + Vectors.RadianToDegree(startAngle)); PopulatePolygonCorners(atomsToDraw, atom.Point2D.Value, startAngle, addAngle, bondLength); @@ -154,11 +147,11 @@ public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vect if (numTerminal == unplacedNeighbours.Atoms.Count) { - Vector2 a = NewVector(placedNeighbours.Atoms[0].Point2D.Value, atom.Point2D.Value); - Vector2 b = NewVector(placedNeighbours.Atoms[1].Point2D.Value, atom.Point2D.Value); - double d1 = GeometryUtil.GetAngle(a.X, a.Y); - double d2 = GeometryUtil.GetAngle(b.X, b.Y); - double sweep = Vectors.Angle(a, b); + var a = NewVector(placedNeighbours.Atoms[0].Point2D.Value, atom.Point2D.Value); + var b = NewVector(placedNeighbours.Atoms[1].Point2D.Value, atom.Point2D.Value); + var d1 = GeometryUtil.GetAngle(a.X, a.Y); + var d2 = GeometryUtil.GetAngle(b.X, b.Y); + var sweep = Vectors.Angle(a, b); if (sweep < Math.PI) { sweep = 2 * Math.PI - sweep; @@ -189,25 +182,28 @@ public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vect newDirection = newDirection * bondLength; newDirection = -newDirection; Debug.WriteLine($"distributePartners->newDirection.Lenght(): {newDirection.Length()}"); - Vector2 distanceMeasure = atom.Point2D.Value; + var distanceMeasure = atom.Point2D.Value; distanceMeasure += newDirection; // get the two sharedAtom partners with the smallest distance to the new center - sortedAtoms = AtomContainerManipulator.GetAtomArray(placedNeighbours); + sortedAtoms = placedNeighbours.Atoms.ToArray(); GeometryUtil.SortBy2DDistance(sortedAtoms, distanceMeasure); - Vector2 closestPoint1 = sortedAtoms[0].Point2D.Value; - Vector2 closestPoint2 = sortedAtoms[1].Point2D.Value; + var closestPoint1 = sortedAtoms[0].Point2D.Value; + var closestPoint2 = sortedAtoms[1].Point2D.Value; closestPoint1 -= atom.Point2D.Value; closestPoint2 -= atom.Point2D.Value; occupiedAngle = Vectors.Angle(closestPoint1, occupiedDirection); occupiedAngle += Vectors.Angle(closestPoint2, occupiedDirection); - double angle1 = GeometryUtil.GetAngle(sortedAtoms[0].Point2D.Value.X - atom.Point2D.Value.X, - sortedAtoms[0].Point2D.Value.Y - atom.Point2D.Value.Y); - double angle2 = GeometryUtil.GetAngle(sortedAtoms[1].Point2D.Value.X - atom.Point2D.Value.X, - sortedAtoms[1].Point2D.Value.Y - atom.Point2D.Value.Y); - double angle3 = GeometryUtil.GetAngle(distanceMeasure.X - atom.Point2D.Value.X, - distanceMeasure.Y - atom.Point2D.Value.Y); + var angle1 = GeometryUtil.GetAngle( + sortedAtoms[0].Point2D.Value.X - atom.Point2D.Value.X, + sortedAtoms[0].Point2D.Value.Y - atom.Point2D.Value.Y); + var angle2 = GeometryUtil.GetAngle( + sortedAtoms[1].Point2D.Value.X - atom.Point2D.Value.X, + sortedAtoms[1].Point2D.Value.Y - atom.Point2D.Value.Y); + var angle3 = GeometryUtil.GetAngle( + distanceMeasure.X - atom.Point2D.Value.X, + distanceMeasure.Y - atom.Point2D.Value.Y); if (debug) { try @@ -269,15 +265,9 @@ public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vect atomsToDraw.Add(unplacedNeighbours.Atoms[f]); } radius = bondLength; - startAngle = GeometryUtil.GetAngle(startAtom.Point2D.Value.X - atom.Point2D.Value.X, startAtom.Point2D.Value.Y - - atom.Point2D.Value.Y); + startAngle = GeometryUtil.GetAngle(startAtom.Point2D.Value.X - atom.Point2D.Value.X, startAtom.Point2D.Value.Y - atom.Point2D.Value.Y); Debug.WriteLine($"Before check: distributePartners->startAngle: {startAngle}"); - // if (startAngle < (Math.PI + 0.001) && startAngle > (Math.PI - // -0.001)) - // { - // startAngle = Math.PI/placedNeighbours.Atoms.Count; - // } - Debug.WriteLine("After check: distributePartners->startAngle: " + startAngle); + Debug.WriteLine($"After check: distributePartners->startAngle: {startAngle}"); PopulatePolygonCorners(atomsToDraw, atom.Point2D.Value, startAngle, addAngle, radius); } @@ -285,10 +275,10 @@ private bool DoAngleSnap(IAtom atom, IAtomContainer placedNeighbours) { if (placedNeighbours.Atoms.Count != 2) return false; - IBond b1 = Molecule.GetBond(atom, placedNeighbours.Atoms[0]); + var b1 = Molecule.GetBond(atom, placedNeighbours.Atoms[0]); if (!b1.IsInRing) return false; - IBond b2 = Molecule.GetBond(atom, placedNeighbours.Atoms[1]); + var b2 = Molecule.GetBond(atom, placedNeighbours.Atoms[1]); if (!b2.IsInRing) return false; @@ -316,33 +306,19 @@ private bool DoAngleSnap(IAtom atom, IAtomContainer placedNeighbours) /// The factor used to scale the initialBondVector public void PlaceLinearChain(IAtomContainer atomContainer, Vector2 initialBondVector, double bondLength) { - IAtomContainer withh = atomContainer.Builder.NewAtomContainer(atomContainer); + var withh = atomContainer.Builder.NewAtomContainer(atomContainer); // BUGFIX - withh does not have cloned cloned atoms, so changes are // reflected in our atom container. If we're using implicit hydrogens // the correct counts need saving and restoring - int[] numh = new int[atomContainer.Atoms.Count]; + var numh = new int[atomContainer.Atoms.Count]; for (int i = 0, n = atomContainer.Atoms.Count; i < n; i++) { numh[i] = atomContainer.Atoms[i].ImplicitHydrogenCount ?? 0; } - // SDG should lay out what it gets and not fiddle with molecules - // during layout so this was - // removed during debugging. Before you put this in again, contact - // er@doktor-steinbeck.de - - // if(GeometryTools.Has2DCoordinatesNew(atomContainer)==2){ - // try{ - // new HydrogenAdder().AddExplicitHydrogensToSatisfyValency(withh); - // }Catch(Exception ex){ - // Trace.TraceWarning("Exception in hydrogen adding. This could mean that cleanup does not respect E/Z: ", ex.Message); - // Debug.WriteLine(ex); - // } - // new HydrogenPlacer().PlaceHydrogens2D(withh, bondLength); - // } - Debug.WriteLine("Placing linear chain of length " + atomContainer.Atoms.Count); - Vector2 bondVector = initialBondVector; + Debug.WriteLine($"Placing linear chain of length {atomContainer.Atoms.Count}"); + var bondVector = initialBondVector; IBond prevBond = null; for (int f = 0; f < atomContainer.Atoms.Count - 1; f++) { @@ -364,7 +340,7 @@ public void PlaceLinearChain(IAtomContainer atomContainer, Vector2 initialBondVe int charge = atom.FormalCharge.Value; // double length of the last bond to determining next placement - Vector2 p = prevBond.GetOther(atom).Point2D.Value; + var p = prevBond.GetOther(atom).Point2D.Value; p = Vector2.Lerp(p, atom.Point2D.Value, 2); nextAtom.Point2D = p; } @@ -373,12 +349,9 @@ public void PlaceLinearChain(IAtomContainer atomContainer, Vector2 initialBondVe { try { - if (f > 2 - && BondTools.IsValidDoubleBondConfiguration(withh, - withh.GetBond(withh.Atoms[f - 2], withh.Atoms[f - 1]))) + if (f > 2 && BondTools.IsValidDoubleBondConfiguration(withh, withh.GetBond(withh.Atoms[f - 2], withh.Atoms[f - 1]))) { - trans = BondTools.IsCisTrans(withh.Atoms[f - 3], withh.Atoms[f - 2], withh.Atoms[f - 1], - withh.Atoms[f - 0], withh); + trans = BondTools.IsCisTrans(withh.Atoms[f - 3], withh.Atoms[f - 2], withh.Atoms[f - 1], withh.Atoms[f - 0], withh); } } catch (Exception) @@ -425,22 +398,23 @@ public Vector2 GetNextBondVector(IAtom atom, IAtom previousAtom, Vector2 distanc return b.Value - a.Value; } - double angle = GeometryUtil.GetAngle(previousAtom.Point2D.Value.X - atom.Point2D.Value.X, - previousAtom.Point2D.Value.Y - atom.Point2D.Value.Y); - double addAngle = Vectors.DegreeToRadian(120); - if (!trans) addAngle = Vectors.DegreeToRadian(60); - if (IsColinear(atom, Molecule.GetConnectedBonds(atom))) addAngle = Vectors.DegreeToRadian(180); + var angle = GeometryUtil.GetAngle(previousAtom.Point2D.Value.X - atom.Point2D.Value.X, previousAtom.Point2D.Value.Y - atom.Point2D.Value.Y); + var addAngle = Vectors.DegreeToRadian(120); + if (!trans) + addAngle = Vectors.DegreeToRadian(60); + if (IsColinear(atom, Molecule.GetConnectedBonds(atom))) + addAngle = Vectors.DegreeToRadian(180); angle += addAngle; - Vector2 vec1 = new Vector2(Math.Cos(angle), Math.Sin(angle)); - Vector2 point1 = atom.Point2D.Value; + var vec1 = new Vector2(Math.Cos(angle), Math.Sin(angle)); + var point1 = atom.Point2D.Value; point1 += vec1; - double distance1 = Vector2.Distance(point1, distanceMeasure); + var distance1 = Vector2.Distance(point1, distanceMeasure); angle += addAngle; - Vector2 vec2 = new Vector2(Math.Cos(angle), Math.Sin(angle)); - Vector2 point2 = atom.Point2D.Value; + var vec2 = new Vector2(Math.Cos(angle), Math.Sin(angle)); + var point2 = atom.Point2D.Value; point2 += vec2; - double distance2 = Vector2.Distance(point2, distanceMeasure); + var distance2 = Vector2.Distance(point2, distanceMeasure); if (distance2 > distance1) { Debug.WriteLine("Exiting AtomPlacer.GetNextBondVector()"); @@ -451,36 +425,30 @@ public Vector2 GetNextBondVector(IAtom atom, IAtom previousAtom, Vector2 distanc } /// - /// Populates the corners of a polygon with atoms. Used to place atoms in a - /// geometrically regular way around a ring center or another atom. If this is - /// used to place the bonding partner of an atom (and not to draw a ring) we - /// want to place the atoms such that those with highest "weight" are placed - /// farmost away from the rest of the molecules. The "weight" mentioned here is - /// calculated by a modified morgan number algorithm. + /// Populates the corners of a polygon with atoms. Used to place atoms in a + /// geometrically regular way around a ring center or another atom. If this is + /// used to place the bonding partner of an atom (and not to draw a ring) we + /// want to place the atoms such that those with highest "weight" are placed + /// far-most away from the rest of the molecules. The "weight" mentioned here is + /// calculated by a modified Morgan number algorithm. /// /// All the atoms to draw /// A start angle (in radians), giving the angle of the most clockwise atom which has already been placed /// An angle (in radians) to be added for each atom from atomsToDraw /// The center of a ring, or an atom for which the partners are to be placed /// The radius of the polygon to be populated: bond length or ring radius - public void PopulatePolygonCorners(IList atoms, - Vector2 center, - double thetaBeg, - double thetaStep, - double radius) + public static void PopulatePolygonCorners(IEnumerable atoms, Vector2 center, double thetaBeg, double thetaStep, double radius) { - int numAtoms = atoms.Count; double theta = thetaBeg; + Debug.WriteLine($"populatePolygonCorners(numAtoms={atoms.Count()}, center={center}, thetaBeg={Common.Mathematics.Vectors.RadianToDegree(thetaBeg)}, r={radius}"); - Debug.WriteLine($"populatePolygonCorners(numAtoms={numAtoms}, center={center}, thetaBeg={Common.Mathematics.Vectors.RadianToDegree(thetaBeg)}, r={radius}"); - - foreach (IAtom atom in atoms) + foreach (var atom in atoms) { theta += thetaStep; - double x = Math.Cos(theta) * radius; - double y = Math.Sin(theta) * radius; - double newX = x + center.X; - double newY = y + center.Y; + var x = Math.Cos(theta) * radius; + var y = Math.Sin(theta) * radius; + var newX = x + center.X; + var newY = y + center.Y; atom.Point2D = new Vector2(newX, newY); atom.IsPlaced = true; Debug.WriteLine($"populatePolygonCorners - angle={Vectors.RadianToDegree(theta)}, newX={newX}, newY={newY}"); @@ -488,7 +456,7 @@ public void PopulatePolygonCorners(IList atoms, } /// - /// Partition the bonding partners of a given atom into placed (coordinates assigned) and not placed. + /// Partition the bonding partners of a given atom into placed (coordinates assigned) and not placed. /// /// The atom whose bonding partners are to be partitioned /// A vector for the unplaced bonding partners to go in @@ -510,26 +478,25 @@ public void PartitionPartners(IAtom atom, IAtomContainer unplacedPartners, IAtom } /// - /// Search an aliphatic molecule for the longest chain. This is the method to - /// be used if there are no rings in the molecule and you want to layout the - /// longest chain in the molecule as a starting point of the structure diagram - /// generation. + /// Search an aliphatic molecule for the longest chain. This is the method to + /// be used if there are no rings in the molecule and you want to layout the + /// longest chain in the molecule as a starting point of the structure diagram + /// generation. /// /// The molecule to be search for the longest unplaced chain /// An AtomContainer holding the longest chain. /// Description of the Exception - static public IAtomContainer GetInitialLongestChain(IAtomContainer molecule) + public static IAtomContainer GetInitialLongestChain(IAtomContainer molecule) { Debug.WriteLine("Start of GetInitialLongestChain()"); - double[][] conMat = ConnectionMatrix.GetMatrix(molecule); + var conMat = ConnectionMatrix.GetMatrix(molecule); Debug.WriteLine("Computing all-pairs-shortest-paths"); - int[][] apsp = PathTools.ComputeFloydAPSP(conMat); + var apsp = PathTools.ComputeFloydAPSP(conMat); int maxPathLength = 0; int bestStartAtom = -1; int bestEndAtom = -1; IAtom atom = null; IAtom startAtom = null; - //IAtom endAtom = null; for (int f = 0; f < apsp.Length; f++) { atom = molecule.Atoms[f]; @@ -546,38 +513,34 @@ static public IAtomContainer GetInitialLongestChain(IAtomContainer molecule) } } } - Debug.WriteLine("Longest chain in molecule is of length " + maxPathLength + " between atoms " - + (bestStartAtom + 1) + " and " + (bestEndAtom + 1)); + Debug.WriteLine($"Longest chain in molecule is of length {maxPathLength} between atoms {bestStartAtom + 1} and {bestEndAtom + 1}"); startAtom = molecule.Atoms[bestStartAtom]; - //endAtom = Molecule.GetAtomAt(bestEndAtom); - IAtomContainer path = molecule.Builder.NewAtomContainer(); + var path = molecule.Builder.NewAtomContainer(); path.Atoms.Add(startAtom); path = GetLongestUnplacedChain(molecule, startAtom); - //PathTools.DepthFirstTargetSearch(molecule, startAtom, endAtom, path); Debug.WriteLine("End of GetInitialLongestChain()"); return path; } /// - /// Search a molecule for the longest unplaced, aliphatic chain in it. If an - /// aliphatic chain encounters an unplaced ring atom, the ring atom is also - /// appended to allow for it to be laid out. This gives us a vector for - /// attaching the unplaced ring later. + /// Search a molecule for the longest unplaced, aliphatic chain in it. If an + /// aliphatic chain encounters an unplaced ring atom, the ring atom is also + /// appended to allow for it to be laid out. This gives us a vector for + /// attaching the unplaced ring later. /// /// The molecule to be search for the longest unplaced chain /// A start atom from which the chain search starts /// An AtomContainer holding the longest unplaced chain. /// Description of the Exception - static public IAtomContainer GetLongestUnplacedChain(IAtomContainer molecule, IAtom startAtom) + public static IAtomContainer GetLongestUnplacedChain(IAtomContainer molecule, IAtom startAtom) { Debug.WriteLine("Start of getLongestUnplacedChain."); - //ConnectivityChecker cc = new ConnectivityChecker(); int longest = 0; int longestPathLength = 0; int maxDegreeSum = 0; int degreeSum = 0; - IAtomContainer[] pathes = new IAtomContainer[molecule.Atoms.Count]; + var pathes = new IAtomContainer[molecule.Atoms.Count]; for (int f = 0; f < molecule.Atoms.Count; f++) { molecule.Atoms[f].IsVisited = false; @@ -608,24 +571,24 @@ static public IAtomContainer GetLongestUnplacedChain(IAtomContainer molecule, IA } /// - /// Performs a breadthFirstSearch in an AtomContainer starting with a - /// particular sphere, which usually consists of one start atom, and searches - /// for the longest aliphatic chain which is yet unplaced. If the search - /// encounters an unplaced ring atom, it is also appended to the chain so that - /// this last bond of the chain can also be laid out. This gives us the - /// orientation for the attachment of the ring system. + /// Performs a breadthFirstSearch in an AtomContainer starting with a + /// particular sphere, which usually consists of one start atom, and searches + /// for the longest aliphatic chain which is yet unplaced. If the search + /// encounters an unplaced ring atom, it is also appended to the chain so that + /// this last bond of the chain can also be laid out. This gives us the + /// orientation for the attachment of the ring system. /// /// The AtomContainer to be searched /// A sphere of atoms to start the search with /// A vector of N paths (N = no of heavy atoms). /// Description of the Exception - static public void BreadthFirstSearch(IAtomContainer ac, IList sphere, IAtomContainer[] pathes) + public static void BreadthFirstSearch(IAtomContainer ac, IList sphere, IAtomContainer[] pathes) { IAtom nextAtom = null; int atomNr; int nextAtomNr; //IAtomContainer path = null; - List newSphere = new List(); + var newSphere = new List(); Debug.WriteLine("Start of breadthFirstSearch"); foreach (var atom in sphere) @@ -669,11 +632,11 @@ static public void BreadthFirstSearch(IAtomContainer ac, IList sphere, IA #if DEBUG /// - /// Returns a string with the numbers of all placed atoms in an AtomContainer + /// Returns a string with the numbers of all placed atoms in an AtomContainer /// /// The AtomContainer for which the placed atoms are to be listed /// A string with the numbers of all placed atoms in an AtomContainer - public string ListPlaced(IAtomContainer ac) + public static string ListPlaced(IAtomContainer ac) { string s = "Placed: "; for (int f = 0; f < ac.Atoms.Count; f++) @@ -699,7 +662,7 @@ public string ListPlaced(IAtomContainer ac) /// The for which the placed atoms are to be listed /// A string with the numbers of all placed atoms in an AtomContainer /// - static public string ListNumbers(IAtomContainer mol, IAtomContainer ac) + public static string ListNumbers(IAtomContainer mol, IAtomContainer ac) { string s = "Numbers: "; for (int f = 0; f < ac.Atoms.Count; f++) @@ -717,7 +680,7 @@ static public string ListNumbers(IAtomContainer mol, IAtomContainer ac) /// The Vector for which the placed atoms are to be listed /// Description of the Parameter /// A string with the numbers of all placed atoms in an AtomContainer - static public string ListNumbers(IAtomContainer mol, List ac) + public static string ListNumbers(IAtomContainer mol, List ac) { string s = "Numbers: "; for (int f = 0; f < ac.Count; f++) @@ -733,7 +696,7 @@ static public string ListNumbers(IAtomContainer mol, List ac) /// /// The AtomContainer to be searched /// True is all the atoms in the given AtomContainer have been placed - static public bool AllPlaced(IAtomContainer ac) + public static bool AllPlaced(IAtomContainer ac) { for (int f = 0; f < ac.Atoms.Count; f++) { @@ -746,37 +709,35 @@ static public bool AllPlaced(IAtomContainer ac) } /// - /// Marks all the atoms in the given AtomContainer as not placed + /// Marks all the atoms in the given AtomContainer as not placed /// /// The AtomContainer whose atoms are to be marked - static public void MarkNotPlaced(IAtomContainer ac) - { - for (int f = 0; f < ac.Atoms.Count; f++) - { - ac.Atoms[f].IsPlaced = false; - } - } + public static void MarkNotPlaced(IAtomContainer ac) + => MarkPlaced(ac, false); /// - /// Marks all the atoms in the given AtomContainer as placed + /// Marks all the atoms in the given AtomContainer as placed /// - /// The AtomContainer whose atoms are to be marked - static public void MarkPlaced(IAtomContainer ac) + /// The whose atoms are to be marked + public static void MarkPlaced(IAtomContainer ac) + => MarkPlaced(ac, true); + + public static void MarkPlaced(IAtomContainer ac, bool isPlaced) { for (int f = 0; f < ac.Atoms.Count; f++) { - ac.Atoms[f].IsPlaced = true; + ac.Atoms[f].IsPlaced = isPlaced; } } /// - /// Get all the placed atoms in an AtomContainer + /// Get all the placed atoms in an /// - /// The AtomContainer to be searched for placed atoms + /// The to be searched for placed atoms /// An AtomContainer containing all the placed atoms - static public IAtomContainer GetPlacedAtoms(IAtomContainer ac) + public static IAtomContainer GetPlacedAtoms(IAtomContainer ac) { - IAtomContainer ret = ac.Builder.NewAtomContainer(); + var ret = ac.Builder.NewAtomContainer(); for (int f = 0; f < ac.Atoms.Count; f++) { if (ac.Atoms[f].IsPlaced) @@ -796,8 +757,8 @@ internal static void CopyPlaced(IRing dest, IAtomContainer src) { foreach (IBond bond in src.Bonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; if (beg.IsPlaced) { dest.Atoms.Add(beg); @@ -823,15 +784,12 @@ internal static void CopyPlaced(IRing dest, IAtomContainer src) static int GetDegreeSum(IAtomContainer ac, IAtomContainer superAC) { int degreeSum = 0; - //string path = "DegreeSum for Path: "; for (int f = 0; f < ac.Atoms.Count; f++) { - //path += ac.Atoms[f].Symbol; degreeSum += superAC.GetConnectedBonds(ac.Atoms[f]).Count(); degreeSum += ac.Atoms[f].ImplicitHydrogenCount ?? 0; } - //Console.Out.WriteLine(path + ": " + degreeSum); return degreeSum; } @@ -853,7 +811,7 @@ internal static void Prioritise(IAtomContainer mol) /// static void Prioritise(IAtomContainer mol, int[][] adjList) { - int[] weights = GetPriority(mol, adjList); + var weights = GetPriority(mol, adjList); for (int i = 0; i < mol.Atoms.Count; i++) { mol.Atoms[i].SetProperty(Priority, weights[i]); @@ -871,10 +829,10 @@ static void Prioritise(IAtomContainer mol, int[][] adjList) /// the priority static int[] GetPriority(IAtomContainer mol, int[][] adjList) { - int n = mol.Atoms.Count; - int[] order = new int[n]; - int[] rank = new int[n]; - int[] prev = new int[n]; + var n = mol.Atoms.Count; + var order = new int[n]; + var rank = new int[n]; + var prev = new int[n]; // init priorities, Helson 99 favours cyclic (init=2) for (int f = 0; f < n; f++) @@ -927,7 +885,7 @@ static int[] GetPriority(IAtomContainer mol, int[][] adjList) /// -N=[N+]=N /// /// - bool IsColinear(IAtom atom, IEnumerable bonds) + private static bool IsColinear(IAtom atom, IEnumerable bonds) { if (bonds.Count() != 2) return false; @@ -973,7 +931,7 @@ bool IsColinear(IAtom atom, IEnumerable bonds) } [Obsolete] - static public bool ShouldBeLinear(IAtom atom, IAtomContainer molecule) + public static bool ShouldBeLinear(IAtom atom, IAtomContainer molecule) { int sum = 0; var bonds = molecule.GetConnectedBonds(atom); diff --git a/NCDK/Layout/Congestion.cs b/NCDK/Layout/Congestion.cs index bba8e307..7d617c32 100644 --- a/NCDK/Layout/Congestion.cs +++ b/NCDK/Layout/Congestion.cs @@ -25,6 +25,7 @@ using NCDK.Numerics; using NCDK.Tools.Manipulator; using System; +using System.Linq; namespace NCDK.Layout { @@ -37,8 +38,7 @@ sealed class Congestion { // lower bound on scores private const double MIN_SCORE = 0.00001; - - double[][] contribution; + readonly double[][] contribution; internal double score; IAtom[] atoms; @@ -46,7 +46,7 @@ public Congestion(IAtomContainer mol, int[][] adjList) { int numAtoms = mol.Atoms.Count; this.contribution = Arrays.CreateJagged(numAtoms, numAtoms); - this.atoms = AtomContainerManipulator.GetAtomArray(mol); + this.atoms = mol.Atoms.ToArray(); for (int v = 0; v < numAtoms; v++) foreach (var w in adjList[v]) contribution[v][v] = contribution[v][w] = -1; diff --git a/NCDK/Layout/CorrectGeometricConfiguration.cs b/NCDK/Layout/CorrectGeometricConfiguration.cs index 84866029..e1451a5b 100644 --- a/NCDK/Layout/CorrectGeometricConfiguration.cs +++ b/NCDK/Layout/CorrectGeometricConfiguration.cs @@ -79,7 +79,9 @@ internal sealed class CorrectGeometricConfiguration public static IAtomContainer Correct(IAtomContainer container) { if (container.StereoElements.Any()) +#pragma warning disable CA1806 // Do not ignore method results new CorrectGeometricConfiguration(container); +#pragma warning restore CA1806 // Do not ignore method results return container; } @@ -252,7 +254,7 @@ private void Reflect(int v, IBond bond) /// the point to reflect /// bond /// the reflected point - private Vector2 Reflect(Vector2 p, IBond bond) + private static Vector2 Reflect(Vector2 p, IBond bond) { IAtom a = bond.Begin; IAtom b = bond.End; @@ -269,7 +271,7 @@ private Vector2 Reflect(Vector2 p, IBond bond) /// plane x start /// plane y end /// the reflected point - private Vector2 Reflect(Vector2 p, double x0, double y0, double x1, double y1) + private static Vector2 Reflect(Vector2 p, double x0, double y0, double x1, double y1) { double dx, dy, a, b; diff --git a/NCDK/Layout/HydrogenPlacer.cs b/NCDK/Layout/HydrogenPlacer.cs index 3e050576..f737b3ca 100644 --- a/NCDK/Layout/HydrogenPlacer.cs +++ b/NCDK/Layout/HydrogenPlacer.cs @@ -91,7 +91,7 @@ public void PlaceHydrogens2D(IAtomContainer container, IAtom atom, double bondLe throw new ArgumentException("cannot place hydrogens on atom without coordinates"); Debug.WriteLine("placing hydrogens connected to atom ", atom.Symbol, ": ", atom.Point2D); - Debug.WriteLine("bond length", bondLength); + Debug.WriteLine($"bond length{bondLength}"); AtomPlacer atomPlacer = new AtomPlacer { @@ -107,7 +107,7 @@ public void PlaceHydrogens2D(IAtomContainer container, IAtom atom, double bondLe { if (conAtom.Point2D == null) { - if (conAtom.Symbol.Equals("H")) + if (string.Equals(conAtom.Symbol, "H", StringComparison.Ordinal)) { unplaced.Atoms.Add(conAtom); } diff --git a/NCDK/Layout/IdentityTemplateLibrary.cs b/NCDK/Layout/IdentityTemplateLibrary.cs index d6f3d88c..abf6fbd9 100644 --- a/NCDK/Layout/IdentityTemplateLibrary.cs +++ b/NCDK/Layout/IdentityTemplateLibrary.cs @@ -28,8 +28,8 @@ using NCDK.Smiles; using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Text; @@ -223,7 +223,8 @@ private string CreateCanonicalSmiles(IAtomContainer mol, int[] ordering) public static KeyValuePair DecodeEntry(string str) { int i = str.IndexOf(' '); - if (i < 0) throw new ArgumentException(); + if (i < 0) + throw new ArgumentException($"{nameof(str)} is not containing space.", nameof(str)); return new KeyValuePair(str.Substring(0, i), DecodeCoordinates(str.Substring(i + 1))); } @@ -238,7 +239,7 @@ public static Vector2[] DecodeCoordinates(string str) { int end = str.IndexOf(')', 2); if (end < 0) - return new Vector2[0]; + return Array.Empty(); var strs = Strings.Tokenize(str.Substring(2, end - 2), ';'); Vector2[] points = new Vector2[strs.Count]; for (int i = 0; i < strs.Count; i++) @@ -247,8 +248,8 @@ public static Vector2[] DecodeCoordinates(string str) int first = coord.IndexOf(','); int second = coord.IndexOf(',', first + 1); points[i] = new Vector2( - double.Parse(coord.Substring(0, first)), - double.Parse(coord.Substring(first + 1, second - (first + 1)))); + double.Parse(coord.Substring(0, first), NumberFormatInfo.InvariantInfo), + double.Parse(coord.Substring(first + 1, second - (first + 1)), NumberFormatInfo.InvariantInfo)); } return points; } @@ -258,7 +259,7 @@ public static Vector2[] DecodeCoordinates(string str) Vector2[] points = new Vector2[strs.Count / 2]; for (int i = 0; i < strs.Count; i += 2) { - points[i / 2] = new Vector2(double.Parse(strs[i]), double.Parse(strs[i + 1])); + points[i / 2] = new Vector2(double.Parse(strs[i], NumberFormatInfo.InvariantInfo), double.Parse(strs[i + 1], NumberFormatInfo.InvariantInfo)); } return points; } @@ -359,7 +360,7 @@ public bool AssignLayout(IAtomContainer container) /// /// molecule (or fragment) to lookup /// the coordinates - public ICollection GetCoordinates(IAtomContainer mol) + public IReadOnlyList GetCoordinates(IAtomContainer mol) { try { @@ -381,7 +382,7 @@ public ICollection GetCoordinates(IAtomContainer mol) } orderedCoordSet.Add(orderedCoords); } - return new ReadOnlyCollection(orderedCoordSet); + return orderedCoordSet; } catch (CDKException) { diff --git a/NCDK/Layout/LayoutRefiner.cs b/NCDK/Layout/LayoutRefiner.cs index 9f891520..b3930e3b 100644 --- a/NCDK/Layout/LayoutRefiner.cs +++ b/NCDK/Layout/LayoutRefiner.cs @@ -99,7 +99,7 @@ sealed class LayoutRefiner private readonly IAtomContainer mol; private readonly IDictionary idxs; private readonly int[][] adjList; - private readonly GraphUtil.EdgeToBondMap bondMap; + private readonly EdgeToBondMap bondMap; private readonly IAtom[] atoms; // measuring and finding congestion @@ -127,13 +127,13 @@ internal LayoutRefiner(IAtomContainer mol, ISet afix, ISet bfix) this.mol = mol; this.afix = afix; this.bfix = bfix; - this.bondMap = GraphUtil.EdgeToBondMap.WithSpaceFor(mol); + this.bondMap = EdgeToBondMap.WithSpaceFor(mol); this.adjList = GraphUtil.ToAdjList(mol, bondMap); this.idxs = new Dictionary(); foreach (var atom in mol.Atoms) idxs[atom] = idxs.Count; - this.atoms = AtomContainerManipulator.GetAtomArray(mol); - + this.atoms = mol.Atoms.ToArray(); + // buffers for storing coordinates this.buffer1 = new Vector2[atoms.Length]; this.buffer2 = new Vector2[atoms.Length]; @@ -298,7 +298,7 @@ public int Compare(AtomPair a, AtomPair b) /// first atom of second bond /// first atom of second bond /// bond is crossing - private bool IsCrossed(Vector2 beg1, Vector2 end1, Vector2 beg2, Vector2 end2) + private static bool IsCrossed(Vector2 beg1, Vector2 end1, Vector2 beg2, Vector2 end2) { return Vectors.LinesIntersect(beg1.X, beg1.Y, end1.X, end1.Y, beg2.X, beg2.Y, end2.X, end2.Y); } diff --git a/NCDK/Layout/MacroCycleLayout.cs b/NCDK/Layout/MacroCycleLayout.cs index fa98480b..a2bfae09 100644 --- a/NCDK/Layout/MacroCycleLayout.cs +++ b/NCDK/Layout/MacroCycleLayout.cs @@ -69,7 +69,7 @@ public MacroCycleLayout(IAtomContainer mol) /// the macrocycle /// the ring set the macrocycle belongs to (may only be it's self) /// layout was successfully, if false caller fall-back to regular polygons - public bool Layout(IRing macrocycle, IRingSet ringset) + public static bool Layout(IRing macrocycle, IRingSet ringset) { IAtomContainer anon = RoundUpIfNeeded(AtomContainerManipulator.Anonymise(macrocycle)); var coords = TEMPLATES.GetCoordinates(anon); @@ -99,7 +99,7 @@ public bool Layout(IRing macrocycle, IRingSet ringset) /// winding of ring CW/CCW /// winding of each turn in the ring /// the best scoring configuration - private MacroScore BestScore(IRing macrocycle, IRingSet ringset, int wind, int[] winding) + private static MacroScore BestScore(IRing macrocycle, IRingSet ringset, int wind, int[] winding) { int numAtoms = macrocycle.Atoms.Count; @@ -194,20 +194,20 @@ private MacroScore BestScore(IRing macrocycle, IRingSet ringset, int wind, int[] int nIncorrectStereo = 0; foreach (var se in macrocycle.StereoElements) { - if (se.Class == StereoElement.Classes.CisTrans) + if (se.Class == StereoClass.CisTrans) { IBond bond = (IBond)se.Focus; IAtom beg = bond.Begin; IAtom end = bond.End; - StereoElement.Configuration cfg; + StereoConfigurations cfg; if (winding[(macrocycle.Atoms.IndexOf(beg) + i) % numAtoms] == winding[(macrocycle.Atoms.IndexOf(end) + i) % numAtoms]) { - cfg = StereoElement.Configuration.Together; + cfg = StereoConfigurations.Together; } else { - cfg = StereoElement.Configuration.Opposite; + cfg = StereoConfigurations.Opposite; } if (cfg == se.Configure) { @@ -239,7 +239,7 @@ private MacroScore BestScore(IRing macrocycle, IRingSet ringset, int wind, int[] /// macrocycle ring /// shared atoms /// the integers - private List GetAttachedInOrder(IRing macrocycle, IAtomContainer shared) + private static List GetAttachedInOrder(IRing macrocycle, IAtomContainer shared) { var ringAttach = new List(); var visit = new HashSet(); @@ -270,7 +270,7 @@ private List GetAttachedInOrder(IRing macrocycle, IAtomContainer shared) /// the macrocycle /// rest of the ring system /// offset into the coordinates - private int SelectCoords(IEnumerable ps, Vector2[] coords, IRing macrocycle, IRingSet ringset) + private static int SelectCoords(IEnumerable ps, Vector2[] coords, IRing macrocycle, IRingSet ringset) { Debug.Assert(ps.Any()); int[] winding = new int[coords.Length]; diff --git a/NCDK/Layout/NonplanarBonds.cs b/NCDK/Layout/NonplanarBonds.cs index 1685e060..499455b2 100644 --- a/NCDK/Layout/NonplanarBonds.cs +++ b/NCDK/Layout/NonplanarBonds.cs @@ -70,7 +70,7 @@ internal sealed class NonplanarBonds private readonly IDictionary atomToIndex; /// Quick lookup of a bond give the atom index of it's atoms. - private readonly GraphUtil.EdgeToBondMap edgeToBond; + private readonly EdgeToBondMap edgeToBond; /// /// Assign non-planar, up and down labels to indicate tetrahedral configuration. Currently all @@ -81,8 +81,10 @@ internal sealed class NonplanarBonds /// an atom had no 2D coordinates or labels could not be assigned to a tetrahedral centre public static IAtomContainer Assign(IAtomContainer container) { - GraphUtil.EdgeToBondMap edgeToBond = GraphUtil.EdgeToBondMap.WithSpaceFor(container); + EdgeToBondMap edgeToBond = EdgeToBondMap.WithSpaceFor(container); +#pragma warning disable CA1806 // Do not ignore method results new NonplanarBonds(container, GraphUtil.ToAdjList(container, edgeToBond), edgeToBond); +#pragma warning restore CA1806 // Do not ignore method results return container; } @@ -92,7 +94,7 @@ public static IAtomContainer Assign(IAtomContainer container) /// structure /// graph adjacency list representation /// an atom had no 2D coordinates or labels could not be assigned to a tetrahedral centre - NonplanarBonds(IAtomContainer container, int[][] g, GraphUtil.EdgeToBondMap edgeToBond) + NonplanarBonds(IAtomContainer container, int[][] g, EdgeToBondMap edgeToBond) { this.container = container; this.tetrahedralElements = new ITetrahedralChirality[container.Atoms.Count]; @@ -207,7 +209,7 @@ public int Compare(int i, int j) } } - private void Rotate(Vector2 p, Vector2 pivot, double cos, double sin) + private static void Rotate(Vector2 p, Vector2 pivot, double cos, double sin) { double x = p.X - pivot.X; double y = p.Y - pivot.Y; @@ -217,7 +219,7 @@ private void Rotate(Vector2 p, Vector2 pivot, double cos, double sin) p.Y = ny + pivot.Y; } - private Vector2 GetRotated(Vector2 org, Vector2 piviot, double theta) + private static Vector2 GetRotated(Vector2 org, Vector2 piviot, double theta) { Vector2 cpy = org; Rotate(cpy, piviot, Math.Cos(theta), Math.Sin(theta)); @@ -264,7 +266,7 @@ private void ModifyAndLabel(SquarePlanar se) double blen = 0; foreach (IAtom atom in atoms) { - IBond bond = container.GetBond(se.Focus, atom); + var bond = container.GetBond(se.Focus, atom); // can't handled these using this method! if (bond.IsInRing) return; @@ -272,14 +274,14 @@ private void ModifyAndLabel(SquarePlanar se) blen += GeometryUtil.GetLength2D(bond); } blen /= bonds.Count; - IAtom focus = se.Focus; - Vector2 fp = focus.Point2D.Value; + var focus = se.Focus; + var fp = focus.Point2D.Value; foreach (IAtom atom in container.Atoms) atom.IsVisited = false; foreach (IBond bond in container.Bonds) bond.IsVisited = false; - Vector2 ref_ = new Vector2(fp.X, fp.Y + blen); + var ref_ = new Vector2(fp.X, fp.Y + blen); SnapBondToPosition(focus, bonds[0], GetRotated(ref_, fp, Vectors.DegreeToRadian(-60))); SnapBondToPosition(focus, bonds[1], GetRotated(ref_, fp, Vectors.DegreeToRadian(60))); SnapBondToPosition(focus, bonds[2], GetRotated(ref_, fp, Vectors.DegreeToRadian(120))); @@ -290,15 +292,15 @@ private void ModifyAndLabel(SquarePlanar se) SetBondDisplay(bonds[3], focus, BondStereo.Up); } - private bool DoMirror(List atoms) + private static bool DoMirror(List atoms) { int p = 1; for (int i = 0; i < atoms.Count; i++) { - IAtom a = atoms[i]; + var a = atoms[i]; for (int j = i + 1; j < atoms.Count; j++) { - IAtom b = atoms[j]; + var b = atoms[j]; if (a.AtomicNumber > b.AtomicNumber) p *= -1; } @@ -311,9 +313,9 @@ private void ModifyAndLabel(TrigonalBipyramidal se) var atoms = se.Normalize().Carriers.ToList(); var bonds = new List(4); double blen = 0; - foreach (IAtom atom in atoms) + foreach (var atom in atoms) { - IBond bond = container.GetBond(se.Focus, atom); + var bond = container.GetBond(se.Focus, atom); // can't handled these using this method! if (bond.IsInRing) return; @@ -321,13 +323,13 @@ private void ModifyAndLabel(TrigonalBipyramidal se) blen += GeometryUtil.GetLength2D(bond); } blen /= bonds.Count; - IAtom focus = se.Focus; - Vector2 fp = focus.Point2D.Value; + var focus = se.Focus; + var fp = focus.Point2D.Value; foreach (IAtom atom in container.Atoms) atom.IsVisited = false; foreach (IBond bond in container.Bonds) bond.IsVisited = false; - Vector2 ref_ = new Vector2(fp.X, fp.Y + blen); + var ref_ = new Vector2(fp.X, fp.Y + blen); // Optional but have a look at the equatorial ligands // and maybe invert the image based on the permutation @@ -364,7 +366,7 @@ private void ModifyAndLabel(Octahedral oc) double blen = 0; foreach (IAtom atom in atoms) { - IBond bond = container.GetBond(oc.Focus, atom); + var bond = container.GetBond(oc.Focus, atom); // can't handled these using this method! if (bond.IsInRing) return; @@ -372,13 +374,13 @@ private void ModifyAndLabel(Octahedral oc) blen += GeometryUtil.GetLength2D(bond); } blen /= bonds.Count; - IAtom focus = oc.Focus; - Vector2 fp = focus.Point2D.Value; + var focus = oc.Focus; + var fp = focus.Point2D.Value; foreach (IAtom atom in container.Atoms) atom.IsVisited = false; foreach (IBond bond in container.Bonds) bond.IsVisited = false; - Vector2 ref_ = new Vector2(fp.X, fp.Y + blen); + var ref_ = new Vector2(fp.X, fp.Y + blen); SnapBondToPosition(focus, bonds[0], GetRotated(ref_, fp, Vectors.DegreeToRadian(0))); SnapBondToPosition(focus, bonds[1], GetRotated(ref_, fp, Vectors.DegreeToRadian(60))); @@ -392,21 +394,28 @@ private void ModifyAndLabel(Octahedral oc) SetBondDisplay(bonds[4], focus, BondStereo.Up); } - private BondStereo Flip(BondStereo disp) + private static BondStereo Flip(BondStereo disp) { switch (disp) { - case BondStereo.Up: return BondStereo.UpInverted; - case BondStereo.UpInverted: return BondStereo.Up; - case BondStereo.Down: return BondStereo.DownInverted; - case BondStereo.DownInverted: return BondStereo.Down; - case BondStereo.UpOrDown: return BondStereo.UpOrDownInverted; - case BondStereo.UpOrDownInverted: return BondStereo.UpOrDown; - default: return disp; + case BondStereo.Up: + return BondStereo.UpInverted; + case BondStereo.UpInverted: + return BondStereo.Up; + case BondStereo.Down: + return BondStereo.DownInverted; + case BondStereo.DownInverted: + return BondStereo.Down; + case BondStereo.UpOrDown: + return BondStereo.UpOrDownInverted; + case BondStereo.UpOrDownInverted: + return BondStereo.UpOrDown; + default: + return disp; } } - private void SetBondDisplay(IBond bond, IAtom focus, BondStereo display) + private static void SetBondDisplay(IBond bond, IAtom focus, BondStereo display) { if (bond.Begin.Equals(focus)) bond.Stereo = display; @@ -421,9 +430,9 @@ private void SetBondDisplay(IBond bond, IAtom focus, BondStereo display) /// a extended tetrahedral element private void Label(ExtendedTetrahedral element) { - IAtom focus = element.Focus; - IAtom[] atoms = element.Peripherals; - IBond[] bonds = new IBond[4]; + var focus = element.Focus; + var atoms = element.Peripherals; + var bonds = new IBond[4]; int p = Parity(element.Winding); @@ -431,15 +440,14 @@ private void Label(ExtendedTetrahedral element) if (focusBonds.Count() != 2) { - Trace.TraceWarning( - "Non-cumulated carbon presented as the focus of extended tetrahedral stereo configuration"); + Trace.TraceWarning("Non-cumulated carbon presented as the focus of extended tetrahedral stereo configuration"); return; } var terminals = element.FindTerminalAtoms(container); - IAtom left = terminals[0]; - IAtom right = terminals[1]; + var left = terminals[0]; + var right = terminals[1]; // some bonds may be null if, this happens when an implicit atom // is present and one or more 'atoms' is a terminal atom @@ -450,7 +458,7 @@ private void Label(ExtendedTetrahedral element) // find the clockwise ordering (in the plane of the page) by sorting by // polar corodinates - int[] rank = new int[4]; + var rank = new int[4]; { for (int i = 0; i < 4; i++) rank[i] = i; @@ -458,7 +466,7 @@ private void Label(ExtendedTetrahedral element) p *= SortClockwise(rank, focus, atoms, 4); // assign all up/down labels to an auxiliary array - BondStereo[] labels = new BondStereo[4]; + var labels = new BondStereo[4]; { for (int i = 0; i < 4; i++) { @@ -468,7 +476,7 @@ private void Label(ExtendedTetrahedral element) } } - int[] priority = new int[] { 5, 5, 5, 5 }; + var priority = new int[] { 5, 5, 5, 5 }; { // set the label for the highest priority and available bonds on one side @@ -476,9 +484,11 @@ private void Label(ExtendedTetrahedral element) int i = 0; foreach (var v in Priority(atomToIndex[focus], atoms, 4)) { - IBond bond = bonds[v]; - if (bond == null) continue; - if (bond.Stereo == BondStereo.None && bond.Order == BondOrder.Single) priority[v] = i++; + var bond = bonds[v]; + if (bond == null) + continue; + if (bond.Stereo == BondStereo.None && bond.Order == BondOrder.Single) + priority[v] = i++; } } @@ -519,19 +529,19 @@ private void Label(ExtendedTetrahedral element) /// a extended tetrahedral element private void Label(Atropisomeric element) { - IBond focus = element.Focus; - IAtom beg = focus.Begin; - IAtom end = focus.End; - IAtom[] atoms = element.Carriers.ToArray(); - IBond[] bonds = new IBond[4]; + var focus = element.Focus; + var beg = focus.Begin; + var end = focus.End; + var atoms = element.Carriers.ToArray(); + var bonds = new IBond[4]; int p = 0; switch (element.Configure) { - case StereoElement.Configuration.Left: + case StereoConfigurations.Left: p = +1; break; - case StereoElement.Configuration.Right: + case StereoConfigurations.Right: p = -1; break; } @@ -544,23 +554,22 @@ private void Label(Atropisomeric element) bonds[3] = container.GetBond(end, atoms[3]); // may be back to front? - if (bonds[0] == null || bonds[1] == null || - bonds[2] == null || bonds[3] == null) + if (bonds[0] == null || bonds[1] == null || bonds[2] == null || bonds[3] == null) throw new InvalidOperationException("Unexpected configuration ordering, beg/end bonds should be in that order."); // find the clockwise ordering (in the plane of the page) by sorting by // polar corodinates - int[] rank = new int[4]; + var rank = new int[4]; for (var i = 0; i < 4; i++) rank[i] = i; - IAtom phantom = beg.Builder.NewAtom(); + var phantom = beg.Builder.NewAtom(); phantom.Point2D = new Vector2((beg.Point2D.Value.X + end.Point2D.Value.X) / 2, (beg.Point2D.Value.Y + end.Point2D.Value.Y) / 2); p *= SortClockwise(rank, phantom, atoms, 4); // assign all up/down labels to an auxiliary array - BondStereo[] labels = new BondStereo[4]; + var labels = new BondStereo[4]; for (var i = 0; i < 4; i++) { int v = rank[i]; @@ -568,7 +577,7 @@ private void Label(Atropisomeric element) labels[v] = p > 0 ? BondStereo.Up : BondStereo.Down; } - int[] priority = new int[] { 5, 5, 5, 5 }; + var priority = new int[] { 5, 5, 5, 5 }; // set the label for the highest priority and available bonds on one side // of the cumulated system, setting both sides doesn't make sense @@ -620,15 +629,16 @@ private void Label(Atropisomeric element) /// the labels could not be assigned private void Label(ITetrahedralChirality element) { - IAtom focus = element.ChiralAtom; - var atoms = element.Ligands; - IBond[] bonds = new IBond[4]; + var focus = element.ChiralAtom; + var atoms = element.Ligands.ToList(); + var bonds = new IBond[4]; - int p = Parity(element.Stereo); + var p = Parity(element.Stereo); int n = 0; // unspecified centre, no need to assign labels - if (p == 0) return; + if (p == 0) + return; for (int i = 0; i < 4; i++) { @@ -640,17 +650,14 @@ private void Label(ITetrahedralChirality element) { bonds[n] = container.GetBond(focus, atoms[i]); if (bonds[n] == null) - throw new ArgumentException("Inconsistent stereo," - + " tetrahedral centre" - + " contained atom not" - + " stored in molecule"); + throw new ArgumentException("Inconsistent stereo, tetrahedral centre contained atom not stored in molecule"); atoms[n] = atoms[i]; n++; } } // sort coordinates and adjust parity (rank gives us the sorted order) - int[] rank = new int[n]; + var rank = new int[n]; for (int i = 0; i < n; i++) rank[i] = i; p *= SortClockwise(rank, focus, atoms, n); @@ -666,9 +673,9 @@ private void Label(ITetrahedralChirality element) // which has anti-clockwise winding for (int i = 0; i < n; i++) { - Vector2 a = atoms[rank[i]].Point2D.Value; - Vector2 b = focus.Point2D.Value; - Vector2 c = atoms[rank[(i + 2) % n]].Point2D.Value; + var a = atoms[rank[i]].Point2D.Value; + var b = focus.Point2D.Value; + var c = atoms[rank[(i + 2) % n]].Point2D.Value; double det = (a.X - c.X) * (b.Y - c.Y) - (a.Y - c.Y) * (b.X - c.X); if (det > 0) { @@ -679,20 +686,21 @@ private void Label(ITetrahedralChirality element) } // assign all up/down labels to an auxiliary array - BondStereo[] labels = new BondStereo[n]; + var labels = new BondStereo[n]; for (int i = 0; i < n; i++) { - int v = rank[i]; + var v = rank[i]; // 4 neighbors (invert every other one) - if (n == 4) p *= -1; + if (n == 4) + p *= -1; labels[v] = invert == v ? p > 0 ? BondStereo.Down : BondStereo.Up : p > 0 ? BondStereo.Up : BondStereo.Down; } // set the label for the highest priority and available bond bool found = false; - BondStereo firstlabel = BondStereo.None; + var firstlabel = BondStereo.None; bool assignTwoLabels = AssignTwoLabels(bonds, labels); foreach (int v in Priority(atomToIndex[focus], atoms, n)) { @@ -722,14 +730,16 @@ private void Label(ITetrahedralChirality element) // it should be possible to always assign labels somewhere -> unchecked exception if (!found) throw new ArgumentException("could not assign non-planar (up/down) labels"); + + element.Ligands = atoms; } - private bool AssignTwoLabels(IBond[] bonds, BondStereo[] labels) + private static bool AssignTwoLabels(IBond[] bonds, BondStereo[] labels) { return labels.Length == 4 && CountRingBonds(bonds) != 3; } - private int CountRingBonds(IBond[] bonds) + private static int CountRingBonds(IBond[] bonds) { int rbonds = 0; foreach (IBond bond in bonds) @@ -746,7 +756,7 @@ private int CountRingBonds(IBond[] bonds) /// /// a value /// the parity - private int IndexParity(int x) + private static int IndexParity(int x) { return (x & 0x1) == 1 ? -1 : +1; } @@ -757,7 +767,7 @@ private int IndexParity(int x) /// /// configuration /// the parity - private int Parity(TetrahedralStereo stereo) + private static int Parity(TetrahedralStereo stereo) { switch (stereo) { @@ -791,15 +801,15 @@ private int NAdjacentCentres(int i) /// the atom /// number of atoms /// prioritised indices - private int[] Priority(int focus, IList atoms, int n) + private int[] Priority(int focus, IReadOnlyList atoms, int n) { - int[] rank = new int[n]; + var rank = new int[n]; for (int i = 0; i < n; i++) rank[i] = i; for (int j = 1; j < n; j++) { - int v = rank[j]; - int i = j - 1; + var v = rank[j]; + var i = j - 1; while ((i >= 0) && HasPriority(focus, atomToIndex[atoms[v]], atomToIndex[atoms[rank[i]]])) { rank[i + 1] = rank[i--]; @@ -809,11 +819,12 @@ private int[] Priority(int focus, IList atoms, int n) return rank; } - private bool IsSp3Carbon(IAtom atom, int deg) + private static bool IsSp3Carbon(IAtom atom, int deg) { - int? elem = atom.AtomicNumber; - int? hcnt = atom.ImplicitHydrogenCount; - if (elem == null || hcnt == null) return false; + var elem = atom.AtomicNumber; + var hcnt = atom.ImplicitHydrogenCount; + if (elem == null || hcnt == null) + return false; return elem == 6 && hcnt <= 1 && deg + hcnt == 4; } @@ -828,28 +839,36 @@ private bool IsSp3Carbon(IAtom atom, int deg) bool HasPriority(int focus, int i, int j) { // prioritise bonds to non-centres - if (tetrahedralElements[i] == null && tetrahedralElements[j] != null) return true; - if (tetrahedralElements[i] != null && tetrahedralElements[j] == null) return false; - if (doubleBondElements[i] == null && doubleBondElements[j] != null) return true; - if (doubleBondElements[i] != null && doubleBondElements[j] == null) return false; + if (tetrahedralElements[i] == null && tetrahedralElements[j] != null) + return true; + if (tetrahedralElements[i] != null && tetrahedralElements[j] == null) + return false; + if (doubleBondElements[i] == null && doubleBondElements[j] != null) + return true; + if (doubleBondElements[i] != null && doubleBondElements[j] == null) + return false; - IAtom iAtom = container.Atoms[i]; - IAtom jAtom = container.Atoms[j]; + var iAtom = container.Atoms[i]; + var jAtom = container.Atoms[j]; - bool iIsSp3 = IsSp3Carbon(iAtom, graph[i].Length); - bool jIsSp3 = IsSp3Carbon(jAtom, graph[j].Length); + var iIsSp3 = IsSp3Carbon(iAtom, graph[i].Length); + var jIsSp3 = IsSp3Carbon(jAtom, graph[j].Length); if (iIsSp3 != jIsSp3) return !iIsSp3; // avoid possible Sp3 centers - if (tetrahedralElements[i] == null && tetrahedralElements[j] != null) return true; - if (tetrahedralElements[i] != null && tetrahedralElements[j] == null) return false; + if (tetrahedralElements[i] == null && tetrahedralElements[j] != null) + return true; + if (tetrahedralElements[i] != null && tetrahedralElements[j] == null) + return false; // prioritise acyclic bonds - bool iCyclic = focus >= 0 ? ringSearch.Cyclic(focus, i) : ringSearch.Cyclic(i); - bool jCyclic = focus >= 0 ? ringSearch.Cyclic(focus, j) : ringSearch.Cyclic(j); - if (!iCyclic && jCyclic) return true; - if (iCyclic && !jCyclic) return false; + var iCyclic = focus >= 0 ? ringSearch.Cyclic(focus, i) : ringSearch.Cyclic(i); + var jCyclic = focus >= 0 ? ringSearch.Cyclic(focus, j) : ringSearch.Cyclic(j); + if (!iCyclic && jCyclic) + return true; + if (iCyclic && !jCyclic) + return false; // avoid placing on pseudo atoms if (iAtom.AtomicNumber > 0 && jAtom.AtomicNumber == 0) @@ -857,14 +876,16 @@ bool HasPriority(int focus, int i, int j) if (iAtom.AtomicNumber == 0 && jAtom.AtomicNumber > 0) return false; - int iDegree = graph[i].Length; - int iElem = iAtom.AtomicNumber.Value; - int jDegree = graph[j].Length; - int jElem = jAtom.AtomicNumber.Value; + var iDegree = graph[i].Length; + var iElem = iAtom.AtomicNumber.Value; + var jDegree = graph[j].Length; + var jElem = jAtom.AtomicNumber.Value; // rank carbon's last - if (iElem == 6) iElem = 256; - if (jElem == 6) jElem = 256; + if (iElem == 6) + iElem = 256; + if (jElem == 6) + jElem = 256; // terminal atoms are always best if (iDegree == 1 && jDegree > 1) @@ -879,8 +900,10 @@ bool HasPriority(int focus, int i, int j) return false; // prioritise atoms with fewer neighbors - if (iDegree < jDegree) return true; - if (iDegree > jDegree) return false; + if (iDegree < jDegree) + return true; + if (iDegree > jDegree) + return false; return false; } @@ -894,7 +917,7 @@ bool HasPriority(int focus, int i, int j) /// the neighbors of the focus /// the number of neighbors /// the permutation parity of the sort - private int SortClockwise(int[] indices, IAtom focus, IList atoms, int n) + private static int SortClockwise(int[] indices, IAtom focus, IReadOnlyList atoms, int n) { int x = 0; for (int j = 1; j < n; j++) @@ -920,28 +943,33 @@ private int SortClockwise(int[] indices, IAtom focus, IList atoms, int n) /// central point /// atom is before /// Sort points in clockwise order, ciamej - static bool Less(int i, int j, IList atoms, Vector2 center) + static bool Less(int i, int j, IReadOnlyList atoms, Vector2 center) { - Vector2 a = atoms[i].Point2D.Value; - Vector2 b = atoms[j].Point2D.Value; + var a = atoms[i].Point2D.Value; + var b = atoms[j].Point2D.Value; - if (a.X - center.X >= 0 && b.X - center.X < 0) return true; - if (a.X - center.X < 0 && b.X - center.X >= 0) return false; + if (a.X - center.X >= 0 && b.X - center.X < 0) + return true; + if (a.X - center.X < 0 && b.X - center.X >= 0) + return false; if (a.X - center.X == 0 && b.X - center.X == 0) { - if (a.Y - center.Y >= 0 || b.Y - center.Y >= 0) return a.Y > b.Y; + if (a.Y - center.Y >= 0 || b.Y - center.Y >= 0) + return a.Y > b.Y; return b.Y > a.Y; } // compute the cross product of vectors (center -> a) x (center -> b) - double det = (a.X - center.X) * (b.Y - center.Y) - (b.X - center.X) * (a.Y - center.Y); - if (det < 0) return true; - if (det > 0) return false; + var det = (a.X - center.X) * (b.Y - center.Y) - (b.X - center.X) * (a.Y - center.Y); + if (det < 0) + return true; + if (det > 0) + return false; // points a and b are on the same line from the center // check which point is closer to the center - double d1 = (a.X - center.X) * (a.X - center.X) + (a.Y - center.Y) * (a.Y - center.Y); - double d2 = (b.X - center.X) * (b.X - center.X) + (b.Y - center.Y) * (b.Y - center.Y); + var d1 = (a.X - center.X) * (a.X - center.X) + (a.Y - center.Y) * (a.Y - center.Y); + var d2 = (b.X - center.X) * (b.X - center.X) + (b.Y - center.Y) * (b.Y - center.Y); return d1 > d2; } @@ -953,23 +981,24 @@ static bool Less(int i, int j, IList atoms, Vector2 center) /// the bond to mark as unspecified private void LabelUnspecified(IBond doubleBond) { - IAtom aBeg = doubleBond.Begin; - IAtom aEnd = doubleBond.End; + var aBeg = doubleBond.Begin; + var aEnd = doubleBond.End; - int beg = atomToIndex[aBeg]; - int end = atomToIndex[aEnd]; + var beg = atomToIndex[aBeg]; + var end = atomToIndex[aEnd]; int nAdj = 0; - IAtom[] focus = new IAtom[4]; - IAtom[] adj = new IAtom[4]; + var focus = new IAtom[4]; + var adj = new IAtom[4]; // build up adj list of all potential atoms foreach (var neighbor in graph[beg]) { - IBond bond = edgeToBond[beg, neighbor]; + var bond = edgeToBond[beg, neighbor]; if (bond.Order == BondOrder.Single) { - if (nAdj == 4) return; // more than 4? not a stereo-dbond + if (nAdj == 4) + return; // more than 4? not a stereo-dbond focus[nAdj] = aBeg; adj[nAdj++] = container.Atoms[neighbor]; } @@ -981,10 +1010,11 @@ private void LabelUnspecified(IBond doubleBond) } foreach (var neighbor in graph[end]) { - IBond bond = edgeToBond[end, neighbor]; + var bond = edgeToBond[end, neighbor]; if (bond.Order == BondOrder.Single) { - if (nAdj == 4) return; // more than 4? not a stereo-dbond + if (nAdj == 4) + return; // more than 4? not a stereo-dbond focus[nAdj] = aEnd; adj[nAdj++] = container.Atoms[neighbor]; } @@ -995,14 +1025,14 @@ private void LabelUnspecified(IBond doubleBond) } } - int[] rank = Priority(-1, adj, nAdj); + var rank = Priority(-1, adj, nAdj); // set the bond to up/down wavy to mark unspecified stereochemistry taking care not // to accidentally mark another stereocentre as unspecified for (int i = 0; i < nAdj; i++) { - if (doubleBondElements[atomToIndex[adj[rank[i]]]] == null && - tetrahedralElements[atomToIndex[adj[rank[i]]]] == null) + if (doubleBondElements[atomToIndex[adj[rank[i]]]] == null + && tetrahedralElements[atomToIndex[adj[rank[i]]]] == null) { edgeToBond[atomToIndex[focus[rank[i]]], atomToIndex[adj[rank[i]]]].Stereo = BondStereo.UpOrDown; @@ -1023,7 +1053,7 @@ private void LabelUnspecified(IBond doubleBond) /// Double bond stereochemistry, InChI Technical Manual private bool IsCisTransEndPoint(int idx) { - IAtom atom = container.Atoms[idx]; + var atom = container.Atoms[idx]; // error: uninit atom if (atom.AtomicNumber == null || atom.FormalCharge == null || @@ -1085,19 +1115,19 @@ private List FindUnspecifiedDoubleBonds(int[][] adjList) if (bond.Order != BondOrder.Double) continue; - IAtom aBeg = bond.Begin; - IAtom aEnd = bond.End; + var aBeg = bond.Begin; + var aEnd = bond.End; - int beg = atomToIndex[aBeg]; - int end = atomToIndex[aEnd]; + var beg = atomToIndex[aBeg]; + var end = atomToIndex[aEnd]; // cyclic bond, ignore it (FIXME may be a cis/trans bond in macro cycle |V| > 7) if (ringSearch.Cyclic(beg, end)) continue; // stereo bond, ignore it depiction is correct - if ((doubleBondElements[beg] != null && doubleBondElements[beg].StereoBond == bond) || - (doubleBondElements[end] != null && doubleBondElements[end].StereoBond == bond)) + if ((doubleBondElements[beg] != null && doubleBondElements[beg].StereoBond == bond) + || (doubleBondElements[end] != null && doubleBondElements[end].StereoBond == bond)) continue; // is actually a tetrahedral centre @@ -1124,21 +1154,25 @@ private bool HasLinearEqualPaths(int[][] adjList, int start, int prev) int b = -1; foreach (var w in adjList[start]) { - if (w == prev) continue; - else if (a == -1) a = w; - else if (b == -1) b = w; - else return false; // ??? + if (w == prev) + continue; + else if (a == -1) + a = w; + else if (b == -1) + b = w; + else + return false; // ??? } if (b < 0) return false; var visit = new HashSet(); - IAtom aAtom = container.Atoms[a]; - IAtom bAtom = container.Atoms[b]; + var aAtom = container.Atoms[a]; + var bAtom = container.Atoms[b]; visit.Add(container.Atoms[start]); if (aAtom.IsInRing || bAtom.IsInRing) return false; - IAtom aNext = aAtom; - IAtom bNext = bAtom; + var aNext = aAtom; + var bNext = bAtom; while (aNext != null && bNext != null) { aAtom = aNext; @@ -1161,7 +1195,7 @@ private bool HasLinearEqualPaths(int[][] adjList, int start, int prev) int cntA = 0, cntB = 0; foreach (var w in adjList[atomToIndex[aAtom]]) { - IAtom atom = container.Atoms[w]; + var atom = container.Atoms[w]; if (visit.Contains(atom)) continue; // hydrogen @@ -1175,7 +1209,7 @@ private bool HasLinearEqualPaths(int[][] adjList, int start, int prev) } foreach (var w in adjList[atomToIndex[bAtom]]) { - IAtom atom = container.Atoms[w]; + var atom = container.Atoms[w]; if (visit.Contains(atom)) continue; // hydrogen @@ -1204,7 +1238,7 @@ private bool HasLinearEqualPaths(int[][] adjList, int start, int prev) return true; } - private bool NotEqual(int? a, int? b) + private static bool NotEqual(int? a, int? b) { return a == null ? b != null : !a.Equals(b); } diff --git a/NCDK/Layout/RingPlacer.cs b/NCDK/Layout/RingPlacer.cs index 6517aad1..ac6ba986 100644 --- a/NCDK/Layout/RingPlacer.cs +++ b/NCDK/Layout/RingPlacer.cs @@ -47,8 +47,7 @@ public class RingPlacer // indicate we want to snap to regular polygons for bridges, not generally applicable // but useful for macro cycles internal const string SnapHint = "sdg.snap.bridged"; - public static readonly double RAD_30 = Vectors.DegreeToRadian(-30); - const bool debug = false; + private static readonly double RAD_30 = Vectors.DegreeToRadian(-30); public IAtomContainer Molecule { get; set; } public AtomPlacer AtomPlacer { get; set; } = new AtomPlacer(); @@ -60,7 +59,9 @@ public class RingPlacer /// /// Default ring start angles. Map contains pairs: ring size with start angle. /// - public static IDictionary DefaultAngles { get; } = new Dictionary() + public static IReadOnlyDictionary DefaultAngles => defaultAngles; + + private static readonly Dictionary defaultAngles = new Dictionary() { {3, Math.PI* (0.1666667)}, {4, Math.PI * (0.25)}, @@ -72,7 +73,7 @@ public class RingPlacer /// /// Suggested ring start angles for JChempaint, different due to Y inversion of canvas. /// - public static IDictionary JCPAngles { get; } = new Dictionary() + public static IReadOnlyDictionary JCPAngles { get; } = new Dictionary() { {3, Math.PI * (0.5)}, {4, Math.PI * (0.25)}, @@ -94,10 +95,10 @@ public RingPlacer() /// The geometric center of these atoms /// A vector pointing the the center of the new ring /// The standard bondlength - public void PlaceRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtomsCenter, Vector2 ringCenterVector, double bondLength) + public virtual void PlaceRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtomsCenter, Vector2 ringCenterVector, double bondLength) { int sharedAtomCount = sharedAtoms.Atoms.Count; - Debug.WriteLine("placeRing -> sharedAtomCount: " + sharedAtomCount); + Debug.WriteLine($"placeRing -> sharedAtomCount: {sharedAtomCount}"); if (sharedAtomCount > 2) { PlaceBridgedRing(ring, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength); @@ -118,7 +119,7 @@ public void PlaceRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtom /// the ring to place. /// center coordinates of the ring. /// given bond length. - public void PlaceRing(IRing ring, Vector2 ringCenter, double bondLength) + public virtual void PlaceRing(IRing ring, Vector2 ringCenter, double bondLength) { PlaceRing(ring, ringCenter, bondLength, DefaultAngles); } @@ -130,9 +131,9 @@ public void PlaceRing(IRing ring, Vector2 ringCenter, double bondLength) /// center coordinates of the ring. /// given bond length. /// a map with start angles when drawing the ring. - public void PlaceRing(IRing ring, Vector2 ringCenter, double bondLength, IDictionary startAngles) + public virtual void PlaceRing(IRing ring, Vector2 ringCenter, double bondLength, IReadOnlyDictionary startAngles) { - var radius = this.GetNativeRingRadius(ring, bondLength); + var radius = GetNativeRingRadius(ring, bondLength); double addAngle = 2 * Math.PI / ring.RingSize; IAtom startAtom = ring.Atoms[0]; @@ -228,6 +229,9 @@ private static double Det(Vector2 a, Vector2 b, Vector2 c) /// The geometric center of these atoms /// A vector pointing the the center of the new ring /// The standard bondlength +#if !DEBUG + static +#endif private void PlaceBridgedRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtomsCenter, Vector2 ringCenterVector, double bondLength) { IAtom[] bridgeAtoms = GetBridgeAtoms(sharedAtoms); @@ -315,9 +319,9 @@ private void PlaceBridgedRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sh } #if DEBUG - Debug.WriteLine($"placeBridgedRing->atomsToPlace: {AtomPlacer.ListNumbers(Molecule, atoms)}"); - Debug.WriteLine($"placeBridgedRing->startAngle: {Vectors.RadianToDegree(startAngle)}"); - Debug.WriteLine($"placeBridgedRing->tStep: {Vectors.RadianToDegree(tStep)}"); + Debug.WriteLine($"{nameof(PlaceBridgedRing)}->atomsToPlace: {AtomPlacer.ListNumbers(Molecule, atoms)}"); + Debug.WriteLine($"{nameof(PlaceBridgedRing)}->startAngle: {Vectors.RadianToDegree(startAngle)}"); + Debug.WriteLine($"{nameof(PlaceBridgedRing)}->tStep: {Vectors.RadianToDegree(tStep)}"); #endif AtomPlacer.PopulatePolygonCorners(atoms, ringCenter, startAngle, -tStep, radius); } @@ -329,11 +333,11 @@ private void PlaceBridgedRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sh /// The ring to be placed /// The atoms of this ring, also members of another ring, which are already placed /// The geometric center of these atoms - /// A vector pointing the the center of the new ring - /// The standard bondlength - public void PlaceSpiroRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtomsCenter, Vector2 ringCenterVector, double bondLength) + /// A vector pointing the center of the new ring + /// The standard bond length + public virtual void PlaceSpiroRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtomsCenter, Vector2 ringCenterVector, double bondLength) { - Debug.WriteLine("placeSpiroRing"); + Debug.WriteLine(nameof(PlaceSpiroRing)); double radius = GetNativeRingRadius(ring, bondLength); Vector2 ringCenter = sharedAtomsCenter; ringCenterVector = Vector2.Normalize(ringCenterVector); @@ -364,8 +368,8 @@ public void PlaceSpiroRing(IRing ring, IAtomContainer sharedAtoms, Vector2 share currentAtom = currentBond.GetOther(currentAtom); atomsToDraw.Add(currentAtom); } - Debug.WriteLine("currentAtom " + currentAtom); - Debug.WriteLine("startAtom " + startAtom); + Debug.WriteLine($"currentAtom {currentAtom}"); + Debug.WriteLine($"startAtom {startAtom}"); AtomPlacer.PopulatePolygonCorners(atomsToDraw, ringCenter, startAngle, addAngle, radius); } @@ -378,7 +382,7 @@ public void PlaceSpiroRing(IRing ring, IAtomContainer sharedAtoms, Vector2 share /// The atoms of this ring, also members of another ring, which are already placed /// A vector pointing the the center of the new ring /// The standard bondlength - public void PlaceFusedRing(IRing ring, + public virtual void PlaceFusedRing(IRing ring, IAtomContainer sharedAtoms, Vector2 ringCenterVector, double bondLength) @@ -573,7 +577,7 @@ private static Vector2 GetPerpendicular(Vector2 a, Vector2 b, Vector2 reference) /// /// The ringset to be checked /// True if coordinates have been assigned to all atoms in all rings. - public bool AllPlaced(IRingSet rs) + public static bool AllPlaced(IRingSet rs) { for (int i = 0; i < rs.Count; i++) { @@ -586,11 +590,11 @@ public bool AllPlaced(IRingSet rs) } /// - /// Walks throught the atoms of each ring in a ring set and marks - /// a ring as PLACED if all of its atoms have been placed. + /// Walks through the atoms of each ring in a ring set and marks + /// a ring as if all of its atoms have been placed. /// /// The ringset to be checked - public void CheckAndMarkPlaced(IRingSet rs) + public static void CheckAndMarkPlaced(IRingSet rs) { bool allPlaced = true; bool ringsetPlaced = true; @@ -617,7 +621,7 @@ public void CheckAndMarkPlaced(IRingSet rs) /// /// The atoms (n > 2) which are shared by two rings /// The bridge atoms, i.e. the outermost atoms in the chain of more than two atoms which are shared by two rings - private IAtom[] GetBridgeAtoms(IAtomContainer sharedAtoms) + private static IAtom[] GetBridgeAtoms(IAtomContainer sharedAtoms) { IAtom[] bridgeAtoms = new IAtom[2]; IAtom atom; @@ -659,12 +663,12 @@ public void PartitionNonRingPartners(IAtom atom, IRing ring, IAtomContainer ring /// /// Returns the ring radius of a perfect polygons of size ring.Atoms.Count - /// The ring radius is the distance of each atom to the ringcenter. + /// The ring radius is the distance of each atom to the ring center. /// /// The ring for which the radius is to calculated /// The bond length for each bond in the ring /// The radius of the ring. - public double GetNativeRingRadius(IRing ring, double bondLength) + public static double GetNativeRingRadius(IRing ring, double bondLength) { int size = ring.Atoms.Count; double radius = bondLength / (2 * Math.Sin((Math.PI) / size)); @@ -677,8 +681,8 @@ public double GetNativeRingRadius(IRing ring, double bondLength) /// coordinates relative to it. /// /// The ring for which the center is to be calculated - /// A Vector2 pointing to the new ringcenter - public Vector2 GetRingCenterOfFirstRing(IRing ring, Vector2 bondVector, double bondLength) + /// A Vector2 pointing to the new ring center + public virtual Vector2 GetRingCenterOfFirstRing(IRing ring, Vector2 bondVector, double bondLength) { int size = ring.Atoms.Count; double radius = bondLength / (2 * Math.Sin((Math.PI) / size)); @@ -690,7 +694,7 @@ public Vector2 GetRingCenterOfFirstRing(IRing ring, Vector2 bondVector, double b return new Vector2((Math.Cos(rotangle) * newRingPerpendicular), (Math.Sin(rotangle) * newRingPerpendicular)); } - private void Rotate(Vector2 vec, double rad) + private static void Rotate(Vector2 vec, double rad) { double rx = (vec.X * Math.Cos(rad)) - (vec.Y * Math.Sin(rad)); double ry = (vec.X * Math.Sin(rad)) + (vec.Y * Math.Cos(rad)); diff --git a/NCDK/Layout/StructureDiagramGenerator.cs b/NCDK/Layout/StructureDiagramGenerator.cs index 362e4b16..8765ec25 100644 --- a/NCDK/Layout/StructureDiagramGenerator.cs +++ b/NCDK/Layout/StructureDiagramGenerator.cs @@ -67,7 +67,7 @@ namespace NCDK.Layout // @cdk.bug 1788686 public class StructureDiagramGenerator { - public static readonly double RAD_30 = Vectors.DegreeToRadian(-30); + private static readonly double RAD_30 = Vectors.DegreeToRadian(-30); public const double DefaultBondLength = 1.5; private IAtomContainer molecule; @@ -76,7 +76,8 @@ public class StructureDiagramGenerator /// The bond length used for laying out the molecule. /// The default value is 1.5. /// - public double BondLength => DefaultBondLength; + public double BondLength { get; set; } = DefaultBondLength; + private Vector2 firstBondVector; private RingPlacer ringPlacer = new RingPlacer(); private AtomPlacer atomPlacer = new AtomPlacer(); @@ -84,12 +85,13 @@ public class StructureDiagramGenerator private List ringSystems = null; private ISet afix = null; private ISet bfix = null; + /// /// Whether identity templates are used. Identity templates use an exact match /// are are very fast. They are used for layout of the 'primary' ring system /// in de facto orientation. /// - public bool UseIdentityTemplates { private get; set; } = true; + public bool UseIdentityTemplates { get; set; } = true; private bool alignMappedReaction = true; /// @@ -102,14 +104,15 @@ public class StructureDiagramGenerator /// private IdentityTemplateLibrary identityLibrary; - public static Vector2 DefaultBondVector = new Vector2(0, 1); + public static Vector2 DefaultBondVector { get; set; } = new Vector2(0, 1); private static IdentityTemplateLibrary DefaultTempleteLibrary = IdentityTemplateLibrary.LoadFromResource("custom-templates.smi") - .Add(IdentityTemplateLibrary.LoadFromResource("chebi-ring-templates.smi")); + .Add(IdentityTemplateLibrary.LoadFromResource("chebi-ring-templates.smi")); public StructureDiagramGenerator() : this(DefaultTempleteLibrary) - { } + { + } private StructureDiagramGenerator(IdentityTemplateLibrary identityLibrary) { @@ -121,7 +124,7 @@ private StructureDiagramGenerator(IdentityTemplateLibrary identityLibrary) /// /// The molecule to be layed out. public StructureDiagramGenerator(IAtomContainer molecule) - : this() + : this() { SetMolecule(molecule, false); } @@ -153,33 +156,33 @@ public void GenerateCoordinates(IAtomContainer mol) public void GenerateCoordinates(IReaction reaction) { // layout products and agents - foreach (IAtomContainer mol in reaction.Products) + foreach (var mol in reaction.Products) GenerateCoordinates(mol); - foreach (IAtomContainer mol in reaction.Agents) + foreach (var mol in reaction.Agents) GenerateCoordinates(mol); // do not align = simple layout of reactants if (alignMappedReaction) { - ISet mapped = ReactionManipulator.FindMappedBonds(reaction); + var mapped = ReactionManipulator.FindMappedBonds(reaction); - var refmap = new MultiDictionary>(); + var refmap = new MultiDictionary>(); - foreach (IAtomContainer mol in reaction.Products) + foreach (var mol in reaction.Products) { Cycles.MarkRingAtomsAndBonds(mol); - ConnectedComponents cc = new ConnectedComponents(GraphUtil.ToAdjListSubgraph(mol, mapped)); + var cc = new ConnectedComponents(GraphUtil.ToAdjListSubgraph(mol, mapped)); var parts = ConnectivityChecker.PartitionIntoMolecules(mol, cc.Components()); - foreach (IAtomContainer part in parts) + foreach (var part in parts) { // skip single atoms (unmapped) if (part.Atoms.Count == 1) continue; - IDictionary map = new Dictionary(); - foreach (IAtom atom in part.Atoms) + var map = new Dictionary(); + foreach (var atom in part.Atoms) { // safe as substructure should only be mapped bonds and therefore atoms! - int idx = atom.GetProperty(CDKPropertyName.AtomAtomMapping); + var idx = atom.GetProperty(CDKPropertyName.AtomAtomMapping); if (map.ContainsKey(idx)) { map[idx] = atom; @@ -193,18 +196,18 @@ public void GenerateCoordinates(IReaction reaction) } } - IDictionary afix = new Dictionary(); - ISet bfix = new HashSet(); + var afix = new Dictionary(); + var bfix = new HashSet(); - foreach (IAtomContainer mol in reaction.Reactants) + foreach (var mol in reaction.Reactants) { Cycles.MarkRingAtomsAndBonds(mol); - ConnectedComponents cc = new ConnectedComponents(GraphUtil.ToAdjListSubgraph(mol, mapped)); + var cc = new ConnectedComponents(GraphUtil.ToAdjListSubgraph(mol, mapped)); var parts = ConnectivityChecker.PartitionIntoMolecules(mol, cc.Components()); // we only aligned the largest part IAtomContainer largest = null; - foreach (IAtomContainer part in parts) + foreach (var part in parts) { if (largest == null || part.Bonds.Count > largest.Bonds.Count) largest = part; @@ -215,15 +218,16 @@ public void GenerateCoordinates(IReaction reaction) if (largest != null && largest.Atoms.Count > 1) { - int idx = largest.Atoms[0].GetProperty(CDKPropertyName.AtomAtomMapping); + var idx = largest.Atoms[0].GetProperty(CDKPropertyName.AtomAtomMapping); // select the largest and use those coordinates - IDictionary reference = Select(refmap[idx]); - foreach (IAtom atom in largest.Atoms) + var reference = Select(refmap[idx]); + foreach (var atom in largest.Atoms) { idx = atom.GetProperty(CDKPropertyName.AtomAtomMapping); - IAtom src = reference[idx]; - if (src == null) continue; + var src = reference[idx]; + if (src == null) + continue; atom.Point2D = src.Point2D; afix[atom] = src; } @@ -235,45 +239,45 @@ public void GenerateCoordinates(IReaction reaction) { if (aggresive) { - foreach (IBond bond in mol.Bonds) - { - if (afix.ContainsKey(bond.Begin) && afix.ContainsKey(bond.End)) + foreach (var bond in mol.Bonds) { - // only fix acyclic bonds if the source atoms were also acyclic - if (!bond.IsInRing) + if (afix.ContainsKey(bond.Begin) && afix.ContainsKey(bond.End)) { - IAtom srcBeg = afix[bond.Begin]; - IAtom srcEnd = afix[bond.End]; - foreach (IAtomContainer product in reaction.Products) + // only fix acyclic bonds if the source atoms were also acyclic + if (!bond.IsInRing) { - IBond srcBond = product.GetBond(srcBeg, srcEnd); - if (srcBond != null) + var srcBeg = afix[bond.Begin]; + var srcEnd = afix[bond.End]; + foreach (var product in reaction.Products) { - if (!srcBond.IsInRing) - bfix.Add(bond); // safe to add - break; + var srcBond = product.GetBond(srcBeg, srcEnd); + if (srcBond != null) + { + if (!srcBond.IsInRing) + bfix.Add(bond); // safe to add + break; + } } } - } - else - { - bfix.Add(bond); + else + { + bfix.Add(bond); + } } } } - } else { - foreach (IBond bond in mol.Bonds) + foreach (var bond in mol.Bonds) { if (afix.ContainsKey(bond.Begin) && afix.ContainsKey(bond.End)) { // only fix bonds that match their ring membership status - IAtom srcBeg = afix[bond.Begin]; - IAtom srcEnd = afix[bond.End]; - foreach (IAtomContainer product in reaction.Products) + var srcBeg = afix[bond.Begin]; + var srcEnd = afix[bond.End]; + foreach (var product in reaction.Products) { - IBond srcBond = product.GetBond(srcBeg, srcEnd); + var srcBond = product.GetBond(srcBeg, srcEnd); if (srcBond != null) { if (srcBond.IsInRing == bond.IsInRing) @@ -285,7 +289,7 @@ public void GenerateCoordinates(IReaction reaction) } // XXX: can do better afix.Clear(); - foreach (IBond bond in bfix) + foreach (var bond in bfix) { afix[bond.Begin] = null; afix[bond.End] = null; @@ -303,7 +307,7 @@ public void GenerateCoordinates(IReaction reaction) } else { - foreach (IAtomContainer mol in reaction.Reactants) + foreach (var mol in reaction.Reactants) GenerateCoordinates(mol); } } @@ -319,10 +323,10 @@ public int Compare(IAtomContainer a, IAtomContainer b) } } - private IDictionary Select(IEnumerable> refs) + private static IReadOnlyDictionary Select(IEnumerable> refs) { - IDictionary largest = Dictionaries.Empty(); - foreach (IDictionary ref_ in refs) + var largest = Dictionaries.Empty(); + foreach (var ref_ in refs) { if (ref_.Count > largest.Count) largest = ref_; @@ -359,7 +363,7 @@ public void SetMolecule(IAtomContainer mol, bool clone, ISet afix, ISet afix, ISet /// always false, substructure templates are not used anymore - [Obsolete] - public bool UseTemplates + [Obsolete("always false, substructure templates are not used anymore")] + public static bool UseTemplates { get { return false; } set { } @@ -408,13 +412,14 @@ public bool UseTemplates /// Always , substructure templates are not used anymore /// substructure templates are no longer used for layout but those provided here /// will be converted to identity templates - [Obsolete] + [Obsolete("substructure templates are no longer used for layout but those provided here ill be converted to identity templates")] public TemplateHandler TemplateHandler { - get { return null; } + get => throw new InvalidOperationException(); + set { - IdentityTemplateLibrary lib = value.ToIdentityTemplateLibrary(); + var lib = value.ToIdentityTemplateLibrary(); lib.Add(identityLibrary); identityLibrary = lib; // new ones take priority } @@ -466,13 +471,12 @@ public void GenerateExperimentalCoordinates() public void GenerateExperimentalCoordinates(Vector2 firstBondVector) { // first make a shallow copy: Atom/Bond references are kept - IAtomContainer original = molecule; - IAtomContainer shallowCopy = molecule.Builder.NewAtomContainer(molecule); + var original = molecule; + var shallowCopy = molecule.Builder.NewAtomContainer(molecule); // delete single-bonded H's from - //IAtom[] atoms = shallowCopy.Atoms; foreach (var curAtom in shallowCopy.Atoms) { - if (curAtom.Symbol.Equals("H")) + if (string.Equals(curAtom.Symbol, "H", StringComparison.Ordinal)) { if (shallowCopy.GetConnectedBonds(curAtom).Count() < 2) { @@ -486,7 +490,7 @@ public void GenerateExperimentalCoordinates(Vector2 firstBondVector) GenerateCoordinates(firstBondVector); double BondLength = GeometryUtil.GetBondLengthAverage(molecule); // ok, now create the coordinates for the hydrogens - HydrogenPlacer hPlacer = new HydrogenPlacer(); + var hPlacer = new HydrogenPlacer(); molecule = original; hPlacer.PlaceHydrogens2D(molecule, BondLength); } @@ -520,8 +524,8 @@ private void GenerateCoordinates(Vector2 firstBondVector, bool isConnected, bool // if molecule contains only one Atom, don't fail, simply set // coordinates to simplest: 0,0. See bug #780545 - Debug.WriteLine("Entry point of generateCoordinates()"); - Debug.WriteLine("We have a molecules with " + numAtoms + " atoms."); + Debug.WriteLine($"Entry point of {nameof(GenerateCoordinates)}"); + Debug.WriteLine($"We have a molecules with {numAtoms} atoms."); if (numAtoms == 0) { return; @@ -534,7 +538,7 @@ private void GenerateCoordinates(Vector2 firstBondVector, bool isConnected, bool else if (molecule.Bonds.Count == 1 && molecule.Atoms.Count == 2) { double xOffset = 0; - foreach (IAtom atom in molecule.Atoms) + foreach (var atom in molecule.Atoms) { atom.Point2D = new Vector2(xOffset, 0); xOffset += BondLength; @@ -579,8 +583,7 @@ private void GenerateCoordinates(Vector2 firstBondVector, bool isConnected, bool // display reasonable error on failed layout, otherwise we'll have a NPE somewhere if (iter == numAtoms && !AtomPlacer.AllPlaced(molecule)) - throw new CDKException("Could not generate layout? If a set of 'fixed' atoms were provided" - + " try removing these and regenerating the layout."); + throw new CDKException("Could not generate layout? If a set of 'fixed' atoms were provided try removing these and regenerating the layout."); if (!isSubLayout) { @@ -606,8 +609,9 @@ private void GenerateCoordinates(Vector2 firstBondVector, bool isConnected, bool /// atoms are fixed private bool HasFixedPart(IAtomContainer mol) { - if (!afix.Any()) return false; - foreach (IAtom atom in mol.Atoms) + if (!afix.Any()) + return false; + foreach (var atom in mol.Atoms) if (afix.Contains(atom)) return true; return false; @@ -622,7 +626,7 @@ private void SeedLayout() if (PrepareRingSystems() > 0) { PrepareRingSystems(); - foreach (IRingSet rset in ringSystems) + foreach (var rset in ringSystems) { if (rset.IsPlaced) { @@ -630,10 +634,10 @@ private void SeedLayout() } else { - List placed = new List(); - List unplaced = new List(); + var placed = new List(); + var unplaced = new List(); - foreach (IAtomContainer ring in rset) + foreach (var ring in rset) { if (ring.IsPlaced) placed.Add((IRing)ring); @@ -644,7 +648,7 @@ private void SeedLayout() // partially laid out rings if (!placed.Any()) { - foreach (IRing ring in unplaced) + foreach (var ring in unplaced) { if (ringPlacer.CompletePartiallyPlacedRing(rset, ring, BondLength)) placed.Add(ring); @@ -655,11 +659,11 @@ private void SeedLayout() while (unplaced.Any() && placed.Any()) { - foreach (IAtomContainer ring in placed) + foreach (var ring in placed) { - ringPlacer.PlaceConnectedRings(rset, (IRing)ring, RingPlacer.Fused, BondLength); - ringPlacer.PlaceConnectedRings(rset, (IRing)ring, RingPlacer.Bridged, BondLength); - ringPlacer.PlaceConnectedRings(rset, (IRing)ring, RingPlacer.Spiro, BondLength); + ringPlacer.PlaceConnectedRings(rset, ring, RingPlacer.Fused, BondLength); + ringPlacer.PlaceConnectedRings(rset, ring, RingPlacer.Bridged, BondLength); + ringPlacer.PlaceConnectedRings(rset, ring, RingPlacer.Spiro, BondLength); } placed.Clear(); foreach (var ring in unplaced) @@ -692,7 +696,7 @@ private void SeedLayout() RingPlacer.CountHetero(ringSystems); ringSystems.Sort(RingPlacer.RING_COMPARATOR); - int respect = LayoutRingSet(firstBondVector, ringSystems[0]); + var respect = LayoutRingSet(firstBondVector, ringSystems[0]); // rotate monocyclic and when >= 4 polycyclic if (respect == 1) @@ -728,7 +732,7 @@ private void SeedLayout() // and placed in on a horizontal axis Debug.WriteLine("Searching initialLongestChain for this purely aliphatic molecule"); IAtomContainer longestChain = AtomPlacer.GetInitialLongestChain(molecule); - Debug.WriteLine("Found linear chain of length " + longestChain.Atoms.Count); + Debug.WriteLine($"Found linear chain of length {longestChain.Atoms.Count}"); Debug.WriteLine("Setting coordinated of first atom to 0,0"); longestChain.Atoms[0].Point2D = new Vector2(0, 0); longestChain.Atoms[0].IsPlaced = true; @@ -745,7 +749,7 @@ private void SeedLayout() private int PrepareRingSystems() { - int numRings = Cycles.MarkRingAtomsAndBonds(molecule); + var numRings = Cycles.MarkRingAtomsAndBonds(molecule); // compute SSSR/MCB if (numRings > 0) { @@ -756,7 +760,7 @@ private int PrepareRingSystems() // Give a handle of our molecule to the ringPlacer ringPlacer.Molecule = molecule; - ringPlacer.CheckAndMarkPlaced(sssr); + RingPlacer.CheckAndMarkPlaced(sssr); // Partition the smallest set of smallest rings into disconnected // ring system. The RingPartioner returns a Vector containing @@ -768,14 +772,14 @@ private int PrepareRingSystems() // set the in-ring db stereo foreach (var se in molecule.StereoElements) { - if (se.Class == StereoElement.Classes.CisTrans) + if (se.Class == StereoClass.CisTrans) { - IBond stereoBond = (IBond)se.Focus; - IBond firstCarrier = (IBond)se.ReadOnlyCarriers[0]; - IBond secondCarrier = (IBond)se.ReadOnlyCarriers[1]; - foreach (IRingSet ringSet in ringSystems) + var stereoBond = (IBond)se.Focus; + var firstCarrier = (IBond)se.Carriers[0]; + var secondCarrier = (IBond)se.Carriers[1]; + foreach (var ringSet in ringSystems) { - foreach (IAtomContainer ring in ringSet) + foreach (var ring in ringSet) { if (ring.Contains(stereoBond)) { @@ -787,10 +791,8 @@ private int PrepareRingSystems() if (begBonds.Count != 1 || endBonds.Count != 1) continue; bool flipped = begBonds.Contains(firstCarrier) != endBonds.Contains(secondCarrier); - StereoElement.Configuration cfg = flipped ? se.Configure.Flip() : se.Configure; - ring.StereoElements.Add(new DoubleBondStereochemistry(stereoBond, - new IBond[] { begBonds[0], endBonds[0] }, - cfg)); + var cfg = flipped ? se.Configure.Flip() : se.Configure; + ring.StereoElements.Add(new DoubleBondStereochemistry(stereoBond, new IBond[] { begBonds[0], endBonds[0] }, cfg)); } } } @@ -805,7 +807,7 @@ private int PrepareRingSystems() return numRings; } - private void AssignStereochem(IAtomContainer molecule) + private static void AssignStereochem(IAtomContainer molecule) { // XXX: can't check this unless we store 'unspecified' double bonds // if (!molecule.stereoElements().iterator().hasNext()) @@ -821,7 +823,7 @@ private void RefinePlacement(IAtomContainer molecule) AtomPlacer.Prioritise(molecule); // refine the layout by rotating, bending, and stretching bonds - LayoutRefiner refiner = new LayoutRefiner(molecule, afix, bfix); + var refiner = new LayoutRefiner(molecule, afix, bfix); refiner.Refine(); // choose the orientation in which to display the structure @@ -849,14 +851,12 @@ private void RefinePlacement(IAtomContainer molecule) var attachBonds = molecule.GetConnectedBonds(begAttach); if (attachBonds.Count() == 1) { - IAtom end = attachBonds.First().GetOther(begAttach); - Vector2 xyBeg = begAttach.Point2D.Value; - Vector2 xyEnd = end.Point2D.Value; + var end = attachBonds.First().GetOther(begAttach); + var xyBeg = begAttach.Point2D.Value; + var xyEnd = end.Point2D.Value; // snap to horizontal '*-(end)-{rest of molecule}' - GeometryUtil.Rotate(molecule, - GeometryUtil.Get2DCenter(molecule), - -Math.Atan2(xyEnd.Y - xyBeg.Y, xyEnd.X - xyBeg.X)); + GeometryUtil.Rotate(molecule, GeometryUtil.Get2DCenter(molecule), -Math.Atan2(xyEnd.Y - xyBeg.Y, xyEnd.X - xyBeg.X)); // put the larger part of the structure is above the bond so fragments are drawn // semi-consistently @@ -881,9 +881,7 @@ private void RefinePlacement(IAtomContainer molecule) atom.Point2D = new Vector2(atom.Point2D.Value.X, -atom.Point2D.Value.Y); // rotate pointing downwards 30-degrees - GeometryUtil.Rotate(molecule, - GeometryUtil.Get2DCenter(molecule), - -Vectors.DegreeToRadian(30)); + GeometryUtil.Rotate(molecule, GeometryUtil.Get2DCenter(molecule), -Vectors.DegreeToRadian(30)); } } } @@ -910,25 +908,25 @@ private void FinalizeLayout(IAtomContainer mol) /// parameter at which we consider orientations equally good (bond align select) private static void SelectOrientation(IAtomContainer mol, double widthDiff, int alignDiff) { - double[] minmax = GeometryUtil.GetMinMax(mol); - Vector2 pivot = new Vector2(minmax[0] + ((minmax[2] - minmax[0]) / 2), minmax[1] + ((minmax[3] - minmax[1]) / 2)); + var minmax = GeometryUtil.GetMinMax(mol); + var pivot = new Vector2(minmax[0] + ((minmax[2] - minmax[0]) / 2), minmax[1] + ((minmax[3] - minmax[1]) / 2)); - double maxWidth = minmax[2] - minmax[0]; - int maxAligned = CountAlignedBonds(mol); + var maxWidth = minmax[2] - minmax[0]; + var maxAligned = CountAlignedBonds(mol); - Vector2[] coords = new Vector2[mol.Atoms.Count]; + var coords = new Vector2[mol.Atoms.Count]; for (int i = 0; i < mol.Atoms.Count; i++) coords[i] = mol.Atoms[i].Point2D.Value; - double step = Vectors.DegreeToRadian(30); - int numSteps = (360 / 30) - 1; + var step = Vectors.DegreeToRadian(30); + var numSteps = (360 / 30) - 1; for (int i = 0; i < numSteps; i++) { GeometryUtil.Rotate(mol, pivot, step); minmax = GeometryUtil.GetMinMax(mol); - double width = minmax[2] - minmax[0]; - double delta = Math.Abs(width - maxWidth); + var width = minmax[2] - minmax[0]; + var delta = Math.Abs(width - maxWidth); // if this orientation is significantly wider than the // best so far select it @@ -942,8 +940,8 @@ private static void SelectOrientation(IAtomContainer mol, double widthDiff, int // the number of bonds aligned to 30 deg (aesthetics) else if (delta <= widthDiff) { - int aligned = CountAlignedBonds(mol); - int alignDelta = aligned - maxAligned; + var aligned = CountAlignedBonds(mol); + var alignDelta = aligned - maxAligned; if (alignDelta > alignDiff || (alignDelta == 0 && width > maxWidth)) { maxAligned = aligned; @@ -966,21 +964,21 @@ private static void SelectOrientation(IAtomContainer mol, double widthDiff, int /// number of aligned bonds private static int CountAlignedBonds(IAtomContainer mol) { - double ref_ = Vectors.DegreeToRadian(30); - double diff = Vectors.DegreeToRadian(1); + var ref_ = Vectors.DegreeToRadian(30); + var diff = Vectors.DegreeToRadian(1); int count = 0; foreach (var bond in mol.Bonds) { - Vector2 beg = bond.Begin.Point2D.Value; - Vector2 end = bond.End.Point2D.Value; + var beg = bond.Begin.Point2D.Value; + var end = bond.End.Point2D.Value; if (beg.X > end.X) { - Vector2 tmp = beg; + var tmp = beg; beg = end; end = tmp; } - Vector2 vec = new Vector2(end.X - beg.X, end.Y - beg.Y); - double angle = Math.Atan2(vec.Y, vec.X); + var vec = new Vector2(end.X - beg.X, end.Y - beg.Y); + var angle = Math.Atan2(vec.Y, vec.X); if (Math.Abs(angle) - ref_ < diff) { @@ -989,6 +987,7 @@ private static int CountAlignedBonds(IAtomContainer mol) } return count; } + private double AdjustForHydrogen(IAtom atom, IAtomContainer mol) { var hcnt = atom.ImplicitHydrogenCount; @@ -1022,8 +1021,8 @@ private double AdjustForHydrogen(IAtom atom, IAtomContainer mol) } else if (bonds.Count() == 1) { - IAtom other = bonds.First().GetOther(atom); - double deltaX = atom.Point2D.Value.X - other.Point2D.Value.X; + var other = bonds.First().GetOther(atom); + var deltaX = atom.Point2D.Value.X - other.Point2D.Value.X; if (Math.Abs(deltaX) > 0.05) pos = (int)Math.Sign(deltaX); } @@ -1038,14 +1037,14 @@ private double AdjustForHydrogen(IAtom atom, IAtomContainer mol) /// the min/max x and y bounds private double[] GetAprxBounds(IAtomContainer mol) { - double maxX = -double.MaxValue; - double maxY = -double.MaxValue; - double minX = double.MaxValue; - double minY = double.MaxValue; - IAtom[] boundedAtoms = new IAtom[4]; + var maxX = -double.MaxValue; + var maxY = -double.MaxValue; + var minX = double.MaxValue; + var minY = double.MaxValue; + var boundedAtoms = new IAtom[4]; for (int i = 0; i < mol.Atoms.Count; i++) { - IAtom atom = mol.Atoms[i]; + var atom = mol.Atoms[i]; if (atom.Point2D != null) { if (atom.Point2D.Value.X < minX) @@ -1070,15 +1069,17 @@ private double[] GetAprxBounds(IAtomContainer mol) } } } - double[] minmax = new double[4]; + var minmax = new double[4]; minmax[0] = minX; minmax[1] = minY; minmax[2] = maxX; minmax[3] = maxY; - double minXAdjust = AdjustForHydrogen(boundedAtoms[0], mol); - double maxXAdjust = AdjustForHydrogen(boundedAtoms[1], mol); - if (minXAdjust < 0) minmax[0] += minXAdjust; - if (maxXAdjust > 0) minmax[1] += maxXAdjust; + var minXAdjust = AdjustForHydrogen(boundedAtoms[0], mol); + var maxXAdjust = AdjustForHydrogen(boundedAtoms[1], mol); + if (minXAdjust < 0) + minmax[0] += minXAdjust; + if (maxXAdjust > 0) + minmax[1] += maxXAdjust; return minmax; } @@ -1089,26 +1090,26 @@ private void GenerateFragmentCoordinates(IAtomContainer mol, IList rollback) mol.Bonds.RemoveAt(numBonds); } var limits = new List(); - int numFragments = frags.Count; + var numFragments = frags.Count; // avoid overwriting our state - ISet afixbackup = new HashSet(afix); - ISet bfixbackup = new HashSet(bfix); + var afixbackup = new HashSet(afix); + var bfixbackup = new HashSet(bfix); // generate the sub-layouts - foreach (IAtomContainer fragment in frags) + foreach (var fragment in frags) { SetMolecule(fragment, false, afix, bfix); GenerateCoordinates(DefaultBondVector, true, true); @@ -1120,24 +1121,24 @@ private void GenerateFragmentCoordinates(IAtomContainer mol, IList xOffsets[col]) xOffsets[col] = width; @@ -1156,14 +1157,13 @@ private void GenerateFragmentCoordinates(IAtomContainer mol, IList ionicBonds, IAtomContainer fragment) { - IChemObjectBuilder bldr = fragment.Builder; + var bldr = fragment.Builder; if (!ionicBonds.Any()) return; - IAtomContainer newfrag = bldr.NewAtomContainer(); - IAtom[] atoms = new IAtom[fragment.Atoms.Count]; + var newfrag = bldr.NewAtomContainer(); + var atoms = new IAtom[fragment.Atoms.Count]; for (int i = 0; i < atoms.Length; i++) atoms[i] = fragment.Atoms[i]; newfrag.SetAtoms(atoms); @@ -1210,26 +1210,26 @@ private void LengthenIonicBonds(IList ionicBonds, IAtomContainer fragment return; var subfragments = ConnectivityChecker.PartitionIntoMolecules(newfrag); - IDictionary atomToFrag = new Dictionary(); + var atomToFrag = new Dictionary(); // index atom->fragment - foreach (IAtomContainer subfragment in subfragments) - foreach (IAtom atom in subfragment.Atoms) + foreach (var subfragment in subfragments) + foreach (var atom in subfragment.Atoms) atomToFrag[atom] = subfragment; - foreach (IBond bond in ionicBonds) + foreach (var bond in ionicBonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; // select which bond to stretch from - int? numBegIonic = bond.Begin.GetProperty("ionicDegree"); - int? numEndIonic = bond.End.GetProperty("ionicDegree"); + var numBegIonic = bond.Begin.GetProperty("ionicDegree"); + var numEndIonic = bond.End.GetProperty("ionicDegree"); if (numBegIonic == null || numEndIonic == null) continue; if (numBegIonic > numEndIonic) { - IAtom tmp = beg; + var tmp = beg; beg = end; end = tmp; } @@ -1239,17 +1239,17 @@ private void LengthenIonicBonds(IList ionicBonds, IAtomContainer fragment continue; } - IAtomContainer endFrags = bldr.NewAtomContainer(); + var endFrags = bldr.NewAtomContainer(); if (!atomToFrag.TryGetValue(beg, out IAtomContainer begFrag)) continue; - foreach (IAtomContainer mol in subfragments) + foreach (var mol in subfragments) { if (mol != begFrag) endFrags.Add(mol); } - double dx = end.Point2D.Value.X - beg.Point2D.Value.X; - double dy = end.Point2D.Value.Y - beg.Point2D.Value.Y; - Vector2 bondVec = new Vector2(dx, dy); + var dx = end.Point2D.Value.X - beg.Point2D.Value.X; + var dy = end.Point2D.Value.Y - beg.Point2D.Value.Y; + var bondVec = new Vector2(dx, dy); bondVec = Vector2.Normalize(bondVec); bondVec *= BondLength / 2; // 1.5 bond length GeometryUtil.Translate2D(endFrags, bondVec); @@ -1259,7 +1259,7 @@ private void LengthenIonicBonds(IList ionicBonds, IAtomContainer fragment /// /// Property to cache the charge of a fragment. /// - private const string FragmentCharge = "FragmentCharge"; + private const string FragmentChargePropertyKey = "FragmentCharge"; /// /// Merge fragments with duplicate atomic ions (e.g. [Na+].[Na+].[Na+]) into @@ -1267,12 +1267,12 @@ private void LengthenIonicBonds(IList ionicBonds, IAtomContainer fragment /// /// input fragments (all connected) /// the merge ions - private List MergeAtomicIons(IEnumerable frags) + private static List MergeAtomicIons(IEnumerable frags) { var res = new List(); foreach (var frag in frags) { - IChemObjectBuilder bldr = frag.Builder; + var bldr = frag.Builder; if (frag.Bonds.Count > 0 || res.Count == 0) { @@ -1284,13 +1284,13 @@ private List MergeAtomicIons(IEnumerable frags) int i = 0; while (i < res.Count) { - IAtom iAtm = frag.Atoms[0]; + var iAtm = frag.Atoms[0]; if (res[i].Bonds.Count == 0) { - IAtom jAtm = res[i].Atoms[0]; - if (NullAsZero(iAtm.FormalCharge) == NullAsZero(jAtm.FormalCharge) && - NullAsZero(iAtm.AtomicNumber) == NullAsZero(jAtm.AtomicNumber) && - NullAsZero(iAtm.ImplicitHydrogenCount) == NullAsZero(jAtm.ImplicitHydrogenCount)) + var jAtm = res[i].Atoms[0]; + if ((iAtm.FormalCharge ?? 0) == (jAtm.FormalCharge ?? 0) && + (iAtm.AtomicNumber ?? 0) == (jAtm.AtomicNumber ?? 0) && + (iAtm.ImplicitHydrogenCount ?? 0) == (jAtm.ImplicitHydrogenCount ?? 0)) { break; } @@ -1320,9 +1320,9 @@ private List MergeAtomicIons(IEnumerable frags) /// charged fragment /// the charge sign to select (+1 : cation, -1: anion) /// the select atoms (includes duplicates) - private List SelectIons(IAtomContainer frag, int sign) + private static List SelectIons(IAtomContainer frag, int sign) { - int fragChg = frag.GetProperty(FragmentCharge).Value; + var fragChg = frag.GetProperty(FragmentChargePropertyKey); Trace.Assert(Math.Sign(fragChg) == sign); var atoms = new List(); @@ -1330,14 +1330,13 @@ private List SelectIons(IAtomContainer frag, int sign) { if (fragChg == 0) break; - int atmChg = NullAsZero(atom.FormalCharge); + var atmChg = atom.FormalCharge ?? 0; if (Math.Sign(atmChg) == sign) { - // skip in first pass if charge separated foreach (var bond in frag.GetConnectedBonds(atom)) { - if (Math.Sign(NullAsZero(bond.GetOther(atom).FormalCharge)) + sign == 0) + if (Math.Sign(bond.GetOther(atom).FormalCharge ?? 0) + sign == 0) goto continue_FIRST_PASS; } @@ -1359,7 +1358,7 @@ private List SelectIons(IAtomContainer frag, int sign) { if (fragChg == 0) break; - int atmChg = NullAsZero(atom.FormalCharge); + var atmChg = atom.FormalCharge ?? 0; if (Math.Sign(atmChg) == sign) { while (fragChg != 0 && atmChg != 0) @@ -1387,7 +1386,7 @@ private List SelectIons(IAtomContainer frag, int sign) /// /// connected fragments /// ionic bonds to make - private IList MakeIonicBonds(IEnumerable frags) + private static IList MakeIonicBonds(IEnumerable frags) { Trace.Assert(frags.Count() > 1); @@ -1403,9 +1402,9 @@ private IList MakeIonicBonds(IEnumerable frags) { int chg = 0; foreach (var atom in frag.Atoms) - chg += NullAsZero(atom.FormalCharge); + chg += atom.FormalCharge ?? 0; chgSum += chg; - frag.SetProperty(FragmentCharge, chg); + frag.SetProperty(FragmentChargePropertyKey, chg); if (chg < 0) negFrags.Add(frag); else if (chg > 0) @@ -1414,10 +1413,10 @@ private IList MakeIonicBonds(IEnumerable frags) // non-neutral or we only have one needsMerge fragment? if (chgSum != 0 || mergedFrags.Count == 1) - return new IBond[0]; + return Array.Empty(); - List cations = new List(); - List anions = new List(); + var cations = new List(); + var anions = new List(); // trivial case if (posFrags.Count == 1 && negFrags.Count == 1) @@ -1438,16 +1437,16 @@ private IList MakeIonicBonds(IEnumerable frags) } if (cations.Count != anions.Count && cations.Count == 0) - return new IBond[0]; + return Array.Empty(); - IChemObjectBuilder bldr = frags.First().Builder; + var bldr = frags.First().Builder; // make the bonds var ionicBonds = new List(cations.Count); for (int i = 0; i < cations.Count; i++) { - IAtom beg = cations[i]; - IAtom end = anions[i]; + var beg = cations[i]; + var end = anions[i]; bool unique = true; foreach (var bond in ionicBonds) @@ -1467,14 +1466,15 @@ private IList MakeIonicBonds(IEnumerable frags) } static FragmentChargeComparer AFragmentChargeComparer { get; } = new FragmentChargeComparer(); + // sort hi->lo fragment charge, if same charge then we put smaller // fragments (bond count) before in cations and after in anions class FragmentChargeComparer : IComparer { public int Compare(IAtomContainer a, IAtomContainer b) { - int qA = a.GetProperty(FragmentCharge); - int qB = b.GetProperty(FragmentCharge); + int qA = a.GetProperty(FragmentChargePropertyKey); + int qB = b.GetProperty(FragmentChargePropertyKey); int cmp = Math.Abs(qA).CompareTo(Math.Abs(qB)); if (cmp != 0) return cmp; int sign = Math.Sign(qA); @@ -1482,14 +1482,6 @@ public int Compare(IAtomContainer a, IAtomContainer b) } } - /// - /// Utility - safely access Object Integers as primitives, when we want the - /// default value of null to be zero. - /// - /// number - /// the number primitive or zero if null - private static int NullAsZero(int? x) => x ?? 0; - /// /// The main method of this StructurDiagramGenerator. Assign a molecule to the /// StructurDiagramGenerator, call the GenerateCoordinates() method and get @@ -1512,26 +1504,28 @@ public void GenerateCoordinates() private bool LookupRingSystem(IRingSet rs, IAtomContainer molecule, bool anon) { // identity templates are disabled - if (!UseIdentityTemplates) return false; + if (!UseIdentityTemplates) + return false; - IChemObjectBuilder bldr = molecule.Builder; + var bldr = molecule.Builder; - IAtomContainer ringSystem = bldr.NewAtomContainer(); + var ringSystem = bldr.NewAtomContainer(); foreach (var container in rs) ringSystem.Add(container); - ISet ringAtoms = new HashSet(); + var ringAtoms = new HashSet(); foreach (var atom in ringSystem.Atoms) ringAtoms.Add(atom); // a temporary molecule of the ring system and 'stubs' of the attached substituents - IAtomContainer ringWithStubs = bldr.NewAtomContainer(); + var ringWithStubs = bldr.NewAtomContainer(); ringWithStubs.Add(ringSystem); foreach (var bond in molecule.Bonds) { - IAtom atom1 = bond.Begin; - IAtom atom2 = bond.End; - if (IsHydrogen(atom1) || IsHydrogen(atom2)) continue; + var atom1 = bond.Begin; + var atom2 = bond.End; + if (IsHydrogen(atom1) || IsHydrogen(atom2)) + continue; if (ringAtoms.Contains(atom1) ^ ringAtoms.Contains(atom2)) { ringWithStubs.Atoms.Add(atom1); @@ -1546,9 +1540,9 @@ private bool LookupRingSystem(IRingSet rs, IAtomContainer molecule, bool anon) // Level 3 - check for an anonymous ring system // skeleton = all single bonds connecting different elements // anonymous = all single bonds connecting carbon - IAtomContainer skeletonStub = ClearHydrogenCounts(AtomContainerManipulator.Skeleton(ringWithStubs)); - IAtomContainer skeleton = ClearHydrogenCounts(AtomContainerManipulator.Skeleton(ringSystem)); - IAtomContainer anonymous = ClearHydrogenCounts(AtomContainerManipulator.Anonymise(ringSystem)); + var skeletonStub = ClearHydrogenCounts(AtomContainerManipulator.Skeleton(ringWithStubs)); + var skeleton = ClearHydrogenCounts(AtomContainerManipulator.Skeleton(ringSystem)); + var anonymous = ClearHydrogenCounts(AtomContainerManipulator.Anonymise(ringSystem)); foreach (var container in new[] { skeletonStub, skeleton, anonymous }) { @@ -1561,7 +1555,7 @@ private bool LookupRingSystem(IRingSet rs, IAtomContainer molecule, bool anon) { for (int i = 0; i < ringSystem.Atoms.Count; i++) { - IAtom atom = ringSystem.Atoms[i]; + var atom = ringSystem.Atoms[i]; atom.Point2D = container.Atoms[i].Point2D; atom.IsPlaced = true; } @@ -1579,8 +1573,9 @@ private bool LookupRingSystem(IRingSet rs, IAtomContainer molecule, bool anon) /// the atom is a hydrogen private static bool IsHydrogen(IAtom atom) { - if (atom.AtomicNumber != null) return atom.AtomicNumber == 1; - return "H".Equals(atom.Symbol); + if (atom.AtomicNumber != null) + return atom.AtomicNumber == 1; + return string.Equals("H", atom.Symbol, StringComparison.Ordinal); } /// @@ -1614,44 +1609,44 @@ private int LayoutRingSet(Vector2 firstBondVector, IRingSet rs) // sort small -> large // Get the most complex ring in this RingSet (largest prioritized) RingSetManipulator.Sort(rs); - IRing first = RingSetManipulator.GetMostComplexRing(rs); + var first = RingSetManipulator.GetMostComplexRing(rs); - bool macro = IsMacroCycle(first, rs); - bool macroDbStereo = macro && first.StereoElements.Any(); + var macro = IsMacroCycle(first, rs); + var macroDbStereo = macro && first.StereoElements.Any(); int result = 0; // Check for an exact match (identity) on the entire ring system if (!macroDbStereo) { if (LookupRingSystem(rs, molecule, rs.Count > 1)) - { - foreach (var container in rs) - container.IsPlaced = true; - rs.IsPlaced = true; - return macro ? 2 : 1; - } - else - { - // attempt ring peeling and retemplate - IRingSet core = GetRingSetCore(rs); - if (core.Count > 0 && - core.Count < rs.Count && - LookupRingSystem(core, molecule, !macro || rs.Count > 1)) { - foreach (var container in core) + foreach (var container in rs) container.IsPlaced = true; + rs.IsPlaced = true; + return macro ? 2 : 1; + } + else + { + // attempt ring peeling and retemplate + var core = GetRingSetCore(rs); + if (core.Count > 0 && + core.Count < rs.Count && + LookupRingSystem(core, molecule, !macro || rs.Count > 1)) + { + foreach (var container in core) + container.IsPlaced = true; + } } - } } // Place the most complex ring at the origin of the coordinate system if (!first.IsPlaced) { - IAtomContainer sharedAtoms = PlaceFirstBond(first.Bonds[0], firstBondVector); - if (!macro || !macroPlacer.Layout(first, rs)) + var sharedAtoms = PlaceFirstBond(first.Bonds[0], firstBondVector); + if (!macro || !MacroCycleLayout.Layout(first, rs)) { // de novo layout of ring as a regular polygon - Vector2 ringCenterVector = ringPlacer.GetRingCenterOfFirstRing(first, firstBondVector, BondLength); + var ringCenterVector = ringPlacer.GetRingCenterOfFirstRing(first, firstBondVector, BondLength); ringPlacer.PlaceRing(first, sharedAtoms, GeometryUtil.Get2DCenter(sharedAtoms), ringCenterVector, BondLength); } else @@ -1671,7 +1666,7 @@ private int LayoutRingSet(Vector2 firstBondVector, IRingSet rs) { // Place all connected rings start with those connected to first int thisRing = 0; - IRing ring = first; + var ring = first; do { if (ring.IsPlaced) @@ -1685,7 +1680,7 @@ private int LayoutRingSet(Vector2 firstBondVector, IRingSet rs) { thisRing = 0; } - ring = (IRing)rs[thisRing]; + ring = rs[thisRing]; } while (!AllPlaced(rs)); } @@ -1697,7 +1692,7 @@ private int LayoutRingSet(Vector2 firstBondVector, IRingSet rs) /// /// ring set /// the ring set core - private IRingSet GetRingSetCore(IRingSet rs) + private static IRingSet GetRingSetCore(IRingSet rs) { var ringlookup = new MultiDictionary(); var ringsystem = new LinkedHashSet(); @@ -1735,7 +1730,7 @@ private IRingSet GetRingSetCore(IRingSet rs) ringsystem.Remove(item); } while (toremove.Count != 0); - IRingSet core = rs.Builder.NewRingSet(); + var core = rs.Builder.NewRingSet(); foreach (var ring in ringsystem) core.Add(ring); @@ -1750,7 +1745,7 @@ private IRingSet GetRingSetCore(IRingSet rs) /// ring to check /// rest of ring system /// ring is a macro cycle - private bool IsMacroCycle(IRing ring, IChemObjectSet rs) + private static bool IsMacroCycle(IRing ring, IChemObjectSet rs) { if (ring.Atoms.Count < 8) return false; @@ -1817,14 +1812,14 @@ private void LayoutAcyclicParts() } Debug.WriteLine("---end of longest unplaced chain---"); #endif + if (longestUnplacedChain.Atoms.Count > 1) { if (placedAtoms.Atoms.Count > 1) { Debug.WriteLine("More than one atoms placed already"); Debug.WriteLine("trying to place neighbors of atom " + (molecule.Atoms.IndexOf(atom) + 1)); - atomPlacer.DistributePartners(atom, placedAtoms, GeometryUtil.Get2DCenter(placedAtoms), - unplacedAtoms, BondLength); + atomPlacer.DistributePartners(atom, placedAtoms, GeometryUtil.Get2DCenter(placedAtoms), unplacedAtoms, BondLength); direction = longestUnplacedChain.Atoms[1].Point2D.Value; startVector = atom.Point2D.Value; direction -= startVector; @@ -1834,8 +1829,7 @@ private void LayoutAcyclicParts() { Debug.WriteLine("Less than or equal one atoms placed already"); Debug.WriteLine("Trying to get next bond vector."); - direction = atomPlacer.GetNextBondVector(atom, placedAtoms.Atoms[0], - GeometryUtil.Get2DCenter(molecule), true); + direction = atomPlacer.GetNextBondVector(atom, placedAtoms.Atoms[0], GeometryUtil.Get2DCenter(molecule), true); } @@ -1874,32 +1868,32 @@ private void LayoutCyclicParts() ResetUnplacedRings(); IAtomContainer placedAtoms = AtomPlacer.GetPlacedAtoms(molecule); Debug.WriteLine("Finding attachment bond to already placed part..."); - IBond nextRingAttachmentBond = GetNextBondWithUnplacedRingAtom(); + var nextRingAttachmentBond = GetNextBondWithUnplacedRingAtom(); if (nextRingAttachmentBond != null) { Debug.WriteLine("...bond found."); // Get the chain and the ring atom that are connected to where we // are coming from. Both are connected by nextRingAttachmentBond. - IAtom ringAttachmentAtom = GetRingAtom(nextRingAttachmentBond); - IAtom chainAttachmentAtom = GetOtherBondAtom(ringAttachmentAtom, nextRingAttachmentBond); + var ringAttachmentAtom = GetRingAtom(nextRingAttachmentBond); + var chainAttachmentAtom = GetOtherBondAtom(ringAttachmentAtom, nextRingAttachmentBond); // Get ring system which ringAttachmentAtom is part of - IRingSet nextRingSystem = GetRingSystemOfAtom(ringSystems, ringAttachmentAtom); + var nextRingSystem = GetRingSystemOfAtom(ringSystems, ringAttachmentAtom); // Get all rings of nextRingSytem as one IAtomContainer - IAtomContainer ringSystem = RingSetManipulator.GetAllInOneContainer(nextRingSystem); + var ringSystem = RingSetManipulator.GetAllInOneContainer(nextRingSystem); // Save coordinates of ringAttachmentAtom and chainAttachmentAtom - Vector2 oldRingAttachmentAtomPoint = ringAttachmentAtom.Point2D.Value; - Vector2 oldChainAttachmentAtomPoint = chainAttachmentAtom.Point2D.Value; + var oldRingAttachmentAtomPoint = ringAttachmentAtom.Point2D.Value; + var oldChainAttachmentAtomPoint = chainAttachmentAtom.Point2D.Value; // Do the layout of the next ring system LayoutRingSet(firstBondVector, nextRingSystem); // Place all the substituents of next ring system AtomPlacer.MarkNotPlaced(placedAtoms); - IAtomContainer placedRingSubstituents = ringPlacer.PlaceRingSubstituents(nextRingSystem, BondLength); + var placedRingSubstituents = ringPlacer.PlaceRingSubstituents(nextRingSystem, BondLength); ringSystem.Add(placedRingSubstituents); AtomPlacer.MarkPlaced(placedAtoms); @@ -1907,27 +1901,27 @@ private void LayoutCyclicParts() Debug.WriteLine("Computing translation/rotation of new ringset to fit old attachment bond orientation..."); // old placed ring atom coordinate - Vector2 oldPoint2 = oldRingAttachmentAtomPoint; + var oldPoint2 = oldRingAttachmentAtomPoint; // old placed substituent atom coordinate - Vector2 oldPoint1 = oldChainAttachmentAtomPoint; + var oldPoint1 = oldChainAttachmentAtomPoint; // new placed ring atom coordinate - Vector2 newPoint2 = ringAttachmentAtom.Point2D.Value; + var newPoint2 = ringAttachmentAtom.Point2D.Value; // new placed substituent atom coordinate - Vector2 newPoint1 = chainAttachmentAtom.Point2D.Value; + var newPoint1 = chainAttachmentAtom.Point2D.Value; - Debug.WriteLine("oldPoint1: " + oldPoint1); - Debug.WriteLine("oldPoint2: " + oldPoint2); - Debug.WriteLine("newPoint1: " + newPoint1); - Debug.WriteLine("newPoint2: " + newPoint2); + Debug.WriteLine($"oldPoint1: {oldPoint1}"); + Debug.WriteLine($"oldPoint2: {oldPoint2}"); + Debug.WriteLine($"newPoint1: {newPoint1}"); + Debug.WriteLine($"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; + var oldAngle = GeometryUtil.GetAngle(oldPoint2.X - oldPoint1.X, oldPoint2.Y - oldPoint1.Y); + var newAngle = GeometryUtil.GetAngle(newPoint2.X - newPoint1.X, newPoint2.Y - newPoint1.Y); + var angleDiff = oldAngle - newAngle; Debug.WriteLine("oldAngle: " + oldAngle + ", newAngle: " + newAngle + "; diff = " + angleDiff); - Vector2 translationVector = oldPoint1; + var translationVector = oldPoint1; translationVector -= newPoint1; // Move to fit old attachment bond orientation @@ -1945,10 +1939,10 @@ private void LayoutCyclicParts() // partially laid out ring system if (ringSystems != null) { - foreach (IRingSet ringset in ringSystems) + foreach (var ringset in ringSystems) { - foreach (IAtomContainer ring in ringset) - ringPlacer.CompletePartiallyPlacedRing(ringset, (IRing)ring, BondLength); + foreach (var ring in ringset) + ringPlacer.CompletePartiallyPlacedRing(ringset, ring, BondLength); if (AllPlaced(ringset)) ringPlacer.PlaceRingSubstituents(ringset, BondLength); } @@ -1965,7 +1959,7 @@ private void LayoutCyclicParts() /// an AtomContainer with all unplaced atoms connected to a given atom private IAtomContainer GetUnplacedAtoms(IAtom atom) { - IAtomContainer unplacedAtoms = atom.Builder.NewAtomContainer(); + var unplacedAtoms = atom.Builder.NewAtomContainer(); var bonds = molecule.GetConnectedBonds(atom); IAtom connectedAtom; foreach (var bond in bonds) @@ -1986,7 +1980,7 @@ private IAtomContainer GetUnplacedAtoms(IAtom atom) /// an AtomContainer with all placed atoms connected to a given atom private IAtomContainer GetPlacedAtoms(IAtom atom) { - IAtomContainer placedAtoms = atom.Builder.NewAtomContainer(); + var placedAtoms = atom.Builder.NewAtomContainer(); var bonds = molecule.GetConnectedBonds(atom); IAtom connectedAtom; foreach (var bond in bonds) @@ -2027,10 +2021,10 @@ private IAtom GetNextAtomWithAliphaticUnplacedNeigbors() /// the next bond with an unplaced ring atom private IBond GetNextBondWithUnplacedRingAtom() { - foreach (IBond bond in molecule.Bonds) + foreach (var bond in molecule.Bonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; if (beg.Point2D != null && end.Point2D != null) { if (end.IsPlaced && !beg.IsPlaced && beg.IsInRing) @@ -2057,31 +2051,31 @@ private IAtomContainer PlaceFirstBond(IBond bond, Vector2 bondVector) { IAtomContainer sharedAtoms = null; - bondVector = Vector2.Normalize(bondVector); - Debug.WriteLine($"placeFirstBondOfFirstRing->bondVector.Length: {bondVector.Length()}"); - bondVector *= BondLength; - Debug.WriteLine($"placeFirstBondOfFirstRing->bondVector.Length after scaling:{bondVector.Length()}"); - IAtom atom; - Vector2 point = Vector2.Zero; - atom = bond.Begin; - Debug.WriteLine("Atom 1 of first Bond: " + (molecule.Atoms.IndexOf(atom) + 1)); - atom.Point2D = point; - atom.IsPlaced = true; - point = Vector2.Zero; - atom = bond.End; - Debug.WriteLine("Atom 2 of first Bond: " + (molecule.Atoms.IndexOf(atom) + 1)); - point += bondVector; - atom.Point2D = point; - atom.IsPlaced = true; - - // The new ring is laid out relative to some shared atoms that have - // already been placed. Usually this is another ring, that has - // already been draw and to which the new ring is somehow connected, - // or some other system of atoms in an aliphatic chain. In this - // case, it's the first bond that we layout by hand. - sharedAtoms = atom.Builder.NewAtomContainer(); - sharedAtoms.Atoms.Add(bond.Begin); - sharedAtoms.Atoms.Add(bond.End); + bondVector = Vector2.Normalize(bondVector); + Debug.WriteLine($"placeFirstBondOfFirstRing->bondVector.Length: {bondVector.Length()}"); + bondVector *= BondLength; + Debug.WriteLine($"placeFirstBondOfFirstRing->bondVector.Length after scaling:{bondVector.Length()}"); + IAtom atom; + var point = Vector2.Zero; + atom = bond.Begin; + Debug.WriteLine("Atom 1 of first Bond: " + (molecule.Atoms.IndexOf(atom) + 1)); + atom.Point2D = point; + atom.IsPlaced = true; + point = Vector2.Zero; + atom = bond.End; + Debug.WriteLine("Atom 2 of first Bond: " + (molecule.Atoms.IndexOf(atom) + 1)); + point += bondVector; + atom.Point2D = point; + atom.IsPlaced = true; + + // The new ring is laid out relative to some shared atoms that have + // already been placed. Usually this is another ring, that has + // already been draw and to which the new ring is somehow connected, + // or some other system of atoms in an aliphatic chain. In this + // case, it's the first bond that we layout by hand. + sharedAtoms = atom.Builder.NewAtomContainer(); + sharedAtoms.Atoms.Add(bond.Begin); + sharedAtoms.Atoms.Add(bond.End); sharedAtoms.Bonds.Add(bond); return sharedAtoms; } @@ -2091,11 +2085,11 @@ private IAtomContainer PlaceFirstBond(IBond bond, Vector2 bondVector) /// /// The Vector to be checked /// true if all rings are placed, false otherwise - private bool AllPlaced(IRingSet rings) + private static bool AllPlaced(IRingSet rings) { for (int f = 0; f < rings.Count; f++) { - if (!((IRing)rings[f]).IsPlaced) + if (!(rings[f]).IsPlaced) { Debug.WriteLine("allPlaced->Ring " + f + " not placed"); return false; @@ -2109,7 +2103,7 @@ private bool AllPlaced(IRingSet rings) /// /// the bond to be search for the unplaced ring atom /// the unplaced ring atom in this bond - private IAtom GetRingAtom(IBond bond) + private static IAtom GetRingAtom(IBond bond) { if (bond.Begin.IsInRing && !bond.Begin.IsPlaced) { @@ -2128,12 +2122,12 @@ private IAtom GetRingAtom(IBond bond) /// a List of ring systems to be searched /// the ring atom to be search in the ring system. /// the ring system the given atom is part of - private IRingSet GetRingSystemOfAtom(IList ringSystems, IAtom ringAtom) + private static IRingSet GetRingSystemOfAtom(IList ringSystems, IAtom ringAtom) { IRingSet ringSet = null; for (int f = 0; f < ringSystems.Count; f++) { - ringSet = (IRingSet)ringSystems[f]; + ringSet = ringSystems[f]; if (ringSet.Contains(ringAtom)) { return ringSet; @@ -2155,7 +2149,7 @@ private void ResetUnplacedRings() int unplacedCounter = 0; for (int f = 0; f < sssr.Count; f++) { - ring = (IRing)sssr[f]; + ring = sssr[f]; if (!ring.IsPlaced) { Debug.WriteLine("Ring with " + ring.Atoms.Count + " atoms is not placed."); @@ -2177,9 +2171,10 @@ private void ResetUnplacedRings() /// the atom we already have /// the bond /// the other atom of the bond - public IAtom GetOtherBondAtom(IAtom atom, IBond bond) + private static IAtom GetOtherBondAtom(IAtom atom, IBond bond) { - if (!bond.Contains(atom)) return null; + if (!bond.Contains(atom)) + return null; if (bond.Begin.Equals(atom)) return bond.End; else @@ -2191,9 +2186,9 @@ public IAtom GetOtherBondAtom(IAtom atom, IBond bond) /// /// coordinates on each other. /// molecule to place the multiple groups of - private void PlaceMultipleGroups(IAtomContainer mol) + private static void PlaceMultipleGroups(IAtomContainer mol) { - var sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); if (sgroups == null) return; var multipleGroups = new List(); @@ -2205,7 +2200,7 @@ private void PlaceMultipleGroups(IAtomContainer mol) if (multipleGroups.Count == 0) return; - int[][] adjlist = GraphUtil.ToAdjList(mol); + var adjlist = GraphUtil.ToAdjList(mol); var idxs = new Dictionary(); foreach (var atom in mol.Atoms) idxs[atom] = idxs.Count; @@ -2217,7 +2212,7 @@ private void PlaceMultipleGroups(IAtomContainer mol) continue; // extract substructure - IAtomContainer substructure = mol.Builder.NewAtomContainer(); + var substructure = mol.Builder.NewAtomContainer(); var visit = new HashSet(); var patoms = (ICollection)sgroup.GetValue(SgroupKey.CtabParentAtomList); if (patoms == null) @@ -2229,8 +2224,8 @@ private void PlaceMultipleGroups(IAtomContainer mol) } foreach (var bond in mol.Bonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; if (visit.Contains(beg) && visit.Contains(end)) substructure.Bonds.Add(bond); } @@ -2241,20 +2236,20 @@ private void PlaceMultipleGroups(IAtomContainer mol) foreach (var atom in sgroup.Atoms) visit.Add(atom); - Pattern ptrn = VentoFoggia.FindSubstructure(substructure, new AtomicNumberAtomMatcher(visit), BondMatcher.CreateOrderMatcher()); + var ptrn = VentoFoggia.FindSubstructure(substructure, new AtomicNumberAtomMatcher(visit), BondMatcher.CreateOrderMatcher()); var sgroupAtoms = sgroup.Atoms; // when there are crossing bonds, things are more tricky as // we need to translate connected parts - List> outgoing = new List>(); - List> xBondVec = new List>(); + var outgoing = new List>(); + var xBondVec = new List>(); if (numCrossing == 2) { foreach (var bond in mol.Bonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; if (patoms.Contains(beg) == patoms.Contains(end)) continue; if (patoms.Contains(beg)) @@ -2274,8 +2269,8 @@ private void PlaceMultipleGroups(IAtomContainer mol) } foreach (var bond in sgroup.Bonds) { - IAtom beg = bond.Begin; - IAtom end = bond.End; + var beg = bond.Begin; + var end = bond.End; if (sgroupAtoms.Contains(beg)) { xBondVec.Add(new KeyValuePair(bond, @@ -2313,17 +2308,18 @@ private void PlaceMultipleGroups(IAtomContainer mol) Trace.Assert(xBondVec.Count == outgoing.Count); foreach (var e in xBondVec) { - IBond bond = e.Key; + var bond = e.Key; // can't fix move ring bonds if (bond.IsInRing) continue; - IAtom beg = sgroupAtoms.Contains(bond.Begin) ? bond.Begin : bond.End; + var beg = sgroupAtoms.Contains(bond.Begin) ? bond.Begin : bond.End; KeyValuePair? best = null; foreach (var candidate in outgoing) { - if (best == null || Vector2.Distance(candidate.Key, beg.Point2D.Value) < Vector2.Distance(best.Value.Key, beg.Point2D.Value)) + if (best == null + || Vector2.Distance(candidate.Key, beg.Point2D.Value) < Vector2.Distance(best.Value.Key, beg.Point2D.Value)) best = candidate; } outgoing.Remove(best.Value); @@ -2336,20 +2332,20 @@ private void PlaceMultipleGroups(IAtomContainer mol) }; Visit(iVisit, adjlist, idxs[bond.GetOther(beg)]); iVisit.Remove(idxs[beg]); - IAtomContainer frag = mol.Builder.NewAtomContainer(); + var frag = mol.Builder.NewAtomContainer(); foreach (var idx in iVisit) frag.Atoms.Add(mol.Atoms[idx]); - Vector2 orgVec = e.Value; - Vector2 newVec = best.Value.Value; + var orgVec = e.Value; + var newVec = best.Value.Value; - Vector2 endP = bond.GetOther(beg).Point2D.Value; - Vector2 newEndP = beg.Point2D.Value; + var endP = bond.GetOther(beg).Point2D.Value; + var newEndP = beg.Point2D.Value; newEndP += newVec; // need perpendicular dot product to get signed angle - double pDot = orgVec.X * newVec.Y - orgVec.Y * newVec.X; - double theta = Math.Atan2(pDot, Vector2.Dot(newVec, orgVec)); + var pDot = orgVec.X * newVec.Y - orgVec.Y * newVec.X; + var theta = Math.Atan2(pDot, Vector2.Dot(newVec, orgVec)); // position GeometryUtil.Translate2D(frag, newEndP.X - endP.X, newEndP.Y - endP.Y); @@ -2371,41 +2367,41 @@ public override bool Matches(IAtom a, IAtom b) { if (!visit.Contains(b)) return false; - int aElem = NullAsZero(a.AtomicNumber); - int bElem = NullAsZero(b.AtomicNumber); + var aElem = a.AtomicNumber ?? 0; + var bElem = b.AtomicNumber ?? 0; if (aElem != bElem) return false; - int aChg = NullAsZero(a.FormalCharge); - int bChg = NullAsZero(b.FormalCharge); + var aChg = a.FormalCharge ?? 0; + var bChg = b.FormalCharge ?? 0; if (aChg != bChg) return false; - int aMass = NullAsZero(a.MassNumber); - int bMass = NullAsZero(b.MassNumber); + var aMass = a.MassNumber ?? 0; + var bMass = b.MassNumber ?? 0; if (aMass != bMass) return false; - int aHcnt = NullAsZero(a.ImplicitHydrogenCount); - int bHcnt = NullAsZero(b.ImplicitHydrogenCount); + var aHcnt = a.ImplicitHydrogenCount ?? 0; + var bHcnt = b.ImplicitHydrogenCount ?? 0; if (aHcnt != bHcnt) return false; return true; } } - private int GetPositionalRingBondPref(IBond bond, IAtomContainer mol) + private static int GetPositionalRingBondPref(IBond bond, IAtomContainer mol) { - int begRingBonds = NumRingBonds(mol, bond.Begin); - int endRingBonds = NumRingBonds(mol, bond.End); + var begRingBonds = NumRingBonds(mol, bond.Begin); + var endRingBonds = NumRingBonds(mol, bond.End); if (begRingBonds == 2 && endRingBonds == 2) return 0; - if ((begRingBonds > 2 && endRingBonds == 2) || - (begRingBonds == 2 && endRingBonds > 2)) + if ((begRingBonds > 2 && endRingBonds == 2) + || (begRingBonds == 2 && endRingBonds > 2)) return 1; return 2; } private void PlacePositionalVariation(IAtomContainer mol) { - var sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); if (sgroups == null) return; @@ -2415,8 +2411,8 @@ private void PlacePositionalVariation(IAtomContainer mol) return; // helps with traversal - GraphUtil.EdgeToBondMap bondMap = GraphUtil.EdgeToBondMap.WithSpaceFor(mol); - int[][] adjlist = GraphUtil.ToAdjList(mol, bondMap); + var bondMap = EdgeToBondMap.WithSpaceFor(mol); + var adjlist = GraphUtil.ToAdjList(mol, bondMap); var idxs = new Dictionary(); foreach (var atom in mol.Atoms) idxs[atom] = idxs.Count; @@ -2425,14 +2421,14 @@ private void PlacePositionalVariation(IAtomContainer mol) { var bonds = new List(); - IAtomContainer shared = mol.Builder.NewAtomContainer(); + var shared = mol.Builder.NewAtomContainer(); foreach (var atom in e.Key) shared.Atoms.Add(atom); - Vector2 center = GeometryUtil.Get2DCenter(shared); + var center = GeometryUtil.Get2DCenter(shared); foreach (var bond in mol.Bonds) { - if (e.Key.Contains(bond.Begin) && + if (e.Key.Contains(bond.Begin) && e.Key.Contains(bond.End)) { bonds.Add(bond); @@ -2440,19 +2436,19 @@ private void PlacePositionalVariation(IAtomContainer mol) } bonds.Sort((a, b) => + { + var atype = GetPositionalRingBondPref(a, mol); + var btype = GetPositionalRingBondPref(b, mol); + if (atype != btype) + return atype.CompareTo(btype); + var aord = a.Order.Numeric(); + var bord = b.Order.Numeric(); + if (aord > 0 && bord > 0) { - int atype = GetPositionalRingBondPref(a, mol); - int btype = GetPositionalRingBondPref(b, mol); - if (atype != btype) - return atype.CompareTo(btype); - int aord = a.Order.Numeric(); - int bord = b.Order.Numeric(); - if (aord > 0 && bord > 0) - { - return aord.CompareTo(bord); - } - return 0; - }); + return aord.CompareTo(bord); + } + return 0; + }); if (bonds.Count >= e.Value.Count) { @@ -2461,20 +2457,20 @@ private void PlacePositionalVariation(IAtomContainer mol) while (begIter.MoveNext() && bndIter.MoveNext()) { - IBond bond = bndIter.Current; - IAtom atom = begIter.Current; + var bond = bndIter.Current; + var atom = begIter.Current; - Vector2 newBegP = bond.Begin.Point2D.Value; - Vector2 newEndP = bond.End.Point2D.Value; + var newBegP = bond.Begin.Point2D.Value; + var newEndP = bond.End.Point2D.Value; - Vector2 bndVec = new Vector2(newEndP.X - newBegP.X, newEndP.Y - newBegP.Y); - Vector2 bndXVec = new Vector2(-bndVec.Y, bndVec.X); + var bndVec = new Vector2(newEndP.X - newBegP.X, newEndP.Y - newBegP.Y); + var bndXVec = new Vector2(-bndVec.Y, bndVec.X); // ensure vector is pointing out of rings - Vector2 centerVec = new Vector2(center.X - ((newBegP.X+ newEndP.X) / 2), - center.Y - ((newBegP.Y + newEndP.Y) / 2)); + var centerVec = new Vector2(center.X - ((newBegP.X + newEndP.X) / 2), + center.Y - ((newBegP.Y + newEndP.Y) / 2)); - double dot = Vector2.Dot(bndXVec, centerVec); + var dot = Vector2.Dot(bndXVec, centerVec); if (Math.Abs(dot) < 0.01) { // close to zero... grab adjacent bonds and use those as @@ -2488,7 +2484,7 @@ private void PlacePositionalVariation(IAtomContainer mol) adj.Remove(bond.End); var newCenter = GeometryUtil.Get2DCenter(adj); centerVec = new Vector2(newCenter.X - ((newBegP.X + newEndP.X) / 2), - newCenter.Y - ((newBegP.Y + newEndP.Y) / 2)); + newCenter.Y - ((newBegP.Y + newEndP.Y) / 2)); if (Vector2.Dot(bndXVec, centerVec) > 0.01) bndXVec = Vector2.Negate(bndXVec); } @@ -2502,7 +2498,7 @@ private void PlacePositionalVariation(IAtomContainer mol) bndVec *= 0.5 * BondLength; // crossing point - double bndStep = (BondLength) / 5; + var bndStep = (BondLength) / 5; newBegP += bndVec; bndXVec = Vector2.Normalize(bndXVec); @@ -2513,7 +2509,7 @@ private void PlacePositionalVariation(IAtomContainer mol) bndXVec *= 4 * bndStep; newEndP += bndXVec; - int atomIdx = idxs[atom]; + var atomIdx = idxs[atom]; if (adjlist[atomIdx].Length != 1) continue; @@ -2522,20 +2518,20 @@ private void PlacePositionalVariation(IAtomContainer mol) Visit(visited, adjlist, atomIdx); // gather up other position group - HashSet newvisit = new HashSet(); + var newvisit = new HashSet(); do { newvisit.Clear(); foreach (var idx in visited) { - IAtom visitedAtom = mol.Atoms[idx]; + var visitedAtom = mol.Atoms[idx]; if (e.Key.Contains(visitedAtom) || e.Value.Contains(visitedAtom)) continue; foreach (var e2 in mapping.Entries) { if (e2.Key.Contains(visitedAtom)) { - int other = idxs[e2.Value]; + var other = idxs[e2.Value]; if (!visited.Contains(other) && newvisit.Add(other)) { Visit(newvisit, adjlist, other); @@ -2543,7 +2539,7 @@ private void PlacePositionalVariation(IAtomContainer mol) } else if (e2.Value == visitedAtom) { - int other = idxs[e2.Key.First()]; + var other = idxs[e2.Key.First()]; if (!visited.Contains(other) && newvisit.Add(other)) { Visit(newvisit, adjlist, other); @@ -2555,20 +2551,20 @@ private void PlacePositionalVariation(IAtomContainer mol) visited.Add(visit); } while (newvisit.Any()); - IAtomContainer frag = mol.Builder.NewAtomContainer(); + var frag = mol.Builder.NewAtomContainer(); foreach (var visit in visited) frag.Atoms.Add(mol.Atoms[visit]); - IBond attachBond = bondMap[atomIdx, adjlist[atomIdx][0]]; - Vector2 begP = atom.Point2D.Value; - Vector2 endP = attachBond.GetOther(atom).Point2D.Value; + var attachBond = bondMap[atomIdx, adjlist[atomIdx][0]]; + var begP = atom.Point2D.Value; + var endP = attachBond.GetOther(atom).Point2D.Value; - Vector2 orgVec = new Vector2(endP.X - begP.X, endP.Y - begP.Y); - Vector2 newVec = new Vector2(newEndP.X - newBegP.X, newEndP.Y - newBegP.Y); + var orgVec = new Vector2(endP.X - begP.X, endP.Y - begP.Y); + var newVec = new Vector2(newEndP.X - newBegP.X, newEndP.Y - newBegP.Y); // need perpendicular dot product to get signed angle - double pDot = orgVec.X * newVec.Y - orgVec.Y * newVec.X; - double theta = Math.Atan2(pDot, Vector2.Dot(newVec, orgVec)); + var pDot = orgVec.X * newVec.Y - orgVec.Y * newVec.X; + var theta = Math.Atan2(pDot, Vector2.Dot(newVec, orgVec)); // position GeometryUtil.Translate2D(frag, newBegP.X - begP.X, newBegP.Y - begP.Y); @@ -2596,7 +2592,7 @@ private static void Visit(HashSet visited, int[][] g, int v) } } - private static IMultiDictionary, IAtom> AggregateMulticenterSgroups(IList sgroups) + private static IMultiDictionary, IAtom> AggregateMulticenterSgroups(ICollection sgroups) { var mapping = new MultiDictionary, IAtom>(); foreach (var sgroup in sgroups) @@ -2610,7 +2606,7 @@ private static IMultiDictionary, IAtom> AggregateMulticenterSgroups( var bonds = sgroup.Bonds; if (bonds.Count != 1) continue; - IBond bond = bonds.First(); + var bond = bonds.First(); foreach (var atom in sgroup.Atoms) { @@ -2645,8 +2641,9 @@ private static int NumRingBonds(IAtomContainer mol, IAtom atom) /// molecule private void PlaceSgroupBrackets(IAtomContainer mol) { - IList sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); - if (sgroups == null) return; + var sgroups = mol.GetCtabSgroups(); + if (sgroups == null) + return; // index all crossing bonds var bondMap = new MultiDictionary(); @@ -2701,19 +2698,16 @@ private void PlaceSgroupBrackets(IAtomContainer mol) } foreach (var bond in xbonds) - sgroup.AddBracket(NewCrossingBracket(bond, - bondMap, - counter, - vert)); + sgroup.AddBracket(NewCrossingBracket(bond, bondMap, counter, vert)); } // <= 1 crossing bonds so simply wrap the entire fragment else { - IAtomContainer tmp = mol.Builder.NewAtomContainer(); + var tmp = mol.Builder.NewAtomContainer(); foreach (var atom in atoms) tmp.Atoms.Add(atom); - double[] minmax = GeometryUtil.GetMinMax(tmp); - double padding = 0.7 * BondLength; + var minmax = GeometryUtil.GetMinMax(tmp); + var 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, @@ -2724,8 +2718,8 @@ private void PlaceSgroupBrackets(IAtomContainer mol) private static double Angle(IBond bond) { - Vector2 end = bond.Begin.Point2D.Value; - Vector2 beg = bond.End.Point2D.Value; + var end = bond.Begin.Point2D.Value; + var beg = bond.End.Point2D.Value; return Math.Atan2(end.Y - beg.Y, end.X - beg.X); } @@ -2739,12 +2733,12 @@ private static double Angle(IBond bond) /// the new bracket private SgroupBracket NewCrossingBracket(IBond bond, IMultiDictionary bonds, IDictionary counter, bool vert) { - IAtom beg = bond.Begin; - IAtom end = bond.End; - Vector2 begXy = beg.Point2D.Value; - Vector2 endXy = end.Point2D.Value; - Vector2 lenOffset = new Vector2(endXy.X - begXy.X, endXy.Y - begXy.Y); - Vector2 bndCrossVec = new Vector2(-lenOffset.Y, lenOffset.X); + var beg = bond.Begin; + var end = bond.End; + var begXy = beg.Point2D.Value; + var endXy = end.Point2D.Value; + var lenOffset = new Vector2(endXy.X - begXy.X, endXy.Y - begXy.Y); + var bndCrossVec = new Vector2(-lenOffset.Y, lenOffset.X); lenOffset = Vector2.Normalize(lenOffset); bndCrossVec = Vector2.Normalize(bndCrossVec); bndCrossVec *= (0.9 * BondLength) / 2; @@ -2772,8 +2766,8 @@ private SgroupBracket NewCrossingBracket(IBond bond, IMultiDictionary ElementType { get { var v = Attribute(Attribute_elementType)?.Value; - if (v == null) return Array.Empty(); + if (v == null) + return Array.Empty(); return Strings.Tokenize(v, ' ').ToArray(); } + set { - SetAttributeValue(Attribute_elementType, value?.Length == 0 ? null : Concat(value)); + SetAttributeValue(Attribute_elementType, value?.Count == 0 ? null : Concat(value)); } } - public double[] Count + public IReadOnlyList Count { get { var v = Attribute(Attribute_count)?.Value; if (v == null) return Array.Empty(); - return Strings.Tokenize(v, ' ').Select(n => double.Parse(n)).ToArray(); + return Strings.Tokenize(v, ' ').Select(n => double.Parse(n, NumberFormatInfo.InvariantInfo)).ToArray(); } set { - SetAttributeValue(Attribute_count, value?.Length == 0 ? null : Concat(value)); + SetAttributeValue(Attribute_count, value?.Count == 0 ? null : Concat(value)); } } @@ -52,15 +55,15 @@ public void Sort(CMLFormula.SortType sort) var counts = Count; var sortS = new List(); { - for (var i = 0; i < elems.Length; i++) - sortS.Add(elems[i] + " " + counts[i]); + for (var i = 0; i < elems.Count; i++) + sortS.Add($"{elems[i]} {counts[i]}"); } sortS.Sort(); - if (sort == CMLFormula.SortType.ALPHABETIC_ELEMENTS) + if (sort == CMLFormula.SortType.AlphabeticElements) { ; // already done } - else if (sort == CMLFormula.SortType.CHFIRST) + else if (sort == CMLFormula.SortType.CHFirst) { var temp = new List(); foreach (var s in sortS) @@ -81,7 +84,7 @@ public void Sort(CMLFormula.SortType sort) { var ss = sortS[i].Split(' '); el[i] = ss[0]; - cl[i] = double.Parse(ss[1]); + cl[i] = double.Parse(ss[1], NumberFormatInfo.InvariantInfo); } } this.ElementType = el; @@ -99,12 +102,12 @@ public string GenerateConcise(int formalCharge) { var elems = ElementType ?? Array.Empty(); var counts = Count ?? Array.Empty(); - if (counts.Length != elems.Length) + if (counts.Count != elems.Count) { - throw new ApplicationException($"atomArray has inconsistent counts/elems {counts.Length} {elems.Length}"); + throw new ApplicationException($"atomArray has inconsistent counts/elems {counts.Count} {elems.Count}"); } var sb = new StringBuilder(); - for (int i = 0; i < elems.Length; i++) + for (int i = 0; i < elems.Count; i++) { sb.Append(' ').Append(elems[i]).Append(' '); sb.Append(Strings.JavaFormat(counts[i], 4, true)); diff --git a/NCDK/LibIO/CML/CMLElement.cs b/NCDK/LibIO/CML/CMLElement.cs index ed1e3032..425c9dce 100644 --- a/NCDK/LibIO/CML/CMLElement.cs +++ b/NCDK/LibIO/CML/CMLElement.cs @@ -1,6 +1,7 @@ using NCDK.Common.Primitives; using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; using System.Xml.Linq; @@ -90,7 +91,7 @@ public partial class CMLElement : XElement internal const string Attribute_errorValue = "errorValue"; internal const string Attribute_value = "value"; - protected static string Concat(T[] values) + protected static string Concat(IEnumerable values) { var sb = new StringBuilder(); bool isFirst = true; @@ -121,7 +122,7 @@ protected static int[] ToIntArray(string s) var ret = new int[ss.Length]; for (int i = 0; i < ss.Length; i++) { - ret[i] = int.Parse(ss[i]); + ret[i] = int.Parse(ss[i], NumberFormatInfo.InvariantInfo); } return ret; } @@ -165,19 +166,19 @@ protected int GetAttributeValueAsInt(string name, int defaultValue) var vs = GetAttributeValue(name, null); if (vs == null) return defaultValue; - return int.Parse(vs); + return int.Parse(vs, NumberFormatInfo.InvariantInfo); } protected int GetAttributeValueAsInt(string name) { var vs = GetAttributeValue(name); - return int.Parse(vs); + return int.Parse(vs, NumberFormatInfo.InvariantInfo); } protected double GetAttributeValueAsDouble(string name) { var vs = GetAttributeValue(name); - return double.Parse(vs); + return double.Parse(vs, NumberFormatInfo.InvariantInfo); } protected int[] GetAttributeValueAsInts(string name) diff --git a/NCDK/LibIO/CML/CMLElementBodies.tt.cs b/NCDK/LibIO/CML/CMLElementBodies.tt.cs index edc58b3a..3482c4d0 100644 --- a/NCDK/LibIO/CML/CMLElementBodies.tt.cs +++ b/NCDK/LibIO/CML/CMLElementBodies.tt.cs @@ -60,7 +60,7 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } @@ -72,29 +72,29 @@ public string ElementType public int FormalCharge { get { return GetAttributeValueAsInt(Attribute_formalCharge, 0); } - set { SetAttributeValue(Attribute_formalCharge, value.ToString()); } + set { SetAttributeValue(Attribute_formalCharge, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } public int HydrogenCount { get { return GetAttributeValueAsInt(Attribute_hydrogenCount, 0); } - set { SetAttributeValue(Attribute_hydrogenCount, value.ToString()); } + set { SetAttributeValue(Attribute_hydrogenCount, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } public int IsotopeNumber { get { return GetAttributeValueAsInt(Attribute_isotopeNumber, 0); } - set { SetAttributeValue(Attribute_isotopeNumber, value.ToString()); } + set { SetAttributeValue(Attribute_isotopeNumber, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } public int SpinMultiplicity { get { return GetAttributeValueAsInt(Attribute_spinMultiplicity, 0); } - set { SetAttributeValue(Attribute_spinMultiplicity, value.ToString()); } + set { SetAttributeValue(Attribute_spinMultiplicity, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } public double X2 { get { var v = Attribute(Attribute_x2).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_x2, value); } } @@ -103,7 +103,7 @@ public double Y2 get { var v = Attribute(Attribute_y2).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_y2, value); } } @@ -112,7 +112,7 @@ public double X3 get { var v = Attribute(Attribute_x3).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_x3, value); } } @@ -121,7 +121,7 @@ public double Y3 get { var v = Attribute(Attribute_y3).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_y3, value); } } @@ -130,7 +130,7 @@ public double Z3 get { var v = Attribute(Attribute_z3).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_z3, value); } } @@ -139,7 +139,7 @@ public double XFract get { var v = Attribute(Attribute_xFract).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_xFract, value); } } @@ -148,7 +148,7 @@ public double YFract get { var v = Attribute(Attribute_yFract).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_yFract, value); } } @@ -157,7 +157,7 @@ public double ZFract get { var v = Attribute(Attribute_zFract).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_zFract, value); } } @@ -175,7 +175,7 @@ public string Order get { return Attribute(Attribute_order)?.Value; } set { SetAttributeValue(Attribute_order, value); } } - public string[] AtomRefs + public System.Collections.Generic.IReadOnlyList AtomRefs { get { @@ -184,7 +184,7 @@ public string[] AtomRefs } set { SetAttributeValue(Attribute_atomRefs, Concat(value)); } } - public string[] AtomRefs2 + public System.Collections.Generic.IReadOnlyList AtomRefs2 { get { @@ -220,14 +220,14 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } public int FormalCharge { get { return GetAttributeValueAsInt(Attribute_formalCharge, 0); } - set { SetAttributeValue(Attribute_formalCharge, value.ToString()); } + set { SetAttributeValue(Attribute_formalCharge, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } public string Inline { @@ -266,7 +266,7 @@ public double ErrorValue get { var v = Attribute(Attribute_errorValue).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_errorValue, value); } } @@ -305,7 +305,7 @@ public double ConstantToSI get { var v = Attribute(Attribute_constantToSI).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_constantToSI, value); } } @@ -314,7 +314,7 @@ public double MultiplierToSI get { var v = Attribute(Attribute_multiplierToSI).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_multiplierToSI, value); } } @@ -338,7 +338,7 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } @@ -347,7 +347,7 @@ public double State get { var v = Attribute(Attribute_state).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_state, value); } } @@ -370,7 +370,7 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } @@ -398,7 +398,7 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } @@ -407,7 +407,7 @@ public double State get { var v = Attribute(Attribute_state).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_state, value); } } @@ -430,7 +430,7 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } @@ -463,7 +463,7 @@ public double Count get { var v = Attribute(Attribute_count).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_count, value); } } @@ -472,7 +472,7 @@ public double State get { var v = Attribute(Attribute_state).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(Attribute_state, value); } } @@ -502,7 +502,7 @@ public partial class CMLCrystal public int Z { get { return GetAttributeValueAsInt(Attribute_z, 0); } - set { SetAttributeValue(Attribute_z, value.ToString()); } + set { SetAttributeValue(Attribute_z, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } } } diff --git a/NCDK/LibIO/CML/CMLFormula.cs b/NCDK/LibIO/CML/CMLFormula.cs index b5f0fc1d..f5448fd4 100644 --- a/NCDK/LibIO/CML/CMLFormula.cs +++ b/NCDK/LibIO/CML/CMLFormula.cs @@ -17,6 +17,7 @@ using NCDK.Config; using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text.RegularExpressions; @@ -48,32 +49,32 @@ public enum FormulaType /// /// the simplest representation. an input-only format. parsing is possible but fragile. The charge semantics are not defined. Not recommended for output. /// - NOPUNCTUATION, + NoPunctuation, /// /// another simple representation. an input-only format. parsing is also fragile as charge semantics are not defined. Not recommended for output. /// - ELEMENT_COUNT_WHITESPACE, + ElementCountWhitespace, /// /// Yet another simple representation. an input-only format. Element counts of 1 should always be given. Fragile as charge field is likely to be undefined. Not recommended for output. /// - ELEMENT_WHITESPACE_COUNT, + ElementWhitespaceCount, /// /// the format used in concise. recommended as the main output form. Element counts of 1 should always be given. the charge shoudl always be included. See concise.xsd and formulaType.xsd for syntax. /// - CONCISE, + Concise, /// /// multipliers for moieties. an input only format. JUMBO will try to parse this correctly but no guarantee is given. /// - MULTIPLIED_ELEMENT_COUNT_WHITESPACE, + MultipliedElementCountWhitespace, /// /// hierarchical formula. an input-only format. JUMBO will try to parse this correctly but no guarantee is given. /// - NESTEDBRACKETS, + NestedBrackets, /// /// an input only format. JUMBO will not yet parse this correctly. comments from IUCr @@ -83,22 +84,22 @@ public enum FormulaType /// /// Moiety, used by IUCr. an input-only format. moieties assumed to be comma separated then ELEMENT_COUNT_WHITESPACE, with optional brackets and post or pre-multipliers /// - MOIETY, + Moiety, /// /// Submoiety, used by IUCr. the part of a moiety within the brackets assumed to b ELEMENT_OPTIONALCOUNT followed by optional FORMULA /// - SUBMOIETY, + Submoiety, /// /// Structural, used by IUCr. not currently implemented, I think. probably the same as nested brackets /// - STRUCTURAL, + Structural, /// /// any of the above. input-only. /// - ANY, + Any, } public enum SortType @@ -106,12 +107,12 @@ public enum SortType /// /// Sort alphabetically. output only. Not sure where this is. /// - ALPHABETIC_ELEMENTS, + AlphabeticElements, /// /// C H and then alphabetically (output only). /// - CHFIRST, + CHFirst, } /// @@ -121,9 +122,9 @@ public enum SortType public enum HydrogenStrategyType { /// use hydrogen count attribute - HYDROGEN_COUNT, + HydrogenCount, /// use explicit hydrogens - EXPLICIT_HYDROGENS, + ExplicitHydrogens, } // only edit insertion module! @@ -145,7 +146,7 @@ public void Normalize() int formalCharge = 0; if (this.Attribute(Attribute_formalCharge) != null) { - formalCharge = int.Parse(this.Attribute(Attribute_formalCharge).Value); + formalCharge = int.Parse(this.Attribute(Attribute_formalCharge).Value, NumberFormatInfo.InvariantInfo); } string conciseS = conciseAtt?.Value; // convention @@ -168,18 +169,16 @@ public void Normalize() else if (atomArrays.Count == 1) { atomArray = atomArrays.First(); - atomArray.Sort(SortType.CHFIRST); + atomArray.Sort(SortType.CHFirst); atomArray2Concise = atomArray.GenerateConcise(formalCharge); } // concise from inline if (inline != null) { - if (SMILES.Equals(convention) || - SMILES1.Equals(convention)) + if (SMILES.Equals(convention, StringComparison.Ordinal) || + SMILES1.Equals(convention, StringComparison.Ordinal)) { - // throw new RuntimeException("Move to SMILESTool"); - // inline2Concise = GetConciseFromSMILES(inline); } } if (conciseS == null) @@ -197,9 +196,6 @@ public void Normalize() if (atomArray == null) { // causes problems with Jmol - // if (conciseS != null) { - // atomArray = CreateAndAddAtomArrayAndFormalChargeFromConcise(conciseS); - // } } else { @@ -207,11 +203,11 @@ public void Normalize() } if (atomArray != null) { - atomArray.Sort(SortType.CHFIRST); + atomArray.Sort(SortType.CHFirst); } // check consistency if (atomArray2Concise != null && - !atomArray2Concise.Equals(conciseS)) + !atomArray2Concise.Equals(conciseS, StringComparison.Ordinal)) { throw new ApplicationException($"concise ({conciseS}) and atomArray ({atomArray2Concise}) differ"); } @@ -248,7 +244,7 @@ CMLAtomArray CreateAndAddAtomArrayAndFormalChargeFromConcise(string concise) string countS = tokens[2 * i + 1]; try { - counts.Add(double.Parse(countS)); + counts.Add(double.Parse(countS, NumberFormatInfo.InvariantInfo)); } catch (FormatException) { @@ -260,7 +256,7 @@ CMLAtomArray CreateAndAddAtomArrayAndFormalChargeFromConcise(string concise) string chargeS = tokens[nelement * 2]; try { - int formalCharge = int.Parse(chargeS); + int formalCharge = int.Parse(chargeS, NumberFormatInfo.InvariantInfo); FormalCharge = formalCharge; } catch (FormatException) @@ -286,7 +282,7 @@ CMLAtomArray CreateAndAddAtomArrayAndFormalChargeFromConcise(string concise) /// /// to check (not modified) /// if invalid - public void CheckAtomArrayFormat(CMLAtomArray atomArray) + public static void CheckAtomArrayFormat(CMLAtomArray atomArray) { if (atomArray.HasElements) { @@ -298,14 +294,14 @@ public void CheckAtomArrayFormat(CMLAtomArray atomArray) { throw new ApplicationException("formula/atomArray must have elementType and count attributes"); } - if (elements.Length != counts.Length) + if (elements.Count != counts.Count) { throw new ApplicationException("formula/atomArray must have equal length elementType and count values"); } var elementSet = new HashSet(); - for (int i = 0; i < elements.Length; i++) + for (int i = 0; i < elements.Count; i++) { - if (elements[i] != null && !(elements[i].Equals("null"))) + if (elements[i] != null && !(elements[i].Equals("null", StringComparison.Ordinal))) { if (elementSet.Contains(elements[i])) { @@ -357,7 +353,7 @@ private string NormalizeConciseAndFormalCharge(string conciseS, int formalCharge CMLAtomArray atomArray = CreateAndAddAtomArrayAndFormalChargeFromConcise(conciseS); if (atomArray != null) { - atomArray.Sort(SortType.CHFIRST); + atomArray.Sort(SortType.CHFirst); conciseS = atomArray.GenerateConcise(formalCharge); } } @@ -393,21 +389,21 @@ public void Add(string elementType, double count) atomArray.Count = Array.Empty(); } } - string[] elements = GetElementTypes(); + var elements = GetElementTypes(); if (elements == null) { - elements = new string[0]; + elements = Array.Empty(); } - double[] counts = GetCounts(); + var counts = GetCounts()?.ToArray(); if (counts == null) { - counts = new double[0]; + counts = Array.Empty(); } - int nelem = elements.Length; + var nelem = elements.Count; bool added = false; for (int i = 0; i < nelem; i++) { - if (elements[i].Equals(elementType)) + if (elements[i].Equals(elementType, StringComparison.Ordinal)) { counts[i] += count; added = true; @@ -416,12 +412,10 @@ public void Add(string elementType, double count) } if (!added) { - string[] newElem = new string[nelem + 1]; - Array.Copy(elements, 0, newElem, 0, nelem); - newElem[nelem] = elementType; - double[] newCount = new double[nelem + 1]; - Array.Copy(counts, 0, newCount, 0, nelem); - newCount[nelem] = count; + var newElem = elements.ToList(); + newElem.Add(elementType); + var newCount = counts.ToList(); + newCount.Add(count); atomArray.ElementType = newElem; atomArray.Count = newCount; } @@ -440,7 +434,7 @@ public void Add(string elementType, double count) /// No defaults. /// /// double[] array of element counts; or null for none. - public double[] GetCounts() + public IReadOnlyList GetCounts() { CMLAtomArray atomArray = AtomArrayElements.FirstOrDefault(); return atomArray?.Count; @@ -455,7 +449,7 @@ public double GetTotalAtomCount() //nwe23 - Fixed a bug here where GetCounts() returns null // for an empty formula, resulting in this crashing rather than // returning 0 as expected for empty formula - double[] counts = GetCounts(); + var counts = GetCounts(); if (counts == null) { return 0; @@ -473,7 +467,7 @@ public double GetTotalAtomCount() /// No defaults. /// /// double[] array of element counts; or null for none. - public string[] GetElementTypes() + public IReadOnlyList GetElementTypes() { CMLAtomArray atomArray = AtomArrayElements.FirstOrDefault(); return atomArray?.ElementType; diff --git a/NCDK/LibIO/CML/CMLMolecule.cs b/NCDK/LibIO/CML/CMLMolecule.cs index daab7e5e..c17da52d 100644 --- a/NCDK/LibIO/CML/CMLMolecule.cs +++ b/NCDK/LibIO/CML/CMLMolecule.cs @@ -1,4 +1,6 @@ -namespace NCDK.LibIO.CML +using System.Globalization; + +namespace NCDK.LibIO.CML { public partial class CMLMolecule { @@ -41,7 +43,7 @@ public string Chirality public int FormalCharge { get { return GetAttributeValueAsInt(Attribute_formalCharge); } - set { SetAttributeValue(Attribute_formalCharge, value.ToString()); } + set { SetAttributeValue(Attribute_formalCharge, value.ToString(NumberFormatInfo.InvariantInfo)); } } public string SpinMultiplicity diff --git a/NCDK/LibIO/CML/CMLScalar.cs b/NCDK/LibIO/CML/CMLScalar.cs index bf686904..4a361e67 100644 --- a/NCDK/LibIO/CML/CMLScalar.cs +++ b/NCDK/LibIO/CML/CMLScalar.cs @@ -1,4 +1,6 @@ -namespace NCDK.LibIO.CML +using System.Globalization; + +namespace NCDK.LibIO.CML { public partial class CMLScalar { @@ -22,13 +24,13 @@ public CMLScalar(bool value) public void SetValue(bool scalar) { - Value = scalar.ToString().ToLowerInvariant(); + Value = scalar.ToString(NumberFormatInfo.InvariantInfo).ToLowerInvariant(); DataType = "xsd:boolean"; } public void SetValue(double scalar) { - Value = scalar.ToString(); + Value = scalar.ToString(NumberFormatInfo.InvariantInfo); DataType = "xsd:double"; } @@ -38,7 +40,7 @@ public void SetValue(double scalar) /// public void SetValue(int scalar) { - Add(scalar.ToString()); + Add(scalar.ToString(NumberFormatInfo.InvariantInfo)); DataType = "xsd:integer"; } } diff --git a/NCDK/LibIO/CML/ConfigCML.ttinclude b/NCDK/LibIO/CML/ConfigCML.ttinclude index eb2b399d..e76d76b7 100644 --- a/NCDK/LibIO/CML/ConfigCML.ttinclude +++ b/NCDK/LibIO/CML/ConfigCML.ttinclude @@ -67,7 +67,7 @@ public void MakeStrsAtt(string name) { #> - public string[] <#= ToFirstCapital(name) #> + public System.Collections.Generic.IReadOnlyList <#= ToFirstCapital(name) #> { get { @@ -89,7 +89,7 @@ get { var v = Attribute(<#= ToAttName(name) #>).Value; - return v == null ? double.NaN : double.Parse(v); + return v == null ? double.NaN : double.Parse(v, System.Globalization.NumberFormatInfo.InvariantInfo); } set { SetAttributeValue(<#= ToAttName(name) #>, value); } } @@ -105,7 +105,7 @@ public int <#= ToFirstCapital(name) #> { get { return GetAttributeValueAsInt(<#= ToAttName(name) #>, 0); } - set { SetAttributeValue(<#= ToAttName(name) #>, value.ToString()); } + set { SetAttributeValue(<#= ToAttName(name) #>, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } } <#+ } diff --git a/NCDK/LibIO/CML/Convertor.cs b/NCDK/LibIO/CML/Convertor.cs index 4a9e48e5..12cdcadf 100644 --- a/NCDK/LibIO/CML/Convertor.cs +++ b/NCDK/LibIO/CML/Convertor.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Xml.Linq; @@ -42,12 +43,12 @@ namespace NCDK.LibIO.CML // @cdk.require java1.5+ public class Convertor { - public const string NS_CML = "http://www.xml-cml.org/schema"; + public const string NamespaceCML = "http://www.xml-cml.org/schema"; private const string CUSTOMIZERS_LIST = "NCDK.libio-cml-customizers.set"; - private IDictionary customizers = null; + private Dictionary customizers = null; - private bool useCMLIDs; + private readonly bool useCMLIDs; private string prefix; /// @@ -64,7 +65,8 @@ public Convertor(bool useCMLIDs, string prefix) public void RegisterCustomizer(ICMLCustomizer customizer) { - if (customizers == null) customizers = new Dictionary(); + if (customizers == null) + customizers = new Dictionary(); if (!customizers.ContainsKey(customizer.GetType().Name)) { @@ -79,12 +81,13 @@ public void RegisterCustomizer(ICMLCustomizer customizer) private void SetupCustomizers() { - if (customizers == null) customizers = new Dictionary(); + if (customizers == null) + customizers = new Dictionary(); try { Debug.WriteLine("Starting loading Customizers..."); - TextReader reader = new StreamReader(ResourceLoader.GetAsStream(this.GetType(), CUSTOMIZERS_LIST)); + var reader = new StreamReader(ResourceLoader.GetAsStream(this.GetType(), CUSTOMIZERS_LIST)); int customizerCount = 0; string customizerName; while ((customizerName = reader.ReadLine()) != null) @@ -132,7 +135,6 @@ private void SetupCustomizers() } } - public CMLCml CDKChemFileToCMLList(IChemFile file) { return CDKChemFileToCMLList(file, true); @@ -140,10 +142,7 @@ public CMLCml CDKChemFileToCMLList(IChemFile file) private CMLCml CDKChemFileToCMLList(IChemFile file, bool setIDs) { - CMLCml cmlList = new CMLCml - { - Convention = "cdk:document" - }; + var cmlList = new CMLCml { Convention = "cdk:document" }; if (useCMLIDs && setIDs) { @@ -167,10 +166,7 @@ public CMLList CDKChemSequenceToCMLList(IChemSequence sequence) private CMLList CDKChemSequenceToCMLList(IChemSequence sequence, bool setIDs) { - CMLList cmlList = new CMLList - { - Convention = "cdk:sequence" - }; + var cmlList = new CMLList { Convention = "cdk:sequence" }; if (useCMLIDs && setIDs) { @@ -194,10 +190,7 @@ public CMLList CDKChemModelToCMLList(IChemModel model) private CMLList CDKChemModelToCMLList(IChemModel model, bool setIDs) { - CMLList cmlList = new CMLList - { - Convention = "cdk:model" - }; + var cmlList = new CMLList { Convention = "cdk:model" }; if (useCMLIDs && setIDs) { @@ -237,13 +230,14 @@ public CMLReactionScheme CDKReactionSchemeToCMLReactionScheme(IReactionScheme cd private CMLReactionScheme CDKReactionSchemeToCMLReactionScheme(IReactionScheme cdkScheme, bool setIDs) { - CMLReactionScheme reactionScheme = new CMLReactionScheme(); + var reactionScheme = new CMLReactionScheme(); if (useCMLIDs && setIDs) { IDCreator.CreateIDs(cdkScheme); } - if (cdkScheme.Id != null && !cdkScheme.Id.Equals("")) reactionScheme.Id = cdkScheme.Id; + if (!string.IsNullOrEmpty(cdkScheme.Id)) + reactionScheme.Id = cdkScheme.Id; foreach (var reaction in cdkScheme.Reactions) reactionScheme.Add(CDKReactionToCMLReaction(reaction)); @@ -261,7 +255,7 @@ public CMLReactionStep CDKReactionToCMLReactionStep(IReaction reaction) private CMLReactionStep CDKReactionToCMLReactionStep(IReaction reaction, bool setIDs) { - CMLReactionStep reactionStep = new CMLReactionStep(); + var reactionStep = new CMLReactionStep(); reactionStep.Add(CDKReactionToCMLReaction(reaction, true)); @@ -275,13 +269,14 @@ public CMLReactionList CDKReactionSetToCMLReactionList(IReactionSet reactionSet) private CMLReactionList CDKReactionSetToCMLReactionList(IReactionSet reactionSet, bool setIDs) { - CMLReactionList reactionList = new CMLReactionList(); + var reactionList = new CMLReactionList(); if (useCMLIDs && setIDs) { IDCreator.CreateIDs(reactionSet); } - if (reactionSet.Id != null && !reactionSet.Id.Equals("")) reactionList.Id = reactionSet.Id; + if (!string.IsNullOrEmpty(reactionSet.Id)) + reactionList.Id = reactionSet.Id; foreach (var reaction in reactionSet) reactionList.Add(CDKReactionToCMLReaction(reaction, false)); @@ -305,7 +300,8 @@ private CMLMoleculeList CDKAtomContainerSetToCMLList(IEnumerableChemObject mapS = pdbPolymer.GetStrandMap(); + var mapS = pdbPolymer.GetStrandMap(); foreach (var key in mapS.Keys) { - IStrand strand = mapS[key]; - List monomerNames = new List(strand.GetMonomerNames()); + var strand = mapS[key]; + var monomerNames = new List(strand.GetMonomerNames()); monomerNames.Sort(); foreach (var name in monomerNames) { @@ -443,18 +442,18 @@ public CMLMolecule CDKMonomerToCMLMolecule(IMonomer monomer) private CMLMolecule CDKMonomerToCMLMolecule(IMonomer monomer, bool setIDs) { - CMLMolecule cmlMolecule = new CMLMolecule + var cmlMolecule = new CMLMolecule { DictRef = "pdb:sequence" }; - if (monomer.MonomerName != null && !monomer.MonomerName.Equals("")) + if (!string.IsNullOrEmpty(monomer.MonomerName)) cmlMolecule.Id = monomer.MonomerName; for (int i = 0; i < monomer.Atoms.Count; i++) { - IAtom cdkAtom = monomer.Atoms[i]; - CMLAtom cmlAtom = CDKAtomToCMLAtom(monomer, cdkAtom); + var cdkAtom = monomer.Atoms[i]; + var cmlAtom = CDKAtomToCMLAtom(monomer, cdkAtom); if (monomer.GetConnectedSingleElectrons(cdkAtom).Count() > 0) { cmlAtom.SpinMultiplicity = monomer.GetConnectedSingleElectrons(cdkAtom).Count() + 1; @@ -479,7 +478,8 @@ private CMLMolecule CDKAtomContainerToCMLMolecule(IAtomContainer structure, bool } this.CheckPrefix(cmlMolecule); - if (structure.Id != null && !structure.Id.Equals("")) if (!isRef) + if (!string.IsNullOrEmpty(structure.Id)) + if (!isRef) cmlMolecule.Id = structure.Id; else cmlMolecule.Ref = structure.Id; @@ -494,7 +494,7 @@ private CMLMolecule CDKAtomContainerToCMLMolecule(IAtomContainer structure, bool { Convention = "iupac:inchi" }; - ident.SetAttributeValue(CMLElement.Attribute_value, structure.GetProperty(CDKPropertyName.InChI).ToString()); + ident.SetAttributeValue(CMLElement.Attribute_value, structure.GetProperty(CDKPropertyName.InChI)); cmlMolecule.Add(ident); } if (!isRef) @@ -518,81 +518,81 @@ private CMLMolecule CDKAtomContainerToCMLMolecule(IAtomContainer structure, bool // ok, output molecular properties, but not TITLE, INCHI, or DictRef's var props = structure.GetProperties(); - foreach (var key in props.Keys) + foreach (var propKey in props.Keys) { - // but only if a string - if (key is string && !isRef) + if (propKey is string key) { - object value = props[key]; - if (!key.Equals(CDKPropertyName.Title) && !key.Equals(CDKPropertyName.InChI)) + // but only if a string + if (!isRef) { - // ok, should output this - CMLScalar scalar = new CMLScalar(); - this.CheckPrefix(scalar); - scalar.DictRef = "cdk:molecularProperty"; - scalar.Title = (string)key; - scalar.SetValue(value.ToString()); - cmlMolecule.Add(scalar); + object value = props[key]; + switch (key) + { + case CDKPropertyName.Title: + case CDKPropertyName.InChI: + break; + default: + // ok, should output this + var scalar = new CMLScalar(); + this.CheckPrefix(scalar); + scalar.DictRef = "cdk:molecularProperty"; + scalar.Title = (string)key; + scalar.SetValue(value.ToString()); + cmlMolecule.Add(scalar); + break; + } } - } - // FIXME: At the moment the order writing the formula is into properties - // but it should be that IMolecularFormula is a extension of IAtomContainer - if (key is string && !isRef && key.ToString().Equals(CDKPropertyName.Formula)) - { - switch (props[key]) + // FIXME: At the moment the order writing the formula is into properties + // but it should be that IMolecularFormula is a extension of IAtomContainer + if (!isRef && string.Equals(key, CDKPropertyName.Formula, StringComparison.Ordinal)) { - case IMolecularFormula cdkFormula: - { - CMLFormula cmlFormula = new CMLFormula(); - IList isotopesList = MolecularFormulaManipulator.PutInOrder( - MolecularFormulaManipulator.OrderEle, cdkFormula); - foreach (var isotope in isotopesList) + switch (props[key]) + { + case IMolecularFormula cdkFormula: { - cmlFormula.Add(isotope.Symbol, cdkFormula.GetCount(isotope)); + var cmlFormula = new CMLFormula(); + var isotopesList = MolecularFormulaManipulator.PutInOrder(MolecularFormulaManipulator.OrderEle, cdkFormula); + foreach (var isotope in isotopesList) + { + cmlFormula.Add(isotope.Symbol, cdkFormula.GetCount(isotope)); + } + cmlMolecule.Add(cmlFormula); } - cmlMolecule.Add(cmlFormula); - } - break; - case IMolecularFormulaSet cdkFormulaSet: - { + break; + case IMolecularFormulaSet cdkFormulaSet: foreach (var cdkFormula in cdkFormulaSet) { - var isotopesList = MolecularFormulaManipulator.PutInOrder( - MolecularFormulaManipulator.OrderEle, cdkFormula); - CMLFormula cmlFormula = new CMLFormula - { - DictRef = "cdk:possibleMachts" - }; + var isotopesList = MolecularFormulaManipulator.PutInOrder(MolecularFormulaManipulator.OrderEle, cdkFormula); + var cmlFormula = new CMLFormula { DictRef = "cdk:possibleMachts" }; foreach (var isotope in isotopesList) { - cmlFormula.Add(isotope.Symbol, - cdkFormula.GetCount(isotope)); + cmlFormula.Add(isotope.Symbol, cdkFormula.GetCount(isotope)); } cmlMolecule.Add(cmlFormula); } - } - break; + break; + } } } } foreach (var element in customizers.Keys) { - ICMLCustomizer customizer = customizers[element]; + var customizer = customizers[element]; try { customizer.Customize(structure, cmlMolecule); } catch (Exception exception) { - Trace.TraceError("Error while customizing CML output with customizer: ", customizer.GetType().Name); + Trace.TraceError($"Error while customizing CML output with customizer: {customizer.GetType().Name}"); Debug.WriteLine(exception); } } return cmlMolecule; } - private bool AddDictRef(IChemObject obj, CMLElement cmlElement) + private static bool AddDictRef(IChemObject obj, CMLElement cmlElement) { var properties = obj.GetProperties(); foreach (var key in properties.Keys) @@ -610,15 +610,15 @@ private bool AddDictRef(IChemObject obj, CMLElement cmlElement) return false; } - private bool AddAtomID(IAtom cdkAtom, CMLAtom cmlAtom) + private static bool AddAtomID(IAtom cdkAtom, CMLAtom cmlAtom) { - if (cdkAtom.Id != null && !cdkAtom.Id.Equals("")) + if (!string.IsNullOrEmpty(cdkAtom.Id)) { cmlAtom.Id = cdkAtom.Id; } else { - cmlAtom.Id = "a" + cdkAtom.GetHashCode().ToString(); + cmlAtom.Id = "a" + cdkAtom.GetHashCode().ToString(NumberFormatInfo.InvariantInfo); } return true; } @@ -646,7 +646,8 @@ public CMLAtom CDKAtomToCMLAtom(IAtomContainer container, IAtom cdkAtom) MapFractionalCoordsToCML(cmlAtom, cdkAtom); int? formalCharge = cdkAtom.FormalCharge; - if (formalCharge != null) cmlAtom.FormalCharge = formalCharge.Value; + if (formalCharge != null) + cmlAtom.FormalCharge = formalCharge.Value; // CML's hydrogen count consists of the sum of implicit and explicit // hydrogens (see bug #1655045). @@ -659,7 +660,8 @@ public CMLAtom CDKAtomToCMLAtom(IAtomContainer container, IAtom cdkAtom) { foreach (var atom in bond.Atoms) { - if ("H".Equals(atom.Symbol) && atom != cdkAtom) totalHydrogen++; + if (string.Equals("H", atom.Symbol, StringComparison.Ordinal) && atom != cdkAtom) + totalHydrogen++; } } } // else: it is the implicit hydrogen count @@ -679,7 +681,6 @@ public CMLAtom CDKAtomToCMLAtom(IAtomContainer container, IAtom cdkAtom) { CMLScalar scalar = new CMLScalar(); this.CheckPrefix(scalar); - // scalar.SetDataType("xsd:float"); scalar.DictRef = "cdk:partialCharge"; scalar.SetValue(cdkAtom.Charge.Value); cmlAtom.Add(scalar); @@ -688,16 +689,13 @@ public CMLAtom CDKAtomToCMLAtom(IAtomContainer container, IAtom cdkAtom) if (cdkAtom.IsAromatic) { - CMLScalar aromAtom = new CMLScalar - { - DictRef = "cdk:aromaticAtom" - }; + CMLScalar aromAtom = new CMLScalar { DictRef = "cdk:aromaticAtom" }; cmlAtom.Add(aromAtom); } foreach (var element in customizers.Keys) { - ICMLCustomizer customizer = (ICMLCustomizer)customizers[element]; + ICMLCustomizer customizer = customizers[element]; try { customizer.Customize(cdkAtom, cmlAtom); @@ -715,7 +713,7 @@ public CMLBond CDKJBondToCMLBond(IBond cdkBond) { CMLBond cmlBond = new CMLBond(); this.CheckPrefix(cmlBond); - if (cdkBond.Id == null || cdkBond.Id.Length == 0) + if (string.IsNullOrEmpty(cdkBond.Id)) { cmlBond.Id = "b" + cdkBond.GetHashCode(); } @@ -728,9 +726,9 @@ public CMLBond CDKJBondToCMLBond(IBond cdkBond) for (int i = 0; i < cdkBond.Atoms.Count; i++) { string atomID = cdkBond.Atoms[i].Id; - if (atomID == null || atomID.Length == 0) + if (string.IsNullOrEmpty(atomID)) { - atomRefArray[i] = "a" + cdkBond.Atoms[i].GetHashCode().ToString(); + atomRefArray[i] = "a" + cdkBond.Atoms[i].GetHashCode().ToString(NumberFormatInfo.InvariantInfo); } else { @@ -747,54 +745,53 @@ public CMLBond CDKJBondToCMLBond(IBond cdkBond) } BondOrder border = cdkBond.Order; - if (border == BondOrder.Single) - { - cmlBond.Order = "S"; - } - else if (border == BondOrder.Double) - { - cmlBond.Order = "D"; - } - else if (border == BondOrder.Triple) - { - cmlBond.Order = "T"; - } - else - { - CMLScalar scalar = new CMLScalar(); - this.CheckPrefix(scalar); - // scalar.SetDataType("xsd:float"); - scalar.DictRef = "cdk:bondOrder"; - scalar.Title = "order"; - scalar.SetValue(cdkBond.Order.Numeric()); - cmlBond.Add(scalar); + switch (border) + { + case BondOrder.Single: + cmlBond.Order = "S"; + break; + case BondOrder.Double: + cmlBond.Order = "D"; + break; + case BondOrder.Triple: + cmlBond.Order = "T"; + break; + default: + CMLScalar scalar = new CMLScalar(); + this.CheckPrefix(scalar); + scalar.DictRef = "cdk:bondOrder"; + scalar.Title = "order"; + scalar.SetValue(cdkBond.Order.Numeric()); + cmlBond.Add(scalar); + break; } if (cdkBond.IsAromatic) { - CMLBondType bType = new CMLBondType - { - DictRef = "cdk:aromaticBond" - }; + CMLBondType bType = new CMLBondType { DictRef = "cdk:aromaticBond" }; cmlBond.Add(bType); } - if (cdkBond.Stereo == BondStereo.Up || cdkBond.Stereo == BondStereo.Down) + switch (cdkBond.Stereo) { - CMLBondStereo bondStereo = new CMLBondStereo(); - this.CheckPrefix(bondStereo); - if (cdkBond.Stereo == BondStereo.Up) - { - bondStereo.DictRef = "cml:W"; - bondStereo.Value = "W"; - } - else - { - bondStereo.DictRef = "cml:H"; - bondStereo.Value = "H"; - } - cmlBond.Add(bondStereo); + case BondStereo.Up: + case BondStereo.Down: + CMLBondStereo bondStereo = new CMLBondStereo(); + this.CheckPrefix(bondStereo); + if (cdkBond.Stereo == BondStereo.Up) + { + bondStereo.DictRef = "cml:W"; + bondStereo.Value = "W"; + } + else + { + bondStereo.DictRef = "cml:H"; + bondStereo.Value = "H"; + } + cmlBond.Add(bondStereo); + break; } - if (cdkBond.GetProperties().Count > 0) WriteProperties(cdkBond, cmlBond); + if (cdkBond.GetProperties().Count > 0) + WriteProperties(cdkBond, cmlBond); foreach (var element in customizers.Keys) { @@ -818,37 +815,28 @@ private void WriteProperties(IChemObject obj, CMLElement cmlElement) var props = obj.GetProperties(); foreach (var key in props.Keys) { - // if (key is DictRef) - // { - // Object value = props[key]; - // CMLScalar scalar = new CMLScalar(); - // this.CheckPrefix(scalar); - // scalar.SetDictRef(((DictRef)key).GetType()); - // scalar.SetValue(value.ToString()); - // cmlElement.AppendChild(scalar); - // } - // else - //if (key is string) + string stringKey = (string)key; + switch (stringKey) { - string stringKey = (string)key; - if (stringKey.Equals(CDKPropertyName.Title)) - { + case CDKPropertyName.Title: // don't output this one. It's covered by AddTitle() - } - else if (!(stringKey.StartsWith("org.openscience.cdk", StringComparison.Ordinal))) - { - object value = props[key]; - CMLScalar scalar = new CMLScalar(); - this.CheckPrefix(scalar); - scalar.Title = (string)key; - scalar.Value = value.ToString(); - cmlElement.Add(scalar); - } + break; + default: + if (!(stringKey.StartsWith("org.openscience.cdk", StringComparison.Ordinal))) + { + object value = props[key]; + CMLScalar scalar = new CMLScalar(); + this.CheckPrefix(scalar); + scalar.Title = (string)key; + scalar.Value = value.ToString(); + cmlElement.Add(scalar); + } + break; } } } - private void MapFractionalCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) + private static void MapFractionalCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) { if (cdkAtom.FractionalPoint3D != null) { @@ -858,7 +846,7 @@ private void MapFractionalCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) } } - private void Map3DCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) + private static void Map3DCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) { if (cdkAtom.Point3D != null) { @@ -868,7 +856,7 @@ private void Map3DCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) } } - private void Map2DCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) + private static void Map2DCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) { if (cdkAtom.Point2D != null) { @@ -879,12 +867,12 @@ private void Map2DCoordsToCML(CMLAtom cmlAtom, IAtom cdkAtom) private void CheckPrefix(CMLElement element) { - if (this.prefix != null) + if (string.IsNullOrWhiteSpace(prefix)) { - this.prefix.Trim(); - if (this.prefix.Length == 0) prefix = null; + prefix = null; } - if (this.prefix != null) element.Name = (XNamespace)(this.prefix) + element.Name.LocalName; + if (prefix != null) + element.Name = (XNamespace)(this.prefix) + element.Name.LocalName; } } } diff --git a/NCDK/LibIO/CML/PDBAtomCustomizer.cs b/NCDK/LibIO/CML/PDBAtomCustomizer.cs index c08d1626..221e38c8 100644 --- a/NCDK/LibIO/CML/PDBAtomCustomizer.cs +++ b/NCDK/LibIO/CML/PDBAtomCustomizer.cs @@ -169,7 +169,7 @@ public void Customize(IAtom atom, object nodeToAdd) } } - private bool HasContent(string str) + private static bool HasContent(string str) { return !string.IsNullOrEmpty(str); } diff --git a/NCDK/LibIO/CML/QSARCustomizer.cs b/NCDK/LibIO/CML/QSARCustomizer.cs index 386d305f..0d010cc7 100644 --- a/NCDK/LibIO/CML/QSARCustomizer.cs +++ b/NCDK/LibIO/CML/QSARCustomizer.cs @@ -25,6 +25,7 @@ using NCDK.QSAR; using NCDK.QSAR.Results; using System; +using System.Globalization; using System.Text; using System.Xml.Linq; @@ -58,7 +59,7 @@ public void Customize(IAtomContainer molecule, object nodeToAdd) CustomizeIChemObject(molecule, nodeToAdd); } - private XElement CreateScalar(IDescriptorResult value) + private static XElement CreateScalar(IDescriptorResult value) { XElement scalar = null; switch (value) @@ -76,7 +77,7 @@ private XElement CreateScalar(IDescriptorResult value) { scalar = new CMLArray(); scalar.SetAttributeValue(CMLElement.Attribute_dataType, "xsd:int"); - scalar.SetAttributeValue(CMLElement.Attribute_size, result.Length.ToString()); + scalar.SetAttributeValue(CMLElement.Attribute_size, result.Length.ToString(NumberFormatInfo.InvariantInfo)); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < result.Length; i++) { @@ -107,7 +108,7 @@ private XElement CreateScalar(IDescriptorResult value) return scalar; } - private void CustomizeIChemObject(IChemObject obj, object nodeToAdd) + private static void CustomizeIChemObject(IChemObject obj, object nodeToAdd) { if (!(nodeToAdd is XElement)) throw new CDKException("NodeToAdd must be of type nu.xom.Element!"); @@ -151,14 +152,14 @@ private void CustomizeIChemObject(IChemObject obj, object nodeToAdd) metaData.SetAttributeValue(CMLElement.Attribute_content, specs.ImplementationVendor); metadataList.Add(metaData); // add parameter setting to the metadata list - object[] parameters = value.Parameters; - // Debug.WriteLine("Value: " + value.Specification.ImplementationIdentifier); - if (parameters != null && parameters.Length > 0) + var parameters = value.Parameters; + // Debug.WriteLine($"Value: {value.Specification.ImplementationIdentifier}"); + if (parameters != null && parameters.Count > 0) { var paramNames = value.ParameterNames; var paramSettings = new CMLMetadataList(); paramSettings.SetAttributeValue(CMLElement.Attribute_title, QSAR_NAMESPACE + ":" + "descriptorParameters"); - for (int i = 0; i < parameters.Length; i++) + for (int i = 0; i < parameters.Count; i++) { var paramSetting = new CMLMetadata(); string paramName = paramNames[i]; @@ -169,7 +170,7 @@ private void CustomizeIChemObject(IChemObject obj, object nodeToAdd) } else if (paramVal == null) { - // Trace.TraceError("Parameter setting was null! Cannot output to CML. Problem param: " + paramName); + // Trace.TraceError($"Parameter setting was null! Cannot output to CML. Problem param: {paramName}"); } else { @@ -181,7 +182,7 @@ private void CustomizeIChemObject(IChemObject obj, object nodeToAdd) metadataList.Add(paramSettings); } property.Add(metadataList); - var scalar = this.CreateScalar(result); + var scalar = CreateScalar(result); scalar.SetAttributeValue(CMLElement.Attribute_dictRef, specsRef); // add the actual descriptor value property.Add(scalar); diff --git a/NCDK/LibIO/DotNetRDF/Convertor.cs b/NCDK/LibIO/DotNetRDF/Convertor.cs index fc79207e..405f9355 100644 --- a/NCDK/LibIO/DotNetRDF/Convertor.cs +++ b/NCDK/LibIO/DotNetRDF/Convertor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; using VDS.RDF; @@ -293,7 +294,7 @@ private void DeserializeElementFields(INode rdfObject, IAtomType element) var symbol = g.GetTriplesWithSubjectPredicate(rdfObject, P_SYMBOL).FirstOrDefault(); if (symbol != null) element.Symbol = symbol.Object.ToString(); var atomicNumber = g.GetTriplesWithSubjectPredicate(rdfObject, P_HASATOMICNUMBER).FirstOrDefault(); - if (atomicNumber != null) element.AtomicNumber = int.Parse(atomicNumber.Object.ToString()); + if (atomicNumber != null) element.AtomicNumber = int.Parse(atomicNumber.Object.ToString(), NumberFormatInfo.InvariantInfo); } private void SerializeAtomTypeFields(INode rdfObject, IAtomType type) @@ -361,7 +362,7 @@ private void DeserializeAtomTypeFields(INode rdfObject, IAtomType element) } var formalCharge = g.GetTriplesWithSubjectPredicate(rdfObject, P_HASFORMALCHARGE).FirstOrDefault(); if (formalCharge != null) - element.FormalCharge = int.Parse(formalCharge.Object.ToString()); + element.FormalCharge = int.Parse(formalCharge.Object.ToString(), NumberFormatInfo.InvariantInfo); } @@ -369,11 +370,11 @@ private void DeserializeIsotopeFields(INode rdfObject, IAtomType isotope) { DeserializeElementFields(rdfObject, isotope); var massNumber = g.GetTriplesWithSubjectPredicate(rdfObject, P_HASMASSNUMBER).FirstOrDefault(); - if (massNumber != null) isotope.MassNumber = int.Parse(massNumber.Object.ToString()); + if (massNumber != null) isotope.MassNumber = int.Parse(massNumber.Object.ToString(), NumberFormatInfo.InvariantInfo); var exactMass = g.GetTriplesWithSubjectPredicate(rdfObject, P_HASEXACTMASS).FirstOrDefault(); - if (exactMass != null) isotope.ExactMass = double.Parse(exactMass.Object.ToString()); + if (exactMass != null) isotope.ExactMass = double.Parse(exactMass.Object.ToString(), NumberFormatInfo.InvariantInfo); var naturalAbundance = g.GetTriplesWithSubjectPredicate(rdfObject, P_HASNATURALABUNDANCE).FirstOrDefault(); - if (naturalAbundance != null) isotope.NaturalAbundance = double.Parse(naturalAbundance.Object.ToString()); + if (naturalAbundance != null) isotope.NaturalAbundance = double.Parse(naturalAbundance.Object.ToString(), NumberFormatInfo.InvariantInfo); } /// @@ -381,7 +382,7 @@ private void DeserializeIsotopeFields(INode rdfObject, IAtomType isotope) /// /// Resource for which the matching should be given. /// the matching . - public BondOrder Resource2Order(INode rdfOrder) + public static BondOrder Resource2Order(INode rdfOrder) { switch (rdfOrder?.ToString()) { @@ -434,7 +435,7 @@ private void DeserializeElectronContainerFields(INode rdfObject, IElectronContai { DeserializeChemObjectFields(rdfObject, bond); var count = g.GetTriplesWithSubjectPredicate(rdfObject, P_HASELECTRONCOUNT).Select(n => n.Object).FirstOrDefault(); - if (count != null) bond.ElectronCount = int.Parse(count.ToString()); + if (count != null) bond.ElectronCount = int.Parse(count.ToString(), NumberFormatInfo.InvariantInfo); } /// diff --git a/NCDK/Maths/MersenneTwister.cs b/NCDK/Maths/MersenneTwister.cs index 2cbee413..5d752084 100644 --- a/NCDK/Maths/MersenneTwister.cs +++ b/NCDK/Maths/MersenneTwister.cs @@ -224,7 +224,7 @@ public override void SetSeed(long seed) /// /// number of random bits to produce /// random bits generated - protected override uint Next(int bits) + protected override uint GenerateNext(int bits) { uint y; diff --git a/NCDK/Maths/Primes.cs b/NCDK/Maths/Primes.cs index 18aad47b..dd353d7d 100644 --- a/NCDK/Maths/Primes.cs +++ b/NCDK/Maths/Primes.cs @@ -177,7 +177,8 @@ internal static class Primes /// public static int GetPrimeAt(int index) { - if (index < 0 || index > PRIMES.Length - 1) throw new IndexOutOfRangeException("out of range " + index); + if (index < 0 || index > PRIMES.Length - 1) + throw new ArgumentOutOfRangeException(nameof(index), "out of range {index}"); return PRIMES[index]; } } diff --git a/NCDK/Maths/RandomNumbersTool.cs b/NCDK/Maths/RandomNumbersTool.cs index 80093a70..18901798 100644 --- a/NCDK/Maths/RandomNumbersTool.cs +++ b/NCDK/Maths/RandomNumbersTool.cs @@ -76,25 +76,14 @@ protected UInt32 Next(int bits) /// // @cdk.module standard // @cdk.githash - public class RandomNumbersTool + public static class RandomNumbersTool { - private static BitsStreamGenerator random; - private static long randomSeed; - - static RandomNumbersTool() - { - randomSeed = System.DateTime.Now.Ticks; - random = new MersenneTwister(randomSeed); - } + private static long randomSeed = DateTime.Now.Ticks; /// /// The instance of Random used by this class. /// - public static BitsStreamGenerator Random - { - get { return random; } - set { random = value; } - } + public static BitsStreamGenerator Random { get; set; } = new MersenneTwister(randomSeed); /// /// The seed being used by this random number generator. @@ -108,7 +97,7 @@ public static long RandomSeed set { randomSeed = value; - random.SetSeed(randomSeed); + Random.SetSeed(randomSeed); } } @@ -126,7 +115,7 @@ public static long RandomSeed /// a random integer between and . public static int RandomInt(int lo, int hi) { - return (Math.Abs(random.Next()) % (hi - lo + 1)) + lo; + return (Math.Abs(Random.Next()) % (hi - lo + 1)) + lo; } /// @@ -146,7 +135,7 @@ public static long RandomLong() /// a random long between and . public static long RandomLong(long lo, long hi) { - return NextLong(random, hi - lo + 1L) + lo; + return NextLong(Random, hi - lo + 1L) + lo; } /// @@ -174,7 +163,7 @@ private static long NextLong(BitsStreamGenerator rng, long n) /// a random float between '0' and '1'. public static float RandomFloat() { - return random.NextFloat(); + return Random.NextFloat(); } /// @@ -185,7 +174,7 @@ public static float RandomFloat() /// a random float between and . public static float RandomFloat(float lo, float hi) { - return (hi - lo) * random.NextFloat() + lo; + return (hi - lo) * Random.NextFloat() + lo; } /// @@ -194,7 +183,7 @@ public static float RandomFloat(float lo, float hi) /// a random double between '0' and '1'. public static double RandomDouble() { - return random.NextDouble(); + return Random.NextDouble(); } /// @@ -205,7 +194,7 @@ public static double RandomDouble() /// a random double between and . public static double RandomDouble(double lo, double hi) { - return (hi - lo) * random.NextDouble() + lo; + return (hi - lo) * Random.NextDouble() + lo; } /// @@ -243,7 +232,7 @@ public static bool FlipCoin(double p) /// a random float from a Gaussian distribution with deviation . public static float GaussianFloat(float dev) { - return (float)random.NextGaussian() * dev; + return (float)Random.NextGaussian() * dev; } /// @@ -253,7 +242,7 @@ public static float GaussianFloat(float dev) /// a random float from a Gaussian distribution with deviation . public static double GaussianDouble(double dev) { - return random.NextGaussian() * dev; + return Random.NextGaussian() * dev; } /// @@ -278,7 +267,7 @@ public abstract class BitsStreamGenerator private double nextGaussian; /// Creates a new random number generator. - public BitsStreamGenerator() + protected BitsStreamGenerator() { nextGaussian = double.NaN; } @@ -309,12 +298,12 @@ public BitsStreamGenerator() /// /// number of random bits to produce /// random bits generated - protected abstract uint Next(int bits); + protected abstract uint GenerateNext(int bits); /// public bool NextBool() { - return Next(1) != 0; + return GenerateNext(1) != 0; } /// @@ -324,7 +313,7 @@ public void NextBytes(byte[] bytes) int iEnd = bytes.Length - 3; while (i < iEnd) { - uint random = Next(32); + uint random = GenerateNext(32); bytes[i] = (byte)(random & 0xff); bytes[i + 1] = (byte)((random >> 8) & 0xff); bytes[i + 2] = (byte)((random >> 16) & 0xff); @@ -332,7 +321,7 @@ public void NextBytes(byte[] bytes) i += 4; } { - uint random = Next(32); + uint random = GenerateNext(32); while (i < bytes.Length) { bytes[i++] = (byte)(random & 0xff); @@ -346,8 +335,8 @@ public void NextBytes(byte[] bytes) /// public double NextDouble() { - ulong high = ((ulong)Next(26)) << 26; - ulong low = (ulong)Next(26); + ulong high = ((ulong)GenerateNext(26)) << 26; + ulong low = (ulong)GenerateNext(26); ulong s = high | low; var ret = Double_1_10000000000000 * s; return ret; @@ -358,7 +347,7 @@ public double NextDouble() /// public float NextFloat() { - var ret = Double_1_800000 * Next(23); + var ret = Double_1_800000 * GenerateNext(23); return (float)ret; } @@ -389,7 +378,7 @@ public double NextGaussian() /// public int Next() { - return (int)Next(32); + return (int)GenerateNext(32); } /// @@ -412,14 +401,14 @@ public int NextInt(int n) { if ((n & -n) == n) { - var nn = (ulong)Next(31); + var nn = (ulong)GenerateNext(31); return (int)(((ulong)n * nn) >> 31); } int bits; int val; do { - bits = (int)Next(31); + bits = (int)GenerateNext(31); val = bits % n; } while (bits - val + (n - 1) < 0); return val; @@ -430,8 +419,8 @@ public int NextInt(int n) /// public long NextLong() { - long high = ((long)Next(32)) << 32; - long low = ((long)Next(32)) & 0xffffffffL; + long high = ((long)GenerateNext(32)) << 32; + long low = ((long)GenerateNext(32)) & 0xffffffffL; return high | low; } diff --git a/NCDK/Modelings/Builder3D/AtomPlacer3D.cs b/NCDK/Modelings/Builder3D/AtomPlacer3D.cs index 0274b8c4..71df4684 100644 --- a/NCDK/Modelings/Builder3D/AtomPlacer3D.cs +++ b/NCDK/Modelings/Builder3D/AtomPlacer3D.cs @@ -38,7 +38,7 @@ namespace NCDK.Modelings.Builder3D // @cdk.githash public class AtomPlacer3D { - private IDictionary pSet = null; + private IReadOnlyDictionary pSet = null; private double[] distances; private int[] firstAtoms = null; private double[] angles = null; @@ -52,24 +52,23 @@ public class AtomPlacer3D private const double DEFAULT_SP2_ANGLE = 120.000; private const double DEFAULT_SP_ANGLE = 180.000; - internal AtomPlacer3D() { } + public AtomPlacer3D() + { + } - /// - /// Initialize the atomPlacer class. - /// /// Force Field parameter as Dictionary - public void Initilize(IDictionary parameterSet) + public AtomPlacer3D(IReadOnlyDictionary parameterSet) { pSet = parameterSet; } /// - /// Count and find first heavy Atom(s) (non Hydrogens) in a chain. + /// Count and find first heavy Atom(s) (non Hydrogens) in a chain. /// /// the reference molecule for searching the chain /// chain to be searched /// the atom number of the first heavy atom the number of heavy atoms in the chain - public int[] FindHeavyAtomsInChain(IAtomContainer molecule, IAtomContainer chain) + public virtual int[] FindHeavyAtomsInChain(IAtomContainer molecule, IAtomContainer chain) { int[] heavy = { -1, -1 }; int hc = 0; @@ -89,26 +88,12 @@ public int[] FindHeavyAtomsInChain(IAtomContainer molecule, IAtomContainer chain } /// - /// Mark all atoms in chain as placed. () - /// - /// chain - /// chain all atoms marked as placed - public IAtomContainer MarkPlaced(IAtomContainer ac) - { - for (int i = 0; i < ac.Atoms.Count; i++) - { - ac.Atoms[i].IsPlaced = true; - } - return ac; - } - - /// - /// Method assigns 3D coordinates to the heavy atoms in an aliphatic chain. + /// Method assigns 3D coordinates to the heavy atoms in an aliphatic chain. /// /// the reference molecule for the chain /// the atoms to be assigned, must be connected /// the 'chain' was not a chain - public void PlaceAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer chain) + public virtual void PlaceAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer chain) { //Debug.WriteLine("******** Place aliphatic Chain *********"); int[] first = new int[2]; @@ -133,7 +118,7 @@ public void PlaceAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer cha { if (!chain.Atoms[i].IsVisited) { - //Debug.WriteLine("Counter:" + counter); + //Debug.WriteLine($"Counter:{counter}"); nextAtomNr = molecule.Atoms.IndexOf(chain.Atoms[i]); id2 = molecule.Atoms[firstAtoms[counter - 1]].AtomTypeName; id1 = molecule.Atoms[nextAtomNr].AtomTypeName; @@ -142,7 +127,7 @@ public void PlaceAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer cha throw new CDKException("atoms do not form a chain, please use ModelBuilder3D"); distances[counter] = GetBondLengthValue(id1, id2); - //Debug.WriteLine(" Distance:" + distances[counter]); + //Debug.WriteLine($" Distance:{distances[counter]}"); firstAtoms[counter] = nextAtomNr; secondAtoms[counter] = firstAtoms[counter - 1]; if (counter > 1) @@ -167,7 +152,7 @@ public void PlaceAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer cha } } thirdAtoms[counter] = firstAtoms[counter - 2]; - //Debug.WriteLine(" Angle:" + angles[counter]); + //Debug.WriteLine($" Angle:{angles[counter]}"); } else { @@ -218,7 +203,7 @@ public void PlaceAliphaticHeavyChain(IAtomContainer molecule, IAtomContainer cha /// the molecule to be placed in 3D /// marks branched chain // @author: egonw,cho - public void ZMatrixChainToCartesian(IAtomContainer molecule, bool flagBranched) + public virtual void ZMatrixChainToCartesian(IAtomContainer molecule, bool flagBranched) { Vector3? result = null; for (int index = 0; index < distances.Length; index++) @@ -285,24 +270,24 @@ public void ZMatrixChainToCartesian(IAtomContainer molecule, bool flagBranched) } /// - /// Gets the hybridisation state of an atom. + /// Gets the hybridisation state of an atom. /// - /// atom + /// atom /// The hybridisationState value (sp=1;sp2=2;sp3=3) - private int GetHybridisationState(IAtom atom1) + private static int GetHybridisationState(IAtom atom) { - BondOrder maxBondOrder = atom1.MaxBondOrder; + BondOrder maxBondOrder = atom.MaxBondOrder; // if (atom1.FormalNeighbourCount == 1 || maxBondOrder > 4) { - if (atom1.FormalNeighbourCount == 1) + if (atom.FormalNeighbourCount == 1) { // WTF?? } - else if (atom1.FormalNeighbourCount == 2 || maxBondOrder == BondOrder.Triple) + else if (atom.FormalNeighbourCount == 2 || maxBondOrder == BondOrder.Triple) { return 1; //sp } - else if (atom1.FormalNeighbourCount == 3 || (maxBondOrder == BondOrder.Double)) + else if (atom.FormalNeighbourCount == 3 || (maxBondOrder == BondOrder.Double)) { return 2; //sp2 } @@ -314,8 +299,8 @@ private int GetHybridisationState(IAtom atom1) } /// - /// Gets the doubleBondConfiguration2D attribute of the AtomPlacer3D object - /// using existing 2D coordinates. + /// Gets the doubleBondConfiguration2D attribute of the AtomPlacer3D object + /// using existing 2D coordinates. /// /// the double bond /// coordinates (Vector2) of atom1 connected to bond @@ -323,7 +308,7 @@ private int GetHybridisationState(IAtom atom1) /// coordinates (Vector2) of atom3 connected to bond /// coordinates (Vector2) of atom4 connected to bond /// The doubleBondConfiguration2D value - private int GetDoubleBondConfiguration2D(IBond bond, Vector2? aa, Vector2? bb, Vector2? cc, Vector2? dd) + private static int GetDoubleBondConfiguration2D(IBond bond, Vector2? aa, Vector2? bb, Vector2? cc, Vector2? dd) { if (bond.Order != BondOrder.Double) { @@ -350,12 +335,12 @@ private int GetDoubleBondConfiguration2D(IBond bond, Vector2? aa, Vector2? bb, V } /// - /// Gets the distanceValue attribute of the parameter set. + /// Gets the distanceValue attribute of the parameter set. /// /// atom1 id /// atom2 id /// The distanceValue value from the force field parameter set - public double GetBondLengthValue(string id1, string id2) + public virtual double GetBondLengthValue(string id1, string id2) { string dkey = ""; if (pSet.ContainsKey(("bond" + id1 + ";" + id2))) @@ -381,7 +366,7 @@ public double GetBondLengthValue(string id1, string id2) /// Description of the Parameter /// Description of the Parameter /// The angleKey value - public double GetAngleValue(string id1, string id2, string id3) + public virtual double GetAngleValue(string id1, string id2, string id3) { string akey = ""; if (pSet.ContainsKey(("angle" + id1 + ";" + id2 + ";" + id3))) @@ -519,12 +504,11 @@ public IAtom GetNextPlacedHeavyAtomWithUnplacedRingNeighbour(IAtomContainer mole } /// - /// Gets the farthestAtom attribute of the AtomPlacer3D object. + /// Gets the farthestAtom attribute of the AtomPlacer3D object. /// /// Description of the Parameter - /// Description of the Parameter /// The farthestAtom value - public IAtom GetFarthestAtom(Vector3 refAtomPoint, IAtomContainer ac) + public virtual IAtom GetFarthestAtom(Vector3 refAtomPoint, IAtomContainer ac) { double distance = 0; IAtom atom = null; @@ -543,9 +527,10 @@ public IAtom GetFarthestAtom(Vector3 refAtomPoint, IAtomContainer ac) } /// - /// Gets the unplacedRingHeavyAtom attribute of the AtomPlacer3D object. + /// Gets the unplacedRingHeavyAtom attribute of the AtomPlacer3D object. /// - /// /// Description of the Parameter + /// + /// Description of the Parameter /// The unplacedRingHeavyAtom value public IAtom GetUnplacedRingHeavyAtom(IAtomContainer molecule, IAtom atom) { @@ -563,18 +548,18 @@ public IAtom GetUnplacedRingHeavyAtom(IAtomContainer molecule, IAtom atom) } /// - /// Calculates the geometric center of all placed atoms in the atomcontainer. + /// Calculates the geometric center of all placed atoms in the . /// /// - /// the geometric center - public Vector3 GeometricCenterAllPlacedAtoms(IAtomContainer molecule) + /// the geometric center + public virtual Vector3 GeometricCenterAllPlacedAtoms(IAtomContainer molecule) { IAtomContainer allPlacedAtoms = GetAllPlacedAtoms(molecule); return GeometryUtil.Get3DCenter(allPlacedAtoms); } /// - /// Returns a placed atom connected to a given atom. + /// Returns a placed atom connected to a given atom. /// /// /// The Atom whose placed bonding partners are to be returned @@ -656,10 +641,10 @@ public int NumberOfUnplacedHeavyAtoms(IAtomContainer ac) } /// - /// Gets the allPlacedAtoms attribute of the AtomPlacer3D object. + /// Gets the all placed atoms attribute of the AtomPlacer3D object. /// /// The allPlacedAtoms value - private IAtomContainer GetAllPlacedAtoms(IAtomContainer molecule) + private static IAtomContainer GetAllPlacedAtoms(IAtomContainer molecule) { IAtomContainer placedAtoms = molecule.Builder.NewAtomContainer(); // Changed by Kaz for (int i = 0; i < molecule.Atoms.Count; i++) @@ -732,13 +717,13 @@ internal bool IsRingHeavyAtom(IAtom atom) } /// - /// Determine if the atom is heavy (non-hydrogen). + /// Determine if the atom is heavy, typically non-hydrogen. /// /// The atom to be checked - /// True if the atom is non-hydrogen - internal bool IsHeavyAtom(IAtom atom) + /// if the atom is heavy, typically non-hydrogen + public virtual bool IsHeavyAtom(IAtom atom) { - return !atom.Symbol.Equals("H"); + return !string.Equals(atom.Symbol, "H", StringComparison.Ordinal); } } } diff --git a/NCDK/Modelings/Builder3D/AtomTetrahedralLigandPlacer3D.cs b/NCDK/Modelings/Builder3D/AtomTetrahedralLigandPlacer3D.cs index c3206790..3239d828 100644 --- a/NCDK/Modelings/Builder3D/AtomTetrahedralLigandPlacer3D.cs +++ b/NCDK/Modelings/Builder3D/AtomTetrahedralLigandPlacer3D.cs @@ -25,11 +25,12 @@ using System; using System.Collections.Generic; using NCDK.Numerics; +using System.Diagnostics; namespace NCDK.Modelings.Builder3D { /// - /// A set of static utility classes for geometric calculations on Atoms. + /// A set of static utility classes for geometric calculations on Atoms. /// // @author Peter Murray-Rust,chhoppe,egonw // @cdk.created 2003-??-?? @@ -37,10 +38,10 @@ namespace NCDK.Modelings.Builder3D // @cdk.githash public class AtomTetrahedralLigandPlacer3D { - private IDictionary pSet = null; - public const double DEFAULT_BOND_LENGTH_H = 1.0; + private IReadOnlyDictionary pSet = null; + public double DefaultBondLengthH { get; set; } = 1.0; - public readonly static double TETRAHEDRAL_ANGLE = 2.0 * Math.Acos(1.0 / Math.Sqrt(3.0)); + private readonly static double TETRAHEDRAL_ANGLE = 2.0 * Math.Acos(1.0 / Math.Sqrt(3.0)); private const double SP2_ANGLE = 120 * Math.PI / 180; private const double SP_ANGLE = Math.PI; @@ -48,32 +49,24 @@ public class AtomTetrahedralLigandPlacer3D readonly static Vector3 XV = new Vector3(1, 0, 0); readonly static Vector3 YV = new Vector3(0, 1, 0); - /// - /// Constructor for the AtomTetrahedralLigandPlacer3D object. - /// internal AtomTetrahedralLigandPlacer3D() { } - /// - /// Constructor for the setParameterSet object. - /// - /// Description of the Parameter - public void SetParameterSet(IDictionary moleculeParameter) + public AtomTetrahedralLigandPlacer3D(IReadOnlyDictionary moleculeParameter) { pSet = moleculeParameter; } /// - /// Generate coordinates for all atoms which are singly bonded and have no - /// coordinates. This is useful when hydrogens are present but have no coordinates. - /// It knows about C, O, N, S only and will give tetrahedral or trigonal - /// geometry elsewhere. Bond lengths are computed from covalent radii or taken - /// out of a parameter set if available. Angles are tetrahedral or trigonal + /// Generate coordinates for all atoms which are singly bonded and have no + /// coordinates. This is useful when hydrogens are present but have no coordinates. + /// It knows about C, O, N, S only and will give tetrahedral or trigonal + /// geometry elsewhere. Bond lengths are computed from covalent radii or taken + /// out of a parameter set if available. Angles are tetrahedral or trigonal /// /// the set of atoms involved - /// // @cdk.keyword coordinate calculation // @cdk.keyword 3D model - public void Add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) + public virtual void Add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) { IAtom refAtom = null; IAtom atomC = null; @@ -81,7 +74,7 @@ public void Add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) for (int i = 0; i < atomContainer.Atoms.Count; i++) { refAtom = atomContainer.Atoms[i]; - if (!refAtom.Symbol.Equals("H") && HasUnsetNeighbour(refAtom, atomContainer)) + if (!refAtom.Symbol.Equals("H", StringComparison.Ordinal) && HasUnsetNeighbour(refAtom, atomContainer)) { IAtomContainer noCoords = GetUnsetAtomsInAtomContainer(refAtom, atomContainer); IAtomContainer withCoords = GetPlacedAtomsInAtomContainer(refAtom, atomContainer); @@ -89,11 +82,11 @@ public void Add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) { atomC = GetPlacedHeavyAtomInAtomContainer(withCoords.Atoms[0], refAtom, atomContainer); } - if (refAtom.FormalNeighbourCount == 0 && refAtom.Symbol.Equals("C")) + if (refAtom.FormalNeighbourCount == 0 && refAtom.Symbol.Equals("C", StringComparison.Ordinal)) { nwanted = noCoords.Atoms.Count; } - else if (refAtom.FormalNeighbourCount == 0 && !refAtom.Symbol.Equals("C")) + else if (refAtom.FormalNeighbourCount == 0 && !refAtom.Symbol.Equals("C", StringComparison.Ordinal)) { nwanted = 4; } @@ -102,7 +95,7 @@ public void Add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) nwanted = refAtom.FormalNeighbourCount.Value - withCoords.Atoms.Count; } Vector3[] newPoints = Get3DCoordinatesForLigands(refAtom, noCoords, withCoords, atomC, nwanted, - DEFAULT_BOND_LENGTH_H, -1); + DefaultBondLengthH, -1); for (int j = 0; j < noCoords.Atoms.Count; j++) { IAtom ligand = noCoords.Atoms[j]; @@ -118,14 +111,14 @@ public void Add3DCoordinatesForSinglyBondedLigands(IAtomContainer atomContainer) } /// - /// Rescales Point2 so that length 1-2 is sum of covalent radii. - /// If covalent radii cannot be found, use bond length of 1.0 + /// Rescales Point2 so that length 1-2 is sum of covalent radii. + /// If covalent radii cannot be found, use bond length of 1.0 /// /// stationary atom /// movable atom /// coordinates for atom 2 /// new coordinates for atom 2 - public Vector3 RescaleBondLength(IAtom atom1, IAtom atom2, Vector3 point2) + public virtual Vector3 RescaleBondLength(IAtom atom1, IAtom atom2, Vector3 point2) { Vector3 point1 = atom1.Point3D.Value; double? d1 = atom1.CovalentRadius; @@ -144,29 +137,29 @@ public Vector3 RescaleBondLength(IAtom atom1, IAtom atom2, Vector3 point2) } /// - /// Adds 3D coordinates for singly-bonded ligands of a reference atom (A). - /// Initially designed for hydrogens. The ligands of refAtom are identified and - /// those with 3D coordinates used to generate the new points. (This allows - /// structures with partially known 3D coordinates to be used, as when groups - /// are added.) "Bent" and "non-planar" groups can be formed by taking a subset - /// of the calculated points. Thus R-NH2 could use 2 of the 3 points calculated - /// from (1,iii) nomenclature: A is point to which new ones are "attached". A - /// may have ligands B, C... B may have ligands J, K.. points X1, X2... are - /// returned The cases (see individual routines, which use idealised geometry - /// by default): (0) zero ligands of refAtom. The resultant points are randomly - /// oriented: (i) 1 points required; +x,0,0 (ii) 2 points: use +x,0,0 and - /// -x,0,0 (iii) 3 points: equilateral triangle in xy plane (iv) 4 points - /// x,x,x, x,-x,-x, -x,x,-x, -x,-x,x (1a) 1 Ligand(B) of refAtom which itself - /// has a ligand (J) (i) 1 points required; vector along AB vector (ii) 2 - /// points: 2 vectors in ABJ plane, staggered and eclipsed wrt J (iii) 3 - /// points: 1 staggered wrt J, the others +- gauche wrt J (1b) 1 Ligand(B) of - /// refAtom which has no other ligands. A random J is generated and (1a) - /// applied (2) 2 Ligands(B, C) of refAtom A (i) 1 points required; vector in - /// ABC plane bisecting AB, AC. If ABC is linear, no points (ii) 2 points: 2 - /// vectors at angle ang, whose resultant is 2i (3) 3 Ligands(B, C, D) of - /// refAtom A (i) 1 points required; if A, B, C, D coplanar, no points. else - /// vector is resultant of BA, CA, DA fails if atom itself has no coordinates - /// or >4 ligands + /// Adds 3D coordinates for singly-bonded ligands of a reference atom (A). + /// Initially designed for hydrogens. The ligands of refAtom are identified and + /// those with 3D coordinates used to generate the new points. (This allows + /// structures with partially known 3D coordinates to be used, as when groups + /// are added.) "Bent" and "non-planar" groups can be formed by taking a subset + /// of the calculated points. Thus R-NH2 could use 2 of the 3 points calculated + /// from (1,iii) nomenclature: A is point to which new ones are "attached". A + /// may have ligands B, C... B may have ligands J, K.. points X1, X2... are + /// returned The cases (see individual routines, which use idealised geometry + /// by default): (0) zero ligands of refAtom. The resultant points are randomly + /// oriented: (i) 1 points required; +x,0,0 (ii) 2 points: use +x,0,0 and + /// -x,0,0 (iii) 3 points: equilateral triangle in xy plane (iv) 4 points + /// x,x,x, x,-x,-x, -x,x,-x, -x,-x,x (1a) 1 Ligand(B) of refAtom which itself + /// has a ligand (J) (i) 1 points required; vector along AB vector (ii) 2 + /// points: 2 vectors in ABJ plane, staggered and eclipsed wrt J (iii) 3 + /// points: 1 staggered wrt J, the others +- gauche wrt J (1b) 1 Ligand(B) of + /// refAtom which has no other ligands. A random J is generated and (1a) + /// applied (2) 2 Ligands(B, C) of refAtom A (i) 1 points required; vector in + /// ABC plane bisecting AB, AC. If ABC is linear, no points (ii) 2 points: 2 + /// vectors at angle ang, whose resultant is 2i (3) 3 Ligands(B, C, D) of + /// refAtom A (i) 1 points required; if A, B, C, D coplanar, no points. else + /// vector is resultant of BA, CA, DA fails if atom itself has no coordinates + /// or >4 ligands /// /// (A) to which new ligands coordinates could be added /// A-X length @@ -175,12 +168,12 @@ public Vector3 RescaleBondLength(IAtom atom1, IAtom atom2, Vector3 point2) /// Description of the Parameter /// Description of the Parameter /// Description of the Parameter - /// Point3D[] points calculated. If request could not be + /// [] points calculated. If request could not be /// fulfilled (e.g. too many atoms, or strange geometry, returns empty - /// array (zero length, not null) + /// array (zero length, not ) /// // @cdk.keyword coordinate generation - public Vector3[] Get3DCoordinatesForLigands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, + public virtual Vector3[] Get3DCoordinatesForLigands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, IAtom atomC, int nwanted, double length, double angle) { Vector3[] newPoints = new Vector3[1]; @@ -226,7 +219,6 @@ public Vector3[] Get3DCoordinatesForLigands(IAtom refAtom, IAtomContainer noCoor // Debug.WriteLine("Get3DCoordinatesForLigandsERROR: Cannot place SP2 Ligands due to:" + ex1.ToString()); throw new CDKException("Cannot place sp2 substituents\n" + ex1.Message, ex1); } - } else { @@ -245,7 +237,7 @@ public Vector3[] Get3DCoordinatesForLigands(IAtom refAtom, IAtomContainer noCoor return newPoints; } - public Vector3 Get3DCoordinatesForSPLigands(IAtom refAtom, IAtomContainer withCoords, double length, double angle) + public virtual Vector3 Get3DCoordinatesForSPLigands(IAtom refAtom, IAtomContainer withCoords, double length, double angle) { //Debug.WriteLine(" SP Ligands start "+refAtom.Point3D+" "+(withCoords.GetAtomAt(0)).Point3D); Vector3 ca = refAtom.Point3D.Value - (withCoords.Atoms[0]).Point3D.Value; @@ -256,8 +248,8 @@ public Vector3 Get3DCoordinatesForSPLigands(IAtom refAtom, IAtomContainer withCo } /// - /// Main method for the calculation of the ligand coordinates for sp2 atoms. - /// Decides if one or two coordinates should be created + /// Main method for the calculation of the ligand coordinates for sp2 atoms. + /// Decides if one or two coordinates should be created /// /// central atom (Atom) /// Description of the Parameter @@ -266,7 +258,7 @@ public Vector3 Get3DCoordinatesForSPLigands(IAtom refAtom, IAtomContainer withCo /// Description of the Parameter /// Description of the Parameter /// coordinates as Points3d [] - public Vector3[] Get3DCoordinatesForSP2Ligands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, + public virtual Vector3[] Get3DCoordinatesForSP2Ligands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, IAtom atomC, double length, double angle) { //Debug.WriteLine(" SP2 Ligands start"); @@ -286,15 +278,15 @@ public Vector3[] Get3DCoordinatesForSP2Ligands(IAtom refAtom, IAtomContainer noC { //Debug.WriteLine("NoCoords 2:"+noCoords.Atoms.Count); newPoints = Calculate3DCoordinatesSP2_2(refAtom.Point3D.Value, (withCoords.Atoms[0]).Point3D.Value, - (atomC != null) ? atomC.Point3D : null, length, angle); + atomC?.Point3D, length, angle); } //Debug.WriteLine("Ready SP2"); return newPoints; } /// - /// Main method for the calculation of the ligand coordinates for sp3 atoms. - /// Decides how many coordinates should be created + /// Main method for the calculation of the ligand coordinates for sp3 atoms. + /// Decides how many coordinates should be created /// /// central atom (Atom) /// how many ligands should be created @@ -305,11 +297,11 @@ public Vector3[] Get3DCoordinatesForSP2Ligands(IAtom refAtom, IAtomContainer noC /// Description of the Parameter /// Description of the Parameter /// Description of the Return Value - public Vector3[] Get3DCoordinatesForSP3Ligands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, + public virtual Vector3[] Get3DCoordinatesForSP3Ligands(IAtom refAtom, IAtomContainer noCoords, IAtomContainer withCoords, IAtom atomC, int nwanted, double length, double angle) { //Debug.WriteLine("SP3 Ligands start "); - Vector3[] newPoints = new Vector3[0]; + Vector3[] newPoints = Array.Empty(); Vector3 aPoint = refAtom.Point3D.Value; int nwithCoords = withCoords.Atoms.Count; if (angle < 0) @@ -323,7 +315,7 @@ public Vector3[] Get3DCoordinatesForSP3Ligands(IAtom refAtom, IAtomContainer noC else if (nwithCoords == 1) { newPoints = Calculate3DCoordinates1(aPoint, (withCoords.Atoms[0]).Point3D.Value, - (atomC != null) ? atomC.Point3D : null, nwanted, length, angle); + atomC?.Point3D, nwanted, length, angle); } else if (nwithCoords == 2) { @@ -344,19 +336,19 @@ public Vector3[] Get3DCoordinatesForSP3Ligands(IAtom refAtom, IAtomContainer noC } /// - /// Calculates substituent points. Calculate substituent points for (0) zero - /// ligands of aPoint. The resultant points are randomly oriented: (i) 1 points - /// required; +x,0,0 (ii) 2 points: use +x,0,0 and -x,0,0 (iii) 3 points: - /// equilateral triangle in the xy plane (iv) 4 points x,x,x, x,-x,-x, -x,x,-x, - /// -x,-x,x where 3x**2 = bond length + /// Calculates substituent points. Calculate substituent points for (0) zero + /// ligands of aPoint. The resultant points are randomly oriented: (i) 1 points + /// required; +x,0,0 (ii) 2 points: use +x,0,0 and -x,0,0 (iii) 3 points: + /// equilateral triangle in the xy plane (iv) 4 points x,x,x, x,-x,-x, -x,x,-x, + /// -x,-x,x where 3x**2 = bond length /// /// to which substituents are added /// number of points to calculate (1-4) /// from aPoint /// Vector3[] nwanted points (or zero if failed) - public Vector3[] Calculate3DCoordinates0(Vector3 aPoint, int nwanted, double length) + public virtual Vector3[] Calculate3DCoordinates0(Vector3 aPoint, int nwanted, double length) { - Vector3[] points = new Vector3[0]; + Vector3[] points = Array.Empty(); if (nwanted == 1) { points = new Vector3[1]; @@ -388,12 +380,12 @@ public Vector3[] Calculate3DCoordinates0(Vector3 aPoint, int nwanted, double len } /// - /// Calculate new Point(s) X in a B-A system to form B-A-X. Use C as reference - /// for * staggering about the B-A bond (1a) 1 Ligand(B) of refAtom (A) which - /// itself has a ligand (C) (i) 1 points required; vector along AB vector (ii) - /// 2 points: 2 vectors in ABC plane, staggered and eclipsed wrt C (iii) 3 - /// points: 1 staggered wrt C, the others +- gauche wrt C If C is null, a - /// random non-colinear C is generated + /// Calculate new Point(s) X in a B-A system to form B-A-X. Use C as reference + /// for * staggering about the B-A bond (1a) 1 Ligand(B) of refAtom (A) which + /// itself has a ligand (C) (i) 1 points required; vector along AB vector (ii) + /// 2 points: 2 vectors in ABC plane, staggered and eclipsed wrt C (iii) 3 + /// points: 1 staggered wrt C, the others +- gauche wrt C If C is null, a + /// random non-colinear C is generated /// /// to which substituents are added /// number of points to calculate (1-3) @@ -402,7 +394,7 @@ public Vector3[] Calculate3DCoordinates0(Vector3 aPoint, int nwanted, double len /// Description of the Parameter /// Description of the Parameter /// Vector3[] nwanted points (or zero if failed) - public Vector3[] Calculate3DCoordinates1(Vector3 aPoint, Vector3 bPoint, Vector3? cPoint, int nwanted, double length, double angle) + public virtual Vector3[] Calculate3DCoordinates1(Vector3 aPoint, Vector3 bPoint, Vector3? cPoint, int nwanted, double length, double angle) { Vector3[] points = new Vector3[nwanted]; // BA vector @@ -452,10 +444,10 @@ public Vector3[] Calculate3DCoordinates1(Vector3 aPoint, Vector3 bPoint, Vector3 } /// - /// Calculate new Point(s) X in a B-A-C system, it forms a B-A(-C)-X - /// system. (2) 2 Ligands(B, C) of refAtom A (i) 1 points required; vector in - /// ABC plane bisecting AB, AC. If ABC is linear, no points (ii) 2 points: 2 - /// points X1, X2, X1-A-X2 = angle about 2i vector + /// Calculate new Point(s) X in a B-A-C system, it forms a B-A(-C)-X + /// system. (2) 2 Ligands(B, C) of refAtom A (i) 1 points required; vector in + /// ABC plane bisecting AB, AC. If ABC is linear, no points (ii) 2 points: 2 + /// points X1, X2, X1-A-X2 = angle about 2i vector /// /// to which substituents are added /// first ligand of A @@ -464,10 +456,10 @@ public Vector3[] Calculate3DCoordinates1(Vector3 aPoint, Vector3 bPoint, Vector3 /// A-X length /// B-A-X angle /// Vector3[] nwanted points (or zero if failed) - public Vector3[] Calculate3DCoordinates2(Vector3 aPoint, Vector3 bPoint, Vector3 cPoint, int nwanted, double length, double angle) + public virtual Vector3[] Calculate3DCoordinates2(Vector3 aPoint, Vector3 bPoint, Vector3 cPoint, int nwanted, double length, double angle) { //Debug.WriteLine("3DCoordinates2"); - Vector3[] newPoints = new Vector3[0]; + Vector3[] newPoints = Array.Empty(); double ang2 = angle / 2.0; Vector3 ba = aPoint - bPoint; @@ -501,9 +493,9 @@ public Vector3[] Calculate3DCoordinates2(Vector3 aPoint, Vector3 bPoint, Vector3 } /// - /// Calculate new point X in a B-A(-D)-C system. It forms a B-A(-D)(-C)-X - /// system. (3) 3 Ligands(B, C, D) of refAtom A (i) 1 points required; if A, B, - /// C, D coplanar, no points. else vector is resultant of BA, CA, DA + /// Calculate new point X in a B-A(-D)-C system. It forms a B-A(-D)(-C)-X + /// system. (3) 3 Ligands(B, C, D) of refAtom A (i) 1 points required; if A, B, + /// C, D coplanar, no points. else vector is resultant of BA, CA, DA /// /// to which substituents are added /// first ligand of A @@ -511,7 +503,7 @@ public Vector3[] Calculate3DCoordinates2(Vector3 aPoint, Vector3 bPoint, Vector3 /// third ligand of A /// A-X length /// Vector3 nwanted points (or null if failed (coplanar)) - public Vector3 Calculate3DCoordinates3(Vector3 aPoint, Vector3 bPoint, Vector3 cPoint, Vector3 dPoint, double length) + public virtual Vector3 Calculate3DCoordinates3(Vector3 aPoint, Vector3 bPoint, Vector3 cPoint, Vector3 dPoint, double length) { //Debug.WriteLine("3DCoordinates3"); Vector3 bc = bPoint - cPoint; @@ -547,7 +539,7 @@ public Vector3 Calculate3DCoordinates3(Vector3 aPoint, Vector3 bPoint, Vector3 c } /// - /// Calculate new point in B-A-C system. It forms B-A(-X)-C system, where A is sp2 + /// Calculate new point in B-A-C system. It forms B-A(-X)-C system, where A is sp2 /// /// central point A (Vector3) /// B (Vector3) @@ -555,7 +547,7 @@ public Vector3 Calculate3DCoordinates3(Vector3 aPoint, Vector3 bPoint, Vector3 c /// bond length /// angle between B(C)-A-X /// new Point (Vector3) - public Vector3 Calculate3DCoordinatesSP2_1(Vector3 aPoint, Vector3 bPoint, Vector3 cPoint, double length, double angle) + private static Vector3 Calculate3DCoordinatesSP2_1(Vector3 aPoint, Vector3 bPoint, Vector3 cPoint, double length, double angle) { //Debug.WriteLine("3DCoordinatesSP2_1"); Vector3 ba = bPoint - aPoint; @@ -574,7 +566,7 @@ public Vector3 Calculate3DCoordinatesSP2_1(Vector3 aPoint, Vector3 bPoint, Vecto } /// - /// Calculate two new points in B-A system. It forms B-A(-X)(-X) system, where A is sp2 + /// Calculate two new points in B-A system. It forms B-A(-X)(-X) system, where A is sp2 /// /// central point A (Vector3) /// B (Vector3) @@ -582,7 +574,7 @@ public Vector3 Calculate3DCoordinatesSP2_1(Vector3 aPoint, Vector3 bPoint, Vecto /// bond length /// angle between B(C)-A-X /// new Points (Vector3 []) - public Vector3[] Calculate3DCoordinatesSP2_2(Vector3 aPoint, Vector3 bPoint, Vector3? cPoint, double length, double angle) + private static Vector3[] Calculate3DCoordinatesSP2_2(Vector3 aPoint, Vector3 bPoint, Vector3? cPoint, double length, double angle) { //Debug.WriteLine("3DCoordinatesSP_2"); Vector3 ca = new Vector3(); @@ -617,11 +609,11 @@ public Vector3[] Calculate3DCoordinatesSP2_2(Vector3 aPoint, Vector3 bPoint, Vec } /// - /// Gets the nonColinearVector attribute of the AtomLigandPlacer3D class + /// Gets the non-colinear vector attribute of the AtomLigandPlacer3D class /// /// Description of the Parameter - /// The nonColinearVector value - private Vector3 GetNonColinearVector(Vector3 ab) + /// The non-colinear vector value + private static Vector3 GetNonColinearVector(Vector3 ab) { Vector3 cr = Vector3.Cross(ab, XV); if (cr.Length() > 0.00001) @@ -635,7 +627,7 @@ private Vector3 GetNonColinearVector(Vector3 ab) } /// - /// Rotates a vector around an axis. + /// Rotates a vector around an axis. /// /// vector to be rotated around axis /// axis of rotation @@ -670,13 +662,13 @@ private double GetDistanceValue(string id1, string id2) else { // Debug.WriteLine("DistanceKEYError:pSet has no key:" + id2 + " ; " + id1 + " take default bond length:" + DEFAULT_BOND_LENGTH_H); - return DEFAULT_BOND_LENGTH_H; + return DefaultBondLengthH; } return ((IList)pSet[dkey])[0]; } /// - /// Gets the angleKey attribute of the AtomPlacer3D object. + /// Gets the angleKey attribute of the AtomPlacer3D object. /// /// Description of the Parameter /// Description of the Parameter @@ -711,15 +703,14 @@ public double GetAngleValue(string id1, string id2, string id3) } else { - Console.Out.WriteLine("AngleKEYError:Unknown angle " + id1 + " " + id2 + " " + id3 + " take default angle:" - + TETRAHEDRAL_ANGLE); + Trace.TraceInformation($"AngleKEYError:Unknown angle {id1} {id2} {id3} take default angle:{TETRAHEDRAL_ANGLE}"); return TETRAHEDRAL_ANGLE; } return ((IList)pSet[akey])[0]; } /// - /// set Atoms in respect to stereoinformation. + /// Set Atoms in respect to stereoinformation. /// take placed neighbours to stereocenter /// create a x b /// if right handed system (spatproduct >0) @@ -734,7 +725,7 @@ public double GetAngleValue(string id1, string id2, string id3) /// neighbour of atomA /// the two possible placement points for unplaced atom (up and down) /// int value of branch point position - public int MakeStereocenter(Vector3 atomA, IBond ax, Vector3 atomB, Vector3 atomC, Vector3[] branchPoints) + public static int MakeStereocenter(Vector3 atomA, IBond ax, Vector3 atomB, Vector3 atomC, Vector3[] branchPoints) { Vector3 b = new Vector3((atomB.X - atomA.X), (atomB.Y - atomA.Y), (atomB.Z - atomA.Z)); Vector3 c = new Vector3((atomC.X - atomA.X), (atomC.Y - atomA.Y), (atomC.Z - atomA.Z)); @@ -763,26 +754,26 @@ public int MakeStereocenter(Vector3 atomA, IBond ax, Vector3 atomB, Vector3 atom } /// - /// Gets the spatproduct of three vectors. + /// Gets the spatproduct of three vectors. /// /// vector a /// vector b /// vector c /// double value of the spatproduct - public double GetSpatproduct(Vector3 a, Vector3 b, Vector3 c) + private static double GetSpatproduct(Vector3 a, Vector3 b, Vector3 c) { return (c.X * (b.Y * a.Z - b.Z * a.Y) + c.Y * (b.Z * a.X - b.X * a.Z) + c.Z * (b.X * a.Y - b.Y * a.X)); } /// - /// Calculates the torsionAngle of a-b-c-d. + /// Calculates the torsionAngle of a-b-c-d. /// /// Vector3 /// Vector3 /// Vector3 /// Vector3 /// The torsionAngle value - public double GetTorsionAngle(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + public static double GetTorsionAngle(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 ab = new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); Vector3 cb = new Vector3(c.X - b.X, c.Y - b.Y, c.Z - b.Z); @@ -805,12 +796,12 @@ public double GetTorsionAngle(Vector3 a, Vector3 b, Vector3 c, Vector3 d) } /// - /// Gets all placed neighbouring atoms of a atom. + /// Gets all placed neighbouring atoms of a atom. /// /// central atom (Atom) /// the molecule /// all connected and placed atoms to the central atom (AtomContainer) - public IAtomContainer GetPlacedAtomsInAtomContainer(IAtom atom, IAtomContainer ac) + internal static IAtomContainer GetPlacedAtomsInAtomContainer(IAtom atom, IAtomContainer ac) { var bonds = ac.GetConnectedBonds(atom); IAtomContainer connectedAtoms = atom.Builder.NewAtomContainer(); @@ -826,14 +817,7 @@ public IAtomContainer GetPlacedAtomsInAtomContainer(IAtom atom, IAtomContainer a return connectedAtoms; } - /// - /// Gets the unsetAtomsInAtomContainer attribute of the - /// AtomTetrahedralLigandPlacer3D object. - /// - /// Description of the Parameter - /// Description of the Parameter - /// The unsetAtomsInAtomContainer value - public IAtomContainer GetUnsetAtomsInAtomContainer(IAtom atom, IAtomContainer ac) + internal static IAtomContainer GetUnsetAtomsInAtomContainer(IAtom atom, IAtomContainer ac) { var atoms = ac.GetConnectedAtoms(atom); IAtomContainer connectedAtoms = atom.Builder.NewAtomContainer(); @@ -847,7 +831,7 @@ public IAtomContainer GetUnsetAtomsInAtomContainer(IAtom atom, IAtomContainer ac return connectedAtoms; } - public bool HasUnsetNeighbour(IAtom atom, IAtomContainer ac) + private static bool HasUnsetNeighbour(IAtom atom, IAtomContainer ac) { var atoms = ac.GetConnectedAtoms(atom); foreach (var curAtom in atoms) @@ -867,13 +851,13 @@ public bool HasUnsetNeighbour(IAtom atom, IAtomContainer ac) /// atom connected to atomA (Atom) /// molecule /// returns a connected atom (Atom) - public IAtom GetPlacedHeavyAtomInAtomContainer(IAtom atomA, IAtom atomB, IAtomContainer ac) + private static IAtom GetPlacedHeavyAtomInAtomContainer(IAtom atomA, IAtom atomB, IAtomContainer ac) { var atoms = ac.GetConnectedAtoms(atomA); IAtom atom = null; foreach (var curAtom in atoms) { - if (curAtom.IsPlaced && !curAtom.Symbol.Equals("H") && curAtom != atomB) + if (curAtom.IsPlaced && !curAtom.Symbol.Equals("H", StringComparison.Ordinal) && curAtom != atomB) { return curAtom; } diff --git a/NCDK/Modelings/Builder3D/ForceFieldConfigurator.cs b/NCDK/Modelings/Builder3D/ForceFieldConfigurator.cs index 73dc4594..ef328e22 100644 --- a/NCDK/Modelings/Builder3D/ForceFieldConfigurator.cs +++ b/NCDK/Modelings/Builder3D/ForceFieldConfigurator.cs @@ -50,8 +50,8 @@ namespace NCDK.Modelings.Builder3D public class ForceFieldConfigurator { private string ffName = "mmff94"; - private IList atomTypes; - private IDictionary parameterSet = null; + private IReadOnlyList atomTypes; + private IReadOnlyDictionary parameterSet = null; private MM2BasedParameterSetReader mm2 = null; private MMFF94BasedParameterSetReader mmff94 = null; private Stream ins = null; @@ -86,7 +86,7 @@ public bool CheckForceFieldType(string ffname) bool check = false; for (int i = 0; i < fftypes.Length; i++) { - if (fftypes[i].Equals(ffname)) + if (fftypes[i].Equals(ffname, StringComparison.Ordinal)) { check = true; break; @@ -116,16 +116,11 @@ public void SetForceFieldConfigurator(string ffname, IChemObjectBuilder builder) { check = this.CheckForceFieldType(ffname); ffName = ffname; - if (ffName.Equals("mm2")) + if (string.Equals(ffName, "mm2", StringComparison.Ordinal)) { - //Debug.WriteLine("ForceFieldConfigurator: open Force Field mm2"); - //f = new File(mm2File); - //ReadFile(f); ins = ResourceLoader.GetAsStream("NCDK.Modelings.ForceField.Data.mm2.prm"); - //Debug.WriteLine("ForceFieldConfigurator: open Force Field mm2 ... READY"); mm2 = new MM2BasedParameterSetReader(); mm2.SetInputStream(ins); - //Debug.WriteLine("ForceFieldConfigurator: mm2 set input stream ... READY"); try { this.SetMM2Parameters(builder); @@ -135,11 +130,8 @@ public void SetForceFieldConfigurator(string ffname, IChemObjectBuilder builder) throw new CDKException("Problems with set MM2Parameters due to " + ex1.ToString(), ex1); } } - else if (ffName.Equals("mmff94") || !check) + else if (ffName.Equals("mmff94", StringComparison.Ordinal) || !check) { - //Debug.WriteLine("ForceFieldConfigurator: open Force Field mmff94"); - //f = new File(mmff94File); - //ReadFile(f); ins = ResourceLoader.GetAsStream("NCDK.Modelings.ForceField.Data.mmff94.prm"); mmff94 = new MMFF94BasedParameterSetReader(); @@ -154,7 +146,6 @@ public void SetForceFieldConfigurator(string ffname, IChemObjectBuilder builder) } } } - //throw new CDKException("Data file for "+ffName+" force field could not be found"); } /// @@ -170,7 +161,7 @@ public void SetAtomTypes(List atomtypes) /// Sets the parameters attribute of the ForceFieldConfigurator object /// /// The new parameter values - public void SetParameters(IDictionary parameterset) + public void SetParameters(IReadOnlyDictionary parameterset) { parameterSet = parameterset; } @@ -180,7 +171,8 @@ public void SetMM2Parameters(IChemObjectBuilder builder) { try { - if (mm2 == null) mm2 = new MM2BasedParameterSetReader(); + if (mm2 == null) + mm2 = new MM2BasedParameterSetReader(); mm2.ReadParameterSets(builder); } catch (Exception ex1) @@ -203,13 +195,13 @@ public void SetMMFF94Parameters(IChemObjectBuilder builder) /// Gets the atomTypes attribute of the ForceFieldConfigurator object /// /// The atomTypes vector - public IList AtomTypes => atomTypes; + public IReadOnlyList AtomTypes => atomTypes; /// /// Gets the parameterSet attribute of the ForceFieldConfigurator object /// /// The parameterSet hashtable - public IDictionary GetParameterSet() + public IReadOnlyDictionary GetParameterSet() { return this.parameterSet; } @@ -217,21 +209,21 @@ public IDictionary GetParameterSet() /// /// Find the atomType for a id /// - /// Atomtype id of the forcefield + /// Atomtype id of the forcefield /// The atomType /// atomType is not known. - private IAtomType GetAtomType(string ID) + private IAtomType GetAtomType(string id) { IAtomType at = null; for (int i = 0; i < atomTypes.Count; i++) { at = (IAtomType)atomTypes[i]; - if (at.AtomTypeName.Equals(ID)) + if (at.AtomTypeName.Equals(id, StringComparison.Ordinal)) { return at; } } - throw new NoSuchAtomTypeException("AtomType " + ID + " could not be found"); + throw new NoSuchAtomTypeException($"AtomType {id} could not be found"); } /// @@ -312,22 +304,22 @@ public IRingSet AssignAtomTyps(IAtomContainer molecule) bondType = "0"; if (bond.Order == BondOrder.Single) { - if ((bond.Begin.AtomTypeName.Equals("Csp2")) - && ((bond.End.AtomTypeName.Equals("Csp2")) || (bond.End.AtomTypeName - .Equals("C=")))) + if ((bond.Begin.AtomTypeName.Equals("Csp2", StringComparison.Ordinal)) + && ((bond.End.AtomTypeName.Equals("Csp2", StringComparison.Ordinal)) + || (bond.End.AtomTypeName.Equals("C=", StringComparison.Ordinal)))) { bondType = "1"; } - if ((bond.Begin.AtomTypeName.Equals("C=")) - && ((bond.End.AtomTypeName.Equals("Csp2")) || (bond.End.AtomTypeName - .Equals("C=")))) + if ((bond.Begin.AtomTypeName.Equals("C=", StringComparison.Ordinal)) + && ((bond.End.AtomTypeName.Equals("Csp2", StringComparison.Ordinal)) + || (bond.End.AtomTypeName.Equals("C=", StringComparison.Ordinal)))) { bondType = "1"; } - if ((bond.Begin.AtomTypeName.Equals("Csp")) - && (bond.End.AtomTypeName.Equals("Csp"))) + if ((bond.Begin.AtomTypeName.Equals("Csp", StringComparison.Ordinal)) + && (bond.End.AtomTypeName.Equals("Csp", StringComparison.Ordinal))) { bondType = "1"; } @@ -345,15 +337,19 @@ public IRingSet AssignAtomTyps(IAtomContainer molecule) /// /// AtomContainer /// true/false - private bool IsHeteroRingSystem(IAtomContainer ac) + private static bool IsHeteroRingSystem(IAtomContainer ac) { if (ac != null) { for (int i = 0; i < ac.Atoms.Count; i++) { - if (!(ac.Atoms[i].Symbol).Equals("H") && !(ac.Atoms[i].Symbol).Equals("C")) + switch (ac.Atoms[i].Symbol) { - return true; + case "H": + case "C": + break; + default: + return true; } } } @@ -402,15 +398,15 @@ private IAtom SetAtom(IAtom atom, string ID) return atom; } - public IAtom ConfigureAtom(IAtom atom, string hoseCode, bool _boolean) + public IAtom ConfigureAtom(IAtom atom, string hoseCode, bool flag) { - if (ffName.Equals("mm2")) + if (string.Equals(ffName, "mm2", StringComparison.Ordinal)) { - return ConfigureMM2BasedAtom(atom, hoseCode, _boolean); + return ConfigureMM2BasedAtom(atom, hoseCode, flag); } - else if (ffName.Equals("mmff94")) + else if (string.Equals(ffName, "mmff94", StringComparison.Ordinal)) { - return ConfigureMMFF94BasedAtom(atom, hoseCode, _boolean); + return ConfigureMMFF94BasedAtom(atom, hoseCode, flag); } return atom; } @@ -611,7 +607,7 @@ public IAtom ConfigureMM2BasedAtom(IAtom atom, string hoseCode, bool hetRing) } } - public string RemoveAromaticityFlagsFromHoseCode(string hoseCode) + public static string RemoveAromaticityFlagsFromHoseCode(string hoseCode) { string hosecode = ""; for (int i = 0; i < hoseCode.Length; i++) diff --git a/NCDK/Modelings/Builder3D/MM2BasedAtomTypePattern.cs b/NCDK/Modelings/Builder3D/MM2BasedAtomTypePattern.cs index 28503ddd..6c268d4a 100644 --- a/NCDK/Modelings/Builder3D/MM2BasedAtomTypePattern.cs +++ b/NCDK/Modelings/Builder3D/MM2BasedAtomTypePattern.cs @@ -49,7 +49,7 @@ internal MM2BasedAtomTypePattern() /// Gets the atomTypePatterns attribute of the MM2BasedAtomTypePattern object /// /// The atomTypePatterns as a vector - public IList AtomTypePatterns => atomTypePatterns; + public IReadOnlyList AtomTypePatterns => atomTypePatterns; /// /// Creates the atom type pattern diff --git a/NCDK/Modelings/Builder3D/MM2BasedParameterSetReader.cs b/NCDK/Modelings/Builder3D/MM2BasedParameterSetReader.cs index 964ede7c..ad650a3d 100644 --- a/NCDK/Modelings/Builder3D/MM2BasedParameterSetReader.cs +++ b/NCDK/Modelings/Builder3D/MM2BasedParameterSetReader.cs @@ -27,6 +27,7 @@ using NCDK.Tools; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; namespace NCDK.Modelings.Builder3D @@ -43,10 +44,10 @@ namespace NCDK.Modelings.Builder3D // @cdk.keyword atom type, MM2 public class MM2BasedParameterSetReader { - private string configFile = "NCDK.Modelings.ForceField.Data.mm2.prm"; + private const string configFile = "NCDK.Modelings.ForceField.Data.mm2.prm"; private Stream ins = null; - private IDictionary parameterSet; - public IList AtomTypes { get; private set; } + private Dictionary parameterSet; + private readonly List atomTypes; private IEnumerator st; private string key = ""; @@ -56,10 +57,12 @@ public class MM2BasedParameterSetReader public MM2BasedParameterSetReader() { parameterSet = new Dictionary(); - AtomTypes = new List(); + atomTypes = new List(); } - public IDictionary GetParamterSet() + public IReadOnlyList AtomTypes => atomTypes; + + public IReadOnlyDictionary GetParamterSet() { return parameterSet; } @@ -81,238 +84,258 @@ private void SetForceFieldDefinitions() { string sid = st.Current; st.MoveNext(); string svalue = st.Current; st.MoveNext(); - if (sid.Equals(">bontunit")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">bond-cubic")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">bond-quartic")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">angleunit")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">angle-sextic")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">strbndunit")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">opbendunit")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">torsionunit")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">vdwtype")) - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - else if (sid.Equals(">radiusrule")) - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - else if (sid.Equals(">radiustype")) - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - else if (sid.Equals(">radiussize")) - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - else if (sid.Equals(">epsilonrule")) - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - else if (sid.Equals(">a-expterm")) - { - try - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals("b-expterm")) - { - try - { - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = svalue; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">c-expterm")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">vdw-14-scale")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">chg-14-scale")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else if (sid.Equals(">dielectric")) - { - try - { - double value1 = double.Parse(svalue); - key = sid.Substring(1); - //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} - parameterSet[key] = value1; - } - catch (FormatException) - { - throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); - } - } - else + switch (sid) { + case ">bontunit": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">bond-cubic": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">bond-quartic": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">angleunit": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">angle-sextic": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">strbndunit": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">opbendunit": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">torsionunit": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">vdwtype": + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + break; + case ">radiusrule": + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + break; + case ">radiustype": + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + break; + case ">radiussize": + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + break; + case ">epsilonrule": + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + break; + case ">a-expterm": + { + try + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case "b-expterm": + { + try + { + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = svalue; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">c-expterm": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">vdw-14-scale": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">chg-14-scale": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + case ">dielectric": + { + try + { + double value1 = double.Parse(svalue, System.Globalization.NumberFormatInfo.InvariantInfo); + key = sid.Substring(1); + //if (parameterSet.ContainsKey(key)){Debug.WriteLine("KeyError: hasKey "+key);} + parameterSet[key] = value1; + } + catch (FormatException) + { + throw new IOException("VdWaalsTable.ReadvdWaals: " + "Malformed Number"); + } + } + break; + default: + break; } } /// - /// Read and stores the atom types in a vector + /// Read and stores the atom types in a vector /// - /// Description of the Exception private void SetAtomTypes(IChemObjectBuilder builder) { string name = ""; @@ -334,9 +357,9 @@ private void SetAtomTypes(IChemObjectBuilder builder) try { - mass = double.Parse(sam); - an = int.Parse(san); - maxbond = int.Parse(smaxbond); + mass = double.Parse(sam, System.Globalization.NumberFormatInfo.InvariantInfo); + an = int.Parse(san, System.Globalization.NumberFormatInfo.InvariantInfo); + maxbond = int.Parse(smaxbond, System.Globalization.NumberFormatInfo.InvariantInfo); } catch (FormatException) @@ -353,13 +376,12 @@ private void SetAtomTypes(IChemObjectBuilder builder) var co = CDKPropertyName.RGB2Int(rl, gl, bl); atomType.SetProperty(CDKPropertyName.Color, co); atomType.AtomTypeName = sid; - AtomTypes.Add(atomType); + atomTypes.Add(atomType); } /// - /// Read vdw radius, stored into the parameter set + /// Read vdw radius, stored into the parameter set /// - /// Description of the Exception private void SetvdWaals() { IList data = new List(); @@ -369,8 +391,8 @@ private void SetvdWaals() string sepsi = st.Current; st.MoveNext(); try { - double epsi = double.Parse(sepsi); - double radius = double.Parse(sradius); + double epsi = double.Parse(sepsi, System.Globalization.NumberFormatInfo.InvariantInfo); + double radius = double.Parse(sradius, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(radius); data.Add(epsi); } @@ -384,9 +406,8 @@ private void SetvdWaals() } /// - /// Read vdW pair radius,stored into the parameter set + /// Read vdW pair radius, stored into the parameter set /// - /// Description of the Exception private void SetvdWaalpr() { IList data = new List(); @@ -397,8 +418,8 @@ private void SetvdWaalpr() string value2 = st.Current; st.MoveNext(); try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); } @@ -411,9 +432,8 @@ private void SetvdWaalpr() } /// - /// Sets the bond attribute stored into the parameter set + /// Sets the bond attribute stored into the parameter set /// - /// Description of the Exception private void SetBond() { IList data = new List(); @@ -425,8 +445,8 @@ private void SetBond() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); } @@ -439,9 +459,8 @@ private void SetBond() } /// - /// Sets the bond3 attribute stored into the parameter set + /// Sets the bond3 attribute stored into the parameter set /// - /// Description of the Exception private void SetBond3() { IList data = new List(); @@ -453,11 +472,10 @@ private void SetBond3() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); - } catch (FormatException) { @@ -468,9 +486,8 @@ private void SetBond3() } /// - /// Sets the bond4 attribute stored into the parameter set + /// Sets the bond4 attribute stored into the parameter set /// - /// Description of the Exception private void SetBond4() { IList data = new List(); @@ -482,8 +499,8 @@ private void SetBond4() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); } @@ -496,9 +513,8 @@ private void SetBond4() } /// - /// Sets the angle attribute stored into the parameter set + /// Sets the angle attribute stored into the parameter set /// - /// Description of the Exception private void SetAngle() { IList data = new List(); @@ -513,10 +529,10 @@ private void SetAngle() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); - double va4 = double.Parse(value4); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, System.Globalization.NumberFormatInfo.InvariantInfo); + double va4 = double.Parse(value4, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -541,9 +557,8 @@ private void SetAngle() } /// - /// Sets the angle3 attribute stored into the parameter set + /// Sets the angle3 attribute stored into the parameter set /// - /// Description of the Exception private void SetAngle3() { IList data = new List(); @@ -558,10 +573,10 @@ private void SetAngle3() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); - double va4 = double.Parse(value4); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, System.Globalization.NumberFormatInfo.InvariantInfo); + double va4 = double.Parse(value4, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -576,9 +591,8 @@ private void SetAngle3() } /// - /// Sets the angle4 attribute stored into the parameter set + /// Sets the angle4 attribute stored into the parameter set /// - /// Description of the Exception private void SetAngle4() { IList data = new List(); @@ -593,10 +607,10 @@ private void SetAngle4() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); - double va4 = double.Parse(value4); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, System.Globalization.NumberFormatInfo.InvariantInfo); + double va4 = double.Parse(value4, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -612,9 +626,8 @@ private void SetAngle4() } /// - /// Sets the strBnd attribute stored into the parameter set + /// Sets the strBnd attribute stored into the parameter set /// - /// Description of the Exception private void SetStrBnd() { IList data = new List(); @@ -624,7 +637,7 @@ private void SetStrBnd() try { - double va1 = double.Parse(value1); + double va1 = double.Parse(value1, NumberFormatInfo.InvariantInfo); data.Add(va1); } catch (FormatException) @@ -636,9 +649,8 @@ private void SetStrBnd() } /// - /// Sets the opBend attribute stored into the parameter set + /// Sets the opBend attribute stored into the parameter set /// - /// Description of the Exception private void SetOpBend() { IList data = new List(); @@ -649,7 +661,7 @@ private void SetOpBend() try { - double va1 = double.Parse(value1); + double va1 = double.Parse(value1, NumberFormatInfo.InvariantInfo); data.Add(va1); key = "opbend" + sid1 + ";" + sid2; if (parameterSet.ContainsKey(key)) @@ -668,9 +680,8 @@ private void SetOpBend() } /// - /// Sets the torsion attribute stored into the parameter set + /// Sets the torsion attribute stored into the parameter set /// - /// Description of the Exception private void SetTorsion() { IList data = new List(); @@ -691,9 +702,9 @@ private void SetTorsion() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -715,9 +726,8 @@ private void SetTorsion() } /// - /// Sets the torsion4 attribute stored into the parameter set + /// Sets the torsion4 attribute stored into the parameter set /// - /// Description of the Exception private void SetTorsion4() { IList data = new List(); @@ -738,9 +748,9 @@ private void SetTorsion4() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -754,9 +764,8 @@ private void SetTorsion4() } /// - /// Sets the charge attribute stored into the parameter set + /// Sets the charge attribute stored into the parameter set /// - /// Description of the Exception private void SetCharge() { IList data = new List(); @@ -766,7 +775,7 @@ private void SetCharge() try { - double va1 = double.Parse(value1); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); } catch (FormatException nfe) @@ -778,9 +787,8 @@ private void SetCharge() } /// - /// Sets the dipole attribute stored into the parameter set + /// Sets the dipole attribute stored into the parameter set /// - /// Description of the Exception private void SetDipole() { IList data = new List(); @@ -792,8 +800,8 @@ private void SetDipole() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); @@ -807,9 +815,8 @@ private void SetDipole() } /// - /// Sets the dipole3 attribute stored into the parameter set + /// Sets the dipole3 attribute stored into the parameter set /// - /// Description of the Exception private void SetDipole3() { IList data = new List(); @@ -821,8 +828,8 @@ private void SetDipole3() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); @@ -836,9 +843,8 @@ private void SetDipole3() } /// - /// Sets the piAtom attribute stored into the parameter set + /// Sets the piAtom attribute stored into the parameter set /// - /// Description of the Exception private void SetPiAtom() { IList data = new List(); @@ -850,9 +856,9 @@ private void SetPiAtom() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -866,9 +872,8 @@ private void SetPiAtom() } /// - /// Sets the piBond attribute stored into the parameter set + /// Sets the piBond attribute stored into the parameter set /// - /// Description of the Exception private void SetPiBond() { IList data = new List(); @@ -880,8 +885,8 @@ private void SetPiBond() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, System.Globalization.NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, System.Globalization.NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); } @@ -896,7 +901,6 @@ private void SetPiBond() /// /// The main method which parses through the force field configuration file /// - /// Description of the Exception public void ReadParameterSets(IChemObjectBuilder builder) { //vdW,vdWp,bond,bond4,bond3,angle,angle4,angle3, @@ -928,108 +932,111 @@ public void ReadParameterSets(IChemObjectBuilder builder) } var e_st = Strings.Tokenize(s, '\t', ' ', ';'); st = e_st.GetEnumerator(); st.MoveNext(); int nt = e_st.Count; - if (s.StartsWithChar('>') & nt > 1) + if (s.StartsWithChar('>') && nt > 1) { SetForceFieldDefinitions(); a[0]++; } - else if (s.StartsWith("atom", StringComparison.Ordinal) & nt <= 8) + else if (s.StartsWith("atom", StringComparison.Ordinal) && nt <= 8) { a[0]++; SetAtomTypes(builder); } - else if (s.StartsWith("vdw ", StringComparison.Ordinal) & nt <= 5) + else if (s.StartsWith("vdw ", StringComparison.Ordinal) && nt <= 5) { SetvdWaals(); a[1]++; } - else if (s.StartsWith("vdwpr ", StringComparison.Ordinal) & nt <= 6) + else if (s.StartsWith("vdwpr ", StringComparison.Ordinal) && nt <= 6) { SetvdWaalpr(); a[2]++; } - else if (s.StartsWith("bond ", StringComparison.Ordinal) & nt <= 7) + else if (s.StartsWith("bond ", StringComparison.Ordinal) && nt <= 7) { SetBond(); a[3]++; } - else if (s.StartsWith("bond4 ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("bond4 ", StringComparison.Ordinal) && nt == 5) { SetBond4(); a[4]++; } - else if (s.StartsWith("bond3 ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("bond3 ", StringComparison.Ordinal) && nt == 5) { SetBond3(); a[5]++; } - else if (s.StartsWith("angle ", StringComparison.Ordinal) & nt == 8) + else if (s.StartsWith("angle ", StringComparison.Ordinal) && nt == 8) { SetAngle(); a[6]++; } - else if (s.StartsWith("angle4 ", StringComparison.Ordinal) & nt == 8) + else if (s.StartsWith("angle4 ", StringComparison.Ordinal) && nt == 8) { SetAngle4(); a[17]++; } - else if (s.StartsWith("angle3 ", StringComparison.Ordinal) & nt == 8) + else if (s.StartsWith("angle3 ", StringComparison.Ordinal) && nt == 8) { SetAngle3(); a[7]++; } - else if (s.StartsWith("strbnd ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("strbnd ", StringComparison.Ordinal) && nt == 5) { SetStrBnd(); a[8]++; } - else if (s.StartsWith("opbend ", StringComparison.Ordinal) & nt == 4) + else if (s.StartsWith("opbend ", StringComparison.Ordinal) && nt == 4) { SetOpBend(); a[9]++; } - else if (s.StartsWith("torsion ", StringComparison.Ordinal) & nt == 14) + else if (s.StartsWith("torsion ", StringComparison.Ordinal) && nt == 14) { SetTorsion(); a[10]++; } - else if (s.StartsWith("torsion4 ", StringComparison.Ordinal) & nt == 14) + else if (s.StartsWith("torsion4 ", StringComparison.Ordinal) && nt == 14) { SetTorsion4(); a[11]++; } - else if (s.StartsWith("charge ", StringComparison.Ordinal) & nt == 3) + else if (s.StartsWith("charge ", StringComparison.Ordinal) && nt == 3) { SetCharge(); a[12]++; } - else if (s.StartsWith("dipole ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("dipole ", StringComparison.Ordinal) && nt == 5) { SetDipole(); a[13]++; } - else if (s.StartsWith("dipole3 ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("dipole3 ", StringComparison.Ordinal) && nt == 5) { SetDipole3(); a[14]++; } - else if (s.StartsWith("piatom ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("piatom ", StringComparison.Ordinal) && nt == 5) { SetPiAtom(); a[15]++; } - else if (s.StartsWith("pibond ", StringComparison.Ordinal) & nt == 5) + else if (s.StartsWith("pibond ", StringComparison.Ordinal) && nt == 5) { SetPiBond(); a[16]++; } }// end while - ins.Close(); } catch (IOException e) { throw new IOException("There was a problem parsing the mm2 forcefield due to:" + e.ToString()); } + finally + { + ins.Close(); + } } /// @@ -1037,13 +1044,13 @@ public void ReadParameterSets(IChemObjectBuilder builder) /// /// atomic number /// exact mass - /// the mass number (or null) if no mass number was found + /// the mass number (or >) if no mass number was found /// isotope configuration could not be loaded - private int? MassNumber(int atomicNumber, double exactMass) + private static int? MassNumber(int atomicNumber, double exactMass) { string symbol = PeriodicTable.GetSymbol(atomicNumber); - IIsotope isotope = Isotopes.Instance.GetIsotope(symbol, exactMass, 0.001); - return isotope != null ? isotope.MassNumber : null; + IIsotope isotope = BODRIsotopeFactory.Instance.GetIsotope(symbol, exactMass, 0.001); + return isotope?.MassNumber; } } } diff --git a/NCDK/Modelings/Builder3D/MMFF94BasedParameterSetReader.cs b/NCDK/Modelings/Builder3D/MMFF94BasedParameterSetReader.cs index fc187e4d..cc8c24d0 100644 --- a/NCDK/Modelings/Builder3D/MMFF94BasedParameterSetReader.cs +++ b/NCDK/Modelings/Builder3D/MMFF94BasedParameterSetReader.cs @@ -27,6 +27,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.Modelings.Builder3D @@ -42,19 +43,19 @@ namespace NCDK.Modelings.Builder3D // @cdk.keyword atom type, mmff94 public class MMFF94BasedParameterSetReader { - private string configFile = "NCDK.Modelings.ForceField.Data.mmff94.prm"; + private const string configFile = "NCDK.Modelings.ForceField.Data.mmff94.prm"; private Stream ins = null; - private IDictionary parameterSet; + private Dictionary parameterSet; private List atomTypes; private IEnumerator st; private string sid; - private string configFilevdW = "NCDK.Modelings.ForceField.Data.mmffvdw.prm"; + private const string configFilevdW = "NCDK.Modelings.ForceField.Data.mmffvdw.prm"; private Stream insvdW = null; private IEnumerator stvdW; private string sidvdW; - private string configFileDFSB = "NCDK.Modelings.ForceField.Data.mmffdfsb.par"; + private const string configFileDFSB = "NCDK.Modelings.ForceField.Data.mmffdfsb.par"; private Stream insDFSB; private IEnumerator stDFSB; @@ -67,12 +68,12 @@ public MMFF94BasedParameterSetReader() atomTypes = new List(); } - public IDictionary GetParamterSet() + public IReadOnlyDictionary GetParamterSet() { return parameterSet; } - public List AtomTypes => atomTypes; + public IReadOnlyList AtomTypes => atomTypes; /// /// Sets the file containing the config data @@ -111,13 +112,13 @@ private void SetAtomTypeData() try { - double well = double.Parse(swell); - double apol = double.Parse(sapol); - double Neff = double.Parse(sNeff); - double fcadj = double.Parse(sfcadj); - //double pbci = double.Parse(spbci); - double a = double.Parse(sA); - double g = double.Parse(sG); + double well = double.Parse(swell, NumberFormatInfo.InvariantInfo); + double apol = double.Parse(sapol, NumberFormatInfo.InvariantInfo); + double Neff = double.Parse(sNeff, NumberFormatInfo.InvariantInfo); + double fcadj = double.Parse(sfcadj, NumberFormatInfo.InvariantInfo); + //double pbci = double.Parse(spbci, NumberFormatInfo.InvariantInfo); + double a = double.Parse(sA, NumberFormatInfo.InvariantInfo); + double g = double.Parse(sG, NumberFormatInfo.InvariantInfo); data.Add(well); data.Add(apol); @@ -133,7 +134,7 @@ private void SetAtomTypeData() throw new IOException("Data: Malformed Number due to:" + nfe); } - Debug.WriteLine("data : well,apol,Neff,sDA,fcadj,spbci,a,g " + data); + Debug.WriteLine($"data : well,apol,Neff,sDA,fcadj,spbci,a,g {data}"); parameterSet[key] = data; } @@ -142,12 +143,12 @@ private void SetAtomTypeData() var data = new List(); try { - double radius = double.Parse(sradius); + double radius = double.Parse(sradius, NumberFormatInfo.InvariantInfo); data.Add(radius); } catch (FormatException nfe2) { - Debug.WriteLine("vdwError: Malformed Number due to:" + nfe2); + Debug.WriteLine($"vdwError: Malformed Number due to:{nfe2}"); } parameterSet[key] = data; @@ -155,7 +156,7 @@ private void SetAtomTypeData() data = new List(); try { - double q0 = double.Parse(sq0); + double q0 = double.Parse(sq0, NumberFormatInfo.InvariantInfo); data.Add(q0); } catch (FormatException nfe3) @@ -192,9 +193,9 @@ private void SetAtomTypes(IChemObjectBuilder builder) try { - maxbond = int.Parse(smaxbond); - mass = double.Parse(smass); - atomNr = int.Parse(satomNr); + maxbond = int.Parse(smaxbond, NumberFormatInfo.InvariantInfo); + mass = double.Parse(smass, NumberFormatInfo.InvariantInfo); + atomNr = int.Parse(satomNr, NumberFormatInfo.InvariantInfo); } catch (FormatException) @@ -233,11 +234,11 @@ private void SetBond() try { - double len = double.Parse(slen); - double k2 = double.Parse(sk2); - double k3 = double.Parse(sk3); - double k4 = double.Parse(sk4); - double bci = double.Parse(sbci); + double len = double.Parse(slen, NumberFormatInfo.InvariantInfo); + double k2 = double.Parse(sk2, NumberFormatInfo.InvariantInfo); + double k3 = double.Parse(sk3, NumberFormatInfo.InvariantInfo); + double k4 = double.Parse(sk4, NumberFormatInfo.InvariantInfo); + double bci = double.Parse(sbci, NumberFormatInfo.InvariantInfo); data.Add(len); data.Add(k2); data.Add(k3); @@ -274,10 +275,10 @@ private void SetAngle() try { //int code=new Integer(scode).Value; - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); - double va4 = double.Parse(value4); + double va1 = double.Parse(value1, NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, NumberFormatInfo.InvariantInfo); + double va4 = double.Parse(value4, NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); data.Add(va3); @@ -319,8 +320,8 @@ private void SetStrBnd() try { //int code=new Integer(scode).Value; - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); + double va1 = double.Parse(value1, NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, NumberFormatInfo.InvariantInfo); data.Add(va1); data.Add(va2); @@ -330,7 +331,7 @@ private void SetStrBnd() throw new IOException("setStrBnd: Malformed Number due to:" + nfe); } var key = "strbnd" + scode + ";" + sid1 + ";" + sid2 + ";" + sid3; - Debug.WriteLine("key =" + key); + Debug.WriteLine($"key ={key}"); parameterSet[key] = data; } @@ -355,14 +356,14 @@ private void SetTorsion() try { - double va1 = double.Parse(value1); - double va2 = double.Parse(value2); - double va3 = double.Parse(value3); - double va4 = double.Parse(value4); - double va5 = double.Parse(value5); + double va1 = double.Parse(value1, NumberFormatInfo.InvariantInfo); + double va2 = double.Parse(value2, NumberFormatInfo.InvariantInfo); + double va3 = double.Parse(value3, NumberFormatInfo.InvariantInfo); + double va4 = double.Parse(value4, NumberFormatInfo.InvariantInfo); + double va5 = double.Parse(value5, NumberFormatInfo.InvariantInfo); var key = "torsion" + scode + ";" + sid1 + ";" + sid2 + ";" + sid3 + ";" + sid4; - Debug.WriteLine("key = " + key); + Debug.WriteLine($"key = {key}"); if (parameterSet.ContainsKey(key)) { data = (IList)parameterSet[key]; @@ -371,7 +372,7 @@ private void SetTorsion() data.Add(va3); data.Add(va4); data.Add(va5); - Debug.WriteLine("data = " + data); + Debug.WriteLine($"data = {data}"); } else { @@ -383,7 +384,7 @@ private void SetTorsion() va4, va5 }; - Debug.WriteLine("data = " + data); + Debug.WriteLine($"data = {data}"); } parameterSet[key] = data; } @@ -409,7 +410,7 @@ private void SetOpBend() try { - double va1 = double.Parse(value1); + double va1 = double.Parse(value1, NumberFormatInfo.InvariantInfo); data.Add(va1); var key = "opbend" + sid1 + ";" + sid2 + ";" + sid3 + ";" + sid4; if (parameterSet.ContainsKey(key)) @@ -443,8 +444,8 @@ private void SetDefaultStrBnd() try { var key = "DFSB" + sIR + ";" + sJR + ";" + sKR; - double kbaIJK = double.Parse(skbaIJK); - double kbaKJI = double.Parse(skbaKJI); + double kbaIJK = double.Parse(skbaIJK, NumberFormatInfo.InvariantInfo); + double kbaKJI = double.Parse(skbaKJI, NumberFormatInfo.InvariantInfo); data.Add(kbaIJK); data.Add(kbaKJI); parameterSet[key] = data; @@ -514,37 +515,37 @@ public void ReadParameterSets(IChemObjectBuilder builder) } var e_st = Strings.Tokenize(s, '\t', ';', ' '); st = e_st.GetEnumerator(); st.MoveNext(); int nt = e_st.Count; - if (s.StartsWith("atom", StringComparison.Ordinal) & nt <= 8) + if (s.StartsWith("atom", StringComparison.Ordinal) && nt <= 8) { SetAtomTypes(builder); a[0]++; } - else if (s.StartsWith("bond", StringComparison.Ordinal) & nt == 9) + else if (s.StartsWith("bond", StringComparison.Ordinal) && nt == 9) { SetBond(); a[1]++; } - else if (s.StartsWith("angle", StringComparison.Ordinal) & nt <= 10) + else if (s.StartsWith("angle", StringComparison.Ordinal) && nt <= 10) { SetAngle(); a[2]++; } - else if (s.StartsWith("strbnd", StringComparison.Ordinal) & nt == 7) + else if (s.StartsWith("strbnd", StringComparison.Ordinal) && nt == 7) { SetStrBnd(); a[3]++; } - else if (s.StartsWith("torsion", StringComparison.Ordinal) & nt == 11) + else if (s.StartsWith("torsion", StringComparison.Ordinal) && nt == 11) { SetTorsion(); a[4]++; } - else if (s.StartsWith("opbend", StringComparison.Ordinal) & nt == 6) + else if (s.StartsWith("opbend", StringComparison.Ordinal) && nt == 6) { SetOpBend(); a[5]++; } - else if (s.StartsWith("data", StringComparison.Ordinal) & nt == 10) + else if (s.StartsWith("data", StringComparison.Ordinal) && nt == 10) { while (true) { @@ -555,14 +556,14 @@ public void ReadParameterSets(IChemObjectBuilder builder) } var e_stvdW = Strings.Tokenize(svdW, '\t', ';', ' '); stvdW = e_stvdW.GetEnumerator(); stvdW.MoveNext(); ntvdW = e_stvdW.Count; - Debug.WriteLine("ntvdW : " + ntvdW); - if (svdW.StartsWith("vdw", StringComparison.Ordinal) & ntvdW == 9) + Debug.WriteLine($"ntvdW : {ntvdW}"); + if (svdW.StartsWith("vdw", StringComparison.Ordinal) && ntvdW == 9) { st.MoveNext(); sid = st.Current; st.MoveNext(); stvdW.MoveNext(); sidvdW = stvdW.Current; stvdW.MoveNext(); - if (sid.Equals(sidvdW)) + if (sid.Equals(sidvdW, StringComparison.Ordinal)) { SetAtomTypeData(); a[6]++; @@ -589,7 +590,7 @@ public void ReadParameterSets(IChemObjectBuilder builder) while (true) { sDFSB = rDFSB.ReadLine(); - Debug.WriteLine("sDFSB = " + sDFSB); + Debug.WriteLine($"sDFSB = {sDFSB}"); if (sDFSB == null) { Debug.WriteLine("sDFSB == null, break"); @@ -597,8 +598,8 @@ public void ReadParameterSets(IChemObjectBuilder builder) } var e_stDFSB = Strings.Tokenize(sDFSB, '\t', ';', ' '); stDFSB = e_stDFSB.GetEnumerator(); stDFSB.MoveNext(); ntDFSB = e_stDFSB.Count; - Debug.WriteLine("ntDFSB : " + ntDFSB); - if (sDFSB.StartsWith("DFSB", StringComparison.Ordinal) & ntDFSB == 6) + Debug.WriteLine($"ntDFSB : {ntDFSB}"); + if (sDFSB.StartsWith("DFSB", StringComparison.Ordinal) && ntDFSB == 6) { SetDefaultStrBnd(); } @@ -619,11 +620,11 @@ public void ReadParameterSets(IChemObjectBuilder builder) /// exact mass /// the mass number (or null) if no mass number was found /// isotope configuration could not be loaded - private int? MassNumber(int atomicNumber, double exactMass) + private static int? MassNumber(int atomicNumber, double exactMass) { string symbol = PeriodicTable.GetSymbol(atomicNumber); - IIsotope isotope = Isotopes.Instance.GetIsotope(symbol, exactMass, 0.001); - return isotope != null ? isotope.MassNumber : null; + IIsotope isotope = BODRIsotopeFactory.Instance.GetIsotope(symbol, exactMass, 0.001); + return isotope?.MassNumber; } } } diff --git a/NCDK/Modelings/Builder3D/MMFF94ParametersCall.cs b/NCDK/Modelings/Builder3D/MMFF94ParametersCall.cs index d666f559..2bb1e10b 100644 --- a/NCDK/Modelings/Builder3D/MMFF94ParametersCall.cs +++ b/NCDK/Modelings/Builder3D/MMFF94ParametersCall.cs @@ -12,19 +12,21 @@ namespace NCDK.Modelings.Builder3D // @cdk.githash public class MMFF94ParametersCall { - private IDictionary pSet = null; + private IReadOnlyDictionary pSet = null; //private final static double DefaultBondLength = 1.5; //private final static double DEFAULT_ANGLE = 90; // Only to test //private final static double DEFAULT_TORSION_ANGLE = 90; - public MMFF94ParametersCall() { } + public MMFF94ParametersCall() + { + } /// /// Initialize the AtomOrder class. /// /// Force Field parameter as Map - public void Initialize(IDictionary parameterSet) + public void Initialize(IReadOnlyDictionary parameterSet) { pSet = parameterSet; } @@ -52,7 +54,7 @@ public IList GetBondData(string code, string id1, string id2) // + code + ";" + id2 + " ;" + id1+" take default bon length:" + // DefaultBondLength); return DefaultBondLength; } - //Debug.WriteLine("dkey = " + dkey); + //Debug.WriteLine($"dkey = {dkey}"); return (IList)pSet[dkey]; } @@ -81,7 +83,7 @@ public IList GetAngleData(string angleType, string id1, string id2, string id3) // +" take default angle:" + DEFAULT_ANGLE); return // (Vector)[DEFAULT_ANGLE,0,0]; } - //Debug.WriteLine("angle key : " + akey); + //Debug.WriteLine($"angle key : {akey}"); return (IList)pSet[akey]; } @@ -125,7 +127,7 @@ public IList GetBondAngleInteractionData(string strbndType, string id1, string i // + " ; " + id2 + " ; " + id3+" take default angle:" + // DEFAULT_ANGLE); return (Vector)[DEFAULT_ANGLE,0,0]; } - //Debug.WriteLine("akey : " + akey); + //Debug.WriteLine($"akey : {akey}"); return (IList)pSet[akey]; } @@ -148,7 +150,7 @@ public IList GetDefaultStretchBendData(int iR, int jR, int kR) // "KEYErrorDefaultStretchBend:Unknown default stretch-bend key in pSet: " // + iR + " ; " + jR + " ; " + kR); } - //Debug.WriteLine("dfsbkey : " + dfsbkey); + //Debug.WriteLine($"dfsbkey : {dfsbkey}"); return (IList)pSet[dfsbkey]; } @@ -192,7 +194,7 @@ public IList GetTorsionData(string code, string id1, string id2, string id3, str // " take default torsion angle:" + DEFAULT_TORSION_ANGLES); return // DEFAULT_TORSION_ANGLE; } - //Debug.WriteLine("dkey = " + dkey); + //Debug.WriteLine($"dkey = {dkey}"); return (IList)pSet[dkey]; } } diff --git a/NCDK/Modelings/Builder3D/ModelBuilder3D.cs b/NCDK/Modelings/Builder3D/ModelBuilder3D.cs index 07316a90..c8de0dc9 100644 --- a/NCDK/Modelings/Builder3D/ModelBuilder3D.cs +++ b/NCDK/Modelings/Builder3D/ModelBuilder3D.cs @@ -64,7 +64,7 @@ public class ModelBuilder3D { private static IDictionary memyselfandi = new Dictionary(); private TemplateHandler3D templateHandler = null; - private IDictionary parameterSet = null; + private IReadOnlyDictionary parameterSet = null; private readonly ForceFieldConfigurator ffc = new ForceFieldConfigurator(); string forceFieldName = "mm2"; @@ -127,7 +127,7 @@ private void SetForceField(string ffname, IChemObjectBuilder builder) } catch (CDKException ex1) { - Trace.TraceError("Problem with ForceField configuration due to>" + ex1.Message); + Trace.TraceError($"Problem with ForceField configuration due to>{ex1.Message}"); Debug.WriteLine(ex1); throw new CDKException("Problem with ForceField configuration due to>" + ex1.Message, ex1); } @@ -153,10 +153,8 @@ public IAtomContainer Generate3DCoordinates(IAtomContainer molecule, bool clone) // setup helper classes AtomPlacer atomPlacer = new AtomPlacer(); - AtomPlacer3D ap3d = new AtomPlacer3D(); - AtomTetrahedralLigandPlacer3D atlp3d = new AtomTetrahedralLigandPlacer3D(); - ap3d.Initilize(parameterSet); - atlp3d.SetParameterSet(parameterSet); + AtomPlacer3D ap3d = new AtomPlacer3D(parameterSet); + AtomTetrahedralLigandPlacer3D atlp3d = new AtomTetrahedralLigandPlacer3D(parameterSet); if (clone) molecule = (IAtomContainer)molecule.Clone(); @@ -172,7 +170,7 @@ public IAtomContainer Generate3DCoordinates(IAtomContainer molecule, bool clone) } catch (CDKException ex3) { - Trace.TraceError("PlaceSubstitutensERROR: Cannot place substitutents due to:" + ex3.Message); + Trace.TraceError($"PlaceSubstitutensERROR: Cannot place substitutents due to:{ex3.Message}"); Debug.WriteLine(ex3); throw new CDKException("PlaceSubstitutensERROR: Cannot place substitutents due to:" + ex3.Message, ex3); @@ -184,7 +182,7 @@ public IAtomContainer Generate3DCoordinates(IAtomContainer molecule, bool clone) IRingSet largestRingSet = null; int numberOfRingAtoms = 0; - IList ringSystems = null; + IReadOnlyList ringSystems = null; if (ringSetMolecule.Count > 0) { if (templateHandler == null) @@ -224,7 +222,7 @@ public IAtomContainer Generate3DCoordinates(IAtomContainer molecule, bool clone) } catch (CDKException ex3) { - Trace.TraceError("PlaceSubstitutensERROR: Cannot place substitutents due to:" + ex3.Message); + Trace.TraceError($"PlaceSubstitutensERROR: Cannot place substitutents due to:{ex3.Message}"); Debug.WriteLine(ex3); throw new CDKException("PlaceSubstitutensERROR: Cannot place substitutents due to:" + ex3.Message, ex3); } @@ -241,7 +239,7 @@ public IAtomContainer Generate3DCoordinates(IAtomContainer molecule, bool clone) /// Gets the ringSetOfAtom attribute of the ModelBuilder3D object. /// /// The ringSetOfAtom value - private IRingSet GetRingSetOfAtom(IList ringSystems, IAtom atom) + private static IRingSet GetRingSetOfAtom(IReadOnlyList ringSystems, IAtom atom) { IRingSet ringSetOfAtom = null; for (int i = 0; i < ringSystems.Count; i++) @@ -258,7 +256,7 @@ private IRingSet GetRingSetOfAtom(IList ringSystems, IAtom atom) /// Layout the molecule, starts with ring systems and than aliphatic chains. /// /// ringSystems of the molecule - private void LayoutMolecule(IList ringSetMolecule, IAtomContainer molecule, AtomPlacer3D ap3d, + private void LayoutMolecule(IReadOnlyList ringSetMolecule, IAtomContainer molecule, AtomPlacer3D ap3d, AtomTetrahedralLigandPlacer3D atlp3d, AtomPlacer atomPlacer) { //Debug.WriteLine("****** LAYOUT MOLECULE MAIN *******"); @@ -273,9 +271,9 @@ private void LayoutMolecule(IList ringSetMolecule, IAtomContainer mole if (atom != null) { //Debug.WriteLine("layout RingSystem..."); - IAtom unplacedAtom = ap3d.GetUnplacedRingHeavyAtom(molecule, atom); - IRingSet ringSetA = GetRingSetOfAtom(ringSetMolecule, unplacedAtom); - IAtomContainer ringSetAContainer = RingSetManipulator.GetAllInOneContainer(ringSetA); + var unplacedAtom = ap3d.GetUnplacedRingHeavyAtom(molecule, atom); + var ringSetA = GetRingSetOfAtom(ringSetMolecule, unplacedAtom); + var ringSetAContainer = RingSetManipulator.GetAllInOneContainer(ringSetA); templateHandler.MapTemplates(ringSetAContainer, ringSetAContainer.Atoms.Count); if (CheckAllRingAtomsHasCoordinates(ringSetAContainer)) @@ -320,7 +318,7 @@ private void LayoutMolecule(IList ringSetMolecule, IAtomContainer mole /// ring system which placedRingAtom is part of /// the geometric center of the already placed molecule /// placed neighbour atom of placedRingAtom - private void LayoutRingSystem(Vector3 originalCoord, IAtom placedRingAtom, IRingSet ringSet, + private static void LayoutRingSystem(Vector3 originalCoord, IAtom placedRingAtom, IRingSet ringSet, Vector3 centerPlacedMolecule, IAtom atomB, AtomPlacer3D ap3d) { //Debug.WriteLine("****** Layout ring System ******");Console.Out.WriteLine(">around atom:"+molecule.Atoms.IndexOf(placedRingAtom)); @@ -398,7 +396,7 @@ private void LayoutRingSystem(Vector3 originalCoord, IAtom placedRingAtom, IRing /// The new branchAtom /// placed atom to which the unplaced atom is connected /// placed atomNeighbours of atomA - private void SetBranchAtom(IAtomContainer molecule, IAtom unplacedAtom, IAtom atomA, IAtomContainer atomNeighbours, + private static void SetBranchAtom(IAtomContainer molecule, IAtom unplacedAtom, IAtom atomA, IAtomContainer atomNeighbours, AtomPlacer3D ap3d, AtomTetrahedralLigandPlacer3D atlp3d) { //Debug.WriteLine("****** SET Branch Atom ****** >"+molecule.Atoms.IndexOf(unplacedAtom)); @@ -445,7 +443,7 @@ private void SetBranchAtom(IAtomContainer molecule, IAtom unplacedAtom, IAtom at { if (atomNeighbours.Atoms.Count > 1) { - stereo = atlp3d.MakeStereocenter(atomA.Point3D.Value, molecule.GetBond(atomA, unplacedAtom), + stereo = AtomTetrahedralLigandPlacer3D.MakeStereocenter(atomA.Point3D.Value, molecule.GetBond(atomA, unplacedAtom), (atomNeighbours.Atoms[0]).Point3D.Value, (atomNeighbours.Atoms[1]).Point3D.Value, branchPoints); } @@ -473,13 +471,9 @@ private void SearchAndPlaceBranches(IAtomContainer molecule, IAtomContainer chai var atoms = molecule.GetConnectedAtoms(chain.Atoms[i]); foreach (var atom in atoms) { - if (!atom.Symbol.Equals("H") & !atom.IsPlaced & !atom.IsInRing) + if (!atom.Symbol.Equals("H", StringComparison.Ordinal) & !atom.IsPlaced & !atom.IsInRing) { - //Debug.WriteLine("SEARCH PLACE AND FOUND Branch Atom "+molecule.Atoms.IndexOf(chain.GetAtomAt(i))+ - // " New Atom:"+molecule.Atoms.IndexOf(atoms[j])+" -> STORE"); connectedAtoms.Add(ap3d.GetPlacedHeavyAtoms(molecule, chain.Atoms[i])); - //Debug.WriteLine("Connected atom1:"+molecule.Atoms.IndexOf(connectedAtoms.GetAtomAt(0))+" atom2:"+ - //molecule.Atoms.IndexOf(connectedAtoms.GetAtomAt(1))+ " Length:"+connectedAtoms.Atoms.Count); try { SetBranchAtom(molecule, atom, chain.Atoms[i], connectedAtoms, ap3d, atlp3d); @@ -554,7 +548,7 @@ private void PlaceLinearChains3D(IAtomContainer molecule, IAtomContainer startAt /// original coordinates of the placed ring atom from template /// new coordinates from branch placement /// AtomContainer contains atoms of ring system - private void TranslateStructure(Vector3 originalCoord, Vector3 newCoord, IAtomContainer ac) + private static void TranslateStructure(Vector3 originalCoord, Vector3 newCoord, IAtomContainer ac) { Vector3 transVector = originalCoord - newCoord; for (int i = 0; i < ac.Atoms.Count; i++) @@ -572,7 +566,7 @@ private void TranslateStructure(Vector3 originalCoord, Vector3 newCoord, IAtomCo /// /// AtomContainer /// bool - private bool CheckAllRingAtomsHasCoordinates(IAtomContainer ac) + private static bool CheckAllRingAtomsHasCoordinates(IAtomContainer ac) { for (int i = 0; i < ac.Atoms.Count; i++) { @@ -594,7 +588,7 @@ private bool CheckAllRingAtomsHasCoordinates(IAtomContainer ac) /// Sets the atomsToPlace attribute of the ModelBuilder3D object. /// /// The new atomsToPlace value - private void SetAtomsToPlace(IAtomContainer ac) + private static void SetAtomsToPlace(IAtomContainer ac) { for (int i = 0; i < ac.Atoms.Count; i++) { @@ -605,7 +599,7 @@ private void SetAtomsToPlace(IAtomContainer ac) /// /// Sets the atomsToUnplaced attribute of the ModelBuilder3D object. /// - private void SetAtomsToUnplaced(IAtomContainer molecule) + private static void SetAtomsToUnplaced(IAtomContainer molecule) { for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -616,7 +610,7 @@ private void SetAtomsToUnplaced(IAtomContainer molecule) /// /// Sets the atomsToUnVisited attribute of the ModelBuilder3D object. /// - private void SetAtomsToUnVisited(IAtomContainer molecule) + private static void SetAtomsToUnVisited(IAtomContainer molecule) { for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -630,7 +624,7 @@ private void SetAtomsToUnVisited(IAtomContainer molecule) /// The new templateHandler value private void SetTemplateHandler(TemplateHandler3D templateHandler) { - this.templateHandler = templateHandler ?? throw new ArgumentNullException("The given template handler is null!"); + this.templateHandler = templateHandler ?? throw new ArgumentNullException(nameof(templateHandler), "The given template handler is null!"); } /// diff --git a/NCDK/Modelings/Builder3D/TemplateExtractor.cs b/NCDK/Modelings/Builder3D/TemplateExtractor.cs index 4b1837c1..3bb834ca 100644 --- a/NCDK/Modelings/Builder3D/TemplateExtractor.cs +++ b/NCDK/Modelings/Builder3D/TemplateExtractor.cs @@ -31,6 +31,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.Modelings.Builder3D @@ -41,15 +42,11 @@ namespace NCDK.Modelings.Builder3D // @author Christian Hoppe // @cdk.module builder3dtools // @cdk.githash - public class TemplateExtractor + public static class TemplateExtractor { - const string usage = "Usage: TemplateExtractor SDFinfile outfile anyAtom=true/false anyBondAnyAtom=true/false"; - private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - public TemplateExtractor() { } - - public void CleanDataSet(string dataFile) + public static void CleanDataSet(string dataFile) { var som = builder.NewAtomContainerSet(); try @@ -80,13 +77,13 @@ public void CleanDataSet(string dataFile) } catch (Exception exc) { - Console.Out.WriteLine("Could not read Molecules from file " + dataFile + " due to: " + exc.Message); + Console.Out.WriteLine($"Could not read Molecules from file {dataFile} due to: {exc.Message}"); } - Console.Out.WriteLine(som.Count + " Templates are read in"); + Console.Out.WriteLine($"{som.Count} Templates are read in"); WriteChemModel(som, dataFile, "_CLEAN"); } - public void ReadNCISdfFileAsTemplate(string dataFile) + public static void ReadNCISdfFileAsTemplate(string dataFile) { var som = builder.NewAtomContainerSet(); try @@ -105,12 +102,12 @@ public void ReadNCISdfFileAsTemplate(string dataFile) } catch (Exception exc) { - Console.Out.WriteLine("Could not read Molecules from file " + dataFile + " due to: " + exc.Message); + Console.Out.WriteLine($"Could not read Molecules from file {dataFile} due to: {exc.Message}"); } Console.Out.WriteLine(som.Count + " Templates are read in"); } - public void PartitionRingsFromComplexRing(string dataFile) + public static void PartitionRingsFromComplexRing(string dataFile) { var som = builder.NewAtomContainerSet(); try @@ -123,7 +120,7 @@ public void PartitionRingsFromComplexRing(string dataFile) Console.Out.WriteLine("READY"); foreach (var m in imdl) { - Console.Out.WriteLine("Atoms:" + m.Atoms.Count); + Console.Out.WriteLine($"Atoms: {m.Atoms.Count}"); IRingSet ringSetM = Cycles.FindSSSR(m).ToRingSet(); // som.Add(m); for (int i = 0; i < ringSetM.Count; i++) @@ -135,17 +132,16 @@ public void PartitionRingsFromComplexRing(string dataFile) } catch (Exception exc) { - Console.Out.WriteLine("Could not read Molecules from file " + dataFile + " due to: " + exc.Message); + Console.Out.WriteLine($"Could not read Molecules from file {dataFile} due to: {exc.Message}"); } - Console.Out.WriteLine(som.Count + " Templates are read in"); + Console.Out.WriteLine($"{som.Count} Templates are read in"); WriteChemModel(som, dataFile, "_VERSUCH"); } - public void ExtractUniqueRingSystemsFromFile(string dataFile) + public static void ExtractUniqueRingSystemsFromFile(string dataFile) { Console.Out.WriteLine("****** EXTRACT UNIQUE RING SYSTEMS ******"); - Console.Out.WriteLine("From file:" + dataFile); - // RingPartitioner ringPartitioner=new RingPartitioner(); + Console.Out.WriteLine($"From file: {dataFile}"); Dictionary hashRingSystems = new Dictionary(); SmilesGenerator smilesGenerator = new SmilesGenerator(); @@ -159,7 +155,6 @@ public void ExtractUniqueRingSystemsFromFile(string dataFile) string molfile = dataFile + "_UniqueRings"; - // FileOutputStream fout=null; try { using (var fout = new FileStream(molfile, FileMode.Create)) @@ -177,9 +172,6 @@ public void ExtractUniqueRingSystemsFromFile(string dataFile) { counterMolecules = counterMolecules + 1; - // try{ HueckelAromaticityDetector.DetectAromaticity(m); - // }Catch(Exception ex1){ Console.Out.WriteLine("Could not find - // aromaticity due to:"+ex1); } IRingSet ringSetM = Cycles.FindSSSR(m).ToRingSet(); if (counterMolecules % 1000 == 0) @@ -217,29 +209,14 @@ public void ExtractUniqueRingSystemsFromFile(string dataFile) return; } - // Console.Out.WriteLine("OrgKey:"+key+" For - // Molecule:"+counter); if (hashRingSystems.ContainsKey(key)) { - // Console.Out.WriteLine("HAS KEY:ADD"); - // Vector tmp=(Vector)HashRingSystems[key]; - // tmp.Add((AtomContainer)ringSet.GetRingSetInAtomContainer()); - // HashRingSystems.Put(key,tmp); - // int - // tmp=((int)HashRingSystems[key]).Value; - // tmp=tmp+1; - // HashRingSystems.Put(key,new int(tmp)); } else { - counterUniqueRings = counterUniqueRings + 1; - // Vector rings2=new Vector(); - // rings2.Add((AtomContainer)RingSetManipulator.GetAllInOneContainer(ringSet)); - hashRingSystems[key] = "1"; + counterUniqueRings = counterUniqueRings + 1;hashRingSystems[key] = "1"; try { - // mdlw.Write(new Molecule - // ((AtomContainer)RingSetManipulator.GetAllInOneContainer(ringSet))); mdlw.Write(builder.NewAtomContainer(ac)); } catch (Exception emdl) @@ -255,39 +232,25 @@ public void ExtractUniqueRingSystemsFromFile(string dataFile) } catch (Exception exc) { - Console.Out.WriteLine("Could not read Molecules from file " + dataFile + " due to: " + exc.Message); + Console.Out.WriteLine($"Could not read Molecules from file {dataFile} due to: {exc.Message}"); } } } catch (Exception ex2) { - Console.Out.WriteLine("IOError:cannot write file due to:" + ex2.ToString()); + Console.Out.WriteLine($"IOError:cannot write file due to: {ex2.ToString()}"); } - // Console.Out.WriteLine("READY Molecules:"+counterMolecules); Console.Out.WriteLine($"READY Molecules:{counterMolecules} RingSystems:{counterRings} UniqueRingsSystem:{counterUniqueRings}"); Console.Out.WriteLine($"HashtableKeys:{hashRingSystems.Count}"); - - // int c=0; Set keyset = HashRingSystems.Keys; Iterator - // it=keyset.Iterator(); IAtomContainerSet som=new AtomContainerSet(); - // SmilesParser smileParser=new SmilesParser(); string ringSmile=""; - // while (it.HasNext()) { key=(string)it.Next(); - // ringSmile=(string)HashRingSystems[key]; - // Console.Out.WriteLine("HashtableSmile:"+ringSmile+" key:"+key); try{ - // som.Add(smileParser.ParseSmiles(ringSmile)); }catch - // (Exception ex5){ Console.Out.WriteLine("Error in som.addmolecule due - // to:"+ex5); } } - - // WriteChemModel(som,dataFile,"_TESTTESTTESTTESTTEST"); } - public void WriteChemModel(IChemObjectSet som, string file, string endFix) + public static void WriteChemModel(IChemObjectSet som, string file, string endFix) { Console.Out.WriteLine($"WRITE Molecules:{som.Count}"); string molfile = file + endFix; try { - using (var fout = new FileStream(molfile, FileMode.Create)) - using (var mdlw = new MDLV2000Writer(fout)) + using (var mdlw = new MDLV2000Writer(new FileStream(molfile, FileMode.Create))) { mdlw.Write(som); } @@ -300,29 +263,20 @@ public void WriteChemModel(IChemObjectSet som, string file, stri } } - public void MakeCanonicalSmileFromRingSystems(string dataFileIn, string dataFileOut) + public static void MakeCanonicalSmileFromRingSystems(string dataFileIn, string dataFileOut) { Console.Out.WriteLine("Start make SMILES..."); - // QueryAtomContainer query=null; - List data = new List(); - SmilesGenerator smiles = new SmilesGenerator(); + var data = new List(); + var smiles = new SmilesGenerator(); try { Console.Out.WriteLine("Start..."); - using (var fin = new StreamReader(dataFileIn)) - using (var imdl = new EnumerableSDFReader(fin, builder)) + using (var imdl = new EnumerableSDFReader(new StreamReader(dataFileIn), builder)) { Console.Out.WriteLine("Read File in.."); foreach (var m in imdl) { - // try{ HueckelAromaticityDetector.DetectAromaticity(m); - // }Catch(Exception ex1){ Console.Out.WriteLine("Could not find - // aromaticity due to:"+ex1); } - - // query=QueryAtomContainerCreator.CreateAnyAtomContainer(m,true); - // Console.Out.WriteLine("string:"+smiles.CreateSMILES(new - // Molecule(m))); try { data.Add((string)smiles.Create(builder.NewAtomContainer(m))); @@ -348,7 +302,6 @@ public void MakeCanonicalSmileFromRingSystems(string dataFileIn, string dataFile { for (int i = 0; i < data.Count; i++) { - // Console.Out.WriteLine("write:"+(string)data[i]); try { fout.Write(((string)data[i])); @@ -358,23 +311,22 @@ public void MakeCanonicalSmileFromRingSystems(string dataFileIn, string dataFile { } } - Console.Out.WriteLine("number of smiles:" + data.Count); + Console.Out.WriteLine($"number of smiles: {data.Count}"); } } catch (Exception exc3) { - Console.Out.WriteLine("Could not write smile in file " + dataFileOut + " due to: " + exc3.Message); + Console.Out.WriteLine($"Could not write smile in file {dataFileOut} due to: {exc3.Message}"); } Console.Out.WriteLine("...ready"); } - public IList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtomAnyBond, IDictionary timings, TextReader fin, int limit) + public static IReadOnlyList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtomAnyBond, IDictionary timings, TextReader fin, int limit) { - HybridizationFingerprinter fingerPrinter = new HybridizationFingerprinter(HybridizationFingerprinter.DefaultSize, HybridizationFingerprinter.DefaultSearchDepth); + var fingerPrinter = new HybridizationFingerprinter(HybridizationFingerprinter.DefaultSize, HybridizationFingerprinter.DefaultSearchDepth); fingerPrinter.SetHashPseudoAtoms(true); - //QueryAtomContainer query=null; IAtomContainer query = null; - List data = new List(); + var data = new List(); try { Trace.TraceInformation("Read data file in ..."); @@ -384,7 +336,7 @@ public IList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtom int moleculeCounter = 0; int fingerprintCounter = 0; - Trace.TraceInformation("Generated Fingerprints: " + fingerprintCounter + " "); + Trace.TraceInformation($"Generated Fingerprints: {fingerprintCounter} "); foreach (var m in imdl) { if (!(moleculeCounter < limit || limit == -1)) @@ -400,7 +352,7 @@ public IList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtom } try { - long time = -DateTime.Now.Ticks / 10000; + var time = -DateTime.Now.Ticks / 10000; if (anyAtom || anyAtomAnyBond) { data.Add(fingerPrinter.GetBitFingerprint(query)); @@ -413,7 +365,7 @@ public IList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtom } time += (DateTime.Now.Ticks / 10000); // store the time - string bin = ((int)Math.Floor(time / 10.0)).ToString(); + var bin = ((int)Math.Floor(time / 10.0)).ToString(NumberFormatInfo.InvariantInfo); if (timings.ContainsKey(bin)) { timings[bin] = (timings[bin]) + 1; @@ -430,8 +382,8 @@ public IList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtom // OK, just adds a fingerprint with all ones, so that any // structure will match this template, and leave it up // to substructure match to figure things out - IBitFingerprint allOnesFingerprint = new BitSetFingerprint(fingerPrinter.Count); - for (int i = 0; i < fingerPrinter.Count; i++) + var allOnesFingerprint = new BitSetFingerprint(fingerPrinter.Length); + for (int i = 0; i < fingerPrinter.Length; i++) { allOnesFingerprint.Set(i); } @@ -459,11 +411,11 @@ public IList MakeFingerprintsFromSdf(bool anyAtom, bool anyAtom return data; } - public void MakeFingerprintFromRingSystems(string dataFileIn, string dataFileOut, bool anyAtom, bool anyAtomAnyBond) + public static void MakeFingerprintFromRingSystems(string dataFileIn, string dataFileOut, bool anyAtom, bool anyAtomAnyBond) { - IDictionary timings = new Dictionary(); + var timings = new Dictionary(); - Console.Out.WriteLine("Start make fingerprint from file:" + dataFileIn + " ..."); + Console.Out.WriteLine($"Start make fingerprint from file: {dataFileIn} ..."); using (var fin = new StreamReader(dataFileIn)) { var data = MakeFingerprintsFromSdf(anyAtom, anyAtomAnyBond, timings, fin, -1); @@ -494,14 +446,14 @@ public void MakeFingerprintFromRingSystems(string dataFileIn, string dataFileOut } } - public IAtomContainer RemoveLoopBonds(IAtomContainer molecule, int position) + public static IAtomContainer RemoveLoopBonds(IAtomContainer molecule, int position) { for (int i = 0; i < molecule.Bonds.Count; i++) { - IBond bond = molecule.Bonds[i]; + var bond = molecule.Bonds[i]; if (bond.Begin== bond.End) { - Console.Out.WriteLine("Loop found! Molecule:" + position); + Console.Out.WriteLine($"Loop found! Molecule: {position}"); molecule.Bonds.Remove(bond); } } @@ -509,19 +461,17 @@ public IAtomContainer RemoveLoopBonds(IAtomContainer molecule, int position) return molecule; } - public IAtomContainer CreateAnyAtomAtomContainer(IAtomContainer atomContainer) + public static IAtomContainer CreateAnyAtomAtomContainer(IAtomContainer atomContainer) { - IAtomContainer query = (IAtomContainer)atomContainer.Clone(); - // Console.Out.WriteLine("createAnyAtomAtomContainer"); + var query = (IAtomContainer)atomContainer.Clone(); for (int i = 0; i < query.Atoms.Count; i++) { - // Console.Out.Write(" "+i); query.Atoms[i].Symbol = "C"; } return query; } - public IAtomContainer ResetFlags(IAtomContainer ac) + public static IAtomContainer ResetFlags(IAtomContainer ac) { for (int f = 0; f < ac.Atoms.Count; f++) { @@ -533,23 +483,5 @@ public IAtomContainer ResetFlags(IAtomContainer ac) } return ac; } - - public static void Main(string[] args) - { - if (args.Length < 4) - { - Console.Out.WriteLine(usage); - } - try - { - new TemplateExtractor().MakeFingerprintFromRingSystems(args[0], args[1], bool.Parse(args[2]), bool.Parse(args[3])); - } - catch (Exception e) - { - Console.Out.WriteLine(usage); - // TODO Auto-generated catch block - Console.Out.WriteLine(e.StackTrace); - } - } } } diff --git a/NCDK/Modelings/Builder3D/TemplateHandler3D.cs b/NCDK/Modelings/Builder3D/TemplateHandler3D.cs index b29062fb..bd4405c6 100644 --- a/NCDK/Modelings/Builder3D/TemplateHandler3D.cs +++ b/NCDK/Modelings/Builder3D/TemplateHandler3D.cs @@ -31,6 +31,7 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; @@ -49,12 +50,11 @@ namespace NCDK.Modelings.Builder3D public class TemplateHandler3D { private static readonly IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - public const string TEMPLATE_PATH = "Data.ringTemplateStructures.sdf.gz"; + private const string TemplatePath = "Data.ringTemplateStructures.sdf.gz"; private readonly List templates = new List(); private readonly List queries = new List(); private readonly List patterns = new List(); - private readonly UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester(); private TemplateHandler3D() { @@ -82,7 +82,7 @@ private void LoadTemplates() { try { - using (var gin = GetType().Assembly.GetManifestResourceStream(GetType(), TEMPLATE_PATH)) + using (var gin = GetType().Assembly.GetManifestResourceStream(GetType(), TemplatePath)) using (var ins = new GZipStream(gin, CompressionMode.Decompress)) using (EnumerableSDFReader sdfr = new EnumerableSDFReader(ins, builder)) { @@ -102,7 +102,7 @@ public static BitArray GetBitSetFromFile(IEnumerable st) { BitArray bitSet = new BitArray(1024); foreach (var s in st) - bitSet.Set(int.Parse(s), true); + bitSet.Set(int.Parse(s, NumberFormatInfo.InvariantInfo), true); return bitSet; } @@ -111,24 +111,24 @@ public static BitArray GetBitSetFromFile(IEnumerable st) /// /// RingSystems of a molecule /// The largestRingSet - public IRingSet GetLargestRingSet(List ringSystems) + public static IRingSet GetLargestRingSet(IEnumerable ringSystems) { IRingSet largestRingSet = null; int atomNumber = 0; IAtomContainer container = null; - for (int i = 0; i < ringSystems.Count; i++) + foreach (var ringSystem in ringSystems) { - container = GetAllInOneContainer(ringSystems[i]); + container = GetAllInOneContainer(ringSystem); if (atomNumber < container.Atoms.Count) { atomNumber = container.Atoms.Count; - largestRingSet = ringSystems[i]; + largestRingSet = ringSystem; } } return largestRingSet; } - private IAtomContainer GetAllInOneContainer(IRingSet ringSet) + private static IAtomContainer GetAllInOneContainer(IRingSet ringSet) { IAtomContainer resultContainer = ringSet.Builder.NewAtomContainer(); var containers = RingSetManipulator.GetAllAtomContainers(ringSet); @@ -137,8 +137,7 @@ private IAtomContainer GetAllInOneContainer(IRingSet ringSet) return resultContainer; } - private bool IsExactMatch(IAtomContainer query, - IDictionary mapping) + private static bool IsExactMatch(IAtomContainer query, IReadOnlyDictionary mapping) { foreach (IAtom src in query.Atoms) { @@ -168,9 +167,9 @@ public void MapTemplates(IAtomContainer mol, int numberOfRingAtoms) LoadTemplates(); IAtomContainer best = null; - IDictionary bestMap = null; + Dictionary bestMap = null; IAtomContainer secondBest = null; - IDictionary secondBestMap = null; + Dictionary secondBestMap = null; for (int i = 0; i < templates.Count; i++) { @@ -183,7 +182,7 @@ public void MapTemplates(IAtomContainer mol, int numberOfRingAtoms) } Mappings mappings = patterns[i].MatchAll(mol); - foreach (IDictionary map in mappings.ToAtomBondMap()) + foreach (var map in mappings.ToAtomBondMap()) { if (IsExactMatch(query, map)) { @@ -193,12 +192,16 @@ public void MapTemplates(IAtomContainer mol, int numberOfRingAtoms) else if (query.Bonds.Count == mol.Bonds.Count) { best = query; - bestMap = new Dictionary(map); + bestMap = new Dictionary(); + foreach (var e in map) + bestMap.Add(e.Key, e.Value); } else { secondBest = query; - secondBestMap = new Dictionary(map); + secondBestMap = new Dictionary(); + foreach (var e in map) + secondBestMap.Add(e.Key, e.Value); } } } @@ -217,8 +220,7 @@ public void MapTemplates(IAtomContainer mol, int numberOfRingAtoms) } } - private void AssignCoords(IAtomContainer template, - IDictionary map) + private static void AssignCoords(IAtomContainer template, IReadOnlyDictionary map) { foreach (IAtom src in template.Atoms) { diff --git a/NCDK/NCDK.csproj b/NCDK/NCDK.csproj index e87931d7..fdd515e5 100644 --- a/NCDK/NCDK.csproj +++ b/NCDK/NCDK.csproj @@ -1,19 +1,19 @@ - net461;netstandard2.0 + net461 NCDK true ncdk.snk Kazuya Ujihara Copyright © 2016-2018 Kazuya Ujihara - 1.3.1.0 - 1.3.1.0 + 1.4.0.0 + 1.4.0.0 NCDK: Chemistry Development Kit for .NET Framework https://github.com/kazuyaujihara/NCDK https://github.com/kazuyaujihara/NCDK/blob/master/LICENSE NCDK is C# implementation of The Chemistry Development Kit (CDK), which is an open-source library of algorithms for structural chemo- and bioinformatics. - 1.3.1-alpha + 1.4.0-alpha Kazuya Ujihara https://github.com/kazuyaujihara/NCDK git @@ -36,12 +36,17 @@ bin\Release\net461\NCDK.xml + NCDK.ruleset bin\Release\netstandard2.0\NCDK.xml + + NCDK.ruleset + + @@ -72,12 +77,6 @@ - - - - - - @@ -151,12 +150,12 @@ - - - - - - + + + + + + @@ -198,16 +197,17 @@ + + + + + - - TextTemplatingFileGenerator - Configuration.tt.cs - True True @@ -217,9 +217,18 @@ TextTemplatingFileGenerator cheminf.tokens - + + True + True + IncludeExamples.tt + + + TextTemplatingFileGenerator + IncludeExamples.xml + + TextTemplatingFileGenerator - EmptyCollections.tt.cs + Configuration.tt.cs TextTemplatingFileGenerator @@ -237,15 +246,6 @@ TextTemplatingFileGenerator IHasProperties.tt.cs - - TextTemplatingFileGenerator - IncludeExamples.xml - - - True - True - IncludeExamples.tt - TextTemplatingFileGenerator CMLElementBodies.tt.cs @@ -449,22 +449,17 @@ PreserveNewest - + - + True True Configuration.tt - - True - True - EmptyCollections.tt - True True diff --git a/NCDK/NCDK.ruleset b/NCDK/NCDK.ruleset new file mode 100644 index 00000000..78a4fced --- /dev/null +++ b/NCDK/NCDK.ruleset @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NCDK/NCDKUtil.cs b/NCDK/NCDKUtil.cs index 5072bd52..2edb51be 100644 --- a/NCDK/NCDKUtil.cs +++ b/NCDK/NCDKUtil.cs @@ -65,7 +65,7 @@ public static void SetBonds(this IAtomContainer mol, IEnumerable bonds) /// Set the stereo elements - this will replace the existing instance with a new instance. /// /// - public static void SetStereoElements(this IAtomContainer mol, IEnumerable> elements) + public static void SetStereoElements(this IAtomContainer mol, IEnumerable> elements) { mol.StereoElements.Clear(); foreach (var se in elements) diff --git a/NCDK/NoSuchAtomException.cs b/NCDK/NoSuchAtomException.cs index 9d784455..4403fe4d 100644 --- a/NCDK/NoSuchAtomException.cs +++ b/NCDK/NoSuchAtomException.cs @@ -32,6 +32,10 @@ namespace NCDK public class NoSuchAtomException : CDKException { + public NoSuchAtomException() + { + } + /// /// Constructs a new with the given message. /// @@ -40,5 +44,9 @@ public NoSuchAtomException(string message) : base(message) { } + + public NoSuchAtomException(string message, System.Exception innerException) : base(message, innerException) + { + } } } diff --git a/NCDK/NoSuchAtomTypeException.cs b/NCDK/NoSuchAtomTypeException.cs index 456c5b3f..ba63af2b 100644 --- a/NCDK/NoSuchAtomTypeException.cs +++ b/NCDK/NoSuchAtomTypeException.cs @@ -31,9 +31,17 @@ namespace NCDK public class NoSuchAtomTypeException : CDKException { + public NoSuchAtomTypeException() + { + } + public NoSuchAtomTypeException(string message) : base(message) { } + + public NoSuchAtomTypeException(string message, System.Exception innerException) : base(message, innerException) + { + } } } diff --git a/NCDK/Normalizers/Normalizer.cs b/NCDK/Normalizers/Normalizer.cs index 7592f86c..3377c2fa 100644 --- a/NCDK/Normalizers/Normalizer.cs +++ b/NCDK/Normalizers/Normalizer.cs @@ -40,7 +40,7 @@ namespace NCDK.Normalizers // @cdk.module smiles // @cdk.githash [Obsolete("The functionality provided by with class is better suited to SMIRKS")] - public class Normalizer + public static class Normalizer { /// /// The method takes an XML files like the following: @@ -97,11 +97,11 @@ public static bool Normalize(IAtomContainer ac, XDocument doc) } } IAtomContainer replaceStructure = sp.ParseSmiles(replacestring); - IList l = null; + IReadOnlyList l = null; UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester(); while ((l = universalIsomorphismTester.GetSubgraphMap(ac, replaceStructure)) != null) { - IList l2 = UniversalIsomorphismTester.MakeAtomsMapOfBondsMap(l, ac, replaceStructure); + var l2 = UniversalIsomorphismTester.MakeAtomsMapOfBondsMap(l, ac, replaceStructure); foreach (var rmap in l) { IBond acbond = ac.Bonds[rmap.Id1]; diff --git a/NCDK/Normalizers/SMSDNormalizer.cs b/NCDK/Normalizers/SMSDNormalizer.cs index 2c97ca43..ee5c078f 100644 --- a/NCDK/Normalizers/SMSDNormalizer.cs +++ b/NCDK/Normalizers/SMSDNormalizer.cs @@ -34,7 +34,7 @@ namespace NCDK.Normalizers // @cdk.githash // @author Syed Asad Rahman [Obsolete("This class is part of SMSD and either duplicates functionality elsewhere in the CDK or provides public access to internal implementation details. SMSD has been deprecated from the CDK and a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] - public class SMSDNormalizer + public static class SMSDNormalizer { /// /// Returns deep copy of the molecule diff --git a/NCDK/Numerics/Plane.cs b/NCDK/Numerics/Plane.cs index 7d6d30c4..d83df41f 100644 --- a/NCDK/Numerics/Plane.cs +++ b/NCDK/Numerics/Plane.cs @@ -163,8 +163,7 @@ public static Plane Normalize(Plane value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Matrix4x4 matrix) { - Matrix4x4 m; - Matrix4x4.Invert(matrix, out m); + Matrix4x4.Invert(matrix, out Matrix4x4 m); double x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z, w = plane.D; diff --git a/NCDK/Numerics/Vector.tt b/NCDK/Numerics/Vector.tt index 43718bde..aae80126 100644 --- a/NCDK/Numerics/Vector.tt +++ b/NCDK/Numerics/Vector.tt @@ -8,6 +8,7 @@ <#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #> #pragma warning disable 3021 +#pragma warning disable CA1000 // Do not declare static members on generic types using System; using System.Diagnostics.Contracts; diff --git a/NCDK/Numerics/Vector.tt.cs b/NCDK/Numerics/Vector.tt.cs index 7fdae1fa..7c75da49 100644 --- a/NCDK/Numerics/Vector.tt.cs +++ b/NCDK/Numerics/Vector.tt.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. #pragma warning disable 3021 +#pragma warning disable CA1000 // Do not declare static members on generic types using System; using System.Diagnostics.Contracts; diff --git a/NCDK/ObservableChemObjectCollection.cs b/NCDK/ObservableChemObjectCollection.cs index 799e8641..2d112d73 100644 --- a/NCDK/ObservableChemObjectCollection.cs +++ b/NCDK/ObservableChemObjectCollection.cs @@ -8,9 +8,8 @@ namespace NCDK { - [Serializable] internal class ObservableChemObjectCollection - : IList + : IList, IReadOnlyList where T : INotify { internal List list; @@ -45,7 +44,7 @@ public virtual T this[int index] { if (!AllowDuplicate) if (list.Contains(value)) - throw new ArgumentException(); + throw new InvalidOperationException(); if (Listener != null) { list[index]?.Listeners?.Remove(Listener); diff --git a/NCDK/Pharmacophore/PharmacophoreAtom.cs b/NCDK/Pharmacophore/PharmacophoreAtom.cs index 8bcf7512..ec239e2c 100644 --- a/NCDK/Pharmacophore/PharmacophoreAtom.cs +++ b/NCDK/Pharmacophore/PharmacophoreAtom.cs @@ -135,7 +135,7 @@ public override bool Equals(object o) if (!(o is PharmacophoreAtom)) return false; PharmacophoreAtom that = (PharmacophoreAtom)o; - return Smarts.Equals(that.Smarts) && symbol.Equals(that.Symbol) + return Smarts.Equals(that.Smarts, StringComparison.Ordinal) && symbol.Equals(that.Symbol, StringComparison.Ordinal) && Point3D.Equals(that.Point3D) && Arrays.AreEqual(this.matchingAtoms, that.matchingAtoms); } } diff --git a/NCDK/Pharmacophore/PharmacophoreBond.cs b/NCDK/Pharmacophore/PharmacophoreBond.cs index 6fbce45f..bc56793f 100644 --- a/NCDK/Pharmacophore/PharmacophoreBond.cs +++ b/NCDK/Pharmacophore/PharmacophoreBond.cs @@ -18,7 +18,7 @@ */ using NCDK.Numerics; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Pharmacophore { diff --git a/NCDK/Pharmacophore/PharmacophoreMatcher.cs b/NCDK/Pharmacophore/PharmacophoreMatcher.cs index a5ecb046..08448738 100644 --- a/NCDK/Pharmacophore/PharmacophoreMatcher.cs +++ b/NCDK/Pharmacophore/PharmacophoreMatcher.cs @@ -29,6 +29,7 @@ using System.Diagnostics; using System.Linq; using NCDK.Common.Base; +using System; namespace NCDK.Pharmacophore { @@ -99,7 +100,7 @@ public class PharmacophoreMatcher private Mappings mappings = null; - private readonly Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.Or(Cycles.AllFinder, Cycles.RelevantFinder)); + private readonly Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.Or(Cycles.AllSimpleFinder, Cycles.RelevantFinder)); /// /// An empty constructor. @@ -153,11 +154,12 @@ public bool Matches(IAtomContainer atomContainer) /// does not have 3D coordinates public bool Matches(IAtomContainer atomContainer, bool initializeTarget) { - if (!GeometryUtil.Has3DCoordinates(atomContainer)) throw new CDKException("Molecule must have 3D coordinates"); - if (pharmacophoreQuery == null) throw new CDKException("Must set the query pharmacophore before matching"); + if (!GeometryUtil.Has3DCoordinates(atomContainer)) + throw new CDKException("Molecule must have 3D coordinates"); + if (pharmacophoreQuery == null) + throw new CDKException("Must set the query pharmacophore before matching"); if (!CheckQuery(pharmacophoreQuery)) - throw new CDKException( - "A problem in the query. Make sure all pharmacophore groups of the same symbol have the same same SMARTS"); + throw new CDKException("A problem in the query. Make sure all pharmacophore groups of the same symbol have the same same SMARTS"); string title = atomContainer.Title; if (initializeTarget) @@ -169,11 +171,11 @@ public bool Matches(IAtomContainer atomContainer, bool initializeTarget) // sure we get the latest set of effective coordinates foreach (var iAtom in pharmacophoreMolecule.Atoms) { - PharmacophoreAtom patom = PharmacophoreAtom.Get(iAtom); + var patom = PharmacophoreAtom.Get(iAtom); var tmpList = new List(); foreach (var idx in patom.GetMatchingAtoms()) tmpList.Add(idx); - Vector3 coords = GetEffectiveCoordinates(atomContainer, tmpList); + var coords = GetEffectiveCoordinates(atomContainer, tmpList); patom.Point3D = coords; } } @@ -203,12 +205,13 @@ public bool Matches(IAtomContainer atomContainer, bool initializeTarget) /// a List of a List of pharmacophore constraints in the target molecule that match the query /// /// - public IList> GetMatchingPharmacophoreBonds() + public IReadOnlyList> GetMatchingPharmacophoreBonds() { - if (mappings == null) return null; + if (mappings == null) + return null; // XXX: re-subsearching the query - var bonds = new List>(); + var bonds = new List>(); foreach (var map in mappings.ToBondMap()) { bonds.Add(new List(map.Values)); @@ -227,11 +230,12 @@ public IList> GetMatchingPharmacophoreBonds() /// . The value is the corresponding query bond. /// /// A List of HashMaps, identifying the query constraint corresponding to a matched constraint in the target molecule. - public List> GetTargetQueryBondMappings() + public IReadOnlyList> GetTargetQueryBondMappings() { - if (mappings == null) return null; + if (mappings == null) + return null; - var bondMap = new List>(); + var bondMap = new List>(); // query -> target so need to inverse the mapping // XXX: re-subsearching the query @@ -257,9 +261,10 @@ public List> GetTargetQueryBondMappings() /// /// a List of a List of pharmacophore groups in the target molecule that match the query /// - public IList> GetMatchingPharmacophoreAtoms() + public IReadOnlyList> GetMatchingPharmacophoreAtoms() { - if (pharmacophoreMolecule == null || mappings == null) return null; + if (pharmacophoreMolecule == null || mappings == null) + return null; return GetPCoreAtoms(mappings); } @@ -279,15 +284,16 @@ public IList> GetMatchingPharmacophoreAtoms() /// /// a List of a List of pharmacophore groups in the target molecule that match the query /// - public IList> GetUniqueMatchingPharmacophoreAtoms() + public IReadOnlyList> GetUniqueMatchingPharmacophoreAtoms() { - if (pharmacophoreMolecule == null || mappings == null) return null; + if (pharmacophoreMolecule == null || mappings == null) + return null; return GetPCoreAtoms(mappings.GetUniqueAtoms()); } - private IList> GetPCoreAtoms(Mappings mappings) + private static List> GetPCoreAtoms(Mappings mappings) { - var atoms = new List>(); + var atoms = new List>(); // XXX: re-subsearching the query foreach (var map in mappings.ToAtomMap()) { @@ -410,9 +416,12 @@ private IAtomContainer GetPharmacophoreMolecule(IAtomContainer input) foreach (var tatom in pharmacophoreMolecule.Atoms) { - if (tatom.Symbol.Equals(startQAtom.Symbol)) startl.Add(tatom); - if (tatom.Symbol.Equals(middleQAtom.Symbol)) middlel.Add(tatom); - if (tatom.Symbol.Equals(endQAtom.Symbol)) endl.Add(tatom); + if (tatom.Symbol.Equals(startQAtom.Symbol, StringComparison.Ordinal)) + startl.Add(tatom); + if (tatom.Symbol.Equals(middleQAtom.Symbol, StringComparison.Ordinal)) + middlel.Add(tatom); + if (tatom.Symbol.Equals(endQAtom.Symbol, StringComparison.Ordinal)) + endl.Add(tatom); } // now we form the relevant angles, but we will @@ -463,7 +472,7 @@ private IAtomContainer GetPharmacophoreMolecule(IAtomContainer input) return pharmacophoreMolecule; } - private PharmacophoreAtom NewPCoreAtom(IAtomContainer input, PharmacophoreQueryAtom qatom, string smarts, int[] mapping) + private static PharmacophoreAtom NewPCoreAtom(IAtomContainer input, PharmacophoreQueryAtom qatom, string smarts, int[] mapping) { Vector3 coords = GetEffectiveCoordinates(input, mapping); PharmacophoreAtom patom = new PharmacophoreAtom(smarts, qatom.Symbol, coords); @@ -478,7 +487,7 @@ private void PrepareInput(IAtomContainer input) arom.Apply(input); } - private bool HasDistanceConstraints(IQueryAtomContainer query) + private static bool HasDistanceConstraints(IQueryAtomContainer query) { foreach (var bond in query.Bonds) { @@ -487,7 +496,7 @@ private bool HasDistanceConstraints(IQueryAtomContainer query) return false; } - private bool HasAngleConstraints(IQueryAtomContainer query) + private static bool HasAngleConstraints(IQueryAtomContainer query) { foreach (var bond in query.Bonds) { @@ -496,7 +505,7 @@ private bool HasAngleConstraints(IQueryAtomContainer query) return false; } - private int[] IntIndices(List atomIndices) + private static int[] IntIndices(List atomIndices) { int[] ret = new int[atomIndices.Count]; for (int i = 0; i < atomIndices.Count; i++) @@ -504,7 +513,7 @@ private int[] IntIndices(List atomIndices) return ret; } - private Vector3 GetEffectiveCoordinates(IAtomContainer atomContainer, List atomIndices) + private static Vector3 GetEffectiveCoordinates(IAtomContainer atomContainer, List atomIndices) { Vector3 ret = Vector3.Zero; foreach (var atomIndice in atomIndices) @@ -521,7 +530,7 @@ private Vector3 GetEffectiveCoordinates(IAtomContainer atomContainer, List return ret; } - private Vector3 GetEffectiveCoordinates(IAtomContainer atomContainer, int[] atomIndices) + private static Vector3 GetEffectiveCoordinates(IAtomContainer atomContainer, int[] atomIndices) { Vector3 ret = Vector3.Zero; foreach (var i in atomIndices) @@ -537,7 +546,7 @@ private Vector3 GetEffectiveCoordinates(IAtomContainer atomContainer, int[] atom return ret; } - private bool CheckQuery(IQueryAtomContainer query) + private static bool CheckQuery(IQueryAtomContainer query) { if (!(query is PharmacophoreQuery)) return false; Dictionary map = new Dictionary(); @@ -554,7 +563,8 @@ private bool CheckQuery(IQueryAtomContainer query) map[label] = smarts; else { - if (!map[label].Equals(smarts)) return false; + if (!map[label].Equals(smarts, StringComparison.Ordinal)) + return false; } } return true; diff --git a/NCDK/Pharmacophore/PharmacophoreQuery.cs b/NCDK/Pharmacophore/PharmacophoreQuery.cs index 41e0be8d..9dffb389 100644 --- a/NCDK/Pharmacophore/PharmacophoreQuery.cs +++ b/NCDK/Pharmacophore/PharmacophoreQuery.cs @@ -18,6 +18,7 @@ */ using NCDK.Isomorphisms.Matchers; +using NCDK.Silent; using System.Collections.Generic; using System.Linq; using System.Text; @@ -39,10 +40,10 @@ namespace NCDK.Pharmacophore // @cdk.githash public class PharmacophoreQuery : QueryAtomContainer { - private List exclusionVolumes; + private readonly List exclusionVolumes; public PharmacophoreQuery() - : base(Default.ChemObjectBuilder.Instance) + : base(ChemObjectBuilder.Instance) { // builder should be injected but this is difficult as this class is create in static methods exclusionVolumes = new List(); diff --git a/NCDK/Pharmacophore/PharmacophoreQueryAngleBond.cs b/NCDK/Pharmacophore/PharmacophoreQueryAngleBond.cs index 11b64b50..f9df4c0a 100644 --- a/NCDK/Pharmacophore/PharmacophoreQueryAngleBond.cs +++ b/NCDK/Pharmacophore/PharmacophoreQueryAngleBond.cs @@ -117,7 +117,7 @@ public double GetLower() return lower; } - private double Round(double val, int places) + private static double Round(double val, int places) { long factor = (long)Math.Pow(10, places); val = val * factor; diff --git a/NCDK/Pharmacophore/PharmacophoreQueryAtom.cs b/NCDK/Pharmacophore/PharmacophoreQueryAtom.cs index c16f1edc..69b9d280 100644 --- a/NCDK/Pharmacophore/PharmacophoreQueryAtom.cs +++ b/NCDK/Pharmacophore/PharmacophoreQueryAtom.cs @@ -20,6 +20,7 @@ using NCDK.Common.Primitives; using NCDK.Isomorphisms.Matchers; using NCDK.Smiles.SMARTS.Parser; +using System; using System.Text; namespace NCDK.Pharmacophore @@ -83,7 +84,7 @@ public PharmacophoreQueryAtom(string symbol, string smarts) public bool Matches(IAtom atom) { PharmacophoreAtom patom = PharmacophoreAtom.Get(atom); - return patom.Symbol.Equals(Symbol); + return patom.Symbol.Equals(Symbol, StringComparison.Ordinal); } /// diff --git a/NCDK/Pharmacophore/PharmacophoreQueryBond.cs b/NCDK/Pharmacophore/PharmacophoreQueryBond.cs index d79b40bc..fb36277d 100644 --- a/NCDK/Pharmacophore/PharmacophoreQueryBond.cs +++ b/NCDK/Pharmacophore/PharmacophoreQueryBond.cs @@ -19,6 +19,7 @@ using NCDK.Isomorphisms.Matchers; using System; +using System.Globalization; using System.Text; namespace NCDK.Pharmacophore @@ -113,7 +114,7 @@ public double GetLower() return lower; } - private double Round(double val, int places) + private static double Round(double val, int places) { long factor = (long)Math.Pow(10, places); val = val * factor; @@ -128,7 +129,7 @@ private double Round(double val, int places) public override string ToString() { StringBuilder sb = new StringBuilder(); - sb.Append($"DC::{Atoms[0]}::{Atoms[1]}::[{GetLower().ToString("F1")} - {GetUpper().ToString("F1")}] "); + sb.Append($"DC::{Atoms[0]}::{Atoms[1]}::[{GetLower().ToString("F1", NumberFormatInfo.InvariantInfo)} - {GetUpper().ToString("F1", NumberFormatInfo.InvariantInfo)}] "); return sb.ToString(); } } diff --git a/NCDK/Pharmacophore/PharmacophoreUtils.cs b/NCDK/Pharmacophore/PharmacophoreUtils.cs index b790c0c7..478121f9 100644 --- a/NCDK/Pharmacophore/PharmacophoreUtils.cs +++ b/NCDK/Pharmacophore/PharmacophoreUtils.cs @@ -17,7 +17,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Xml; @@ -33,7 +35,7 @@ namespace NCDK.Pharmacophore // @cdk.githash // @cdk.keyword pharmacophore // @cdk.keyword 3D isomorphism - public class PharmacophoreUtils + public static class PharmacophoreUtils { /// /// Read in a set of pharmacophore definitions to create pharmacophore queries. @@ -142,16 +144,16 @@ public static void WritePharmacophoreDefinition(PharmacophoreQuery[] queries, St case PharmacophoreQueryBond dbond: { elem = new XElement("distanceConstraint"); - elem.SetAttributeValue("lower", dbond.GetLower().ToString()); - elem.SetAttributeValue("upper", dbond.GetUpper().ToString()); + elem.SetAttributeValue("lower", dbond.GetLower().ToString(NumberFormatInfo.InvariantInfo)); + elem.SetAttributeValue("upper", dbond.GetUpper().ToString(NumberFormatInfo.InvariantInfo)); elem.SetAttributeValue("units", "A"); } break; case PharmacophoreQueryAngleBond dbond: { elem = new XElement("angleConstraint"); - elem.SetAttributeValue("lower", dbond.GetLower().ToString()); - elem.SetAttributeValue("upper", dbond.GetUpper().ToString()); + elem.SetAttributeValue("lower", dbond.GetLower().ToString(NumberFormatInfo.InvariantInfo)); + elem.SetAttributeValue("upper", dbond.GetUpper().ToString(NumberFormatInfo.InvariantInfo)); elem.SetAttributeValue("units", "degrees"); } break; @@ -191,7 +193,7 @@ private static List Getdefs(XDocument doc) var children = root.Elements(); foreach (var e in children) { - if (e.Name.LocalName.Equals("pharmacophore")) ret.Add(ProcessPharmacophoreElement(e, groups)); + if (string.Equals(e.Name.LocalName, "pharmacophore", StringComparison.Ordinal)) ret.Add(ProcessPharmacophoreElement(e, groups)); } return ret; } @@ -206,7 +208,7 @@ private static Dictionary GetGroupDefinitions(XElement e) var children = e.Elements(); foreach (var child in children) { - if (child.Name.LocalName.Equals("group")) + if (string.Equals(child.Name.LocalName, "group", StringComparison.Ordinal)) { string id = child.Attribute("id").Value.Trim(); string smarts = child.Value.Trim(); @@ -230,11 +232,11 @@ private static PharmacophoreQuery ProcessPharmacophoreElement(XElement e, Dictio var children = e.Elements(); foreach (var child in children) { - if (child.Name.LocalName.Equals("distanceConstraint")) + if (string.Equals(child.Name.LocalName, "distanceConstraint", StringComparison.Ordinal)) { ProcessDistanceConstraint(child, local, global, ret); } - else if (child.Name.LocalName.Equals("angleConstraint")) + else if (string.Equals(child.Name.LocalName, "angleConstraint", StringComparison.Ordinal)) { ProcessAngleConstraint(child, local, global, ret); } @@ -250,13 +252,13 @@ private static void ProcessDistanceConstraint(XElement child, Dictionary visited = new Dictionary(); - public IList> Pockets { get; set; } = new List>(); + Dictionary visited = new Dictionary(); + private List> pockets = new List>(); - /// - /// - /// /// The file name containing the protein /// if true generate the grid public ProteinPocketFinder(string biopolymerFile, bool cubicGrid) @@ -82,10 +80,6 @@ public ProteinPocketFinder(string biopolymerFile, double latticeConstant, bool c { CreateCubicGrid(); } - else - { - - } } public ProteinPocketFinder(string biopolymerFile, double[][][] grid) @@ -102,6 +96,8 @@ public ProteinPocketFinder(IBioPolymer protein, double[][][] grid) gridGenerator.Grid = grid; } + public IReadOnlyList> Pockets => pockets; + /// Creates from a PDB File a BioPolymer. private void ReadBioPolymer(string biopolymerFile) { @@ -135,7 +131,7 @@ private void ReadBioPolymer(string biopolymerFile) /// double[] stores min,max,min,max,min,max public double[] FindGridBoundaries() { - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(Protein); + IAtom[] atoms = Protein.Atoms.ToArray(); double[] minMax = new double[6]; minMax[0] = atoms[0].Point3D.Value.X; minMax[1] = atoms[0].Point3D.Value.X; @@ -176,7 +172,6 @@ public double[] FindGridBoundaries() /// Method creates a cubic grid with the grid generator class. public void CreateCubicGrid() { - // Debug.WriteLine(" CREATE CUBIC GRID"); gridGenerator.SetDimension(FindGridBoundaries(), true); gridGenerator.GenerateGrid(); this.Grid = gridGenerator.Grid; @@ -192,28 +187,26 @@ public void CreateCubicGrid() /// public void AssignProteinToGrid() { - // logger.debug.Print(" ASSIGN PROTEIN TO GRID"); // 1. Step: Set all grid points to solvent accessible - this.Grid = gridGenerator.InitializeGrid(this.Grid, 0); + this.Grid = GridGenerator.InitializeGrid(this.Grid, 0); // 2. Step Grid points inaccessible to solvent are assigend a value of -1 // set grid points around (r_atom+r_solv) to -1 - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(Protein); Vector3 gridPoint; int checkGridPoints = 0; double vdWRadius = 0; int[] dim = gridGenerator.Dim; - //int proteinAtomCount = 0;//Debugging int[] minMax = { 0, 0, 0, 0, 0, 0 }; - for (int i = 0; i < atoms.Length; i++) + foreach (var atom in Protein.Atoms) { - if (((PDBAtom)atoms[i]).HetAtom.Value) + var patom = (PDBAtom)atom; + if (patom.HetAtom.Value) { continue; } - gridPoint = gridGenerator.GetGridPointFrom3dCoordinates(atoms[i].Point3D.Value); + gridPoint = gridGenerator.GetGridPointFrom3dCoordinates(patom.Point3D.Value); this.Grid[(int)gridPoint.X][(int)gridPoint.Y][(int)gridPoint.Z] = -1; - vdWRadius = PeriodicTable.GetVdwRadius(atoms[i].Symbol).Value; + vdWRadius = PeriodicTable.GetVdwRadius(patom.Symbol).Value; if (vdWRadius == 0) { vdWRadius = RAtom; @@ -237,15 +230,11 @@ public void AssignProteinToGrid() for (int z = minMax[4]; z <= minMax[5]; z++) { this.Grid[x][y][z] = this.Grid[x][y][z] - 1; - //proteinAtomCount++;//Debugging } } } }// for atoms.Length - - // Debug.WriteLine("- checkGridPoints>" + checkGridPoints - // + " ProteinGridPoints>" + proteinAtomCount); } public void DebuggCheckPSPEvent() @@ -261,7 +250,6 @@ public void DebuggCheckPSPEvent() { for (int z = 0; z <= dim[2]; z++) { - if (this.Grid[x][y][z] == 0) { pspEvents[0]++; @@ -316,10 +304,7 @@ public void DebuggCheckPSPEvent() } Debug.WriteLine(" " + i + ":" + pspEvents[i]); } - Debug.WriteLine(" pspAll>" + sum); - // Debug.WriteLine(" PSPAll:"+pspAll+" minPSP:"+minPSP+" - // #pspMin:"+pspMin+" psp7:"+psp7+" proteinGridPoints:"+proteinGrid - // +" solventGridPoints:"+solventGrid); + Debug.WriteLine($" pspAll>{sum}"); } /// @@ -328,7 +313,6 @@ public void DebuggCheckPSPEvent() /// public void SiteFinder() { - //Debug.WriteLine("SITEFINDER"); try { AssignProteinToGrid(); @@ -340,9 +324,6 @@ public void SiteFinder() // 3. Step scan allong x,y,z axis and the diagonals, if PSP event add +1 // to grid cell int[] dim = gridGenerator.Dim; - // Debug.WriteLine(" SITEFINDER-SCAN - dim:" + dim[0] + " grid:" - // + this.grid[0].Length + " grid point sum:" + this.grid.Length - // /// this.grid[0].Length * this.grid[0][0].Length); AxisScanX(dim[2], dim[1], dim[0]);// x-Axis AxisScanY(dim[2], dim[0], dim[1]);// y-Axis AxisScanZ(dim[0], dim[1], dim[2]);// z-Axis @@ -352,8 +333,6 @@ public void SiteFinder() DiagonalAxisScanYXZ(dim[1], dim[0], dim[2]);// diagonal3-Axis DiagonalAxisScanXYZ(dim[0], dim[1], dim[2]);// diagonal4-Axis - //debuggCheckPSPEvent(); - FindPockets(); SortPockets(); @@ -364,13 +343,12 @@ public void SiteFinder() /// private void SortPockets() { - // Debug.WriteLine(" SORT POCKETS Start#:" + pockets.Count); var hashPockets = new Dictionary>(); - IList pocket; - var sortPockets = new List>(Pockets.Count); - for (int i = 0; i < Pockets.Count; i++) + IReadOnlyList pocket; + var sortPockets = new List>(pockets.Count); + for (int i = 0; i < pockets.Count; i++) { - pocket = Pockets[i]; + pocket = pockets[i]; if (hashPockets.ContainsKey(pocket.Count)) { var tmp = hashPockets[pocket.Count]; @@ -379,10 +357,7 @@ private void SortPockets() } else { - List value = new List - { - i - }; + var value = new List { i }; hashPockets[pocket.Count] = value; } } @@ -392,15 +367,12 @@ private void SortPockets() for (int i = keys.Count - 1; i >= 0; i--) { var value = hashPockets[keys[i]]; - // Debug.WriteLine("key:" + i + " Value" + keys[i] - // + " #Pockets:" + value.Count); for (int j = 0; j < value.Count; j++) { - sortPockets.Add(Pockets[value[j]]); + sortPockets.Add(pockets[value[j]]); } } - // Debug.WriteLine(" SORT POCKETS End#:" + sortPockets.Count); - Pockets = sortPockets; + pockets = sortPockets; } /// @@ -411,60 +383,30 @@ private void SortPockets() private void FindPockets() { int[] dim = gridGenerator.Dim; - // Debug.WriteLine(" FIND POCKETS>dimx:" + dim[0] + " dimy:" + dim[1] - // + " dimz:" + dim[2] + " linkageRadius>" + linkageRadius - // + " latticeConstant>" + latticeConstant + " pocketSize:" - // + pocketSize + " minPSPocket:" + minPSPocket + " minPSCluster:" - // + minPSCluster); - //int pointsVisited = 0;//Debugging - //int significantPointsVisited = 0;//Debugging for (int x = 0; x < dim[0]; x++) { for (int y = 0; y < dim[1]; y++) { for (int z = 0; z < dim[2]; z++) { - // logger.debug.Print(" x:"+x+" y:"+y+" z:"+z); Vector3 start = new Vector3(x, y, z); - //pointsVisited++; if (this.Grid[x][y][z] >= MinPSPocket & !visited.ContainsKey(x + "." + y + "." + z)) { List subPocket = new List(); - // logger.debug.Print("new Point: "+grid[x][y][z]); - //significantPointsVisited++; - // Debug.WriteLine("visited:"+pointsVisited); subPocket = this.ClusterPSPPocket(start, subPocket, dim); if (subPocket != null && subPocket.Count >= PocketSize) { - Pockets.Add(subPocket); + pockets.Add(subPocket); } - // Debug.WriteLine(" Points visited:"+pointsVisited+" - // subPocketSize:"+subPocket.Count+" - // pocketsSize:"+pockets.Count - // +" hashtable:"+visited.Count); - } } } - } - // try { - // Debug.WriteLine(" ->>>> #pockets:" + pockets.Count - // + " significantPointsVisited:" + significantPointsVisited - // + " keys:" + visited.Count + " PointsVisited:" - // + pointsVisited); - // } catch (Exception ex1) { - // logger.debug - // .Println("Problem in System.out due to " + ex1.ToString()); - // } - } /// Method performs the clustering, is called by FindPockets(). public List ClusterPSPPocket(Vector3 root, List subPocket, int[] dim) { - // Debug.WriteLine(" ****** New Root ******:"+root.X+" "+root.Y+" - // "+root.Z); visited[(int)root.X + "." + (int)root.Y + "." + (int)root.Z] = 1; int[] minMax = { 0, 0, 0, 0, 0, 0 }; minMax[0] = (int)(root.X - LinkageRadius); @@ -474,8 +416,6 @@ public List ClusterPSPPocket(Vector3 root, List subPocket, int minMax[4] = (int)(root.Z - LinkageRadius); minMax[5] = (int)(root.Z + LinkageRadius); minMax = CheckBoundaries(minMax, dim); - // Debug.WriteLine("cluster:"+minMax[0]+" "+minMax[1]+" "+minMax[2]+" - // "+minMax[3]+" "+minMax[4]+" "+minMax[5]+" "); for (int k = minMax[0]; k <= minMax[1]; k++) { for (int m = minMax[2]; m <= minMax[3]; m++) @@ -483,13 +423,8 @@ public List ClusterPSPPocket(Vector3 root, List subPocket, int for (int l = minMax[4]; l <= minMax[5]; l++) { Vector3 node = new Vector3(k, m, l); - // Debug.WriteLine(" clusterPSPPocket:"+root.X+" - // "+root.Y+" "+root.Z+" ->"+k+" "+m+" "+l+" - // #>"+this.grid[k][m][l]+" key:"+visited.ContainsKey(new - // string(k+"."+m+"."+l))); if (this.Grid[k][m][l] >= MinPSCluster && !visited.ContainsKey(k + "." + m + "." + l)) { - // Debug.WriteLine(" ---->FOUND"); subPocket.Add(node); this.ClusterPSPPocket(node, subPocket, dim); } @@ -506,7 +441,7 @@ public List ClusterPSPPocket(Vector3 root, List subPocket, int /// with minMax values /// dimension /// new minMax values between 0 and dim - private int[] CheckBoundaries(int[] minMax, int[] dim) + private static int[] CheckBoundaries(int[] minMax, int[] dim) { if (minMax[0] < 0) { @@ -555,12 +490,10 @@ private void FirePSPEvent(List line) public void DiagonalAxisScanXZY(int dimK, int dimL, int dimM) { // x min ->x max;left upper corner z+y max->min//1 - //Debug.WriteLine(" diagonalAxisScanXZY"); if (dimM < dimL) { dimL = dimM; } - //int gridPoints = 0;//Debugging List line = new List(); int pspEvent = 0; int m = 0; @@ -603,7 +536,6 @@ public void DiagonalAxisScanXZY(int dimK, int dimL, int dimM) } dimL = j; } - //Debug.WriteLine(" #gridPoints>" + gridPoints); } /// @@ -615,8 +547,6 @@ public void DiagonalAxisScanXZY(int dimK, int dimL, int dimM) public void DiagonalAxisScanYZX(int dimK, int dimL, int dimM) { // y min -> y max; right lower corner zmax->zmin, xmax ->min//4 - // logger.debug.Print(" diagonalAxisScanYZX"); - //int gridPoints = 0;//Debugging if (dimM < dimL) { dimL = dimM; @@ -663,7 +593,6 @@ public void DiagonalAxisScanYZX(int dimK, int dimL, int dimM) } dimL = j; } - // Debug.WriteLine(" #gridPoints>"+gridPoints); } /// @@ -675,8 +604,6 @@ public void DiagonalAxisScanYZX(int dimK, int dimL, int dimM) public void DiagonalAxisScanYXZ(int dimK, int dimL, int dimM) { // y min -> y max; left lower corner z max->min, x min->max//2 - // logger.debug.Print(" diagonalAxisScanYXZ"); - //int gridPoints = 0;//Debugging if (dimM < dimL) { dimL = dimM; @@ -699,7 +626,6 @@ public void DiagonalAxisScanYXZ(int dimK, int dimL, int dimM) l = 0;// x for (int m = dimM; m >= 0; m--) {// z - //gridPoints++; if (Grid[l][k][m] < 0) { if (pspEvent < 2) @@ -727,7 +653,6 @@ public void DiagonalAxisScanYXZ(int dimK, int dimL, int dimM) }// for k;y dimM = j; } - // Debug.WriteLine(" #gridPoints>"+gridPoints); } /// @@ -739,8 +664,6 @@ public void DiagonalAxisScanYXZ(int dimK, int dimL, int dimM) public void DiagonalAxisScanXYZ(int dimK, int dimL, int dimM) { // x min -> xmax;left lower corner z max->min, y min->max//3 - // logger.debug.Print(" diagonalAxisScanXYZ"); - //int gridPoints = 0;//Debugging if (dimM < dimL) { dimL = dimM; @@ -791,7 +714,6 @@ public void DiagonalAxisScanXYZ(int dimK, int dimL, int dimM) }// for k;x dimM = j; } - // Debug.WriteLine(" #gridPoints>"+gridPoints); } /// @@ -803,8 +725,6 @@ public void DiagonalAxisScanXYZ(int dimK, int dimL, int dimM) public void AxisScanX(int dimK, int dimL, int dimM) { // z,y,x - // logger.debug.Print(" diagonalAxisScanX"); - //int gridPoints = 0;//Debugging List line = new List(); int pspEvent = 0; for (int k = 0; k <= dimK; k++) @@ -843,7 +763,6 @@ public void AxisScanX(int dimK, int dimL, int dimM) } } } - // Debug.WriteLine(" #gridPoints>" + gridPoints); } /// @@ -952,7 +871,7 @@ public void AxisScanZ(int dimK, int dimL, int dimM) public void AssignVdWRadiiToProtein() { AtomTypeFactory atf = null; - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(Protein); + IAtom[] atoms = Protein.Atoms.ToArray(); try { atf = AtomTypeFactory.GetInstance(VanDerWaalsFile, atoms[0].Builder); @@ -1019,19 +938,19 @@ public void WritePocketsToPMesh(string outPutFileName) { try { - for (int i = 0; i < Pockets.Count; i++) + for (int i = 0; i < pockets.Count; i++) {// go through every // pocket - var writer = new StreamWriter(outPutFileName + "-" + i + ".pmesh"); - var pocket = Pockets[i]; - writer.Write(pocket.Count + "\n"); + var writer = new StreamWriter($"{outPutFileName}-{i}.pmesh"); + var pocket = pockets[i]; + writer.Write($"{pocket.Count}\\n"); for (int j = 0; j < pocket.Count; j++) {// go through every // grid point of the // actual pocket - Vector3 actualGridPoint = (Vector3)pocket[j]; - Vector3 coords = gridGenerator.GetCoordinatesFromGridPoint(actualGridPoint); - writer.Write(coords.X + "\t" + coords.Y + "\t" + coords.Z + "\n"); + var actualGridPoint = pocket[j]; + var coords = gridGenerator.GetCoordinatesFromGridPoint(actualGridPoint); + writer.Write($"{coords.X}\\t{coords.Y}\\t{coords.Z}\\n"); } writer.Close(); } diff --git a/NCDK/QSAR/AbstractDescriptor.cs b/NCDK/QSAR/AbstractDescriptor.cs index c8d189b6..61a038dd 100644 --- a/NCDK/QSAR/AbstractDescriptor.cs +++ b/NCDK/QSAR/AbstractDescriptor.cs @@ -37,14 +37,14 @@ public abstract class AbstractDescriptor : IDescriptor /// Default implementation of initialise allows optional override. /// /// chem object build - public void Initialise(IChemObjectBuilder builder) + public virtual void Initialise(IChemObjectBuilder builder) { // do nothing } public abstract IImplementationSpecification Specification { get; } public abstract IReadOnlyList ParameterNames { get; } - public abstract object[] Parameters { get; set; } + public abstract IReadOnlyList Parameters { get; set; } public abstract IReadOnlyList DescriptorNames { get; } public abstract object GetParameterType(string name); } diff --git a/NCDK/QSAR/AtomValenceTool.cs b/NCDK/QSAR/AtomValenceTool.cs index 17c62cef..cc0a03ec 100644 --- a/NCDK/QSAR/AtomValenceTool.cs +++ b/NCDK/QSAR/AtomValenceTool.cs @@ -32,7 +32,7 @@ namespace NCDK.QSAR // @cdk.dictref valence, atom public static class AtomValenceTool { - private static IDictionary valencesTable = new Dictionary + private static Dictionary valencesTable = new Dictionary { { "H", 1 }, { "He", 8 }, @@ -87,7 +87,7 @@ public static class AtomValenceTool public static int GetValence(IAtom atom) { if (!valencesTable.TryGetValue(atom.Symbol, out int ret)) - throw new System.NullReferenceException(); + throw new NoSuchAtomException(); return ret; } } diff --git a/NCDK/QSAR/DescriptorEngine.cs b/NCDK/QSAR/DescriptorEngine.cs index c5c20ab1..59c7ac03 100644 --- a/NCDK/QSAR/DescriptorEngine.cs +++ b/NCDK/QSAR/DescriptorEngine.cs @@ -61,9 +61,9 @@ public class DescriptorEngine private static readonly XNamespace rdfNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; private EntryDictionary dict = null; - private IList classNames = new List(200); - private IList descriptors = new List(200); - private IList speclist = null; + private List classNames = new List(200); + private List descriptors = new List(200); + private List speclist = null; private readonly IChemObjectBuilder builder; private DescriptorEngine() @@ -89,8 +89,8 @@ public DescriptorEngine(IEnumerable classNames, IChemObjectBuilder build : this(builder) { this.classNames = classNames.ToList(); - descriptors = InstantiateDescriptors(classNames); - speclist = InitializeSpecifications(descriptors).ToList(); + descriptors = InstantiateDescriptors(classNames).ToList(); + speclist = ToSpecifications(descriptors).ToList(); // get the dictionary for the descriptors DictionaryDatabase dictDB = new DictionaryDatabase(); @@ -116,7 +116,7 @@ public static DescriptorEngine Create(IChemObjectBuilder builder) where T : I o.classNames.Add(descriptor.GetType().FullName); } - o.speclist = o.InitializeSpecifications(o.descriptors).Cast().ToList(); + o.speclist = ToSpecifications(o.descriptors).ToList(); Debug.WriteLine($"Found #descriptors: {o.classNames.Count}"); // get the dictionary for the descriptors @@ -192,7 +192,7 @@ public void Process(IAtomContainer molecule) } else { - Debug.WriteLine("Unknown descriptor type for: ", descriptor.GetType().FullName); + Debug.WriteLine($"Unknown descriptor type for: {descriptor.GetType().FullName}"); } } } @@ -223,13 +223,14 @@ public string GetDictionaryType(string identifier) var dictEntries = dict.Entries; string specRef = GetSpecRef(identifier); - Debug.WriteLine("Got identifier: " + identifier); - Debug.WriteLine("Final spec ref: " + specRef); + Debug.WriteLine($"Got identifier: {identifier}"); + Debug.WriteLine($"Final spec ref: {specRef}"); foreach (var dictEntry in dictEntries) { - if (!dictEntry.ClassName.Equals("Descriptor")) continue; - if (dictEntry.Id.Equals(specRef.ToLowerInvariant())) + if (!string.Equals(dictEntry.ClassName, "Descriptor", StringComparison.Ordinal)) + continue; + if (dictEntry.Id.Equals(specRef.ToLowerInvariant(), StringComparison.Ordinal)) { XElement rawElement = (XElement)dictEntry.RawContent; // Assert(rawElement != null); @@ -241,8 +242,8 @@ public string GetDictionaryType(string identifier) foreach (var element in classifications) { var attr = element.Attribute(rdfNS + "resource"); - if ((attr.Value.IndexOf("molecularDescriptor") != -1) - || (attr.Value.IndexOf("atomicDescriptor") != -1)) + if (attr.Value.Contains("molecularDescriptor") + || attr.Value.Contains("atomicDescriptor")) { string[] tmp = attr.Value.Split('#'); return tmp[1]; @@ -302,7 +303,7 @@ public string GetDictionaryType(IImplementationSpecification descriptorSpecifica /// specification reference /// An array containing the names of the QSAR descriptor classes that this descriptor was declared /// to belong to. If an entry for the specified identifier was not found, null is returned. - public string[] GetDictionaryClass(string identifier) + public IEnumerable GetDictionaryClass(string identifier) { var dictEntries = dict.Entries; @@ -310,22 +311,22 @@ public string[] GetDictionaryClass(string identifier) if (specRef == null) { Trace.TraceError("Cannot determine specification for id: ", identifier); - return new string[0]; + return Array.Empty(); } List dictClasses = new List(); foreach (var dictEntry in dictEntries) { - if (!dictEntry.ClassName.Equals("Descriptor")) continue; - if (dictEntry.Id.Equals(specRef.ToLowerInvariant())) + if (!string.Equals(dictEntry.ClassName, "Descriptor", StringComparison.Ordinal)) continue; + if (dictEntry.Id.Equals(specRef.ToLowerInvariant(), StringComparison.Ordinal)) { XElement rawElement = (XElement)dictEntry.RawContent; var classifications = rawElement.Elements(dict.NS + "isClassifiedAs"); foreach (var element in classifications) { var attr = element.Attribute(rdfNS + "resource"); - if ((attr.Value.IndexOf("molecularDescriptor") >= 0) - || (attr.Value.IndexOf("atomicDescriptor") >= 0)) + if (attr.Value.Contains("molecularDescriptor") + || attr.Value.Contains("atomicDescriptor")) { continue; } @@ -360,7 +361,7 @@ public string[] GetDictionaryClass(string identifier) /// A DescriptorSpecification object /// An array containing the names of the QSAR descriptor classes that this descriptor was declared /// to belong to. If an entry for the specified identifier was not found, null is returned. - public string[] GetDictionaryClass(IImplementationSpecification descriptorSpecification) + public IEnumerable GetDictionaryClass(IImplementationSpecification descriptorSpecification) { return GetDictionaryClass(descriptorSpecification.SpecificationReference); } @@ -391,8 +392,9 @@ public string GetDictionaryDefinition(string identifier) string definition = null; foreach (var dictEntry in dictEntries) { - if (!dictEntry.ClassName.Equals("Descriptor")) continue; - if (dictEntry.Id.Equals(specRef.ToLowerInvariant())) + if (!string.Equals(dictEntry.ClassName, "Descriptor", StringComparison.Ordinal)) + continue; + if (dictEntry.Id.Equals(specRef.ToLowerInvariant(), StringComparison.Ordinal)) { definition = dictEntry.Definition; break; @@ -436,8 +438,9 @@ public string GetDictionaryTitle(string identifier) string title = null; foreach (var dictEntry in dictEntries) { - if (!dictEntry.ClassName.Equals("Descriptor")) continue; - if (dictEntry.Id.Equals(specRef.ToLowerInvariant())) + if (!string.Equals(dictEntry.ClassName, "Descriptor", StringComparison.Ordinal)) + continue; + if (dictEntry.Id.Equals(specRef.ToLowerInvariant(), StringComparison.Ordinal)) { title = dictEntry.Label; break; @@ -462,7 +465,7 @@ public string GetDictionaryTitle(DescriptorSpecification descriptorSpecification /// A of objects. These are the keys /// with which the objects can be obtained from a /// molecules property list - public IList GetDescriptorSpecifications() + public IEnumerable GetDescriptorSpecifications() { return speclist; } @@ -481,7 +484,7 @@ public void SetDescriptorSpecifications(IEnumerable /// A list of class names. - public IList GetDescriptorClassNames() + public IEnumerable GetDescriptorClassNames() { return classNames; } @@ -490,7 +493,7 @@ public IList GetDescriptorClassNames() /// Returns a containing the instantiated descriptor classes. /// /// A containing descriptor classes - public IList GetDescriptorInstances() + public IEnumerable GetDescriptorInstances() { return descriptors; } @@ -500,9 +503,9 @@ public IList GetDescriptorInstances() /// /// A of descriptor objects /// - public void SetDescriptorInstances(IList descriptors) + public void SetDescriptorInstances(IEnumerable descriptors) { - this.descriptors = descriptors; + this.descriptors = descriptors.ToList(); } /// @@ -514,7 +517,7 @@ public IEnumerable GetAvailableDictionaryClasses() List classList = new List(); foreach (var spec in speclist) { - string[] tmp = GetDictionaryClass(spec); + var tmp = GetDictionaryClass(spec); if (tmp != null) { foreach (var t in tmp) @@ -617,7 +620,7 @@ public static IEnumerable GetDescriptorClassNameByPackage(string namespa yield break; } - public IList InstantiateDescriptors(IEnumerable descriptorClassNames) + public static IEnumerable InstantiateDescriptors(IEnumerable descriptorClassNames) { var assembly = Assembly.GetExecutingAssembly(); var descriptors = new List(); @@ -639,7 +642,7 @@ public IList InstantiateDescriptors(IEnumerable descriptorC return descriptors; } - private IDescriptor Instantiate(Type c) + private static IDescriptor Instantiate(Type c) { ConstructorInfo ctor; ctor = c.GetConstructor(Type.EmptyTypes); @@ -652,7 +655,7 @@ private IDescriptor Instantiate(Type c) throw new InvalidOperationException($"descriptor {c.Name} has no usable constructors"); } - public IEnumerable InitializeSpecifications(IEnumerable descriptors) + public static IEnumerable ToSpecifications(IEnumerable descriptors) { foreach (var descriptor in descriptors) { @@ -668,14 +671,14 @@ private string GetSpecRef(string identifier) for (int i = 0; i < classNames.Count; i++) { string className = classNames[i]; - if (className.Equals(identifier)) + if (className.Equals(identifier, StringComparison.Ordinal)) { IDescriptor descriptor = descriptors[i]; IImplementationSpecification descSpecification = descriptor.Specification; string[] tmp = descSpecification.SpecificationReference.Split('#'); if (tmp.Length != 2) { - Debug.WriteLine("Something fishy with the spec ref: ", descSpecification.SpecificationReference); + Debug.WriteLine($"Something fishy with the spec ref: {descSpecification.SpecificationReference}"); } else { @@ -689,7 +692,7 @@ private string GetSpecRef(string identifier) string[] tmp = identifier.Split('#'); if (tmp.Length != 2) { - Debug.WriteLine("Something fishy with the identifier: ", identifier); + Debug.WriteLine($"Something fishy with the identifier: {identifier}"); } else { diff --git a/NCDK/QSAR/DescriptorException.cs b/NCDK/QSAR/DescriptorException.cs index 9feff8d1..3fff2354 100644 --- a/NCDK/QSAR/DescriptorException.cs +++ b/NCDK/QSAR/DescriptorException.cs @@ -31,6 +31,10 @@ namespace NCDK.QSAR // @cdk.githash public class DescriptorException : CDKException { + public DescriptorException() + { + } + /// /// Constructs a new DescriptorException with the given message. /// @@ -47,5 +51,9 @@ public DescriptorException(string message) public DescriptorException(string name, string message) : base(name + ": " + message) { } + + public DescriptorException(string message, System.Exception innerException) : base(message, innerException) + { + } } } diff --git a/NCDK/QSAR/DescriptorValue.cs b/NCDK/QSAR/DescriptorValue.cs index a7465ac3..a3ac33c5 100644 --- a/NCDK/QSAR/DescriptorValue.cs +++ b/NCDK/QSAR/DescriptorValue.cs @@ -20,13 +20,14 @@ using NCDK.QSAR.Results; using System; using System.Collections.Generic; +using System.Globalization; namespace NCDK.QSAR { public interface IDescriptorValue { DescriptorSpecification Specification { get; } - object[] Parameters { get; } + IReadOnlyList Parameters { get; } IReadOnlyList ParameterNames { get; } IReadOnlyList Names { get; } IDescriptorResult Value { get; } @@ -39,11 +40,12 @@ public class DescriptorValue where TDescriptorResult : IDescriptorResult { private DescriptorSpecification specification; - private IReadOnlyList parameterNames; - private object[] parameterSettings; + private readonly IReadOnlyList parameterNames; + private readonly IReadOnlyList parameterSettings; private TDescriptorResult value; private IReadOnlyList descriptorNames; - private Exception exception; + [NonSerialized] + private readonly Exception exception; /// /// Construct a descriptor value object, representing the numeric values as well as parameters and provenance. @@ -56,10 +58,11 @@ public class DescriptorValue /// The parameter settings /// The actual values /// The names of the values - public DescriptorValue(DescriptorSpecification specification, IReadOnlyList parameterNames, object[] parameterSettings, + public DescriptorValue(DescriptorSpecification specification, IReadOnlyList parameterNames, IReadOnlyList parameterSettings, TDescriptorResult value, IReadOnlyList descriptorNames) : this(specification, parameterNames, parameterSettings, value, descriptorNames, null) - { } + { + } /// /// Construct a descriptor value object, representing the numeric values as well as parameters and provenance. @@ -73,8 +76,8 @@ public DescriptorValue(DescriptorSpecification specification, IReadOnlyListThe actual values /// The names of the values /// The exception object that should have been caught if an error occurred during descriptor calculation - public DescriptorValue(DescriptorSpecification specification, IReadOnlyList parameterNames, object[] parameterSettings, - TDescriptorResult value, IReadOnlyList descriptorNames, Exception exception) + public DescriptorValue(DescriptorSpecification specification, IReadOnlyList parameterNames, IReadOnlyList parameterSettings, + TDescriptorResult value, IReadOnlyList descriptorNames, Exception exception) { this.specification = specification; this.parameterNames = parameterNames; @@ -85,7 +88,7 @@ public DescriptorValue(DescriptorSpecification specification, IReadOnlyList this.specification; - public object[] Parameters => this.parameterSettings; + public IReadOnlyList Parameters => this.parameterSettings; public IReadOnlyList ParameterNames => this.parameterNames; public TDescriptorResult Value => this.value; public Exception Exception => exception; @@ -136,7 +139,7 @@ public IReadOnlyList Names } var names = new string[ndesc]; for (int i = 0; i < ndesc; i++) - names[i] = title + i.ToString(); + names[i] = title + i.ToString(NumberFormatInfo.InvariantInfo); descriptorNames = names; } } diff --git a/NCDK/QSAR/Descriptors/AtomPair/PiContactDetectionDescriptor.cs b/NCDK/QSAR/Descriptors/AtomPair/PiContactDetectionDescriptor.cs index cb68c22b..ba4b8bcd 100644 --- a/NCDK/QSAR/Descriptors/AtomPair/PiContactDetectionDescriptor.cs +++ b/NCDK/QSAR/Descriptors/AtomPair/PiContactDetectionDescriptor.cs @@ -75,8 +75,8 @@ public PiContactDetectionDescriptor() { } /// /// The specification attribute of the PiContactDetectionDescriptor object. /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#piContact", typeof(PiContactDetectionDescriptor).FullName, "The Chemistry Development Kit"); @@ -86,11 +86,11 @@ public PiContactDetectionDescriptor() { } /// Parameters contains a bool (true if is needed a checkAromaticity)Parameters contains a bool (true if is needed a checkAromaticity) /// /// Description of the Exception - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException("PiContactDetectionDescriptor expects 1 parameters"); } @@ -111,7 +111,7 @@ public object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(false), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(false), NAMES, e); } /// @@ -170,7 +170,7 @@ public DescriptorValue> Calculate(IAtom first, IAtom second, IAtomC { piContact = true; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( piContact), DescriptorNames); } @@ -181,7 +181,7 @@ public DescriptorValue> Calculate(IAtom first, IAtom second, IAtomC /// AtomContainer /// The bool result /// - private bool IsANeighboorsInAnAtomContainer(IEnumerable neighs, IAtomContainer ac) + private static bool IsANeighboorsInAnAtomContainer(IEnumerable neighs, IAtomContainer ac) { bool isIn = false; int count = 0; @@ -211,7 +211,7 @@ private bool IsANeighboorsInAnAtomContainer(IEnumerable neighs, IAtomCont /// The parameterType value public object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } diff --git a/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt b/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt index 34f8dde3..81b281a7 100644 --- a/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt +++ b/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt @@ -20,21 +20,21 @@ namespace NCDK.QSAR.Descriptors.Atomic { <# var fn = Path.Combine(new FileInfo(this.Host.TemplateFile).Directory.Parent.Parent.FullName, "IAtomicDescriptor"); - using (var reader = new StreamReader(fn)) - { - string line; - while ((line = reader.ReadLine()) != null) - { - if (line.Length > 0 && line[0] == '#') - continue; - line = line.Trim(); - if (string.IsNullOrEmpty(line)) - continue; - var cIndex = line.LastIndexOf("."); - var className = line.Substring(cIndex + 1); + using (var reader = new StreamReader(fn)) + { + string line; + while ((line = reader.ReadLine()) != null) + { + if (line.Length > 0 && line[0] == '#') + continue; + line = line.Trim(); + if (string.IsNullOrEmpty(line)) + continue; + var cIndex = line.LastIndexOf("."); + var className = line.Substring(cIndex + 1); #> - public partial class <#=className#> - { + public partial class <#=className#> + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -72,9 +72,9 @@ namespace NCDK.QSAR.Descriptors.Atomic if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -84,11 +84,11 @@ namespace NCDK.QSAR.Descriptors.Atomic cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } + } <# - } - } + } + } #> } diff --git a/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt.cs b/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt.cs index 97c97b9b..efeaed19 100644 --- a/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt.cs +++ b/NCDK/QSAR/Descriptors/Atomic/$AtomicDescriptor.tt.cs @@ -11,8 +11,8 @@ namespace NCDK.QSAR.Descriptors.Atomic { - public partial class VdWRadiusDescriptor - { + public partial class VdWRadiusDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -50,9 +50,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -62,11 +62,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class StabilizationPlusChargeDescriptor - { + } + public partial class StabilizationPlusChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -104,9 +104,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -116,11 +116,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class SigmaElectronegativityDescriptor - { + } + public partial class SigmaElectronegativityDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -158,9 +158,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -170,11 +170,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class RDFProtonDescriptor_GSR - { + } + public partial class RDFProtonDescriptorGSR + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -212,9 +212,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -224,11 +224,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class RDFProtonDescriptor_GHR_topol - { + } + public partial class RDFProtonDescriptorGHRTopology + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -266,9 +266,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -278,11 +278,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class RDFProtonDescriptor_GHR - { + } + public partial class RDFProtonDescriptorGHR + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -320,9 +320,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -332,11 +332,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class RDFProtonDescriptor_GDR - { + } + public partial class RDFProtonDescriptorGDR + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -374,9 +374,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -386,11 +386,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class RDFProtonDescriptor_G3R - { + } + public partial class RDFProtonDescriptorG3R + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -428,9 +428,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -440,11 +440,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class ProtonTotalPartialChargeDescriptor - { + } + public partial class ProtonTotalPartialChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -482,9 +482,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -494,11 +494,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class ProtonAffinityHOSEDescriptor - { + } + public partial class ProtonAffinityHOSEDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -536,9 +536,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -548,11 +548,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class PiElectronegativityDescriptor - { + } + public partial class PiElectronegativityDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -590,9 +590,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -602,11 +602,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class PeriodicTablePositionDescriptor - { + } + public partial class PeriodicTablePositionDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -644,9 +644,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -656,11 +656,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class PartialTChargePEOEDescriptor - { + } + public partial class PartialTChargePEOEDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -698,9 +698,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -710,11 +710,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class PartialTChargeMMFF94Descriptor - { + } + public partial class PartialTChargeMMFF94Descriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -752,9 +752,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -764,11 +764,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class PartialSigmaChargeDescriptor - { + } + public partial class PartialSigmaChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -806,9 +806,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -818,11 +818,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class PartialPiChargeDescriptor - { + } + public partial class PartialPiChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -860,9 +860,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -872,11 +872,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class IsProtonInConjugatedPiSystemDescriptor - { + } + public partial class IsProtonInConjugatedPiSystemDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -914,9 +914,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -926,11 +926,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class IsProtonInAromaticSystemDescriptor - { + } + public partial class IsProtonInAromaticSystemDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -968,9 +968,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -980,11 +980,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class IPAtomicHOSEDescriptor - { + } + public partial class IPAtomicHOSEDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1022,9 +1022,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1034,11 +1034,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class InductiveAtomicSoftnessDescriptor - { + } + public partial class InductiveAtomicSoftnessDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1076,9 +1076,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1088,11 +1088,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class InductiveAtomicHardnessDescriptor - { + } + public partial class InductiveAtomicHardnessDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1130,9 +1130,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1142,11 +1142,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class EffectiveAtomPolarizabilityDescriptor - { + } + public partial class EffectiveAtomPolarizabilityDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1184,9 +1184,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1196,11 +1196,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class DistanceToAtomDescriptor - { + } + public partial class DistanceToAtomDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1238,9 +1238,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1250,11 +1250,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class CovalentRadiusDescriptor - { + } + public partial class CovalentRadiusDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1292,9 +1292,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1304,11 +1304,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class BondsToAtomDescriptor - { + } + public partial class BondsToAtomDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1346,9 +1346,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1358,11 +1358,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class AtomValenceDescriptor - { + } + public partial class AtomValenceDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1400,9 +1400,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1412,11 +1412,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class AtomHybridizationVSEPRDescriptor - { + } + public partial class AtomHybridizationVSEPRDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1454,9 +1454,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1466,11 +1466,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class AtomHybridizationDescriptor - { + } + public partial class AtomHybridizationDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1508,9 +1508,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1520,11 +1520,11 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } - public partial class AtomDegreeDescriptor - { + } + public partial class AtomDegreeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; // FIXME: needs a better solution! @@ -1562,9 +1562,9 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -1574,7 +1574,7 @@ public void CacheDescriptorValue(IAtom atom, IAtomContainer container, IDescript cachedDescriptorValues[atom] = value; } - IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) + IDescriptorValue IAtomicDescriptor.Calculate(IAtom atom, IAtomContainer container) => Calculate(atom, container); - } + } } diff --git a/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt b/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt index f004a628..7d5aa1ba 100644 --- a/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt +++ b/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt @@ -21,20 +21,20 @@ using System.Linq; namespace NCDK.QSAR.Descriptors.Atomic { <# - string[] classNames = new string[] - { - "RDFProtonDescriptor_G3R", - "RDFProtonDescriptor_GDR", - "RDFProtonDescriptor_GHR", - "RDFProtonDescriptor_GHR_topol", - "RDFProtonDescriptor_GSR", - }; - foreach (var className in classNames) - { + string[] classNames = new string[] + { + "RDFProtonDescriptorG3R", + "RDFProtonDescriptorGDR", + "RDFProtonDescriptorGHR", + "RDFProtonDescriptorGHRTopology", + "RDFProtonDescriptorGSR", + }; + foreach (var className in classNames) + { #> - public partial class <#=className#> - { - private bool checkAromaticity { get; set; } = false; + public partial class <#=className#> + { + private bool CheckAromaticity { get; set; } = false; private IAtomContainer acold = null; private IRingSet varRingSet = null; private IChemObjectSet varAtomContainerSet = null; @@ -44,24 +44,24 @@ namespace NCDK.QSAR.Descriptors.Atomic /// /// Parameters are the proton position and a boolean ( if you need to detect aromaticity) /// - public virtual object[] Parameters + public virtual IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("RDFProtonDescriptor only expects one parameters"); + throw new CDKException($"{nameof(<#=className#>)} only expects one parameters"); } if (!(value[0] is bool)) { - throw new CDKException("The second parameter must be of type bool"); + throw new CDKException($"The second parameter must be of type {nameof(System.Boolean)}"); } - checkAromaticity = (bool)value[0]; + CheckAromaticity = (bool)value[0]; } get { // return the parameters as used for the descriptor calculation - return new object[] { checkAromaticity }; + return new object[] { CheckAromaticity }; } } @@ -70,7 +70,7 @@ namespace NCDK.QSAR.Descriptors.Atomic ArrayResult result = new ArrayResult(desc_length); for (int i = 0; i < desc_length; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } public virtual IDescriptorValue Calculate(IAtom atom, IAtomContainer varAtomContainerSet) @@ -85,7 +85,7 @@ namespace NCDK.QSAR.Descriptors.Atomic int atomPosition = atomContainer.Atoms.IndexOf(atom); IAtom clonedAtom = varAtomContainer.Atoms[atomPosition]; ArrayResult rdfProtonCalculatedValues = new ArrayResult(desc_length); - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return GetDummyDescriptorValue(new CDKException("Invalid atom specified")); } @@ -120,7 +120,7 @@ namespace NCDK.QSAR.Descriptors.Atomic return GetDummyDescriptorValue(ex1); } } - if (checkAromaticity) + if (CheckAromaticity) { try { @@ -307,7 +307,7 @@ namespace NCDK.QSAR.Descriptors.Atomic atoms, bondsInCycloex)) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); } else { @@ -317,7 +317,7 @@ namespace NCDK.QSAR.Descriptors.Atomic // Others definitions - private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) + private static bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) { bool isBondNotRotatable = false; int counter = 0; @@ -335,7 +335,7 @@ namespace NCDK.QSAR.Descriptors.Atomic } else { - if (atom1.Symbol.Equals("H")) + if (string.Equals(atom1.Symbol, "H", StringComparison.Ordinal)) counter += 1; else counter += 0; @@ -353,7 +353,7 @@ namespace NCDK.QSAR.Descriptors.Atomic return isBondNotRotatable; } - private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) + private static bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) { bool isDoubleBondedToOxygen = false; var neighToCarbon = mol.GetConnectedAtoms(carbonAtom); @@ -361,7 +361,7 @@ namespace NCDK.QSAR.Descriptors.Atomic int counter = 0; foreach (var neighbour in neighToCarbon) { - if (neighbour.Symbol.Equals("O")) + if (string.Equals(neighbour.Symbol, "O", StringComparison.Ordinal)) { tmpBond = mol.GetBond(neighbour, carbonAtom); if (tmpBond.Order == BondOrder.Double) counter += 1; @@ -373,7 +373,7 @@ namespace NCDK.QSAR.Descriptors.Atomic // this method calculates the angle between two bonds given coordinates of their atoms - internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + internal static double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 firstLine = a - b; Vector3 secondLine = c - d; @@ -383,7 +383,7 @@ namespace NCDK.QSAR.Descriptors.Atomic } // this method store atoms and bonds in proper lists: - private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, + private static void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, List doubleVec, List cycloexVec, int a1, List atomVec, int sphere, bool isBondInCycloex) { @@ -409,7 +409,7 @@ namespace NCDK.QSAR.Descriptors.Atomic } // generic method for calculation of distance btw 2 atoms - internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + internal static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; @@ -420,7 +420,7 @@ namespace NCDK.QSAR.Descriptors.Atomic // given a double bond // this method returns a bond bonded to this double bond - internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) + internal static int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) { int nearestBond = -1; double distance = 0; @@ -448,7 +448,7 @@ namespace NCDK.QSAR.Descriptors.Atomic // method which calculated distance btw an atom and the middle point of a bond // and returns distance and coordinates of middle point - internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) + internal static double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) { Vector3 middlePoint = theBond.Geometric3DCenter; Vector3 protonPoint = proton.Point3D.Value; @@ -472,11 +472,11 @@ namespace NCDK.QSAR.Descriptors.Atomic /// The parameterType value public virtual object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } - } + } <# - } + } #> } diff --git a/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt.cs b/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt.cs index 6721cbbf..89267b24 100644 --- a/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt.cs +++ b/NCDK/QSAR/Descriptors/Atomic/$ProtonDescriptor.tt.cs @@ -13,9 +13,9 @@ namespace NCDK.QSAR.Descriptors.Atomic { - public partial class RDFProtonDescriptor_G3R - { - private bool checkAromaticity { get; set; } = false; + public partial class RDFProtonDescriptorG3R + { + private bool CheckAromaticity { get; set; } = false; private IAtomContainer acold = null; private IRingSet varRingSet = null; private IChemObjectSet varAtomContainerSet = null; @@ -25,24 +25,24 @@ public partial class RDFProtonDescriptor_G3R /// /// Parameters are the proton position and a boolean ( if you need to detect aromaticity) /// - public virtual object[] Parameters + public virtual IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("RDFProtonDescriptor only expects one parameters"); + throw new CDKException($"{nameof(RDFProtonDescriptorG3R)} only expects one parameters"); } if (!(value[0] is bool)) { - throw new CDKException("The second parameter must be of type bool"); + throw new CDKException($"The second parameter must be of type {nameof(System.Boolean)}"); } - checkAromaticity = (bool)value[0]; + CheckAromaticity = (bool)value[0]; } get { // return the parameters as used for the descriptor calculation - return new object[] { checkAromaticity }; + return new object[] { CheckAromaticity }; } } @@ -51,7 +51,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult result = new ArrayResult(desc_length); for (int i = 0; i < desc_length; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } public virtual IDescriptorValue Calculate(IAtom atom, IAtomContainer varAtomContainerSet) @@ -66,7 +66,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer int atomPosition = atomContainer.Atoms.IndexOf(atom); IAtom clonedAtom = varAtomContainer.Atoms[atomPosition]; ArrayResult rdfProtonCalculatedValues = new ArrayResult(desc_length); - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return GetDummyDescriptorValue(new CDKException("Invalid atom specified")); } @@ -101,7 +101,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer return GetDummyDescriptorValue(ex1); } } - if (checkAromaticity) + if (CheckAromaticity) { try { @@ -288,7 +288,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atoms, bondsInCycloex)) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); } else { @@ -298,7 +298,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer // Others definitions - private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) + private static bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) { bool isBondNotRotatable = false; int counter = 0; @@ -316,7 +316,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai } else { - if (atom1.Symbol.Equals("H")) + if (string.Equals(atom1.Symbol, "H", StringComparison.Ordinal)) counter += 1; else counter += 0; @@ -334,7 +334,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai return isBondNotRotatable; } - private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) + private static bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) { bool isDoubleBondedToOxygen = false; var neighToCarbon = mol.GetConnectedAtoms(carbonAtom); @@ -342,7 +342,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb int counter = 0; foreach (var neighbour in neighToCarbon) { - if (neighbour.Symbol.Equals("O")) + if (string.Equals(neighbour.Symbol, "O", StringComparison.Ordinal)) { tmpBond = mol.GetBond(neighbour, carbonAtom); if (tmpBond.Order == BondOrder.Double) counter += 1; @@ -354,7 +354,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb // this method calculates the angle between two bonds given coordinates of their atoms - internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + internal static double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 firstLine = a - b; Vector3 secondLine = c - d; @@ -364,7 +364,7 @@ internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, V } // this method store atoms and bonds in proper lists: - private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, + private static void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, List doubleVec, List cycloexVec, int a1, List atomVec, int sphere, bool isBondInCycloex) { @@ -390,7 +390,7 @@ private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singl } // generic method for calculation of distance btw 2 atoms - internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + internal static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; @@ -401,7 +401,7 @@ internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) // given a double bond // this method returns a bond bonded to this double bond - internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) + internal static int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) { int nearestBond = -1; double distance = 0; @@ -429,7 +429,7 @@ internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bo // method which calculated distance btw an atom and the middle point of a bond // and returns distance and coordinates of middle point - internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) + internal static double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) { Vector3 middlePoint = theBond.Geometric3DCenter; Vector3 protonPoint = proton.Point3D.Value; @@ -453,13 +453,13 @@ internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBon /// The parameterType value public virtual object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } - } - public partial class RDFProtonDescriptor_GDR - { - private bool checkAromaticity { get; set; } = false; + } + public partial class RDFProtonDescriptorGDR + { + private bool CheckAromaticity { get; set; } = false; private IAtomContainer acold = null; private IRingSet varRingSet = null; private IChemObjectSet varAtomContainerSet = null; @@ -469,24 +469,24 @@ public partial class RDFProtonDescriptor_GDR /// /// Parameters are the proton position and a boolean ( if you need to detect aromaticity) /// - public virtual object[] Parameters + public virtual IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("RDFProtonDescriptor only expects one parameters"); + throw new CDKException($"{nameof(RDFProtonDescriptorGDR)} only expects one parameters"); } if (!(value[0] is bool)) { - throw new CDKException("The second parameter must be of type bool"); + throw new CDKException($"The second parameter must be of type {nameof(System.Boolean)}"); } - checkAromaticity = (bool)value[0]; + CheckAromaticity = (bool)value[0]; } get { // return the parameters as used for the descriptor calculation - return new object[] { checkAromaticity }; + return new object[] { CheckAromaticity }; } } @@ -495,7 +495,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult result = new ArrayResult(desc_length); for (int i = 0; i < desc_length; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } public virtual IDescriptorValue Calculate(IAtom atom, IAtomContainer varAtomContainerSet) @@ -510,7 +510,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer int atomPosition = atomContainer.Atoms.IndexOf(atom); IAtom clonedAtom = varAtomContainer.Atoms[atomPosition]; ArrayResult rdfProtonCalculatedValues = new ArrayResult(desc_length); - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return GetDummyDescriptorValue(new CDKException("Invalid atom specified")); } @@ -545,7 +545,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer return GetDummyDescriptorValue(ex1); } } - if (checkAromaticity) + if (CheckAromaticity) { try { @@ -732,7 +732,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atoms, bondsInCycloex)) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); } else { @@ -742,7 +742,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer // Others definitions - private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) + private static bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) { bool isBondNotRotatable = false; int counter = 0; @@ -760,7 +760,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai } else { - if (atom1.Symbol.Equals("H")) + if (string.Equals(atom1.Symbol, "H", StringComparison.Ordinal)) counter += 1; else counter += 0; @@ -778,7 +778,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai return isBondNotRotatable; } - private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) + private static bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) { bool isDoubleBondedToOxygen = false; var neighToCarbon = mol.GetConnectedAtoms(carbonAtom); @@ -786,7 +786,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb int counter = 0; foreach (var neighbour in neighToCarbon) { - if (neighbour.Symbol.Equals("O")) + if (string.Equals(neighbour.Symbol, "O", StringComparison.Ordinal)) { tmpBond = mol.GetBond(neighbour, carbonAtom); if (tmpBond.Order == BondOrder.Double) counter += 1; @@ -798,7 +798,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb // this method calculates the angle between two bonds given coordinates of their atoms - internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + internal static double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 firstLine = a - b; Vector3 secondLine = c - d; @@ -808,7 +808,7 @@ internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, V } // this method store atoms and bonds in proper lists: - private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, + private static void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, List doubleVec, List cycloexVec, int a1, List atomVec, int sphere, bool isBondInCycloex) { @@ -834,7 +834,7 @@ private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singl } // generic method for calculation of distance btw 2 atoms - internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + internal static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; @@ -845,7 +845,7 @@ internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) // given a double bond // this method returns a bond bonded to this double bond - internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) + internal static int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) { int nearestBond = -1; double distance = 0; @@ -873,7 +873,7 @@ internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bo // method which calculated distance btw an atom and the middle point of a bond // and returns distance and coordinates of middle point - internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) + internal static double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) { Vector3 middlePoint = theBond.Geometric3DCenter; Vector3 protonPoint = proton.Point3D.Value; @@ -897,13 +897,13 @@ internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBon /// The parameterType value public virtual object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } - } - public partial class RDFProtonDescriptor_GHR - { - private bool checkAromaticity { get; set; } = false; + } + public partial class RDFProtonDescriptorGHR + { + private bool CheckAromaticity { get; set; } = false; private IAtomContainer acold = null; private IRingSet varRingSet = null; private IChemObjectSet varAtomContainerSet = null; @@ -913,24 +913,24 @@ public partial class RDFProtonDescriptor_GHR /// /// Parameters are the proton position and a boolean ( if you need to detect aromaticity) /// - public virtual object[] Parameters + public virtual IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("RDFProtonDescriptor only expects one parameters"); + throw new CDKException($"{nameof(RDFProtonDescriptorGHR)} only expects one parameters"); } if (!(value[0] is bool)) { - throw new CDKException("The second parameter must be of type bool"); + throw new CDKException($"The second parameter must be of type {nameof(System.Boolean)}"); } - checkAromaticity = (bool)value[0]; + CheckAromaticity = (bool)value[0]; } get { // return the parameters as used for the descriptor calculation - return new object[] { checkAromaticity }; + return new object[] { CheckAromaticity }; } } @@ -939,7 +939,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult result = new ArrayResult(desc_length); for (int i = 0; i < desc_length; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } public virtual IDescriptorValue Calculate(IAtom atom, IAtomContainer varAtomContainerSet) @@ -954,7 +954,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer int atomPosition = atomContainer.Atoms.IndexOf(atom); IAtom clonedAtom = varAtomContainer.Atoms[atomPosition]; ArrayResult rdfProtonCalculatedValues = new ArrayResult(desc_length); - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return GetDummyDescriptorValue(new CDKException("Invalid atom specified")); } @@ -989,7 +989,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer return GetDummyDescriptorValue(ex1); } } - if (checkAromaticity) + if (CheckAromaticity) { try { @@ -1176,7 +1176,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atoms, bondsInCycloex)) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); } else { @@ -1186,7 +1186,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer // Others definitions - private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) + private static bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) { bool isBondNotRotatable = false; int counter = 0; @@ -1204,7 +1204,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai } else { - if (atom1.Symbol.Equals("H")) + if (string.Equals(atom1.Symbol, "H", StringComparison.Ordinal)) counter += 1; else counter += 0; @@ -1222,7 +1222,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai return isBondNotRotatable; } - private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) + private static bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) { bool isDoubleBondedToOxygen = false; var neighToCarbon = mol.GetConnectedAtoms(carbonAtom); @@ -1230,7 +1230,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb int counter = 0; foreach (var neighbour in neighToCarbon) { - if (neighbour.Symbol.Equals("O")) + if (string.Equals(neighbour.Symbol, "O", StringComparison.Ordinal)) { tmpBond = mol.GetBond(neighbour, carbonAtom); if (tmpBond.Order == BondOrder.Double) counter += 1; @@ -1242,7 +1242,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb // this method calculates the angle between two bonds given coordinates of their atoms - internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + internal static double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 firstLine = a - b; Vector3 secondLine = c - d; @@ -1252,7 +1252,7 @@ internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, V } // this method store atoms and bonds in proper lists: - private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, + private static void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, List doubleVec, List cycloexVec, int a1, List atomVec, int sphere, bool isBondInCycloex) { @@ -1278,7 +1278,7 @@ private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singl } // generic method for calculation of distance btw 2 atoms - internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + internal static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; @@ -1289,7 +1289,7 @@ internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) // given a double bond // this method returns a bond bonded to this double bond - internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) + internal static int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) { int nearestBond = -1; double distance = 0; @@ -1317,7 +1317,7 @@ internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bo // method which calculated distance btw an atom and the middle point of a bond // and returns distance and coordinates of middle point - internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) + internal static double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) { Vector3 middlePoint = theBond.Geometric3DCenter; Vector3 protonPoint = proton.Point3D.Value; @@ -1341,13 +1341,13 @@ internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBon /// The parameterType value public virtual object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } - } - public partial class RDFProtonDescriptor_GHR_topol - { - private bool checkAromaticity { get; set; } = false; + } + public partial class RDFProtonDescriptorGHRTopology + { + private bool CheckAromaticity { get; set; } = false; private IAtomContainer acold = null; private IRingSet varRingSet = null; private IChemObjectSet varAtomContainerSet = null; @@ -1357,24 +1357,24 @@ public partial class RDFProtonDescriptor_GHR_topol /// /// Parameters are the proton position and a boolean ( if you need to detect aromaticity) /// - public virtual object[] Parameters + public virtual IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("RDFProtonDescriptor only expects one parameters"); + throw new CDKException($"{nameof(RDFProtonDescriptorGHRTopology)} only expects one parameters"); } if (!(value[0] is bool)) { - throw new CDKException("The second parameter must be of type bool"); + throw new CDKException($"The second parameter must be of type {nameof(System.Boolean)}"); } - checkAromaticity = (bool)value[0]; + CheckAromaticity = (bool)value[0]; } get { // return the parameters as used for the descriptor calculation - return new object[] { checkAromaticity }; + return new object[] { CheckAromaticity }; } } @@ -1383,7 +1383,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult result = new ArrayResult(desc_length); for (int i = 0; i < desc_length; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } public virtual IDescriptorValue Calculate(IAtom atom, IAtomContainer varAtomContainerSet) @@ -1398,7 +1398,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer int atomPosition = atomContainer.Atoms.IndexOf(atom); IAtom clonedAtom = varAtomContainer.Atoms[atomPosition]; ArrayResult rdfProtonCalculatedValues = new ArrayResult(desc_length); - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return GetDummyDescriptorValue(new CDKException("Invalid atom specified")); } @@ -1433,7 +1433,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer return GetDummyDescriptorValue(ex1); } } - if (checkAromaticity) + if (CheckAromaticity) { try { @@ -1620,7 +1620,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atoms, bondsInCycloex)) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); } else { @@ -1630,7 +1630,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer // Others definitions - private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) + private static bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) { bool isBondNotRotatable = false; int counter = 0; @@ -1648,7 +1648,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai } else { - if (atom1.Symbol.Equals("H")) + if (string.Equals(atom1.Symbol, "H", StringComparison.Ordinal)) counter += 1; else counter += 0; @@ -1666,7 +1666,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai return isBondNotRotatable; } - private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) + private static bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) { bool isDoubleBondedToOxygen = false; var neighToCarbon = mol.GetConnectedAtoms(carbonAtom); @@ -1674,7 +1674,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb int counter = 0; foreach (var neighbour in neighToCarbon) { - if (neighbour.Symbol.Equals("O")) + if (string.Equals(neighbour.Symbol, "O", StringComparison.Ordinal)) { tmpBond = mol.GetBond(neighbour, carbonAtom); if (tmpBond.Order == BondOrder.Double) counter += 1; @@ -1686,7 +1686,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb // this method calculates the angle between two bonds given coordinates of their atoms - internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + internal static double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 firstLine = a - b; Vector3 secondLine = c - d; @@ -1696,7 +1696,7 @@ internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, V } // this method store atoms and bonds in proper lists: - private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, + private static void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, List doubleVec, List cycloexVec, int a1, List atomVec, int sphere, bool isBondInCycloex) { @@ -1722,7 +1722,7 @@ private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singl } // generic method for calculation of distance btw 2 atoms - internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + internal static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; @@ -1733,7 +1733,7 @@ internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) // given a double bond // this method returns a bond bonded to this double bond - internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) + internal static int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) { int nearestBond = -1; double distance = 0; @@ -1761,7 +1761,7 @@ internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bo // method which calculated distance btw an atom and the middle point of a bond // and returns distance and coordinates of middle point - internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) + internal static double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) { Vector3 middlePoint = theBond.Geometric3DCenter; Vector3 protonPoint = proton.Point3D.Value; @@ -1785,13 +1785,13 @@ internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBon /// The parameterType value public virtual object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } - } - public partial class RDFProtonDescriptor_GSR - { - private bool checkAromaticity { get; set; } = false; + } + public partial class RDFProtonDescriptorGSR + { + private bool CheckAromaticity { get; set; } = false; private IAtomContainer acold = null; private IRingSet varRingSet = null; private IChemObjectSet varAtomContainerSet = null; @@ -1801,24 +1801,24 @@ public partial class RDFProtonDescriptor_GSR /// /// Parameters are the proton position and a boolean ( if you need to detect aromaticity) /// - public virtual object[] Parameters + public virtual IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("RDFProtonDescriptor only expects one parameters"); + throw new CDKException($"{nameof(RDFProtonDescriptorGSR)} only expects one parameters"); } if (!(value[0] is bool)) { - throw new CDKException("The second parameter must be of type bool"); + throw new CDKException($"The second parameter must be of type {nameof(System.Boolean)}"); } - checkAromaticity = (bool)value[0]; + CheckAromaticity = (bool)value[0]; } get { // return the parameters as used for the descriptor calculation - return new object[] { checkAromaticity }; + return new object[] { CheckAromaticity }; } } @@ -1827,7 +1827,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult result = new ArrayResult(desc_length); for (int i = 0; i < desc_length; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } public virtual IDescriptorValue Calculate(IAtom atom, IAtomContainer varAtomContainerSet) @@ -1842,7 +1842,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer int atomPosition = atomContainer.Atoms.IndexOf(atom); IAtom clonedAtom = varAtomContainer.Atoms[atomPosition]; ArrayResult rdfProtonCalculatedValues = new ArrayResult(desc_length); - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { return GetDummyDescriptorValue(new CDKException("Invalid atom specified")); } @@ -1877,7 +1877,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer return GetDummyDescriptorValue(ex1); } } - if (checkAromaticity) + if (CheckAromaticity) { try { @@ -2064,7 +2064,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atoms, bondsInCycloex)) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, rdfProtonCalculatedValues, DescriptorNames); } else { @@ -2074,7 +2074,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer // Others definitions - private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) + private static bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContainer detected) { bool isBondNotRotatable = false; int counter = 0; @@ -2092,7 +2092,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai } else { - if (atom1.Symbol.Equals("H")) + if (string.Equals(atom1.Symbol, "H", StringComparison.Ordinal)) counter += 1; else counter += 0; @@ -2110,7 +2110,7 @@ private bool GetIfBondIsNotRotatable(IAtomContainer mol, IBond bond, IAtomContai return isBondNotRotatable; } - private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) + private static bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carbonAtom) { bool isDoubleBondedToOxygen = false; var neighToCarbon = mol.GetConnectedAtoms(carbonAtom); @@ -2118,7 +2118,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb int counter = 0; foreach (var neighbour in neighToCarbon) { - if (neighbour.Symbol.Equals("O")) + if (string.Equals(neighbour.Symbol, "O", StringComparison.Ordinal)) { tmpBond = mol.GetBond(neighbour, carbonAtom); if (tmpBond.Order == BondOrder.Double) counter += 1; @@ -2130,7 +2130,7 @@ private bool GetIfACarbonIsDoubleBondedToAnOxygen(IAtomContainer mol, IAtom carb // this method calculates the angle between two bonds given coordinates of their atoms - internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) + internal static double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, Vector3 d) { Vector3 firstLine = a - b; Vector3 secondLine = c - d; @@ -2140,7 +2140,7 @@ internal double CalculateAngleBetweenTwoLines(Vector3 a, Vector3 b, Vector3 c, V } // this method store atoms and bonds in proper lists: - private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, + private static void CheckAndStore(int bondToStore, BondOrder bondOrder, List singleVec, List doubleVec, List cycloexVec, int a1, List atomVec, int sphere, bool isBondInCycloex) { @@ -2166,7 +2166,7 @@ private void CheckAndStore(int bondToStore, BondOrder bondOrder, List singl } // generic method for calculation of distance btw 2 atoms - internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + internal static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; @@ -2177,7 +2177,7 @@ internal double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) // given a double bond // this method returns a bond bonded to this double bond - internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) + internal static int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bond) { int nearestBond = -1; double distance = 0; @@ -2205,7 +2205,7 @@ internal int GetNearestBondtoAGivenAtom(IAtomContainer mol, IAtom atom, IBond bo // method which calculated distance btw an atom and the middle point of a bond // and returns distance and coordinates of middle point - internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) + internal static double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBond) { Vector3 middlePoint = theBond.Geometric3DCenter; Vector3 protonPoint = proton.Point3D.Value; @@ -2229,8 +2229,8 @@ internal double[] CalculateDistanceBetweenAtomAndBond(IAtom proton, IBond theBon /// The parameterType value public virtual object GetParameterType(string name) { - if (name.Equals("checkAromaticity")) return true; + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) return true; return null; } - } + } } diff --git a/NCDK/QSAR/Descriptors/Atomic/AtomDegreeDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/AtomDegreeDescriptor.cs index 222e6b69..21de3587 100644 --- a/NCDK/QSAR/Descriptors/Atomic/AtomDegreeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/AtomDegreeDescriptor.cs @@ -51,8 +51,8 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.dictref qsar-descriptors:atomDegree public partial class AtomDegreeDescriptor : IAtomicDescriptor { - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomDegree", typeof(AtomDegreeDescriptor).FullName, "The Chemistry Development Kit"); @@ -60,7 +60,7 @@ public partial class AtomDegreeDescriptor : IAtomicDescriptor /// /// The parameters attribute of the AtomDegreeDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = new string[] { "aNeg" }; @@ -76,9 +76,10 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer contain var neighboors = container.GetConnectedAtoms(atom); foreach (var neighboor in neighboors) { - if (!neighboor.Symbol.Equals("H")) atomDegree += 1; + if (!string.Equals(neighboor.Symbol, "H", StringComparison.Ordinal)) + atomDegree += 1; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(atomDegree), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(atomDegree), DescriptorNames); } /// @@ -92,8 +93,6 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer contain /// /// Description of the Parameter /// An Object of class equal to that of the parameter being requested - public object GetParameterType(string name) => null; - - + public object GetParameterType(string name) => null; } } diff --git a/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationDescriptor.cs index 238b1851..8040df7b 100644 --- a/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationDescriptor.cs @@ -45,8 +45,8 @@ public partial class AtomHybridizationDescriptor : IAtomicDescriptor /// /// The specification attribute of the AtomHybridizationDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomHybridization", typeof(AtomHybridizationDescriptor).FullName, @@ -55,13 +55,13 @@ public partial class AtomHybridizationDescriptor : IAtomicDescriptor /// /// This descriptor does have any parameter. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = new string[] { "aHyb" }; private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(Hybridization.Unset), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(Hybridization.Unset), DescriptorNames, e); } /// @@ -89,7 +89,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContain } Hybridization atomHybridization = matched.Hybridization; var result = new Result(atomHybridization); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptor.cs index 1abbb191..c22366c4 100644 --- a/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptor.cs @@ -80,8 +80,8 @@ public AtomHybridizationVSEPRDescriptor() { } /// /// The specification attribute of the AtomHybridizationVSEPRDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomHybridizationVSEPR", typeof(AtomHybridizationVSEPRDescriptor).FullName, @@ -90,7 +90,7 @@ public AtomHybridizationVSEPRDescriptor() { } /// /// The parameters attribute of the AtomHybridizationVSEPRDescriptor object /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = new string[] { "hybr" }; @@ -109,28 +109,28 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContain } catch (CDKException) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(Hybridization.Unset), // does that work?? + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(Hybridization.Unset), // does that work?? DescriptorNames, new CDKException("Atom type was null")); } if (atomType == null) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(Hybridization.Unset), // does that work?? + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(Hybridization.Unset), // does that work?? DescriptorNames, new CDKException("Atom type was null")); } if (atomType.Hybridization.IsUnset()) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(Hybridization.Unset), // does that work?? + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(Hybridization.Unset), // does that work?? DescriptorNames, new CDKException("Hybridization was null")); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( atomType.Hybridization), DescriptorNames); } /// /// The parameterNames attribute of the AtomHybridizationVSEPRDescriptor object /// - public IReadOnlyList ParameterNames { get; } = new string[0]; + public IReadOnlyList ParameterNames { get; } = System.Array.Empty(); /// /// Gets the parameterType attribute of the AtomHybridizationVSEPRDescriptor object diff --git a/NCDK/QSAR/Descriptors/Atomic/AtomValenceDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/AtomValenceDescriptor.cs index b1b4d019..c1c671b9 100644 --- a/NCDK/QSAR/Descriptors/Atomic/AtomValenceDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/AtomValenceDescriptor.cs @@ -43,8 +43,8 @@ public AtomValenceDescriptor() { } /// /// The specification attribute of the AtomValenceDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomValence", typeof(AtomValenceDescriptor).FullName, "The Chemistry Development Kit"); @@ -52,7 +52,7 @@ public AtomValenceDescriptor() { } /// /// The parameters attribute of the VdWRadiusDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = new string[] { "val" }; @@ -65,7 +65,7 @@ public AtomValenceDescriptor() { } public DescriptorValue> Calculate(IAtom atom, IAtomContainer container) { int atomValence = AtomValenceTool.GetValence(atom); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(atomValence), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(atomValence), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/BondsToAtomDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/BondsToAtomDescriptor.cs index 661c7fb7..37c9f2ff 100644 --- a/NCDK/QSAR/Descriptors/Atomic/BondsToAtomDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/BondsToAtomDescriptor.cs @@ -57,8 +57,8 @@ public BondsToAtomDescriptor() { } /// /// The specification attribute of the BondsToAtomDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondsToAtom", typeof(BondsToAtomDescriptor).FullName, "The Chemistry Development Kit"); @@ -68,11 +68,11 @@ public BondsToAtomDescriptor() { } /// /// Description of the Exception /// The parameter is the position to focus - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("BondsToAtomDescriptor only expects one parameters"); } @@ -103,7 +103,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer contain // could be cached int bondsToAtom = new ShortestPaths(container, atom).GetDistanceTo(focus); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( bondsToAtom), DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs index cfe3bb23..2c2faaa5 100644 --- a/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs @@ -54,8 +54,8 @@ public partial class CovalentRadiusDescriptor : IAtomicDescriptor public CovalentRadiusDescriptor() { } /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#covalentradius", typeof(CovalentRadiusDescriptor).FullName, "The Chemistry Development Kit"); @@ -63,7 +63,7 @@ public CovalentRadiusDescriptor() { } /// /// The parameters attribute of the VdWRadiusDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = new string[] { "covalentRadius" }; @@ -83,7 +83,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont } catch (Exception exception) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, exception); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, exception); } double covalentradius; @@ -92,13 +92,13 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont string symbol = atom.Symbol; IAtomType type = factory.GetAtomType(symbol); covalentradius = type.CovalentRadius.Value; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( covalentradius), DescriptorNames); } catch (Exception exception) { Debug.WriteLine(exception); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( double.NaN), DescriptorNames, exception); } } diff --git a/NCDK/QSAR/Descriptors/Atomic/DistanceToAtomDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/DistanceToAtomDescriptor.cs index ab8b8a6f..1a5fa769 100644 --- a/NCDK/QSAR/Descriptors/Atomic/DistanceToAtomDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/DistanceToAtomDescriptor.cs @@ -58,8 +58,8 @@ public DistanceToAtomDescriptor() { } /// /// The specification attribute of the DistanceToAtomDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#distanceToAtom", typeof(DistanceToAtomDescriptor).FullName, "The Chemistry Development Kit"); @@ -68,11 +68,11 @@ public DistanceToAtomDescriptor() { } /// The parameters attribute of the DistanceToAtomDescriptor object /// /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("DistanceToAtomDescriptor only expects two parameters"); } @@ -104,14 +104,14 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont if (atom.Point3D == null || focus.Point3D == null) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( double.NaN), DescriptorNames, new CDKException( "Target or focus atom must have 3D coordinates.")); } distanceToAtom = CalculateDistanceBetweenTwoAtoms(atom, focus); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( distanceToAtom), DescriptorNames); } @@ -121,7 +121,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont /// The IAtom 1 /// The IAtom 2 /// distance between atom1 and atom2 - private double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + private static double CalculateDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; Vector3 firstPoint = atom1.Point3D.Value; diff --git a/NCDK/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptor.cs index 45619e03..43dc027b 100644 --- a/NCDK/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptor.cs @@ -49,21 +49,11 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.dictref qsar-descriptors:effectivePolarizability public partial class EffectiveAtomPolarizabilityDescriptor : IAtomicDescriptor { - private Polarizability pol; - - /// - /// Constructor for the EffectiveAtomPolarizabilityDescriptor object - /// - public EffectiveAtomPolarizabilityDescriptor() - { - pol = new Polarizability(); - } - /// /// The specification attribute of the EffectiveAtomPolarizabilityDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#effectivePolarizability", typeof(EffectiveAtomPolarizabilityDescriptor).FullName, "The Chemistry Development Kit"); @@ -71,7 +61,7 @@ public EffectiveAtomPolarizabilityDescriptor() /// /// The parameters attribute of the EffectiveAtomPolarizabilityDescriptor object /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = new string[] { "effAtomPol" }; @@ -96,7 +86,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) var originalFlag = atom.IsVisited; var originalBondOrderSum = atom.BondOrderSum; var originalMaxBondOrder = atom.MaxBondOrder; - polarizability = pol.CalculateGHEffectiveAtomPolarizability(ac, atom, 100, true); + polarizability = Polarizability.CalculateGHEffectiveAtomPolarizability(ac, atom, 100, true); // restore original props atom.AtomTypeName = originalAtomtypeName; atom.FormalNeighbourCount = originalNeighborCount; @@ -106,11 +96,11 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) atom.Hybridization = originalHybridization; atom.MaxBondOrder = originalMaxBondOrder; atom.BondOrderSum = originalBondOrderSum; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(polarizability), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(polarizability), DescriptorNames); } catch (Exception ex1) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, ex1); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, ex1); } } diff --git a/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs index 199c3b0b..af8fee25 100644 --- a/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs @@ -23,7 +23,9 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; +using System.Linq; using System.Text; namespace NCDK.QSAR.Descriptors.Atomic @@ -76,8 +78,8 @@ public IPAtomicHOSEDescriptor() /// /// The specification attribute of the IPAtomicHOSEDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#ionizationPotential", typeof(IPAtomicHOSEDescriptor).FullName, "The Chemistry Development Kit"); @@ -85,7 +87,7 @@ public IPAtomicHOSEDescriptor() /// /// The parameters attribute of the IPAtomicHOSEDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -111,13 +113,11 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(container); + LonePairElectronChecker.Saturate(container); } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( - double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } } @@ -130,21 +130,26 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont atom.MaxBondOrder = originalMaxBondOrder; atom.BondOrderSum = originalBondOrderSum; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(value), - NAMES); - + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(value), NAMES); } /// /// Looking if the Atom belongs to the halogen family. - /// + /// /// The IAtom /// True, if it belongs - /// - internal bool FamilyHalogen(IAtom atom) + internal static bool FamilyHalogen(IAtom atom) { - string symbol = atom.Symbol; - return symbol.Equals("F") || symbol.Equals("Cl") || symbol.Equals("Br") || symbol.Equals("I"); + switch (atom.Symbol) + { + case "F": + case "Cl": + case "Br": + case "I": + return true; + default: + return false; + } } /// @@ -168,8 +173,8 @@ class IPdb { IPAtomicHOSEDescriptor parent; - Dictionary> listGroup = new Dictionary>(); - Dictionary> listGroupS = new Dictionary>(); + private Dictionary> listGroup = new Dictionary>(); + private readonly Dictionary> listGroupS = new Dictionary>(); /// /// The constructor of the IPdb. @@ -193,7 +198,7 @@ public double ExtractIP(IAtomContainer container, IAtom atom) string nameS = ""; Dictionary hoseVSenergy = new Dictionary(); Dictionary hoseVSenergyS = new Dictionary(); - if (parent.FamilyHalogen(atom)) + if (FamilyHalogen(atom)) { name = "X_IP_HOSE.db"; nameS = "X_IP_HOSE_S.db"; @@ -228,7 +233,7 @@ public double ExtractIP(IAtomContainer container, IAtom atom) { hcg.GetSpheres(container, atom, spheres, true); var atoms = hcg.GetNodesInSphere(spheres); - if (atoms.Count != 0) + if (atoms.Any()) { exactSphere = spheres; hoseCode = hcg.GetHOSECode(container, atom, spheres, true); @@ -296,7 +301,7 @@ public double ExtractIP(IAtomContainer container, IAtom atom) /// /// The BufferedReader /// HashMap with the Hose vs energy attributes - private Dictionary ExtractAttributes(TextReader input) + private static Dictionary ExtractAttributes(TextReader input) { Dictionary hoseVSenergy = new Dictionary(); string line; @@ -305,10 +310,12 @@ private Dictionary ExtractAttributes(TextReader input) { while ((line = input.ReadLine()) != null) { - if (line.StartsWithChar('#')) continue; - List values = ExtractInfo(line); - if (values[1].Equals("")) continue; - hoseVSenergy[values[0]] = double.Parse(values[1]); + if (line.StartsWithChar('#')) + continue; + var values = ExtractInfo(line); + if (values[1].Length == 0) + continue; + hoseVSenergy[values[0]] = double.Parse(values[1], NumberFormatInfo.InvariantInfo); } } catch (IOException e) diff --git a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs index 47693467..770b673a 100644 --- a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs @@ -63,8 +63,8 @@ public InductiveAtomicHardnessDescriptor() { } /// The specification attribute of the InductiveAtomicHardnessDescriptor object /// /// The specification value - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomicHardness", typeof(InductiveAtomicHardnessDescriptor).FullName, "The Chemistry Development Kit"); @@ -72,13 +72,13 @@ public InductiveAtomicHardnessDescriptor() { } /// /// The parameters attribute of the InductiveAtomicHardnessDescripto object /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -156,11 +156,11 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) atomicHardness = 2 * atomicHardness; atomicHardness = atomicHardness * 0.172; atomicHardness = 1 / atomicHardness; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( atomicHardness), NAMES); } - private double CalculateSquareDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + private static double CalculateSquareDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; double tmp; @@ -174,7 +174,7 @@ private double CalculateSquareDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) /// /// The parameterNames attribute of the InductiveAtomicHardnessDescriptor object /// - public IReadOnlyList ParameterNames { get; } = new string[0]; + public IReadOnlyList ParameterNames { get; } = Array.Empty(); /// /// Gets the parameterType attribute of the InductiveAtomicHardnessDescriptor object diff --git a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs index e255e112..453e1fa7 100644 --- a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs @@ -62,8 +62,8 @@ public InductiveAtomicSoftnessDescriptor() { } /// /// The specification attribute of the InductiveAtomicSoftnessDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomicSoftness", typeof(InductiveAtomicSoftnessDescriptor).FullName, "The Chemistry Development Kit"); @@ -71,13 +71,13 @@ public InductiveAtomicSoftnessDescriptor() { } /// /// The parameters attribute of the InductiveAtomicSoftnessDescriptor object /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -153,10 +153,10 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) atomicSoftness = 2 * atomicSoftness; atomicSoftness = atomicSoftness * 0.172; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(atomicSoftness), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(atomicSoftness), NAMES); } - private double CalculateSquareDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) + private static double CalculateSquareDistanceBetweenTwoAtoms(IAtom atom1, IAtom atom2) { double distance; double tmp; diff --git a/NCDK/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptor.cs index 7e0b6561..b89c40a3 100644 --- a/NCDK/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptor.cs @@ -19,6 +19,7 @@ using NCDK.Aromaticities; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -63,8 +64,8 @@ public IsProtonInAromaticSystemDescriptor() { } /// /// The specification attribute of the IsProtonInAromaticSystemDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#isProtonInAromaticSystem", typeof(IsProtonInAromaticSystemDescriptor).FullName, "The Chemistry Development Kit"); @@ -73,11 +74,11 @@ public IsProtonInAromaticSystemDescriptor() { } /// The parameters attribute of the IsProtonInAromaticSystemDescriptor object /// /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("IsProtonInAromaticSystemDescriptor only expects two parameters"); } @@ -119,12 +120,12 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atomCon } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), NAMES, e); } } var neighboor = mol.GetConnectedAtoms(clonedAtom); IAtom neighbour0 = (IAtom)neighboor.First(); - if (atom.Symbol.Equals("H")) + if (string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { //Debug.WriteLine("aromatic proton"); if (neighbour0.IsAromatic) @@ -151,7 +152,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atomCon { isProtonInAromaticSystem = 0; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(isProtonInAromaticSystem), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(isProtonInAromaticSystem), NAMES); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptor.cs index e8fc5b1a..ad125474 100644 --- a/NCDK/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptor.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Aromaticities; using NCDK.Graphs.Invariant; using NCDK.QSAR.Results; @@ -25,13 +26,13 @@ namespace NCDK.QSAR.Descriptors.Atomic { /// - /// This class evaluates if a proton is joined to a conjugated system. - /// + /// This class evaluates if a proton is joined to a conjugated system. + /// /// - /// This descriptor uses these parameters: + /// This descriptor uses these parameters: /// /// NameDefaultDescription - /// checkAromaticityfalseTrue is the aromaticity has to be checked + /// checkAromaticityfalse is the aromaticity has to be checked /// /// // @author mfe4 @@ -47,15 +48,15 @@ public partial class IsProtonInConjugatedPiSystemDescriptor : IAtomicDescriptor private IChemObjectSet acSet = null; /// - /// Constructor for the IsProtonInConjugatedPiSystemDescriptor object + /// Constructor for the IsProtonInConjugatedPiSystemDescriptor object /// public IsProtonInConjugatedPiSystemDescriptor() { } /// /// The specification attribute of the IsProtonInConjugatedPiSystemDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#isProtonInConjugatedPiSystem", typeof(IsProtonInConjugatedPiSystemDescriptor).FullName, "The Chemistry Development Kit"); @@ -64,13 +65,13 @@ public IsProtonInConjugatedPiSystemDescriptor() { } /// The parameters attribute of the IsProtonInConjugatedPiSystemDescriptor object /// /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { - throw new CDKException("IsProtonInConjugatedPiSystemDescriptor only expects one parameters"); + throw new CDKException($"{typeof(IsProtonInConjugatedPiSystemDescriptor)} only expects one parameters"); } if (!(value[0] is bool)) { @@ -110,10 +111,10 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atomCo } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(false), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(false), NAMES, e); } } - if (atom.Symbol.Equals("H")) + if (string.Equals(atom.Symbol, "H", System.StringComparison.Ordinal)) { if (acold != clonedAtomContainer) { @@ -135,7 +136,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atomCo } } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( isProtonInPiSystem), NAMES); } diff --git a/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs index 4717d3ca..db6eb3c1 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs @@ -74,8 +74,8 @@ public PartialPiChargeDescriptor() /// /// The specification attribute of the PartialPiChargeDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#partialPiCharge", typeof(PartialPiChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -100,25 +100,25 @@ public PartialPiChargeDescriptor() /// /// /// Description of the Exception - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 3) + if (value.Count > 3) throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); if (!(value[0] is int)) throw new CDKException("The parameter must be of type int"); maxIterations = (int)value[0]; - if (value.Length > 1 && value[1] != null) + if (value.Count > 1 && value[1] != null) { if (!(value[1] is bool)) throw new CDKException("The parameter must be of type bool"); lpeChecker = (bool)value[1]; } - if (value.Length > 2 && value[2] != null) + if (value.Count > 2 && value[2] != null) { if (!(value[2] is int)) throw new CDKException("The parameter must be of type int"); @@ -136,7 +136,7 @@ public object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -170,10 +170,9 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) if (lpeChecker) { - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); try { - lpcheck.Saturate(ac); + LonePairElectronChecker.Saturate(ac); } catch (CDKException e) { @@ -208,7 +207,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) atom.MaxBondOrder = originalMaxBondOrder; atom.BondOrderSum = originalBondOrderSum; - return GetCachedDescriptorValue(atom) != null ? new DescriptorValue>(_Specification, ParameterNames, + return GetCachedDescriptorValue(atom) != null ? new DescriptorValue>(specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(atom), NAMES) : null; } @@ -224,9 +223,9 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) /// The parameterType value public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; - if ("lpeChecker".Equals(name)) return true; - if ("maxResonStruc".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) return int.MaxValue; + if (string.Equals("lpeChecker", name, StringComparison.Ordinal)) return true; + if (string.Equals("maxResonStruc", name, StringComparison.Ordinal)) return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptor.cs index b8bb6ccd..0317ca52 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptor.cs @@ -62,8 +62,8 @@ public PartialSigmaChargeDescriptor() /// /// The specification attribute of the PartialSigmaChargeDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#partialSigmaCharge", typeof(PartialSigmaChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -73,11 +73,11 @@ public PartialSigmaChargeDescriptor() /// Number of maximum iterations /// /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("PartialSigmaChargeDescriptor only expects one parameter"); } @@ -124,12 +124,12 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) } catch (Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } } atom.Charge = originalCharge; - return GetCachedDescriptorValue(atom) != null ? new DescriptorValue>(_Specification, ParameterNames, + return GetCachedDescriptorValue(atom) != null ? new DescriptorValue>(specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(atom), NAMES) : null; } @@ -145,7 +145,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) /// The parameterType value public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Atomic/PartialTChargeMMFF94Descriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PartialTChargeMMFF94Descriptor.cs index 432a9314..8cdbf09d 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PartialTChargeMMFF94Descriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PartialTChargeMMFF94Descriptor.cs @@ -16,7 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.ForceField.MMFF; +using NCDK.ForceFields; using NCDK.QSAR.Results; using System; using System.Collections.Generic; @@ -46,7 +46,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public partial class PartialTChargeMMFF94Descriptor : IAtomicDescriptor { private static readonly string[] NAMES = { "partialTCMMFF94" }; - private static readonly string CHARGE_CACHE = "mmff.qsar.charge.cache"; + private const string Key_ChargeCache = "mmff.qsar.charge.cache"; private Mmff mmff; /// @@ -60,8 +60,8 @@ public PartialTChargeMMFF94Descriptor() /// /// The specification attribute of the PartialTChargeMMFF94Descriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#partialTChargeMMFF94", typeof(PartialTChargeMMFF94Descriptor).FullName, "The Chemistry Development Kit"); @@ -69,7 +69,7 @@ public PartialTChargeMMFF94Descriptor() /// /// The parameters attribute of the PartialTChargeMMFF94Descriptor object /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -83,15 +83,15 @@ public PartialTChargeMMFF94Descriptor() /// partial charge of parameter atom public DescriptorValue> Calculate(IAtom atom, IAtomContainer org) { - if (atom.GetProperty(CHARGE_CACHE) == null) + if (atom.GetProperty(Key_ChargeCache) == null) { IAtomContainer copy = (IAtomContainer)org.Clone(); foreach (var a in org.Atoms) { if (a.ImplicitHydrogenCount == null || a.ImplicitHydrogenCount != 0) { - Trace.TraceError("Hydrogens must be explict for MMFF charge calculation"); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + Trace.TraceError("Hydrogens must be explicit for MMFF charge calculation"); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES); } } @@ -104,14 +104,14 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer org) // cache charges for (int i = 0; i < org.Atoms.Count; i++) { - org.Atoms[i].SetProperty(CHARGE_CACHE, copy.Atoms[i].Charge.Value); + org.Atoms[i].SetProperty(Key_ChargeCache, copy.Atoms[i].Charge.Value); } } - return new DescriptorValue>(_Specification, + return new DescriptorValue>(specification, ParameterNames, Parameters, - new Result(atom.GetProperty(CHARGE_CACHE)), + new Result(atom.GetProperty(Key_ChargeCache)), NAMES); } diff --git a/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs index c9eed6b9..6f5d63ff 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs @@ -73,8 +73,8 @@ public PartialTChargePEOEDescriptor() /// /// The specification attribute of the PartialTChargePEOEDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#PartialTChargePEOE", typeof(PartialTChargePEOEDescriptor).FullName, "The Chemistry Development Kit"); @@ -82,22 +82,25 @@ public PartialTChargePEOEDescriptor() /// /// The parameters attribute of the PartialTChargePEOEDescriptor object /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 3) throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); + if (value.Count > 3) + throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); + + if (!(value[0] is int)) + throw new CDKException("The parameter must be of type int"); - if (!(value[0] is int)) throw new CDKException("The parameter must be of type int"); maxIterations = (int)value[0]; - if (value.Length > 1 && value[1] != null) + if (value.Count > 1 && value[1] != null) { if (!(value[1] is bool)) throw new CDKException("The parameter must be of type bool"); lpeChecker = (bool)value[1]; } - if (value.Length > 2 && value[2] != null) + if (value.Count > 2 && value[2] != null) { if (!(value[2] is int)) throw new CDKException("The parameter must be of type int"); maxResonStruc = (int)value[2]; @@ -137,20 +140,22 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) } catch (CDKException e) { - new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); +#pragma warning disable CA1806 // Do not ignore method results + new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); +#pragma warning restore CA1806 // Do not ignore method results } if (lpeChecker) { - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); try { - lpcheck.Saturate(ac); + LonePairElectronChecker.Saturate(ac); } catch (CDKException e) { - new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( - double.NaN), NAMES, e); +#pragma warning disable CA1806 // Do not ignore method results + new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); +#pragma warning restore CA1806 // Do not ignore method results } } @@ -172,7 +177,9 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) } catch (Exception e) { - new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); +#pragma warning disable CA1806 // Do not ignore method results + new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); +#pragma warning restore CA1806 // Do not ignore method results } } // restore original props @@ -184,7 +191,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) atom.MaxBondOrder = originalMaxBondOrder; atom.BondOrderSum = originalBondOrderSum; - return GetCachedDescriptorValue(atom) != null ? new DescriptorValue>(_Specification, ParameterNames, + return GetCachedDescriptorValue(atom) != null ? new DescriptorValue>(specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(atom), NAMES) : null; } @@ -200,9 +207,9 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) /// An Object of class equal to that of the parameter being requested public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; - if ("lpeChecker".Equals(name)) return true; - if ("maxResonStruc".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) return int.MaxValue; + if (string.Equals("lpeChecker", name, StringComparison.Ordinal)) return true; + if (string.Equals("maxResonStruc", name, StringComparison.Ordinal)) return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptor.cs index 87020c3b..8cb2f56e 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptor.cs @@ -42,65 +42,54 @@ namespace NCDK.QSAR.Descriptors.Atomic public partial class PeriodicTablePositionDescriptor : IAtomicDescriptor { private static readonly string[] NAMES = { "periodicTablePosition" }; - public IDictionary periodicTable; - - /// - /// Constructor for the PeriodicTablePositionDescriptor object - /// - public PeriodicTablePositionDescriptor() + private static readonly IDictionary periodicTable = new Dictionary { - if (periodicTable == null) - { - periodicTable = new Dictionary - { - ["H"] = 1, - ["Li"] = 2, - ["Be"] = 2, - ["B"] = 2, - ["C"] = 2, - ["N"] = 2, - ["O"] = 2, - ["F"] = 2, - ["Na"] = 3, - ["Mg"] = 3, - ["Al"] = 3, - ["Si"] = 3, - ["P"] = 3, - ["S"] = 3, - ["Cl"] = 3, - ["K"] = 4, - ["Ca"] = 4, - ["Ga"] = 4, - ["Ge"] = 4, - ["As"] = 4, - ["Se"] = 4, - ["Br"] = 4, - ["Rb"] = 5, - ["Sr"] = 5, - ["In"] = 5, - ["Sn"] = 5, - ["Sb"] = 5, - ["Te"] = 5, - ["I"] = 5, - ["Cs"] = 6, - ["Ba"] = 6, - ["Tl"] = 6, - ["Pb"] = 6, - ["Bi"] = 6, - ["Po"] = 6, - ["At"] = 6, - ["Fr"] = 7, - ["Ra"] = 7 - }; - } - } + ["H"] = 1, + ["Li"] = 2, + ["Be"] = 2, + ["B"] = 2, + ["C"] = 2, + ["N"] = 2, + ["O"] = 2, + ["F"] = 2, + ["Na"] = 3, + ["Mg"] = 3, + ["Al"] = 3, + ["Si"] = 3, + ["P"] = 3, + ["S"] = 3, + ["Cl"] = 3, + ["K"] = 4, + ["Ca"] = 4, + ["Ga"] = 4, + ["Ge"] = 4, + ["As"] = 4, + ["Se"] = 4, + ["Br"] = 4, + ["Rb"] = 5, + ["Sr"] = 5, + ["In"] = 5, + ["Sn"] = 5, + ["Sb"] = 5, + ["Te"] = 5, + ["I"] = 5, + ["Cs"] = 6, + ["Ba"] = 6, + ["Tl"] = 6, + ["Pb"] = 6, + ["Bi"] = 6, + ["Po"] = 6, + ["At"] = 6, + ["Fr"] = 7, + ["Ra"] = 7 + }; /// /// The specification attribute of the PeriodicTablePositionDescriptor object /// /// The specification value - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#period", typeof(PeriodicTablePositionDescriptor).FullName, "The Chemistry Development Kit"); @@ -108,7 +97,7 @@ public PeriodicTablePositionDescriptor() /// /// The parameters attribute of the PeriodicTablePositionDescriptor object /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -123,7 +112,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer contain int period; string symbol = atom.Symbol; period = periodicTable[symbol]; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(period), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(period), NAMES); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs index b51b43d9..239e417c 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs @@ -20,6 +20,7 @@ using NCDK.QSAR.Results; using NCDK.Tools; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.QSAR.Descriptors.Atomic @@ -65,8 +66,8 @@ public PiElectronegativityDescriptor() /// /// Gets the specification attribute of the PiElectronegativityDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#piElectronegativity", typeof(PiElectronegativityDescriptor).FullName, "The Chemistry Development Kit"); @@ -88,22 +89,22 @@ public PiElectronegativityDescriptor() /// /// /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 3) throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); - + if (value.Count > 3) throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); if (!(value[0] is int)) throw new CDKException("The parameter must be of type int"); + maxIterations = (int)value[0]; - if (value.Length > 1 && value[1] != null) + if (value.Count > 1 && value[1] != null) { if (!(value[1] is bool)) throw new CDKException("The parameter must be of type bool"); lpeChecker = (bool)value[1]; } - if (value.Length > 2 && value[2] != null) + if (value.Count > 2 && value[2] != null) { if (!(value[2] is int)) throw new CDKException("The parameter must be of type int"); maxResonStruc = (int)value[2]; @@ -135,14 +136,13 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atom AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(clone); if (lpeChecker) { - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(atomContainer); + LonePairElectronChecker.Saturate(atomContainer); } localAtom = clone.Atoms[atomContainer.Atoms.IndexOf(atom)]; } catch (CDKException) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, null); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, null); } if (maxIterations != -1 && maxIterations != 0) electronegativity.MaxIterations = maxIterations; @@ -150,7 +150,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atom double result = electronegativity.CalculatePiElectronegativity(clone, localAtom); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(result), + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(result), NAMES); } @@ -166,9 +166,12 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atom /// The parameterType value public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; - if ("lpeChecker".Equals(name)) return true; - if ("maxResonStruc".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) + return int.MaxValue; + if (string.Equals("lpeChecker", name, StringComparison.Ordinal)) + return true; + if (string.Equals("maxResonStruc", name, StringComparison.Ordinal)) + return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs index b4ce0b8d..4c7b5625 100644 --- a/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -66,8 +67,8 @@ public ProtonAffinityHOSEDescriptor() /// /// The specification attribute of the ProtonAffinityDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#ionizationPotential", typeof(ProtonAffinityHOSEDescriptor).FullName, "The Chemistry Development Kit"); @@ -75,7 +76,7 @@ public ProtonAffinityHOSEDescriptor() /// /// The parameters attribute of the ProtonAffinityDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -99,16 +100,15 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont atom = container.Atoms[i]; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(container); + LonePairElectronChecker.Saturate(container); } catch (CDKException) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, null); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, null); } value = db.ExtractAffinity(container, atom); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(value), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(value), NAMES); } /// @@ -116,10 +116,19 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont /// /// The IAtom /// True, if it belongs - private bool FamilyHalogen(IAtom atom) + internal static bool FamilyHalogen(IAtom atom) { string symbol = atom.Symbol; - return symbol.Equals("F") || symbol.Equals("Cl") || symbol.Equals("Br") || symbol.Equals("I"); + switch (symbol) + { + case "F": + case "Cl": + case "Br": + case "I": + return true; + default: + return false; + } } /// @@ -167,7 +176,7 @@ public double ExtractAffinity(IAtomContainer container, IAtom atom) Dictionary hoseVSenergy = new Dictionary(); Dictionary hoseVSenergyS = new Dictionary(); - if (parent.FamilyHalogen(atom)) + if (FamilyHalogen(atom)) { name = "X_AffiProton_HOSE.db"; nameS = "X_AffiProton_HOSE_S.db"; @@ -200,8 +209,8 @@ public double ExtractAffinity(IAtomContainer container, IAtom atom) for (int spheres = parent.maxSpheresToUse; spheres > 0; spheres--) { hcg.GetSpheres(container, atom, spheres, true); - var atoms = hcg.GetNodesInSphere(spheres); - if (atoms.Count != 0) + var atoms = hcg.GetNodesInSphere(spheres); + if (atoms.Any()) { exactSphere = spheres; hoseCode = hcg.GetHOSECode(container, atom, spheres, true); @@ -269,7 +278,7 @@ public double ExtractAffinity(IAtomContainer container, IAtom atom) /// /// The BufferedReader /// HashMap with the Hose vs energy attributes - private Dictionary ExtractAttributes(TextReader input) + private static Dictionary ExtractAttributes(TextReader input) { Dictionary hoseVSenergy = new Dictionary(); string line; @@ -281,7 +290,7 @@ private Dictionary ExtractAttributes(TextReader input) if (line.StartsWithChar('#')) continue; List values = ExtractInfo(line); if (!values[1].Any()) continue; - hoseVSenergy[values[0]] = double.Parse(values[1]); + hoseVSenergy[values[0]] = double.Parse(values[1], NumberFormatInfo.InvariantInfo); } } catch (IOException e) diff --git a/NCDK/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptor.cs index 68a92112..e525e2f6 100644 --- a/NCDK/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptor.cs @@ -52,8 +52,8 @@ public ProtonTotalPartialChargeDescriptor() { } /// /// The specification attribute of the ProtonTotalPartialChargeDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#protonPartialCharge", typeof(ProtonTotalPartialChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -61,7 +61,7 @@ public ProtonTotalPartialChargeDescriptor() { } /// /// The parameters attribute of the ProtonTotalPartialChargeDescriptor /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { get; } = MakeDescriptorNames(); private static string[] MakeDescriptorNames() @@ -79,7 +79,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult result = new ArrayResult(MAX_PROTON_COUNT); for (int i = 0; i < neighboors.Count + 1; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } /// @@ -122,7 +122,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer int hydrogenNeighbors = 0; foreach (var neighboor in neighboors) { - if (neighboor.Symbol.Equals("H")) + if (string.Equals(neighboor.Symbol, "H", StringComparison.Ordinal)) { hydrogenNeighbors++; protonPartialCharge.Add(neighboor.Charge.Value); @@ -132,7 +132,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer for (int i = 0; i < remainder; i++) protonPartialCharge.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, protonPartialCharge, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, protonPartialCharge, DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3R.cs b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3R.cs index abaa0c90..545721c4 100644 --- a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3R.cs +++ b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3R.cs @@ -44,14 +44,14 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.githash // @cdk.dictref qsar-descriptors:rdfProtonCalculatedValues // @cdk.bug 1632419 - public partial class RDFProtonDescriptor_G3R : IAtomicDescriptor + public partial class RDFProtonDescriptorG3R : IAtomicDescriptor { private const int desc_length = 13; /// /// Constructor for the RDFProtonDescriptor object /// - public RDFProtonDescriptor_G3R() + public RDFProtonDescriptorG3R() { names = new string[desc_length]; for (int i = 0; i < desc_length; i++) @@ -64,18 +64,17 @@ public RDFProtonDescriptor_G3R() public IReadOnlyList DescriptorNames => names; /// - /// Gets the specification attribute of the RDFProtonDescriptor_G3R object + /// Gets the specification attribute of the RDFProtonDescriptorG3R object /// /// The specification value - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification __Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rdfProtonCalculatedValues", - typeof(RDFProtonDescriptor_G3R).FullName, + typeof(RDFProtonDescriptorG3R).FullName, "The Chemistry Development Kit"); - private DescriptorSpecification _Specification => __Specification; - private bool MakeDescriptorLastStage( + private static bool MakeDescriptorLastStage( ArrayResult rdfProtonCalculatedValues, IAtom atom, IAtom clonedAtom, diff --git a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDR.cs b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDR.cs index ca48c0df..9068d42c 100644 --- a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDR.cs +++ b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDR.cs @@ -45,14 +45,14 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.githash // @cdk.dictref qsar-descriptors:rdfProtonCalculatedValues // @cdk.bug 1632419 - public partial class RDFProtonDescriptor_GDR : IAtomicDescriptor + public partial class RDFProtonDescriptorGDR : IAtomicDescriptor { private const int desc_length = 7; /// /// Constructor for the RDFProtonDescriptor object /// - public RDFProtonDescriptor_GDR() + public RDFProtonDescriptorGDR() { names = new string[desc_length]; for (int i = 0; i < desc_length; i++) @@ -65,16 +65,15 @@ public RDFProtonDescriptor_GDR() public IReadOnlyList DescriptorNames => names; /// - /// The specification attribute of the RDFProtonDescriptor_GDR object + /// The specification attribute of the RDFProtonDescriptorGDR object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification __Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rdfProtonCalculatedValues", - typeof(RDFProtonDescriptor_GDR).FullName, "The Chemistry Development Kit"); - private DescriptorSpecification _Specification => __Specification; + typeof(RDFProtonDescriptorGDR).FullName, "The Chemistry Development Kit"); - private bool MakeDescriptorLastStage( + private static bool MakeDescriptorLastStage( ArrayResult rdfProtonCalculatedValues, IAtom atom, IAtom clonedAtom, diff --git a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR.cs b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR.cs index 1b94835c..59a8cc36 100644 --- a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR.cs +++ b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR.cs @@ -44,14 +44,14 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.githash // @cdk.dictref qsar-descriptors:rdfProtonCalculatedValues // @cdk.bug 1632419 - public partial class RDFProtonDescriptor_GHR : IAtomicDescriptor + public partial class RDFProtonDescriptorGHR : IAtomicDescriptor { private const int desc_length = 15; /// /// Constructor for the RDFProtonDescriptor object /// - public RDFProtonDescriptor_GHR() + public RDFProtonDescriptorGHR() { names = new string[desc_length]; for (int i = 0; i < desc_length; i++) @@ -64,17 +64,16 @@ public RDFProtonDescriptor_GHR() public IReadOnlyList DescriptorNames => names; /// - /// The specification attribute of the RDFProtonDescriptor_GHR object + /// The specification attribute of the RDFProtonDescriptorGHR object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification __Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rdfProtonCalculatedValues", - typeof(RDFProtonDescriptor_GHR).FullName, + typeof(RDFProtonDescriptorGHR).FullName, "The Chemistry Development Kit"); - private DescriptorSpecification _Specification => __Specification; - private bool MakeDescriptorLastStage( + private static bool MakeDescriptorLastStage( ArrayResult rdfProtonCalculatedValues, IAtom atom, IAtom clonedAtom, diff --git a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topol.cs b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topol.cs index 69154e73..0d87e730 100644 --- a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topol.cs +++ b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topol.cs @@ -44,11 +44,11 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.githash // @cdk.dictref qsar-descriptors:rdfProtonCalculatedValues // @cdk.bug 1632419 - public partial class RDFProtonDescriptor_GHR_topol : IAtomicDescriptor + public partial class RDFProtonDescriptorGHRTopology : IAtomicDescriptor { private const int desc_length = 15; - public RDFProtonDescriptor_GHR_topol() + public RDFProtonDescriptorGHRTopology() { names = new string[desc_length]; for (int i = 0; i < desc_length; i++) @@ -61,16 +61,15 @@ public RDFProtonDescriptor_GHR_topol() public IReadOnlyList DescriptorNames => names; /// - /// The specification attribute of the RDFProtonDescriptor_GHR_topol object + /// The specification attribute of the RDFProtonDescriptorGHRTopology object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification __Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rdfProtonCalculatedValues", - typeof(RDFProtonDescriptor_GHR_topol).FullName, "The Chemistry Development Kit"); - private DescriptorSpecification _Specification => __Specification; + typeof(RDFProtonDescriptorGHRTopology).FullName, "The Chemistry Development Kit"); - private bool MakeDescriptorLastStage( + private static bool MakeDescriptorLastStage( ArrayResult rdfProtonCalculatedValues, IAtom atom, IAtom clonedAtom, diff --git a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSR.cs b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSR.cs index 89e1cb46..75666a63 100644 --- a/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSR.cs +++ b/NCDK/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSR.cs @@ -44,11 +44,11 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.githash // @cdk.dictref qsar-descriptors:rdfProtonCalculatedValues // @cdk.bug 1632419 - public partial class RDFProtonDescriptor_GSR : IAtomicDescriptor + public partial class RDFProtonDescriptorGSR : IAtomicDescriptor { private const int desc_length = 7; - public RDFProtonDescriptor_GSR() + public RDFProtonDescriptorGSR() { names = new string[desc_length]; for (int i = 0; i < desc_length; i++) @@ -61,17 +61,16 @@ public RDFProtonDescriptor_GSR() public IReadOnlyList DescriptorNames => names; /// - /// The specification attribute of the RDFProtonDescriptor_GSR object + /// The specification attribute of the RDFProtonDescriptorGSR object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification __Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rdfProtonCalculatedValues", - typeof(RDFProtonDescriptor_GSR).FullName, + typeof(RDFProtonDescriptorGSR).FullName, "The Chemistry Development Kit"); - private DescriptorSpecification _Specification => __Specification; - private bool MakeDescriptorLastStage( + private static bool MakeDescriptorLastStage( ArrayResult rdfProtonCalculatedValues, IAtom atom, IAtom clonedAtom, diff --git a/NCDK/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptor.cs index 420d14cb..f2791246 100644 --- a/NCDK/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptor.cs @@ -65,8 +65,8 @@ public SigmaElectronegativityDescriptor() /// /// The specification attribute of the SigmaElectronegativityDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#sigmaElectronegativity", typeof(SigmaElectronegativityDescriptor).FullName, @@ -82,11 +82,11 @@ public SigmaElectronegativityDescriptor() /// /// /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("SigmaElectronegativityDescriptor only expects one parameter"); } @@ -94,7 +94,9 @@ public object[] Parameters { throw new CDKException("The parameter must be of type int"); } - if (value.Length == 0) return; + if (value.Count == 0) + return; + maxIterations = (int)value[0]; } get @@ -125,14 +127,14 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } if (maxIterations != -1 && maxIterations != 0) electronegativity.MaxIterations = maxIterations; double result = electronegativity.CalculateSigmaElectronegativity(clone, localAtom); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(result), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(result), NAMES); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptor.cs index fdd9928d..b0fc468a 100644 --- a/NCDK/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptor.cs @@ -48,21 +48,11 @@ public partial class StabilizationPlusChargeDescriptor : IAtomicDescriptor { private static readonly string[] NAMES = { "stabilPlusC" }; - private StabilizationCharges stabil; - - /// - /// Constructor for the StabilizationPlusChargeDescriptor object - /// - public StabilizationPlusChargeDescriptor() - { - stabil = new StabilizationCharges(); - } - /// /// The specification attribute of the StabilizationPlusChargeDescriptor object /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#stabilizationPlusCharge", typeof(StabilizationPlusChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -78,7 +68,7 @@ public StabilizationPlusChargeDescriptor() /// /// /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -101,12 +91,12 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } - double result = stabil.CalculatePositive(clone, localAtom); + double result = StabilizationCharges.CalculatePositive(clone, localAtom); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(result), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(result), NAMES); } /// diff --git a/NCDK/QSAR/Descriptors/Atomic/VdWRadiusDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/VdWRadiusDescriptor.cs index 77615d30..846e1562 100644 --- a/NCDK/QSAR/Descriptors/Atomic/VdWRadiusDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/VdWRadiusDescriptor.cs @@ -73,8 +73,8 @@ public VdWRadiusDescriptor() { } /// /// /// An object containing the descriptor specification - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#vdwradius", typeof(VdWRadiusDescriptor).FullName, "The Chemistry Development Kit"); @@ -82,7 +82,7 @@ public VdWRadiusDescriptor() { } /// /// The parameters attribute of the VdWRadiusDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -95,7 +95,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont { string symbol = atom.Symbol; double vdwradius = PeriodicTable.GetVdwRadius(symbol).Value; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(vdwradius), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(vdwradius), NAMES); } /// diff --git a/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt b/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt index 9906c878..fd4077ef 100644 --- a/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt +++ b/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt @@ -12,7 +12,7 @@ // retrieved one by one. // @cdk.module qsar // @cdk.githash - + using NCDK.QSAR.Results; using System.Collections.Generic; @@ -20,21 +20,21 @@ namespace NCDK.QSAR.Descriptors.Bonds { <# var fn = Path.Combine(new FileInfo(this.Host.TemplateFile).Directory.Parent.Parent.FullName, "IBondDescriptor"); - using (var reader = new StreamReader(fn)) - { - string line; - while ((line = reader.ReadLine()) != null) - { - if (line.Length > 0 && line[0] == '#') - continue; - line = line.Trim(); - if (string.IsNullOrEmpty(line)) - continue; - var cIndex = line.LastIndexOf("."); - var className = line.Substring(cIndex + 1); + using (var reader = new StreamReader(fn)) + { + string line; + while ((line = reader.ReadLine()) != null) + { + if (line.Length > 0 && line[0] == '#') + continue; + line = line.Trim(); + if (string.IsNullOrEmpty(line)) + continue; + var cIndex = line.LastIndexOf("."); + var className = line.Substring(cIndex + 1); #> - public partial class <#=className#> - { + public partial class <#=className#> + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; @@ -73,9 +73,9 @@ namespace NCDK.QSAR.Descriptors.Bonds if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -87,9 +87,9 @@ namespace NCDK.QSAR.Descriptors.Bonds IDescriptorValue IBondDescriptor.Calculate(IBond bond, IAtomContainer atomContainer) => Calculate(bond, atomContainer); - } + } <# - } - } + } + } #> } diff --git a/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt.cs b/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt.cs index 33f1987f..bf7556a1 100644 --- a/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt.cs +++ b/NCDK/QSAR/Descriptors/Bonds/$BondDescriptor.tt.cs @@ -5,14 +5,14 @@ // retrieved one by one. // @cdk.module qsar // @cdk.githash - + using NCDK.QSAR.Results; using System.Collections.Generic; namespace NCDK.QSAR.Descriptors.Bonds { - public partial class BondSigmaElectronegativityDescriptor - { + public partial class BondSigmaElectronegativityDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; @@ -51,9 +51,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -65,9 +65,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript IDescriptorValue IBondDescriptor.Calculate(IBond bond, IAtomContainer atomContainer) => Calculate(bond, atomContainer); - } - public partial class BondPartialTChargeDescriptor - { + } + public partial class BondPartialTChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; @@ -106,9 +106,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -120,9 +120,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript IDescriptorValue IBondDescriptor.Calculate(IBond bond, IAtomContainer atomContainer) => Calculate(bond, atomContainer); - } - public partial class BondPartialSigmaChargeDescriptor - { + } + public partial class BondPartialSigmaChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; @@ -161,9 +161,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -175,9 +175,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript IDescriptorValue IBondDescriptor.Calculate(IBond bond, IAtomContainer atomContainer) => Calculate(bond, atomContainer); - } - public partial class BondPartialPiChargeDescriptor - { + } + public partial class BondPartialPiChargeDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; @@ -216,9 +216,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -230,9 +230,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript IDescriptorValue IBondDescriptor.Calculate(IBond bond, IAtomContainer atomContainer) => Calculate(bond, atomContainer); - } - public partial class AtomicNumberDifferenceDescriptor - { + } + public partial class AtomicNumberDifferenceDescriptor + { private const string PreviousAtomContainer = "previousAtomContainer"; private IDictionary cachedDescriptorValues = null; @@ -271,9 +271,9 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript if (cachedDescriptorValues == null) { cachedDescriptorValues = new Dictionary() - { - [PreviousAtomContainer] = container, - }; + { + [PreviousAtomContainer] = container, + }; } else if (cachedDescriptorValues[PreviousAtomContainer] != container) { @@ -285,5 +285,5 @@ public void CacheDescriptorValue(IBond bond, IAtomContainer container, IDescript IDescriptorValue IBondDescriptor.Calculate(IBond bond, IAtomContainer atomContainer) => Calculate(bond, atomContainer); - } + } } diff --git a/NCDK/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptor.cs index 89ab0878..55d6a200 100644 --- a/NCDK/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptor.cs @@ -45,13 +45,13 @@ public AtomicNumberDifferenceDescriptor() { } - private void EnsureIsotopeFactory() + private static void EnsureIsotopeFactory() { if (factory == null) { try { - factory = Isotopes.Instance; + factory = BODRIsotopeFactory.Instance; } catch (IOException e) { @@ -61,13 +61,13 @@ private void EnsureIsotopeFactory() } } - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondAtomicNumberImbalance", typeof(AtomicNumberDifferenceDescriptor).FullName, "The Chemistry Development Kit"); - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames => NAMES; @@ -76,13 +76,13 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) EnsureIsotopeFactory(); if (bond.Atoms.Count != 2) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( double.NaN), NAMES, new CDKException("Only 2-center bonds are considered")); } IAtom[] atoms = BondManipulator.GetAtomArray(bond); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( Math.Abs(factory.GetElement(atoms[0].Symbol).AtomicNumber.Value - factory.GetElement(atoms[1].Symbol).AtomicNumber.Value)), NAMES); } diff --git a/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs index 359e29d5..a08dd055 100644 --- a/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs @@ -77,8 +77,8 @@ public BondPartialPiChargeDescriptor() /// /// The specification attribute of the BondPartialPiChargeDescriptor object. /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondPartialPiCharge", typeof(BondPartialPiChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -89,25 +89,25 @@ public BondPartialPiChargeDescriptor() /// /// This descriptor does have any parameter. /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 3) + if (value.Count > 3) throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); if (!(value[0] is int)) throw new CDKException("The parameter must be of type int"); maxIterations = (int)value[0]; - if (value.Length > 1 && value[1] != null) + if (value.Count > 1 && value[1] != null) { if (!(value[1] is bool)) throw new CDKException("The parameter must be of type bool"); lpeChecker = (bool)value[1]; } - if (value.Length > 2 && value[2] != null) + if (value.Count > 2 && value[2] != null) { if (!(value[2] is int)) throw new CDKException("The parameter must be of type int"); @@ -125,7 +125,7 @@ public object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -158,8 +158,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); if (lpeChecker) { - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(ac); + LonePairElectronChecker.Saturate(ac); } } catch (CDKException e) @@ -201,7 +200,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) bond.Atoms[1].MaxBondOrder = originalMaxBondOrder2; bond.Atoms[1].BondOrderSum = originalBondOrderSum2; - return GetCachedDescriptorValue(bond) != null ? new DescriptorValue>(_Specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(bond), NAMES) : null; + return GetCachedDescriptorValue(bond) != null ? new DescriptorValue>(specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(bond), NAMES) : null; } /// @@ -216,9 +215,9 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) /// An Object of class equal to that of the parameter being requested public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; - if ("lpeChecker".Equals(name)) return true; - if ("maxResonStruc".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) return int.MaxValue; + if (string.Equals("lpeChecker", name, StringComparison.Ordinal)) return true; + if (string.Equals("maxResonStruc", name, StringComparison.Ordinal)) return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptor.cs index d5fa5115..2301eabf 100644 --- a/NCDK/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptor.cs @@ -64,8 +64,8 @@ public BondPartialSigmaChargeDescriptor() /// /// The specification attribute of the BondPartialSigmaChargeDescriptor object. /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondPartialSigmaCharge", typeof(BondPartialSigmaChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -73,11 +73,11 @@ public BondPartialSigmaChargeDescriptor() /// /// The parameters attribute of the BondPartialSigmaChargeDescriptor object /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("PartialSigmaChargeDescriptor only expects one parameter"); } @@ -98,7 +98,7 @@ public object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -132,7 +132,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) } bond.Atoms[0].Charge = originalCharge1; bond.Atoms[1].Charge = originalCharge2; - return GetCachedDescriptorValue(bond) != null ? new DescriptorValue>(_Specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(bond), NAMES) : null; + return GetCachedDescriptorValue(bond) != null ? new DescriptorValue>(specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(bond), NAMES) : null; } /// @@ -147,7 +147,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) /// An Object of class equal to that of the parameter being requested public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs index 48518c3e..43b8803c 100644 --- a/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs @@ -73,8 +73,8 @@ public BondPartialTChargeDescriptor() /// /// The specification attribute of the BondPartialTChargeDescriptor object. /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondPartialTCharge", typeof(BondPartialTChargeDescriptor).FullName, "The Chemistry Development Kit"); @@ -82,25 +82,25 @@ public BondPartialTChargeDescriptor() /// /// The parameters attribute of the BondPartialTChargeDescriptor object. /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 3) + if (value.Count > 3) throw new CDKException("PartialPiChargeDescriptor only expects three parameter"); if (!(value[0] is int)) throw new CDKException("The parameter must be of type int"); maxIterations = (int)value[0]; - if (value.Length > 1 && value[1] != null) + if (value.Count > 1 && value[1] != null) { if (!(value[1] is bool)) throw new CDKException("The parameter must be of type bool"); lpeChecker = (bool)value[1]; } - if (value.Length > 2 && value[2] != null) + if (value.Count > 2 && value[2] != null) { if (!(value[2] is int)) throw new CDKException("The parameter must be of type int"); @@ -118,7 +118,7 @@ public object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -151,8 +151,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); if (lpeChecker) { - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(ac); + LonePairElectronChecker.Saturate(ac); } } catch (CDKException e) @@ -204,7 +203,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) bond.Atoms[1].MaxBondOrder = originalMaxBondOrder2; bond.Atoms[1].BondOrderSum = originalBondOrderSum2; - return GetCachedDescriptorValue(bond) != null ? new DescriptorValue>(_Specification, ParameterNames, + return GetCachedDescriptorValue(bond) != null ? new DescriptorValue>(specification, ParameterNames, Parameters, (Result)GetCachedDescriptorValue(bond), NAMES) : null; } @@ -220,9 +219,9 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) /// An Object of class equal to that of the parameter being requested public object GetParameterType(string name) { - if ("maxIterations".Equals(name)) return int.MaxValue; - if ("lpeChecker".Equals(name)) return true; - if ("maxResonStruc".Equals(name)) return int.MaxValue; + if (string.Equals("maxIterations", name, StringComparison.Ordinal)) return int.MaxValue; + if (string.Equals("lpeChecker", name, StringComparison.Ordinal)) return true; + if (string.Equals("maxResonStruc", name, StringComparison.Ordinal)) return int.MaxValue; return null; } } diff --git a/NCDK/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptor.cs index 844df48e..de29841c 100644 --- a/NCDK/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptor.cs @@ -63,8 +63,8 @@ public BondSigmaElectronegativityDescriptor() /// /// The specification attribute of the BondSigmaElectronegativityDescriptor object. /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondSigmaElectronegativity", typeof(BondSigmaElectronegativityDescriptor).FullName, "The Chemistry Development Kit"); @@ -72,11 +72,11 @@ public BondSigmaElectronegativityDescriptor() /// /// The parameters attribute of the BondSigmaElectronegativityDescriptor object. /// - public object[] Parameters + public IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("SigmaElectronegativityDescriptor only expects one parameter"); } @@ -84,7 +84,9 @@ public object[] Parameters { throw new CDKException("The parameter must be of type int"); } - if (value.Length == 0) return; + if (value.Count == 0) + return; + maxIterations = (int)value[0]; } get @@ -98,7 +100,7 @@ public object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), NAMES, e); } /// @@ -128,7 +130,7 @@ public DescriptorValue> Calculate(IBond aBond, IAtomContainer ato double electroAtom1 = electronegativity.CalculateSigmaElectronegativity(ac, bond.Atoms[0]); double electroAtom2 = electronegativity.CalculateSigmaElectronegativity(ac, bond.Atoms[1]); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(Math.Abs(electroAtom1 - electroAtom2)), NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(Math.Abs(electroAtom1 - electroAtom2)), NAMES); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs index aaf89d57..9aa73b61 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs @@ -75,14 +75,35 @@ public class ALOGPDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { IAtomContainer atomContainer; IRingSet rs; - string[] fragment; // estate fragments for each atom + /// + /// estate fragments for each atom + /// + string[] fragment; - AtomicProperties ap; // needed to retrieve electronegativities + /// + /// needed to retrieve electronegativities + /// + AtomicProperties ap; - int[] frags = new int[121]; // counts of each type of fragment in the molecule - public int[] alogpfrag; // alogp fragments for each atom (used to see which atoms have missing fragments) - readonly static double[] FRAGVAL = new double[121]; // coefficients for alogp model - readonly static double[] REFRACVAL = new double[121]; // coefficients for refractivity model + /// + /// counts of each type of fragment in the molecule + /// + readonly int[] frags = new int[121]; + + /// + /// alogp fragments for each atom (used to see which atoms have missing fragments) + /// + private int[] alogpfrag; + + /// + /// coefficients for alogp model + /// + readonly static double[] FRAGVAL = new double[121]; + + /// + /// coefficients for refractivity model + /// + readonly static double[] REFRACVAL = new double[121]; static ALOGPDescriptor() { @@ -441,25 +462,25 @@ private double[] Calculate(IAtomContainer atomContainer, string[] fragment, IRin private void CalcGroup001_005(int i) { // C in CH3R - if (fragment[i].Equals("SsCH3")) + if (string.Equals(fragment[i], "SsCH3", StringComparison.Ordinal)) { var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); int htype = GetHAtomType(atomContainer.Atoms[i], ca); foreach (var a in ca) { - if (a.Symbol.Equals("C")) - { - frags[1]++; - alogpfrag[i] = 1; - } - else if (a.Symbol.Equals("H")) + switch (a.Symbol) { - frags[htype]++; - } - else - { - frags[5]++; - alogpfrag[i] = 5; + case "C": + frags[1]++; + alogpfrag[i] = 1; + break; + case "H": + frags[htype]++; + break; + default: + frags[5]++; + alogpfrag[i] = 5; + break; } } } @@ -469,7 +490,7 @@ private void CalcGroup002_006_007(int i) { // C in CH2RX - if (fragment[i].Equals("SssCH2")) + if (string.Equals(fragment[i], "SssCH2", StringComparison.Ordinal)) { var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); int htype = GetHAtomType(atomContainer.Atoms[i], ca); @@ -478,14 +499,18 @@ private void CalcGroup002_006_007(int i) // Debug.WriteLine("here"); foreach (var a in ca) { - if (a.Symbol.Equals("C")) - carbonCount++; - else if (a.Symbol.Equals("H")) + switch (a.Symbol) { - frags[htype]++; + case "C": + carbonCount++; + break; + case "H": + frags[htype]++; + break; + default: + heteroCount++; + break; } - else - heteroCount++; } if (carbonCount == 2 && heteroCount == 0) @@ -508,7 +533,7 @@ private void CalcGroup002_006_007(int i) private void CalcGroup003_008_009_010(int i) { - if (fragment[i].Equals("SsssCH")) + if (string.Equals(fragment[i], "SsssCH", StringComparison.Ordinal)) { var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); int htype = GetHAtomType(atomContainer.Atoms[i], ca); @@ -517,14 +542,18 @@ private void CalcGroup003_008_009_010(int i) // Debug.WriteLine("here"); foreach (var a in ca) { - if (a.Symbol.Equals("C")) - carbonCount++; - else if (a.Symbol.Equals("H")) + switch (a.Symbol) { - frags[htype]++; + case "C": + carbonCount++; + break; + case "H": + frags[htype]++; + break; + default: + heteroCount++; + break; } - else - heteroCount++; } if (carbonCount == 3 && heteroCount == 0) @@ -553,7 +582,7 @@ private void CalcGroup003_008_009_010(int i) private void CalcGroup004_011_to_014(int i) { // C in CH2RX - if (fragment[i].Equals("SssssC")) + if (string.Equals(fragment[i], "SssssC", StringComparison.Ordinal)) { var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); int carbonCount = 0; @@ -561,10 +590,15 @@ private void CalcGroup004_011_to_014(int i) // Debug.WriteLine("here"); foreach (var a in ca) { - if (a.Symbol.Equals("C")) - carbonCount++; - else - heteroCount++; + switch (a.Symbol) + { + case "C": + carbonCount++; + break; + default: + heteroCount++; + break; + } } if (carbonCount == 4 && heteroCount == 0) @@ -597,7 +631,7 @@ private void CalcGroup004_011_to_014(int i) private void CalcGroup015(int i) { - if (fragment[i].Equals("SdCH2")) + if (string.Equals(fragment[i], "SdCH2", StringComparison.Ordinal)) { frags[15]++; alogpfrag[i] = 15; @@ -610,7 +644,8 @@ private void CalcGroup016_018_036_037(int i) { IAtom ai = atomContainer.Atoms[i]; - if (!fragment[i].Equals("SdsCH")) return; + if (!string.Equals(fragment[i], "SdsCH", StringComparison.Ordinal)) + return; var ca = atomContainer.GetConnectedAtoms(ai); int htype = GetHAtomType(atomContainer.Atoms[i], ca); @@ -622,11 +657,12 @@ private void CalcGroup016_018_036_037(int i) foreach (var a in ca) { - if (a.Symbol.Equals("H")) continue; + if (string.Equals(a.Symbol, "H", StringComparison.Ordinal)) + continue; if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (!a.Symbol.Equals("C")) + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { haveCsX = true; } @@ -639,7 +675,7 @@ private void CalcGroup016_018_036_037(int i) } else if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) { - if (!a.Symbol.Equals("C")) + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { haveCdX = true; } @@ -679,7 +715,7 @@ private void CalcGroup017_019_020_038_to_041(int i) IAtom ai = atomContainer.Atoms[i]; - if (!fragment[i].Equals("SdssC")) return; + if (!string.Equals(fragment[i], "SdssC", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(ai); @@ -692,7 +728,7 @@ private void CalcGroup017_019_020_038_to_041(int i) { if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (a.Symbol.Equals("C")) + if (string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { rCount++; } @@ -709,7 +745,7 @@ private void CalcGroup017_019_020_038_to_041(int i) } else if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) { - if (!a.Symbol.Equals("C")) + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { haveCdX = true; } @@ -747,9 +783,7 @@ private void CalcGroup017_019_020_038_to_041(int i) frags[38]++; alogpfrag[i] = 38; } - } - } else { @@ -778,27 +812,27 @@ private void CalcGroup021_to_023_040(int i) var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]).ToList(); IAtom ai = atomContainer.Atoms[i]; - if (fragment[i].Equals("StCH")) + if (string.Equals(fragment[i], "StCH", StringComparison.Ordinal)) { frags[21]++; alogpfrag[i] = 21; int htype = GetHAtomType(atomContainer.Atoms[i], ca); frags[htype]++; } - else if (fragment[i].Equals("SddC")) + else if (string.Equals(fragment[i], "SddC", StringComparison.Ordinal)) { - if (((IAtom)ca[0]).Symbol.Equals("C") && ((IAtom)ca[1]).Symbol.Equals("C")) + if (string.Equals(ca[0].Symbol, "C", StringComparison.Ordinal) && string.Equals(ca[1].Symbol, "C", StringComparison.Ordinal)) {// R==C==R frags[22]++; alogpfrag[i] = 22; } - else if (!((IAtom)ca[0]).Symbol.Equals("C") && !((IAtom)ca[1]).Symbol.Equals("C")) + else if (!string.Equals(ca[0].Symbol, "C", StringComparison.Ordinal) && !string.Equals(ca[1].Symbol, "C", StringComparison.Ordinal)) {// X==C==X frags[40]++; alogpfrag[i] = 40; } } - else if (fragment[i].Equals("StsC")) + else if (string.Equals(fragment[i], "StsC", StringComparison.Ordinal)) { bool haveCtX = false; @@ -808,14 +842,14 @@ private void CalcGroup021_to_023_040(int i) { if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (!a.Symbol.Equals("C")) + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { haveCsX = true; } } else if (atomContainer.GetBond(ai, a).Order == BondOrder.Triple) { - if (!a.Symbol.Equals("C")) + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { haveCtX = true; } @@ -848,7 +882,7 @@ private void CalcGroup024_027_030_033_042(int i) // 33: C in R--CH...X // 42: C in X--CH...X - if (!fragment[i].Equals("SaaCH")) return; + if (!string.Equals(fragment[i], "SaaCH", StringComparison.Ordinal)) return; // Debug.WriteLine("here"); //IAtom ai = atomContainer.Atoms[i]; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]).ToList(); @@ -856,15 +890,15 @@ private void CalcGroup024_027_030_033_042(int i) frags[htype]++; IAtom ca0; IAtom ca1; - //Determinig which neigbour is the H atom - if (((IAtom)ca[0]).Symbol.Equals("H")) + // determining which neigbour is the H atom + if (string.Equals(ca[0].Symbol, "H", StringComparison.Ordinal)) { ca0 = (IAtom)ca[1]; ca1 = (IAtom)ca[2]; } else { - if (((IAtom)ca[1]).Symbol.Equals("H")) + if (string.Equals(ca[1].Symbol, "H", StringComparison.Ordinal)) { ca0 = (IAtom)ca[0]; ca1 = (IAtom)ca[2]; @@ -876,7 +910,7 @@ private void CalcGroup024_027_030_033_042(int i) } } - if (ca0.Symbol.Equals("C") && ca1.Symbol.Equals("C")) + if (string.Equals(ca0.Symbol, "C", StringComparison.Ordinal) && string.Equals(ca1.Symbol, "C", StringComparison.Ordinal)) { frags[24]++; alogpfrag[i] = 24; @@ -906,7 +940,7 @@ private void CalcGroup024_027_030_033_042(int i) } } - if (!(ca0).Symbol.Equals("C") && !((IAtom)ca[1]).Symbol.Equals("C")) + if (!string.Equals(ca0.Symbol, "C", StringComparison.Ordinal) && !string.Equals(ca[1].Symbol, "C", StringComparison.Ordinal)) { if (haveDouble1 && haveDouble2) { // X--CH--X @@ -920,8 +954,8 @@ private void CalcGroup024_027_030_033_042(int i) } } - else if (ca0.Symbol.Equals("C") && !ca1.Symbol.Equals("C") - || (!ca0.Symbol.Equals("C") && ca1.Symbol.Equals("C"))) + else if (string.Equals(ca0.Symbol, "C", StringComparison.Ordinal) && !string.Equals(ca1.Symbol, "C", StringComparison.Ordinal) + || (!string.Equals(ca0.Symbol, "C", StringComparison.Ordinal) && string.Equals(ca1.Symbol, "C", StringComparison.Ordinal))) { if (haveDouble1 && haveDouble2) @@ -951,7 +985,7 @@ private void CalcGroup025_026_028_029_031_032_034_035_043_044(int i) // 43: X--CR...X // 43: X--CX...X - if (!fragment[i].Equals("SsaaC") && !fragment[i].Equals("SaaaC")) return; + if (!string.Equals(fragment[i], "SsaaC", StringComparison.Ordinal) && !string.Equals(fragment[i], "SaaaC", StringComparison.Ordinal)) return; IAtom ai = atomContainer.Atoms[i]; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); @@ -1024,11 +1058,11 @@ private void CalcGroup025_026_028_029_031_032_034_035_043_044(int i) } - if (!sameringatoms[0].Symbol.Equals("C") && !sameringatoms[1].Symbol.Equals("C")) + if (!string.Equals(sameringatoms[0].Symbol, "C", StringComparison.Ordinal) && !string.Equals(sameringatoms[1].Symbol, "C", StringComparison.Ordinal)) { if (haveDouble1 && haveDouble2) { // X--CR--X - if (nonringatom.Symbol.Equals("C")) + if (string.Equals(nonringatom.Symbol, "C", StringComparison.Ordinal)) { frags[31]++; alogpfrag[i] = 31; @@ -1043,7 +1077,7 @@ private void CalcGroup025_026_028_029_031_032_034_035_043_044(int i) else { - if (nonringatom.Symbol.Equals("C")) + if (string.Equals(nonringatom.Symbol, "C", StringComparison.Ordinal)) { // X--CR..X frags[43]++; alogpfrag[i] = 43; @@ -1057,10 +1091,10 @@ private void CalcGroup025_026_028_029_031_032_034_035_043_044(int i) } } - else if (sameringatoms[0].Symbol.Equals("C") && sameringatoms[1].Symbol.Equals("C")) + else if (string.Equals(sameringatoms[0].Symbol, "C", StringComparison.Ordinal) && string.Equals(sameringatoms[1].Symbol, "C", StringComparison.Ordinal)) { - if (nonringatom.Symbol.Equals("C")) + if (string.Equals(nonringatom.Symbol, "C", StringComparison.Ordinal)) {// R--CR--R frags[25]++; alogpfrag[i] = 25; @@ -1072,13 +1106,13 @@ private void CalcGroup025_026_028_029_031_032_034_035_043_044(int i) } } - else if ((sameringatoms[0].Symbol.Equals("C") && !sameringatoms[1].Symbol.Equals("C")) - || (!sameringatoms[0].Symbol.Equals("C") && sameringatoms[1].Symbol.Equals("C"))) + else if ((string.Equals(sameringatoms[0].Symbol, "C", StringComparison.Ordinal) && !string.Equals(sameringatoms[1].Symbol, "C", StringComparison.Ordinal)) + || (!string.Equals(sameringatoms[0].Symbol, "C", StringComparison.Ordinal) && string.Equals(sameringatoms[1].Symbol, "C", StringComparison.Ordinal))) { if (haveDouble1 && haveDouble2) { // R--CR--X - if (nonringatom.Symbol.Equals("C")) + if (string.Equals(nonringatom.Symbol, "C", StringComparison.Ordinal)) { frags[28]++; alogpfrag[i] = 28; @@ -1093,7 +1127,7 @@ private void CalcGroup025_026_028_029_031_032_034_035_043_044(int i) else { - if (nonringatom.Symbol.Equals("C")) + if (string.Equals(nonringatom.Symbol, "C", StringComparison.Ordinal)) { // R--CR..X frags[34]++; alogpfrag[i] = 34; @@ -1122,18 +1156,18 @@ private int GetHAtomType(IAtom ai, IEnumerable connectedAtoms) ca = connectedAtoms; // first check for alpha carbon: - if (ai.Symbol.Equals("C") && !ai.IsAromatic) + if (string.Equals(ai.Symbol, "C", StringComparison.Ordinal) && !ai.IsAromatic) { foreach (var a in ca) { - if (atomContainer.GetBond(ai, a).Order == BondOrder.Single && a.Symbol.Equals("C")) + if (atomContainer.GetBond(ai, a).Order == BondOrder.Single && string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { // single bonded var ca2 = atomContainer.GetConnectedAtoms(a); foreach (var a2 in ca2) { IAtom ca2k = a2; - if (!ca2k.Symbol.Equals("C")) + if (!string.Equals(ca2k.Symbol, "C", StringComparison.Ordinal)) { if (atomContainer.GetBond(a, ca2k).Order != BondOrder.Single) return 51; @@ -1145,11 +1179,11 @@ private int GetHAtomType(IAtom ai, IEnumerable connectedAtoms) return 51; } } - } // end !ca2[k].Symbol.Equals("C")) + } // end !string.Equals(ca2[k].Symbol, "C", StringComparison.Ordinal)) } // end k loop } // end if (atomContainer.GetBond(ai, ((IAtom)ca[j])).Order == BondOrder.Single) { }// end j loop - } // end if(ai.Symbol.Equals("C") && !ai.IsAromatic) + } // end if(string.Equals(ai.Symbol, "C", StringComparison.Ordinal) && !ai.IsAromatic) var bonds = atomContainer.GetConnectedBonds(ai); int doublebondcount = 0; @@ -1188,7 +1222,7 @@ private int GetHAtomType(IAtom ai, IEnumerable connectedAtoms) break; } } - if (haveDouble && a.Symbol.Equals("N")) + if (haveDouble && string.Equals(a.Symbol, "N", StringComparison.Ordinal)) oxNum += 2; // C-N bond order for pyridine type N's is considered to be 2 else oxNum += (int)BondManipulator.DestroyBondOrder(atomContainer.GetBond(ai, a).Order); @@ -1198,13 +1232,13 @@ private int GetHAtomType(IAtom ai, IEnumerable connectedAtoms) foreach (var a2 in ca2) { string s2 = (a2).Symbol; - if (!s2.Equals("C")) xCount++; + if (!string.Equals(s2, "C", StringComparison.Ordinal)) xCount++; } }// end j loop if (oxNum == 0) { - if (hybrid.Equals("sp3")) + if (string.Equals(hybrid, "sp3", StringComparison.Ordinal)) { if (xCount == 0) return 46; @@ -1216,15 +1250,15 @@ private int GetHAtomType(IAtom ai, IEnumerable connectedAtoms) return 54; else if (xCount >= 4) return 55; } - else if (hybrid.Equals("sp2")) return 47; + else if (string.Equals(hybrid, "sp2", StringComparison.Ordinal)) return 47; } - else if (oxNum == 1 && hybrid.Equals("sp3")) + else if (oxNum == 1 && string.Equals(hybrid, "sp3", StringComparison.Ordinal)) return 47; - else if ((oxNum == 2 && hybrid.Equals("sp3")) || (oxNum == 1 && hybrid.Equals("sp2")) - || (oxNum == 0 && hybrid.Equals("sp"))) + else if ((oxNum == 2 && string.Equals(hybrid, "sp3", StringComparison.Ordinal)) || (oxNum == 1 && string.Equals(hybrid, "sp2", StringComparison.Ordinal)) + || (oxNum == 0 && string.Equals(hybrid, "sp", StringComparison.Ordinal))) return 48; - else if ((oxNum == 3 && hybrid.Equals("sp3")) || (oxNum >= 2 && hybrid.Equals("sp2")) - || (oxNum >= 1 && hybrid.Equals("sp"))) return 49; + else if ((oxNum == 3 && string.Equals(hybrid, "sp3", StringComparison.Ordinal)) || (oxNum >= 2 && string.Equals(hybrid, "sp2", StringComparison.Ordinal)) + || (oxNum >= 1 && string.Equals(hybrid, "sp", StringComparison.Ordinal))) return 49; return (0); } @@ -1238,12 +1272,12 @@ private void CalcGroup056_57(int i) // enol = HO-C=C- // carboxyl= HO-C(=O)- - if (!fragment[i].Equals("SsOH")) return; + if (!string.Equals(fragment[i], "SsOH", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]).ToList(); frags[50]++; //H atom attached to a hetero atom IAtom ca0 = (IAtom)ca[0]; - if (ca0.Symbol.Equals("H")) ca0 = (IAtom)ca[1]; + if (string.Equals(ca0.Symbol, "H", StringComparison.Ordinal)) ca0 = (IAtom)ca[1]; if (ca0.IsAromatic) { // phenol @@ -1275,10 +1309,10 @@ private void CalcGroup058_61(int i) // 62: O in O- IAtom ca0 = (IAtom)ca[0]; - if (fragment[i].Equals("SsOm")) + if (string.Equals(fragment[i], "SsOm", StringComparison.Ordinal)) { - if (ca0.Symbol.Equals("N") && ca0.FormalCharge == 1) + if (string.Equals(ca0.Symbol, "N", StringComparison.Ordinal) && ca0.FormalCharge == 1) { frags[61]++; alogpfrag[i] = 61; @@ -1290,9 +1324,9 @@ private void CalcGroup058_61(int i) } } - else if (fragment[i].Equals("SdO")) + else if (string.Equals(fragment[i], "SdO", StringComparison.Ordinal)) { - if (ca0.Symbol.Equals("N") && ca0.FormalCharge == 1) + if (string.Equals(ca0.Symbol, "N", StringComparison.Ordinal) && ca0.FormalCharge == 1) { frags[61]++; alogpfrag[i] = 61; @@ -1310,14 +1344,15 @@ private void CalcGroup059_060_063(int i) { // O in Al-O-Ar, Ar2O, R...O...R, ROC=X // ... = aromatic single bonds - if (!fragment[i].Equals("SssO") && !fragment[i].Equals("SaaO")) return; + if (!string.Equals(fragment[i], "SssO", StringComparison.Ordinal) && !string.Equals(fragment[i], "SaaO", StringComparison.Ordinal)) + return; // Al-O-Ar, Ar2O var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]).ToList(); IAtom ca0 = (IAtom)ca[0]; IAtom ca1 = (IAtom)ca[1]; - if (fragment[i].Equals("SssO")) + if (string.Equals(fragment[i], "SssO", StringComparison.Ordinal)) { if (ca0.IsAromatic || ca1.IsAromatic) { @@ -1330,7 +1365,7 @@ private void CalcGroup059_060_063(int i) foreach (var a in ca) { - // if (((IAtom)ca[j]).Symbol.Equals("C")) { // for malathion + // if (((IAtom)ca[j]).string.Equals(Symbol, "C", StringComparison.Ordinal)) { // for malathion // O-P(=S) // was considered to count as group 60 @@ -1339,7 +1374,7 @@ private void CalcGroup059_060_063(int i) { if (atomContainer.GetBond(a, a2).Order == BondOrder.Double) { - if (!(a2).Symbol.Equals("C")) + if (!string.Equals(a2.Symbol, "C", StringComparison.Ordinal)) { frags[60]++; alogpfrag[i] = 60; @@ -1350,7 +1385,7 @@ private void CalcGroup059_060_063(int i) } // end j ca loop - if (ca0.Symbol.Equals("O") || ca1.Symbol.Equals("O")) + if (string.Equals(ca0.Symbol, "O", StringComparison.Ordinal) || string.Equals(ca1.Symbol, "O", StringComparison.Ordinal)) { frags[63]++; alogpfrag[i] = 63; @@ -1364,12 +1399,11 @@ private void CalcGroup059_060_063(int i) } } - else if (fragment[i].Equals("SaaO")) + else if (string.Equals(fragment[i], "SaaO", StringComparison.Ordinal)) { frags[60]++; alogpfrag[i] = 60; } - } private void CalcGroup066_to_079(int i) @@ -1377,14 +1411,14 @@ private void CalcGroup066_to_079(int i) int nAr = 0; int nAl = 0; IAtom ai = atomContainer.Atoms[i]; - if (!ai.Symbol.Equals("N")) return; + if (!string.Equals(ai.Symbol, "N", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); //IAtom ca0 = (IAtom)ca[0]; //IAtom ca1 = (IAtom)ca[1]; foreach (var a in ca) { - if (a.Symbol.Equals("H")) continue; + if (string.Equals(a.Symbol, "H", StringComparison.Ordinal)) continue; if (a.IsAromatic) nAr++; else @@ -1394,14 +1428,14 @@ private void CalcGroup066_to_079(int i) // first check if have RC(=O)N or NX=X foreach (var a in ca) { - if (a.Symbol.Equals("H")) continue; + if (string.Equals(a.Symbol, "H", StringComparison.Ordinal)) continue; var ca2 = atomContainer.GetConnectedAtoms(a); foreach (var a2 in ca2) { IAtom ca2k = a2; if (atomContainer.Atoms.IndexOf(ca2k) != i) { - if (!ca2k.Symbol.Equals("C")) + if (!string.Equals(ca2k.Symbol, "C", StringComparison.Ordinal)) { if (!ca2k.IsAromatic && !a.IsAromatic @@ -1419,13 +1453,13 @@ private void CalcGroup066_to_079(int i) } } - if (fragment[i].Equals("SsNH2")) + if (string.Equals(fragment[i], "SsNH2", StringComparison.Ordinal)) { IAtom ca0 = null; //Find which neigbpur is not the hydrogen atom foreach (var a in ca) { - if (a.Symbol.Equals("H")) + if (string.Equals(a.Symbol, "H", StringComparison.Ordinal)) continue; else { @@ -1433,7 +1467,7 @@ private void CalcGroup066_to_079(int i) break; } } - if (ca0.IsAromatic || !ca0.Symbol.Equals("C")) + if (ca0.IsAromatic || !string.Equals(ca0.Symbol, "C", StringComparison.Ordinal)) { frags[69]++; alogpfrag[i] = 69; @@ -1445,13 +1479,13 @@ private void CalcGroup066_to_079(int i) } frags[50] += 2; //H atom attached to a hetero atom } - else if (fragment[i].Equals("SaaNH") || fragment[i].Equals("SsaaN")) + else if (string.Equals(fragment[i], "SaaNH", StringComparison.Ordinal) || string.Equals(fragment[i], "SsaaN", StringComparison.Ordinal)) { // R...NH...R frags[73]++; alogpfrag[i] = 73; - if (fragment[i].Equals("SaaNH")) frags[50]++; //H atom attached to a hetero atom + if (string.Equals(fragment[i], "SaaNH", StringComparison.Ordinal)) frags[50]++; //H atom attached to a hetero atom } - else if (fragment[i].Equals("SssNH")) + else if (string.Equals(fragment[i], "SssNH", StringComparison.Ordinal)) { if (nAr == 2 && nAl == 0) { // Ar2NH @@ -1471,7 +1505,7 @@ private void CalcGroup066_to_079(int i) } frags[50]++; //H atom attached to a hetero atom } - else if (fragment[i].Equals("SsssN")) + else if (string.Equals(fragment[i], "SsssN", StringComparison.Ordinal)) { if ((nAr == 3 && nAl == 0) || (nAr == 2 && nAl == 1)) { // Ar3N & @@ -1490,12 +1524,12 @@ private void CalcGroup066_to_079(int i) alogpfrag[i] = 68; } } - else if (fragment[i].Equals("SaaN")) + else if (string.Equals(fragment[i], "SaaN", StringComparison.Ordinal)) { frags[75]++; alogpfrag[i] = 75; } - else if (fragment[i].Equals("SssdNp")) + else if (string.Equals(fragment[i], "SssdNp", StringComparison.Ordinal)) { bool haveSsOm = false; bool haveSdO = false; @@ -1503,11 +1537,11 @@ private void CalcGroup066_to_079(int i) foreach (var a in ca) { - if (fragment[atomContainer.Atoms.IndexOf(a)].Equals("SsOm")) + if (string.Equals(fragment[atomContainer.Atoms.IndexOf(a)], "SsOm", StringComparison.Ordinal)) { haveSsOm = true; } - else if (fragment[atomContainer.Atoms.IndexOf(a)].Equals("SdO")) + else if (string.Equals(fragment[atomContainer.Atoms.IndexOf(a)], "SdO", StringComparison.Ordinal)) { haveSdO = true; } @@ -1537,24 +1571,24 @@ private void CalcGroup066_to_079(int i) } } - else if (fragment[i].Equals("StN")) + else if (string.Equals(fragment[i], "StN", StringComparison.Ordinal)) { IAtom ca0 = (IAtom)ca.ElementAt(0); - if (ca0.Symbol.Equals("C")) + if (string.Equals(ca0.Symbol, "C", StringComparison.Ordinal)) { // R#N frags[74]++; alogpfrag[i] = 74; } } - else if (fragment[i].Equals("SdNH") || fragment[i].Equals("SdsN")) + else if (string.Equals(fragment[i], "SdNH", StringComparison.Ordinal) || string.Equals(fragment[i], "SdsN", StringComparison.Ordinal)) { // test for RO-NO - if (fragment[i].Equals("SdsN")) + if (string.Equals(fragment[i], "SdsN", StringComparison.Ordinal)) { var caa = ca.ToList(); IAtom ca0 = (IAtom)caa[0]; IAtom ca1 = (IAtom)caa[1]; - if (ca0.Symbol.Equals("O") && ca1.Symbol.Equals("O")) + if (string.Equals(ca0.Symbol, "O", StringComparison.Ordinal) && string.Equals(ca1.Symbol, "O", StringComparison.Ordinal)) { frags[76]++; alogpfrag[i] = 76; @@ -1567,10 +1601,10 @@ private void CalcGroup066_to_079(int i) foreach (var a in ca) { - if (a.Symbol.Equals("H")) continue; + if (string.Equals(a.Symbol, "H", StringComparison.Ordinal)) continue; if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) { - if (a.Symbol.Equals("C")) + if (string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { frags[74]++; alogpfrag[i] = 74; @@ -1583,7 +1617,7 @@ private void CalcGroup066_to_079(int i) } else { - if (!a.Symbol.Equals("C") + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal) || a.IsAromatic) { flag2 = true; @@ -1601,7 +1635,7 @@ private void CalcGroup066_to_079(int i) } } - if (fragment[i].Equals("SdNH")) frags[50]++; //H atom attached to a hetero atom + if (string.Equals(fragment[i], "SdNH", StringComparison.Ordinal)) frags[50]++; //H atom attached to a hetero atom } else if (fragment[i].IndexOf('p') > -1) { @@ -1617,7 +1651,7 @@ private void CalcGroup066_to_079(int i) private void CalcGroup081_to_085(int i) { - if (!fragment[i].Equals("SsF")) return; + if (!string.Equals(fragment[i], "SsF", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ca0 = (IAtom)ca.ElementAt(0); @@ -1677,28 +1711,28 @@ private void CalcGroup081_to_085(int i) } - if (hybrid.Equals("sp3") && oxNum == 1) + if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 1) { frags[81]++; alogpfrag[i] = 81; } - else if (hybrid.Equals("sp3") && oxNum == 2) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 2) { frags[82]++; alogpfrag[i] = 82; } - else if (hybrid.Equals("sp3") && oxNum == 3) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 3) { frags[83]++; alogpfrag[i] = 83; } - else if (hybrid.Equals("sp2") && oxNum == 1) + else if (string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum == 1) { frags[84]++; alogpfrag[i] = 84; } - else if ((hybrid.Equals("sp2") && oxNum > 1) || (hybrid.Equals("sp") && oxNum >= 1) - || (hybrid.Equals("sp3") && oxNum == 4) || !ca0.Symbol.Equals("C")) + else if ((string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum > 1) || (string.Equals(hybrid, "sp", StringComparison.Ordinal) && oxNum >= 1) + || (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 4) || !string.Equals(ca0.Symbol, "C", StringComparison.Ordinal)) { frags[85]++; alogpfrag[i] = 85; @@ -1709,7 +1743,7 @@ private void CalcGroup081_to_085(int i) private void CalcGroup086_to_090(int i) { - if (!fragment[i].Equals("SsCl")) return; + if (!string.Equals(fragment[i], "SsCl", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ca0 = (IAtom)ca.ElementAt(0); @@ -1768,28 +1802,28 @@ private void CalcGroup086_to_090(int i) } } - if (hybrid.Equals("sp3") && oxNum == 1) + if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 1) { frags[86]++; alogpfrag[i] = 86; } - else if (hybrid.Equals("sp3") && oxNum == 2) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 2) { frags[87]++; alogpfrag[i] = 87; } - else if (hybrid.Equals("sp3") && oxNum == 3) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 3) { frags[88]++; alogpfrag[i] = 88; } - else if (hybrid.Equals("sp2") && oxNum == 1) + else if (string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum == 1) { frags[89]++; alogpfrag[i] = 89; } - else if ((hybrid.Equals("sp2") && oxNum > 1) || (hybrid.Equals("sp") && oxNum >= 1) - || (hybrid.Equals("sp3") && oxNum == 4) || !ca0.Symbol.Equals("C")) + else if ((string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum > 1) || (string.Equals(hybrid, "sp", StringComparison.Ordinal) && oxNum >= 1) + || (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 4) || !string.Equals(ca0.Symbol, "C", StringComparison.Ordinal)) { frags[90]++; alogpfrag[i] = 90; @@ -1800,7 +1834,7 @@ private void CalcGroup086_to_090(int i) private void CalcGroup091_to_095(int i) { - if (!fragment[i].Equals("SsBr")) return; + if (!string.Equals(fragment[i], "SsBr", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ca0 = (IAtom)ca.ElementAt(0); @@ -1860,28 +1894,28 @@ private void CalcGroup091_to_095(int i) } - if (hybrid.Equals("sp3") && oxNum == 1) + if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 1) { frags[91]++; alogpfrag[i] = 91; } - else if (hybrid.Equals("sp3") && oxNum == 2) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 2) { frags[92]++; alogpfrag[i] = 92; } - else if (hybrid.Equals("sp3") && oxNum == 3) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 3) { frags[93]++; alogpfrag[i] = 93; } - else if (hybrid.Equals("sp2") && oxNum == 1) + else if (string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum == 1) { frags[94]++; alogpfrag[i] = 94; } - else if ((hybrid.Equals("sp2") && oxNum > 1) || (hybrid.Equals("sp") && oxNum >= 1) - || (hybrid.Equals("sp3") && oxNum == 4) || !ca0.Symbol.Equals("C")) + else if ((string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum > 1) || (string.Equals(hybrid, "sp", StringComparison.Ordinal) && oxNum >= 1) + || (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 4) || !string.Equals(ca0.Symbol, "C", StringComparison.Ordinal)) { frags[95]++; alogpfrag[i] = 95; @@ -1892,7 +1926,7 @@ private void CalcGroup091_to_095(int i) private void CalcGroup096_to_100(int i) { - if (!fragment[i].Equals("SsI")) return; + if (!string.Equals(fragment[i], "SsI", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ca0 = (IAtom)ca.ElementAt(0); @@ -1952,28 +1986,28 @@ private void CalcGroup096_to_100(int i) } - if (hybrid.Equals("sp3") && oxNum == 1) + if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 1) { frags[96]++; alogpfrag[i] = 96; } - else if (hybrid.Equals("sp3") && oxNum == 2) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 2) { frags[97]++; alogpfrag[i] = 97; } - else if (hybrid.Equals("sp3") && oxNum == 3) + else if (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 3) { frags[98]++; alogpfrag[i] = 98; } - else if (hybrid.Equals("sp2") && oxNum == 1) + else if (string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum == 1) { frags[99]++; alogpfrag[i] = 99; } - else if ((hybrid.Equals("sp2") && oxNum > 1) || (hybrid.Equals("sp") && oxNum >= 1) - || (hybrid.Equals("sp3") && oxNum == 4) || !ca0.Symbol.Equals("C")) + else if ((string.Equals(hybrid, "sp2", StringComparison.Ordinal) && oxNum > 1) || (string.Equals(hybrid, "sp", StringComparison.Ordinal) && oxNum >= 1) + || (string.Equals(hybrid, "sp3", StringComparison.Ordinal) && oxNum == 4) || !string.Equals(ca0.Symbol, "C", StringComparison.Ordinal)) { frags[100]++; alogpfrag[i] = 100; @@ -1988,22 +2022,22 @@ private void CalcGroup101_to_104(int i) if (ai.FormalCharge == -1) { - if (s.Equals("F")) + if (string.Equals(s, "F", StringComparison.Ordinal)) { frags[101]++; alogpfrag[i] = 101; } - else if (s.Equals("Cl")) + else if (string.Equals(s, "Cl", StringComparison.Ordinal)) { frags[102]++; alogpfrag[i] = 102; } - else if (s.Equals("Br")) + else if (string.Equals(s, "Br", StringComparison.Ordinal)) { frags[103]++; alogpfrag[i] = 103; } - else if (s.Equals("I")) + else if (string.Equals(s, "I", StringComparison.Ordinal)) { frags[104]++; alogpfrag[i] = 104; @@ -2016,7 +2050,7 @@ private void CalcGroup101_to_104(int i) private void CalcGroup106(int i) { // S in SH - if (fragment[i].Equals("SsSH")) + if (string.Equals(fragment[i], "SsSH", StringComparison.Ordinal)) { frags[106]++; alogpfrag[i] = 106; @@ -2028,24 +2062,24 @@ private void CalcGroup107(int i) { // S in R2S, RS-SR // R = any group linked through C - // if (!Fragment[i].Equals("SssS")) return; + // if (!string.Equals(Fragment[i], "SssS", StringComparison.Ordinal)) return; // In ALOGP, for malathion PSC is consider to have group 107 (even // though has P instead of R) // for lack of fragment, use this fragment for SaaS - if (fragment[i].Equals("SssS") || fragment[i].Equals("SaaS")) + if (string.Equals(fragment[i], "SssS", StringComparison.Ordinal) || string.Equals(fragment[i], "SaaS", StringComparison.Ordinal)) { frags[107]++; alogpfrag[i] = 107; } // IAtom [] ca=atomContainer.GetConnectedAtoms(atomContainer.GetAtomAt(i)); // - // if ((ca.ElementAt(0).Symbol.Equals("C") && ca[1].Symbol.Equals("C")) + // if ((ca.ElementAt(0).string.Equals(Symbol, "C", StringComparison.Ordinal) && string.Equals(ca[1].Symbol, "C", StringComparison.Ordinal)) // || - // (ca.ElementAt(0).Symbol.Equals("C") && ca[1].Symbol.Equals("S")) || - // (ca.ElementAt(0).Symbol.Equals("S") && ca[1].Symbol.Equals("C"))) { + // (ca.ElementAt(0).string.Equals(Symbol, "C", StringComparison.Ordinal) && string.Equals(ca[1].Symbol, "S", StringComparison.Ordinal)) || + // (ca.ElementAt(0).string.Equals(Symbol, "S", StringComparison.Ordinal) && string.Equals(ca[1].Symbol, "C", StringComparison.Ordinal))) { // frags[107]++; // alogpfrag[i]=107; // } @@ -2056,7 +2090,7 @@ private void CalcGroup108(int i) // S in R=S // In ALOGP, for malathion P=S is consider to have group 108 (even // though has P instead of R) - if (fragment[i].Equals("SdS")) + if (string.Equals(fragment[i], "SdS", StringComparison.Ordinal)) { frags[108]++; alogpfrag[i] = 108; @@ -2067,7 +2101,7 @@ private void CalcGroup109(int i) { // for now S in O-S(=O)-O is assigned to this group // (it doesn't check which atoms are singly bonded to S - if (!fragment[i].Equals("SdssS")) return; + if (!string.Equals(fragment[i], "SdssS", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ai = atomContainer.Atoms[i]; @@ -2078,14 +2112,14 @@ private void CalcGroup109(int i) { if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (a.Symbol.Equals("C")) + if (string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { ssCCount++; } } else if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) { - if (a.Symbol.Equals("O")) + if (string.Equals(a.Symbol, "O", StringComparison.Ordinal)) { sdOCount++; } @@ -2100,7 +2134,7 @@ private void CalcGroup109(int i) private void CalcGroup110(int i) { - if (!fragment[i].Equals("SddssS")) return; + if (!string.Equals(fragment[i], "SddssS", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ai = atomContainer.Atoms[i]; @@ -2111,14 +2145,14 @@ private void CalcGroup110(int i) { if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (a.Symbol.Equals("C")) + if (string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { ssCCount++; } } else if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) { - if (a.Symbol.Equals("O")) + if (string.Equals(a.Symbol, "O", StringComparison.Ordinal)) { sdOCount++; } @@ -2134,7 +2168,7 @@ private void CalcGroup110(int i) private void CalcGroup111(int i) { - if (fragment[i].Equals("SssssSi")) + if (string.Equals(fragment[i], "SssssSi", StringComparison.Ordinal)) { frags[111]++; alogpfrag[i] = 111; @@ -2153,13 +2187,13 @@ private void CalcGroup116_117_120(int i) int rCount = 0; bool pdX = false; - if (!fragment[i].Equals("SdsssP")) return; + if (!string.Equals(fragment[i], "SdsssP", StringComparison.Ordinal)) return; foreach (var a in ca) { if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (a.Symbol.Equals("C")) + if (string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { rCount++; } @@ -2170,7 +2204,7 @@ private void CalcGroup116_117_120(int i) } else if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) { - if (!a.Symbol.Equals("C")) + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { pdX = true; } @@ -2200,7 +2234,7 @@ private void CalcGroup116_117_120(int i) private void CalcGroup118_119(int i) { - if (!fragment[i].Equals("SsssP")) return; + if (!string.Equals(fragment[i], "SsssP", StringComparison.Ordinal)) return; var ca = atomContainer.GetConnectedAtoms(atomContainer.Atoms[i]); IAtom ai = atomContainer.Atoms[i]; @@ -2211,7 +2245,7 @@ private void CalcGroup118_119(int i) { if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) { - if (a.Symbol.Equals("C")) + if (string.Equals(a.Symbol, "C", StringComparison.Ordinal)) { rCount++; } @@ -2235,7 +2269,7 @@ private void CalcGroup118_119(int i) } - private bool InSameAromaticRing(IAtomContainer atomContainer, IAtom atom1, IAtom atom2, IRingSet rs) + private static bool InSameAromaticRing(IAtomContainer atomContainer, IAtom atom1, IAtom atom2, IRingSet rs) { bool sameRing = false; @@ -2321,7 +2355,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain } } - double[] ret = new double[0]; + double[] ret = Array.Empty(); try { ret = Calculate(container, fragment, rs); @@ -2338,7 +2372,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain ret[2] }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames); } private DescriptorValue> GetDummyDescriptorValue(Exception e) @@ -2349,7 +2383,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e double.NaN, double.NaN }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } @@ -2357,16 +2391,16 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e public override IDescriptorResult DescriptorResultType => new ArrayResult(3); /// - public override IImplementationSpecification Specification => _Specification; - protected static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification("http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#ALOGP", typeof(ALOGPDescriptor).FullName, "The Chemistry Development Kit"); - public override IReadOnlyList ParameterNames => new string[0]; + public override IReadOnlyList ParameterNames => Array.Empty(); public override object GetParameterType(string name) => null; - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set { } @@ -2377,4 +2411,3 @@ public override object[] Parameters IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); }// end class } - diff --git a/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs index fb681c20..ebaba60f 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs @@ -75,15 +75,15 @@ public APolDescriptor() } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification("http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#apol", typeof(APolDescriptor).FullName, "The Chemistry Development Kit"); /// /// The parameters attribute of the APolDescriptor object. /// - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set @@ -105,7 +105,7 @@ public DescriptorValue> Calculate(IAtomContainer container) int atomicNumber; try { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IElement element; string symbol; foreach (var atom in container.Atoms) @@ -119,12 +119,12 @@ public DescriptorValue> Calculate(IAtomContainer container) apol += polarizabilities[1] * atom.ImplicitHydrogenCount.Value; } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(apol), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(apol), DescriptorNames); } catch (Exception ex1) { Debug.WriteLine(ex1); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, new CDKException($"Problems with IsotopeFactory due to {ex1.ToString()}", ex1)); } } diff --git a/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs index 79aaf74b..d9e93cd8 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs @@ -70,18 +70,18 @@ static AcidicGroupCountDescriptor() } } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#acidicGroupCount", typeof(AcidicGroupCountDescriptor).FullName, "The Chemistry Development Kit"); - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException("AcidicGroupCountDescriptor requires 1 parameter."); } @@ -126,7 +126,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { if (tool.Matches(atomContainer)) count += tool.MatchesCount; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(count), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(count), DescriptorNames); } catch (CDKException exception) { @@ -134,21 +134,21 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } - public override IDescriptorResult DescriptorResultType => Result.Instance; + public override IDescriptorResult DescriptorResultType => Result.Instance(); public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity" }; public override object GetParameterType(string name) { object obj = null; - if (name.Equals("checkAromaticity")) + if (string.Equals(name, "checkAromaticity", StringComparison.Ordinal)) obj = true; return obj; } private DescriptorValue> GetDummyDescriptorValue(Exception exception) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(-1), DescriptorNames, exception); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(-1), DescriptorNames, exception); } IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs index 55522deb..81643579 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs @@ -22,6 +22,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.MCSS; using System.Collections.Generic; +using System.Linq; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -68,8 +69,8 @@ public AminoAcidCountDescriptor() } /// - public override IImplementationSpecification Specification => _Specification; - public DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#aminoAcidsCount", typeof(AminoAcidCountDescriptor).FullName, @@ -79,7 +80,7 @@ public AminoAcidCountDescriptor() /// The parameters attribute of the object. /// /// if more than one parameter or a non-bool parameter is specified - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set { } // no parameters exist @@ -96,15 +97,15 @@ public override object[] Parameters public DescriptorValue> Calculate(IAtomContainer ac) { ac = Clone(ac); // don't modify input - int resultLength = substructureSet.Count; - ArrayResult results = new ArrayResult(resultLength); + var resultLength = substructureSet.Count; + var results = new ArrayResult(resultLength); - UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester(); + var universalIsomorphismTester = new UniversalIsomorphismTester(); IAtomContainer substructure; for (int i = 0; i < resultLength; i++) { substructure = substructureSet[i]; - IList> maps; + IEnumerable> maps = null; try { maps = universalIsomorphismTester.GetSubgraphMaps(ac, substructure); @@ -113,15 +114,15 @@ public DescriptorValue> Calculate(IAtomContainer ac) { for (int j = 0; j < resultLength; j++) results.Add(0); // TODO: original code is (int)double.NaN. - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, DescriptorNames, new CDKException("Error in substructure search: " + e.Message)); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, new CDKException("Error in substructure search: " + e.Message)); } if (maps != null) { - results.Add(maps.Count); + results.Add(maps.Count()); } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames); } /// @@ -138,7 +139,7 @@ public DescriptorValue> Calculate(IAtomContainer ac) /// /// Gets the parameterNames attribute of the AromaticAtomsCountDescriptor object. /// - public override IReadOnlyList ParameterNames => new string[0]; + public override IReadOnlyList ParameterNames => System.Array.Empty(); /// /// Gets the parameterType attribute of the AromaticAtomsCountDescriptor object. diff --git a/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs index a5c7286f..ec46e65b 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs @@ -59,8 +59,8 @@ public class AromaticAtomsCountDescriptor : AbstractMolecularDescriptor, IMolecu public AromaticAtomsCountDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#aromaticAtomsCount", typeof(AromaticAtomsCountDescriptor).FullName, "The Chemistry Development Kit"); @@ -69,11 +69,11 @@ public AromaticAtomsCountDescriptor() { } /// The parameters attribute of the AromaticAtomsCountDescriptor object. /// /// if more than one parameter or a non-bool parameter is specified - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException("AromaticAtomsCountDescriptor expects one parameter"); } @@ -116,7 +116,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } catch (CDKException) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, new CDKException("Error during atom type perception")); } @@ -126,7 +126,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, new CDKException($"Error during aromaticity detection: {e.Message}")); } @@ -138,7 +138,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) aromaticAtomsCount += 1; } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(aromaticAtomsCount), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(aromaticAtomsCount), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs index f4b07d22..1d4d6e95 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs @@ -59,31 +59,32 @@ public class AromaticBondsCountDescriptor : AbstractMolecularDescriptor, IMolecu public AromaticBondsCountDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#aromaticBondsCount", typeof(AromaticBondsCountDescriptor).FullName, "The Chemistry Development Kit"); /// - /// Sets the parameters attribute of the AromaticBondsCountDescriptor object. - /// - /// This descriptor takes one parameter, which should be bool to indicate whether - /// aromaticity has been checked (TRUE) or not (FALSE). + /// The parameters attribute of the object. /// - /// if more than one parameter or a non-bool parameter is specified - public override object[] Parameters + /// + /// This descriptor takes one parameter, which should be boolean to indicate whether + /// aromaticity has been checked () or not (). + /// + /// if more than one parameter or a non-boolean parameter is specified + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { - throw new CDKException("AromaticBondsCountDescriptor expects one parameter"); + throw new CDKException($"{nameof(AromaticBondsCountDescriptor)} expects one parameter"); } if (!(value[0] is bool)) { - throw new CDKException("The first parameter must be of type bool"); + throw new CDKException($"The first parameter must be of type {nameof(System.Boolean)}"); } // ok, all should be fine checkAromaticity = (bool)value[0]; @@ -99,10 +100,11 @@ public override object[] Parameters /// /// Calculate the count of aromatic atoms in the supplied . - /// - /// The method take a bool checkAromaticity: if the bool is true, it means that - /// aromaticity has to be checked. /// + /// + /// The method take a boolean checkAromaticity: if the boolean is , it means that + /// aromaticity has to be checked. + /// /// The for which this descriptor is to be calculated /// the number of aromatic atoms of this AtomContainer /// @@ -119,7 +121,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } catch (CDKException) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, new CDKException("Error during atom type perception")); } try @@ -128,7 +130,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } catch (CDKException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, new CDKException($"Error during aromaticity detection: {e.Message}")); } @@ -140,7 +142,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) aromaticBondsCount += 1; } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(aromaticBondsCount), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(aromaticBondsCount), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs index e00032ae..68a491d2 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs @@ -18,6 +18,7 @@ */ using NCDK.QSAR.Results; +using System; using System.Collections.Generic; namespace NCDK.QSAR.Descriptors.Moleculars @@ -62,8 +63,8 @@ public AtomCountDescriptor() } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#atomCount", typeof(AtomCountDescriptor).FullName, @@ -73,11 +74,11 @@ public AtomCountDescriptor() /// Sets the parameters attribute of the AtomCountDescriptor object. /// /// if the number of parameters is greater than 1 or else the parameter is not of type string - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("AtomCount only expects one parameter"); } @@ -99,7 +100,7 @@ public override IReadOnlyList DescriptorNames get { string name = "n"; - if (elementName.Equals("*")) + if (string.Equals(elementName, "*", StringComparison.Ordinal)) name = "nAtom"; else name += elementName; @@ -120,19 +121,19 @@ public DescriptorValue> Calculate(IAtomContainer container) if (container == null) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, new CDKException("The supplied AtomContainer was NULL")); } if (container.Atoms.Count == 0) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, new CDKException( "The supplied AtomContainer did not have any atoms")); } - if (elementName.Equals("*")) + if (string.Equals(elementName, "*", StringComparison.Ordinal)) { for (int i = 0; i < container.Atoms.Count; i++) { @@ -142,11 +143,11 @@ public DescriptorValue> Calculate(IAtomContainer container) } atomCount += container.Atoms.Count; } - else if (elementName.Equals("H")) + else if (string.Equals(elementName, "H", StringComparison.Ordinal)) { for (int i = 0; i < container.Atoms.Count; i++) { - if (container.Atoms[i].Symbol.Equals(elementName)) + if (container.Atoms[i].Symbol.Equals(elementName, StringComparison.Ordinal)) { atomCount += 1; } @@ -162,14 +163,14 @@ public DescriptorValue> Calculate(IAtomContainer container) { for (int i = 0; i < container.Atoms.Count; i++) { - if (container.Atoms[i].Symbol.Equals(elementName)) + if (container.Atoms[i].Symbol.Equals(elementName, StringComparison.Ordinal)) { atomCount += 1; } } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( atomCount), DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorCharge.cs b/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorCharge.cs index feb3365a..66385856 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorCharge.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorCharge.cs @@ -96,7 +96,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain { result.Add(aChargeSum); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, NAMES); } catch (Exception ex) @@ -104,15 +104,15 @@ public DescriptorValue> Calculate(IAtomContainer atomContain ArrayResult result = new ArrayResult(5); for (int i = 0; i < 5; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, NAMES, + return new DescriptorValue>(specification, ParameterNames, Parameters, result, NAMES, new CDKException("Error while calculating the ATS_charge descriptor: " + ex.Message, ex)); } } - public override IReadOnlyList ParameterNames { get; } = new string[0]; + public override IReadOnlyList ParameterNames { get; } = Array.Empty(); public override object GetParameterType(string name) => null; - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set { } @@ -120,8 +120,8 @@ public override object[] Parameters public override IReadOnlyList DescriptorNames => NAMES; - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#autoCorrelationCharge", typeof(AutocorrelationDescriptorCharge).FullName, diff --git a/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMass.cs b/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMass.cs index 33fdfea9..11301f1d 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMass.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMass.cs @@ -21,6 +21,7 @@ using NCDK.Graphs.Matrix; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.IO; @@ -36,14 +37,14 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.githash public class AutocorrelationDescriptorMass : AbstractMolecularDescriptor, IMolecularDescriptor { - private readonly static string[] NAMES = { "ATSm1", "ATSm2", "ATSm3", "ATSm4", "ATSm5" }; - private readonly static double CARBON_MASS = 12.010735896788; + private readonly static string[] Names = { "ATSm1", "ATSm2", "ATSm3", "ATSm4", "ATSm5" }; + private const double CarbonMass = 12.010735896788; private static double ScaledAtomicMasses(IElement element) { - IsotopeFactory isofac = Isotopes.Instance; + IsotopeFactory isofac = BODRIsotopeFactory.Instance; double realmasses = isofac.GetNaturalMass(element); - return (realmasses / CARBON_MASS); + return (realmasses / CarbonMass); } private static double[] ListConvertion(IAtomContainer container) @@ -99,7 +100,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain result.Add(aMasSum); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames); } @@ -108,25 +109,25 @@ public DescriptorValue> Calculate(IAtomContainer atomContain ArrayResult result = new ArrayResult(5); for (int i = 0; i < 5; i++) result.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, new CDKException("Error while calculating the ATS_mass descriptor: " + ex.Message, ex)); } } - public override IReadOnlyList ParameterNames { get; } = new string[0]; + public override IReadOnlyList ParameterNames { get; } = Array.Empty(); public override object GetParameterType(string name) => null; - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set { } } - public override IReadOnlyList DescriptorNames => NAMES; + public override IReadOnlyList DescriptorNames => Names; - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#autoCorrelationMass", typeof(AutocorrelationDescriptorMass).FullName, diff --git a/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizability.cs b/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizability.cs index a97c02e4..d9a7be9d 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizability.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizability.cs @@ -46,13 +46,12 @@ private static double[] Listpolarizability(IAtomContainer container, int[][] dma int natom = container.Atoms.Count; double[] polars = new double[natom]; - Polarizability polar = new Polarizability(); for (int i = 0; i < natom; i++) { IAtom atom = container.Atoms[i]; try { - polars[i] = polar.CalculateGHEffectiveAtomPolarizability(container, atom, false, dmat); + polars[i] = Polarizability.CalculateGHEffectiveAtomPolarizability(container, atom, false, dmat); } catch (Exception ex1) { @@ -120,10 +119,10 @@ public DescriptorValue> Calculate(IAtomContainer container) { for (int i = 0; i < natom; i++) { - if (molecule.Atoms[i].Symbol.Equals("H")) continue; + if (string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) continue; for (int j = 0; j < natom; j++) { - if (molecule.Atoms[j].Symbol.Equals("H")) continue; + if (string.Equals(molecule.Atoms[j].Symbol, "H", StringComparison.Ordinal)) continue; if (distancematrix[i][j] == k) { polarizabilitySum[k] += w[i] * w[j]; @@ -142,7 +141,7 @@ public DescriptorValue> Calculate(IAtomContainer container) } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames); } @@ -158,14 +157,14 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(5); for (int i = 0; i < 5; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } public override IReadOnlyList ParameterNames => null; public override object GetParameterType(string name) => null; - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set { } @@ -173,8 +172,8 @@ public override object[] Parameters public override IReadOnlyList DescriptorNames => NAMES; - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#autoCorrelationPolarizability", typeof(AutocorrelationDescriptorPolarizability).FullName, diff --git a/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs index fb946652..11ae8253 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs @@ -130,8 +130,8 @@ public BCUTDescriptor() this.checkAromaticity = true; } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification("http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#BCUT", typeof(BCUTDescriptor).FullName, "The Chemistry Development Kit"); @@ -146,12 +146,12 @@ public BCUTDescriptor() /// /// if the parameters are of the wrong type /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { // we expect 3 parameters - if (value.Length != 3) + if (value.Count != 3) { throw new CDKException("BCUTDescriptor requires 3 parameters"); } @@ -232,7 +232,7 @@ public override object GetParameterType(string name) } } - private bool HasUndefined(double[][] m) + private static bool HasUndefined(double[][] m) { foreach (var aM in m) { @@ -358,7 +358,7 @@ public DescriptorValue> Calculate(IAtomContainer container) int nheavy = 0; for (int i = 0; i < molecule.Atoms.Count; i++) { - if (!molecule.Atoms[i].Symbol.Equals("H")) nheavy++; + if (!string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) nheavy++; } if (nheavy == 0) return GetDummyDescriptorValue(new CDKException("No heavy atoms in the molecule")); @@ -371,8 +371,8 @@ public DescriptorValue> Calculate(IAtomContainer container) { for (int i = 0; i < molecule.Atoms.Count; i++) { - if (molecule.Atoms[i].Symbol.Equals("H")) continue; - diagvalue[counter] = Isotopes.Instance.GetMajorIsotope(molecule.Atoms[i].Symbol).ExactMass.Value; + if (string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) continue; + diagvalue[counter] = BODRIsotopeFactory.Instance.GetMajorIsotope(molecule.Atoms[i].Symbol).ExactMass.Value; counter++; } } @@ -390,15 +390,11 @@ public DescriptorValue> Calculate(IAtomContainer container) double[] eval1 = eigenDecomposition.Select(n => n.Real).ToArray(); // get charge weighted BCUT - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); GasteigerMarsiliPartialCharges peoe; try { - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); double[] charges = new double[molecule.Atoms.Count]; - // pepe = new GasteigerPEPEPartialCharges(); - // pepe.CalculateCharges(molecule); - // for (int i = 0; i < molecule.Atoms.Count; i++) charges[i] = molecule.Atoms[i].Charge; peoe = new GasteigerMarsiliPartialCharges(); peoe.AssignGasteigerMarsiliSigmaPartialCharges(molecule, true); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -415,7 +411,7 @@ public DescriptorValue> Calculate(IAtomContainer container) counter = 0; for (int i = 0; i < molecule.Atoms.Count; i++) { - if (molecule.Atoms[i].Symbol.Equals("H")) continue; + if (string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) continue; diagvalue[counter] = molecule.Atoms[i].Charge.Value; counter++; } @@ -429,13 +425,12 @@ public DescriptorValue> Calculate(IAtomContainer container) int[][] topoDistance = PathTools.ComputeFloydAPSP(AdjacencyMatrix.GetMatrix(molecule)); // get polarizability weighted BCUT - Polarizability pol = new Polarizability(); counter = 0; for (int i = 0; i < molecule.Atoms.Count; i++) { - if (molecule.Atoms[i].Symbol.Equals("H")) continue; - diagvalue[counter] = pol.CalculateGHEffectiveAtomPolarizability(molecule, molecule.Atoms[i], false, - topoDistance); + if (string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) + continue; + diagvalue[counter] = Polarizability.CalculateGHEffectiveAtomPolarizability(molecule, molecule.Atoms[i], false, topoDistance); counter++; } burdenMatrix = BurdenMatrix.EvalMatrix(molecule, diagvalue); @@ -515,7 +510,7 @@ public DescriptorValue> Calculate(IAtomContainer container) } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } @@ -527,7 +522,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(6); for (int i = 0; i < 6; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs index db3a2200..462c93ad 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs @@ -70,8 +70,8 @@ public BPolDescriptor() } } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bpol", typeof(BPolDescriptor).FullName, @@ -81,7 +81,7 @@ public BPolDescriptor() /// The parameters attribute of the BPolDescriptor object /// /// Description of the Exception - public override object[] Parameters + public override IReadOnlyList Parameters { set { @@ -110,7 +110,7 @@ public DescriptorValue> Calculate(IAtomContainer container) double difference; try { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IElement element0; IElement element1; @@ -142,13 +142,13 @@ public DescriptorValue> Calculate(IAtomContainer container) difference = Math.Abs(polarizabilities[atnum] - polarizabilities[1]) * impH; bpol += difference; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(bpol), DescriptorNames); } catch (Exception ex1) { Debug.WriteLine(ex1); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( double.NaN), DescriptorNames, new CDKException("Problems with IsotopeFactory due to " + ex1.ToString(), ex1)); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs index e3c642ae..b1cb63d7 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs @@ -72,14 +72,14 @@ static BasicGroupCountDescriptor() } } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#basicGroupCount", typeof(BasicGroupCountDescriptor).FullName, "The Chemistry Development Kit"); - public override object[] Parameters + public override IReadOnlyList Parameters { get { return null; } set { } @@ -98,7 +98,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { if (tool.Matches(atomContainer)) count += tool.MatchesCount; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(count), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(count), DescriptorNames); } catch (CDKException exception) { @@ -106,9 +106,8 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } - public override IDescriptorResult DescriptorResultType => Result.Instance; - public override IReadOnlyList ParameterNames { get; } - = new string[] { }; + public override IDescriptorResult DescriptorResultType => Result.Instance(); + public override IReadOnlyList ParameterNames { get; } = Array.Empty(); public override object GetParameterType(string name) { @@ -118,7 +117,7 @@ public override object GetParameterType(string name) private DescriptorValue> GetDummyDescriptorValue(Exception exception) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(-1), + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(-1), DescriptorNames, exception); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs index 3ee5dbee..2844b729 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs @@ -18,6 +18,7 @@ */ using NCDK.QSAR.Results; +using System; using System.Collections.Generic; namespace NCDK.QSAR.Descriptors.Moleculars @@ -70,8 +71,8 @@ public BondCountDescriptor() { } /// /// The specification attribute of the BondCountDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#bondCount", typeof(BondCountDescriptor).FullName, @@ -81,11 +82,11 @@ public BondCountDescriptor() { } /// The parameters attribute of the BondCountDescriptor object /// /// Description of the Exception - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("BondCount only expects one parameter"); } @@ -112,7 +113,7 @@ public override IReadOnlyList DescriptorNames { get { - if (order.Equals("")) + if (string.IsNullOrEmpty(order)) return new string[] { "nB" }; else return new string[] { "nB" + order }; @@ -126,7 +127,7 @@ public override IReadOnlyList DescriptorNames /// The number of bonds of a certain type. public DescriptorValue> Calculate(IAtomContainer container) { - if (order.Equals("")) + if (string.IsNullOrEmpty(order)) { int bondCount = 0; foreach (var bond in container.Bonds) @@ -134,7 +135,7 @@ public DescriptorValue> Calculate(IAtomContainer container) bool hasHydrogen = false; for (int i = 0; i < bond.Atoms.Count; i++) { - if (bond.Atoms[i].Symbol.Equals("H")) + if (string.Equals(bond.Atoms[i].Symbol, "H", StringComparison.Ordinal)) { hasHydrogen = true; break; @@ -142,7 +143,7 @@ public DescriptorValue> Calculate(IAtomContainer container) } if (!hasHydrogen) bondCount++; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(bondCount), DescriptorNames, null); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(bondCount), DescriptorNames, null); } else { @@ -154,20 +155,20 @@ public DescriptorValue> Calculate(IAtomContainer container) bondCount += 1; } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(bondCount), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(bondCount), DescriptorNames); } } - private bool BondMatch(BondOrder order, string orderString) + private static bool BondMatch(BondOrder order, string orderString) { - if (order == BondOrder.Single && "s".Equals(orderString)) + if (order == BondOrder.Single && "s".Equals(orderString, StringComparison.Ordinal)) return true; - else if (order == BondOrder.Double && "d".Equals(orderString)) + else if (order == BondOrder.Double && "d".Equals(orderString, StringComparison.Ordinal)) return true; - else if (order == BondOrder.Triple && "t".Equals(orderString)) + else if (order == BondOrder.Triple && "t".Equals(orderString, StringComparison.Ordinal)) return true; else - return (order == BondOrder.Quadruple && "q".Equals(orderString)); + return (order == BondOrder.Quadruple && "q".Equals(orderString, StringComparison.Ordinal)); } /// @@ -185,7 +186,7 @@ private bool BondMatch(BondOrder order, string orderString) /// The parameterType value public override object GetParameterType(string name) { - if ("order".Equals(name)) return ""; + if (string.Equals("order", name, StringComparison.Ordinal)) return ""; return null; } diff --git a/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs index a0d26f2f..e9066685 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs @@ -129,8 +129,8 @@ public class CPSADescriptor : AbstractMolecularDescriptor, IMolecularDescriptor public CPSADescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#CPSA", typeof(CPSADescriptor).FullName, @@ -144,7 +144,7 @@ public CPSADescriptor() { } /// /// The parameters attribute of the CPSADescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } /// /// Gets the parameterType attribute of the CPSADescriptor object. @@ -166,7 +166,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain { for (int i = 0; i < 29; i++) retval.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames, new CDKException("Molecule must have 3D coordinates")); } @@ -191,7 +191,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain Debug.WriteLine("Error in assigning Gasteiger-Marsilli charges"); for (int i = 0; i < 29; i++) retval.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames, new CDKException("Error in getting G-M charges")); } @@ -206,7 +206,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain Debug.WriteLine("Error in surface area calculation"); for (int i = 0; i < 29; i++) retval.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames, new CDKException("Error in surface area calculation")); } @@ -340,7 +340,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain retval.Add(rhsa); retval.Add(rpsa); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs index 8aa7e578..2d512e81 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs @@ -19,6 +19,7 @@ using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.QSAR.Descriptors.Moleculars @@ -59,8 +60,8 @@ public class CarbonTypesDescriptor : AbstractMolecularDescriptor, IMolecularDesc public CarbonTypesDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#carbonTypes", typeof(CarbonTypesDescriptor).FullName, @@ -70,7 +71,7 @@ public CarbonTypesDescriptor() { } /// Sets the parameters attribute of the GravitationalIndexDescriptor object. /// /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { @@ -116,13 +117,15 @@ public DescriptorValue> Calculate(IAtomContainer container) foreach (var atom in container.Atoms) { - if (!atom.Symbol.Equals("C") && !atom.Symbol.Equals("c")) continue; + if (!atom.Symbol.Equals("C", StringComparison.Ordinal) && !atom.Symbol.Equals("c", StringComparison.Ordinal)) + continue; var connectedAtoms = container.GetConnectedAtoms(atom); int cc = 0; foreach (var connectedAtom in connectedAtoms) { - if (connectedAtom.Symbol.Equals("C") || connectedAtom.Symbol.Equals("c")) cc++; + if (connectedAtom.Symbol.Equals("C", StringComparison.Ordinal) || connectedAtom.Symbol.Equals("c", StringComparison.Ordinal)) + cc++; } BondOrder maxBondOrder = GetHighestBondOrder(container, atom); @@ -159,10 +162,10 @@ public DescriptorValue> Calculate(IAtomContainer container) c4sp3 }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } - private BondOrder GetHighestBondOrder(IAtomContainer container, IAtom atom) + private static BondOrder GetHighestBondOrder(IAtomContainer container, IAtom atom) { var bonds = container.GetConnectedBonds(atom); BondOrder maxOrder = BondOrder.Single; diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs index 3dba7086..660ad34b 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs @@ -33,7 +33,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars /// Evaluates chi chain descriptors. /// /// - /// The code currently evluates the simple and valence chi chain descriptors of orders 3, 4, 5, 6 and 7. + /// The code currently evaluates the simple and valence chi chain descriptors of orders 3, 4, 5, 6 and 7. /// It utilizes the graph isomorphism code of the CDK to find fragments matching /// SMILES strings representing the fragments corresponding to each type of chain. /// @@ -74,8 +74,8 @@ public class ChiChainDescriptor : AbstractMolecularDescriptor, IMolecularDescrip public ChiChainDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#chiChain", typeof(ChiChainDescriptor).FullName, @@ -88,7 +88,7 @@ public override object GetParameterType(string name) return null; //To change body of implemented methods use File | Settings | File Templates. } - public override object[] Parameters + public override IReadOnlyList Parameters { set { @@ -108,13 +108,14 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } public DescriptorValue> Calculate(IAtomContainer container) { - if (sp == null) sp = new SmilesParser(container.Builder); + if (sp == null) + sp = new SmilesParser(container.Builder); // we don't make a clone, since removeHydrogens returns a deep copy IAtomContainer localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); @@ -182,17 +183,17 @@ public DescriptorValue> Calculate(IAtomContainer container) order7v, }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(10); - private IList> Order3(IAtomContainer container) + private static List> Order3(IAtomContainer container) { - var ret = new List>(); + var ret = new List>(); - IRingSet rings = Cycles.FindSSSR(container).ToRingSet(); + var rings = Cycles.FindSSSR(container).ToRingSet(); int nring = rings.Count; for (int i = 0; i < nring; i++) @@ -211,9 +212,9 @@ private IList> Order3(IAtomContainer container) return ret; } - private IList> Order4(IAtomContainer atomContainer) + private IEnumerable> Order4(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[2]; + var queries = new QueryAtomContainer[2]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("C1CCC1"), false); @@ -226,9 +227,9 @@ private IList> Order4(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order5(IAtomContainer atomContainer) + private IEnumerable> Order5(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[3]; + var queries = new QueryAtomContainer[3]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("C1CCCC1"), false); @@ -242,9 +243,9 @@ private IList> Order5(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order6(IAtomContainer atomContainer) + private IEnumerable> Order6(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[9]; + var queries = new QueryAtomContainer[9]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CC1CCCC1"), false); @@ -264,7 +265,7 @@ private IList> Order6(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order7(IAtomContainer atomContainer) + private IEnumerable> Order7(IAtomContainer atomContainer) { string[] smiles = { "C1CCCCC1C", diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs index 008dcc80..178f86d7 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs @@ -71,8 +71,8 @@ public class ChiClusterDescriptor : AbstractMolecularDescriptor, IMolecularDescr public ChiClusterDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#chiCluster", typeof(ChiClusterDescriptor).FullName, @@ -81,7 +81,7 @@ public ChiClusterDescriptor() { } public override IReadOnlyList ParameterNames => null; public override object GetParameterType(string name) => null; public override IReadOnlyList DescriptorNames => NAMES; - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } private DescriptorValue> GetDummyDescriptorValue(Exception e) { @@ -89,13 +89,14 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } public DescriptorValue> Calculate(IAtomContainer container) { - if (sp == null) sp = new SmilesParser(container.Builder); + if (sp == null) + sp = new SmilesParser(container.Builder); // removeHydrogens does a deep copy, so no need to clone IAtomContainer localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); @@ -157,15 +158,15 @@ public DescriptorValue> Calculate(IAtomContainer container) order6v, }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(8); - private IList> Order3(IAtomContainer atomContainer) + private IEnumerable> Order3(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("C(C)(C)(C)"), false); @@ -177,13 +178,12 @@ private IList> Order3(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order4(IAtomContainer atomContainer) + private IEnumerable> Order4(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator - .CreateAnyAtomAnyBondContainer(sp.ParseSmiles("C(C)(C)(C)(C)"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("C(C)(C)(C)(C)"), false); } catch (InvalidSmilesException e) { @@ -192,9 +192,9 @@ private IList> Order4(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order5(IAtomContainer atomContainer) + private IEnumerable> Order5(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CC(C)C(C)(C)"), false); @@ -206,9 +206,9 @@ private IList> Order5(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order6(IAtomContainer atomContainer) + private IEnumerable> Order6(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CC(C)C(C)(C)C"), false); diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs index 49c3f379..ed0dac44 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs @@ -53,13 +53,13 @@ internal class ChiIndexUtils /// The target /// An array of query fragments /// A list of lists, each list being the atoms that match the query fragments - public static IList> GetFragments(IAtomContainer atomContainer, QueryAtomContainer[] queries) + public static IEnumerable> GetFragments(IAtomContainer atomContainer, QueryAtomContainer[] queries) { UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester(); - var uniqueSubgraphs = new List>(); + var uniqueSubgraphs = new List>(); foreach (var query in queries) { - IList> subgraphMaps = null; + IEnumerable> subgraphMaps = null; try { // we get the list of bond mappings @@ -69,8 +69,10 @@ public static IList> GetFragments(IAtomContainer atomContainer, Query { Console.Error.WriteLine(e.StackTrace); } - if (subgraphMaps == null) continue; - if (!subgraphMaps.Any()) continue; + if (subgraphMaps == null) + continue; + if (!subgraphMaps.Any()) + continue; // get the atom paths in the unique set of bond maps uniqueSubgraphs.AddRange(GetUniqueBondSubgraphs(subgraphMaps, atomContainer)); @@ -83,19 +85,18 @@ public static IList> GetFragments(IAtomContainer atomContainer, Query // will have number of atoms equal to the number of bonds+1. So we need to check // fragment size against all unique query sizes - I get lazy and don't check // unique query sizes, but the size of each query - var retValue = new List>(); foreach (var fragment in uniqueSubgraphs) { foreach (var query in queries) { if (fragment.Count == query.Atoms.Count) { - retValue.Add(fragment); + yield return fragment; break; } } } - return retValue; + yield break; } /// @@ -104,7 +105,7 @@ public static IList> GetFragments(IAtomContainer atomContainer, Query /// The target /// A list of fragments /// The simple chi index - public static double EvalSimpleIndex(IAtomContainer atomContainer, IList> fragLists) + public static double EvalSimpleIndex(IAtomContainer atomContainer, IEnumerable> fragLists) { double sum = 0; foreach (var fragList in fragLists) @@ -112,11 +113,12 @@ public static double EvalSimpleIndex(IAtomContainer atomContainer, IListA list of fragments /// The valence corrected chi index /// if the cannot be created - public static double EvalValenceIndex(IAtomContainer atomContainer, IList> fragList) + public static double EvalValenceIndex(IAtomContainer atomContainer, IEnumerable> fragList) { try { - IsotopeFactory ifac = Isotopes.Instance; + var ifac = BODRIsotopeFactory.Instance; ifac.ConfigureAtoms(atomContainer); } catch (IOException e) @@ -150,12 +152,12 @@ public static double EvalValenceIndex(IAtomContainer atomContainer, IListThe empirical delta V if it is present in one of the above environments, -1 otherwise protected internal static double DeltavSulphur(IAtom atom, IAtomContainer atomContainer) { - if (!atom.Symbol.Equals("S")) return -1; + if (!string.Equals(atom.Symbol, "S", StringComparison.Ordinal)) + return -1; // check whether it's a S in S-S var connected = atomContainer.GetConnectedAtoms(atom); foreach (var connectedAtom in connected) { - if (connectedAtom.Symbol.Equals("S") - && atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Single) return .89; + if (connectedAtom.Symbol.Equals("S", StringComparison.Ordinal) + && atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Single) + return 0.89; } int count = 0; foreach (var connectedAtom in connected) { - if (connectedAtom.Symbol.Equals("O") - && atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Double) count++; + if (connectedAtom.Symbol.Equals("O", StringComparison.Ordinal) + && atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Double) + count++; } if (count == 1) return 1.33; // check whether it's a S in -SO- - else if (count == 2) return 2.67; // check whether it's a S in -SO2- + else if (count == 2) + return 2.67; // check whether it's a S in -SO2- return -1; } @@ -242,20 +249,25 @@ protected internal static double DeltavSulphur(IAtom atom, IAtomContainer atomCo /// The empirical delta V if present in the above environment, -1 otherwise private static double DeltavPhosphorous(IAtom atom, IAtomContainer atomContainer) { - if (!atom.Symbol.Equals("P")) return -1; + if (!string.Equals(atom.Symbol, "P", StringComparison.Ordinal)) + return -1; var connected = atomContainer.GetConnectedAtoms(atom); int conditions = 0; - if (connected.Count() == 4) conditions++; + if (connected.Count() == 4) + conditions++; foreach (var connectedAtom in connected) { - if (connectedAtom.Symbol.Equals("O") - && atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Double) conditions++; - if (atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Single) conditions++; + if (connectedAtom.Symbol.Equals("O", StringComparison.Ordinal) + && atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Double) + conditions++; + if (atomContainer.GetBond(atom, connectedAtom).Order == BondOrder.Single) + conditions++; } - if (conditions == 5) return 2.22; + if (conditions == 5) + return 2.22; return -1; } @@ -270,9 +282,9 @@ private static double DeltavPhosphorous(IAtom atom, IAtomContainer atomContainer /// A of bon mappings /// The molecule we are examining /// A unique of atom paths - private static IList> GetUniqueBondSubgraphs(IList> subgraphs, IAtomContainer ac) + private static List> GetUniqueBondSubgraphs(IEnumerable> subgraphs, IAtomContainer ac) { - List> bondList = new List>(); + var bondList = new List>(); foreach (var subgraph in subgraphs) { var current = subgraph; @@ -287,21 +299,20 @@ private static IList> GetUniqueBondSubgraphs(IList> subgr foreach (var bl in bondList) { if (Compares.AreEqual(bl, ids)) - goto GO_NO_REGISTER; ; + goto GO_NO_REGISTER; } - bondList.Add(ids); - GO_NO_REGISTER: + bondList.Add(ids); + GO_NO_REGISTER: ; } - var paths = new List>(); + var paths = new List>(); foreach (var aBondList1 in bondList) { var aBondList = aBondList1; var tmp = new List(); - foreach (var anABondList in aBondList) + foreach (var bondNumber in aBondList) { - int bondNumber = (int)anABondList; foreach (var atom in ac.Bonds[bondNumber].Atoms) { int atomInt = ac.Atoms.IndexOf(atom); diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs index 23940743..445cd19b 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs @@ -69,8 +69,8 @@ public class ChiPathClusterDescriptor : AbstractMolecularDescriptor, IMolecularD public ChiPathClusterDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#chiPathCluster", typeof(ChiPathClusterDescriptor).FullName, @@ -79,20 +79,20 @@ public ChiPathClusterDescriptor() { } public override IReadOnlyList ParameterNames => null; public override object GetParameterType(string name) => null; public override IReadOnlyList DescriptorNames => NAMES; - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public DescriptorValue> Calculate(IAtomContainer container) { - if (sp == null) sp = new SmilesParser(container.Builder); + if (sp == null) + sp = new SmilesParser(container.Builder); - IAtomContainer localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); + var localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); + var matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); foreach (var atom in localAtomContainer.Atoms) { - IAtomType type; try { - type = matcher.FindMatchingAtomType(localAtomContainer, atom); + var type = matcher.FindMatchingAtomType(localAtomContainer, atom); AtomTypeManipulator.Configure(atom, type); } catch (Exception e) @@ -140,7 +140,7 @@ public DescriptorValue> Calculate(IAtomContainer container) order6v, }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } private DescriptorValue> GetDummyDescriptorValue(Exception e) @@ -149,14 +149,14 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(6); - private IList> Order4(IAtomContainer atomContainer) + private IEnumerable> Order4(IAtomContainer atomContainer) { QueryAtomContainer[] queries = new QueryAtomContainer[1]; try @@ -170,7 +170,7 @@ private IList> Order4(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order5(IAtomContainer atomContainer) + private IEnumerable> Order5(IAtomContainer atomContainer) { QueryAtomContainer[] queries = new QueryAtomContainer[3]; try @@ -186,9 +186,9 @@ private IList> Order5(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order6(IAtomContainer atomContainer) + private IEnumerable> Order6(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[6]; + var queries = new QueryAtomContainer[6]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CC(C)(C)CCC"), false); diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs index e5021968..b700f3cc 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs @@ -20,7 +20,6 @@ using NCDK.AtomTypes; using NCDK.Isomorphisms.Matchers; using NCDK.QSAR.Results; -using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -58,19 +57,19 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.keyword descriptor public class ChiPathDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { - private SmilesParser sp; - - public ChiPathDescriptor() { } + public ChiPathDescriptor() + { + } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = - new DescriptorSpecification( + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#chiPath", typeof(ChiPathDescriptor).FullName, "The Chemistry Development Kit"); public override IReadOnlyList ParameterNames => null; public override object GetParameterType(string name) => null; - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames { get; } = _DescriptorNames(); private static string[] _DescriptorNames() @@ -86,16 +85,13 @@ private static string[] _DescriptorNames() public DescriptorValue> Calculate(IAtomContainer container) { - if (sp == null) sp = new SmilesParser(container.Builder); - - IAtomContainer localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); + var localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); + var matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); foreach (var atom in localAtomContainer.Atoms) { - IAtomType type; try { - type = matcher.FindMatchingAtomType(localAtomContainer, atom); + var type = matcher.FindMatchingAtomType(localAtomContainer, atom); AtomTypeManipulator.Configure(atom, type); } catch (Exception e) @@ -103,7 +99,7 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException("Error in atom typing: " + e.Message)); } } - CDKHydrogenAdder hAdder = CDKHydrogenAdder.GetInstance(container.Builder); + var hAdder = CDKHydrogenAdder.GetInstance(container.Builder); try { hAdder.AddImplicitHydrogens(localAtomContainer); @@ -142,7 +138,7 @@ public DescriptorValue> Calculate(IAtomContainer container) double order6v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph6); double order7v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph7); - ArrayResult retval = new ArrayResult + var retval = new ArrayResult { order0s, order1s, @@ -162,7 +158,7 @@ public DescriptorValue> Calculate(IAtomContainer container) order7v, }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } catch (CDKException e) { @@ -172,47 +168,44 @@ public DescriptorValue> Calculate(IAtomContainer container) private DescriptorValue> GetDummyDescriptorValue(Exception e) { - int ndesc = DescriptorNames.Count; - ArrayResult results = new ArrayResult(ndesc); + var ndesc = DescriptorNames.Count; + var results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } /// - /// Returns the specific type of the DescriptorResult object. - ///

- /// The return value from this method really indicates what type of result will + /// An object that implements the interface indicating + /// the actual type of values returned by the descriptor in the object + ///

+ /// + /// The value really indicates what type of result will /// be obtained from the object. Note that the same result /// can be achieved by interrogating the object; this method /// allows you to do the same thing, without actually calculating the descriptor. - /// - /// an object that implements the interface indicating - /// the actual type of values returned by the descriptor in the object - /// + /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(16); - private List> Order0(IAtomContainer atomContainer) + private static List> Order0(IAtomContainer atomContainer) { - var fragments = new List>(); + var fragments = new List>(); foreach (var atom in atomContainer.Atoms) { - List tmp = new List - { - atomContainer.Atoms.IndexOf(atom) - }; + var tmp = new List { atomContainer.Atoms.IndexOf(atom) }; fragments.Add(tmp); } return fragments; } - private List> Order1(IAtomContainer atomContainer) + private static List> Order1(IAtomContainer atomContainer) { - var fragments = new List>(); + var fragments = new List>(); foreach (var bond in atomContainer.Bonds) { - if (bond.Atoms.Count != 2) throw new CDKException("We only consider 2 center bonds"); - List tmp = new List + if (bond.Atoms.Count != 2) + throw new CDKException("We only consider 2 center bonds"); + var tmp = new List { atomContainer.Atoms.IndexOf(bond.Atoms[0]), atomContainer.Atoms.IndexOf(bond.Atoms[1]) @@ -222,12 +215,19 @@ private List> Order1(IAtomContainer atomContainer) return fragments; } - private IList> Order2(IAtomContainer atomContainer) + private static readonly IAtomContainer C3 = CDK.SilentSmilesParser.ParseSmiles("CCC"); + private static readonly IAtomContainer C4 = CDK.SilentSmilesParser.ParseSmiles("CCCC"); + private static readonly IAtomContainer C5 = CDK.SilentSmilesParser.ParseSmiles("CCCCC"); + private static readonly IAtomContainer C6 = CDK.SilentSmilesParser.ParseSmiles("CCCCCC"); + private static readonly IAtomContainer C7 = CDK.SilentSmilesParser.ParseSmiles("CCCCCCC"); + private static readonly IAtomContainer C8 = CDK.SilentSmilesParser.ParseSmiles("CCCCCCCC"); + + private static IEnumerable> Order2(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CCC"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(C3, false); } catch (InvalidSmilesException e) { @@ -236,12 +236,12 @@ private IList> Order2(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order3(IAtomContainer atomContainer) + private static IEnumerable> Order3(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CCCC"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(C4, false); } catch (InvalidSmilesException e) { @@ -250,12 +250,12 @@ private IList> Order3(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order4(IAtomContainer atomContainer) + private static IEnumerable> Order4(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CCCCC"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(C5, false); } catch (InvalidSmilesException e) { @@ -264,12 +264,12 @@ private IList> Order4(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order5(IAtomContainer atomContainer) + private static IEnumerable> Order5(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CCCCCC"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(C6, false); } catch (InvalidSmilesException e) { @@ -278,12 +278,12 @@ private IList> Order5(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order6(IAtomContainer atomContainer) + private static IEnumerable> Order6(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CCCCCCC"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(C7, false); } catch (InvalidSmilesException e) { @@ -292,12 +292,12 @@ private IList> Order6(IAtomContainer atomContainer) return ChiIndexUtils.GetFragments(atomContainer, queries); } - private IList> Order7(IAtomContainer atomContainer) + private static IEnumerable> Order7(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { - queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CCCCCCCC"), false); + queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(C8, false); } catch (InvalidSmilesException e) { diff --git a/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs index ae6057ba..795aadb9 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs @@ -71,8 +71,8 @@ public class EccentricConnectivityIndexDescriptor : AbstractMolecularDescriptor, public EccentricConnectivityIndexDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#eccentricConnectivityIndex", typeof(EccentricConnectivityIndexDescriptor).FullName, @@ -95,7 +95,7 @@ public EccentricConnectivityIndexDescriptor() { } /// /// the parameters attribute of the EccentricConnectivityIndexDescriptor object /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } /// /// Calculates the eccentric connectivity @@ -122,7 +122,7 @@ public DescriptorValue> Calculate(IAtomContainer container) eccenindex += max * degree; } Result retval = new Result(eccenindex); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames, null); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs index d94c61da..275a9e21 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs @@ -85,7 +85,7 @@ public DescriptorValue> Calculate(IAtomContainer container) { result = new Result(double.NaN); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames); } /// @@ -107,8 +107,8 @@ public DescriptorValue> Calculate(IAtomContainer container) public override IDescriptorResult DescriptorResultType { get; } = new Result(); /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#fmf", typeof(FMFDescriptor).FullName, @@ -132,7 +132,7 @@ public DescriptorValue> Calculate(IAtomContainer container) /// /// The parameters for this descriptor. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } /// /// Returns an array of names for each descriptor value calculated. diff --git a/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs index 4150a160..a1298e8b 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs @@ -52,18 +52,18 @@ public class FractionalPSADescriptor : AbstractMolecularDescriptor, IMolecularDe { public FractionalPSADescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#fractionalPSA", typeof(FractionalPSADescriptor).FullName, "The Chemistry Development Kit"); - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 0) + if (value.Count != 0) { throw new CDKException("The FractionalPSADescriptor expects zero parameters"); } @@ -78,7 +78,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -111,7 +111,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) // molecular weight foreach (var atom in mol.Atoms) { - weight += Isotopes.Instance.GetMajorIsotope(atom.Symbol).ExactMass.Value; + weight += BODRIsotopeFactory.Instance.GetMajorIsotope(atom.Symbol).ExactMass.Value; weight += (atom.ImplicitHydrogenCount ?? 0) * 1.00782504; } } @@ -121,7 +121,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) throw; return GetDummyDescriptorValue(exception); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( weight == 0 ? 0 : polar / weight), DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs index 38c8d16d..dc9d367e 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs @@ -52,8 +52,8 @@ public class FragmentComplexityDescriptor : AbstractMolecularDescriptor, IMolecu public FragmentComplexityDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#NilaComplexity", typeof(FragmentComplexityDescriptor).FullName, @@ -63,11 +63,11 @@ public FragmentComplexityDescriptor() { } /// The parameters attribute of the FragmentComplexityDescriptor object. /// This descriptor takes no parameter. /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 0) + if (value.Count > 0) { throw new CDKException("FragmentComplexityDescriptor expects no parameter"); } @@ -93,18 +93,18 @@ public DescriptorValue> Calculate(IAtomContainer container) double h = 0; for (int i = 0; i < container.Atoms.Count; i++) { - if (!container.Atoms[i].Symbol.Equals("H")) + if (!string.Equals(container.Atoms[i].Symbol, "H", StringComparison.Ordinal)) { a++; } - if (!container.Atoms[i].Symbol.Equals("H") & !container.Atoms[i].Symbol.Equals("C")) + if (!container.Atoms[i].Symbol.Equals("H", StringComparison.Ordinal) & !container.Atoms[i].Symbol.Equals("C", StringComparison.Ordinal)) { h++; } } int b = container.Bonds.Count + AtomContainerManipulator.GetImplicitHydrogenCount(container); double c = Math.Abs(b * b - a * a + a) + (h / 100); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(c), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(c), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs index 323c308b..f00150d5 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs @@ -83,8 +83,8 @@ private struct Pair public GravitationalIndexDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#gravitationalIndex", typeof(GravitationalIndexDescriptor).FullName, @@ -93,7 +93,7 @@ public GravitationalIndexDescriptor() { } /// /// The parameters attribute of the GravitationalIndexDescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -115,7 +115,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } @@ -134,7 +134,7 @@ public DescriptorValue> Calculate(IAtomContainer container) double mass2; try { - factory = Isotopes.Instance; + factory = BODRIsotopeFactory.Instance; } catch (Exception e) { @@ -175,7 +175,8 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException("GravitationalIndex: Only handles 2 center bonds")); } - if (b.Atoms[0].Symbol.Equals("H") || b.Atoms[1].Symbol.Equals("H")) continue; + if (b.Atoms[0].Symbol.Equals("H", StringComparison.Ordinal) || b.Atoms[1].Symbol.Equals("H", StringComparison.Ordinal)) + continue; mass1 = factory.GetMajorIsotope(b.Atoms[0].Symbol).MassNumber.Value; mass2 = factory.GetMajorIsotope(b.Atoms[1].Symbol).MassNumber.Value; @@ -198,7 +199,7 @@ public DescriptorValue> Calculate(IAtomContainer container) var x = new List(); for (int i = 0; i < container.Atoms.Count; i++) { - if (!container.Atoms[i].Symbol.Equals("H")) x.Add(i); + if (!string.Equals(container.Atoms[i].Symbol, "H", StringComparison.Ordinal)) x.Add(i); } int npair = x.Count * (x.Count - 1) / 2; var p = new Pair[npair]; @@ -257,7 +258,7 @@ public DescriptorValue> Calculate(IAtomContainer container) Math.Pow(allheavysum, 1.0 / 3.0) }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs index 11e37f54..e4bb670f 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs @@ -87,8 +87,8 @@ public HBondAcceptorCountDescriptor() { } /// /// The specification value /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#hBondacceptors", typeof(HBondAcceptorCountDescriptor).FullName, @@ -99,11 +99,11 @@ public HBondAcceptorCountDescriptor() { } /// /// a means that aromaticity has to be checked /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException($"{nameof(HBondAcceptorCountDescriptor)} expects a single parameter"); } @@ -125,7 +125,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); } /// @@ -158,40 +158,41 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) foreach (var atom in ac.Atoms) { // looking for suitable nitrogen atoms - if (atom.Symbol.Equals("N") && atom.FormalCharge <= 0) + if (atom.Symbol.Equals("N", StringComparison.Ordinal) && atom.FormalCharge <= 0) { - // excluding nitrogens that are adjacent to an oxygen var bonds = ac.GetConnectedBonds(atom); int nPiBonds = 0; foreach (var bond in bonds) { - if (bond.GetConnectedAtom(atom).Symbol.Equals("O")) goto continue_atomloop; + if (bond.GetConnectedAtom(atom).Symbol.Equals("O", StringComparison.Ordinal)) + goto continue_atomloop; if (BondOrder.Double.Equals(bond.Order)) nPiBonds++; } // if the nitrogen is aromatic and there are no pi bonds then it's // lone pair cannot accept any hydrogen bonds - if (atom.IsAromatic && nPiBonds == 0) continue; + if (atom.IsAromatic && nPiBonds == 0) + continue; hBondAcceptors++; } // looking for suitable oxygen atoms - else if (atom.Symbol.Equals("O") && atom.FormalCharge <= 0) + else if (atom.Symbol.Equals("O", StringComparison.Ordinal) && atom.FormalCharge <= 0) { //excluding oxygens that are adjacent to a nitrogen or to an aromatic carbon var neighbours = ac.GetConnectedAtoms(atom); foreach (var neighbour in neighbours) - if (neighbour.Symbol.Equals("N") - || (neighbour.Symbol.Equals("C") && neighbour.IsAromatic)) + if (neighbour.Symbol.Equals("N", StringComparison.Ordinal) + || (neighbour.Symbol.Equals("C", StringComparison.Ordinal) && neighbour.IsAromatic)) goto continue_atomloop; hBondAcceptors++; } - continue_atomloop: + continue_atomloop: ; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(hBondAcceptors), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(hBondAcceptors), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs index 58dbdfa0..b7d3f75a 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs @@ -77,8 +77,8 @@ public HBondDonorCountDescriptor() { } /// /// The specification attribute of the HBondDonorCountDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#hBondDonors", typeof(HBondDonorCountDescriptor).FullName, @@ -87,7 +87,7 @@ public HBondDonorCountDescriptor() { } /// /// The parameter of this HBondDonorCountDescriptor instance. /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { @@ -104,7 +104,7 @@ public override object[] Parameters private IDescriptorValue GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); } /// @@ -119,37 +119,43 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) //IAtom[] atoms = ac.GetAtoms(); // iterate over all atoms of this AtomContainer; use label atomloop to allow for labelled continue - + //atomloop: for (int atomIndex = 0; atomIndex < ac.Atoms.Count; atomIndex++) { IAtom atom = (IAtom)ac.Atoms[atomIndex]; // checking for O and N atoms where the formal charge is >= 0 - if ((atom.Symbol.Equals("O") || atom.Symbol.Equals("N")) && atom.FormalCharge >= 0) + switch (atom.Symbol) { - // implicit hydrogens - int implicitH = atom.ImplicitHydrogenCount ?? 0; - if (implicitH > 0) - { - hBondDonors++; - goto continue_atomloop; // we skip the explicit hydrogens part cause we found implicit hydrogens - } - // explicit hydrogens - var neighbours = ac.GetConnectedAtoms(atom); - foreach (var neighbour in neighbours) - { - if (((IAtom)neighbour).Symbol.Equals("H")) + case "O": + case "N": + if (atom.FormalCharge >= 0) { - hBondDonors++; - goto continue_atomloop; + // implicit hydrogens + int implicitH = atom.ImplicitHydrogenCount ?? 0; + if (implicitH > 0) + { + hBondDonors++; + goto continue_atomloop; // we skip the explicit hydrogens part cause we found implicit hydrogens + } + // explicit hydrogens + var neighbours = ac.GetConnectedAtoms(atom); + foreach (var neighbour in neighbours) + { + if (((IAtom)neighbour).Symbol.Equals("H", StringComparison.Ordinal)) + { + hBondDonors++; + goto continue_atomloop; + } + } } - } + break; } - continue_atomloop: - ; + continue_atomloop: + ; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(hBondDonors), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(hBondDonors), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs index 4439a8d4..b0e0efa8 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs @@ -49,8 +49,8 @@ public HybridizationRatioDescriptor() { } /// /// A which specifies which descriptor is implemented by this class. /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#hybratio", typeof(HybridizationRatioDescriptor).FullName, @@ -60,7 +60,7 @@ public HybridizationRatioDescriptor() { } /// The parameters attribute of the HybridizationRatioDescriptor object. /// This descriptor takes no parameters /// - public override object[] Parameters { get { return Array.Empty(); } set { } } + public override IReadOnlyList Parameters { get { return Array.Empty(); } set { } } public override IReadOnlyList DescriptorNames { get; } = new string[] { "HybRatio" }; @@ -70,7 +70,7 @@ public HybridizationRatioDescriptor() { } /// a dummy value private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -88,13 +88,13 @@ public DescriptorValue> Calculate(IAtomContainer container) int nsp3 = 0; foreach (var atom in clone.Atoms) { - if (!atom.Symbol.Equals("C")) continue; + if (!string.Equals(atom.Symbol, "C", StringComparison.Ordinal)) continue; if (atom.Hybridization == Hybridization.SP2) nsp2++; else if (atom.Hybridization == Hybridization.SP3) nsp3++; } double ratio = nsp3 / (double)(nsp2 + nsp3); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(ratio), DescriptorNames); } catch (CDKException e) diff --git a/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs index 3a29f03b..d22636c1 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs @@ -60,8 +60,8 @@ public KappaShapeIndicesDescriptor() { } /// /// The specification attribute of the KappaShapeIndicesDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#kierValues", typeof(KappaShapeIndicesDescriptor).FullName, "The Chemistry Development Kit"); @@ -70,7 +70,7 @@ public KappaShapeIndicesDescriptor() { } /// The parameters attribute of the /// KappaShapeIndicesDescriptor object /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -206,7 +206,7 @@ public DescriptorValue> Calculate(IAtomContainer container) kierValues.Add(kier1); kierValues.Add(kier2); kierValues.Add(kier3); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, kierValues, + return new DescriptorValue>(specification, ParameterNames, Parameters, kierValues, DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs index 277fc0d0..e863d604 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs @@ -23,6 +23,7 @@ using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; +using System.Linq; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -299,13 +300,13 @@ namespace NCDK.QSAR.Descriptors.Moleculars public class KierHallSmartsDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { private static string[] names; - private static readonly string[] SMARTS = EStateFragments.Smarts; + private static readonly IReadOnlyList SMARTS = EStateFragments.Smarts; public KierHallSmartsDescriptor() { - string[] tmp = EStateFragments.Names; - names = new string[tmp.Length]; - for (int i = 0; i < tmp.Length; i++) + var tmp = EStateFragments.Names; + names = new string[tmp.Count]; + for (int i = 0; i < tmp.Count; i++) names[i] = "khs." + tmp[i]; } @@ -322,8 +323,8 @@ public KierHallSmartsDescriptor() /// Implementation-Vendor: CDK, JOELib, or anything else /// /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#kierHallSmarts", typeof(KierHallSmartsDescriptor).FullName, @@ -333,7 +334,7 @@ public KierHallSmartsDescriptor() /// The parameters attribute of the descriptor. /// /// if any parameters are specified - public override object[] Parameters + public override IReadOnlyList Parameters { get { @@ -352,7 +353,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e) ArrayResult result = new ArrayResult(); foreach (var smart in SMARTS) result.Add(0); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } /// @@ -370,17 +371,17 @@ public DescriptorValue> Calculate(IAtomContainer container) IAtomContainer atomContainer = (IAtomContainer)container.Clone(); atomContainer = AtomContainerManipulator.RemoveHydrogens(atomContainer); - int[] counts = new int[SMARTS.Length]; + int[] counts = new int[SMARTS.Count]; try { SMARTSQueryTool sqt = new SMARTSQueryTool("C", container.Builder); - for (int i = 0; i < SMARTS.Length; i++) + for (int i = 0; i < SMARTS.Count; i++) { sqt.Smarts = SMARTS[i]; bool status = sqt.Matches(atomContainer); if (status) { - counts[i] = sqt.GetUniqueMatchingAtoms().Count; + counts[i] = sqt.GetUniqueMatchingAtoms().Count(); } else counts[i] = 0; @@ -395,11 +396,11 @@ public DescriptorValue> Calculate(IAtomContainer container) foreach (var i in counts) result.Add(i); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames); } /// - public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(SMARTS.Length); + public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(SMARTS.Count); /// /// Gets the parameterNames attribute of the descriptor. diff --git a/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs index 79f5f06c..45b7c9a9 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs @@ -67,8 +67,8 @@ public class LargestChainDescriptor : AbstractMolecularDescriptor, IMolecularDes public LargestChainDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#largestChain", typeof(LargestChainDescriptor).FullName, @@ -83,11 +83,11 @@ public LargestChainDescriptor() { } /// /// /// if more than one parameter or a non-bool parameter is specified - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 2) + if (value.Count > 2) { throw new CDKException("LargestChainDescriptor only expects two parameter"); } @@ -110,7 +110,7 @@ public override object[] Parameters private IDescriptorValue GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); } /// @@ -147,7 +147,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(max), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(max), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs index 3e12f7fa..a721dedb 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs @@ -62,8 +62,8 @@ public class LargestPiSystemDescriptor : AbstractMolecularDescriptor, IMolecular public LargestPiSystemDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#largestPiSystem", typeof(LargestPiSystemDescriptor).FullName, @@ -76,11 +76,11 @@ public LargestPiSystemDescriptor() { } /// aromaticity has been checked (TRUE) or not (FALSE). /// /// if more than one parameter or a non-bool parameter is specified - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("LargestPiSystemDescriptor only expects one parameter"); } @@ -102,7 +102,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); } /// @@ -148,11 +148,10 @@ public DescriptorValue> Calculate(IAtomContainer container) for (int i = 0; i < container.Atoms.Count; i++) { //Possible pi System double bond or triple bond, charge, N or O (free electron pair) - //Debug.WriteLine("atom:"+i+" maxBondOrder:"+container.GetMaximumBondOrder(atoms[i])+" Aromatic:"+atoms[i].IsAromatic+" FormalCharge:"+atoms[i].FormalCharge+" Charge:"+atoms[i].Charge+" Flag:"+atoms[i].IsVisited); if ((container.GetMaximumBondOrder(container.Atoms[i]) != BondOrder.Single || Math.Abs(container.Atoms[i].FormalCharge.Value) >= 1 || container.Atoms[i].IsAromatic - || container.Atoms[i].Symbol.Equals("N") || container.Atoms[i].Symbol.Equals("O")) + || container.Atoms[i].Symbol.Equals("N", StringComparison.Ordinal) || container.Atoms[i].Symbol.Equals("O", StringComparison.Ordinal)) & !container.Atoms[i].IsVisited) { //Debug.WriteLine("...... -> Accepted"); @@ -180,7 +179,7 @@ public DescriptorValue> Calculate(IAtomContainer container) container.Atoms[i].IsVisited = originalFlag4[i]; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result( + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result( largestPiSystemAtomsCount), DescriptorNames); } @@ -210,7 +209,7 @@ private void BreadthFirstSearch(IAtomContainer container, List sphere, Li nextAtom = ((IBond)bond).GetConnectedAtom(atom); if ((container.GetMaximumBondOrder(nextAtom) != BondOrder.Single || Math.Abs(nextAtom.FormalCharge.Value) >= 1 || nextAtom.IsAromatic - || nextAtom.Symbol.Equals("N") || nextAtom.Symbol.Equals("O")) + || nextAtom.Symbol.Equals("N", StringComparison.Ordinal) || nextAtom.Symbol.Equals("O", StringComparison.Ordinal)) & !nextAtom.IsVisited) { //Debug.WriteLine("BDS> AtomNr:"+container.Atoms.IndexOf(nextAtom)+" maxBondOrder:"+container.GetMaximumBondOrder(nextAtom)+" Aromatic:"+nextAtom.IsAromatic+" FormalCharge:"+nextAtom.FormalCharge+" Charge:"+nextAtom.Charge+" Flag:"+nextAtom.IsVisited); @@ -247,7 +246,7 @@ private void BreadthFirstSearch(IAtomContainer container, List sphere, Li /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) { - if ("checkAromaticity".Equals(name)) return false; + if (string.Equals("checkAromaticity", name, StringComparison.Ordinal)) return false; return null; } diff --git a/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs index 6adfbee0..15576fd2 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs @@ -66,8 +66,8 @@ public LengthOverBreadthDescriptor() { } /// /// The specification attribute of the PetitjeanNumberDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#lengthOverBreadth", typeof(LengthOverBreadthDescriptor).FullName, @@ -76,7 +76,7 @@ public LengthOverBreadthDescriptor() { } /// /// Sets the parameters attribute of the PetitjeanNumberDescriptor object /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -87,7 +87,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e double.NaN, double.NaN }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames, e); } /// @@ -166,13 +166,13 @@ public DescriptorValue> Calculate(IAtomContainer atomContain mmLOB }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, DescriptorNames); } /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(2); - private void RotateZ(double[][] coords, double theta) + private static void RotateZ(double[][] coords, double theta) { int natom = coords.Length; double[][] m; @@ -202,7 +202,7 @@ private void RotateZ(double[][] coords, double theta) } } - private double[] Extents(IAtomContainer atomContainer, double[][] coords, bool withRadii) + private static double[] Extents(IAtomContainer atomContainer, double[][] coords, bool withRadii) { double xmax = -1e30; double ymax = -1e30; diff --git a/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs index aea9876d..e6ed07ab 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs @@ -52,7 +52,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.dictref qsar-descriptors:largestAliphaticChain public class LongestAliphaticChainDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { - public const string CHECK_RING_SYSTEM = "checkRingSystem"; + private const string CHECK_RING_SYSTEM = "checkRingSystem"; private bool checkRingSystem = false; private static readonly string[] NAMES = { "nAtomLAC" }; @@ -62,8 +62,8 @@ public class LongestAliphaticChainDescriptor : AbstractMolecularDescriptor, IMol public LongestAliphaticChainDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#longestAliphaticChain", typeof(LongestAliphaticChainDescriptor).FullName, "The Chemistry Development Kit"); @@ -75,11 +75,11 @@ public LongestAliphaticChainDescriptor() { } /// aromaticity has been checked (TRUE) or not (FALSE). /// /// if more than one parameter or a non-bool parameter is specified - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("LongestAliphaticChainDescriptor only expects one parameter"); } @@ -102,7 +102,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { return new DescriptorValue>( - _Specification, + specification, ParameterNames, Parameters, new Result(0), @@ -178,7 +178,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) } return new DescriptorValue>( - _Specification, + specification, ParameterNames, Parameters, new Result(longest), @@ -200,7 +200,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) { - if (name.Equals(CHECK_RING_SYSTEM)) + if (name.Equals(CHECK_RING_SYSTEM, StringComparison.Ordinal)) return true; else throw new ArgumentException("No parameter for name", nameof(name)); diff --git a/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs index 56b1d3af..18eccbac 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs @@ -112,8 +112,8 @@ public MDEDescriptor() } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#mde", typeof(MDEDescriptor).FullName, "The Chemistry Development Kit"); @@ -122,7 +122,7 @@ public MDEDescriptor() /// The parameters attribute of the WeightDescriptor object. /// /// if more than 1 parameter is specified or if the parameter is not of type string - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -142,14 +142,14 @@ public DescriptorValue> Calculate(IAtomContainer container) retval.Add(Dedge(local, i)); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(19); - private double Dedge(IAtomContainer atomContainer, int which) + private static double Dedge(IAtomContainer atomContainer, int which) { int[][] adjMatrix = AdjacencyMatrix.GetMatrix(atomContainer); int[][] tdist = PathTools.ComputeFloydAPSP(adjMatrix); @@ -251,7 +251,7 @@ private double Dedge(IAtomContainer atomContainer, int which) return retval; } - private int[][] EvalATable(IAtomContainer atomContainer, int atomicNum) + private static int[][] EvalATable(IAtomContainer atomContainer, int atomicNum) { //IAtom[] atoms = atomContainer.GetAtoms(); int natom = atomContainer.Atoms.Count; @@ -269,7 +269,7 @@ private int[][] EvalATable(IAtomContainer atomContainer, int atomicNum) return atypes; } - private double EvalCValue(int[][] distmat, int[][] codemat, int type1, int type2) + private static double EvalCValue(int[][] distmat, int[][] codemat, int type1, int type2) { double lambda = 1; double n = 0; diff --git a/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs index 8acb8461..cc391d31 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs @@ -40,8 +40,8 @@ public class MannholdLogPDescriptor : AbstractMolecularDescriptor, IMolecularDes /// /// The specification attribute of the MannholdLogPDescriptor object. /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/" + "chemoinformatics-algorithms/#mannholdLogP", typeof(MannholdLogPDescriptor).FullName, @@ -52,11 +52,11 @@ public class MannholdLogPDescriptor : AbstractMolecularDescriptor, IMolecularDes /// would have been the method to set them. /// /// Exception throw when invalid parameter values are passed - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value != null && value.Length > 0) + if (value != null && value.Count > 0) { throw new CDKException("MannholdLogPDescriptor has no parameters."); } @@ -71,7 +71,7 @@ public override object[] Parameters private IDescriptorValue GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -87,9 +87,9 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) int heteroCount = 0; foreach (var atom in ac.Atoms) { - if (!ChemicalElements.Hydrogen.ToIElement().Symbol.Equals(atom.Symbol)) + if (!ChemicalElements.Hydrogen.ToIElement().Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) { - if (ChemicalElements.Carbon.ToIElement().Symbol.Equals(atom.Symbol)) + if (ChemicalElements.Carbon.ToIElement().Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) { carbonCount++; } @@ -101,7 +101,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } double mLogP = 1.46 + 0.11 * carbonCount - 0.11 * heteroCount; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(mLogP), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(mLogP), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs index 6f43ea7f..7c09eaa4 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs @@ -80,8 +80,8 @@ public class MomentOfInertiaDescriptor : AbstractMolecularDescriptor, IMolecular { private static readonly string[] NAMES = { "MOMI-X", "MOMI-Y", "MOMI-Z", "MOMI-XY", "MOMI-XZ", "MOMI-YZ", "MOMI-R" }; - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#momentOfInertia", typeof(MomentOfInertiaDescriptor).FullName, "The Chemistry Development Kit"); @@ -89,7 +89,7 @@ public class MomentOfInertiaDescriptor : AbstractMolecularDescriptor, IMolecular /// /// The parameters attribute of the MomentOfInertiaDescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -111,7 +111,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } @@ -130,7 +130,7 @@ public DescriptorValue> Calculate(IAtomContainer container) IAtomContainer clone; IsotopeFactory factory; clone = (IAtomContainer)container.Clone(); - factory = Isotopes.Instance; + factory = BODRIsotopeFactory.Instance; factory.ConfigureAtoms(clone); ArrayResult retval = new ArrayResult(7); @@ -214,7 +214,7 @@ public DescriptorValue> Calculate(IAtomContainer container) pri = Math.Sqrt(eval[0] * ccf / MolecularFormulaManipulator.GetTotalExactMass(formula)); retval.Add(Math.Sqrt(Math.PI * 2 * pri * ccf / MolecularFormulaManipulator.GetTotalExactMass(formula))); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs index acf793e0..78337435 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs @@ -69,8 +69,8 @@ public PetitjeanNumberDescriptor() { } /// /// The specification attribute of the PetitjeanNumberDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#petitjeanNumber", typeof(PetitjeanNumberDescriptor).FullName, "The Chemistry Development Kit"); @@ -78,7 +78,7 @@ public PetitjeanNumberDescriptor() { } /// /// The parameters attribute of the PetitjeanNumberDescriptor object /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -98,7 +98,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) petitjeanNumber = 0; else petitjeanNumber = (diameter - radius) / (double)diameter; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(petitjeanNumber), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(petitjeanNumber), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs index 27ce1b5f..c54dbb60 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs @@ -70,8 +70,8 @@ public class PetitjeanShapeIndexDescriptor : AbstractMolecularDescriptor, IMolec public PetitjeanShapeIndexDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#petitjeanShapeIndex", typeof(PetitjeanShapeIndexDescriptor).FullName, "The Chemistry Development Kit"); @@ -79,7 +79,7 @@ public PetitjeanShapeIndexDescriptor() { } /// /// Sets the parameters attribute of the PetitjeanShapeIndexDescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -157,7 +157,7 @@ public DescriptorValue> Calculate(IAtomContainer container) retval.Add(double.NaN); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs index dec82f3e..0b3a8223 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs @@ -20,6 +20,7 @@ using NCDK.Graphs; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -71,8 +72,8 @@ public RotatableBondsCountDescriptor() { } /// /// The specification attribute of the RotatableBondsCountDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rotatableBondsCount", typeof(RotatableBondsCountDescriptor).FullName, "The Chemistry Development Kit"); @@ -81,11 +82,11 @@ public RotatableBondsCountDescriptor() { } /// The parameters attribute of the RotatableBondsCountDescriptor object /// /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 2) + if (value.Count != 2) { throw new CDKException("RotatableBondsCount expects two parameters"); } @@ -126,7 +127,7 @@ public DescriptorValue> Calculate(IAtomContainer ac) } catch (NoSuchAtomException e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); } foreach (var bond in ac.Bonds) { @@ -139,7 +140,8 @@ public DescriptorValue> Calculate(IAtomContainer ac) { IAtom atom0 = bond.Atoms[0]; IAtom atom1 = bond.Atoms[1]; - if (atom0.Symbol.Equals("H") || atom1.Symbol.Equals("H")) continue; + if (atom0.Symbol.Equals("H", StringComparison.Ordinal) || atom1.Symbol.Equals("H", StringComparison.Ordinal)) + continue; if (bond.Order == BondOrder.Single) { if ((BondManipulator.IsLowerOrder(ac.GetMaximumBondOrder(atom0), BondOrder.Triple)) @@ -171,7 +173,7 @@ public DescriptorValue> Calculate(IAtomContainer ac) } } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(rotatableBondsCount), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(rotatableBondsCount), DescriptorNames); } /// @@ -186,14 +188,13 @@ public DescriptorValue> Calculate(IAtomContainer ac) /// /// if both partners are involved in an amide C-N bond /// - private bool IsAmide(IAtom atom0, IAtom atom1, IAtomContainer ac) + private static bool IsAmide(IAtom atom0, IAtom atom1, IAtomContainer ac) { - - if (atom0.Symbol.Equals("C") && atom1.Symbol.Equals("N")) + if (atom0.Symbol.Equals("C", StringComparison.Ordinal) && atom1.Symbol.Equals("N", StringComparison.Ordinal)) { foreach (var neighbor in ac.GetConnectedAtoms(atom0)) { - if (neighbor.Symbol.Equals("O") + if (neighbor.Symbol.Equals("O", StringComparison.Ordinal) && ac.GetBond(atom0, neighbor).Order == BondOrder.Double) { return true; @@ -203,12 +204,12 @@ private bool IsAmide(IAtom atom0, IAtom atom1, IAtomContainer ac) return false; } - private int GetConnectedHCount(IAtomContainer atomContainer, IAtom atom) + private static int GetConnectedHCount(IAtomContainer atomContainer, IAtom atom) { var connectedAtoms = atomContainer.GetConnectedAtoms(atom); int n = 0; foreach (var anAtom in connectedAtoms) - if (anAtom.Symbol.Equals("H")) n++; + if (string.Equals(anAtom.Symbol, "H", StringComparison.Ordinal)) n++; return n; } diff --git a/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs index ac85ce39..840ea83c 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs @@ -64,8 +64,8 @@ public class RuleOfFiveDescriptor : AbstractMolecularDescriptor, IMolecularDescr public RuleOfFiveDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#lipinskifailures", typeof(RuleOfFiveDescriptor).FullName, @@ -79,11 +79,11 @@ public RuleOfFiveDescriptor() { } /// aromaticity should be checked or has already been checked. The name of the paramete /// is checkAromaticity. /// if more than 1 parameter or a non-bool parameter is specified - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException("RuleOfFiveDescriptor expects one parameter"); } @@ -169,10 +169,12 @@ public DescriptorValue> Calculate(IAtomContainer mol) } catch (CDKException e) { - new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); +#pragma warning disable CA1806 // Do not ignore method results + new DescriptorValue>(specification, ParameterNames, Parameters, new Result(0), DescriptorNames, e); +#pragma warning restore CA1806 // Do not ignore method results } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(lipinskifailures), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(lipinskifailures), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs index 4947fa7d..5ae07bb3 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs @@ -44,12 +44,14 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.keyword descriptor public class SmallRingDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { - private static readonly string[] NAMES = {"nSmallRings", // total number of small rings (of size 3 through 9) + private static readonly string[] NAMES = + { + "nSmallRings", // total number of small rings (of size 3 through 9) "nAromRings", // total number of small aromatic rings "nRingBlocks", // total number of distinct ring blocks "nAromBlocks", // total number of "aromatically connected components" "nRings3", "nRings4", "nRings5", "nRings6", "nRings7", "nRings8", "nRings9" // individual breakdown of small rings - }; + }; private IAtomContainer mol; private int[][] atomAdj, bondAdj; // precalculated adjacencies @@ -60,13 +62,15 @@ public class SmallRingDescriptor : AbstractMolecularDescriptor, IMolecularDescri private bool[] piAtom; // true for all atoms involved in a double bond private int[] implicitH; // hydrogens in addition to those encoded - public SmallRingDescriptor() { } + public SmallRingDescriptor() + { + } /// /// Fetch descriptor specification. /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#smallRings", typeof(SmallRingDescriptor).FullName, @@ -75,7 +79,7 @@ public SmallRingDescriptor() { } /// /// parameters: empty array, there are none. /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { } get { return Array.Empty(); } @@ -170,7 +174,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) nRings8, nRings9, }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, result, NAMES); + return new DescriptorValue>(specification, ParameterNames, Parameters, result, NAMES); } // analyze the molecule graph, and build up the desired properties @@ -204,7 +208,7 @@ private void ExcavateMolecule() for (int n = 0; n < na; n++) if (atomAdj[n] == null) { - atomAdj[n] = new int[0]; + atomAdj[n] = Array.Empty(); bondAdj[n] = atomAdj[n]; } @@ -218,14 +222,14 @@ private void ExcavateMolecule() string el = atom.Symbol; int hy = 0; for (int i = 0; i < HYVALENCE_EL.Length; i++) - if (el.Equals(HYVALENCE_EL[i])) + if (el.Equals(HYVALENCE_EL[i], StringComparison.Ordinal)) { hy = HYVALENCE_VAL[i]; break; } if (hy == 0) continue; int ch = atom.FormalCharge.Value; - if (el.Equals("C")) ch = -Math.Abs(ch); + if (string.Equals(el, "C", StringComparison.Ordinal)) ch = -Math.Abs(ch); int unpaired = 0; // (not current available, maybe introduce later) hy += ch - unpaired; for (int i = 0; i < bondAdj[n].Length; i++) @@ -512,23 +516,23 @@ private void DetectRelaxedAromaticity() 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // figure out which atoms have a lone pair which is considered valid for aromaticity: if electrons[i]>=2, then it qualifies - int[] electrons = new int[na]; + var electrons = new int[na]; for (int n = 0; n < na; n++) { - IAtom atom = mol.Atoms[n]; - int atno = atom.AtomicNumber.Value; + var atom = mol.Atoms[n]; + var atno = atom.AtomicNumber.Value; electrons[n] = (ELEMENT_BLOCKS[atno] == 2 ? ELEMENT_VALENCE[atno] : 0) - atom.FormalCharge.Value - implicitH[n]; } for (int n = 0; n < nb; n++) if (bondOrder[n] > 0) { - IBond bond = mol.Bonds[n]; + var bond = mol.Bonds[n]; electrons[mol.Atoms.IndexOf(bond.Atoms[0])] -= bondOrder[n]; electrons[mol.Atoms.IndexOf(bond.Atoms[1])] -= bondOrder[n]; } // pull out all of the small rings that could be upgraded to aromatic - List rings = new List(); + var rings = new List(); foreach (var r in smallRings) if (r.Length <= 7) { @@ -559,7 +563,7 @@ private void DetectRelaxedAromaticity() for (int n = 0; n < rings.Count; n++) { - int[] r = rings[n]; + var r = rings[n]; int pairs = 0, maybe = 0; for (int i = 0; i < r.Length; i++) { @@ -605,15 +609,16 @@ private void DetectRelaxedAromaticity() // rebuild the graph using only aromatic bonds, and count the number of non-singleton connected components private int CountAromaticComponents() { - int na = mol.Atoms.Count; - int[][] graph = new int[na][]; + var na = mol.Atoms.Count; + var graph = new int[na][]; for (int n = 0; n < na; n++) { for (int i = 0; i < atomAdj[n].Length; i++) - if (bondArom[bondAdj[n][i]]) graph[n] = AppendInteger(graph[n], atomAdj[n][i]); + if (bondArom[bondAdj[n][i]]) + graph[n] = AppendInteger(graph[n], atomAdj[n][i]); } - int[] cc = new int[na]; // -1=isolated, so ignore; 0=unassigned; >0=contained in a component + var cc = new int[na]; // -1=isolated, so ignore; 0=unassigned; >0=contained in a component int first = -1, high = 1; for (int n = 0; n < na; n++) { @@ -625,7 +630,8 @@ private int CountAromaticComponents() cc[n] = 1; } } - if (first < 0) return 0; // all isolated + if (first < 0) + return 0; // all isolated while (true) { @@ -633,7 +639,8 @@ private int CountAromaticComponents() { first++; } - if (first >= na) break; + if (first >= na) + break; bool anything = false; for (int i = first; i < na; i++) @@ -648,16 +655,18 @@ private int CountAromaticComponents() } } } - if (!anything) cc[first] = ++high; + if (!anything) + cc[first] = ++high; } return high; } // convenience function for concatenating an integer - private int[] AppendInteger(int[] a, int v) + private static int[] AppendInteger(int[] a, int v) { - if (a == null || a.Length == 0) return new int[] { v }; - int[] b = new int[a.Length + 1]; + if (a == null || a.Length == 0) + return new int[] { v }; + var b = new int[a.Length + 1]; for (int n = a.Length - 1; n >= 0; n--) b[n] = a[n]; b[a.Length] = v; @@ -668,7 +677,8 @@ private int[] AppendInteger(int[] a, int v) private int FindBond(int a1, int a2) { for (int n = atomAdj[a1].Length - 1; n >= 0; n--) - if (atomAdj[a1][n] == a2) return bondAdj[a1][n]; + if (atomAdj[a1][n] == a2) + return bondAdj[a1][n]; return -1; } diff --git a/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs index 0ad328af..1fde522c 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs @@ -23,6 +23,7 @@ using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; namespace NCDK.QSAR.Descriptors.Moleculars @@ -135,8 +136,8 @@ public TPSADescriptor() /// Gets the specification attribute of the TPSADescriptor object. /// /// The specification value - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#tpsa", typeof(TPSADescriptor).FullName, @@ -149,11 +150,11 @@ public TPSADescriptor() /// the descriptor routine should check for aromaticity () or /// not (). /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException("TPSADescriptor expects one parameter"); } @@ -175,7 +176,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -224,71 +225,76 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) // iterate over all atoms of ac foreach (var atom in ac.Atoms) { - if (atom.Symbol.Equals("N") || atom.Symbol.Equals("O") || atom.Symbol.Equals("S") || atom.Symbol.Equals("P")) + switch (atom.Symbol) { - int singleBondCount = 0; - int doubleBondCount = 0; - int tripleBondCount = 0; - int aromaticBondCount = 0; - double maxBondOrder = 0; - double bondOrderSum = 0; - int hCount = 0; - int isIn3MemberRing = 0; + case "N": + case "O": + case "S": + case "P": + int singleBondCount = 0; + int doubleBondCount = 0; + int tripleBondCount = 0; + int aromaticBondCount = 0; + double maxBondOrder = 0; + double bondOrderSum = 0; + int hCount = 0; + int isIn3MemberRing = 0; - // counting the number of single/double/triple/aromatic bonds - var connectedBonds = ac.GetConnectedBonds(atom); - foreach (var connectedBond in connectedBonds) - { - if (connectedBond.IsAromatic) - aromaticBondCount++; - else if (connectedBond.Order == BondOrder.Single) - singleBondCount++; - else if (connectedBond.Order == BondOrder.Double) - doubleBondCount++; - else if (connectedBond.Order == BondOrder.Triple) tripleBondCount++; - } - int formalCharge = atom.FormalCharge.Value; - var connectedAtoms = ac.GetConnectedAtoms(atom).ToList(); - int numberOfNeighbours = connectedAtoms.Count; + // counting the number of single/double/triple/aromatic bonds + var connectedBonds = ac.GetConnectedBonds(atom); + foreach (var connectedBond in connectedBonds) + { + if (connectedBond.IsAromatic) + aromaticBondCount++; + else if (connectedBond.Order == BondOrder.Single) + singleBondCount++; + else if (connectedBond.Order == BondOrder.Double) + doubleBondCount++; + else if (connectedBond.Order == BondOrder.Triple) tripleBondCount++; + } + int formalCharge = atom.FormalCharge.Value; + var connectedAtoms = ac.GetConnectedAtoms(atom).ToList(); + int numberOfNeighbours = connectedAtoms.Count; - // EXPLICIT hydrogens: count the number of hydrogen atoms - for (int neighbourIndex = 0; neighbourIndex < numberOfNeighbours; neighbourIndex++) - if (((IAtom)connectedAtoms[neighbourIndex]).Symbol.Equals("H")) hCount++; - // IMPLICIT hydrogens: count the number of hydrogen atoms and adjust other atom profile properties - int implicitHAtoms = atom.ImplicitHydrogenCount ?? 0; + // EXPLICIT hydrogens: count the number of hydrogen atoms + for (int neighbourIndex = 0; neighbourIndex < numberOfNeighbours; neighbourIndex++) + if (((IAtom)connectedAtoms[neighbourIndex]).Symbol.Equals("H", StringComparison.Ordinal)) + hCount++; + // IMPLICIT hydrogens: count the number of hydrogen atoms and adjust other atom profile properties + int implicitHAtoms = atom.ImplicitHydrogenCount ?? 0; - for (int hydrogenIndex = 0; hydrogenIndex < implicitHAtoms; hydrogenIndex++) - { - hCount++; - numberOfNeighbours++; - singleBondCount++; - } - // Calculate bond order sum using the counters of single/double/triple/aromatic bonds - bondOrderSum += singleBondCount * 1.0; - bondOrderSum += doubleBondCount * 2.0; - bondOrderSum += tripleBondCount * 3.0; - bondOrderSum += aromaticBondCount * 1.5; - // setting maxBondOrder - if (singleBondCount > 0) maxBondOrder = 1.0; - if (aromaticBondCount > 0) maxBondOrder = 1.5; - if (doubleBondCount > 0) maxBondOrder = 2.0; - if (tripleBondCount > 0) maxBondOrder = 3.0; + for (int hydrogenIndex = 0; hydrogenIndex < implicitHAtoms; hydrogenIndex++) + { + hCount++; + numberOfNeighbours++; + singleBondCount++; + } + // Calculate bond order sum using the counters of single/double/triple/aromatic bonds + bondOrderSum += singleBondCount * 1.0; + bondOrderSum += doubleBondCount * 2.0; + bondOrderSum += tripleBondCount * 3.0; + bondOrderSum += aromaticBondCount * 1.5; + // setting maxBondOrder + if (singleBondCount > 0) maxBondOrder = 1.0; + if (aromaticBondCount > 0) maxBondOrder = 1.5; + if (doubleBondCount > 0) maxBondOrder = 2.0; + if (tripleBondCount > 0) maxBondOrder = 3.0; - // isIn3MemberRing checker - if (rs.Contains(atom)) - { - var rsAtom = rs.GetRings(atom); - foreach (var ring in rsAtom) + // isIn3MemberRing checker + if (rs.Contains(atom)) { - if (ring.RingSize == 3) isIn3MemberRing = 1; + var rsAtom = rs.GetRings(atom); + foreach (var ring in rsAtom) + { + if (ring.RingSize == 3) isIn3MemberRing = 1; + } } - } - // create a profile of the current atom (atoms[atomIndex]) according to the profile definition in the constructor - string profile = atom.Symbol + "+" + maxBondOrder.ToString("F1") + "+" + bondOrderSum.ToString("F1") + "+" + numberOfNeighbours - + "+" + hCount + "+" + formalCharge + "+" + aromaticBondCount + "+" + isIn3MemberRing + "+" - + singleBondCount + "+" + doubleBondCount + "+" + tripleBondCount; - //Debug.WriteLine("tpsa profile: "+ profile); - profiles.Add(profile); + // create a profile of the current atom (atoms[atomIndex]) according to the profile definition in the constructor + string profile = atom.Symbol + "+" + maxBondOrder.ToString("F1", NumberFormatInfo.InvariantInfo) + "+" + bondOrderSum.ToString("F1", NumberFormatInfo.InvariantInfo) + "+" + numberOfNeighbours + + "+" + hCount + "+" + formalCharge + "+" + aromaticBondCount + "+" + isIn3MemberRing + "+" + + singleBondCount + "+" + doubleBondCount + "+" + tripleBondCount; + profiles.Add(profile); + break; } } // END OF ATOM LOOP @@ -299,13 +305,11 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (map.ContainsKey(profiles[profileIndex])) { tpsa += (double)map[profiles[profileIndex]]; - //Debug.WriteLine("tpsa contribs: " + profiles.ElementAt(profileIndex) + "\t" + ((double)map[profiles.ElementAt(profileIndex])).Value); } } profiles.Clear(); // remove all profiles from the profiles-Vector - //Debug.WriteLine("tpsa: " + tpsa); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(tpsa), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(tpsa), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs index 8ff662ae..94acf471 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs @@ -35,19 +35,19 @@ namespace NCDK.QSAR.Descriptors.Moleculars public class VABCDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#vabc", typeof(VABCDescriptor).FullName, "The Chemistry Development Kit"); /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 0) + if (value.Count != 0) { throw new CDKException("The VABCDescriptor expects zero parameters"); } @@ -62,7 +62,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -83,7 +83,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) return GetDummyDescriptorValue(exception); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(volume), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(volume), DescriptorNames); } /// @@ -91,7 +91,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// - public override IReadOnlyList ParameterNames { get; } = new string[0]; + public override IReadOnlyList ParameterNames { get; } = Array.Empty(); /// public override object GetParameterType(string name) => null; diff --git a/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs index 139d0d9d..5cd3c36f 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs @@ -62,8 +62,8 @@ public VAdjMaDescriptor() { } /// /// The specification attribute of the VAdjMaDescriptor object /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#vAdjMa", typeof(VAdjMaDescriptor).FullName, @@ -72,7 +72,7 @@ public VAdjMaDescriptor() { } /// /// Tthe parameters attribute of the VAdjMaDescriptor object /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -97,7 +97,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { vadjMa += (Math.Log(n) / Math.Log(2)) + 1; } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(vadjMa), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(vadjMa), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs index c9c9ae69..d088b9ec 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs @@ -113,7 +113,10 @@ namespace NCDK.QSAR.Descriptors.Moleculars public class WHIMDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { string type = ""; - IDictionary hashatwt, hashvdw, hasheneg, hashpol; + private readonly Dictionary hashatwt; + private readonly Dictionary hashvdw; + private readonly Dictionary hasheneg; + private readonly Dictionary hashpol; public WHIMDescriptor() { @@ -121,94 +124,101 @@ public WHIMDescriptor() // set up the values from TOD98 - this.hashatwt = new Dictionary(); - this.hashvdw = new Dictionary(); - this.hasheneg = new Dictionary(); - this.hashpol = new Dictionary(); - - this.hashatwt["H"] = 0.084; - this.hashatwt["B"] = 0.900; - this.hashatwt["C"] = 1.000; - this.hashatwt["N"] = 1.166; - this.hashatwt["O"] = 1.332; - this.hashatwt["F"] = 1.582; - this.hashatwt["Al"] = 2.246; - this.hashatwt["Si"] = 2.339; - this.hashatwt["P"] = 2.579; - this.hashatwt["S"] = 2.670; - this.hashatwt["Cl"] = 2.952; - this.hashatwt["Fe"] = 4.650; - this.hashatwt["Co"] = 4.907; - this.hashatwt["Ni"] = 4.887; - this.hashatwt["Cu"] = 5.291; - this.hashatwt["Zn"] = 5.445; - this.hashatwt["Br"] = 6.653; - this.hashatwt["Sn"] = 9.884; - this.hashatwt["I"] = 10.566; - - this.hashvdw["H"] = 0.299; - this.hashvdw["B"] = 0.796; - this.hashvdw["C"] = 1.000; - this.hashvdw["N"] = 0.695; - this.hashvdw["O"] = 0.512; - this.hashvdw["F"] = 0.410; - this.hashvdw["Al"] = 1.626; - this.hashvdw["Si"] = 1.424; - this.hashvdw["P"] = 1.181; - this.hashvdw["S"] = 1.088; - this.hashvdw["Cl"] = 1.035; - this.hashvdw["Fe"] = 1.829; - this.hashvdw["Co"] = 1.561; - this.hashvdw["Ni"] = 0.764; - this.hashvdw["Cu"] = 0.512; - this.hashvdw["Zn"] = 1.708; - this.hashvdw["Br"] = 1.384; - this.hashvdw["Sn"] = 2.042; - this.hashvdw["I"] = 1.728; - - this.hasheneg["H"] = 0.944; - this.hasheneg["B"] = 0.828; - this.hasheneg["C"] = 1.000; - this.hasheneg["N"] = 1.163; - this.hasheneg["O"] = 1.331; - this.hasheneg["F"] = 1.457; - this.hasheneg["Al"] = 0.624; - this.hasheneg["Si"] = 0.779; - this.hasheneg["P"] = 0.916; - this.hasheneg["S"] = 1.077; - this.hasheneg["Cl"] = 1.265; - this.hasheneg["Fe"] = 0.728; - this.hasheneg["Co"] = 0.728; - this.hasheneg["Ni"] = 0.728; - this.hasheneg["Cu"] = 0.740; - this.hasheneg["Zn"] = 0.810; - this.hasheneg["Br"] = 1.172; - this.hasheneg["Sn"] = 0.837; - this.hasheneg["I"] = 1.012; - - this.hashpol["H"] = 0.379; - this.hashpol["B"] = 1.722; - this.hashpol["C"] = 1.000; - this.hashpol["N"] = 0.625; - this.hashpol["O"] = 0.456; - this.hashpol["F"] = 0.316; - this.hashpol["Al"] = 3.864; - this.hashpol["Si"] = 3.057; - this.hashpol["P"] = 2.063; - this.hashpol["S"] = 1.648; - this.hashpol["Cl"] = 1.239; - this.hashpol["Fe"] = 4.773; - this.hashpol["Co"] = 4.261; - this.hashpol["Ni"] = 3.864; - this.hashpol["Cu"] = 3.466; - this.hashpol["Zn"] = 4.034; - this.hashpol["Br"] = 1.733; - this.hashpol["Sn"] = 4.375; - this.hashpol["I"] = 3.040; + this.hashatwt = new Dictionary + { + ["H"] = 0.084, + ["B"] = 0.900, + ["C"] = 1.000, + ["N"] = 1.166, + ["O"] = 1.332, + ["F"] = 1.582, + ["Al"] = 2.246, + ["Si"] = 2.339, + ["P"] = 2.579, + ["S"] = 2.670, + ["Cl"] = 2.952, + ["Fe"] = 4.650, + ["Co"] = 4.907, + ["Ni"] = 4.887, + ["Cu"] = 5.291, + ["Zn"] = 5.445, + ["Br"] = 6.653, + ["Sn"] = 9.884, + ["I"] = 10.566 + }; + + this.hashvdw = new Dictionary + { + ["H"] = 0.299, + ["B"] = 0.796, + ["C"] = 1.000, + ["N"] = 0.695, + ["O"] = 0.512, + ["F"] = 0.410, + ["Al"] = 1.626, + ["Si"] = 1.424, + ["P"] = 1.181, + ["S"] = 1.088, + ["Cl"] = 1.035, + ["Fe"] = 1.829, + ["Co"] = 1.561, + ["Ni"] = 0.764, + ["Cu"] = 0.512, + ["Zn"] = 1.708, + ["Br"] = 1.384, + ["Sn"] = 2.042, + ["I"] = 1.728 + }; + + this.hasheneg = new Dictionary + { + ["H"] = 0.944, + ["B"] = 0.828, + ["C"] = 1.000, + ["N"] = 1.163, + ["O"] = 1.331, + ["F"] = 1.457, + ["Al"] = 0.624, + ["Si"] = 0.779, + ["P"] = 0.916, + ["S"] = 1.077, + ["Cl"] = 1.265, + ["Fe"] = 0.728, + ["Co"] = 0.728, + ["Ni"] = 0.728, + ["Cu"] = 0.740, + ["Zn"] = 0.810, + ["Br"] = 1.172, + ["Sn"] = 0.837, + ["I"] = 1.012 + }; + + this.hashpol = new Dictionary + { + ["H"] = 0.379, + ["B"] = 1.722, + ["C"] = 1.000, + ["N"] = 0.625, + ["O"] = 0.456, + ["F"] = 0.316, + ["Al"] = 3.864, + ["Si"] = 3.057, + ["P"] = 2.063, + ["S"] = 1.648, + ["Cl"] = 1.239, + ["Fe"] = 4.773, + ["Co"] = 4.261, + ["Ni"] = 3.864, + ["Cu"] = 3.466, + ["Zn"] = 4.034, + ["Br"] = 1.733, + ["Sn"] = 4.375, + ["I"] = 3.040 + }; } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#WHIM", typeof(WHIMDescriptor).FullName, @@ -221,11 +231,11 @@ public WHIMDescriptor() /// mass, volume, eneg, polar /// /// if the parameters are of the wrong type - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 1) + if (value.Count != 1) { throw new CDKException("WHIMDescriptor requires 1 parameter"); } @@ -234,9 +244,17 @@ public override object[] Parameters throw new CDKException("Parameters must be of type string"); } this.type = (string)value[0]; - if (!this.type.Equals("unity") && !this.type.Equals("mass") && !this.type.Equals("volume") - && !this.type.Equals("eneg") && !this.type.Equals("polar")) - throw new CDKException("Weighting scheme must be one of those specified in the API"); + switch (this.type) + { + case "unity": + case "mass": + case "volume": + case "eneg": + case "polar": + break; + default: + throw new CDKException("Weighting scheme must be one of those specified in the API"); + } } get { @@ -274,7 +292,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } @@ -310,28 +328,29 @@ public DescriptorValue> Calculate(IAtomContainer container) IDictionary hash = null; double[] wt = new double[ac.Atoms.Count]; - if (this.type.Equals("unity")) + if (string.Equals(this.type, "unity", StringComparison.Ordinal)) { for (int i = 0; i < ac.Atoms.Count; i++) wt[i] = 1.0; } else { - if (this.type.Equals("mass")) - { - hash = this.hashatwt; - } - else if (this.type.Equals("volume")) - { - hash = this.hashvdw; - } - else if (this.type.Equals("eneg")) - { - hash = this.hasheneg; - } - else if (this.type.Equals("polar")) + switch (this.type) { - hash = this.hashpol; + case "mass": + hash = this.hashatwt; + break; + case "volume": + hash = this.hashvdw; + break; + case "eneg": + hash = this.hasheneg; + break; + case "polar": + hash = this.hashpol; + break; + default: + break; } for (int i = 0; i < ac.Atoms.Count; i++) { @@ -439,7 +458,7 @@ public DescriptorValue> Calculate(IAtomContainer container) d }; - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } } @@ -450,9 +469,9 @@ public DescriptorValue> Calculate(IAtomContainer container) class PCA { - Matrix evec; - Matrix t; - double[] eval; + private readonly Matrix evec; + private Matrix t; + private readonly double[] eval; public PCA(double[][] cmat, double[] wt) { diff --git a/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs index 40e5bb29..aa07d6d9 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs @@ -68,8 +68,8 @@ public class WeightDescriptor : AbstractMolecularDescriptor, IMolecularDescripto public WeightDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification("http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#weight", typeof(WeightDescriptor).FullName, "The Chemistry Development Kit"); @@ -78,11 +78,11 @@ public WeightDescriptor() { } /// The parameters attribute of the WeightDescriptor object. /// /// if more than 1 parameter is specified or if the parameter is not of type string - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length > 1) + if (value.Count > 1) { throw new CDKException("weight only expects one parameter"); } @@ -105,7 +105,7 @@ public override IReadOnlyList DescriptorNames get { string name = "w"; - if (elementName.Equals("*")) + if (string.Equals(elementName, "*", StringComparison.Ordinal)) name = "MW"; else name += elementName; @@ -115,7 +115,7 @@ public override IReadOnlyList DescriptorNames private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -127,14 +127,14 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e) public DescriptorValue> Calculate(IAtomContainer container) { double weight = 0; - if (elementName.Equals("*")) + if (string.Equals(elementName, "*", StringComparison.Ordinal)) { try { for (int i = 0; i < container.Atoms.Count; i++) { //Debug.WriteLine("WEIGHT: "+container.GetAtomAt(i).Symbol +" " +IsotopeFactory.Instance.GetMajorIsotope( container.GetAtomAt(i).Symbol ).ExactMass); - weight += Isotopes.Instance.GetMajorIsotope(container.Atoms[i].Symbol).ExactMass.Value; + weight += BODRIsotopeFactory.Instance.GetMajorIsotope(container.Atoms[i].Symbol).ExactMass.Value; int hcount = container.Atoms[i].ImplicitHydrogenCount ?? 0; weight += (hcount * 1.00782504); } @@ -144,16 +144,16 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(e); } } - else if (elementName.Equals("H")) + else if (string.Equals(elementName, "H", StringComparison.Ordinal)) { try { - IIsotope h = Isotopes.Instance.GetMajorIsotope("H"); + IIsotope h = BODRIsotopeFactory.Instance.GetMajorIsotope("H"); for (int i = 0; i < container.Atoms.Count; i++) { - if (container.Atoms[i].Symbol.Equals(elementName)) + if (container.Atoms[i].Symbol.Equals(elementName, StringComparison.Ordinal)) { - weight += Isotopes.Instance.GetMajorIsotope(container.Atoms[i].Symbol).ExactMass.Value; + weight += BODRIsotopeFactory.Instance.GetMajorIsotope(container.Atoms[i].Symbol).ExactMass.Value; } else { @@ -172,9 +172,9 @@ public DescriptorValue> Calculate(IAtomContainer container) { for (int i = 0; i < container.Atoms.Count; i++) { - if (container.Atoms[i].Symbol.Equals(elementName)) + if (container.Atoms[i].Symbol.Equals(elementName, StringComparison.Ordinal)) { - weight += Isotopes.Instance.GetMajorIsotope(container.Atoms[i].Symbol).ExactMass.Value; + weight += BODRIsotopeFactory.Instance.GetMajorIsotope(container.Atoms[i].Symbol).ExactMass.Value; } } } @@ -184,7 +184,7 @@ public DescriptorValue> Calculate(IAtomContainer container) } } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(weight), + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(weight), DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs index 9d861dd9..52685ea5 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs @@ -72,8 +72,8 @@ public class WeightedPathDescriptor : AbstractMolecularDescriptor, IMolecularDes public WeightedPathDescriptor() { } - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#weightedPath", typeof(WeightedPathDescriptor).FullName, @@ -82,7 +82,7 @@ public WeightedPathDescriptor() { } /// /// The parameters attribute of the WeightedPathDescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -197,13 +197,13 @@ public DescriptorValue> Calculate(IAtomContainer container) mid += count; retval.Add(mid); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(5); - private double[] GetPathWeights(List> pathList, IAtomContainer atomContainer) + private static double[] GetPathWeights(List> pathList, IAtomContainer atomContainer) { double[] pathWts = new double[pathList.Count]; for (int i = 0; i < pathList.Count; i++) diff --git a/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs index 933bab4d..49115c9c 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs @@ -62,11 +62,8 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.keyword Wiener number public class WienerNumbersDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { - private static readonly string[] NAMES = { "WPATH", "WPOL" }; - double[][] matr = null; ArrayResult wienerNumbers = null; - ConnectionMatrix connectionMatrix = new ConnectionMatrix(); /// /// Constructor for the WienerNumbersDescriptor object. @@ -75,8 +72,8 @@ public WienerNumbersDescriptor() { } /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#wienerNumbers", typeof(WienerNumbersDescriptor).FullName, @@ -85,9 +82,9 @@ public WienerNumbersDescriptor() /// /// The parameters attribute of the WienerNumbersDescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } - public override IReadOnlyList DescriptorNames => NAMES; + public override IReadOnlyList DescriptorNames { get; } = new string[] { "WPATH", "WPOL" }; /// /// Calculate the Wiener numbers. @@ -121,8 +118,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain wienerNumbers.Add(wienerPathNumber); wienerNumbers.Add(wienerPolarityNumber); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, wienerNumbers, - DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, wienerNumbers, DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs index ee58086a..bf436fef 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs @@ -117,8 +117,8 @@ public XLogPDescriptor() { } /// /// The specification attribute of the XLogPDescriptor object. /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#xlogP", typeof(XLogPDescriptor).FullName, @@ -128,11 +128,11 @@ public XLogPDescriptor() { } /// The parameters attribute of the XLogPDescriptor object. /// /// - public override object[] Parameters + public override IReadOnlyList Parameters { set { - if (value.Length != 2) + if (value.Count != 2) { throw new CDKException("XLogPDescriptor expects two parameter"); } @@ -148,6 +148,7 @@ public override object[] Parameters checkAromaticity = (bool)value[0]; salicylFlag = (bool)value[1]; } + get { // return the parameters as used for the descriptor calculation @@ -159,7 +160,7 @@ public override object[] Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); } /// @@ -201,7 +202,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } double xlogP = 0; - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); string symbol = ""; int bondCount = 0; int atomCount = ac.Atoms.Count; @@ -215,11 +215,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) for (int i = 0; i < atomCount; i++) { atomi = (IAtom)ac.Atoms[i]; - // Problem fused ring systems + // Problem fused ring systems IList atomRingSet = rs.GetRings(atomi).ToList(); atomi.SetProperty("IS_IN_AROMATIC_RING", false); atomi.SetProperty(CDKPropertyName.PartOfRingOfSize, 0); - //Debug.WriteLine("atomRingSet.size "+atomRingSet.Count); if (atomRingSet.Count > 0) { if (atomRingSet.Count > 1) @@ -234,7 +233,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) foreach (var ring in Cycles.FindEssential(container).ToRingSet()) atomRingSet.Add(ring); } - //Debug.WriteLine(" SSSRatomRingSet.size "+atomRingSet.Count); } for (int j = 0; j < atomRingSet.Count; j++) { @@ -257,15 +255,12 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } } - //else{ - //Debug.WriteLine(); - //} } for (int i = 0; i < atomCount; i++) { atomi = (IAtom)ac.Atoms[i]; - if (xlogPOld == xlogP & i > 0 & !symbol.Equals("H")) + if (xlogPOld == xlogP & i > 0 & !symbol.Equals("H", StringComparison.Ordinal)) { //Debug.WriteLine("\nXlogPAssignmentError: Could not assign atom number:"+(i-1)); } @@ -276,7 +271,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) hsCount = GetHydrogenCount(ac, atomi); maxBondOrder = ac.GetMaximumBondOrder(atomi); #if DEBUG - if (!symbol.Equals("H")) + if (!string.Equals(symbol, "H", StringComparison.Ordinal)) { //Debug.WriteLine("i:"+i+" Symbol:"+symbol+" "+" bondC:"+bondCount+" Charge:"+atoms[i].FormalCharge+" hsC:"+hsCount+" maxBO:"+maxBondOrder+" Arom:"+atoms[i].IsAromatic+" AtomTypeX:"+GetAtomTypeXCount(ac, atoms[i])+" PiSys:"+GetPiSystemsCount(ac, atoms[i])+" C=:"+GetDoubleBondedCarbonsCount(ac, atoms[i])+" AromCc:"+GetAromaticCarbonsCount(ac,atoms[i])+" RS:"+((int)atoms[i].GetProperty(CDKPropertyName.PART_OF_RING_OF_SIZE)).IntValue()+"\t"); } @@ -291,7 +286,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (hsCount >= 1) { xlogP += 0.209; - //Debug.WriteLine("XLOGP: 38 0.209"); } else { @@ -299,11 +293,9 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { case BondOrder.Double: xlogP += 2.073; - //Debug.WriteLine("XLOGP: 40 2.037"); break; case BondOrder.Triple: xlogP += 0.33; - //Debug.WriteLine("XLOGP: 39 0.33"); break; } } @@ -319,18 +311,15 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetAtomTypeXCount(ac, atomi) == 0) { xlogP += 0.296; - //Debug.WriteLine("XLOGP: 34 0.296"); } else { xlogP -= 0.151; - //Debug.WriteLine("XLOGP: 35 C.ar.X -0.151"); } } else { xlogP += 0.337; - //Debug.WriteLine("XLOGP: 32 0.337"); } } else if (GetAromaticNitrogensCount(ac, atomi) >= 1) @@ -340,18 +329,15 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetAtomTypeXCount(ac, atomi) == 0) { xlogP += 0.174; - //Debug.WriteLine("XLOGP: 36 C.ar.(X) 0.174"); } else { xlogP += 0.366; - //Debug.WriteLine("XLOGP: 37 0.366"); } } else if (GetHydrogenCount(ac, atomi) == 1) { xlogP += 0.126; - //Debug.WriteLine("XLOGP: 33 0.126"); } } //NOT aromatic, but sp2 @@ -366,12 +352,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) <= 1) { xlogP += 0.05; - //Debug.WriteLine("XLOGP: 26 0.05"); } else { xlogP += 0.013; - //Debug.WriteLine("XLOGP: 27 0.013"); } } else if (GetAtomTypeXCount(ac, atomi) == 1) @@ -379,12 +363,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP -= 0.03; - //Debug.WriteLine("XLOGP: 28 -0.03"); } else { xlogP -= 0.027; - //Debug.WriteLine("XLOGP: 29 -0.027"); } } else if (GetAtomTypeXCount(ac, atomi) == 2) @@ -392,12 +374,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.005; - //Debug.WriteLine("XLOGP: 30 0.005"); } else { xlogP -= 0.315; - //Debug.WriteLine("XLOGP: 31 -0.315"); } } break; @@ -407,12 +387,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.466; - //Debug.WriteLine("XLOGP: 22 0.466"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 0.136; - //Debug.WriteLine("XLOGP: 23 0.136"); } } else @@ -420,24 +398,20 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.001; - //Debug.WriteLine("XLOGP: 24 0.001"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.31; - //Debug.WriteLine("XLOGP: 25 -0.31"); } } break; case 2: xlogP += 0.42; - //Debug.WriteLine("XLOGP: 21 0.42"); break; } if (GetIfCarbonIsHydrophobic(ac, atomi)) { xlogP += 0.211; - //Debug.WriteLine("XLOGP: Hydrophobic Carbon 0.211"); } }//sp2 NOT aromatic break; @@ -451,17 +425,14 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP -= 0.006; - //Debug.WriteLine("XLOGP: 16 -0.006"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.57; - //Debug.WriteLine("XLOGP: 17 -0.57"); } if (GetPiSystemsCount(ac, atomi) >= 2) { xlogP -= 0.317; - //Debug.WriteLine("XLOGP: 18 -0.317"); } } else @@ -469,12 +440,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP -= 0.316; - //Debug.WriteLine("XLOGP: 19 -0.316"); } else { xlogP -= 0.723; - //Debug.WriteLine("XLOGP: 20 -0.723"); } } break; @@ -484,17 +453,14 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.127; - //Debug.WriteLine("XLOGP: 10 0.127"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.243; - //Debug.WriteLine("XLOGP: 11 -0.243"); } if (GetPiSystemsCount(ac, atomi) >= 2) { xlogP -= 0.499; - //Debug.WriteLine("XLOGP: 12 -0.499"); } } else @@ -502,17 +468,14 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP -= 0.205; - //Debug.WriteLine("XLOGP: 13 -0.205"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.305; - //Debug.WriteLine("XLOGP: 14 -0.305"); } if (GetPiSystemsCount(ac, atomi) >= 2) { xlogP -= 0.709; - //Debug.WriteLine("XLOGP: 15 -0.709"); } } break; @@ -522,17 +485,14 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.358; - //Debug.WriteLine("XLOGP: 4 0.358"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.008; - //Debug.WriteLine("XLOGP: 5 -0.008"); } if (GetPiSystemsCount(ac, atomi) == 2) { xlogP -= 0.185; - //Debug.WriteLine("XLOGP: 6 -0.185"); } } else @@ -540,17 +500,14 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP -= 0.137; - //Debug.WriteLine("XLOGP: 7 -0.137"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.303; - //Debug.WriteLine("XLOGP: 8 -0.303"); } if (GetPiSystemsCount(ac, atomi) == 2) { xlogP -= 0.815; - //Debug.WriteLine("XLOGP: 9 -0.815"); } } break; @@ -560,26 +517,21 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.528; - //Debug.WriteLine("XLOGP: 1 0.528"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 0.267; - //Debug.WriteLine("XLOGP: 2 0.267"); } } else { - //if (GetNitrogenOrOxygenCount(ac, atomi) == 1) { xlogP -= 0.032; - //Debug.WriteLine("XLOGP: 3 -0.032"); } break; } if (GetIfCarbonIsHydrophobic(ac, atomi)) { xlogP += 0.211; - //Debug.WriteLine("XLOGP: Hydrophobic Carbon 0.211"); } break; } @@ -590,7 +542,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) && maxBondOrder == BondOrder.Double) { xlogP += 1.178; - //Debug.WriteLine("XLOGP: 66 1.178"); } else { @@ -602,12 +553,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetAtomTypeXCount(ac, atomi) == 0) { xlogP += 0.078; - //Debug.WriteLine("XLOGP: 57 0.078"); } if (GetAtomTypeXCount(ac, atomi) == 1) { xlogP -= 0.118; - //Debug.WriteLine("XLOGP: 58 -0.118"); } } if (hsCount == 1) @@ -616,20 +565,17 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { xlogP -= 0.096; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 55 -0.096"); } else { xlogP -= 0.044; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 56 -0.044"); } } if (hsCount == 2) { xlogP -= 0.646; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 54 -0.646"); } } else @@ -640,7 +586,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetCarbonsCount(ac, atomi) == 1) { xlogP -= 0.566; - //Debug.WriteLine("XLOGP: 68 -0.566"); } } else if (bondCount == 2) @@ -649,7 +594,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (atomi.GetProperty("IS_IN_AROMATIC_RING")) { xlogP -= 0.493; - //Debug.WriteLine("XLOGP: 67 -0.493"); if (checkAminoAcid != 0) { checkAminoAcid += 1; @@ -664,7 +608,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetDoubleBondedOxygenCount(ac, atomi) == 1) { xlogP += 0.427; - //Debug.WriteLine("XLOGP: 65 0.427"); } } if (GetDoubleBondedNitrogenCount(ac, atomi) == 1) @@ -672,12 +615,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetAtomTypeXCount(ac, atomi) == 0) { xlogP += 0.536; - //Debug.WriteLine("XLOGP: 63 0.536"); } if (GetAtomTypeXCount(ac, atomi) == 1) { xlogP -= 0.597; - //Debug.WriteLine("XLOGP: 64 -0.597"); } } } @@ -688,12 +629,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.007; - //Debug.WriteLine("XLOGP: 59 0.007"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.275; - //Debug.WriteLine("XLOGP: 60 -0.275"); } } else if (GetAtomTypeXCount(ac, atomi) == 1) @@ -701,12 +640,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.366; - //Debug.WriteLine("XLOGP: 61 0.366"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 0.251; - //Debug.WriteLine("XLOGP: 62 0.251"); } } } @@ -717,7 +654,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) // N sp3 if (hsCount == 0) { - //if (rs.Contains(atomi)&&ringSize>3) { if (atomi.IsAromatic || (rs.Contains(atomi) && atomi.GetProperty(CDKPropertyName.PartOfRingOfSize) > 3 && GetPiSystemsCount(ac, atomi) >= 1)) @@ -725,12 +661,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetAtomTypeXCount(ac, atomi) == 0) { xlogP += 0.881; - //Debug.WriteLine("XLOGP: 51 0.881"); } else { xlogP -= 0.01; - //Debug.WriteLine("XLOGP: 53 -0.01"); } } else @@ -740,18 +674,15 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.159; - //Debug.WriteLine("XLOGP: 49 0.159"); } if (GetPiSystemsCount(ac, atomi) > 0) { xlogP += 0.761; - //Debug.WriteLine("XLOGP: 50 0.761"); } } else { xlogP -= 0.239; - //Debug.WriteLine("XLOGP: 52 -0.239"); } } } @@ -759,14 +690,13 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { if (GetAtomTypeXCount(ac, atomi) == 0) { - // like pyrrole + // like pyrrole if (atomi.IsAromatic || (rs.Contains(atomi) && atomi.GetProperty(CDKPropertyName.PartOfRingOfSize) > 3 && GetPiSystemsCount(ac, atomi) >= 2)) { xlogP += 0.545; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 46 0.545"); } else { @@ -774,13 +704,11 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { xlogP -= 0.112; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 44 -0.112"); } if (GetPiSystemsCount(ac, atomi) > 0) { xlogP += 0.166; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 45 0.166"); } } } @@ -790,13 +718,11 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { xlogP += 0.153; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 48 0.153"); } else { xlogP += 0.324; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 47 0.324"); } } } @@ -808,13 +734,11 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { xlogP -= 0.534; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 41 -0.534"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP -= 0.329; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 42 -0.329"); } if (checkAminoAcid != 0) @@ -826,7 +750,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { xlogP -= 1.082; hBondDonors.Add(i); - //Debug.WriteLine("XLOGP: 43 -1.082"); } } } @@ -841,7 +764,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { hBondAcceptors.Add(i); } - //Debug.WriteLine("XLOGP: 75 A=O -0.399"); } else if (bondCount == 1 && hsCount == 0 && (GetPresenceOfNitro(ac, atomi) || GetPresenceOfCarbonil(ac, atomi) == 1) @@ -852,7 +774,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { hBondAcceptors.Add(i); } - //Debug.WriteLine("XLOGP: 75 A=O -0.399"); } else if (bondCount >= 1) { @@ -863,18 +784,15 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.084; - //Debug.WriteLine("XLOGP: 72 R-O-R 0.084"); } if (GetPiSystemsCount(ac, atomi) > 0) { xlogP += 0.435; - //Debug.WriteLine("XLOGP: 73 R-O-R.1 0.435"); } } else if (GetAtomTypeXCount(ac, atomi) == 1) { xlogP += 0.105; - //Debug.WriteLine("XLOGP: 74 R-O-X 0.105"); } } else @@ -886,14 +804,12 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) xlogP -= 0.467; hBondDonors.Add(i); hBondAcceptors.Add(i); - //Debug.WriteLine("XLOGP: 69 R-OH -0.467"); } if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 0.082; hBondDonors.Add(i); hBondAcceptors.Add(i); - //Debug.WriteLine("XLOGP: 70 R-OH.1 0.082"); } } else if (GetAtomTypeXCount(ac, atomi) == 1) @@ -901,7 +817,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) xlogP -= 0.522; hBondDonors.Add(i); hBondAcceptors.Add(i); - //Debug.WriteLine("XLOGP: 71 X-OH -0.522"); } } } @@ -911,19 +826,16 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) || (bondCount == 1 && atomi.FormalCharge == -1)) { xlogP -= 0.148; - //Debug.WriteLine("XLOGP: 78 A=S -0.148"); } else if (bondCount == 2) { if (hsCount == 0) { xlogP += 0.255; - //Debug.WriteLine("XLOGP: 77 A-S-A 0.255"); } else { xlogP += 0.419; - //Debug.WriteLine("XLOGP: 76 A-SH 0.419"); } } else if (bondCount == 3) @@ -931,7 +843,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetOxygenCount(ac, atomi) >= 1) { xlogP -= 1.375; - //Debug.WriteLine("XLOGP: 79 A-SO-A -1.375"); } } else if (bondCount == 4) @@ -939,7 +850,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetDoubleBondedOxygenCount(ac, atomi) >= 2) { xlogP -= 0.168; - //Debug.WriteLine("XLOGP: 80 A-SO2-A -0.168"); } } break; @@ -947,61 +857,51 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (GetDoubleBondedSulfurCount(ac, atomi) >= 1 && bondCount >= 4) { xlogP += 1.253; - //Debug.WriteLine("XLOGP: 82 S=PA3 1.253"); } else if (GetOxygenCount(ac, atomi) >= 1 || GetDoubleBondedOxygenCount(ac, atomi) == 1 && bondCount >= 4) { xlogP -= 0.447; - //Debug.WriteLine("XLOGP: 81 O=PA3 -0.447"); } break; case "F": if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.375; - //Debug.WriteLine("XLOGP: 83 F.0 0.512"); } else if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 0.202; - //Debug.WriteLine("XLOGP: 84 F.1 0.202"); } break; case "Cl": if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.512; - //Debug.WriteLine("XLOGP: 85 Cl.0 0.512"); } else if (GetPiSystemsCount(ac, atomi) >= 1) { xlogP += 0.663; - //Debug.WriteLine("XLOGP: 86 Cl.1 0.663"); } break; case "Br": if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 0.85; - //Debug.WriteLine("XLOGP: 87 Br.0 0.85"); } else if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 0.839; - //Debug.WriteLine("XLOGP: 88 Br.1 0.839"); } break; case "I": if (GetPiSystemsCount(ac, atomi) == 0) { xlogP += 1.05; - //Debug.WriteLine("XLOGP: 89 I.0 1.05"); } else if (GetPiSystemsCount(ac, atomi) == 1) { xlogP += 1.109; - //Debug.WriteLine("XLOGP: 90 I.1 1.109"); } break; } @@ -1012,15 +912,12 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { case 2: xlogP += 0.137; - //Debug.WriteLine("XLOGP: Halogen 1-3 pair 0.137"); break; case 3: xlogP += (3 * 0.137); - //Debug.WriteLine("XLOGP: Halogen 1-3 pair 0.411"); break; case 4: xlogP += (6 * 0.137); - //Debug.WriteLine("XLOGP: Halogen 1-3 pair 1.902"); break; } @@ -1030,14 +927,11 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (!rs.Contains(atomi)) { xlogP += 0.580; - //Debug.WriteLine("XLOGP: sp2 Oxygen 1-5 pair 0.580"); } } } - //Debug.WriteLine("XLOGP: Before Correction:"+xlogP); int[][] pairCheck = null; - // //Debug.WriteLine("Acceptors:"+hBondAcceptors.Count+" Donors:"+hBondDonors.Count); if (hBondAcceptors.Count > 0 && hBondDonors.Count > 0) { pairCheck = InitializeHydrogenPairCheck(Arrays.CreateJagged(atomCount, atomCount)); @@ -1051,13 +945,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) || CheckRingLink(rs, ac, ac.Atoms[hBondDonors[j]])) { int dist = apsp.From(ac.Atoms[hBondAcceptors[i]]).GetDistanceTo(ac.Atoms[hBondDonors[j]]); - // //Debug.WriteLine(" Acc:"+CheckRingLink(rs,ac,atoms[((int)hBondAcceptors[i]).IntValue()]) - // +" S:"+atoms[((int)hBondAcceptors[i]).IntValue()].Symbol - // +" Nr:"+((int)hBondAcceptors[i]).IntValue() - // +" Don:"+CheckRingLink(rs,ac,atoms[((int)hBondDonors[j]).IntValue()]) - // +" S:"+atoms[((int)hBondDonors[j]).IntValue()].Symbol - // +" Nr:"+((int)hBondDonors[j]).IntValue() - // +" i:"+i+" j:"+j+" path:"+path.Count); if (CheckRingLink(rs, ac, ac.Atoms[hBondAcceptors[i]]) && CheckRingLink(rs, ac, ac.Atoms[hBondDonors[j]])) { @@ -1066,7 +953,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) xlogP += 0.429; pairCheck[hBondAcceptors[i]][hBondDonors[j]] = 1; pairCheck[hBondDonors[j]][hBondAcceptors[i]] = 1; - //Debug.WriteLine("XLOGP: Internal HBonds 1-4 0.429"); } } else @@ -1076,7 +962,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) xlogP += 0.429; pairCheck[hBondAcceptors[i]][hBondDonors[j]] = 1; pairCheck[hBondDonors[j]][hBondAcceptors[i]] = 1; - //Debug.WriteLine("XLOGP: Internal HBonds 1-5 0.429"); } } } @@ -1095,9 +980,9 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { bondAtom0 = bond.Atoms[0]; bondAtom1 = bond.Atoms[1]; - if ((bondAtom0.Symbol.Equals("C") && bondAtom1.Symbol.Equals("N")) - || (bondAtom0.Symbol.Equals("N") && bondAtom1.Symbol.Equals("C")) - && bond.Order == BondOrder.Single) + if ((bondAtom0.Symbol.Equals("C", StringComparison.Ordinal) && bondAtom1.Symbol.Equals("N", StringComparison.Ordinal)) + || (bondAtom0.Symbol.Equals("N", StringComparison.Ordinal) && bondAtom1.Symbol.Equals("C", StringComparison.Ordinal)) + && bond.Order == BondOrder.Single) { aminoAcid.RemoveBond(bondAtom0, bondAtom1); aminoAcid.Bonds.Add(new AnyOrderQueryBond((IQueryAtom)bondAtom0, (IQueryAtom)bondAtom1, BondOrder.Single, atomContainer.Builder)); @@ -1105,7 +990,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } - //AtomContainer aminoacid = sp.ParseSmiles("NCC(=O)O"); try { if (universalIsomorphismTester.IsSubgraph(ac, aminoAcid)) @@ -1117,7 +1001,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) { map = (RMap)list[j]; atom1_ = ac.Atoms[map.Id1]; - if (atom1_.Symbol.Equals("O") && ac.GetMaximumBondOrder(atom1_) == BondOrder.Single) + if (atom1_.Symbol.Equals("O", StringComparison.Ordinal) && ac.GetMaximumBondOrder(atom1_) == BondOrder.Single) { if (ac.GetConnectedBonds(atom1_).Count() == 2 && GetHydrogenCount(ac, atom1_) == 0) { @@ -1125,7 +1009,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) else { xlogP -= 2.166; - //Debug.WriteLine("XLOGP: alpha amino acid -2.166"); break; } } @@ -1145,7 +1028,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (universalIsomorphismTester.IsSubgraph(ac, paba)) { xlogP -= 0.501; - //Debug.WriteLine("XLOGP: p-amino sulphonic acid -0.501"); } } catch (CDKException e) @@ -1162,7 +1044,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (universalIsomorphismTester.IsSubgraph(ac, salicilic)) { xlogP += 0.554; - //Debug.WriteLine("XLOGP: salicylic acid 0.554"); } } catch (CDKException e) @@ -1171,8 +1052,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) } } - // ortho oxygen pair - //AtomContainer orthopair = sp.ParseSmiles("OCCO"); + // ortho oxygen pair QueryAtomContainer orthopair = new QueryAtomContainer(atomContainer.Builder); AromaticAtom atom1 = new AromaticAtom(atomContainer.Builder) { Symbol = "C" }; AromaticAtom atom2 = new AromaticAtom(atomContainer.Builder) { Symbol = "C" }; @@ -1193,7 +1073,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (universalIsomorphismTester.IsSubgraph(ac, orthopair)) { xlogP -= 0.268; - //Debug.WriteLine("XLOGP: Ortho oxygen pair -0.268"); } } catch (CDKException e) @@ -1201,7 +1080,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) return GetDummyDescriptorValue(e); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(xlogP), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(xlogP), DescriptorNames); } /// @@ -1220,7 +1099,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// value /// void /// - private int[][] InitializeHydrogenPairCheck(int[][] pairCheck) + private static int[][] InitializeHydrogenPairCheck(int[][] pairCheck) { for (int i = 0; i < pairCheck.Length; i++) { @@ -1239,7 +1118,7 @@ private int[][] InitializeHydrogenPairCheck(int[][] pairCheck) /// /// /// The hydrogenCount value - private bool CheckRingLink(IRingSet ringSet, IAtomContainer ac, IAtom atom) + private static bool CheckRingLink(IRingSet ringSet, IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); if (ringSet.Contains(atom)) @@ -1262,13 +1141,13 @@ private bool CheckRingLink(IRingSet ringSet, IAtomContainer ac, IAtom atom) /// /// /// The hydrogenCount value - private int GetHydrogenCount(IAtomContainer ac, IAtom atom) + private static int GetHydrogenCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int hcounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("H")) + if (string.Equals(neighbour.Symbol, "H", StringComparison.Ordinal)) { hcounter += 1; } @@ -1282,16 +1161,20 @@ private int GetHydrogenCount(IAtomContainer ac, IAtom atom) /// /// /// The alogenCount value - private int GetHalogenCount(IAtomContainer ac, IAtom atom) + private static int GetHalogenCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int acounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("F") || neighbour.Symbol.Equals("I") - || neighbour.Symbol.Equals("Cl") || neighbour.Symbol.Equals("Br")) + switch (neighbour.Symbol) { - acounter += 1; + case "F": + case "I": + case "Cl": + case "Br": + acounter += 1; + break; } } return acounter; @@ -1303,22 +1186,26 @@ private int GetHalogenCount(IAtomContainer ac, IAtom atom) /// /// /// The nitrogenOrOxygenCount value - private int GetAtomTypeXCount(IAtomContainer ac, IAtom atom) + private static int GetAtomTypeXCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int nocounter = 0; IBond bond; foreach (var neighbour in neighbours) { - if ((neighbour.Symbol.Equals("N") || neighbour.Symbol.Equals("O")) - && !neighbour.GetProperty("IS_IN_AROMATIC_RING")) + switch (neighbour.Symbol) { - //if (ac.GetMaximumBondOrder(neighbours[i]) == 1.0) { - bond = ac.GetBond(neighbour, atom); - if (bond.Order != BondOrder.Double) - { - nocounter += 1; - } + case "N": + case "O": + if (!neighbour.GetProperty("IS_IN_AROMATIC_RING")) + { + bond = ac.GetBond(neighbour, atom); + if (bond.Order != BondOrder.Double) + { + nocounter += 1; + } + } + break; } } return nocounter; @@ -1330,15 +1217,20 @@ private int GetAtomTypeXCount(IAtomContainer ac, IAtom atom) /// /// /// The aromaticCarbonsCount value - private int GetAromaticCarbonsCount(IAtomContainer ac, IAtom atom) + private static int GetAromaticCarbonsCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int carocounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("C") && neighbour.IsAromatic) + switch (neighbour.Symbol) { - carocounter += 1; + case "C": + if (neighbour.IsAromatic) + { + carocounter += 1; + } + break; } } return carocounter; @@ -1350,13 +1242,13 @@ private int GetAromaticCarbonsCount(IAtomContainer ac, IAtom atom) /// /// /// The carbonsCount value - private int GetCarbonsCount(IAtomContainer ac, IAtom atom) + private static int GetCarbonsCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int ccounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("C")) + if (string.Equals(neighbour.Symbol, "C", StringComparison.Ordinal)) { if (!neighbour.IsAromatic) { @@ -1373,18 +1265,20 @@ private int GetCarbonsCount(IAtomContainer ac, IAtom atom) /// /// /// The carbonsCount value - private int GetOxygenCount(IAtomContainer ac, IAtom atom) + private static int GetOxygenCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int ocounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("O")) + switch (neighbour.Symbol) { - if (!neighbour.IsAromatic) - { - ocounter += 1; - } + case "O": + if (!neighbour.IsAromatic) + { + ocounter += 1; + } + break; } } return ocounter; @@ -1396,20 +1290,22 @@ private int GetOxygenCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The doubleBondedCarbonsCount value - private int GetDoubleBondedCarbonsCount(IAtomContainer ac, IAtom atom) + private static int GetDoubleBondedCarbonsCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); IBond bond; int cdbcounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("C")) + switch (neighbour.Symbol) { - bond = ac.GetBond(neighbour, atom); - if (bond.Order == BondOrder.Double) - { - cdbcounter += 1; - } + case "C": + bond = ac.GetBond(neighbour, atom); + if (bond.Order == BondOrder.Double) + { + cdbcounter += 1; + } + break; } } return cdbcounter; @@ -1421,7 +1317,7 @@ private int GetDoubleBondedCarbonsCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The doubleBondedOxygenCount value - private int GetDoubleBondedOxygenCount(IAtomContainer ac, IAtom atom) + private static int GetDoubleBondedOxygenCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); IBond bond; @@ -1433,20 +1329,22 @@ private int GetDoubleBondedOxygenCount(IAtomContainer ac, IAtom atom) } foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("O")) + switch (neighbour.Symbol) { - bond = ac.GetBond(neighbour, atom); - if (chargeFlag && neighbour.FormalCharge == -1 && bond.Order == BondOrder.Single) - { - odbcounter += 1; - } - if (!neighbour.IsAromatic) - { - if (bond.Order == BondOrder.Double) + case "O": + bond = ac.GetBond(neighbour, atom); + if (chargeFlag && neighbour.FormalCharge == -1 && bond.Order == BondOrder.Single) { odbcounter += 1; } - } + if (!neighbour.IsAromatic) + { + if (bond.Order == BondOrder.Double) + { + odbcounter += 1; + } + } + break; } } return odbcounter; @@ -1458,27 +1356,29 @@ private int GetDoubleBondedOxygenCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The doubleBondedSulfurCount value - private int GetDoubleBondedSulfurCount(IAtomContainer ac, IAtom atom) + private static int GetDoubleBondedSulfurCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); IBond bond; int sdbcounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("S")) + switch (neighbour.Symbol) { - if (atom.FormalCharge == 1 && neighbour.FormalCharge == -1) - { - sdbcounter += 1; - } - bond = ac.GetBond(neighbour, atom); - if (!neighbour.IsAromatic) - { - if (bond.Order == BondOrder.Double) + case "S": + if (atom.FormalCharge == 1 && neighbour.FormalCharge == -1) { sdbcounter += 1; } - } + bond = ac.GetBond(neighbour, atom); + if (!neighbour.IsAromatic) + { + if (bond.Order == BondOrder.Double) + { + sdbcounter += 1; + } + } + break; } } return sdbcounter; @@ -1490,23 +1390,25 @@ private int GetDoubleBondedSulfurCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The doubleBondedNitrogenCount value - private int GetDoubleBondedNitrogenCount(IAtomContainer ac, IAtom atom) + private static int GetDoubleBondedNitrogenCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); IBond bond; int ndbcounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("N")) + switch (neighbour.Symbol) { - bond = ac.GetBond(neighbour, atom); - if (!neighbour.IsAromatic) - { - if (bond.Order == BondOrder.Double) + case "N": + bond = ac.GetBond(neighbour, atom); + if (!neighbour.IsAromatic) { - ndbcounter += 1; + if (bond.Order == BondOrder.Double) + { + ndbcounter += 1; + } } - } + break; } } return ndbcounter; @@ -1518,15 +1420,20 @@ private int GetDoubleBondedNitrogenCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The aromaticNitrogensCount value - private int GetAromaticNitrogensCount(IAtomContainer ac, IAtom atom) + private static int GetAromaticNitrogensCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int narocounter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("N") && neighbour.GetProperty("IS_IN_AROMATIC_RING")) + switch (neighbour.Symbol) { - narocounter += 1; + case "N": + if (neighbour.GetProperty("IS_IN_AROMATIC_RING")) + { + narocounter += 1; + } + break; } } return narocounter; @@ -1540,7 +1447,7 @@ private int GetAromaticNitrogensCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The piSystemsCount value - private int GetPiSystemsCount(IAtomContainer ac, IAtom atom) + private static int GetPiSystemsCount(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int picounter = 0; @@ -1549,17 +1456,18 @@ private int GetPiSystemsCount(IAtomContainer ac, IAtom atom) var bonds = ac.GetConnectedBonds(neighbour); foreach (var bond in bonds) { - if (bond.Order != BondOrder.Single && !bond.GetConnectedAtom(neighbour).Equals(atom) - && !neighbour.Symbol.Equals("P") && !neighbour.Symbol.Equals("S")) + if (bond.Order != BondOrder.Single && !bond.GetConnectedAtom(neighbour).Equals(atom)) { - picounter += 1; + switch (neighbour.Symbol) + { + case "P": + case "S": + break; + default: + picounter += 1; + break; + } } - // else if (bonds[j].GetConnectedAtom(neighbours[i])!=atom && - // !neighbours[i].Symbol.Equals("P") && - // !neighbours[i].Symbol.Equals("S") && - // bonds[j].getConnectedAtom - // (neighbours[i]).IsAromatic){ picounter - // += 1; } } } return picounter; @@ -1571,15 +1479,15 @@ private int GetPiSystemsCount(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The presenceOfCarbonil value - private bool GetPresenceOfHydroxy(IAtomContainer ac, IAtom atom) + private static bool GetPresenceOfHydroxy(IAtomContainer ac, IAtom atom) { IAtom neighbour0 = (IAtom)ac.GetConnectedAtoms(atom).First(); - if (neighbour0.Symbol.Equals("C")) + if (string.Equals(neighbour0.Symbol, "C", StringComparison.Ordinal)) { var first = ac.GetConnectedAtoms(neighbour0); foreach (var conAtom in first) { - if (conAtom.Symbol.Equals("O")) + if (string.Equals(conAtom.Symbol, "O", StringComparison.Ordinal)) { if (ac.GetBond(neighbour0, conAtom).Order == BondOrder.Single) { @@ -1600,23 +1508,22 @@ private bool GetPresenceOfHydroxy(IAtomContainer ac, IAtom atom) /// /// Gets the presenceOfN=O attribute of the XLogPDescriptor object. - /// + /// /// Description of the Parameter /// Description of the Parameter /// The presenceOfNitor [bool] - /// - private bool GetPresenceOfNitro(IAtomContainer ac, IAtom atom) + private static bool GetPresenceOfNitro(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); //int counter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("N")) + if (string.Equals(neighbour.Symbol, "N", StringComparison.Ordinal)) { var second = ac.GetConnectedAtoms(neighbour); foreach (var conAtom in second) { - if (conAtom.Symbol.Equals("O")) + if (string.Equals(conAtom.Symbol, "O", StringComparison.Ordinal)) { var bond = ac.GetBond(neighbour, conAtom); if (bond.Order == BondOrder.Double) @@ -1632,20 +1539,16 @@ private bool GetPresenceOfNitro(IAtomContainer ac, IAtom atom) /// /// Gets the presenceOfSulfat A-S(O2)-A attribute of the XLogPDescriptor object. - /// + /// /// Description of the Parameter /// Description of the Parameter /// The presenceOfSulfat [bool] - /// - private bool GetPresenceOfSulfat(IAtomContainer ac, IAtom atom) + private static bool GetPresenceOfSulfat(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); - //IAtom[] second = null; - //IBond bond = null; - //int counter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("S") && GetOxygenCount(ac, neighbour) >= 2 + if (neighbour.Symbol.Equals("S", StringComparison.Ordinal) && GetOxygenCount(ac, neighbour) >= 2 && ac.GetConnectedBonds(neighbour).Count() == 4) { return true; @@ -1656,23 +1559,22 @@ private bool GetPresenceOfSulfat(IAtomContainer ac, IAtom atom) /// /// Gets the presenceOfCarbonil attribute of the XLogPDescriptor object. - /// + /// /// Description of the Parameter /// Description of the Parameter /// The presenceOfCarbonil value - /// - private int GetPresenceOfCarbonil(IAtomContainer ac, IAtom atom) + private static int GetPresenceOfCarbonil(IAtomContainer ac, IAtom atom) { var neighbours = ac.GetConnectedAtoms(atom); int counter = 0; foreach (var neighbour in neighbours) { - if (neighbour.Symbol.Equals("C")) + if (string.Equals(neighbour.Symbol, "C", StringComparison.Ordinal)) { var second = ac.GetConnectedAtoms(neighbour); foreach (var conAtom in second) { - if (conAtom.Symbol.Equals("O")) + if (string.Equals(conAtom.Symbol, "O", StringComparison.Ordinal)) { var bond = ac.GetBond(neighbour, conAtom); if (bond.Order == BondOrder.Double) @@ -1693,7 +1595,7 @@ private int GetPresenceOfCarbonil(IAtomContainer ac, IAtom atom) /// Description of the Parameter /// Description of the Parameter /// The ifCarbonIsHydrophobic value - private bool GetIfCarbonIsHydrophobic(IAtomContainer ac, IAtom atom) + private static bool GetIfCarbonIsHydrophobic(IAtomContainer ac, IAtom atom) { var first = ac.GetConnectedAtoms(atom); //IAtom[] fourth = null; @@ -1701,48 +1603,40 @@ private bool GetIfCarbonIsHydrophobic(IAtomContainer ac, IAtom atom) { foreach (var firstAtom in first) { - if (firstAtom.Symbol.Equals("C") || firstAtom.Symbol.Equals("H")) - { - } - else + switch (firstAtom.Symbol) { - return false; + case "C": + case "H": + break; + default: + return false; } var second = ac.GetConnectedAtoms(firstAtom); if (second.Any()) { foreach (var secondAtom in second) { - if (secondAtom.Symbol.Equals("C") || secondAtom.Symbol.Equals("H")) - { - } - else + switch (secondAtom.Symbol) { - return false; + case "C": + case "H": + break; + default: + return false; } var third = ac.GetConnectedAtoms(secondAtom); if (third.Any()) { foreach (var thirdAtom in third) { - if (thirdAtom.Symbol.Equals("C") || thirdAtom.Symbol.Equals("H")) - { - } - else + switch (thirdAtom.Symbol) { - return false; + case "C": + case "H": + break; + default: + return false; } - //fourth = ac.GetConnectedAtoms(third[c]); - //if (fourth.Length > 0) { - // for (int d = 0; d < fourth.Length; d++) { - // if (fourth[d].Symbol.Equals("C") || fourth[d].Symbol.Equals("H")) { - // } else { - // return false; - // } - // } - //} else { - // return false; - //} } } else @@ -1776,7 +1670,7 @@ private bool GetIfCarbonIsHydrophobic(IAtomContainer ac, IAtom atom) /// The parameterType value public override object GetParameterType(string name) => true; - private IAtomContainer CreatePaba(IChemObjectBuilder builder) + private static IAtomContainer CreatePaba(IChemObjectBuilder builder) { // SMILES CS(=O)(=O)c1ccc(N)cc1 IAtomContainer container = builder.NewAtomContainer(); @@ -1840,7 +1734,7 @@ private IAtomContainer CreatePaba(IChemObjectBuilder builder) return container; } - private IAtomContainer NewAminoAcid(IChemObjectBuilder builder) + private static IAtomContainer NewAminoAcid(IChemObjectBuilder builder) { // SMILES NCC(=O)O IAtomContainer container = builder.NewAtomContainer(); @@ -1861,7 +1755,7 @@ private IAtomContainer NewAminoAcid(IChemObjectBuilder builder) return container; } - private IAtomContainer CreateSalicylicAcid(IChemObjectBuilder builder) + private static IAtomContainer CreateSalicylicAcid(IChemObjectBuilder builder) { // SMILES O=C(O)c1ccccc1O IAtomContainer container = builder.NewAtomContainer(); diff --git a/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs index 1dec2e32..11052821 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs @@ -18,6 +18,7 @@ */ using NCDK.QSAR.Results; +using System; using System.Collections.Generic; namespace NCDK.QSAR.Descriptors.Moleculars @@ -44,8 +45,8 @@ public ZagrebIndexDescriptor() { } /// /// The specification attribute of the ZagrebIndexDescriptor object. /// - public override IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public override IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#zagrebIndex", typeof(ZagrebIndexDescriptor).FullName, @@ -54,7 +55,7 @@ public ZagrebIndexDescriptor() { } /// /// The parameters attribute of the ZagrebIndexDescriptor object. /// - public override object[] Parameters { get { return null; } set { } } + public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -68,19 +69,19 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) double zagreb = 0; foreach (var atom in atomContainer.Atoms) { - if (atom.Symbol.Equals("H")) continue; + if (string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) continue; int atomDegree = 0; var neighbours = atomContainer.GetConnectedAtoms(atom); foreach (var neighbour in neighbours) { - if (!neighbour.Symbol.Equals("H")) + if (!string.Equals(neighbour.Symbol, "H", StringComparison.Ordinal)) { atomDegree += 1; } } zagreb += (atomDegree * atomDegree); } - return new DescriptorValue>(_Specification, ParameterNames, Parameters, new Result(zagreb), DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(zagreb), DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Proteins/TaeAminoAcidDescriptor.cs b/NCDK/QSAR/Descriptors/Proteins/TaeAminoAcidDescriptor.cs index 25126a4a..842a5ed3 100644 --- a/NCDK/QSAR/Descriptors/Proteins/TaeAminoAcidDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Proteins/TaeAminoAcidDescriptor.cs @@ -16,10 +16,12 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.QSAR.Results; using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; namespace NCDK.QSAR.Descriptors.Proteins @@ -103,7 +105,7 @@ public partial class TaeAminoAcidDescriptor : IMolecularDescriptor private Dictionary nametrans = new Dictionary(); - private List GetMonomers(IBioPolymer iBioPolymer) + private static List GetMonomers(IBioPolymer iBioPolymer) { List monomList = new List(); @@ -147,7 +149,7 @@ private void LoadTAEParams() double[] data = new double[ndesc]; for (int j = 1; j < components.Length; j++) - data[j - 1] = double.Parse(components[j]); + data[j - 1] = double.Parse(components[j], NumberFormatInfo.InvariantInfo); taeParams[key] = data; } @@ -194,8 +196,8 @@ public TaeAminoAcidDescriptor() LoadTAEParams(); } - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#taeAminoAcid", typeof(TaeAminoAcidDescriptor).FullName, "The Chemistry Development Kit"); @@ -203,7 +205,7 @@ public TaeAminoAcidDescriptor() /// /// The parameters attribute of the TaeAminoAcidDescriptor object. /// - public object[] Parameters { get { return null; } set { } } + public IReadOnlyList Parameters { get { return null; } set { } } public IReadOnlyList DescriptorNames { @@ -234,7 +236,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e ArrayResult results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, results, DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } /// @@ -265,10 +267,10 @@ public DescriptorValue> Calculate(IAtomContainer container) if (o.Length == 0) continue; - string olc = o.ToLowerInvariant()[0].ToString(); + string olc = new string(new char[] { o.ToLowerInvariant()[0] }); string tlc = (string)nametrans[olc]; - Debug.WriteLine("Converted " + olc + " to " + tlc); + Debug.WriteLine($"Converted {olc} to {tlc}"); // get the params for this AA Double[] parameters = (Double[])taeParams[tlc]; @@ -281,7 +283,7 @@ public DescriptorValue> Calculate(IAtomContainer container) for (int i = 0; i < ndesc; i++) retval.Add(desc[i]); - return new DescriptorValue>(_Specification, ParameterNames, Parameters, retval, DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) diff --git a/NCDK/QSAR/Descriptors/Substances/OxygenAtomCountDescriptor.cs b/NCDK/QSAR/Descriptors/Substances/OxygenAtomCountDescriptor.cs index 66c5c0c3..e74afefc 100644 --- a/NCDK/QSAR/Descriptors/Substances/OxygenAtomCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Substances/OxygenAtomCountDescriptor.cs @@ -38,15 +38,15 @@ public class OxygenAtomCountDescriptor : ISubstanceDescriptor public object GetParameterType(string substance) => null; /// - public object[] Parameters + public IReadOnlyList Parameters { get { return Array.Empty(); } set { } } /// - public IImplementationSpecification Specification => _Specification; - private static DescriptorSpecification _Specification { get; } = + public IImplementationSpecification Specification => specification; + private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://egonw.github.com/resource/NM_001002", typeof(OxygenAtomCountDescriptor).FullName, @@ -62,14 +62,14 @@ public DescriptorValue> Calculate(ISubstance substance) { foreach (var atom in container.Atoms) { - if ("O".Equals(atom.Symbol) || 8 == atom.AtomicNumber) + if (string.Equals("O", atom.Symbol, StringComparison.Ordinal) || 8 == atom.AtomicNumber) count++; } } } return new DescriptorValue>( - _Specification, ParameterNames, Parameters, + specification, ParameterNames, Parameters, new Result(count), DescriptorNames ); } @@ -78,6 +78,6 @@ IDescriptorValue ISubstanceDescriptor.Calculate(ISubstance substance) => Calculate(substance); /// - public IDescriptorResult DescriptorResultType { get; } = Result.Instance; + public IDescriptorResult DescriptorResultType { get; } = Result.Instance(); } } diff --git a/NCDK/QSAR/IAtomicDescriptor b/NCDK/QSAR/IAtomicDescriptor index 49285ed3..584e2e3c 100644 --- a/NCDK/QSAR/IAtomicDescriptor +++ b/NCDK/QSAR/IAtomicDescriptor @@ -2,11 +2,11 @@ NCDK.QSAR.Descriptors.Atomic.VdWRadiusDescriptor NCDK.QSAR.Descriptors.Atomic.StabilizationPlusChargeDescriptor NCDK.QSAR.Descriptors.Atomic.SigmaElectronegativityDescriptor -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GSR -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GHR_topol -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GHR -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GDR -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_G3R +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGSR +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGHRTopology +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGHR +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGDR +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorG3R NCDK.QSAR.Descriptors.Atomic.ProtonTotalPartialChargeDescriptor NCDK.QSAR.Descriptors.Atomic.ProtonAffinityHOSEDescriptor NCDK.QSAR.Descriptors.Atomic.PiElectronegativityDescriptor diff --git a/NCDK/QSAR/IDescriptor.cs b/NCDK/QSAR/IDescriptor.cs index 64769eee..470a0849 100644 --- a/NCDK/QSAR/IDescriptor.cs +++ b/NCDK/QSAR/IDescriptor.cs @@ -139,7 +139,7 @@ public interface IDescriptor /// /// Must be done before callin calculate as the parameters influence the calculation outcome before set. /// - object[] Parameters { get; set; } + IReadOnlyList Parameters { get; set; } /// /// Returns an array of names for each descriptor value calculated. diff --git a/NCDK/QSAR/Results/ArrayResult.cs b/NCDK/QSAR/Results/ArrayResult.cs index 141405ea..a1abe9e4 100644 --- a/NCDK/QSAR/Results/ArrayResult.cs +++ b/NCDK/QSAR/Results/ArrayResult.cs @@ -33,8 +33,8 @@ public interface IArrayResult public class ArrayResult : IArrayResult, IReadOnlyList { - int size; - List array; + readonly int size; + readonly List array; public ArrayResult() : this(0) diff --git a/NCDK/QSAR/Results/Result.cs b/NCDK/QSAR/Results/Result.cs index 9de02e17..e57a0cad 100644 --- a/NCDK/QSAR/Results/Result.cs +++ b/NCDK/QSAR/Results/Result.cs @@ -24,11 +24,19 @@ public interface IResult { } + internal static class ResultInstance + { + public static readonly Result Value = new Result(); + } + + public static class Result + { + public static Result Instance() => ResultInstance.Value; + } + public class Result : IResult { - public static Result Instance { get; } = new Result(); - public T Value { get; private set; } public Result() diff --git a/NCDK/Reactions/Mechanisms/AdductionLPMechanism.cs b/NCDK/Reactions/Mechanisms/AdductionLPMechanism.cs index e9d75664..536bb65e 100644 --- a/NCDK/Reactions/Mechanisms/AdductionLPMechanism.cs +++ b/NCDK/Reactions/Mechanisms/AdductionLPMechanism.cs @@ -18,6 +18,7 @@ */ using NCDK.AtomTypes; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -78,14 +79,16 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom1C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; charge = atom2C.FormalCharge.Value; atom2C.FormalCharge = charge - 1; atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom1C.Builder.NewReaction(); reaction.Reactants.Add(molecule1); diff --git a/NCDK/Reactions/Mechanisms/AdductionPBMechanism.cs b/NCDK/Reactions/Mechanisms/AdductionPBMechanism.cs index 4dc75000..773de59c 100644 --- a/NCDK/Reactions/Mechanisms/AdductionPBMechanism.cs +++ b/NCDK/Reactions/Mechanisms/AdductionPBMechanism.cs @@ -18,6 +18,7 @@ */ using NCDK.AtomTypes; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.Reactions.Mechanisms @@ -81,19 +82,22 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom1C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; charge = atom3C.FormalCharge.Value; atom3C.FormalCharge = charge - 1; atom3C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom1C.Builder.NewReaction(); reaction.Reactants.Add(molecule1); diff --git a/NCDK/Reactions/Mechanisms/HeterolyticCleavageMechanism.cs b/NCDK/Reactions/Mechanisms/HeterolyticCleavageMechanism.cs index b2e0e715..0a172240 100644 --- a/NCDK/Reactions/Mechanisms/HeterolyticCleavageMechanism.cs +++ b/NCDK/Reactions/Mechanisms/HeterolyticCleavageMechanism.cs @@ -19,6 +19,7 @@ using NCDK.AtomTypes; using NCDK.Graphs; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.Reactions.Mechanisms @@ -81,7 +82,8 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom1C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; charge = atom2C.FormalCharge.Value; atom2C.FormalCharge = charge - 1; @@ -90,7 +92,8 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom1C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/HomolyticCleavageMechanism.cs b/NCDK/Reactions/Mechanisms/HomolyticCleavageMechanism.cs index 5f3f00c4..df9b63ea 100644 --- a/NCDK/Reactions/Mechanisms/HomolyticCleavageMechanism.cs +++ b/NCDK/Reactions/Mechanisms/HomolyticCleavageMechanism.cs @@ -19,6 +19,7 @@ using NCDK.AtomTypes; using NCDK.Graphs; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.Reactions.Mechanisms @@ -79,12 +80,14 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList // check if resulting atom type is reasonable atom1C.Hybridization = Hybridization.Unset; IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; // check if resulting atom type is reasonable: an acceptor atom cannot be charged positive*/ atom2C.Hybridization = Hybridization.Unset; type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom2C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/RadicalSiteIonizationMechanism.cs b/NCDK/Reactions/Mechanisms/RadicalSiteIonizationMechanism.cs index 4ca561fa..4c9e79ce 100644 --- a/NCDK/Reactions/Mechanisms/RadicalSiteIonizationMechanism.cs +++ b/NCDK/Reactions/Mechanisms/RadicalSiteIonizationMechanism.cs @@ -19,6 +19,7 @@ using NCDK.AtomTypes; using NCDK.Graphs; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -86,18 +87,21 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom1C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; reactantCloned.SingleElectrons.Add(atom2C.Builder.NewSingleElectron(atom3C)); atom3C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom2C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/RadicalSiteRearrangementMechanism.cs b/NCDK/Reactions/Mechanisms/RadicalSiteRearrangementMechanism.cs index 3d0cc1f6..3378089a 100644 --- a/NCDK/Reactions/Mechanisms/RadicalSiteRearrangementMechanism.cs +++ b/NCDK/Reactions/Mechanisms/RadicalSiteRearrangementMechanism.cs @@ -18,6 +18,7 @@ */ using NCDK.AtomTypes; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -84,13 +85,15 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; reactantCloned.SingleElectrons.Add(atom2C.Builder.NewSingleElectron(atom3C)); atom3C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom2C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/RearrangementChargeMechanism.cs b/NCDK/Reactions/Mechanisms/RearrangementChargeMechanism.cs index da7b5a3a..4d54148a 100644 --- a/NCDK/Reactions/Mechanisms/RearrangementChargeMechanism.cs +++ b/NCDK/Reactions/Mechanisms/RearrangementChargeMechanism.cs @@ -19,6 +19,7 @@ using NCDK.AtomTypes; using NCDK.Graphs; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -122,10 +123,12 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = bond2.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/RemovingSEofBMechanism.cs b/NCDK/Reactions/Mechanisms/RemovingSEofBMechanism.cs index 66c83327..11cc5001 100644 --- a/NCDK/Reactions/Mechanisms/RemovingSEofBMechanism.cs +++ b/NCDK/Reactions/Mechanisms/RemovingSEofBMechanism.cs @@ -19,6 +19,7 @@ using NCDK.AtomTypes; using NCDK.Graphs; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.Reactions.Mechanisms @@ -82,11 +83,13 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom1C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom1C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/RemovingSEofNBMechanism.cs b/NCDK/Reactions/Mechanisms/RemovingSEofNBMechanism.cs index a0e12b65..884b7a78 100644 --- a/NCDK/Reactions/Mechanisms/RemovingSEofNBMechanism.cs +++ b/NCDK/Reactions/Mechanisms/RemovingSEofNBMechanism.cs @@ -18,6 +18,7 @@ */ using NCDK.AtomTypes; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -80,7 +81,8 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList reactantCloned.Atoms[posAtom].Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, reactantCloned.Atoms[posAtom]); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = molecule.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/SharingElectronMechanism.cs b/NCDK/Reactions/Mechanisms/SharingElectronMechanism.cs index bf91aab5..f2106e67 100644 --- a/NCDK/Reactions/Mechanisms/SharingElectronMechanism.cs +++ b/NCDK/Reactions/Mechanisms/SharingElectronMechanism.cs @@ -18,6 +18,7 @@ */ using NCDK.AtomTypes; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -82,12 +83,12 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) return null; atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) return null; IReaction reaction = atom2C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/Mechanisms/TautomerizationMechanism.cs b/NCDK/Reactions/Mechanisms/TautomerizationMechanism.cs index 67a52836..50324624 100644 --- a/NCDK/Reactions/Mechanisms/TautomerizationMechanism.cs +++ b/NCDK/Reactions/Mechanisms/TautomerizationMechanism.cs @@ -18,6 +18,7 @@ */ using NCDK.AtomTypes; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; namespace NCDK.Reactions.Mechanisms @@ -85,12 +86,14 @@ public IReaction Initiate(IChemObjectSet atomContainerSet, IList atom1C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; atom3C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C); - if (type == null || type.AtomTypeName.Equals("X")) return null; + if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return null; IReaction reaction = atom2C.Builder.NewReaction(); reaction.Reactants.Add(molecule); diff --git a/NCDK/Reactions/ReactionEngine.cs b/NCDK/Reactions/ReactionEngine.cs index 8b774a31..991f3c53 100644 --- a/NCDK/Reactions/ReactionEngine.cs +++ b/NCDK/Reactions/ReactionEngine.cs @@ -38,7 +38,8 @@ namespace NCDK.Reactions public class ReactionEngine { private EntryDictionary dictionary; - public Dictionary ParamsMap { get; set; } + + public IReadOnlyDictionary ParamsMap { get; set; } public IReactionMechanism Mechanism { get; set; } /// @@ -69,7 +70,7 @@ private void ExtractMechanism(EntryReact entry) string mechanismName = "NCDK.Reactions.Mechanisms." + entry.Mechanism; try { - Mechanism = (IReactionMechanism)this.GetType().Assembly.GetType(mechanismName).GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + Mechanism = (IReactionMechanism)this.GetType().Assembly.GetType(mechanismName).GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); Trace.TraceInformation("Loaded mechanism: ", mechanismName); } catch (ArgumentException exception) @@ -122,13 +123,13 @@ private void InitiateParameterMap2(EntryReact entry) { var paramDic = entry.ParameterClass; - ParameterList = new List(); + this.ParameterList = new List(); foreach (var param in paramDic) { string paramName = "NCDK.Reactions.Types.Parameters." + param[0]; try { - IParameterReaction ipc = (IParameterReaction)this.GetType().Assembly.GetType(paramName).GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + var ipc = (IParameterReaction)this.GetType().Assembly.GetType(paramName).GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); ipc.IsSetParameter = bool.Parse(param[1]); ipc.Value = param[2]; diff --git a/NCDK/Reactions/Types/$ExampleCodes.tt b/NCDK/Reactions/Types/$ExampleCodes.tt index c53feafd..5ef5829c 100644 --- a/NCDK/Reactions/Types/$ExampleCodes.tt +++ b/NCDK/Reactions/Types/$ExampleCodes.tt @@ -14,9 +14,9 @@ namespace NCDK.Reactions.Types foreach (var cs in source.GetFiles() .Where(fn => fn.Extension == ".cs") .Where(fn => - fn.Name.Length > 0 - && !fn.Name.StartsWith("Abstract", StringComparison.Ordinal) - && !(fn.Name[0] == '$'))) + fn.Name.Length > 0 + && !fn.Name.StartsWith("Abstract", StringComparison.Ordinal) + && !(fn.Name[0] == '$'))) { string name = Path.GetFileNameWithoutExtension(cs.Name); #> diff --git a/NCDK/Reactions/Types/AbstractAdductionLPReaction.cs b/NCDK/Reactions/Types/AbstractAdductionLPReaction.cs index 21ce31f1..e06ec55a 100644 --- a/NCDK/Reactions/Types/AbstractAdductionLPReaction.cs +++ b/NCDK/Reactions/Types/AbstractAdductionLPReaction.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Reactions.Types.Parameters; using NCDK.Tools.Manipulator; using System.Collections.Generic; @@ -29,8 +30,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractAdductionLPReaction : ReactionEngine, IReactionProcess { - public AbstractAdductionLPReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -45,9 +44,11 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb IAtomContainer reactant = reactants[0]; IParameterReaction ipr = base.GetParameterClass(typeof(SetReactionCenter)); - if (ipr != null && !ipr.IsSetParameter) SetActiveCenters(reactant); + if (ipr != null && !ipr.IsSetParameter) + SetActiveCenters(reactant); - if (AtomContainerManipulator.GetTotalCharge(reactant) > 0) return setOfReactions; + if (AtomContainerManipulator.GetTotalCharge(reactant) > 0) + return setOfReactions; foreach (var atomi in reactant.Atoms) { @@ -56,10 +57,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb && reactant.GetConnectedLonePairs(atomi).Any() && !reactant.GetConnectedSingleElectrons(atomi).Any()) { - var atomList = new List - { - atomi - }; + var atomList = new List { atomi }; IAtom atomH = reactant.Builder.NewAtom(atomSymbol); atomH.FormalCharge = 1; atomList.Add(atomH); @@ -81,9 +79,10 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { - if (AtomContainerManipulator.GetTotalCharge(reactant) > 0) return; + if (AtomContainerManipulator.GetTotalCharge(reactant) > 0) + return; foreach (var atomi in reactant.Atoms) { diff --git a/NCDK/Reactions/Types/AbstractElectronImpactDBReaction.cs b/NCDK/Reactions/Types/AbstractElectronImpactDBReaction.cs index e6f2d471..704db3cd 100644 --- a/NCDK/Reactions/Types/AbstractElectronImpactDBReaction.cs +++ b/NCDK/Reactions/Types/AbstractElectronImpactDBReaction.cs @@ -28,8 +28,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractElectronImpactDBReaction : ReactionEngine, IReactionProcess { - public AbstractElectronImpactDBReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -91,7 +89,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant, BondCheck bondChecker) + private static void SetActiveCenters(IAtomContainer reactant, BondCheck bondChecker) { foreach (var bondi in reactant.Bonds) { diff --git a/NCDK/Reactions/Types/AbstractHeterolyticCleavageReaction.cs b/NCDK/Reactions/Types/AbstractHeterolyticCleavageReaction.cs index 19b09522..0cda8374 100644 --- a/NCDK/Reactions/Types/AbstractHeterolyticCleavageReaction.cs +++ b/NCDK/Reactions/Types/AbstractHeterolyticCleavageReaction.cs @@ -28,8 +28,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractHeterolyticCleavageReaction : ReactionEngine, IReactionProcess { - public AbstractHeterolyticCleavageReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -92,7 +90,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant, BondCheck bondCheck) + private static void SetActiveCenters(IAtomContainer reactant, BondCheck bondCheck) { foreach (var bond in reactant.Bonds) { diff --git a/NCDK/Reactions/Types/AbstractRadicalSiteInitiationReaction.cs b/NCDK/Reactions/Types/AbstractRadicalSiteInitiationReaction.cs index 7e38fbf4..edf4b073 100644 --- a/NCDK/Reactions/Types/AbstractRadicalSiteInitiationReaction.cs +++ b/NCDK/Reactions/Types/AbstractRadicalSiteInitiationReaction.cs @@ -16,7 +16,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Reactions.Types.Parameters; +using System; using System.Collections.Generic; using System.Linq; @@ -28,8 +30,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractRadicalSiteInitiationReaction : ReactionEngine, IReactionProcess { - public AbstractRadicalSiteInitiationReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -67,7 +67,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb && bondj.Order == BondOrder.Single) { IAtom atomk = bondj.GetOther(atomj); - if (atomk.IsReactiveCenter && atomk.Symbol.Equals(atomSymbol) + if (atomk.IsReactiveCenter && atomk.Symbol.Equals(atomSymbol, StringComparison.Ordinal) && atomk.FormalCharge == 0) { var atomList = new List @@ -100,7 +100,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant, string atomSymbol, int charge) + private static void SetActiveCenters(IAtomContainer reactant, string atomSymbol, int charge) { foreach (var atomi in reactant.Atoms) { @@ -120,7 +120,7 @@ private void SetActiveCenters(IAtomContainer reactant, string atomSymbol, int ch if (bondj.Order == BondOrder.Single) { IAtom atomk = bondj.GetOther(atomj); - if (atomk.Symbol.Equals(atomSymbol) && atomk.FormalCharge == 0) + if (atomk.Symbol.Equals(atomSymbol, StringComparison.Ordinal) && atomk.FormalCharge == 0) { atomi.IsReactiveCenter = true; atomj.IsReactiveCenter = true; diff --git a/NCDK/Reactions/Types/AbstractRadicalSiteReaction.cs b/NCDK/Reactions/Types/AbstractRadicalSiteReaction.cs index 869e7564..aa4d8556 100644 --- a/NCDK/Reactions/Types/AbstractRadicalSiteReaction.cs +++ b/NCDK/Reactions/Types/AbstractRadicalSiteReaction.cs @@ -21,6 +21,7 @@ using NCDK.RingSearches; using NCDK.Tools; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -32,8 +33,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractRadicalSiteReaction : ReactionEngine, IReactionProcess { - public AbstractRadicalSiteReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -71,7 +70,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb { if (atomi.IsReactiveCenter && reactant.GetConnectedSingleElectrons(atomi).Count() == 1) { - IList atom1s = null; + IEnumerable atom1s = null; if (checkPrev) { hcg.GetSpheres(reactant, atomi, length - 1, true); @@ -123,14 +122,14 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant, int length, bool checkPrev, AtomCheck atomCheck) + private static void SetActiveCenters(IAtomContainer reactant, int length, bool checkPrev, AtomCheck atomCheck) { HOSECodeGenerator hcg = new HOSECodeGenerator(); foreach (var atomi in reactant.Atoms) { if (reactant.GetConnectedSingleElectrons(atomi).Count() == 1) { - IList atom1s = null; + IEnumerable atom1s = null; if (checkPrev) { hcg.GetSpheres(reactant, atomi, length - 1, true); @@ -140,9 +139,11 @@ private void SetActiveCenters(IAtomContainer reactant, int length, bool checkPre hcg.GetSpheres(reactant, atomi, length, true); foreach (var atoml in hcg.GetNodesInSphere(length)) { - if (atoml != null && !atoml.IsInRing - && (atoml.FormalCharge ?? 0) == 0 - && !atoml.Symbol.Equals("H") && reactant.GetMaximumBondOrder(atoml) == BondOrder.Single) + if (atoml != null + && !atoml.IsInRing + && (atoml.FormalCharge ?? 0) == 0 + && !atoml.Symbol.Equals("H", StringComparison.Ordinal) + && reactant.GetMaximumBondOrder(atoml) == BondOrder.Single) { foreach (var atomR in reactant.GetConnectedAtoms(atoml)) { diff --git a/NCDK/Reactions/Types/AbstractRearrangementReaction.cs b/NCDK/Reactions/Types/AbstractRearrangementReaction.cs index 63df1e18..924e0447 100644 --- a/NCDK/Reactions/Types/AbstractRearrangementReaction.cs +++ b/NCDK/Reactions/Types/AbstractRearrangementReaction.cs @@ -28,8 +28,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractRearrangementReaction : ReactionEngine, IReactionProcess { - public AbstractRearrangementReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -107,7 +105,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant, CheckReactant checkReatant, CheckReactantAtom checkReatantAtom, CheckAtom checkAtom) + private static void SetActiveCenters(IAtomContainer reactant, CheckReactant checkReatant, CheckReactantAtom checkReatantAtom, CheckAtom checkAtom) { if (checkReatant != null && !checkReatant(reactant)) return; diff --git a/NCDK/Reactions/Types/AbstractSharingReaction.cs b/NCDK/Reactions/Types/AbstractSharingReaction.cs index e356d4ad..0754c135 100644 --- a/NCDK/Reactions/Types/AbstractSharingReaction.cs +++ b/NCDK/Reactions/Types/AbstractSharingReaction.cs @@ -29,8 +29,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public abstract class AbstractSharingReaction : ReactionEngine, IReactionProcess { - public AbstractSharingReaction() { } - /// public abstract ReactionSpecification Specification { get; } @@ -86,7 +84,7 @@ internal IReactionSet Initiate(IChemObjectSet reactants, IChemOb return setOfReactions; } - private void SetActiveCenters(IAtomContainer reactant, CheckReactantAtom checkReactantAtom, CheckAtom checkAtom, CheckBond checkBond) + private static void SetActiveCenters(IAtomContainer reactant, CheckReactantAtom checkReactantAtom, CheckAtom checkAtom, CheckBond checkBond) { foreach (var atomi in reactant.Atoms) { diff --git a/NCDK/Reactions/Types/AdductionProtonPBReaction.cs b/NCDK/Reactions/Types/AdductionProtonPBReaction.cs index 77175074..93cd7eb3 100644 --- a/NCDK/Reactions/Types/AdductionProtonPBReaction.cs +++ b/NCDK/Reactions/Types/AdductionProtonPBReaction.cs @@ -38,9 +38,6 @@ namespace NCDK.Reactions.Types // @cdk.githash public partial class AdductionProtonPBReaction : ReactionEngine, IReactionProcess { - /// - /// Constructor of the AdductionProtonPBReaction object. - /// public AdductionProtonPBReaction() { } /// @@ -142,7 +139,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// The active center will be those which correspond with X=Y. /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { if (AtomContainerManipulator.GetTotalCharge(reactant) != 0) return; diff --git a/NCDK/Reactions/Types/CarbonylEliminationReaction.cs b/NCDK/Reactions/Types/CarbonylEliminationReaction.cs index f7c0f10f..9e87a8d4 100644 --- a/NCDK/Reactions/Types/CarbonylEliminationReaction.cs +++ b/NCDK/Reactions/Types/CarbonylEliminationReaction.cs @@ -17,6 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Reactions.Types.Parameters; +using System; using System.Collections.Generic; using System.Diagnostics; @@ -46,8 +47,8 @@ public CarbonylEliminationReaction() { } /// The specification value public ReactionSpecification Specification => new ReactionSpecification( - "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#CarbonylElimination", this - .GetType().Name, "$Id$", "The Chemistry Development Kit"); + "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#CarbonylElimination", + this.GetType().Name, "$Id$", "The Chemistry Development Kit"); /// /// Initiate process. @@ -68,7 +69,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje if (ipr != null && !ipr.IsSetParameter) SetActiveCenters(reactant); foreach (var atomi in reactant.Atoms) { - if (atomi.IsReactiveCenter && atomi.Symbol.Equals("O") + if (atomi.IsReactiveCenter && atomi.Symbol.Equals("O", StringComparison.Ordinal) && atomi.FormalCharge == 1) { foreach (var bondi in reactant.GetConnectedBonds(atomi)) @@ -129,11 +130,11 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { foreach (var atomi in reactant.Atoms) { - if (atomi.Symbol.Equals("O") && atomi.FormalCharge == 1) + if (atomi.Symbol.Equals("O", StringComparison.Ordinal) && atomi.FormalCharge == 1) { foreach (var bondi in reactant.GetConnectedBonds(atomi)) { @@ -142,7 +143,8 @@ private void SetActiveCenters(IAtomContainer reactant) IAtom atomj = bondi.GetOther(atomi); foreach (var bondj in reactant.GetConnectedBonds(atomj)) { - if (bondj.Equals(bondi)) continue; + if (bondj.Equals(bondi)) + continue; if (bondj.Order == BondOrder.Single) { diff --git a/NCDK/Reactions/Types/ElectronImpactNBEReaction.cs b/NCDK/Reactions/Types/ElectronImpactNBEReaction.cs index 5d134f80..a6520282 100644 --- a/NCDK/Reactions/Types/ElectronImpactNBEReaction.cs +++ b/NCDK/Reactions/Types/ElectronImpactNBEReaction.cs @@ -106,7 +106,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// lone pair electrons. /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { foreach (var atom in reactant.Atoms) { diff --git a/NCDK/Reactions/Types/HyperconjugationReaction.cs b/NCDK/Reactions/Types/HyperconjugationReaction.cs index 083e1388..46d3e0c3 100644 --- a/NCDK/Reactions/Types/HyperconjugationReaction.cs +++ b/NCDK/Reactions/Types/HyperconjugationReaction.cs @@ -17,6 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Reactions.Types.Parameters; +using System; using System.Collections.Generic; using System.Linq; @@ -97,7 +98,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje if (atomk.IsReactiveCenter && (atomk.FormalCharge ?? 0) == 0 && !reactant.GetConnectedSingleElectrons(atomk).Any() - && atomk.Symbol.Equals("H") + && atomk.Symbol.Equals("H", StringComparison.Ordinal) ) { var atomList = new List @@ -140,7 +141,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { foreach (var atomi in reactant.Atoms) { @@ -163,7 +164,7 @@ private void SetActiveCenters(IAtomContainer reactant) IAtom atomk = bondj.GetOther(atomj); if ((atomk.FormalCharge ?? 0) == 0 && !reactant.GetConnectedSingleElectrons(atomk).Any() - && atomk.Symbol.Equals("H") + && atomk.Symbol.Equals("H", StringComparison.Ordinal) ) { atomi.IsReactiveCenter = true; diff --git a/NCDK/Reactions/Types/PiBondingMovementReaction.cs b/NCDK/Reactions/Types/PiBondingMovementReaction.cs index 824548d3..f56c5ec7 100644 --- a/NCDK/Reactions/Types/PiBondingMovementReaction.cs +++ b/NCDK/Reactions/Types/PiBondingMovementReaction.cs @@ -47,13 +47,13 @@ public PiBondingMovementReaction() { } /// public ReactionSpecification Specification => new ReactionSpecification( - "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#PiBondingMovement", this - .GetType().Name, "$Id$", "The Chemistry Development Kit"); + "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#PiBondingMovement", + this.GetType().Name, "$Id$", "The Chemistry Development Kit"); /// - /// Initiate process. - /// It is needed to call the addExplicitHydrogensToSatisfyValency - /// from the class tools.HydrogenAdder. + /// Initiate process. + /// It is needed to call the addExplicitHydrogensToSatisfyValency + /// from the class tools.HydrogenAdder. /// /// Description of the Exception /// reactants of the reaction. @@ -62,24 +62,20 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje { CheckInitiateParams(reactants, agents); - IReactionSet setOfReactions = reactants.Builder.NewReactionSet(); - IAtomContainer reactant = reactants[0]; + var setOfReactions = reactants.Builder.NewReactionSet(); + var reactant = reactants[0]; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactant); // if the parameter hasActiveCenter is not fixed yet, set the active centers - IParameterReaction ipr = base.GetParameterClass(typeof(SetReactionCenter)); + var ipr = base.GetParameterClass(typeof(SetReactionCenter)); if (ipr != null && !ipr.IsSetParameter) SetActiveCenters(reactant); - // if((bool)paramsMap["lookingSymmetry"]){ - // Aromaticity.CDKLegacy.Apply(reactant); - // } - - AllRingsFinder arf = new AllRingsFinder(); - IRingSet ringSet = arf.FindAllRings((IAtomContainer)reactant); + var arf = new AllRingsFinder(); + var ringSet = arf.FindAllRings((IAtomContainer)reactant); for (int ir = 0; ir < ringSet.Count; ir++) { - IRing ring = (IRing)ringSet[ir]; + var ring = ringSet[ir]; //only rings with even number of atoms int nrAtoms = ring.Atoms.Count; @@ -118,7 +114,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje } - reaction.Products.Add((IAtomContainer)reactantCloned); + reaction.Products.Add(reactantCloned); setOfReactions.Add(reaction); } @@ -132,17 +128,16 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// Set the active center for this molecule. /// The active center will be those which correspond to a ring /// with pi electrons with resonance. - /// - /// FIXME REACT: It could be possible that a ring is a super ring of others small rings /// + /// FIXME REACT: It could be possible that a ring is a super ring of others small rings /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { - AllRingsFinder arf = new AllRingsFinder(); - IRingSet ringSet = arf.FindAllRings(reactant); + var arf = new AllRingsFinder(); + var ringSet = arf.FindAllRings(reactant); for (int ir = 0; ir < ringSet.Count; ir++) { - IRing ring = (IRing)ringSet[ir]; + var ring = ringSet[ir]; //only rings with even number of atoms int nrAtoms = ring.Atoms.Count; if (nrAtoms % 2 == 0) diff --git a/NCDK/Reactions/Types/RadicalSiteHrAlphaReaction.cs b/NCDK/Reactions/Types/RadicalSiteHrAlphaReaction.cs index dcf0a9a4..bf512b27 100644 --- a/NCDK/Reactions/Types/RadicalSiteHrAlphaReaction.cs +++ b/NCDK/Reactions/Types/RadicalSiteHrAlphaReaction.cs @@ -16,6 +16,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Reactions.Types { /// @@ -54,7 +56,7 @@ public RadicalSiteHrAlphaReaction() { } /// agents of the reaction (Must be in this case null). public override IReactionSet Initiate(IChemObjectSet reactants, IChemObjectSet agents) { - return base.Initiate(reactants, agents, 2, false, atom => atom.Symbol.Equals("H")); + return base.Initiate(reactants, agents, 2, false, atom => atom.Symbol.Equals("H", StringComparison.Ordinal)); } } } diff --git a/NCDK/Reactions/Types/RadicalSiteHrBetaReaction.cs b/NCDK/Reactions/Types/RadicalSiteHrBetaReaction.cs index 900452f7..ca1fb842 100644 --- a/NCDK/Reactions/Types/RadicalSiteHrBetaReaction.cs +++ b/NCDK/Reactions/Types/RadicalSiteHrBetaReaction.cs @@ -16,6 +16,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Reactions.Types { /// @@ -53,7 +55,7 @@ public RadicalSiteHrBetaReaction() { } /// agents of the reaction (Must be in this case null). public override IReactionSet Initiate(IChemObjectSet reactants, IChemObjectSet agents) { - return base.Initiate(reactants, agents, 3, false, atom => atom.Symbol.Equals("H")); + return base.Initiate(reactants, agents, 3, false, atom => atom.Symbol.Equals("H", StringComparison.Ordinal)); } } } diff --git a/NCDK/Reactions/Types/RadicalSiteHrDeltaReaction.cs b/NCDK/Reactions/Types/RadicalSiteHrDeltaReaction.cs index 68c601a7..be0ad324 100644 --- a/NCDK/Reactions/Types/RadicalSiteHrDeltaReaction.cs +++ b/NCDK/Reactions/Types/RadicalSiteHrDeltaReaction.cs @@ -16,6 +16,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Reactions.Types { /// @@ -54,7 +56,7 @@ public RadicalSiteHrDeltaReaction() { } /// agents of the reaction (Must be in this case null). public override IReactionSet Initiate(IChemObjectSet reactants, IChemObjectSet agents) { - return base.Initiate(reactants, agents, 5, false, atom => atom.Symbol.Equals("H")); + return base.Initiate(reactants, agents, 5, false, atom => atom.Symbol.Equals("H", StringComparison.Ordinal)); } } } diff --git a/NCDK/Reactions/Types/RadicalSiteHrGammaReaction.cs b/NCDK/Reactions/Types/RadicalSiteHrGammaReaction.cs index 9cd2f90d..c0bb94f1 100644 --- a/NCDK/Reactions/Types/RadicalSiteHrGammaReaction.cs +++ b/NCDK/Reactions/Types/RadicalSiteHrGammaReaction.cs @@ -16,6 +16,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Reactions.Types { /// @@ -54,7 +56,7 @@ public RadicalSiteHrGammaReaction() { } /// agents of the reaction (Must be in this case null). public override IReactionSet Initiate(IChemObjectSet reactants, IChemObjectSet agents) { - return base.Initiate(reactants, agents, 4, false, atom => atom.Symbol.Equals("H")); + return base.Initiate(reactants, agents, 4, false, atom => atom.Symbol.Equals("H", StringComparison.Ordinal)); } } } diff --git a/NCDK/Reactions/Types/SharingChargeDBReaction.cs b/NCDK/Reactions/Types/SharingChargeDBReaction.cs index 2fc5d01c..64fccf1f 100644 --- a/NCDK/Reactions/Types/SharingChargeDBReaction.cs +++ b/NCDK/Reactions/Types/SharingChargeDBReaction.cs @@ -48,13 +48,13 @@ public SharingChargeDBReaction() { } /// The specification value public ReactionSpecification Specification => new ReactionSpecification( - "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#SharingChargeDB", this - .GetType().Name, "$Id$", "The Chemistry Development Kit"); + "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#SharingChargeDB", + this.GetType().Name, "$Id$", "The Chemistry Development Kit"); /// - /// Initiate process. - /// It is needed to call the addExplicitHydrogensToSatisfyValency - /// from the class tools.HydrogenAdder. + /// Initiate process. + /// It is needed to call the addExplicitHydrogensToSatisfyValency + /// from the class tools.HydrogenAdder. /// /// reactants of the reaction. /// agents of the reaction (Must be in this case null). @@ -127,7 +127,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { foreach (var atomi in reactant.Atoms) { diff --git a/NCDK/Reactions/Types/SharingChargeSBReaction.cs b/NCDK/Reactions/Types/SharingChargeSBReaction.cs index 7eaa190b..4399e523 100644 --- a/NCDK/Reactions/Types/SharingChargeSBReaction.cs +++ b/NCDK/Reactions/Types/SharingChargeSBReaction.cs @@ -48,8 +48,8 @@ public SharingChargeSBReaction() { } /// The specification value public ReactionSpecification Specification => new ReactionSpecification( - "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#SharingChargeSB", this - .GetType().Name, "$Id$", "The Chemistry Development Kit"); + "http://almost.cubic.uni-koeln.de/jrg/Members/mrc/reactionDict/reactionDict#SharingChargeSB", + this.GetType().Name, "$Id$", "The Chemistry Development Kit"); /// /// Initiate process. @@ -127,7 +127,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { foreach (var atomi in reactant.Atoms) { diff --git a/NCDK/Reactions/Types/TautomerizationReaction.cs b/NCDK/Reactions/Types/TautomerizationReaction.cs index 355d79bd..85b59c29 100644 --- a/NCDK/Reactions/Types/TautomerizationReaction.cs +++ b/NCDK/Reactions/Types/TautomerizationReaction.cs @@ -16,7 +16,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Reactions.Types.Parameters; +using System; using System.Collections.Generic; using System.Linq; @@ -53,7 +55,8 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje // if the parameter hasActiveCenter is not fixed yet, set the active centers IParameterReaction ipr = base.GetParameterClass(typeof(SetReactionCenter)); - if (ipr != null && !ipr.IsSetParameter) SetActiveCenters(reactant); + if (ipr != null && !ipr.IsSetParameter) + SetActiveCenters(reactant); foreach (var atomi in reactant.Atoms) { @@ -85,13 +88,12 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje { foreach (var bondk in reactant.GetConnectedBonds(atomk)) { - if (bondk.Equals(bondj)) continue; - if (bondk.IsReactiveCenter - && bondk.Order == BondOrder.Single) + if (bondk.Equals(bondj)) + continue; + if (bondk.IsReactiveCenter && bondk.Order == BondOrder.Single) { IAtom atoml = bondk.GetOther(atomk); // Atom pos 4 - if (atoml.IsReactiveCenter - && atoml.Symbol.Equals("H")) + if (atoml.IsReactiveCenter && atoml.Symbol.Equals("H", StringComparison.Ordinal)) { var atomList = new List { @@ -144,7 +146,7 @@ public IReactionSet Initiate(IChemObjectSet reactants, IChemObje /// /// /// The molecule to set the activity - private void SetActiveCenters(IAtomContainer reactant) + private static void SetActiveCenters(IAtomContainer reactant) { foreach (var atomi in reactant.Atoms) { @@ -175,7 +177,7 @@ private void SetActiveCenters(IAtomContainer reactant) if (bondk.Order == BondOrder.Single) { IAtom atoml = bondk.GetOther(atomk); // Atom pos 4 - if (atoml.Symbol.Equals("H")) + if (string.Equals(atoml.Symbol, "H", StringComparison.Ordinal)) { atomi.IsReactiveCenter = true; atomj.IsReactiveCenter = true; diff --git a/NCDK/RingSearches/AllRingsFinder.cs b/NCDK/RingSearches/AllRingsFinder.cs index b08a92f6..0d60e514 100644 --- a/NCDK/RingSearches/AllRingsFinder.cs +++ b/NCDK/RingSearches/AllRingsFinder.cs @@ -25,9 +25,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using System; using NCDK.Graphs; -using static NCDK.Graphs.GraphUtil; +using System; namespace NCDK.RingSearches { @@ -57,18 +56,9 @@ public sealed class AllRingsFinder /// Precomputed threshold - stops the computation running forever. private readonly Threshold threshold; - /// - /// Constructor for the AllRingsFinder. - /// - /// true=logging will be done (slower), false = no logging. - [Obsolete("turn logging off by setting the level in the logger implementation")] - public AllRingsFinder(bool logging) - : this(Threshold.PubChem_99) - { } - - /// Default constructor using a threshold of . + /// Default constructor using a threshold of . public AllRingsFinder() - : this(Threshold.PubChem_99) + : this(Threshold.PubChem99) { } /// Internal constructor. @@ -104,12 +94,11 @@ public IRingSet FindAllRings(IAtomContainer container) /// An exception thrown if the threshold was exceeded public IRingSet FindAllRings(IAtomContainer container, int maxRingSize) { - EdgeToBondMap edges = EdgeToBondMap.WithSpaceFor(container); - int[][] graph = GraphUtil.ToAdjList(container, edges); - - RingSearch rs = new RingSearch(container, graph); + var edges = EdgeToBondMap.WithSpaceFor(container); + var graph = GraphUtil.ToAdjList(container, edges); - IRingSet ringSet = container.Builder.NewRingSet(); + var rs = new RingSearch(container, graph); + var ringSet = container.Builder.NewRingSet(); // don't need to run on isolated rings, just need to put vertices in // cyclic order @@ -117,7 +106,7 @@ public IRingSet FindAllRings(IAtomContainer container, int maxRingSize) { if (isolated.Length <= maxRingSize) { - IRing ring = ToRing(container, edges, GraphUtil.Cycle(graph, isolated)); + var ring = ToRing(container, edges, GraphUtil.Cycle(graph, isolated)); ringSet.Add(ring); } } @@ -125,8 +114,7 @@ public IRingSet FindAllRings(IAtomContainer container, int maxRingSize) // for each set of fused cyclic vertices run the separate search foreach (var fused in rs.Fused()) { - AllCycles ac = new AllCycles(GraphUtil.Subgraph(graph, fused), Math.Min(maxRingSize, fused.Length), - threshold.Value); + var ac = new AllCycles(GraphUtil.Subgraph(graph, fused), Math.Min(maxRingSize, fused.Length), threshold.Value); if (!ac.Completed) throw new CDKException("Threshold exceeded for AllRingsFinder"); @@ -163,14 +151,15 @@ public IRingSet FindAllRingsInIsolatedRingSystem(IAtomContainer container) /// An exception thrown if the threshold was exceeded public IRingSet FindAllRingsInIsolatedRingSystem(IAtomContainer atomContainer, int maxRingSize) { - EdgeToBondMap edges = EdgeToBondMap.WithSpaceFor(atomContainer); - int[][] graph = GraphUtil.ToAdjList(atomContainer, edges); + var edges = EdgeToBondMap.WithSpaceFor(atomContainer); + var graph = GraphUtil.ToAdjList(atomContainer, edges); - AllCycles ac = new AllCycles(graph, maxRingSize, threshold.Value); + var ac = new AllCycles(graph, maxRingSize, threshold.Value); - if (!ac.Completed) throw new CDKException("Threshold exceeded for AllRingsFinder"); + if (!ac.Completed) + throw new CDKException("Threshold exceeded for AllRingsFinder"); - IRingSet ringSet = atomContainer.Builder.NewRingSet(); + var ringSet = atomContainer.Builder.NewRingSet(); foreach (var path in ac.GetPaths()) { @@ -180,39 +169,6 @@ public IRingSet FindAllRingsInIsolatedRingSystem(IAtomContainer atomContainer, i return ringSet; } - /// - /// Checks if the timeout has been reached and exception if so. - /// This is used to prevent this AllRingsFinder to run for ages in certain - /// rare cases with ring systems of large size or special topology. - /// - /// The exception thrown in case of hitting the timeout - [Obsolete("timeout not used")] - public void CheckTimeout() - { - // unused - } - - /// - /// Sets the timeout value in milliseconds of the object This - /// is used to prevent this AllRingsFinder to run for ages in certain rare - /// cases with ring systems of large size or special topology - /// - /// The new timeout value - /// a reference to the instance this method was called for - [Obsolete("use the new threshold (during construction)")] - public AllRingsFinder SetTimeout(long timeout) - { - Console.Error.WriteLine(nameof(AllRingsFinder) + "." + nameof(SetTimeout) + "() is not used, please " + "use the new threshold values"); - return this; - } - - /// - /// Gets the timeout values in milliseconds of the object - /// - /// The timeout value - [Obsolete("timeout not used")] - public long TimeOut => 0; - /// /// Convert a cycle in [] representation to an . /// @@ -220,18 +176,18 @@ public AllRingsFinder SetTimeout(long timeout) /// edge map /// vertex walk forming the cycle, first and last vertex the same /// a new ring - private IRing ToRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle) + private static IRing ToRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle) { - int len = cycle.Length - 1; - IAtom[] atoms = new IAtom[len]; - IBond[] bonds = new IBond[len]; + var len = cycle.Length - 1; + var atoms = new IAtom[len]; + var bonds = new IBond[len]; for (int i = 0; i < len; i++) { atoms[i] = container.Atoms[cycle[i]]; bonds[i] = edges[cycle[i], cycle[i + 1]]; atoms[i].IsInRing = true; } - IRing ring = container.Builder.NewRing(atoms, bonds); + var ring = container.Builder.NewRing(atoms, bonds); return ring; } @@ -243,108 +199,21 @@ private IRing ToRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle) /// edge map /// vertex walk forming the cycle, first and last vertex the same /// a new ring - private IRing ToRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle, int[] mapping) + private static IRing ToRing(IAtomContainer container, EdgeToBondMap edges, int[] cycle, int[] mapping) { - int len = cycle.Length - 1; - IAtom[] atoms = new IAtom[len]; - IBond[] bonds = new IBond[len]; + var len = cycle.Length - 1; + var atoms = new IAtom[len]; + var bonds = new IBond[len]; for (int i = 0; i < len; i++) { atoms[i] = container.Atoms[mapping[cycle[i]]]; bonds[i] = edges[mapping[cycle[i]], mapping[cycle[i + 1]]]; atoms[i].IsInRing = true; } - IRing ring = container.Builder.NewRing(atoms, bonds); + var ring = container.Builder.NewRing(atoms, bonds); return ring; } - /// - /// The threshold values provide a limit at which the computation stops. - /// There will always be some ring systems in which we cannot compute every - /// possible ring (e.g. fullerenes). This limit replaces the previous timeout - /// and provides a more meaningful measure of what to expect based on - /// precomputed percentiles. It is important to consider that, higher is not - /// always better - generally the large values generate many more rings then - /// can be reasonably be handled. - /// - /// - /// The latest results were calculated on PubChem Compound (Dec' 12) and - /// summarised below. - /// - /// Maximum DegreePercent - /// (%)Completed
(ring systems)
Uncompleted
- /// (ring systems)
- /// 7299.95178340138835 - /// 8499.96178358766972 - /// 12699.97178376925156 - /// 21699.98178392933555 - /// 68499.99 (default)178410651783 - /// 88299.991178413421506 - /// 106299.992178414291419 - /// 144099.993178416021246 - /// 307299.994178417891059 - ///
- ///
- /// AllRingsFinder, Sport Edition - public class Threshold - { - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.95% of ring systems. - /// - public static readonly Threshold PubChem_95 = new Threshold(72); - - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.96% of ring systems. - /// - public static readonly Threshold PubChem_96 = new Threshold(84); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.97% of ring systems. - /// - public static readonly Threshold PubChem_97 = new Threshold(126); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.98% of ring systems. - /// - public static readonly Threshold PubChem_98 = new Threshold(216); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.99% of ring systems. - /// - public static readonly Threshold PubChem_99 = new Threshold(684); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.991% of ring systems. - /// - public static readonly Threshold PubChem_991 = new Threshold(882); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.992% of ring systems. - /// - public static readonly Threshold PubChem_992 = new Threshold(1062); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.993% of ring systems. - /// - public static readonly Threshold PubChem_993 = new Threshold(1440); - /// - /// Based on PubChem Compound (Dec '12), perception will complete for - /// 99.994% of ring systems. - /// - public static readonly Threshold PubChem_994 = new Threshold(3072); - /// Run without any threshold, possibly until the end of time itself. - public static readonly Threshold None = new Threshold(int.MaxValue); - - internal int Value { get; private set; } - - private Threshold(int value) - { - Value = value; - } - } - /// /// Create an instance using the given threshold. /// @@ -358,4 +227,102 @@ public static AllRingsFinder UsingThreshold(Threshold threshold) return new AllRingsFinder(threshold); } } + + + /// + /// The threshold values provide a limit at which the computation stops. + /// There will always be some ring systems in which we cannot compute every + /// possible ring (e.g. fullerenes). This limit replaces the previous timeout + /// and provides a more meaningful measure of what to expect based on + /// precomputed percentiles. It is important to consider that, higher is not + /// always better - generally the large values generate many more rings then + /// can be reasonably be handled. + /// + /// + /// The latest results were calculated on PubChem Compound (Dec' 12) and + /// summarised below. + /// + /// Maximum DegreePercent + /// (%)Completed
(ring systems)
Uncompleted
+ /// (ring systems)
+ /// 7299.95178340138835 + /// 8499.96178358766972 + /// 12699.97178376925156 + /// 21699.98178392933555 + /// 68499.99 (default)178410651783 + /// 88299.991178413421506 + /// 106299.992178414291419 + /// 144099.993178416021246 + /// 307299.994178417891059 + ///
+ ///
+ /// AllRingsFinder, Sport Edition + public class Threshold + { + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.95% of ring systems. + /// + public static readonly Threshold PubChem95 = new Threshold(72); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.96% of ring systems. + /// + public static readonly Threshold PubChem96 = new Threshold(84); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.97% of ring systems. + /// + public static readonly Threshold PubChem97 = new Threshold(126); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.98% of ring systems. + /// + public static readonly Threshold PubChem98 = new Threshold(216); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.99% of ring systems. + /// + public static readonly Threshold PubChem99 = new Threshold(684); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.991% of ring systems. + /// + public static readonly Threshold PubChem991 = new Threshold(882); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.992% of ring systems. + /// + public static readonly Threshold PubChem992 = new Threshold(1062); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.993% of ring systems. + /// + public static readonly Threshold PubChem993 = new Threshold(1440); + + /// + /// Based on PubChem Compound (Dec '12), perception will complete for + /// 99.994% of ring systems. + /// + public static readonly Threshold PubChem994 = new Threshold(3072); + + /// + /// Run without any threshold, possibly until the end of time itself. + /// + public static readonly Threshold None = new Threshold(int.MaxValue); + + internal int Value { get; private set; } + + private Threshold(int value) + { + Value = value; + } + } } diff --git a/NCDK/RingSearches/JumboCyclicVertexSearch.cs b/NCDK/RingSearches/JumboCyclicVertexSearch.cs index c0d8e2fd..300c1ff1 100644 --- a/NCDK/RingSearches/JumboCyclicVertexSearch.cs +++ b/NCDK/RingSearches/JumboCyclicVertexSearch.cs @@ -37,7 +37,7 @@ internal class JumboCyclicVertexSearch : ICyclicVertexSearch { /// graph representation - private readonly int[][] g; + private readonly IReadOnlyList> g; /// set of known cyclic vertices private readonly BitArray cyclic; @@ -52,21 +52,19 @@ internal class JumboCyclicVertexSearch private BitArray visited; /// the vertices in our path at a given vertex index - private BitArray[] state; + private readonly BitArray[] state; /// vertex colored by each component. private int[] colors; - private int numCycles = 0; - /// /// Create a new cyclic vertex search for the provided graph. /// /// adjacency list representation of a graph - public JumboCyclicVertexSearch(int[][] graph) + public JumboCyclicVertexSearch(IReadOnlyList> graph) { this.g = graph; - int n = graph.Length; + int n = graph.Count; cyclic = new BitArray(n); @@ -120,7 +118,7 @@ private void Search(int v, BitArray prev, BitArray curr) // include w - they are adjacent if (prev[w]) { - numCycles++; + NumCycles++; // we have a cycle, xor the state when we last visited 'w' // with our current state. this set is all the vertices // we visited since then @@ -140,7 +138,7 @@ private void Search(int v, BitArray prev, BitArray curr) /// Synchronisation lock. private readonly object syncLock = new object(); - public int NumCycles =>numCycles; + public int NumCycles { get; private set; } = 0; /// /// Lazily build an indexed lookup of vertex color. The vertex color @@ -151,7 +149,7 @@ private void Search(int v, BitArray prev, BitArray curr) /// vertex colors public int[] VertexColor() { - int[] result = colors; + var result = colors; if (result == null) { lock (syncLock) @@ -174,7 +172,7 @@ public int[] VertexColor() /// vertex colors private int[] BuildVertexColor() { - int[] color = new int[g.Length]; + int[] color = new int[g.Count]; int n = 1; Arrays.Fill(color, -1); @@ -199,7 +197,7 @@ public bool Cyclic(int v) /// public bool Cyclic(int u, int v) { - int[] colors = VertexColor(); + var colors = VertexColor(); // if either vertex has no color then the edge can not // be cyclic @@ -231,7 +229,7 @@ public int[] Cyclic() /// public int[][] Isolated() { - List isolated = new List(cycles.Count()); + var isolated = new List(cycles.Count()); for (int i = 0; i < cycles.Count(); i++) { if (!fused[i]) isolated.Add(ToArray(cycles[i])); @@ -242,7 +240,7 @@ public int[][] Isolated() /// public int[][] Fused() { - List fused = new List(cycles.Count()); + var fused = new List(cycles.Count()); for (int i = 0; i < cycles.Count(); i++) { if (this.fused[i]) fused.Add(ToArray(cycles[i])); diff --git a/NCDK/RingSearches/RegularCyclicVertexSearch.cs b/NCDK/RingSearches/RegularCyclicVertexSearch.cs index c89c15b3..d1d3439d 100644 --- a/NCDK/RingSearches/RegularCyclicVertexSearch.cs +++ b/NCDK/RingSearches/RegularCyclicVertexSearch.cs @@ -38,7 +38,7 @@ internal class RegularCyclicVertexSearch : ICyclicVertexSearch { /// graph representation - private readonly int[][] g; + private readonly IReadOnlyList> g; /// set of known cyclic vertices private long cyclic; @@ -53,21 +53,19 @@ internal class RegularCyclicVertexSearch private long visited; /// the vertices in our path at a given vertex index - private long[] state; + private readonly long[] state; /// Vertex colors - which component does each vertex belong. private volatile int[] colors; - private int numCycles = 0; - /// /// Create a new cyclic vertex search for the provided graph. /// /// adjacency list representation of a graph - internal RegularCyclicVertexSearch(int[][] graph) + internal RegularCyclicVertexSearch(IReadOnlyList> graph) { this.g = graph; - int n = graph.Length; + int n = graph.Count; // skip search if empty graph if (n == 0) return; @@ -92,7 +90,6 @@ internal RegularCyclicVertexSearch(int[][] graph) // no longer needed for the lifetime of the object state = null; - } /// @@ -118,7 +115,7 @@ private void Search(int v, long prev, long curr) // include w - they are adjacent if (IsBitSet(prev, w)) { - numCycles++; + NumCycles++; // xor the state when we last visited 'w' with our current // state. this set is all the vertices we visited since then @@ -134,7 +131,7 @@ private void Search(int v, long prev, long curr) } } - public int NumCycles => numCycles; + public int NumCycles { get; private set; } = 0; /// /// Returns whether the vertex 'v' has been visited. @@ -272,13 +269,13 @@ public int[] VertexColor() /// vertex colors private int[] BuildVertexColor() { - int[] color = new int[g.Length]; + int[] color = new int[g.Count]; int n = 1; Arrays.Fill(color, -1); foreach (var l_cycle in cycles) { var cycle = l_cycle; - for (int i = 0; i < g.Length; i++) + for (int i = 0; i < g.Count; i++) { if ((cycle & 0x1) == 0x1) color[i] = color[i] < 0 ? n : 0; @@ -298,7 +295,7 @@ public bool Cyclic(int v) /// public bool Cyclic(int u, int v) { - int[] colors = VertexColor(); + var colors = VertexColor(); // if either vertex has no color then the edge can not // be cyclic @@ -334,7 +331,7 @@ public int[] Cyclic() /// public int[][] Isolated() { - List isolated = new List(cycles.Count()); + var isolated = new List(cycles.Count()); for (int i = 0; i < cycles.Count(); i++) { if (!fused[i]) isolated.Add(ToArray(cycles[i])); @@ -367,7 +364,8 @@ internal static int[] ToArray(long set) // fill the cyclic vertices with the bits that have been set for (int v = 0; i < vertices.Length; v++) { - if (IsBitSet(set, v)) vertices[i++] = v; + if (IsBitSet(set, v)) + vertices[i++] = v; } return vertices; diff --git a/NCDK/RingSearches/RingPartitioner.cs b/NCDK/RingSearches/RingPartitioner.cs index 613d18f7..2babc059 100644 --- a/NCDK/RingSearches/RingPartitioner.cs +++ b/NCDK/RingSearches/RingPartitioner.cs @@ -27,9 +27,9 @@ namespace NCDK.RingSearches { /// - /// Partitions a RingSet into RingSets of connected rings. Rings which share an - /// Atom, a Bond or three or more atoms with at least on other ring in the - /// RingSet are considered connected. + /// Partitions a RingSet into RingSets of connected rings. Rings which share an + /// atom, a bond or three or more atoms with at least on other ring in the + /// RingSet are considered connected. /// // @cdk.module standard // @cdk.githash @@ -43,9 +43,9 @@ public static class RingPartitioner // minimum details /// - /// Partitions a RingSet into RingSets of connected rings. Rings which share - /// an Atom, a Bond or three or more atoms with at least on other ring in - /// the RingSet are considered connected. Thus molecules such as azulene and + /// Partitions a RingSet into RingSets of connected rings. Rings which share + /// an Atom, a Bond or three or more atoms with at least on other ring in + /// the RingSet are considered connected. Thus molecules such as azulene and /// indole will return a List with 1 element. /// /// @@ -55,13 +55,15 @@ public static class RingPartitioner /// /// The RingSet to be partitioned /// A of connected RingSets - public static IList PartitionRings(IEnumerable ringSet) + public static IReadOnlyList PartitionRings(IEnumerable ringSet) { - var ringSets = new List(); - if (!ringSet.Any()) return ringSets; + var ringSets = new List(); + if (!ringSet.Any()) + return ringSets; var ring = ringSet.First(); - if (ring == null) return ringSets; - IRingSet rs = ring.Builder.NewRingSet(); + if (ring == null) + return ringSets; + var rs = ring.Builder.NewRingSet(); foreach (var r in ringSet) rs.Add(r); do @@ -76,21 +78,22 @@ public static IList PartitionRings(IEnumerable ringSet) } /// - /// Converts a RingSet to an AtomContainer. + /// Converts a RingSet to an AtomContainer. /// /// The RingSet to be converted. /// The AtomContainer containing the bonds and atoms of the ringSet. public static IAtomContainer ConvertToAtomContainer(IRingSet ringSet) { - IRing ring = (IRing)ringSet[0]; - if (ring == null) return null; - IAtomContainer ac = ring.Builder.NewAtomContainer(); + var ring = ringSet[0]; + if (ring == null) + return null; + var ac = ring.Builder.NewAtomContainer(); for (int i = 0; i < ringSet.Count; i++) { - ring = (IRing)ringSet[i]; + ring = ringSet[i]; for (int r = 0; r < ring.Bonds.Count; r++) { - IBond bond = ring.Bonds[r]; + var bond = ring.Bonds[r]; if (!ac.Contains(bond)) { for (int j = 0; j < bond.Atoms.Count; j++) @@ -105,10 +108,10 @@ public static IAtomContainer ConvertToAtomContainer(IRingSet ringSet) } /// - /// Perform a walk in the given RingSet, starting at a given Ring and - /// recursively searching for other Rings connected to this ring. By doing - /// this it finds all rings in the RingSet connected to the start ring, - /// putting them in newRs, and removing them from rs. + /// Perform a walk in the given RingSet, starting at a given Ring and + /// recursively searching for other Rings connected to this ring. By doing + /// this it finds all rings in the RingSet connected to the start ring, + /// putting them in newRs, and removing them from rs. /// /// The RingSet to be searched /// The ring to start with @@ -118,7 +121,6 @@ private static IRingSet WalkRingSystem(IRingSet rs, IRing ring, IRingSet newRs) { IRing tempRing; var tempRings = rs.GetConnectedRings(ring); - // Debug.WriteLine("walkRingSystem -> tempRings.Count: " + tempRings.Count); rs.Remove(ring); foreach (var container in tempRings) { diff --git a/NCDK/RingSearches/RingSearch.cs b/NCDK/RingSearches/RingSearch.cs index 02d75109..b3ab7358 100644 --- a/NCDK/RingSearches/RingSearch.cs +++ b/NCDK/RingSearches/RingSearch.cs @@ -100,7 +100,7 @@ public RingSearch(IAtomContainer container) /// non-null input structure /// non-null adjacency list representation of the container /// if the container or graph was null - public RingSearch(IAtomContainer container, int[][] graph) + public RingSearch(IAtomContainer container, IReadOnlyList> graph) : this(container, MakeSearcher(graph)) { } @@ -124,14 +124,14 @@ public RingSearch(IAtomContainer container, ICyclicVertexSearch searcher) /// non-null graph /// a new cyclic vertex search for the given graph /// if the graph was null - private static ICyclicVertexSearch MakeSearcher(int[][] graph) + private static ICyclicVertexSearch MakeSearcher(IReadOnlyList> graph) { if (graph == null) throw new ArgumentNullException(nameof(graph), "graph[][] must not be null"); // if the molecule has 64 or less atoms we can use single 64 bit long // values to represent our sets of vertices - if (graph.Length <= 64) + if (graph.Count <= 64) { return new RegularCyclicVertexSearch(graph); } @@ -188,7 +188,8 @@ public bool Cyclic(IBond bond) // XXX: linear search - but okay for now int u = container.Atoms.IndexOf(bond.Begin); int v = container.Atoms.IndexOf(bond.End); - if (u < 0 || v < 0) throw new NoSuchAtomException("atoms of the bond are not found in the container"); + if (u < 0 || v < 0) + throw new NoSuchAtomException("atoms of the bond are not found in the container"); return searcher.Cyclic(u, v); } @@ -247,9 +248,9 @@ public int[][] Fused() /// > public IAtomContainer RingFragments() { - int[] vertices = Cyclic(); + var vertices = Cyclic(); int n = vertices.Length; - IAtom[] atoms = new IAtom[n]; + var atoms = new IAtom[n]; List bonds = new List(); for (int i = 0; i < vertices.Length; i++) @@ -300,7 +301,7 @@ internal static bool Match(int eitherColor, int otherColor) /// /// list of isolated ring fragments /// - public IList IsolatedRingFragments() + public IEnumerable IsolatedRingFragments() { return ToFragments(Isolated()); } @@ -313,7 +314,7 @@ public IList IsolatedRingFragments() /// /// list of fused ring fragments /// - public IList FusedRingFragments() + public IEnumerable FusedRingFragments() { return ToFragments(Fused()); } @@ -323,17 +324,16 @@ public IList FusedRingFragments() /// /// 2D array of vertices (rows=n fragments) /// the vertices converted to an atom container - /// + /// /// /// - private IList ToFragments(int[][] verticesList) + private IEnumerable ToFragments(IReadOnlyList> verticesList) { - List fragments = new List(); foreach (var vertices in verticesList) { - fragments.Add(ToFragment(vertices)); + yield return ToFragment(vertices); } - return fragments; + yield break; } /// @@ -341,9 +341,9 @@ private IList ToFragments(int[][] verticesList) /// /// array of vertices. Length=cycle weight, values 0 ... nAtoms /// atom container only containing the specified atoms (and bonds) - private IAtomContainer ToFragment(int[] vertices) + private IAtomContainer ToFragment(IReadOnlyList vertices) { - int n = vertices.Length; + int n = vertices.Count; ICollection atoms = new HashSet(); IList bonds = new List(); diff --git a/NCDK/SGroups/SgroupTool.cs b/NCDK/SGroups/SgroupTool.cs new file mode 100644 index 00000000..3771a5e0 --- /dev/null +++ b/NCDK/SGroups/SgroupTool.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; +using System.Linq; + +namespace NCDK.Sgroups +{ + public static class SgroupTool + { + /// + /// Key to store/fetch CTab Sgroups from Molfiles. Important! - Use at your own risk, + /// property is transitive and may be removed in future with a more specific accessor. + /// + public const string CtabSgroupsPropertyKey = "cdk:CtabSgroups"; + + public static IList GetCtabSgroups(this IAtomContainer o) + => o.GetProperty>(CtabSgroupsPropertyKey); + + public static void SetCtabSgroups(this IAtomContainer o, IList chirality) + => o.SetProperty(CtabSgroupsPropertyKey, chirality); + + private static Dictionary StrToSgroupTypeMap { get; } = new Dictionary + { + [""] = 0, + ["SUP"] = SgroupType.CtabAbbreviation, + ["MUL"] = SgroupType.CtabMultipleGroup, + ["SRU"] = SgroupType.CtabStructureRepeatUnit, + ["MON"] = SgroupType.CtabMonomer, + ["MOD"] = SgroupType.CtabModified, + ["COP"] = SgroupType.CtabCopolymer, + ["MER"] = SgroupType.CtabMer, + ["CRO"] = SgroupType.CtabCrossLink, + ["GRA"] = SgroupType.CtabMultipleGroup, + ["ANY"] = SgroupType.CtabAnyPolymer, + ["COM"] = SgroupType.CtabComponent, + ["MIX"] = SgroupType.CtabMixture, + ["FOR"] = SgroupType.CtabFormulation, + ["DAT"] = SgroupType.CtabData, + ["GEN"] = SgroupType.CtabGeneric, + ["N/A"] = SgroupType.ExtMulticenter, + }; + + public static string Key(this SgroupType value) + => StrToSgroupTypeMap.Keys.ElementAt((int)value); + + public static SgroupType ToSgroupType(string str) + { + if (!StrToSgroupTypeMap.TryGetValue(str, out SgroupType o)) + return SgroupType.CtabGeneric; + return o; + } + + public static IReadOnlyList SgroupKeyValues { get; } = System.Enum.GetValues(typeof(SgroupKey)).Cast().ToArray(); + } +} diff --git a/NCDK/SMARTS/SmartsFragmentExtractor.cs b/NCDK/SMARTS/SmartsFragmentExtractor.cs index fe18c064..0cc3f5d0 100644 --- a/NCDK/SMARTS/SmartsFragmentExtractor.cs +++ b/NCDK/SMARTS/SmartsFragmentExtractor.cs @@ -23,10 +23,27 @@ using NCDK.Common.Collections; using System; +using System.Collections.Generic; using System.Text; namespace NCDK.SMARTS { + /// + /// Modes of the extractor. + /// + public enum SubstructureSelectionMode + { + /// + /// SMARTS similar to JCompoundMapper. + /// + JCompoundMapper = 1, + + /// + /// exact SMARTS. + /// + ExactSmarts = 2, + } + /// /// Utility class to create SMARTS that match part (substructure) of a molecule. /// SMARTS are generated by providing the atom indexes. An example use cases is @@ -34,9 +51,9 @@ namespace NCDK.SMARTS /// /// /// - /// The extractor has two modes. (default) captures the element, + /// The extractor has two modes. (default) captures the element, /// valence, hydrogen count, connectivity, and charge in the SMARTS atom expressions. - /// The alternative mode, , only captures the element, + /// The alternative mode, , only captures the element, /// non-zero charge, and peripheral bonds. Although the later looks cleaner, the /// peripheral bonds intend to capture the connectivity of the terminal atoms but /// since the valence is not bounded further substitution is still allowed. This @@ -46,7 +63,7 @@ namespace NCDK.SMARTS /// The difference is easily demonstrated for methyl. Consider the compound /// of 2-methylpentane "CC(C)CCC", if we extract one of the methyl atoms /// depending on the mode we obtain "[CH3v4X4+0]" or "C*". The first - /// of these patterns (obtained by ) matches the compound in + /// of these patterns (obtained by ) matches the compound in /// three places (the three methyl groups). The second matches six /// times (every atom) because the substituion on the carbon is not locked. /// A further complication is introduced by the inclusion of the peripheral atoms, @@ -56,38 +73,13 @@ namespace NCDK.SMARTS /// /// /// - /// - /// IChemObjectBuilder bldr = SilentChemObjectBuilder.getInstance(); - /// SmilesParser smipar = new SmilesParser(bldr); - /// - /// IAtomContainer mol = smipar.parseSmiles("[nH]1ccc2c1cccc2"); - /// SmartsFragmentExtractor subsmarts = new SmartsFragmentExtractor(mol); - /// - /// // smarts=[nH1v3X3+0][cH1v4X3+0][cH1v4X3+0][cH0v4X3+0] - /// // hits =1 - /// String smarts = mol.generate(new int[]{0,1,3,4}); - /// - /// subsmarts.setMode(MODE_JCOMPOUNDMAPPER); - /// // smarts=n(ccc(a)a)a - /// // hits = 0 - one of the 'a' atoms needs to match the nitrogen - /// String smarts = mol.generate(new int[]{0,1,3,4}); - /// + /// /// // @author Nikolay Kochev // @author Nina Jeliazkova // @author John May public sealed class SmartsFragmentExtractor { - /// - /// Sets the mode of the extractor to produce SMARTS similar to JCompoundMapper. - /// - public const int MODE_JCOMPOUNDMAPPER = 1; - - /// - /// Sets the mode of the extractor to produce exact SMARTS. - /// - public const int MODE_EXACT = 2; - // molecule being selected over private readonly IAtomContainer mol; @@ -106,7 +98,7 @@ public sealed class SmartsFragmentExtractor private int numVisit; // which mode should SMARTS be encoded in - private int mode = MODE_EXACT; + private SubstructureSelectionMode mode = SubstructureSelectionMode.ExactSmarts; /// /// Create a new instance over the provided molecule. @@ -170,13 +162,13 @@ public SmartsFragmentExtractor(IAtomContainer mol) /// Set the mode of SMARTS substructure selection /// /// the mode - public void SetMode(int mode) + public void SetMode(SubstructureSelectionMode mode) { // check arg switch (mode) { - case MODE_EXACT: - case MODE_JCOMPOUNDMAPPER: + case SubstructureSelectionMode.ExactSmarts: + case SubstructureSelectionMode.JCompoundMapper: break; default: throw new ArgumentException("Invalid mode specified!"); @@ -195,15 +187,15 @@ public void SetMode(int mode) ///
/// atom indexes /// SMARTS, null if an empty array is passed - public string Generate(int[] atomIdxs) + public string Generate(IReadOnlyList atomIdxs) { if (atomIdxs == null) throw new ArgumentNullException(nameof(atomIdxs), "No atom indexes provided"); - if (atomIdxs.Length == 0) + if (atomIdxs.Count == 0) return null; // makes sense? // special case - if (atomIdxs.Length == 1 && mode == MODE_EXACT) + if (atomIdxs.Count == 1 && mode == SubstructureSelectionMode.ExactSmarts) return aexpr[atomIdxs[0]]; // initialize traversal information @@ -227,7 +219,7 @@ public string Generate(int[] atomIdxs) // second pass builds the expression StringBuilder sb = new StringBuilder(); - for (int i = 0; i < atomIdxs.Length; i++) + for (int i = 0; i < atomIdxs.Count; i++) { if (avisit[atomIdxs[i]] < 0) { @@ -299,7 +291,7 @@ private void EncodeExpr(int idx, int bprev, StringBuilder sb) sb.Append(rnum); } - if (mode == MODE_EXACT && avisit[nbr] == 0 || + if (mode == SubstructureSelectionMode.ExactSmarts && avisit[nbr] == 0 || bidx == bprev || rbnds[bidx] != 0) remain--; @@ -309,7 +301,7 @@ private void EncodeExpr(int idx, int bprev, StringBuilder sb) { int nbr = atomAdj[idx][j]; int bidx = bondAdj[idx][j]; - if (mode == MODE_EXACT && avisit[nbr] == 0 || + if (mode == SubstructureSelectionMode.ExactSmarts && avisit[nbr] == 0 || bidx == bprev || rbnds[bidx] != 0) continue; // ignored @@ -369,7 +361,7 @@ private string EncodeAtomExpr(int atmIdx) { IAtom atom = mol.Atoms[atmIdx]; - bool complex = mode == MODE_EXACT; + bool complex = mode == SubstructureSelectionMode.ExactSmarts; StringBuilder sb = new StringBuilder(); @@ -396,7 +388,7 @@ private string EncodeAtomExpr(int atmIdx) break; } - if (mode == MODE_EXACT) + if (mode == SubstructureSelectionMode.ExactSmarts) { int hcount = atom.ImplicitHydrogenCount.Value; @@ -432,7 +424,7 @@ private string EncodeAtomExpr(int atmIdx) if (abs > 1) sb.Append(abs); complex = true; } - else if (mode == MODE_EXACT) + else if (mode == SubstructureSelectionMode.ExactSmarts) { sb.Append("+0"); } diff --git a/NCDK/SMSD/AbstractMCS.cs b/NCDK/SMSD/AbstractMCS.cs index 08ee37b7..5c411de9 100644 --- a/NCDK/SMSD/AbstractMCS.cs +++ b/NCDK/SMSD/AbstractMCS.cs @@ -144,7 +144,7 @@ public abstract class AbstractMCS /// and map.Value for the target molecule. ///
/// All possible MCS atom Mappings - public abstract IList> GetAllAtomMapping(); + public abstract IReadOnlyList> GetAllAtomMapping(); /// /// Returns all plausible mappings between query and target molecules @@ -153,19 +153,19 @@ public abstract class AbstractMCS /// and map.Value for the target molecule. /// /// All possible MCS Mapping Index - public abstract IList> GetAllMapping(); + public abstract IReadOnlyList> GetAllMapping(); /// /// Returns one of the best matches with atoms mapped. /// /// Best Atom Mapping - public abstract IDictionary GetFirstAtomMapping(); + public abstract IReadOnlyDictionary GetFirstAtomMapping(); /// /// Returns one of the best matches with atom indexes mapped. /// /// Best Mapping Index - public abstract IDictionary GetFirstMapping(); + public abstract IReadOnlyDictionary GetFirstMapping(); /// /// timeout in mins (default 0.10 min) for bond sensitive searches diff --git a/NCDK/SMSD/Algorithms/MCSPluses/BKKCKCF.cs b/NCDK/SMSD/Algorithms/MCSPluses/BKKCKCF.cs index 387fa240..03317bd3 100644 --- a/NCDK/SMSD/Algorithms/MCSPluses/BKKCKCF.cs +++ b/NCDK/SMSD/Algorithms/MCSPluses/BKKCKCF.cs @@ -22,6 +22,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Common.Collections; using NCDK.SMSD.Tools; using System.Collections.Generic; @@ -40,14 +41,14 @@ namespace NCDK.SMSD.Algorithms.MCSPluses // @author Syed Asad Rahman public class BKKCKCF { - private List> maxCliquesSet = null; + private List> maxCliquesSet = null; - private IList cEdges = null; - private IList dEdges = null; + private IReadOnlyList cEdges = null; + private IReadOnlyList dEdges = null; private int bestCliqueSize = 0; - private IList compGraphNodes = null; + private IReadOnlyList compGraphNodes = null; private double dEdgeIterationSize = 0; - private double cEdgeIterationSize = 0; + private readonly double cEdgeIterationSize = 0; /// /// Creates index new instance of Bron Kerbosch Cazals Karande Koch Clique Finder @@ -59,28 +60,25 @@ public class BKKCKCF /// /// C-Edges set of allowed edges /// D-Edges set of prohibited edges - internal BKKCKCF(IList compGraphNodesOrg, IList cEdgesOrg, IList dEdgesOrg) + internal BKKCKCF(IReadOnlyList compGraphNodesOrg, IReadOnlyList cEdgesOrg, IReadOnlyList dEdgesOrg) { MCSPlus.SetTimeManager(new TimeManager()); this.compGraphNodes = compGraphNodesOrg; this.cEdges = cEdgesOrg; this.dEdges = dEdgesOrg; bestCliqueSize = 0; + //Orignal assignment as per paper dEdgeIterationSize = dEdges.Count / 2; //Orignal assignment as per paper cEdgeIterationSize = cEdges.Count / 2; - //reset Degdes and Cedges if required - // SetEdges(); - //Initialization maxCliquesSet - maxCliquesSet = new List>(); + maxCliquesSet = new List>(); Init(); - } /// @@ -196,9 +194,9 @@ protected int GetBestCliqueSize() return bestCliqueSize; } - internal Deque> GetMaxCliqueSet() + internal Deque> GetMaxCliqueSet() { - Deque> solution = new Deque>(); + var solution = new Deque>(); foreach (var s in maxCliquesSet) solution.Push(s); return solution; @@ -253,7 +251,7 @@ private void FindCliques(List potentialVertex, List vertexOfCurrentCli } } - private void CopyVertex(List neighbourVertex, Deque pCopyNIntersec, Deque pCopy, + private static void CopyVertex(List neighbourVertex, Deque pCopyNIntersec, Deque pCopy, List qCopyNIntersec, List qCopy, List xCopyNIntersec, List xCopy, List yCopyNIntersec, List yCopy) { @@ -284,7 +282,7 @@ private void CopyVertex(List neighbourVertex, Deque pCopyNIntersec, De } } - private void GroupNeighbors(int index, Deque pCopy, List qCopy, List xCopy, + private static void GroupNeighbors(int index, Deque pCopy, List qCopy, List xCopy, List yCopy, List neighbourVertex, List potentialDVertex, List potentialVertex, List excludedVertex, List excludedCVertex) { diff --git a/NCDK/SMSD/Algorithms/MCSPluses/ExactMapping.cs b/NCDK/SMSD/Algorithms/MCSPluses/ExactMapping.cs index a5932578..2face1c4 100644 --- a/NCDK/SMSD/Algorithms/MCSPluses/ExactMapping.cs +++ b/NCDK/SMSD/Algorithms/MCSPluses/ExactMapping.cs @@ -35,7 +35,7 @@ namespace NCDK.SMSD.Algorithms.MCSPluses // @cdk.module smsd // @cdk.githash // @author Syed Asad Rahman - public class ExactMapping + public static class ExactMapping { /// /// Extract atom mapping from the cliques and stores it in an . @@ -63,7 +63,7 @@ private static IEnumerable ExtractCliqueMapping(IEnumerable compGraphN /// /// extract atom mapping from the clique List and print it on the screen /// - public static IList> ExtractMapping(IList> mappings, IList compGraphNodes, IList cliqueListOrg) + internal static List> ExtractMapping(List> mappings, IReadOnlyList compGraphNodes, IReadOnlyList cliqueListOrg) { try { diff --git a/NCDK/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraph.cs b/NCDK/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraph.cs index da5e5533..eb35dc0b 100644 --- a/NCDK/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraph.cs +++ b/NCDK/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraph.cs @@ -22,12 +22,12 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Common.Base; using NCDK.SMSD.Algorithms.Matchers; using NCDK.SMSD.Helper; using System; using System.Collections.Generic; -using System.Collections.ObjectModel; namespace NCDK.SMSD.Algorithms.MCSPluses { @@ -89,7 +89,7 @@ public GenerateCompatibilityGraph(IAtomContainer source, IAtomContainer target, } } - private List> LabelAtoms(IAtomContainer atomCont) + private static List> LabelAtoms(IAtomContainer atomCont) { List> labelList = new List>(); @@ -125,7 +125,7 @@ private List> LabelAtoms(IAtomContainer atomCont) return labelList; } - private void BubbleSort(List label) + private static void BubbleSort(List label) { bool flag = true; // set flag to 1 to begin initial pass @@ -150,7 +150,7 @@ private void BubbleSort(List label) } } - private List ReduceAtomSet(IAtomContainer atomCont) + private static List ReduceAtomSet(IAtomContainer atomCont) { List basicAtoms = new List(); @@ -373,19 +373,19 @@ private static bool IsMatchFeasible(IAtomContainer ac1, IBond bondA1, IAtomConta return false; } - public IList GetCEgdes() + public IReadOnlyList GetCEgdes() { - return new ReadOnlyCollection(cEdges); + return cEdges; } - internal IList GetDEgdes() + internal IReadOnlyList GetDEgdes() { - return new ReadOnlyCollection(dEdges); + return dEdges; } - internal IList GetCompGraphNodes() + internal IReadOnlyList GetCompGraphNodes() { - return new ReadOnlyCollection(compGraphNodes); + return compGraphNodes; } internal int CEdgesSize => cEdgesSize; diff --git a/NCDK/SMSD/Algorithms/MCSPluses/MCSPlus.cs b/NCDK/SMSD/Algorithms/MCSPluses/MCSPlus.cs index 6b86c48b..b4de149d 100644 --- a/NCDK/SMSD/Algorithms/MCSPluses/MCSPlus.cs +++ b/NCDK/SMSD/Algorithms/MCSPluses/MCSPlus.cs @@ -22,7 +22,7 @@ */ using NCDK.Common.Collections; using NCDK.SMSD.Algorithms.McGregors; -using NCDK.SMSD.Global; +using NCDK.SMSD.Globals; using NCDK.SMSD.Tools; using System; using System.Collections.Generic; @@ -40,26 +40,20 @@ namespace NCDK.SMSD.Algorithms.MCSPluses // @cdk.githash // @author Syed Asad Rahman [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] - public class MCSPlus + public static class MCSPlus { - /// - /// Default constructor added - /// - public MCSPlus() - { } - private static TimeManager timeManager = null; /// /// the timeout /// - protected static double GetTimeOut() => TimeOut.Instance.Time; + internal static double GetTimeOut() => TimeOut.Instance.Time; /// /// the timeManager /// [MethodImpl(MethodImplOptions.Synchronized)] - protected static TimeManager GetTimeManager() + internal static TimeManager GetTimeManager() { return timeManager; } @@ -68,16 +62,16 @@ protected static TimeManager GetTimeManager() /// /// the timeManager to set [MethodImpl(MethodImplOptions.Synchronized)] - protected internal static void SetTimeManager(TimeManager aTimeManager) + internal static void SetTimeManager(TimeManager aTimeManager) { TimeOut.Instance.Enabled = false; timeManager = aTimeManager; } - internal IList> GetOverlaps(IAtomContainer ac1, IAtomContainer ac2, bool shouldMatchBonds) + internal static List> GetOverlaps(IAtomContainer ac1, IAtomContainer ac2, bool shouldMatchBonds) { - Deque> maxCliqueSet = null; - IList> mappings = new List>(); + Deque> maxCliqueSet = null; + var mappings = new List>(); try { GenerateCompatibilityGraph gcg = new GenerateCompatibilityGraph(ac1, ac2, shouldMatchBonds); @@ -86,17 +80,9 @@ internal IList> GetOverlaps(IAtomContainer ac1, IAtomContainer ac2, b var cEdges = gcg.GetCEgdes(); var dEdges = gcg.GetDEgdes(); - // Console.Error.WriteLine("**************************************************"); - // Console.Error.WriteLine("CEdges: " + CEdges.Count); - // Console.Out.WriteLine("DEdges: " + DEdges.Count); - BKKCKCF init = new BKKCKCF(compGraphNodes, cEdges, dEdges); maxCliqueSet = init.GetMaxCliqueSet(); - // Console.Error.WriteLine("**************************************************"); - // Console.Error.WriteLine("Max_Cliques_Set: " + maxCliqueSet.Count); - // Console.Out.WriteLine("Best Clique Size: " + init.GetBestCliqueSize()); - //clear all the compatibility graph content gcg.Clear(); while (maxCliqueSet.Count != 0) @@ -107,7 +93,7 @@ internal IList> GetOverlaps(IAtomContainer ac1, IAtomContainer ac2, b { McGregor mgit = new McGregor(ac1, ac2, mappings, shouldMatchBonds); mgit.StartMcGregorIteration(mgit.MCSSize, cliqueList, compGraphNodes); - mappings = mgit.Mappings; + mappings = mgit.mappings; mgit = null; } else diff --git a/NCDK/SMSD/Algorithms/MCSPluses/MCSPlusHandler.cs b/NCDK/SMSD/Algorithms/MCSPluses/MCSPlusHandler.cs index 7f1c6329..1fd5b521 100644 --- a/NCDK/SMSD/Algorithms/MCSPluses/MCSPlusHandler.cs +++ b/NCDK/SMSD/Algorithms/MCSPluses/MCSPlusHandler.cs @@ -41,10 +41,10 @@ namespace NCDK.SMSD.Algorithms.MCSPluses [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] public class MCSPlusHandler : AbstractMCSAlgorithm, IMCSBase { - private static IList> allAtomMCS = null; - private static IDictionary atomsMCS = null; - private static IDictionary firstMCS = null; - private static List> allMCS = null; + private static List> allAtomMCS = null; + private static Dictionary atomsMCS = null; + private static SortedDictionary firstMCS = null; + private static List> allMCS = null; private IAtomContainer source = null; private IAtomContainer target = null; private bool flagExchange = false; @@ -54,10 +54,10 @@ public class MCSPlusHandler : AbstractMCSAlgorithm, IMCSBase /// public MCSPlusHandler() { - allAtomMCS = new List>(); + allAtomMCS = new List>(); atomsMCS = new Dictionary(); firstMCS = new SortedDictionary(); - allMCS = new List>(); + allMCS = new List>(); } [MethodImpl(MethodImplOptions.Synchronized)] @@ -79,17 +79,17 @@ public void Set(IQueryAtomContainer source, IAtomContainer target) [MethodImpl(MethodImplOptions.Synchronized)] public override void SearchMCS(bool shouldMatchBonds) { - IList> mappings = null; + IList> mappings = null; try { if (source.Atoms.Count >= target.Atoms.Count) { - mappings = new MCSPlus().GetOverlaps(source, target, shouldMatchBonds); + mappings = MCSPlus.GetOverlaps(source, target, shouldMatchBonds); } else { flagExchange = true; - mappings = new MCSPlus().GetOverlaps(target, source, shouldMatchBonds); + mappings = MCSPlus.GetOverlaps(target, source, shouldMatchBonds); } PostFilter.Filter(mappings); SetAllMapping(); @@ -112,8 +112,7 @@ private void SetAllMapping() int counter = 0; foreach (var solution in finalSolution) { - // Console.Out.WriteLine("Number of MCS solution: " + solution); - IDictionary validSolution = new SortedDictionary(); + var validSolution = new SortedDictionary(); if (!flagExchange) { foreach (var map in solution) @@ -145,7 +144,7 @@ private void SetAllAtomMapping() int counter = 0; foreach (var solution in allMCS) { - IDictionary atomMappings = new Dictionary(); + var atomMappings = new Dictionary(); foreach (var map in solution) { int iIndex = map.Key; @@ -168,43 +167,47 @@ private void SetAllAtomMapping() } [MethodImpl(MethodImplOptions.Synchronized)] - private void SetFirstMapping() + private static void SetFirstMapping() { if (allMCS.Count != 0) { - firstMCS = new SortedDictionary(allMCS.First()); + firstMCS = new SortedDictionary(); + foreach (var e in allMCS.First()) + firstMCS.Add(e.Key, e.Value); } } [MethodImpl(MethodImplOptions.Synchronized)] - private void SetFirstAtomMapping() + private static void SetFirstAtomMapping() { if (allAtomMCS.Count != 0) { - atomsMCS = new Dictionary(allAtomMCS.First()); + atomsMCS = new Dictionary(); + foreach (var e in allAtomMCS.First()) + atomsMCS.Add(e.Key, e.Value); } } [MethodImpl(MethodImplOptions.Synchronized)] - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { return allMCS; } [MethodImpl(MethodImplOptions.Synchronized)] - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { return firstMCS; } [MethodImpl(MethodImplOptions.Synchronized)] - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { return allAtomMCS; } [MethodImpl(MethodImplOptions.Synchronized)] - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { return atomsMCS; } diff --git a/NCDK/SMSD/Algorithms/Matchers/DefaultBondMatcher.cs b/NCDK/SMSD/Algorithms/Matchers/DefaultBondMatcher.cs index 97b1c6ed..e644d839 100644 --- a/NCDK/SMSD/Algorithms/Matchers/DefaultBondMatcher.cs +++ b/NCDK/SMSD/Algorithms/Matchers/DefaultBondMatcher.cs @@ -59,8 +59,7 @@ public class DefaultBondMatcher : IBondMatcher { private IBond queryBond = null; private IQueryBond smartQueryBond = null; - private int unsaturation = 0; - private bool shouldMatchBonds = false; + private readonly int unsaturation = 0; /// /// Constructor @@ -70,7 +69,7 @@ public DefaultBondMatcher() this.queryBond = null; this.smartQueryBond = null; this.unsaturation = -1; - shouldMatchBonds = false; + IsBondMatchFlag = false; } /// @@ -144,41 +143,31 @@ private bool IsBondTypeMatch(IBond targetBond) return false; } - private int GetValency(IAtom atom) + private static int GetValency(IAtom atom) { return atom.Valency ?? 0; } - private int GetUnsaturation(IAtomContainer container, IBond bond) + private static int GetUnsaturation(IAtomContainer container, IBond bond) { return GetUnsaturation(container, bond.Begin) + GetUnsaturation(container, bond.End); } - private int GetUnsaturation(IAtomContainer container, IAtom atom) + private static int GetUnsaturation(IAtomContainer container, IAtom atom) { return GetValency(atom) - (CountNeighbors(container, atom) + CountImplicitHydrogens(atom)); } - private int CountNeighbors(IAtomContainer container, IAtom atom) + private static int CountNeighbors(IAtomContainer container, IAtom atom) { return container.GetConnectedBonds(atom).Count(); } - private int CountImplicitHydrogens(IAtom atom) + private static int CountImplicitHydrogens(IAtom atom) { return atom.ImplicitHydrogenCount ?? 0; } - public bool IsBondMatchFlag - { - get - { - return shouldMatchBonds; - } - set - { - this.shouldMatchBonds = value; - } - } + public bool IsBondMatchFlag { get; set; } = false; } } diff --git a/NCDK/SMSD/Algorithms/Matchers/DefaultMCSPlusAtomMatcher.cs b/NCDK/SMSD/Algorithms/Matchers/DefaultMCSPlusAtomMatcher.cs index d8508608..28a2a8ac 100644 --- a/NCDK/SMSD/Algorithms/Matchers/DefaultMCSPlusAtomMatcher.cs +++ b/NCDK/SMSD/Algorithms/Matchers/DefaultMCSPlusAtomMatcher.cs @@ -45,6 +45,7 @@ * THE SOFTWARE. */ using NCDK.Isomorphisms.Matchers; +using System; using System.Linq; namespace NCDK.SMSD.Algorithms.Matchers @@ -59,7 +60,7 @@ public class DefaultMCSPlusAtomMatcher : IAtomMatcher { private int maximumNeighbors; private string symbol = null; - private IAtom qAtom = null; + private readonly IAtom qAtom = null; private IQueryAtom smartQueryAtom = null; private bool shouldMatchBonds = false; @@ -148,7 +149,7 @@ private bool MatchSymbol(IAtom atom) { return false; } - return symbol.Equals(atom.Symbol); + return symbol.Equals(atom.Symbol, StringComparison.Ordinal); } private bool MatchMaximumNeighbors(IAtomContainer targetContainer, IAtom targetAtom) @@ -162,7 +163,7 @@ private bool MatchMaximumNeighbors(IAtomContainer targetContainer, IAtom targetA return maximumTargetNeighbors >= maximumNeighbors; } - private int CountImplicitHydrogens(IAtom atom) + private static int CountImplicitHydrogens(IAtom atom) { return atom.ImplicitHydrogenCount ?? 0; } diff --git a/NCDK/SMSD/Algorithms/Matchers/DefaultMatcher.cs b/NCDK/SMSD/Algorithms/Matchers/DefaultMatcher.cs index be995503..7bd9348c 100644 --- a/NCDK/SMSD/Algorithms/Matchers/DefaultMatcher.cs +++ b/NCDK/SMSD/Algorithms/Matchers/DefaultMatcher.cs @@ -44,6 +44,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ + namespace NCDK.SMSD.Algorithms.Matchers { /// @@ -52,13 +53,10 @@ namespace NCDK.SMSD.Algorithms.Matchers // @cdk.module smsd // @cdk.githash // @author Syed Asad Rahman - public class DefaultMatcher + public static class DefaultMatcher { - - public static bool IsBondMatch(IBondMatcher bondMatcher, IAtomContainer ac2, IBond bondA2, - bool shouldMatchBonds) + public static bool IsBondMatch(IBondMatcher bondMatcher, IAtomContainer ac2, IBond bondA2, bool shouldMatchBonds) { - // ok, bonds match if (bondMatcher.Matches(ac2, bondA2)) { @@ -66,23 +64,18 @@ public static bool IsBondMatch(IBondMatcher bondMatcher, IAtomContainer ac2, IBo return true; } return false; - } - public static bool IsAtomMatch(IAtomMatcher atomMatcher1, IAtomMatcher atomMatcher2, IAtomContainer ac2, - IBond bondA2, bool shouldMatchBonds) + public static bool IsAtomMatch(IAtomMatcher atomMatcher1, IAtomMatcher atomMatcher2, IAtomContainer ac2, IBond bondA2, bool shouldMatchBonds) { - // ok, atoms match if (atomMatcher1.Matches(ac2, bondA2.Atoms[0]) && atomMatcher2.Matches(ac2, bondA2.Atoms[1])) { - // Console.Out.WriteLine("Atom Matched"); return true; } // ok, atoms match if (atomMatcher1.Matches(ac2, bondA2.Atoms[1]) && atomMatcher2.Matches(ac2, bondA2.Atoms[0])) { - // Console.Out.WriteLine("Atom Matched"); return true; } return false; diff --git a/NCDK/SMSD/Algorithms/Matchers/DefaultRGraphAtomMatcher.cs b/NCDK/SMSD/Algorithms/Matchers/DefaultRGraphAtomMatcher.cs index e4b3673e..355d0c8f 100644 --- a/NCDK/SMSD/Algorithms/Matchers/DefaultRGraphAtomMatcher.cs +++ b/NCDK/SMSD/Algorithms/Matchers/DefaultRGraphAtomMatcher.cs @@ -45,6 +45,7 @@ * THE SOFTWARE. */ using NCDK.Isomorphisms.Matchers; +using System; using System.Linq; namespace NCDK.SMSD.Algorithms.Matchers @@ -59,23 +60,12 @@ public class DefaultRGraphAtomMatcher : IAtomMatcher { private int maximumNeighbors; private string symbol = null; - private IAtom qAtom = null; - private bool shouldMatchBonds = false; + private readonly IAtom qAtom = null; /// /// the shouldMatchBonds /// - public bool IsBondMatchFlag - { - get - { - return shouldMatchBonds; - } - set - { - this.shouldMatchBonds = value; - } - } + public bool IsBondMatchFlag { get; set; } = false; /// /// Constructor @@ -154,7 +144,7 @@ private bool MatchSymbol(IAtom atom) { return false; } - return symbol.Equals(atom.Symbol); + return symbol.Equals(atom.Symbol, StringComparison.Ordinal); } private bool MatchMaximumNeighbors(IAtomContainer targetContainer, IAtom targetAtom) @@ -168,17 +158,17 @@ private bool MatchMaximumNeighbors(IAtomContainer targetContainer, IAtom targetA return maximumTargetNeighbors >= maximumNeighbors; } - private int CountImplicitHydrogens(IAtom atom) + private static int CountImplicitHydrogens(IAtom atom) { return atom.ImplicitHydrogenCount ?? 0; } - private int CountSaturation(IAtomContainer container, IAtom atom) + private static int CountSaturation(IAtomContainer container, IAtom atom) { return CountNeighbors(container, atom) + CountImplicitHydrogens(atom); } - private int CountNeighbors(IAtomContainer container, IAtom atom) + private static int CountNeighbors(IAtomContainer container, IAtom atom) { return container.GetConnectedAtoms(atom).Count(); } diff --git a/NCDK/SMSD/Algorithms/Matchers/DefaultVFAtomMatcher.cs b/NCDK/SMSD/Algorithms/Matchers/DefaultVFAtomMatcher.cs index 459fde6f..b8b8a6d3 100644 --- a/NCDK/SMSD/Algorithms/Matchers/DefaultVFAtomMatcher.cs +++ b/NCDK/SMSD/Algorithms/Matchers/DefaultVFAtomMatcher.cs @@ -46,6 +46,7 @@ */ using NCDK.Isomorphisms.Matchers; using NCDK.SMSD.Algorithms.VFLib.Builder; +using System; using System.Linq; namespace NCDK.SMSD.Algorithms.Matchers @@ -60,7 +61,7 @@ public class DefaultVFAtomMatcher : IVFAtomMatcher { private int maximumNeighbors; private string symbol = null; - private IAtom qAtom = null; + private readonly IAtom qAtom = null; private IQueryAtom smartQueryAtom = null; private bool shouldMatchBonds = false; @@ -149,7 +150,7 @@ private bool MatchSymbol(IAtom atom) { return false; } - return symbol.Equals(atom.Symbol); + return symbol.Equals(atom.Symbol, StringComparison.Ordinal); } private bool MatchMaximumNeighbors(TargetProperties targetContainer, IAtom targetAtom) @@ -163,7 +164,7 @@ private bool MatchMaximumNeighbors(TargetProperties targetContainer, IAtom targe return maximumTargetNeighbors <= maximumNeighbors; } - private int CountImplicitHydrogens(IAtom atom) + private static int CountImplicitHydrogens(IAtom atom) { return atom.ImplicitHydrogenCount ?? 0; } diff --git a/NCDK/SMSD/Algorithms/Matchers/DefaultVFBondMatcher.cs b/NCDK/SMSD/Algorithms/Matchers/DefaultVFBondMatcher.cs index a4549018..e46e3654 100644 --- a/NCDK/SMSD/Algorithms/Matchers/DefaultVFBondMatcher.cs +++ b/NCDK/SMSD/Algorithms/Matchers/DefaultVFBondMatcher.cs @@ -59,7 +59,7 @@ namespace NCDK.SMSD.Algorithms.Matchers public class DefaultVFBondMatcher : IVFBondMatcher { private IBond queryBond = null; - private int unsaturation = 0; + private readonly int unsaturation = 0; private bool shouldMatchBonds; private IQueryBond smartQueryBond = null; @@ -146,37 +146,37 @@ private bool IsBondTypeMatch(IBond targetBond) return false; } - private int GetUnsaturation(TargetProperties container, IBond bond) + private static int GetUnsaturation(TargetProperties container, IBond bond) { return GetUnsaturation(container, bond.Atoms[0]) + GetUnsaturation(container, bond.Atoms[1]); } - private int GetUnsaturation(TargetProperties container, IAtom atom) + private static int GetUnsaturation(TargetProperties container, IAtom atom) { return GetValency(atom) - container.CountNeighbors(atom); } - private int GetValency(IAtom atom) + private static int GetValency(IAtom atom) { return (atom.Valency == null) ? 0 : atom.Valency.Value; } - private int GetUnsaturation(IAtomContainer container, IBond bond) + private static int GetUnsaturation(IAtomContainer container, IBond bond) { return GetUnsaturation(container, bond.Atoms[0]) + GetUnsaturation(container, bond.Atoms[1]); } - private int GetUnsaturation(IAtomContainer container, IAtom atom) + private static int GetUnsaturation(IAtomContainer container, IAtom atom) { return GetValency(atom) - (CountNeighbors(container, atom) + CountImplicitHydrogens(atom)); } - private int CountNeighbors(IAtomContainer container, IAtom atom) + private static int CountNeighbors(IAtomContainer container, IAtom atom) { return container.GetConnectedAtoms(atom).Count(); } - private int CountImplicitHydrogens(IAtom atom) + private static int CountImplicitHydrogens(IAtom atom) { return atom.ImplicitHydrogenCount ?? 0; } diff --git a/NCDK/SMSD/Algorithms/McGregors/McGregor.cs b/NCDK/SMSD/Algorithms/McGregors/McGregor.cs index 9644fc56..102b40ab 100644 --- a/NCDK/SMSD/Algorithms/McGregors/McGregor.cs +++ b/NCDK/SMSD/Algorithms/McGregors/McGregor.cs @@ -21,11 +21,13 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Isomorphisms.Matchers; using NCDK.SMSD.Helper; using System; using System.Collections.Generic; using System.IO; +using System.Linq; namespace NCDK.SMSD.Algorithms.McGregors { @@ -48,11 +50,11 @@ public sealed class McGregor private IAtomContainer target = null; private BinaryTree last = null; private BinaryTree first = null; - private Stack> bestArcs = null; - private IList modifiedARCS = null; + private Stack> bestArcs = null; + private List modifiedARCS = null; private int bestarcsleft = 0; private int globalMCSSize = 0; - private IList> mappings = null; + internal List> mappings = null; /* This should be more or equal to all the atom types */ private static readonly string[] SIGNS = {"$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$15", "$16", "$17", "$18", "$19", "$20", "$21", "$22", "$23", "$24", "$25", "$26", "$27", @@ -61,31 +63,24 @@ public sealed class McGregor private bool newMatrix = false; private bool bondMatch = false; - /// - /// Constructor for the McGregor algorithm. - /// - /// - /// - /// - /// - public McGregor(IAtomContainer source, IAtomContainer target, IList> mappings, bool shouldMatchBonds) + public McGregor(IAtomContainer source, IAtomContainer target, IEnumerable> mappings, bool shouldMatchBonds) { IsBondMatch = shouldMatchBonds; this.source = source; this.target = target; - this.mappings = mappings; + this.mappings = mappings.ToList(); this.bestarcsleft = 0; - if (mappings.Count != 0) + if (this.mappings.Count != 0) { - this.globalMCSSize = mappings[0].Count; + this.globalMCSSize = this.mappings[0].Count; } else { this.globalMCSSize = 0; } this.modifiedARCS = new List(); - this.bestArcs = new Stack>(); + this.bestArcs = new Stack>(); this.newMatrix = false; } @@ -95,24 +90,24 @@ public McGregor(IAtomContainer source, IAtomContainer target, IList> /// /// /// - public McGregor(IQueryAtomContainer source, IAtomContainer target, IList> mappings) + public McGregor(IQueryAtomContainer source, IAtomContainer target, IEnumerable> mappings) { IsBondMatch = true; this.source = source; this.target = target; - this.mappings = mappings; + this.mappings = mappings.ToList(); this.bestarcsleft = 0; - if (mappings.Count != 0) + if (this.mappings.Count != 0) { - this.globalMCSSize = mappings[0].Count; + this.globalMCSSize = this.mappings[0].Count; } else { this.globalMCSSize = 0; } this.modifiedARCS = new List(); - this.bestArcs = new Stack>(); + this.bestArcs = new Stack>(); this.newMatrix = false; } @@ -122,7 +117,7 @@ public McGregor(IQueryAtomContainer source, IAtomContainer target, IList /// /// - public void StartMcGregorIteration(int largestMappingSize, IDictionary presentMapping) + public void StartMcGregorIteration(int largestMappingSize, IReadOnlyDictionary presentMapping) { this.globalMCSSize = (largestMappingSize / 2); var cTab1Copy = McGregorChecks.GenerateCTabCopy(source); @@ -218,8 +213,9 @@ public void StartMcGregorIteration(int largestMappingSize, IDictionary /// /// /// - public void StartMcGregorIteration(int largestMappingSize, IList cliqueVector, - IList compGraphNodes) + public void StartMcGregorIteration(int largestMappingSize, + IReadOnlyList cliqueVector, + IReadOnlyList compGraphNodes) { this.globalMCSSize = (largestMappingSize / 2); List cTab1Copy = McGregorChecks.GenerateCTabCopy(source); @@ -354,7 +350,7 @@ private int Iterator(McgregorHelper mcGregorHelper) bestarcsleft = 0; Startsearch(mcGregorHelper); - Stack> bestArcsCopy = new Stack>(); + var bestArcsCopy = new Stack>(); foreach (var bestArc in bestArcs) bestArcsCopy.Push(bestArc); @@ -370,7 +366,7 @@ private int Iterator(McgregorHelper mcGregorHelper) return 0; } - private void SearchAndExtendMappings(Stack> bestarcsCopy, McgregorHelper mcGregorHelper) + private void SearchAndExtendMappings(Stack> bestarcsCopy, McgregorHelper mcGregorHelper) { int mappedAtomCount = mcGregorHelper.MappedAtomCount; @@ -762,7 +758,7 @@ private void Startsearch(McgregorHelper mcGregorHelper) /// Returns computed mappings. /// mappings /// - public IList> Mappings => mappings; + public IReadOnlyList> Mappings => mappings; /// /// Returns MCS size. @@ -776,16 +772,12 @@ private void SetFinalMappings(List mappedAtoms, int mappedAtomCount) { if (mappedAtomCount >= globalMCSSize) { - // Console.Out.WriteLine("Hello-1"); if (mappedAtomCount > globalMCSSize) { - // Console.Out.WriteLine("Hello-2"); this.globalMCSSize = mappedAtomCount; - // Console.Out.WriteLine("best_MAPPING_size: " + globalMCSSize); mappings.Clear(); } mappings.Add(mappedAtoms); - // Console.Out.WriteLine("mappings " + mappings); } } catch (Exception ex) @@ -893,10 +885,12 @@ private void ExtendMapping(int xIndex, int yIndex, McgregorHelper mcGregorHelper } } - private bool MatchGAtoms(string g1A, string g2A, string g1B, string g2B) + private static bool MatchGAtoms(string g1A, string g2A, string g1B, string g2B) { - return (string.Equals(g1A, g1B, StringComparison.OrdinalIgnoreCase) && string.Equals(g2A, g2B, StringComparison.OrdinalIgnoreCase)) - || (string.Equals(g1A, g2B, StringComparison.OrdinalIgnoreCase) && string.Equals(g2A, g1B, StringComparison.OrdinalIgnoreCase)); + return (string.Equals(g1A, g1B, StringComparison.OrdinalIgnoreCase) + && string.Equals(g2A, g2B, StringComparison.OrdinalIgnoreCase)) + || (string.Equals(g1A, g2B, StringComparison.OrdinalIgnoreCase) + && string.Equals(g2A, g1B, StringComparison.OrdinalIgnoreCase)); } /// diff --git a/NCDK/SMSD/Algorithms/McGregors/McGregorChecks.cs b/NCDK/SMSD/Algorithms/McGregors/McGregorChecks.cs index 72485b1b..96318d94 100644 --- a/NCDK/SMSD/Algorithms/McGregors/McGregorChecks.cs +++ b/NCDK/SMSD/Algorithms/McGregors/McGregorChecks.cs @@ -24,6 +24,7 @@ using NCDK.SMSD.Helper; using System; using System.Collections.Generic; +using System.Linq; namespace NCDK.SMSD.Algorithms.McGregors { @@ -34,9 +35,9 @@ namespace NCDK.SMSD.Algorithms.McGregors // @cdk.githash // @author Syed Asad Rahman [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] - public class McGregorChecks + public static class McGregorChecks { - protected internal static bool IsFurtherMappingPossible(IAtomContainer source, IAtomContainer target, + internal static bool IsFurtherMappingPossible(IAtomContainer source, IAtomContainer target, int neighborBondNumA, int neighborBondNumB, IList iBondNeighborAtomsA, IList iBondNeighborAtomsB, IList cBondNeighborsA, IList cBondNeighborsB, bool shouldMatchBonds) @@ -86,7 +87,7 @@ protected internal static bool IsFurtherMappingPossible(IAtomContainer source, I return false; } - protected internal static bool IsMatchFeasible(IAtomContainer ac1, IBond bondA1, IAtomContainer ac2, IBond bondA2, + internal static bool IsMatchFeasible(IAtomContainer ac1, IBond bondA1, IAtomContainer ac2, IBond bondA2, bool shouldMatchBonds) { if (ac1 is IQueryAtomContainer) @@ -124,7 +125,7 @@ protected internal static bool IsMatchFeasible(IAtomContainer ac1, IBond bondA1, } } - protected internal static int SearchCorrespondingAtom(int mappedAtomsSize, int atomFromOtherMolecule, int molecule, IList mappedAtomsOrg) + internal static int SearchCorrespondingAtom(int mappedAtomsSize, int atomFromOtherMolecule, int molecule, IList mappedAtomsOrg) { List mappedAtoms = new List(mappedAtomsOrg); @@ -143,7 +144,7 @@ protected internal static int SearchCorrespondingAtom(int mappedAtomsSize, int a return correspondingAtom; } - protected internal static bool IsAtomMatch(string g1A, string g2A, string g1B, string g2B) + internal static bool IsAtomMatch(string g1A, string g2A, string g1B, string g2B) { if ((string.Equals(g1A, g1B, StringComparison.OrdinalIgnoreCase) && string.Equals(g2A, g2B, StringComparison.OrdinalIgnoreCase)) || (string.Equals(g1A, g2B, StringComparison.OrdinalIgnoreCase) && string.Equals(g2A, g1B, StringComparison.OrdinalIgnoreCase))) @@ -154,7 +155,7 @@ protected internal static bool IsAtomMatch(string g1A, string g2A, string g1B, s } // Modified function call by ASAD in Java have to check - protected internal static int RemoveTreeStructure(BinaryTree curStruc) + internal static int RemoveTreeStructure(BinaryTree curStruc) { BinaryTree equalStruc = curStruc.Equal; BinaryTree notEqualStruc = curStruc.NotEqual; @@ -176,7 +177,7 @@ protected internal static int RemoveTreeStructure(BinaryTree curStruc) //Function compaires a structure array with itself. Sometimes a mapping occurs several times within the array. //The function eliminates these recurring mappings. Function is called in function best_solution. //The function is called by itself as long as the last list element is processed. - protected internal static IList RemoveRecurringMappings(IList atomMapping) + internal static IList RemoveRecurringMappings(IList atomMapping) { bool exist = true; List tempMap = new List(); @@ -212,7 +213,7 @@ protected internal static IList RemoveRecurringMappings(IList atomMapp /// position by zeros. Only the entry of the current position is set to one. /// Return value "count_arcsleft" counts the number of arcs, which are still in the matrix. /// - protected internal static void RemoveRedundantArcs(int row, int column, IList marcs, McgregorHelper mcGregorHelper) + internal static void RemoveRedundantArcs(int row, int column, IList marcs, McgregorHelper mcGregorHelper) { int neighborBondNumA = mcGregorHelper.NeighborBondNumA; int neighborBondNumB = mcGregorHelper.NeighborBondNumB; @@ -254,7 +255,7 @@ protected internal static void RemoveRedundantArcs(int row, int column, IList GenerateCSetCopy(int bondNumber, IList cSet) + internal static List GenerateCSetCopy(int bondNumber, IList cSet) { List cTabCopy = new List(); for (int a = 0; a < bondNumber; a++) @@ -267,7 +268,7 @@ protected internal static List GenerateCSetCopy(int bondNumber, IList GenerateCTabCopy(IAtomContainer atomContainer) + internal static List GenerateCTabCopy(IAtomContainer atomContainer) { List cTabCopy = new List(); foreach (var bond in atomContainer.Bonds) @@ -282,8 +283,7 @@ protected internal static List GenerateCTabCopy(IAtomContainer atomConta return cTabCopy; } - protected static bool Case1(int g1Atom, int g3Atom, int g4Atom, int rowAtom1, int rowAtom2, - int columnAtom3, int columnAtom4) + static bool Case1(int g1Atom, int g3Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) { if (((g1Atom == rowAtom1) || (g1Atom == rowAtom2)) && (!(((columnAtom3 == g3Atom) || (columnAtom4 == g3Atom)) || ((columnAtom3 == g4Atom) || (columnAtom4 == g4Atom))))) @@ -293,7 +293,7 @@ protected static bool Case1(int g1Atom, int g3Atom, int g4Atom, int rowAtom1, in return false; } - protected static bool Case2(int g2Atom, int g3Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) + static bool Case2(int g2Atom, int g3Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) { if (((g2Atom == rowAtom1) || (g2Atom == rowAtom2)) && (!(((columnAtom3 == g3Atom) || (columnAtom4 == g3Atom)) || ((columnAtom3 == g4Atom) || (columnAtom4 == g4Atom))))) @@ -303,7 +303,7 @@ protected static bool Case2(int g2Atom, int g3Atom, int g4Atom, int rowAtom1, in return false; } - protected static bool Case3(int g1Atom, int g3Atom, int g2Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) + static bool Case3(int g1Atom, int g3Atom, int g2Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) { if (((g3Atom == columnAtom3) || (g3Atom == columnAtom4)) && (!(((rowAtom1 == g1Atom) || (rowAtom2 == g1Atom)) || ((rowAtom1 == g2Atom) || (rowAtom2 == g2Atom))))) @@ -313,7 +313,7 @@ protected static bool Case3(int g1Atom, int g3Atom, int g2Atom, int rowAtom1, in return false; } - protected static bool Case4(int g1Atom, int g2Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) + static bool Case4(int g1Atom, int g2Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) { if (((g4Atom == columnAtom3) || (g4Atom == columnAtom4)) && (!(((rowAtom1 == g1Atom) || (rowAtom2 == g1Atom)) || ((rowAtom1 == g2Atom) || (rowAtom2 == g2Atom))))) @@ -323,7 +323,7 @@ protected static bool Case4(int g1Atom, int g2Atom, int g4Atom, int rowAtom1, in return false; } - protected static bool Cases(int g1Atom, int g2Atom, int g3Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) + static bool Cases(int g1Atom, int g2Atom, int g3Atom, int g4Atom, int rowAtom1, int rowAtom2, int columnAtom3, int columnAtom4) { if (Case1(g1Atom, g3Atom, g4Atom, rowAtom1, rowAtom2, columnAtom3, columnAtom4) || Case2(g2Atom, g3Atom, g4Atom, rowAtom1, rowAtom2, columnAtom3, columnAtom4) @@ -335,7 +335,7 @@ protected static bool Cases(int g1Atom, int g2Atom, int g3Atom, int g4Atom, int return false; } - protected internal static List SetArcs(IAtomContainer source, IAtomContainer target, int neighborBondNumA, + internal static List SetArcs(IAtomContainer source, IAtomContainer target, int neighborBondNumA, int neighborBondNumB, List iBondNeighborAtomsA, List iBondNeighborAtomsB, List cBondNeighborsA, List cBondNeighborsB, List modifiedARCS, bool shouldMatchBonds) @@ -374,7 +374,7 @@ protected internal static List SetArcs(IAtomContainer source, IAtomContaine return modifiedARCS; } - protected internal static int CountArcsLeft(List tempmarcs, int neighborBondNumA, int neighborBondNumB) + internal static int CountArcsLeft(List tempmarcs, int neighborBondNumA, int neighborBondNumB) { int arcsleft = 0; @@ -392,8 +392,7 @@ protected internal static int CountArcsLeft(List tempmarcs, int neighborBon return arcsleft; } - protected internal static int ChangeCharBonds(int correspondingAtom, string newSymbol, int neighborBondNum, - IAtomContainer atomContainer, IList cBondNeighbors) + internal static int ChangeCharBonds(int correspondingAtom, string newSymbol, int neighborBondNum, IAtomContainer atomContainer, IList cBondNeighbors) { for (int atomIndex = 0; atomIndex < neighborBondNum; atomIndex++) { @@ -415,8 +414,7 @@ protected internal static int ChangeCharBonds(int correspondingAtom, string newS return 0; } - protected internal static int ChangeCharBonds(int correspondingAtom, string newSymbol, int neighborBondNum, - IList iBondNeighbors, IList cBondNeighbors) + internal static int ChangeCharBonds(int correspondingAtom, string newSymbol, int neighborBondNum, IList iBondNeighbors, IList cBondNeighbors) { for (int atomIndex = 0; atomIndex < neighborBondNum; atomIndex++) { @@ -492,9 +490,9 @@ internal static bool IsFurtherMappingPossible(IAtomContainer source, IAtomContai return false; } - internal static List MarkUnMappedAtoms(bool flag, IAtomContainer container, IDictionary presentMapping) + internal static List MarkUnMappedAtoms(bool flag, IAtomContainer container, IReadOnlyDictionary presentMapping) { - List unmappedMolAtoms = new List(); + var unmappedMolAtoms = new List(); int unmappedNum = 0; bool atomIsUnmapped = true; diff --git a/NCDK/SMSD/Algorithms/McGregors/QueryProcessor.cs b/NCDK/SMSD/Algorithms/McGregors/QueryProcessor.cs index 34f32b88..90da7868 100644 --- a/NCDK/SMSD/Algorithms/McGregors/QueryProcessor.cs +++ b/NCDK/SMSD/Algorithms/McGregors/QueryProcessor.cs @@ -196,8 +196,7 @@ protected internal void Process(int setNumA, int setNumB, IList iBondSetA, } } - private int SearchCorrespondingAtom(int mappedAtomsSize, int atomFromOtherMolecule, int molecule, - IList mappedAtomsOrg) + private static int SearchCorrespondingAtom(int mappedAtomsSize, int atomFromOtherMolecule, int molecule, IList mappedAtomsOrg) { List mappedAtoms = new List(mappedAtomsOrg); diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKMCS.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKMCS.cs similarity index 90% rename from NCDK/SMSD/Algorithms/RGraph/CDKMCS.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKMCS.cs index 578fcc29..aac12f00 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKMCS.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKMCS.cs @@ -51,15 +51,16 @@ using NCDK.Isomorphisms.Matchers; using NCDK.SMSD.Algorithms.Matchers; -using NCDK.SMSD.Global; +using NCDK.SMSD.Globals; using NCDK.SMSD.Tools; using NCDK.Tools.Manipulator; +using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// This class implements atom multipurpose structure comparison tool. @@ -105,10 +106,14 @@ namespace NCDK.SMSD.Algorithms.RGraph // @cdk.require java1.5+ // @cdk.module smsd // @cdk.githash - public class CDKMCS + public static class CDKMCS { - const int Id1 = 0; - const int Id2 = 1; + private enum IdType + { + Id1 = 0, + Id2 = 1, + }; + private static TimeManager timeManager = null; /////////////////////////////////////////////////////////////////////////// @@ -156,7 +161,7 @@ public static bool IsIsomorph(IAtomContainer sourceGraph, IAtomContainer targetG else { string atomSymbol = atom2.Symbol; - return sourceGraph.Atoms[0].Symbol.Equals(atomSymbol); + return sourceGraph.Atoms[0].Symbol.Equals(atomSymbol, StringComparison.Ordinal); } } return (GetIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds) != null); @@ -170,14 +175,14 @@ public static bool IsIsomorph(IAtomContainer sourceGraph, IAtomContainer targetG /// /// the first isomorph mapping found projected of sourceGraph. This is atom List of CDKRMap objects containing Ids of matching bonds. /// - public static IList GetIsomorphMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) + public static IReadOnlyList GetIsomorphMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { if (sourceGraph is IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } - IList result = null; + IReadOnlyList result = null; var rMapsList = Search(sourceGraph, targetGraph, GetBitSet(sourceGraph), GetBitSet(targetGraph), false, false, shouldMatchBonds); @@ -199,17 +204,17 @@ public static IList GetIsomorphMap(IAtomContainer sourceGraph, IAtomCon /// the first isomorph atom mapping found projected on sourceGraph. /// This is atom List of CDKRMap objects containing Ids of matching atoms. /// if the first molecules is not an instance of - public static IList GetIsomorphAtomsMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) + public static IReadOnlyList GetIsomorphAtomsMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { if (sourceGraph is IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } - IList list = CheckSingleAtomCases(sourceGraph, targetGraph); + IReadOnlyList list = CheckSingleAtomCases(sourceGraph, targetGraph); if (list == null) { - return MakeAtomsMapOfBondsMap(CDKMCS.GetIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds), + return MakeAtomsMapOfBondsMap(GetIsomorphMap(sourceGraph, targetGraph, shouldMatchBonds), sourceGraph, targetGraph); } else if (list.Count == 0) @@ -231,13 +236,15 @@ public static IList GetIsomorphAtomsMap(IAtomContainer sourceGraph, IAt /// /// the list of all the 'mappings' /// - public static IList> GetIsomorphMaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) + public static IReadOnlyList> GetIsomorphMaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { return Search(sourceGraph, targetGraph, GetBitSet(sourceGraph), GetBitSet(targetGraph), true, true, shouldMatchBonds); } // // Subgraph search + // + /// /// Returns all the subgraph 'bondA1 mappings' found for targetGraph in sourceGraph. /// This is an ArrayList of ArrayLists of CDKRMap objects. @@ -247,8 +254,7 @@ public static IList> GetIsomorphMaps(IAtomContainer sourceGraph, /// /// the list of all the 'mappings' found projected of sourceGraph /// - public static IList> GetSubgraphMaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, - bool shouldMatchBonds) + public static IReadOnlyList> GetSubgraphMaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { return Search(sourceGraph, targetGraph, new BitArray(sourceGraph.Bonds.Count), GetBitSet(targetGraph), true, true, shouldMatchBonds); } @@ -261,9 +267,9 @@ public static IList> GetSubgraphMaps(IAtomContainer sourceGraph, /// /// the first subgraph bondA1 mapping found projected on sourceGraph. This is atom List of CDKRMap objects containing Ids of matching bonds. /// - public static IList GetSubgraphMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) + public static IReadOnlyList GetSubgraphMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { - IList result = null; + IReadOnlyList result = null; var rMapsList = Search(sourceGraph, targetGraph, new BitArray(sourceGraph.Bonds.Count), GetBitSet(targetGraph), false, false, shouldMatchBonds); @@ -285,18 +291,17 @@ public static IList GetSubgraphMap(IAtomContainer sourceGraph, IAtomCon /// all subgraph atom mappings found projected on sourceGraph. This is atom /// List of CDKRMap objects containing Ids of matching atoms. /// - public static IList> GetSubgraphAtomsMaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, + public static IReadOnlyList> GetSubgraphAtomsMaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { - IList list = CheckSingleAtomCases(sourceGraph, targetGraph); + var list = CheckSingleAtomCases(sourceGraph, targetGraph); if (list == null) { - return MakeAtomsMapsOfBondsMaps(CDKMCS.GetSubgraphMaps(sourceGraph, targetGraph, shouldMatchBonds), - sourceGraph, targetGraph); + return MakeAtomsMapsOfBondsMaps(GetSubgraphMaps(sourceGraph, targetGraph, shouldMatchBonds), sourceGraph, targetGraph); } else { - IList> atomsMap = new List> + var atomsMap = new List> { list }; @@ -313,13 +318,12 @@ public static IList> GetSubgraphAtomsMaps(IAtomContainer sourceGr /// the first subgraph atom mapping found projected on sourceGraph. /// This is atom List of CDKRMap objects containing Ids of matching atoms. /// - public static IList GetSubgraphAtomsMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) + public static IReadOnlyList GetSubgraphAtomsMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { - IList list = CheckSingleAtomCases(sourceGraph, targetGraph); + var list = CheckSingleAtomCases(sourceGraph, targetGraph); if (list == null) { - return MakeAtomsMapOfBondsMap(CDKMCS.GetSubgraphMap(sourceGraph, targetGraph, shouldMatchBonds), - sourceGraph, targetGraph); + return MakeAtomsMapOfBondsMap(GetSubgraphMap(sourceGraph, targetGraph, shouldMatchBonds), sourceGraph, targetGraph); } else if (list.Count == 0) { @@ -373,7 +377,7 @@ public static bool IsSubgraph(IAtomContainer sourceGraph, IAtomContainer targetG } else { - if (atom2.Symbol.Equals(atom.Symbol)) + if (atom2.Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) { return true; } @@ -398,13 +402,12 @@ public static bool IsSubgraph(IAtomContainer sourceGraph, IAtomContainer targetG /// the list of all the maximal common substructure /// found projected of sourceGraph (list of ) /// - public static IList GetOverlaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) + public static IReadOnlyList GetOverlaps(IAtomContainer sourceGraph, IAtomContainer targetGraph, bool shouldMatchBonds) { - IList> rMapsList = Search(sourceGraph, targetGraph, new BitArray(sourceGraph.Bonds.Count), new BitArray(targetGraph.Bonds.Count), true, false, - shouldMatchBonds); + var rMapsList = Search(sourceGraph, targetGraph, new BitArray(sourceGraph.Bonds.Count), new BitArray(targetGraph.Bonds.Count), true, false, shouldMatchBonds); // projection on G1 - IList graphList = ProjectList(rMapsList, sourceGraph, Id1); + var graphList = ProjectList(rMapsList, sourceGraph, IdType.Id1); // reduction of set of solution (isomorphism and substructure // with different 'mappings' @@ -475,14 +478,14 @@ public static CDKRGraph BuildRGraph(IAtomContainer sourceGraph, IAtomContainer t /// /// atom List of Lists of CDKRMap objects that represent the search solutions /// - public static IList> Search(IAtomContainer sourceGraph, IAtomContainer targetGraph, + public static IReadOnlyList> Search(IAtomContainer sourceGraph, IAtomContainer targetGraph, BitArray sourceBitSet, BitArray targetBitSet, bool findAllStructure, bool findAllMap, bool shouldMatchBonds) { // handle single query atom case separately if (targetGraph.Atoms.Count == 1) { - var matches = new List>(); + var matches = new List>(); IAtom queryAtom = targetGraph.Atoms[0]; // we can have a IQueryAtomContainer *or* an IAtomContainer @@ -492,7 +495,7 @@ public static IList> Search(IAtomContainer sourceGraph, IAtomCont { if (qAtom.Matches(atom)) { - List lmap = new List + var lmap = new List { new CDKRMap(sourceGraph.Atoms.IndexOf(atom), 0) }; @@ -504,7 +507,7 @@ public static IList> Search(IAtomContainer sourceGraph, IAtomCont { foreach (var atom in sourceGraph.Atoms) { - if (queryAtom.Symbol.Equals(atom.Symbol)) + if (string.Equals(queryAtom.Symbol, atom.Symbol, StringComparison.Ordinal)) { List lmap = new List { @@ -518,7 +521,7 @@ public static IList> Search(IAtomContainer sourceGraph, IAtomCont } // reset result - var rMapsList = new List>(); + var rMapsList = new List>(); // build the CDKRGraph corresponding to this problem CDKRGraph rGraph = BuildRGraph(sourceGraph, targetGraph, shouldMatchBonds); SetTimeManager(new TimeManager()); @@ -544,7 +547,7 @@ public static IList> Search(IAtomContainer sourceGraph, IAtomCont /// the molecule on which project /// the key in the CDKRMap of the molecule graph /// an AtomContainer - public static IAtomContainer Project(IList rMapList, IAtomContainer graph, int key) + private static IAtomContainer Project(IReadOnlyList rMapList, IAtomContainer graph, IdType key) { IAtomContainer atomContainer = graph.Builder.NewAtomContainer(); @@ -554,7 +557,7 @@ public static IAtomContainer Project(IList rMapList, IAtomContainer gra foreach (var rMap in rMapList) { - if (key == CDKMCS.Id1) + if (key == CDKMCS.IdType.Id1) { bond = graph.Bonds[rMap.Id1]; } @@ -592,9 +595,9 @@ public static IAtomContainer Project(IList rMapList, IAtomContainer gra /// the molecule on which project /// the key in the CDKRMap of the molecule graph /// atom list of AtomContainer - public static IList ProjectList(IList> rMapsList, IAtomContainer graph, int key) + private static IReadOnlyList ProjectList(IReadOnlyList> rMapsList, IAtomContainer graph, IdType key) { - IList graphList = new List(); + var graphList = new List(); foreach (var rMapList in rMapsList) { @@ -610,9 +613,9 @@ public static IList ProjectList(IList> rMapsList, /// the list of structure to clean /// the list cleaned /// if there is atom problem in obtaining subgraphs - private static IList GetMaximum(IList graphList, bool shouldMatchBonds) + private static IReadOnlyList GetMaximum(IReadOnlyList graphList, bool shouldMatchBonds) { - List reducedGraphList = new List(graphList); + var reducedGraphList = new List(graphList); for (int i = 0; i < graphList.Count; i++) { @@ -670,7 +673,7 @@ public static List CheckSingleAtomCases(IAtomContainer sourceGraph, IAt string atomSymbol = atom.Symbol; for (int i = 0; i < sourceGraph.Atoms.Count; i++) { - if (sourceGraph.Atoms[i].Symbol.Equals(atomSymbol)) + if (sourceGraph.Atoms[i].Symbol.Equals(atomSymbol, StringComparison.Ordinal)) { arrayList.Add(new CDKRMap(i, 0)); } @@ -694,7 +697,7 @@ public static List CheckSingleAtomCases(IAtomContainer sourceGraph, IAt } else { - if (atom2.Symbol.Equals(atom.Symbol)) + if (atom2.Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) { arrayList.Add(new CDKRMap(0, i)); } @@ -715,7 +718,7 @@ public static List CheckSingleAtomCases(IAtomContainer sourceGraph, IAt /// The first atom container. Must not be atom IQueryAtomContainer. /// The second one (first and second as in getMap). May be an QueryAtomContaienr. /// A Vector of Vectors of CDKRMap objects of matching Atoms. - public static IList> MakeAtomsMapsOfBondsMaps(IList> list, IAtomContainer sourceGraph, IAtomContainer targetGraph) + public static IReadOnlyList> MakeAtomsMapsOfBondsMaps(IReadOnlyList> list, IAtomContainer sourceGraph, IAtomContainer targetGraph) { if (list == null) { @@ -725,7 +728,7 @@ public static IList> MakeAtomsMapsOfBondsMaps(IList> result = new List>(); + var result = new List>(); foreach (var l2 in list) { result.Add(MakeAtomsMapOfBondsMap(l2, sourceGraph, targetGraph)); @@ -740,7 +743,7 @@ public static IList> MakeAtomsMapsOfBondsMaps(IListfirst molecule. Must not be an IQueryAtomContainer. /// second molecule. May be an IQueryAtomContainer. /// The mapping found projected on sourceGraph. This is atom List of CDKRMap objects containing Ids of matching atoms. - public static IList MakeAtomsMapOfBondsMap(IList list, IAtomContainer sourceGraph, IAtomContainer targetGraph) + public static IReadOnlyList MakeAtomsMapOfBondsMap(IReadOnlyList list, IAtomContainer sourceGraph, IAtomContainer targetGraph) { if (list == null) { @@ -825,7 +828,7 @@ private static void NodeConstructor(CDKRGraph graph, IAtomContainer ac1, IAtomCo { if (ac1 is IQueryAtomContainer) { - throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); + throw new CDKException($"The first {nameof(IAtomContainer)} must not be an {nameof(IQueryAtomContainer)}"); } // resets the target graph. @@ -948,7 +951,7 @@ private static void ArcConstructor(CDKRGraph graph, IAtomContainer ac1, IAtomCon else { if (bondA1.Equals(bondB1) || bondA2.Equals(bondB2) - || (!GetCommonSymbol(bondA1, bondB1).Equals(GetCommonSymbol(bondA2, bondB2)))) + || (!GetCommonSymbol(bondA1, bondB1).Equals(GetCommonSymbol(bondA2, bondB2), StringComparison.Ordinal))) { rNodeX.Forbidden.Set(j, true); rNodeY.Forbidden.Set(i, true); @@ -1206,35 +1209,35 @@ private static bool TestSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac for (int i = 0; i < ac1.Atoms.Count; i++) { atom = ac1.Atoms[i]; - if (atom.Symbol.Equals("S")) + if (string.Equals(atom.Symbol, "S", StringComparison.Ordinal)) { ac1SCount++; } - else if (atom.Symbol.Equals("N")) + else if (string.Equals(atom.Symbol, "N", StringComparison.Ordinal)) { ac1NCount++; } - else if (atom.Symbol.Equals("O")) + else if (string.Equals(atom.Symbol, "O", StringComparison.Ordinal)) { ac1OCount++; } - else if (atom.Symbol.Equals("F")) + else if (string.Equals(atom.Symbol, "F", StringComparison.Ordinal)) { ac1FCount++; } - else if (atom.Symbol.Equals("Cl")) + else if (string.Equals(atom.Symbol, "Cl", StringComparison.Ordinal)) { ac1ClCount++; } - else if (atom.Symbol.Equals("Br")) + else if (string.Equals(atom.Symbol, "Br", StringComparison.Ordinal)) { ac1BrCount++; } - else if (atom.Symbol.Equals("I")) + else if (string.Equals(atom.Symbol, "I", StringComparison.Ordinal)) { ac1ICount++; } - else if (atom.Symbol.Equals("C")) + else if (string.Equals(atom.Symbol, "C", StringComparison.Ordinal)) { ac1CCount++; } @@ -1246,35 +1249,35 @@ private static bool TestSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac { continue; } - if (atom.Symbol.Equals("S")) + if (string.Equals(atom.Symbol, "S", StringComparison.Ordinal)) { ac2SCount++; } - else if (atom.Symbol.Equals("N")) + else if (string.Equals(atom.Symbol, "N", StringComparison.Ordinal)) { ac2NCount++; } - else if (atom.Symbol.Equals("O")) + else if (string.Equals(atom.Symbol, "O", StringComparison.Ordinal)) { ac2OCount++; } - else if (atom.Symbol.Equals("F")) + else if (string.Equals(atom.Symbol, "F", StringComparison.Ordinal)) { ac2FCount++; } - else if (atom.Symbol.Equals("Cl")) + else if (string.Equals(atom.Symbol, "Cl", StringComparison.Ordinal)) { ac2ClCount++; } - else if (atom.Symbol.Equals("Br")) + else if (string.Equals(atom.Symbol, "Br", StringComparison.Ordinal)) { ac2BrCount++; } - else if (atom.Symbol.Equals("I")) + else if (string.Equals(atom.Symbol, "I", StringComparison.Ordinal)) { ac2ICount++; } - else if (atom.Symbol.Equals("C")) + else if (string.Equals(atom.Symbol, "C", StringComparison.Ordinal)) { ac2CCount++; } @@ -1314,7 +1317,7 @@ private static bool TestSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac /// the timeout [MethodImpl(MethodImplOptions.Synchronized)] - protected static double GetTimeOut() + internal static double GetTimeOut() { return TimeOut.Instance.Time; } diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKMCSHandler.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKMCSHandler.cs similarity index 84% rename from NCDK/SMSD/Algorithms/RGraph/CDKMCSHandler.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKMCSHandler.cs index 5b44a78a..1f4113be 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKMCSHandler.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKMCSHandler.cs @@ -20,6 +20,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Common.Collections; using NCDK.Graphs; using NCDK.Isomorphisms.Matchers; @@ -31,7 +32,7 @@ using System.Linq; using System.Runtime.CompilerServices; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// This class acts as a handler class for algorithm. @@ -45,10 +46,10 @@ public class CDKMCSHandler : AbstractMCSAlgorithm, IMCSBase private IAtomContainer source; private IAtomContainer target; private bool rOnPFlag = false; - private List> allAtomMCS = null; - private IDictionary firstAtomMCS = null; - private IDictionary firstMCS = null; - private List> allMCS = null; + private List> allAtomMCS = null; + private Dictionary firstAtomMCS = null; + private SortedDictionary firstMCS = null; + private List> allMCS = null; //~--- constructors ------------------------------------------------------- /// @@ -56,10 +57,10 @@ public class CDKMCSHandler : AbstractMCSAlgorithm, IMCSBase /// public CDKMCSHandler() { - this.allAtomMCS = new List>(); + this.allAtomMCS = new List>(); this.firstAtomMCS = new Dictionary(); this.firstMCS = new SortedDictionary(); - this.allMCS = new List>(); + this.allMCS = new List>(); } public void Set(MolHandler source, MolHandler target) @@ -104,7 +105,6 @@ public override void SearchMCS(bool shouldMatchBonds) catch (CDKException) { rmap = null; - // Console.Error.WriteLine("WARNING: graphContainer: most probably time out error "); } } @@ -115,7 +115,7 @@ public override void SearchMCS(bool shouldMatchBonds) /// /// IMolecule Set /// - protected IChemObjectSet GetUncommon(IAtomContainer mol, IAtomContainer mcss, bool shouldMatchBonds) + private static IChemObjectSet GetUncommon(IAtomContainer mol, IAtomContainer mcss, bool shouldMatchBonds) { List atomSerialsToDelete = new List(); @@ -152,7 +152,6 @@ protected IChemObjectSet GetUncommon(IAtomContainer mol, IAtomCo private void SetAllMapping() { //int count_final_sol = 1; - //Console.Out.WriteLine("Output of the final FinalMappings: "); try { var sol = FinalMappings.Instance.GetFinalMapping(); @@ -192,12 +191,12 @@ private void SetAllMapping() [MethodImpl(MethodImplOptions.Synchronized)] private void SetAllAtomMapping() { - List> sol = allMCS; + var sol = allMCS; int counter = 0; foreach (var finalSolution in sol) { - IDictionary atomMappings = new Dictionary(); + var atomMappings = new Dictionary(); foreach (var solutions in finalSolution) { int iIndex = solutions.Key; @@ -217,12 +216,12 @@ private void SetAllAtomMapping() [MethodImpl(MethodImplOptions.Synchronized)] private void SetFirstMapping() { - if (allMCS.Count != 0) { - firstMCS = new SortedDictionary(allMCS[0]); + firstMCS = new SortedDictionary(); + foreach (var e in allMCS[0]) + firstMCS.Add(e.Key, e.Value); } - } [MethodImpl(MethodImplOptions.Synchronized)] @@ -230,29 +229,30 @@ private void SetFirstAtomMapping() { if (allAtomMCS.Count != 0) { - firstAtomMCS = new Dictionary(allAtomMCS[0]); + firstAtomMCS = new Dictionary(); + foreach (var e in allAtomMCS[0]) + firstAtomMCS.Add(e.Key, e.Value); } - } - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { - return new ReadOnlyCollection>(allMCS); + return allMCS; } - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { return new ReadOnlyDictionary(firstMCS); } - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { - return new ReadOnlyCollection>(allAtomMCS); + return allAtomMCS; } - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { - return new ReadOnlyDictionary(firstAtomMCS); + return firstAtomMCS; } } } diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKRGraph.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKRGraph.cs similarity index 97% rename from NCDK/SMSD/Algorithms/RGraph/CDKRGraph.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKRGraph.cs index 1e4e3ef8..3296b8c2 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKRGraph.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKRGraph.cs @@ -29,7 +29,7 @@ using System.Collections; using System.Collections.Generic; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// This class implements the Resolution Graph (CDKRGraph). @@ -304,10 +304,10 @@ private void Solution(BitArray traversed) var sol = Solutions[ii]; CheckTimeOut(); - if (!BitArrays.AreEqual(sol, traversed)) + if (!BitArrays.Equals(sol, traversed)) { // if we asked to save all 'mappings' then keep this mapping - if (IsFindAllMap && (BitArrays.AreEqual(projG1, ProjectG1(sol)) || BitArrays.AreEqual(projG2, ProjectG2(sol)))) + if (IsFindAllMap && (BitArrays.Equals(projG1, ProjectG1(sol)) || BitArrays.Equals(projG2, ProjectG2(sol)))) { // do nothing } // if the new solution is included mark maxIterator as included @@ -380,7 +380,7 @@ private bool MustContinue(BitArray potentialNode) break; // if we want every 'mappings' do not stop - if (IsFindAllMap && (BitArrays.AreEqual(projG1, ProjectG1(sol)) || BitArrays.AreEqual(projG2, ProjectG2(sol)))) + if (IsFindAllMap && (BitArrays.Equals(projG1, ProjectG1(sol)) || BitArrays.Equals(projG2, ProjectG2(sol)))) { // do nothing } // if maxIterator is not possible to do better than an already existing solution than stop. @@ -435,7 +435,7 @@ private BitArray BuildB(BitArray sourceBitSet, BitArray targetBitSet) /// the BitArray /// the CDKRMap list /// - public IList BitSetToRMap(BitArray set) + public IReadOnlyList BitSetToRMap(BitArray set) { List rMapList = new List(); @@ -543,7 +543,7 @@ public BitArray ProjectG2(BitArray set) /// a bitSet /// a bitSet /// true if sourceBitSet is contained in targetBitSet - private bool IsContainedIn(BitArray sourceBitSet, BitArray targetBitSet) + private static bool IsContainedIn(BitArray sourceBitSet, BitArray targetBitSet) { bool result = false; @@ -555,7 +555,7 @@ private bool IsContainedIn(BitArray sourceBitSet, BitArray targetBitSet) BitArray setA = (BitArray)sourceBitSet.Clone(); setA.And(targetBitSet); - if (BitArrays.AreEqual(setA, sourceBitSet)) + if (BitArrays.Equals(setA, sourceBitSet)) { result = true; } diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKRMap.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKRMap.cs similarity index 98% rename from NCDK/SMSD/Algorithms/RGraph/CDKRMap.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKRMap.cs index 0c4e9573..ab0b59f5 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKRMap.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKRMap.cs @@ -24,7 +24,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// An CDKRMap implements the association between an edge (bond) in G1 and an edge diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKRMapHandler.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKRMapHandler.cs similarity index 82% rename from NCDK/SMSD/Algorithms/RGraph/CDKRMapHandler.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKRMapHandler.cs index 135e85f5..c6842027 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKRMapHandler.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKRMapHandler.cs @@ -20,13 +20,15 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.SMSD.Helper; using NCDK.Tools.Manipulator; +using System; using System.Collections; using System.Collections.Generic; using System.Linq; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// This algorithm derives from the algorithm described in @@ -49,39 +51,13 @@ public CDKRMapHandler() /// Returns source molecule /// /// the source - public IAtomContainer Source - { - get - { - return source; - } - set - { - source = value; - } - } + public IAtomContainer Source { get; set; } /// /// Returns target molecule /// /// the target - public IAtomContainer Target - { - get - { - return target; - } - - set - { - target = value; - } - } - - private IList> mappings; - private IAtomContainer source; - private IAtomContainer target; - private bool timeoutFlag = false; + public IAtomContainer Target { get; set; } /// /// This function calculates all the possible combinations of MCS @@ -95,7 +71,7 @@ public void CalculateOverlapsAndReduce(IAtomContainer molecule1, IAtomContainer Source = molecule1; Target = molecule2; - Mappings = new List>(); + Mappings = new List>(); if ((Source.Atoms.Count == 1) || (Target.Atoms.Count == 1)) { @@ -112,19 +88,13 @@ public void CalculateOverlapsAndReduce(IAtomContainer molecule1, IAtomContainer } else { - var overlaps = CDKMCS.Search(Source, Target, new BitArray(Source.Bonds.Count), new BitArray(Target.Bonds.Count), true, - true, shouldMatchBonds); - + var overlaps = CDKMCS.Search(Source, Target, new BitArray(Source.Bonds.Count), new BitArray(Target.Bonds.Count), true,true, shouldMatchBonds); var reducedList = RemoveSubGraph(overlaps); var allMaxOverlaps = GetAllMaximum(reducedList); while (allMaxOverlaps.Count != 0) { - // Console.Out.WriteLine("source: " + source.Atoms.Count + ", target: " + target.Atoms.Count + ", overl: " + allMaxOverlaps.Peek().Count); - var maxOverlapsAtoms = MakeAtomsMapOfBondsMap(allMaxOverlaps.Peek(), Source, - Target); - // Console.Out.WriteLine("size of maxOverlaps: " + maxOverlapsAtoms.Count); + var maxOverlapsAtoms = MakeAtomsMapOfBondsMap(allMaxOverlaps.Peek(), Source, Target); IdentifyMatchedParts(maxOverlapsAtoms, Source, Target); - // IdentifyMatchedParts(allMaxOverlaps.Peek(), source, target); allMaxOverlaps.Pop(); } } @@ -146,7 +116,7 @@ public void CalculateOverlapsAndReduceExactMatch(IAtomContainer molecule1, IAtom Source = molecule1; Target = molecule2; - Mappings = new List>(); + Mappings = new List>(); //Console.Out.WriteLine("Searching: "); //List overlaps = UniversalIsomorphismTesterBondTypeInSensitive.GetSubgraphAtomsMap(source, target); @@ -194,7 +164,7 @@ public void CalculateSubGraphs(IAtomContainer molecule1, IAtomContainer molecule Source = molecule1; Target = molecule2; - Mappings = new List>(); + Mappings = new List>(); //Console.Out.WriteLine("Searching: "); //List overlaps = UniversalIsomorphismTesterBondTypeInSensitive.GetSubgraphAtomsMap(source, target); @@ -242,7 +212,7 @@ public void CalculateIsomorphs(IAtomContainer molecule1, IAtomContainer molecule Source = molecule1; Target = molecule2; - Mappings = new List>(); + Mappings = new List>(); //Console.Out.WriteLine("Searching: "); //List overlaps = UniversalIsomorphismTesterBondTypeInSensitive.GetSubgraphAtomsMap(source, target); @@ -275,9 +245,9 @@ public void CalculateIsomorphs(IAtomContainer molecule1, IAtomContainer molecule FinalMappings.Instance.Set(Mappings); } - protected IList> RemoveSubGraph(IList> overlaps) + protected static IReadOnlyList> RemoveSubGraph(IReadOnlyList> overlaps) { - var reducedList = new List>(overlaps); + var reducedList = new List>(overlaps); for (int i = 0; i < overlaps.Count; i++) { @@ -305,7 +275,7 @@ protected IList> RemoveSubGraph(IList> overlaps) return reducedList; } - protected List RemoveRedundantMappingsForSingleAtomCase(List overlaps) + protected static IReadOnlyList RemoveRedundantMappingsForSingleAtomCase(IReadOnlyList overlaps) { List reducedList = new List { @@ -322,14 +292,13 @@ protected List RemoveRedundantMappingsForSingleAtomCase(List o /// first molecule. Must not be an IQueryAtomContainer. /// second molecule. May be an IQueryAtomContainer. /// The mapping found projected on graph1. This is sourceAtom List of CDKRMap objects containing Ids of matching atoms. - private static IList> MakeAtomsMapOfBondsMap(IList rMapList, IAtomContainer graph1, - IAtomContainer graph2) + private static IReadOnlyList> MakeAtomsMapOfBondsMap(IReadOnlyList rMapList, IAtomContainer graph1, IAtomContainer graph2) { if (rMapList == null) { return (null); } - IList> result = null; + IReadOnlyList> result = null; if (rMapList.Count == 1) { result = MakeAtomsMapOfBondsMapSingleBond(rMapList, graph1, graph2); @@ -400,7 +369,7 @@ private static IList> MakeAtomsMapOfBondsMap(IList rMapL } } } - result = new List> + result = new List> { resultLocal }; @@ -416,7 +385,7 @@ private static IList> MakeAtomsMapOfBondsMap(IList rMapL /// first molecule. Must not be an IQueryAtomContainer. /// second molecule. May be an IQueryAtomContainer. /// The mapping found projected on sourceGraph. This is atom List of CDKRMap objects containing Ids of matching atoms. - private static IList> MakeAtomsMapOfBondsMapSingleBond(IList list, IAtomContainer sourceGraph, IAtomContainer targetGraph) + private static IReadOnlyList> MakeAtomsMapOfBondsMapSingleBond(IReadOnlyList list, IAtomContainer sourceGraph, IAtomContainer targetGraph) { if (list == null) { @@ -443,13 +412,11 @@ private static IList> MakeAtomsMapOfBondsMapSingleBond(IList> MakeAtomsMapOfBondsMapSingleBond(IList> MakeAtomsMapOfBondsMapSingleBond(IList> result = new List>(); + var result = new List>(); if (result1.Count == result2.Count) { result.Add(result1); @@ -494,7 +459,7 @@ private static IList> MakeAtomsMapOfBondsMapSingleBond(IList overlaps) + protected static IList GetMaximum(IList overlaps) { IList list = null; int count = 0; @@ -506,37 +471,28 @@ protected IList GetMaximum(IList overlaps) list = arrayList; count = arrayList.Count; } - } return list; } - protected Stack> GetAllMaximum(IList> overlaps) + protected static Stack> GetAllMaximum(IReadOnlyList> overlaps) { - Stack> allMaximumMappings = null; + Stack> allMaximumMappings = null; int count = -1; foreach (var arrayList in overlaps) { - //Console.Out.WriteLine("O size" + sourceAtom.Count); - if (arrayList.Count > count) { - - List list = new List(arrayList); + var list = new List(arrayList); count = arrayList.Count; - - //Console.Out.WriteLine("List size" + list.Count); - - //Collection threadSafeList = Collections.SynchronizedCollection( list ); - allMaximumMappings = new Stack>(); - //allMaximumMappings.Clear(); + allMaximumMappings = new Stack>(); allMaximumMappings.Push(list); } else if (arrayList.Count == count) { - List list = new List(arrayList); + var list = new List(arrayList); count = arrayList.Count; allMaximumMappings.Push(list); } @@ -544,17 +500,17 @@ protected Stack> GetAllMaximum(IList> overlaps) return allMaximumMappings; } - protected void IdentifyMatchedParts(IList> list, IAtomContainer source, IAtomContainer target) + protected void IdentifyMatchedParts(IReadOnlyList> list, IAtomContainer source, IAtomContainer target) { - List array1 = new List(); - List array2 = new List(); + var array1 = new List(); + var array2 = new List(); // We have serial numbers of the bonds/Atoms to delete Now we will // collect the actual bond/Atoms rather than serial number for deletion. // RonP flag check whether reactant is mapped on product or Vise Versa foreach (var rMap in list) { - IDictionary atomNumbersFromContainer = new SortedDictionary(); + var atomNumbersFromContainer = new SortedDictionary(); foreach (var rmap in rMap) { IAtom sourceAtom = source.Atoms[rmap.Id1]; @@ -568,7 +524,7 @@ protected void IdentifyMatchedParts(IList> list, IAtomContainer s atomNumbersFromContainer[indexI] = indexJ; } - + // Added the Mapping Numbers to the FinalMapping* Mappings.Add(atomNumbersFromContainer); } @@ -587,8 +543,6 @@ protected void IdentifySingleAtomsMatchedParts(List list, IAtomContaine foreach (var rmap in list) { - //System.err.Print("Map " + o.GetType()); - IAtom sAtom = source.Atoms[rmap.Id1]; IAtom tAtom = target.Atoms[rmap.Id2]; @@ -605,10 +559,9 @@ protected void IdentifySingleAtomsMatchedParts(List list, IAtomContaine } } - protected bool IsSubgraph(IList rmaps1, IList rmaps2) + protected static bool IsSubgraph(IReadOnlyList rmaps1, IReadOnlyList rmaps2) { - //Console.Out.WriteLine("Entering isSubgraph."); - List rmaps2clone = new List(rmaps2); + var rmaps2clone = new List(rmaps2); foreach (var rmap1 in rmaps1) { bool found = false; @@ -630,7 +583,7 @@ protected bool IsSubgraph(IList rmaps1, IList rmaps2) return true; } - protected bool IsSameRMap(CDKRMap sourceRMap, CDKRMap targetRMap) + protected static bool IsSameRMap(CDKRMap sourceRMap, CDKRMap targetRMap) { return sourceRMap.Id1 == targetRMap.Id1 && sourceRMap.Id2 == targetRMap.Id2 ? true : false; } @@ -638,32 +591,12 @@ protected bool IsSameRMap(CDKRMap sourceRMap, CDKRMap targetRMap) /// /// mapping solutions /// - public IList> Mappings - { - get - { - return mappings; - } - set - { - this.mappings = value; - } - } + public IList> Mappings { get; internal set; } /// /// true if a time out occurred else false /// - public bool IsTimedOut - { - get - { - return timeoutFlag; - } - set - { - this.timeoutFlag = value; - } - } + public bool IsTimedOut { get; set; } = false; } } diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKRNode.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKRNode.cs similarity index 83% rename from NCDK/SMSD/Algorithms/RGraph/CDKRNode.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKRNode.cs index 14f9db75..d9d463f9 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKRNode.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKRNode.cs @@ -27,7 +27,7 @@ using NCDK.Common.Collections; using System.Collections; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// Node of the resolution graphe (RGraph) An CDKRNode represents an association @@ -44,18 +44,14 @@ namespace NCDK.SMSD.Algorithms.RGraph // @cdk.githash public class CDKRNode { - // G1/G2 mapping - - private CDKRMap rMap = null; - /// /// Constructor for the RNode object /// - /// number of the bond in the graphe 1 - /// number of the bond in the graphe 2 + /// number of the bond in the graph 1 + /// number of the bond in the graph 2 public CDKRNode(int id1, int id2) { - rMap = new CDKRMap(id1, id2); + RMap = new CDKRMap(id1, id2); // Initialization of Extension and Forbidden is removed // Caller must do it. } @@ -63,12 +59,12 @@ public CDKRNode(int id1, int id2) /// /// the extension attribute of the RNode object /// - public BitArray Extension { get; set; } + public BitArray Extension { get; internal set; } /// /// the forbidden attribute of the RNode object /// - public BitArray Forbidden { get; set; } + public BitArray Forbidden { get; internal set; } /// /// Returns a string representation of the RNode @@ -83,16 +79,6 @@ public override string ToString() /// /// resolution map/graph /// - public CDKRMap RMap - { - get - { - return rMap; - } - set - { - this.rMap = value; - } - } + public CDKRMap RMap { get; set; } = null; } } diff --git a/NCDK/SMSD/Algorithms/RGraph/CDKSubGraphHandler.cs b/NCDK/SMSD/Algorithms/RGraphs/CDKSubGraphHandler.cs similarity index 84% rename from NCDK/SMSD/Algorithms/RGraph/CDKSubGraphHandler.cs rename to NCDK/SMSD/Algorithms/RGraphs/CDKSubGraphHandler.cs index ff91e9ce..a175133b 100644 --- a/NCDK/SMSD/Algorithms/RGraph/CDKSubGraphHandler.cs +++ b/NCDK/SMSD/Algorithms/RGraphs/CDKSubGraphHandler.cs @@ -29,7 +29,7 @@ using System.Collections.ObjectModel; using System.Runtime.CompilerServices; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// This class acts as a handler class for algorithm. @@ -43,10 +43,10 @@ public class CDKSubGraphHandler : AbstractSubGraph, IMCSBase private IAtomContainer source; private IAtomContainer target; private bool rOnPFlag = false; - private List> allAtomMCS = null; - private IDictionary firstAtomMCS = null; - private IDictionary firstMCS = null; - private List> allMCS = null; + private List> allAtomMCS = null; + private Dictionary firstAtomMCS = null; + private SortedDictionary firstMCS = null; + private List> allMCS = null; //~--- constructors ------------------------------------------------------- /// @@ -54,10 +54,10 @@ public class CDKSubGraphHandler : AbstractSubGraph, IMCSBase /// public CDKSubGraphHandler() { - this.allAtomMCS = new List>(); + this.allAtomMCS = new List>(); this.firstAtomMCS = new Dictionary(); this.firstMCS = new SortedDictionary(); - this.allMCS = new List>(); + this.allMCS = new List>(); } public void Set(MolHandler source, MolHandler target) @@ -110,7 +110,7 @@ public override bool IsSubgraph(bool shouldMatchBonds) return GetFirstMapping().Count != 0; } - protected IChemObjectSet GetUncommon(IAtomContainer mol, IAtomContainer mcss, bool shouldMatchBonds) + private static IChemObjectSet GetUncommon(IAtomContainer mol, IAtomContainer mcss, bool shouldMatchBonds) { List atomSerialsToDelete = new List(); @@ -185,12 +185,12 @@ private void SetAllMapping() [MethodImpl(MethodImplOptions.Synchronized)] private void SetAllAtomMapping() { - List> sol = allMCS; + var sol = allMCS; int counter = 0; foreach (var finalSolution in sol) { - IDictionary atomMappings = new Dictionary(); + var atomMappings = new Dictionary(); foreach (var solutions in finalSolution) { int iIndex = solutions.Key; @@ -213,7 +213,9 @@ private void SetFirstMapping() { if (allMCS.Count != 0) { - firstMCS = new SortedDictionary(allMCS[0]); + firstMCS = new SortedDictionary(); + foreach (var e in allMCS[0]) + firstMCS.Add(e.Key, e.Value); } } @@ -222,28 +224,30 @@ private void SetFirstAtomMapping() { if (allAtomMCS.Count != 0) { - firstAtomMCS = new Dictionary(allAtomMCS[0]); + firstAtomMCS = new Dictionary(); + foreach (var e in allAtomMCS[0]) + firstAtomMCS.Add(e.Key, e.Value); } } - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { - return new ReadOnlyCollection>(allMCS); + return allMCS; } - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { - return new ReadOnlyDictionary(firstMCS); + return firstMCS; } - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { - return new ReadOnlyCollection>(allAtomMCS); + return allAtomMCS; } - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { - return new ReadOnlyDictionary(firstAtomMCS); + return firstAtomMCS; } } } diff --git a/NCDK/SMSD/Algorithms/Single/SingleMapping.cs b/NCDK/SMSD/Algorithms/Singles/SingleMapping.cs similarity index 83% rename from NCDK/SMSD/Algorithms/Single/SingleMapping.cs rename to NCDK/SMSD/Algorithms/Singles/SingleMapping.cs index 338f4ef6..f1c68211 100644 --- a/NCDK/SMSD/Algorithms/Single/SingleMapping.cs +++ b/NCDK/SMSD/Algorithms/Singles/SingleMapping.cs @@ -20,12 +20,13 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Isomorphisms.Matchers; using NCDK.SMSD.Tools; using System; using System.Collections.Generic; -namespace NCDK.SMSD.Algorithms.Single +namespace NCDK.SMSD.Algorithms.Singles { /// /// This class handles single atom mapping. @@ -39,7 +40,7 @@ public class SingleMapping { private IAtomContainer source = null; private IAtomContainer target = null; - private List> mappings = null; + private List> mappings = null; private IDictionary connectedBondOrder = null; /// @@ -52,9 +53,9 @@ public SingleMapping() { } /// /// Mappings /// - protected internal IList> GetOverLaps(IAtomContainer source, IAtomContainer target, bool removeHydrogen) + protected internal IReadOnlyList> GetOverLaps(IAtomContainer source, IAtomContainer target, bool removeHydrogen) { - mappings = new List>(); + mappings = new List>(); connectedBondOrder = new SortedDictionary(); this.source = source; this.target = target; @@ -76,9 +77,9 @@ protected internal IList> GetOverLaps(IAtomContainer s /// Returns single mapping solutions. /// /// - protected internal IList> GetOverLaps(IQueryAtomContainer source, IAtomContainer target, bool removeHydrogen) + protected internal IReadOnlyList> GetOverLaps(IQueryAtomContainer source, IAtomContainer target, bool removeHydrogen) { - mappings = new List>(); + mappings = new List>(); connectedBondOrder = new SortedDictionary(); this.source = source; this.target = target; @@ -102,12 +103,12 @@ private void SetSourceSingleAtomMap(IQueryAtomContainer source, bool removeHydro BondEnergies be = BondEnergies.Instance; foreach (var sourceAtom in source.Atoms) { - IQueryAtom smartAtom = (IQueryAtom)sourceAtom; - if ((removeHydrogen && !smartAtom.Symbol.Equals("H")) || (!removeHydrogen)) + var smartAtom = (IQueryAtom)sourceAtom; + if ((removeHydrogen && !smartAtom.Symbol.Equals("H", StringComparison.Ordinal)) || (!removeHydrogen)) { foreach (var targetAtom in target.Atoms) { - IDictionary mapAtoms = new Dictionary(); + var mapAtoms = new Dictionary(); if (smartAtom.Matches(targetAtom)) { mapAtoms[sourceAtom] = targetAtom; @@ -117,7 +118,7 @@ private void SetSourceSingleAtomMap(IQueryAtomContainer source, bool removeHydro foreach (var bond in bonds) { BondOrder order = bond.Order; - totalOrder += order.Numeric() + be.GetEnergies(bond); + totalOrder += order.Numeric() + BondEnergies.GetEnergies(bond); } if (targetAtom.FormalCharge != sourceAtom.FormalCharge) { @@ -130,7 +131,7 @@ private void SetSourceSingleAtomMap(IQueryAtomContainer source, bool removeHydro } else { - Console.Error.WriteLine("Skippping Hydrogen mapping or This is not a single mapping case!"); + Console.Error.WriteLine("Skipping Hydrogen mapping or This is not a single mapping case!"); } } } @@ -141,11 +142,11 @@ private void SetSourceSingleAtomMap(bool removeHydrogen) BondEnergies be = BondEnergies.Instance; foreach (var sourceAtom in source.Atoms) { - if ((removeHydrogen && !sourceAtom.Symbol.Equals("H")) || (!removeHydrogen)) + if ((removeHydrogen && !sourceAtom.Symbol.Equals("H", StringComparison.Ordinal)) || (!removeHydrogen)) { foreach (var targetAtom in target.Atoms) { - IDictionary mapAtoms = new Dictionary(); + var mapAtoms = new Dictionary(); if (string.Equals(sourceAtom.Symbol, targetAtom.Symbol, StringComparison.OrdinalIgnoreCase)) { mapAtoms[sourceAtom] = targetAtom; @@ -155,7 +156,7 @@ private void SetSourceSingleAtomMap(bool removeHydrogen) foreach (var bond in bonds) { BondOrder order = bond.Order; - totalOrder += order.Numeric() + be.GetEnergies(bond); + totalOrder += order.Numeric() + BondEnergies.GetEnergies(bond); } if (targetAtom.FormalCharge != sourceAtom.FormalCharge) { @@ -168,7 +169,7 @@ private void SetSourceSingleAtomMap(bool removeHydrogen) } else { - Console.Error.WriteLine("Skippping Hydrogen mapping or This is not a single mapping case!"); + Console.Error.WriteLine("Skipping Hydrogen mapping or This is not a single mapping case!"); } } } @@ -179,11 +180,11 @@ private void SetTargetSingleAtomMap(bool removeHydrogen) BondEnergies be = BondEnergies.Instance; foreach (var targetAtom in target.Atoms) { - if ((removeHydrogen && !targetAtom.Symbol.Equals("H")) || (!removeHydrogen)) + if ((removeHydrogen && !targetAtom.Symbol.Equals("H", StringComparison.Ordinal)) || (!removeHydrogen)) { foreach (var sourceAtoms in source.Atoms) { - IDictionary mapAtoms = new Dictionary(); + var mapAtoms = new Dictionary(); if (string.Equals(targetAtom.Symbol, sourceAtoms.Symbol, StringComparison.OrdinalIgnoreCase)) { @@ -194,7 +195,7 @@ private void SetTargetSingleAtomMap(bool removeHydrogen) foreach (var bond in bonds) { BondOrder order = bond.Order; - totalOrder += order.Numeric() + be.GetEnergies(bond); + totalOrder += order.Numeric() + BondEnergies.GetEnergies(bond); } if (sourceAtoms.FormalCharge != targetAtom.FormalCharge) { @@ -207,23 +208,23 @@ private void SetTargetSingleAtomMap(bool removeHydrogen) } else { - Console.Error.WriteLine("Skippping Hydrogen mapping or This is not a single mapping case!"); + Console.Error.WriteLine("Skipping Hydrogen mapping or This is not a single mapping case!"); } } } private void PostFilter() { - List> sortedMap = new List>(); + var sortedMap = new List>(); foreach (var entry in SortByValue(connectedBondOrder)) { - IDictionary mapToBeMoved = mappings[entry.Key]; + var mapToBeMoved = mappings[entry.Key]; sortedMap.Add(mapToBeMoved); } mappings = sortedMap; } - private IList> SortByValue(IDictionary map) + private static List> SortByValue(IDictionary map) { var list = new List>(); foreach (var entry in map) @@ -236,4 +237,3 @@ private IList> SortByValue(IDictionary ma } } } - diff --git a/NCDK/SMSD/Algorithms/Single/SingleMappingHandler.cs b/NCDK/SMSD/Algorithms/Singles/SingleMappingHandler.cs similarity index 74% rename from NCDK/SMSD/Algorithms/Single/SingleMappingHandler.cs rename to NCDK/SMSD/Algorithms/Singles/SingleMappingHandler.cs index 76ba193b..e28f7c88 100644 --- a/NCDK/SMSD/Algorithms/Single/SingleMappingHandler.cs +++ b/NCDK/SMSD/Algorithms/Singles/SingleMappingHandler.cs @@ -20,16 +20,16 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Isomorphisms.Matchers; using NCDK.SMSD.Tools; using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; -namespace NCDK.SMSD.Algorithms.Single +namespace NCDK.SMSD.Algorithms.Singles { /// /// This is a handler class for single atom mapping . @@ -40,22 +40,22 @@ namespace NCDK.SMSD.Algorithms.Single [Obsolete("This class is part of SMSD and either duplicates functionality elsewhere in the CDK or provides public access to internal implementation details. SMSD has been deprecated from the CDK and a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] public class SingleMappingHandler : AbstractMCSAlgorithm, IMCSBase { - private static List> allAtomMCS = null; - private static IDictionary atomsMCS = null; - private static IDictionary firstMCS = null; - private static List> allMCS = null; + private static List> allAtomMCS = null; + private static Dictionary atomsMCS = null; + private static SortedDictionary firstMCS = null; + private static List> allMCS = null; private IAtomContainer source = null; private IQueryAtomContainer smartSource = null; private IAtomContainer target = null; - private bool removeHydrogen = false; + private readonly bool removeHydrogen = false; public SingleMappingHandler(bool removeH) { this.removeHydrogen = removeH; - allAtomMCS = new List>(); + allAtomMCS = new List>(); atomsMCS = new Dictionary(); firstMCS = new SortedDictionary(); - allMCS = new List>(); + allMCS = new List>(); } public void Set(MolHandler source, MolHandler target) @@ -76,7 +76,7 @@ public void Set(IQueryAtomContainer source, IAtomContainer target) public override void SearchMCS(bool bondTypeMatch) { SingleMapping singleMapping = new SingleMapping(); - IList> mappings = null; + IReadOnlyList> mappings = null; try { if (this.smartSource == null) @@ -100,14 +100,14 @@ public override void SearchMCS(bool bondTypeMatch) //SetStereoScore(); } - private void SetAllMapping(IList> mappings) + private void SetAllMapping(IReadOnlyList> mappings) { try { int counter = 0; foreach (var solution in mappings) { - IDictionary atomMappings = new SortedDictionary(); + var atomMappings = new SortedDictionary(); foreach (var map in solution) { IAtom sourceAtom = map.Key; @@ -124,14 +124,14 @@ private void SetAllMapping(IList> mappings) } [MethodImpl(MethodImplOptions.Synchronized)] - private void SetAllAtomMapping(IList> mappings) + private static void SetAllAtomMapping(IReadOnlyList> mappings) { try { int counter = 0; foreach (var solution in mappings) { - IDictionary atomMappings = new Dictionary(); + var atomMappings = new Dictionary(); foreach (var map in solution) { IAtom sourceAtom = map.Key; @@ -148,41 +148,45 @@ private void SetAllAtomMapping(IList> mappings) } [MethodImpl(MethodImplOptions.Synchronized)] - private void SetFirstMapping() + private static void SetFirstMapping() { if (allMCS.Count > 0) { - firstMCS = new SortedDictionary(allMCS.First()); + firstMCS = new SortedDictionary(); + foreach (var e in allMCS.First()) + firstMCS.Add(e.Key, e.Value); } } [MethodImpl(MethodImplOptions.Synchronized)] - private void SetFirstAtomMapping() + private static void SetFirstAtomMapping() { if (allAtomMCS.Count > 0) { - atomsMCS = new Dictionary(allAtomMCS.First()); + atomsMCS = new Dictionary(); + foreach (var e in allAtomMCS.First()) + atomsMCS.Add(e.Key, e.Value); } } - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { - return new ReadOnlyCollection>(allMCS); + return allMCS; } - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { - return new ReadOnlyDictionary(firstMCS); + return firstMCS; } - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { - return new ReadOnlyCollection>(allAtomMCS); + return allAtomMCS; } - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { - return new ReadOnlyDictionary(atomsMCS); + return atomsMCS; } } } diff --git a/NCDK/SMSD/Algorithms/VFLib/Builder/NodeBuilder.cs b/NCDK/SMSD/Algorithms/VFLib/Builder/NodeBuilder.cs index 495c2297..73128136 100644 --- a/NCDK/SMSD/Algorithms/VFLib/Builder/NodeBuilder.cs +++ b/NCDK/SMSD/Algorithms/VFLib/Builder/NodeBuilder.cs @@ -39,7 +39,6 @@ public class NodeBuilder : INode { private List neighborsList; private List edgesList; - private IVFAtomMatcher matcher; /// /// Construct a node for a query atom @@ -49,19 +48,19 @@ protected internal NodeBuilder(IVFAtomMatcher matcher) { edgesList = new List(); neighborsList = new List(); - this.matcher = matcher; + this.AtomMatcher = matcher; } public int CountNeighbors() => neighborsList.Count; public IEnumerable Neighbors() { - return new ReadOnlyCollection(neighborsList); + return neighborsList; } - public IVFAtomMatcher AtomMatcher => matcher; + public IVFAtomMatcher AtomMatcher { get; } - public IList GetEdges() => new ReadOnlyCollection(edgesList); + public IReadOnlyList GetEdges() => edgesList; public void AddEdge(EdgeBuilder edge) { diff --git a/NCDK/SMSD/Algorithms/VFLib/Builder/TargetProperties.cs b/NCDK/SMSD/Algorithms/VFLib/Builder/TargetProperties.cs index d0c236d5..2ceaa3e4 100644 --- a/NCDK/SMSD/Algorithms/VFLib/Builder/TargetProperties.cs +++ b/NCDK/SMSD/Algorithms/VFLib/Builder/TargetProperties.cs @@ -35,47 +35,34 @@ namespace NCDK.SMSD.Algorithms.VFLib.Builder // @cdk.githash // @author Syed Asad Rahman [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] - [Serializable] public class TargetProperties { - private IDictionary connectedTargetAtomCountMap = null; - private IDictionary> connectedTargetAtomListMap = null; - private IBond[][] map = null; - private IDictionary atoms = null; - private IDictionary atomsIndex = null; + private Dictionary connectedTargetAtomCountMap = null; + private readonly Dictionary> connectedTargetAtomListMap = null; + private readonly IBond[][] map = null; + private Dictionary atoms = null; + private readonly Dictionary atomsIndex = null; - /// - /// - /// the connectedTargetAtomCountMap public int CountNeighbors(IAtom atom) { if (connectedTargetAtomCountMap == null || !connectedTargetAtomCountMap.ContainsKey(atom)) { - Console.Out.WriteLine("Object not found in " + atoms.Count + " atoms"); + Console.Out.WriteLine($"Object not found in {atoms.Count} atoms"); return 0; } return connectedTargetAtomCountMap[atom]; } - /// - /// - /// the connected Target Atom List - public IList GetNeighbors(IAtom atom) + public IReadOnlyList GetNeighbors(IAtom atom) { return connectedTargetAtomListMap[atom]; } - /// - /// - /// the map public IBond GetBond(IAtom atom1, IAtom atom2) { return map[atoms[atom2]][atoms[atom1]]; } - /// - /// atom count - /// public int AtomCount => atoms.Count; public TargetProperties(IAtomContainer container) @@ -84,7 +71,7 @@ public TargetProperties(IAtomContainer container) atoms = new Dictionary(); atomsIndex = new Dictionary(); connectedTargetAtomCountMap = new Dictionary(); - connectedTargetAtomListMap = new Dictionary>(); + connectedTargetAtomListMap = new Dictionary>(); map = Arrays.CreateJagged(container.Atoms.Count, container.Atoms.Count); foreach (var atom in container.Atoms) { diff --git a/NCDK/SMSD/Algorithms/VFLib/IMapper.cs b/NCDK/SMSD/Algorithms/VFLib/IMapper.cs index cc1d97c0..25e7834c 100644 --- a/NCDK/SMSD/Algorithms/VFLib/IMapper.cs +++ b/NCDK/SMSD/Algorithms/VFLib/IMapper.cs @@ -78,14 +78,14 @@ public interface IMapper /// /// molecule. /// get maps. - IList> GetMaps(IAtomContainer target); + IReadOnlyList> GetMaps(IAtomContainer target); /// /// Returns first solution map. /// /// molecule. /// get first map. - IDictionary GetFirstMap(IAtomContainer target); + IReadOnlyDictionary GetFirstMap(IAtomContainer target); /// /// checks if a map exits for a molecule. @@ -106,14 +106,14 @@ public interface IMapper /// /// molecule. /// get maps. - IList> GetMaps(TargetProperties target); + IReadOnlyList> GetMaps(TargetProperties target); /// /// Returns first solution map. /// /// molecule. /// get first map. - IDictionary GetFirstMap(TargetProperties target); + IReadOnlyDictionary GetFirstMap(TargetProperties target); } } diff --git a/NCDK/SMSD/Algorithms/VFLib/INode.cs b/NCDK/SMSD/Algorithms/VFLib/INode.cs index 5d32543e..64ce6d3f 100644 --- a/NCDK/SMSD/Algorithms/VFLib/INode.cs +++ b/NCDK/SMSD/Algorithms/VFLib/INode.cs @@ -83,7 +83,7 @@ public interface INode /// Returns List of Edges. /// edges. /// - IList GetEdges(); + IReadOnlyList GetEdges(); /// /// Adds edge to the edge list. diff --git a/NCDK/SMSD/Algorithms/VFLib/IState.cs b/NCDK/SMSD/Algorithms/VFLib/IState.cs index 1923b8b6..80e5fac0 100644 --- a/NCDK/SMSD/Algorithms/VFLib/IState.cs +++ b/NCDK/SMSD/Algorithms/VFLib/IState.cs @@ -65,7 +65,7 @@ public interface IState /// This map is shared among all states obtained through nextState. /// /// the current mapping of query atoms onto target atoms - IDictionary GetMap(); + IReadOnlyDictionary GetMap(); /// /// Returns true if another candidate match can be found or diff --git a/NCDK/SMSD/Algorithms/VFLib/Map/VFMCSMapper.cs b/NCDK/SMSD/Algorithms/VFLib/Map/VFMCSMapper.cs index 3dac4324..bbe1c622 100644 --- a/NCDK/SMSD/Algorithms/VFLib/Map/VFMCSMapper.cs +++ b/NCDK/SMSD/Algorithms/VFLib/Map/VFMCSMapper.cs @@ -50,7 +50,7 @@ using NCDK.SMSD.Algorithms.VFLib.Builder; using NCDK.SMSD.Algorithms.VFLib.Query; -using NCDK.SMSD.Global; +using NCDK.SMSD.Globals; using NCDK.SMSD.Tools; using System; using System.Collections.Generic; @@ -68,8 +68,8 @@ namespace NCDK.SMSD.Algorithms.VFLib.Map [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] public class VFMCSMapper : IMapper { - private IQuery query = null; - private List> maps = null; + private readonly IQuery query = null; + private List> maps = null; private int currentMCSSize = -1; private static TimeManager timeManager = null; @@ -98,14 +98,14 @@ public VFMCSMapper(IQuery query) { TimeManager = new TimeManager(); this.query = query; - this.maps = new List>(); + this.maps = new List>(); } public VFMCSMapper(IAtomContainer queryMolecule, bool bondMatcher) { TimeManager = new TimeManager(); this.query = new QueryCompiler(queryMolecule, bondMatcher).Compile(); - this.maps = new List>(); + this.maps = new List>(); } /// @@ -116,15 +116,15 @@ public bool HasMap(IAtomContainer targetMolecule) return MapFirst(state); } - public IList> GetMaps(IAtomContainer target) + public IReadOnlyList> GetMaps(IAtomContainer target) { IState state = new VFState(query, new TargetProperties(target)); maps.Clear(); MapAll(state); - return new List>(maps); + return maps; } - public IDictionary GetFirstMap(IAtomContainer target) + public IReadOnlyDictionary GetFirstMap(IAtomContainer target) { IState state = new VFState(query, new TargetProperties(target)); maps.Clear(); @@ -148,15 +148,15 @@ public bool HasMap(TargetProperties targetMolecule) return MapFirst(state); } - public IList> GetMaps(TargetProperties targetMolecule) + public IReadOnlyList> GetMaps(TargetProperties targetMolecule) { IState state = new VFState(query, targetMolecule); maps.Clear(); MapAll(state); - return new List>(maps); + return maps; } - public IDictionary GetFirstMap(TargetProperties targetMolecule) + public IReadOnlyDictionary GetFirstMap(TargetProperties targetMolecule) { IState state = new VFState(query, targetMolecule); maps.Clear(); @@ -174,7 +174,7 @@ public int CountMaps(TargetProperties targetMolecule) private void AddMapping(IState state) { - IDictionary map = state.GetMap(); + var map = state.GetMap(); if (!HasMap(map) && map.Count > currentMCSSize) { maps.Add(map); @@ -195,7 +195,7 @@ private void MapAll(IState state) if (state.IsGoal) { - IDictionary map = state.GetMap(); + var map = state.GetMap(); if (!HasMap(map)) { maps.Add(state.GetMap()); @@ -249,7 +249,7 @@ private bool MapFirst(IState state) return found; } - private bool HasMap(IDictionary map) + private bool HasMap(IReadOnlyDictionary map) { foreach (var storedMap in maps) { diff --git a/NCDK/SMSD/Algorithms/VFLib/Map/VFMapper.cs b/NCDK/SMSD/Algorithms/VFLib/Map/VFMapper.cs index de377de1..674d799c 100644 --- a/NCDK/SMSD/Algorithms/VFLib/Map/VFMapper.cs +++ b/NCDK/SMSD/Algorithms/VFLib/Map/VFMapper.cs @@ -44,11 +44,11 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ + using NCDK.SMSD.Algorithms.VFLib.Builder; using NCDK.SMSD.Algorithms.VFLib.Query; -using NCDK.SMSD.Global; +using NCDK.SMSD.Globals; using NCDK.SMSD.Tools; using System; using System.Collections.Generic; @@ -66,8 +66,8 @@ namespace NCDK.SMSD.Algorithms.VFLib.Map [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] public class VFMapper : IMapper { - private IQuery query; - private List> maps; + private readonly IQuery query; + private List> maps; private int currentMCSSize = -1; private static TimeManager timeManager = null; @@ -100,14 +100,14 @@ public VFMapper(IQuery query) { SetTimeManager(new TimeManager()); this.query = query; - this.maps = new List>(); + this.maps = new List>(); } public VFMapper(IAtomContainer queryMolecule, bool bondMatcher) { SetTimeManager(new TimeManager()); this.query = new QueryCompiler(queryMolecule, bondMatcher).Compile(); - this.maps = new List>(); + this.maps = new List>(); } /// @@ -119,15 +119,15 @@ public bool HasMap(IAtomContainer targetMolecule) return MapFirst(state); } - public IList> GetMaps(IAtomContainer target) + public IReadOnlyList> GetMaps(IAtomContainer target) { IState state = new VFState(query, new TargetProperties(target)); maps.Clear(); MapAll(state); - return new List>(maps); + return new List>(maps); } - public IDictionary GetFirstMap(IAtomContainer target) + public IReadOnlyDictionary GetFirstMap(IAtomContainer target) { IState state = new VFState(query, new TargetProperties(target)); maps.Clear(); @@ -152,15 +152,15 @@ public bool HasMap(TargetProperties targetMolecule) return MapFirst(state); } - public IList> GetMaps(TargetProperties targetMolecule) + public IReadOnlyList> GetMaps(TargetProperties targetMolecule) { IState state = new VFState(query, targetMolecule); maps.Clear(); MapAll(state); - return new List>(maps); + return new List>(maps); } - public IDictionary GetFirstMap(TargetProperties targetMolecule) + public IReadOnlyDictionary GetFirstMap(TargetProperties targetMolecule) { IState state = new VFState(query, targetMolecule); maps.Clear(); @@ -178,7 +178,7 @@ public int CountMaps(TargetProperties targetMolecule) private void AddMapping(IState state) { - IDictionary map = state.GetMap(); + var map = state.GetMap(); if (!HasMap(map) && map.Count > currentMCSSize) { maps.Add(map); @@ -204,7 +204,7 @@ private void MapAll(IState state) if (state.IsGoal) { - IDictionary map = state.GetMap(); + var map = state.GetMap(); if (!HasMap(map)) { maps.Add(state.GetMap()); @@ -254,7 +254,7 @@ private bool MapFirst(IState state) return found; } - private bool HasMap(IDictionary map) + private bool HasMap(IReadOnlyDictionary map) { foreach (var storedMap in maps) { diff --git a/NCDK/SMSD/Algorithms/VFLib/Map/VFState.cs b/NCDK/SMSD/Algorithms/VFLib/Map/VFState.cs index b3d6f74d..7d0261e0 100644 --- a/NCDK/SMSD/Algorithms/VFLib/Map/VFState.cs +++ b/NCDK/SMSD/Algorithms/VFLib/Map/VFState.cs @@ -1,6 +1,4 @@ /* - * - * * Copyright (C) 2009-2010 Syed Asad Rahman * * Contact: cdk-devel@lists.sourceforge.net @@ -46,8 +44,8 @@ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. - * */ + using NCDK.SMSD.Algorithms.VFLib.Builder; using System; using System.Collections.Generic; @@ -69,7 +67,7 @@ public class VFState : IState private TargetProperties target; private List queryPath; private List targetPath; - private IDictionary map; + private Dictionary map; /// /// Initialise the VFState with query and target @@ -84,6 +82,8 @@ public VFState(IQuery query, TargetProperties target) this.target = target; this.candidates = new List(); LoadRootCandidates(); + + Console.WriteLine(map.Count); } private VFState(VFState state, Match match) @@ -98,6 +98,7 @@ private VFState(VFState state, Match match) map[match.QueryNode] = match.TargetAtom; queryPath.Add(match.QueryNode); + targetPath.Add(match.TargetAtom); LoadCandidates(match); } @@ -120,7 +121,7 @@ public void BackTrack() } } - public IDictionary GetMap() + public IReadOnlyDictionary GetMap() { return new Dictionary(map); } @@ -132,11 +133,17 @@ public bool HasNextCandidate() public bool IsDead => query.CountNodes() > target.AtomCount; - public bool IsGoal => map.Count == query.CountNodes(); + public bool IsGoal + { + get + { + return map.Count == query.CountNodes(); + } + } public bool IsMatchFeasible(Match match) { - if (map.ContainsKey(match.QueryNode) || map.Values.Contains(match.TargetAtom)) + if (map.ContainsKey(match.QueryNode) || map.ContainsValue(match.TargetAtom)) { return false; } diff --git a/NCDK/SMSD/Algorithms/VFLib/Query/QueryCompiler.cs b/NCDK/SMSD/Algorithms/VFLib/Query/QueryCompiler.cs index af58a840..55e9a5d8 100644 --- a/NCDK/SMSD/Algorithms/VFLib/Query/QueryCompiler.cs +++ b/NCDK/SMSD/Algorithms/VFLib/Query/QueryCompiler.cs @@ -129,7 +129,7 @@ private IQuery Build(IAtomContainer queryMolecule) return result; } - private IQuery Build(IQueryAtomContainer queryMolecule) + private static IQuery Build(IQueryAtomContainer queryMolecule) { VFQueryBuilder result = new VFQueryBuilder(); foreach (var atoms in queryMolecule.Atoms) @@ -161,12 +161,12 @@ private IVFBondMatcher CreateBondMatcher(IAtomContainer mol, IBond bond) return new DefaultVFBondMatcher(mol, bond, IsBondMatchFlag); } - private IVFAtomMatcher CreateAtomMatcher(IQueryAtom atom, IQueryAtomContainer container) + private static IVFAtomMatcher CreateAtomMatcher(IQueryAtom atom, IQueryAtomContainer container) { return new DefaultVFAtomMatcher(atom, container); } - private IVFBondMatcher CreateBondMatcher(IQueryBond bond) + private static IVFBondMatcher CreateBondMatcher(IQueryBond bond) { return new DefaultVFBondMatcher(bond); } diff --git a/NCDK/SMSD/Algorithms/VFLib/VFlibMCSHandler.cs b/NCDK/SMSD/Algorithms/VFLib/VFlibMCSHandler.cs index e469b9f5..11d63e14 100644 --- a/NCDK/SMSD/Algorithms/VFLib/VFlibMCSHandler.cs +++ b/NCDK/SMSD/Algorithms/VFLib/VFlibMCSHandler.cs @@ -52,13 +52,13 @@ namespace NCDK.SMSD.Algorithms.VFLib [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] public class VFlibMCSHandler : AbstractMCSAlgorithm, IMCSBase { - private static List> allAtomMCS = null; - private static IDictionary atomsMCS = null; - private static List> allAtomMCSCopy = null; - private static IDictionary firstMCS = null; - private static List> allMCS = null; - private static List> allMCSCopy = null; - private List> vfLibSolutions = null; + private static List> allAtomMCS = null; + private static Dictionary atomsMCS = null; + private static List> allAtomMCSCopy = null; + private static SortedDictionary firstMCS = null; + private static List> allMCS = null; + private static List> allMCSCopy = null; + private List> vfLibSolutions = null; private IQueryAtomContainer queryMol = null; private IAtomContainer mol1 = null; private IAtomContainer mol2 = null; @@ -72,12 +72,12 @@ public class VFlibMCSHandler : AbstractMCSAlgorithm, IMCSBase /// public VFlibMCSHandler() { - allAtomMCS = new List>(); - allAtomMCSCopy = new List>(); + allAtomMCS = new List>(); + allAtomMCSCopy = new List>(); atomsMCS = new Dictionary(); firstMCS = new SortedDictionary(); - allMCS = new List>(); - allMCSCopy = new List>(); + allMCS = new List>(); + allMCSCopy = new List>(); } public override void SearchMCS(bool bondTypeMatch) @@ -108,7 +108,7 @@ public override void SearchMCS(bool bondTypeMatch) SetFirstMappings(); } - private void SetFirstMappings() + private static void SetFirstMappings() { if (allAtomMCS.Count != 0) { @@ -145,7 +145,7 @@ public void Set(IQueryAtomContainer source, IAtomContainer target) mol2 = target; } - private bool HasMap(IDictionary maps, List> mapGlobal) + private static bool HasMap(IReadOnlyDictionary maps, List> mapGlobal) { foreach (var test in mapGlobal) { @@ -157,27 +157,27 @@ private bool HasMap(IDictionary maps, List> mapG return false; } - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { - return new ReadOnlyCollection>(allAtomMCS); + return allAtomMCS; } - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { - return new ReadOnlyCollection>(allMCS); + return allMCS; } - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { - return new ReadOnlyDictionary(atomsMCS); + return atomsMCS; } - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { - return new ReadOnlyDictionary(firstMCS); + return firstMCS; } - private int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer productMolecule) + private static int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer productMolecule) { List atoms = new List(); for (int i = 0; i < reactantMolecule.Atoms.Count; i++) @@ -211,7 +211,7 @@ private void SearchVFMCSMappings() countP = GetProductMol().Atoms.Count + AtomContainerManipulator.GetSingleBondEquivalentSum(GetProductMol()); } - vfLibSolutions = new List>(); + vfLibSolutions = new List>(); if (queryMol != null) { query = new QueryCompiler(queryMol).Compile(); @@ -246,20 +246,18 @@ private void SearchVFMCSMappings() SetVFMappings(false, query); } SetVFMappings(false, query); - // Console.Out.WriteLine("Sol count " + vfLibSolutions.Count); - // Console.Out.WriteLine("Sol size " + vfLibSolutions.Iterator().Next().Count); - // Console.Out.WriteLine("MCSSize " + vfMCSSize); - // Console.Out.WriteLine("After Sol count " + allMCSCopy.Count); - } private void SearchMcGregorMapping() { - IList> mappings = new List>(); + var mappings = new List>(); bool ropFlag = true; foreach (var firstPassMappings in allMCSCopy) { - IDictionary tMapping = new SortedDictionary(firstPassMappings); + var tMapping = new SortedDictionary(); + foreach (var e in firstPassMappings) + tMapping.Add(e.Key, e.Value); + McGregor mgit = null; if (queryMol != null) { @@ -283,14 +281,11 @@ private void SearchMcGregorMapping() } } mgit.StartMcGregorIteration(mgit.MCSSize, tMapping); //Start McGregor search - mappings = mgit.Mappings; + mappings = mgit.mappings; mgit = null; } - // Console.Out.WriteLine("\nSol count after MG" + mappings.Count); SetMcGregorMappings(ropFlag, mappings); vfMCSSize = vfMCSSize / 2; - // Console.Out.WriteLine("After set Sol count MG" + allMCS.Count); - // Console.Out.WriteLine("MCSSize " + vfMCSSize + "\n"); } private void SetVFMappings(bool rONP, IQuery query) @@ -298,8 +293,8 @@ private void SetVFMappings(bool rONP, IQuery query) int counter = 0; foreach (var solution in vfLibSolutions) { - IDictionary atomatomMapping = new Dictionary(); - IDictionary indexindexMapping = new SortedDictionary(); + var atomatomMapping = new Dictionary(); + var indexindexMapping = new SortedDictionary(); if (solution.Count > vfMCSSize) { this.vfMCSSize = solution.Count; @@ -356,7 +351,7 @@ private void SetVFMappings(bool rONP, IQuery query) } } - private void SetMcGregorMappings(bool ronp, IList> mappings) + private void SetMcGregorMappings(bool ronp, List> mappings) { int counter = 0; foreach (var mapping in mappings) @@ -368,8 +363,8 @@ private void SetMcGregorMappings(bool ronp, IList> mappings) allMCS.Clear(); counter = 0; } - IDictionary atomatomMapping = new Dictionary(); - IDictionary indexindexMapping = new SortedDictionary(); + var atomatomMapping = new Dictionary(); + var indexindexMapping = new SortedDictionary(); for (int index = 0; index < mapping.Count; index += 2) { IAtom qAtom = null; diff --git a/NCDK/SMSD/Algorithms/VFLib/VFlibSubStructureHandler.cs b/NCDK/SMSD/Algorithms/VFLib/VFlibSubStructureHandler.cs index 7ee81828..eb3cd130 100644 --- a/NCDK/SMSD/Algorithms/VFLib/VFlibSubStructureHandler.cs +++ b/NCDK/SMSD/Algorithms/VFLib/VFlibSubStructureHandler.cs @@ -54,16 +54,16 @@ namespace NCDK.SMSD.Algorithms.VFLib [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] public class VFlibSubStructureHandler : AbstractSubGraph, IMCSBase { - private static List> allAtomMCS = null; - private static IDictionary atomsMCS = null; - private static List> allAtomMCSCopy = null; - private static IDictionary firstMCS = null; - private static List> allMCS = null; - private static List> allMCSCopy = null; + private static List> allAtomMCS = null; + private static Dictionary atomsMCS = null; + private static List> allAtomMCSCopy = null; + private static SortedDictionary firstMCS = null; + private static List> allMCS = null; + private static List> allMCSCopy = null; private IQueryAtomContainer queryMol = null; private IAtomContainer mol1 = null; private IAtomContainer mol2 = null; - private List> vfLibSolutions = null; + private List> vfLibSolutions = null; private int vfMCSSize = -1; private bool bondMatchFlag = false; @@ -72,15 +72,15 @@ public class VFlibSubStructureHandler : AbstractSubGraph, IMCSBase /// public VFlibSubStructureHandler() { - allAtomMCS = new List>(); - allAtomMCSCopy = new List>(); + allAtomMCS = new List>(); + allAtomMCSCopy = new List>(); atomsMCS = new Dictionary(); firstMCS = new SortedDictionary(); - allMCS = new List>(); - allMCSCopy = new List>(); + allMCS = new List>(); + allMCSCopy = new List>(); } - private void SetFirstMappings() + private static void SetFirstMappings() { if (allAtomMCS.Count != 0) { @@ -116,7 +116,7 @@ public void Set(IQueryAtomContainer source, IAtomContainer target) mol2 = target; } - private bool HasMap(IDictionary map, List> mapGlobal) + private static bool HasMap(IReadOnlyDictionary map, List> mapGlobal) { foreach (var test in mapGlobal) { @@ -128,27 +128,27 @@ private bool HasMap(IDictionary map, List> mapGl return false; } - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { - return new ReadOnlyCollection>(allAtomMCS); + return allAtomMCS; } - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { - return new ReadOnlyCollection>(allMCS); + return allMCS; } - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { - return new ReadOnlyDictionary(atomsMCS); + return atomsMCS; } - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { - return new ReadOnlyDictionary(firstMCS); + return firstMCS; } - private int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer productMolecule) + private static int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer productMolecule) { List atoms = new List(); for (int i = 0; i < reactantMolecule.Atoms.Count; i++) @@ -170,10 +170,9 @@ private int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer private void SearchVFMappings() { - // Console.Out.WriteLine("searchVFMappings "); IQuery query = null; IMapper mapper = null; - vfLibSolutions = new List>(); + vfLibSolutions = new List>(); if (queryMol != null) { query = new QueryCompiler(queryMol).Compile(); @@ -223,8 +222,8 @@ private void SetVFMappings(bool ronp, IQuery query) int counter = 0; foreach (var solution in vfLibSolutions) { - IDictionary atomatomMapping = new Dictionary(); - IDictionary indexindexMapping = new SortedDictionary(); + var atomatomMapping = new Dictionary(); + var indexindexMapping = new SortedDictionary(); if (solution.Count > vfMCSSize) { this.vfMCSSize = solution.Count; @@ -275,24 +274,12 @@ private void SetVFMappings(bool ronp, IQuery query) counter++; } } - // Console.Out.WriteLine("allMCSCopy " + allMCSCopy.Count); } public override bool IsSubgraph(bool shouldMatchBonds) { IsBondMatchFlag = shouldMatchBonds; SearchVFMappings(); - // bool flag = McGregorFlag(); - // if (flag && vfLibSolutions.Count != 0) { - // try { - // SearchMcGregorMapping(); - // } catch (CDKException ex) { - // Trace.TraceError(Level.SEVERE, null, ex); - // } catch (IOException ex) { - // Trace.TraceError(Level.SEVERE, null, ex); - // } - // - // } else if (allAtomMCSCopy.Count != 0) { diff --git a/NCDK/SMSD/Algorithms/VFLib/VFlibTurboHandler.cs b/NCDK/SMSD/Algorithms/VFLib/VFlibTurboHandler.cs index 3d7eeb63..af878879 100644 --- a/NCDK/SMSD/Algorithms/VFLib/VFlibTurboHandler.cs +++ b/NCDK/SMSD/Algorithms/VFLib/VFlibTurboHandler.cs @@ -54,30 +54,29 @@ namespace NCDK.SMSD.Algorithms.VFLib [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] public class VFlibTurboHandler : AbstractSubGraph, IMCSBase { - private List> allAtomMCS = null; - private IDictionary atomsMCS = null; - private List> allAtomMCSCopy = null; - private IDictionary firstMCS = null; - private List> allMCS = null; - private List> allMCSCopy = null; - private IQueryAtomContainer queryMol = null; - private IAtomContainer mol1 = null; - private IAtomContainer mol2 = null; - private IDictionary vfLibSolutions = null; + private readonly List> allAtomMCS; + private readonly Dictionary atomsMCS; + private readonly List> allAtomMCSCopy; + private readonly SortedDictionary firstMCS; + private readonly List> allMCS; + private readonly List> allMCSCopy; + private IQueryAtomContainer queryMol; + private IAtomContainer mol1; + private IAtomContainer mol2; + private Dictionary vfLibSolutions; private int vfMCSSize = -1; - private bool bondMatchFlag = false; /// /// Constructor for an extended VF Algorithm for the MCS search /// public VFlibTurboHandler() { - allAtomMCS = new List>(); - allAtomMCSCopy = new List>(); + allAtomMCS = new List>(); + allAtomMCSCopy = new List>(); atomsMCS = new Dictionary(); firstMCS = new SortedDictionary(); - allMCS = new List>(); - allMCSCopy = new List>(); + allMCS = new List>(); + allMCSCopy = new List>(); } private void SetFirstMappings() @@ -116,7 +115,7 @@ public void Set(IQueryAtomContainer source, IAtomContainer target) mol2 = target; } - private bool HasMap(IDictionary map, List> mapGlobal) + private static bool HasMap(IReadOnlyDictionary map, List> mapGlobal) { foreach (var test in mapGlobal) { @@ -128,27 +127,27 @@ private bool HasMap(IDictionary map, List> mapGl return false; } - public IList> GetAllAtomMapping() + public IReadOnlyList> GetAllAtomMapping() { - return new ReadOnlyCollection>(allAtomMCS); + return allAtomMCS; } - public IList> GetAllMapping() + public IReadOnlyList> GetAllMapping() { - return new ReadOnlyCollection>(allMCS); + return allMCS; } - public IDictionary GetFirstAtomMapping() + public IReadOnlyDictionary GetFirstAtomMapping() { - return new ReadOnlyDictionary(atomsMCS); + return atomsMCS; } - public IDictionary GetFirstMapping() + public IReadOnlyDictionary GetFirstMapping() { - return new ReadOnlyDictionary(firstMCS); + return firstMCS; } - private int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer productMolecule) + private static int CheckCommonAtomCount(IAtomContainer reactantMolecule, IAtomContainer productMolecule) { List atoms = new List(); for (int i = 0; i < reactantMolecule.Atoms.Count; i++) @@ -180,7 +179,7 @@ private void SearchVFMappings() mapper = new VFMapper(query); if (mapper.HasMap(GetProductMol())) { - IDictionary map = mapper.GetFirstMap(GetProductMol()); + var map = mapper.GetFirstMap(GetProductMol()); if (map != null) { foreach (var e in map) @@ -195,7 +194,7 @@ private void SearchVFMappings() mapper = new VFMapper(query); if (mapper.HasMap(GetProductMol())) { - IDictionary map = mapper.GetFirstMap(GetProductMol()); + var map = mapper.GetFirstMap(GetProductMol()); if (map != null) { foreach (var e in map) @@ -210,7 +209,7 @@ private void SearchVFMappings() mapper = new VFMapper(query); if (mapper.HasMap(GetReactantMol())) { - IDictionary map = mapper.GetFirstMap(GetReactantMol()); + var map = mapper.GetFirstMap(GetReactantMol()); if (map != null) { foreach (var e in map) @@ -223,27 +222,24 @@ private void SearchVFMappings() private void SearchMcGregorMapping() { - IList> mappings = new List>(); + var mappings = new List>(); foreach (var firstPassMappings in allMCSCopy) { McGregor mgit = new McGregor(GetReactantMol(), GetProductMol(), mappings, IsBondMatchFlag); mgit.StartMcGregorIteration(mgit.MCSSize, firstPassMappings); //Start McGregor search - mappings = mgit.Mappings; + mappings = mgit.mappings; mgit = null; } - // Console.Out.WriteLine("\nSol count after MG" + mappings.Count); SetMcGregorMappings(mappings); vfMCSSize = vfMCSSize / 2; - // Console.Out.WriteLine("After set Sol count MG" + allMCS.Count); - // Console.Out.WriteLine("MCSSize " + vfMCSSize + "\n"); } private void SetVFMappings(bool ronp, IQuery query) { int counter = 0; - IDictionary atomatomMapping = new Dictionary(); - IDictionary indexindexMapping = new SortedDictionary(); + var atomatomMapping = new Dictionary(); + var indexindexMapping = new SortedDictionary(); if (vfLibSolutions.Count > vfMCSSize) { this.vfMCSSize = vfLibSolutions.Count; @@ -270,8 +266,6 @@ private void SetVFMappings(bool ronp, IQuery query) atomatomMapping[qAtom] = tAtom; indexindexMapping[qIndex] = tIndex; } - // Console.Out.WriteLine("indexindexMapping " + indexindexMapping.Count); - // Console.Out.WriteLine("MCS Size " + vfMCSSize); if (atomatomMapping.Count != 0 && !HasMap(indexindexMapping, allMCSCopy) && indexindexMapping.Count == vfMCSSize) { @@ -279,10 +273,9 @@ private void SetVFMappings(bool ronp, IQuery query) allMCSCopy.Insert(counter, indexindexMapping); counter++; } - // Console.Out.WriteLine("allMCSCopy " + allMCSCopy.Count); } - private void SetMcGregorMappings(IList> mappings) + private void SetMcGregorMappings(List> mappings) { int counter = 0; this.vfMCSSize = 0; @@ -295,8 +288,8 @@ private void SetMcGregorMappings(IList> mappings) allMCS.Clear(); counter = 0; } - IDictionary atomatomMapping = new Dictionary(); - IDictionary indexindexMapping = new SortedDictionary(); + var atomatomMapping = new Dictionary(); + var indexindexMapping = new SortedDictionary(); for (int index = 0; index < mapping.Count; index += 2) { IAtom qAtom = null; @@ -332,17 +325,6 @@ public override bool IsSubgraph(bool shouldMatchBonds) { IsBondMatchFlag = shouldMatchBonds; SearchVFMappings(); - // bool flag = McGregorFlag(); - // if (flag && vfLibSolutions.Count != 0) { - // try { - // SearchMcGregorMapping(); - // } catch (CDKException ex) { - // Trace.TraceError(Level.SEVERE, null, ex); - // } catch (IOException ex) { - // Trace.TraceError(Level.SEVERE, null, ex); - // } - // - // } else if (allAtomMCSCopy.Count != 0) { @@ -353,17 +335,7 @@ public override bool IsSubgraph(bool shouldMatchBonds) return (allMCS.Count != 0 && allMCS.First().Count == GetReactantMol().Atoms.Count) ? true : false; } - public bool IsBondMatchFlag - { - get - { - return bondMatchFlag; - } - set - { - this.bondMatchFlag = value; - } - } + public bool IsBondMatchFlag { get; set; } = false; private IAtomContainer GetReactantMol() { diff --git a/NCDK/SMSD/Filters/ChemicalFilters.cs b/NCDK/SMSD/Filters/ChemicalFilters.cs index 0a316710..80ff9a51 100644 --- a/NCDK/SMSD/Filters/ChemicalFilters.cs +++ b/NCDK/SMSD/Filters/ChemicalFilters.cs @@ -22,10 +22,12 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Aromaticities; using NCDK.Graphs; using NCDK.Isomorphisms.Matchers; -using NCDK.SMSD.Ring; +using NCDK.Silent; +using NCDK.SMSD.Rings; using NCDK.SMSD.Tools; using NCDK.Tools.Manipulator; using System; @@ -34,6 +36,7 @@ using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; + namespace NCDK.SMSD.Filters { /// @@ -44,9 +47,9 @@ namespace NCDK.SMSD.Filters // @author Syed Asad Rahman public class ChemicalFilters { - private List> allMCS = null; + private IList> allMCS = null; private IDictionary firstSolution = null; - private List> allAtomMCS = null; + private IList> allAtomMCS = null; private IDictionary firstAtomMCS = null; private List stereoScore = null; private List fragmentSize = null; @@ -64,7 +67,7 @@ public class ChemicalFilters /// c: Stereo matches /// /// - public ChemicalFilters(List> allMCS, List> allAtomMCS, + public ChemicalFilters(IList> allMCS, IList> allAtomMCS, IDictionary firstSolution, IDictionary firstAtomMCS, IAtomContainer sourceMol, IAtomContainer targetMol) { @@ -91,9 +94,12 @@ private void Clear() bEnergies.Clear(); } - private void Clear(IDictionary> sortedAllMCS, - IDictionary> sortedAllAtomMCS, IDictionary stereoScoreMap, - IDictionary fragmentScoreMap, IDictionary energySelectionMap) + private static void Clear( + IDictionary> sortedAllMCS, + IDictionary> sortedAllAtomMCS, + IDictionary stereoScoreMap, + IDictionary fragmentScoreMap, + IDictionary energySelectionMap) { sortedAllMCS.Clear(); sortedAllAtomMCS.Clear(); @@ -102,9 +108,12 @@ private void Clear(IDictionary> sortedAllMCS, energySelectionMap.Clear(); } - private void AddSolution(int counter, int key, IDictionary> allFragmentAtomMCS, - IDictionary> allFragmentMCS, IDictionary stereoScoreMap, - IDictionary energyScoreMap, IDictionary fragmentScoreMap) + private void AddSolution(int counter, int key, + IReadOnlyDictionary> allFragmentAtomMCS, + IReadOnlyDictionary> allFragmentMCS, + IReadOnlyDictionary stereoScoreMap, + IReadOnlyDictionary energyScoreMap, + IReadOnlyDictionary fragmentScoreMap) { allAtomMCS.Insert(counter, allFragmentAtomMCS[key]); allMCS.Insert(counter, allFragmentMCS[key]); @@ -113,9 +122,12 @@ private void AddSolution(int counter, int key, IDictionary> sortedAllMCS, - IDictionary> sortedAllAtomMCS, IDictionary stereoScoreMap, - IDictionary fragmentScoreMap, IDictionary energySelectionMap) + private void InitializeMaps( + IDictionary> sortedAllMCS, + IDictionary> sortedAllAtomMCS, + IDictionary stereoScoreMap, + IDictionary fragmentScoreMap, + IDictionary energySelectionMap) { int index = 0; foreach (var atomsMCS in allAtomMCS) @@ -163,12 +175,12 @@ private void InitializeMaps(IDictionary> sortedAllMCS [MethodImpl(MethodImplOptions.Synchronized)] public void SortResultsByStereoAndBondMatch() { - IDictionary> allStereoMCS = new Dictionary>(); - IDictionary> allStereoAtomMCS = new Dictionary>(); + var allStereoMCS = new Dictionary>(); + var allStereoAtomMCS = new Dictionary>(); - IDictionary fragmentScoreMap = new SortedDictionary(); - IDictionary energyScoreMap = new SortedDictionary(); - IDictionary aStereoScoreMap = new Dictionary(); + var fragmentScoreMap = new SortedDictionary(); + var energyScoreMap = new SortedDictionary(); + var aStereoScoreMap = new Dictionary(); InitializeMaps(allStereoMCS, allStereoAtomMCS, aStereoScoreMap, fragmentScoreMap, energyScoreMap); @@ -230,19 +242,19 @@ public void SortResultsByStereoAndBondMatch() [MethodImpl(MethodImplOptions.Synchronized)] public void SortResultsByFragments() { - IDictionary> allFragmentMCS = new SortedDictionary>(); - IDictionary> allFragmentAtomMCS = new SortedDictionary>(); + var allFragmentMCS = new SortedDictionary>(); + var allFragmentAtomMCS = new SortedDictionary>(); - IDictionary stereoScoreMap = new SortedDictionary(); - IDictionary energyScoreMap = new SortedDictionary(); - IDictionary fragmentScoreMap = new SortedDictionary(); + var stereoScoreMap = new SortedDictionary(); + var energyScoreMap = new SortedDictionary(); + var fragmentScoreMap = new SortedDictionary(); InitializeMaps(allFragmentMCS, allFragmentAtomMCS, stereoScoreMap, fragmentScoreMap, energyScoreMap); int minFragmentScore = 9999; foreach (var key in allFragmentAtomMCS.Keys) { - IDictionary mcsAtom = allFragmentAtomMCS[key]; + var mcsAtom = allFragmentAtomMCS[key]; int fragmentCount = GetMappedMoleculeFragmentSize(mcsAtom); fragmentScoreMap[key] = fragmentCount; if (minFragmentScore > fragmentCount) @@ -287,18 +299,18 @@ public void SortResultsByFragments() [MethodImpl(MethodImplOptions.Synchronized)] public void SortResultsByEnergies() { - IDictionary> allEnergyMCS = new SortedDictionary>(); - IDictionary> allEnergyAtomMCS = new SortedDictionary>(); + var allEnergyMCS = new SortedDictionary>(); + var allEnergyAtomMCS = new SortedDictionary>(); - IDictionary stereoScoreMap = new SortedDictionary(); - IDictionary fragmentScoreMap = new SortedDictionary(); - IDictionary aEnergySelectionMap = new SortedDictionary(); + var stereoScoreMap = new SortedDictionary(); + var fragmentScoreMap = new SortedDictionary(); + var aEnergySelectionMap = new SortedDictionary(); InitializeMaps(allEnergyMCS, allEnergyAtomMCS, stereoScoreMap, fragmentScoreMap, aEnergySelectionMap); foreach (var key in allEnergyMCS.Keys) { - IDictionary mcsAtom = allEnergyMCS[key]; + var mcsAtom = allEnergyMCS[key]; double energies = GetMappedMoleculeEnergies(mcsAtom); aEnergySelectionMap[key] = energies; } @@ -336,19 +348,16 @@ public void SortResultsByEnergies() } } - private IDictionary MakeBondMapsOfAtomMaps(IAtomContainer ac1, IAtomContainer ac2, - IDictionary mappings) + private static IReadOnlyDictionary MakeBondMapsOfAtomMaps(IAtomContainer ac1, IAtomContainer ac2, IReadOnlyDictionary mappings) { - IDictionary maps = new Dictionary(); + var maps = new Dictionary(); foreach (var atoms in ac1.Atoms) { - int ac1AtomNumber = ac1.Atoms.IndexOf(atoms); if (mappings.ContainsKey(ac1AtomNumber)) { - int ac2AtomNumber = mappings[ac1AtomNumber]; var connectedAtoms = ac1.GetConnectedAtoms(atoms); @@ -363,8 +372,7 @@ private IDictionary MakeBondMapsOfAtomMaps(IAtomContainer ac1, IAt int ac2ConnectedAtomNumber = mappings[ac1ConnectedAtomNumber]; IBond ac1Bond = ac1.GetBond(atoms, cAtoms); - IBond ac2Bond = ac2 - .GetBond(ac2.Atoms[ac2AtomNumber], ac2.Atoms[ac2ConnectedAtomNumber]); + IBond ac2Bond = ac2.GetBond(ac2.Atoms[ac2AtomNumber], ac2.Atoms[ac2ConnectedAtomNumber]); if (ac2Bond == null) { @@ -384,10 +392,10 @@ private IDictionary MakeBondMapsOfAtomMaps(IAtomContainer ac1, IAt } [MethodImpl(MethodImplOptions.Synchronized)] - private int GetMappedMoleculeFragmentSize(IDictionary mcsAtomSolution) + private int GetMappedMoleculeFragmentSize(IReadOnlyDictionary mcsAtomSolution) { - IAtomContainer educt = Default.ChemObjectBuilder.Instance.NewAtomContainer(rMol); - IAtomContainer product = Default.ChemObjectBuilder.Instance.NewAtomContainer(pMol); + IAtomContainer educt = ChemObjectBuilder.Instance.NewAtomContainer(rMol); + IAtomContainer product = ChemObjectBuilder.Instance.NewAtomContainer(pMol); if (mcsAtomSolution != null) { @@ -403,12 +411,12 @@ private int GetMappedMoleculeFragmentSize(IDictionary mcsAtomSolut } [MethodImpl(MethodImplOptions.Synchronized)] - private double GetMappedMoleculeEnergies(IDictionary mcsAtomSolution) + private double GetMappedMoleculeEnergies(IReadOnlyDictionary mcsAtomSolution) { double totalBondEnergy = -9999.0; - IAtomContainer educt = Default.ChemObjectBuilder.Instance.NewAtomContainer(rMol); - IAtomContainer product = Default.ChemObjectBuilder.Instance.NewAtomContainer(pMol); + IAtomContainer educt = ChemObjectBuilder.Instance.NewAtomContainer(rMol); + IAtomContainer product = ChemObjectBuilder.Instance.NewAtomContainer(pMol); foreach (var eAtom in educt.Atoms) { @@ -456,37 +464,36 @@ internal static IEnumerable> SortMapByValueInDecending /// Return sorted energy in ascending order. /// sorted bond breaking energy /// - public IList GetSortedEnergy() + public IReadOnlyList GetSortedEnergy() { - return new ReadOnlyCollection(bEnergies); + return bEnergies; } /// /// Return sorted fragment in ascending order of the size. /// sorted fragment count /// - public IList GetSortedFragment() + public IReadOnlyList GetSortedFragment() { - return new ReadOnlyCollection(fragmentSize); + return fragmentSize; } /// /// Return Stereo matches in descending order. /// sorted stereo matches /// - public IList GetStereoMatches() + public IReadOnlyList GetStereoMatches() { - return new ReadOnlyCollection(stereoScore); + return stereoScore; } - private List GetMappedFragment(IAtomContainer molecule, ICollection atomsMCS) + private static List GetMappedFragment(IAtomContainer molecule, IEnumerable atomsMCS) { IAtomContainer subgraphContainer = molecule.Builder.NewAtomContainer(molecule); - List list = new List(atomsMCS.Count); + var list = new List(); foreach (var atom in atomsMCS) { int post = molecule.Atoms.IndexOf(atom); - // Console.Out.WriteLine("Atom to be removed " + post); list.Add(subgraphContainer.Atoms[post]); } @@ -511,8 +518,7 @@ private List GetMappedFragment(IAtomContainer molecule, ICollection atomMapMCS, IAtomContainer reactant, - IAtomContainer product) + private static double GetAtomScore(double score, IReadOnlyDictionary atomMapMCS, IAtomContainer reactant, IAtomContainer product) { foreach (var mappings in atomMapMCS) { @@ -557,11 +563,10 @@ private double GetAtomScore(double score, IDictionary atomMapMCS, return score; } - private double GetBondScore(double score, IDictionary bondMaps) + private static double GetBondScore(double score, IReadOnlyDictionary bondMaps) { foreach (var matchedBonds in bondMaps) { - IBond rBond = matchedBonds.Key; IBond pBond = matchedBonds.Value; @@ -571,7 +576,7 @@ private double GetBondScore(double score, IDictionary bondMaps) return score; } - private double GetBondFormalChargeMatches(IBond rBond, IBond pBond) + private static double GetBondFormalChargeMatches(IBond rBond, IBond pBond) { double score = 0.0; if (rBond != null && pBond != null) @@ -581,7 +586,7 @@ private double GetBondFormalChargeMatches(IBond rBond, IBond pBond) IAtom patom1 = pBond.Atoms[0]; IAtom patom2 = pBond.Atoms[1]; - if (ratom1.Symbol.Equals(patom1.Symbol) && ratom1.Symbol.Equals(patom1.Symbol)) + if (ratom1.Symbol.Equals(patom1.Symbol, StringComparison.Ordinal) && ratom1.Symbol.Equals(patom1.Symbol, StringComparison.Ordinal)) { if ((ratom1.FormalCharge != patom1.FormalCharge) || ratom2.FormalCharge != patom2.FormalCharge) @@ -602,7 +607,7 @@ private double GetBondFormalChargeMatches(IBond rBond, IBond pBond) score += 100; } } - else if (ratom1.Symbol.Equals(patom2.Symbol) && ratom2.Symbol.Equals(patom1.Symbol)) + else if (ratom1.Symbol.Equals(patom2.Symbol, StringComparison.Ordinal) && ratom2.Symbol.Equals(patom1.Symbol, StringComparison.Ordinal)) { if ((ratom1.FormalCharge != patom2.FormalCharge) || ratom2.FormalCharge != patom1.FormalCharge) @@ -628,7 +633,7 @@ private double GetBondFormalChargeMatches(IBond rBond, IBond pBond) return score; } - private double GetBondTypeMatches(IBond queryBond, IBond targetBond) + private static double GetBondTypeMatches(IBond queryBond, IBond targetBond) { double score = 0; @@ -714,7 +719,7 @@ private double GetBondTypeMatches(IBond queryBond, IBond targetBond) return score; } - private double GetRingMatchScore(IList list) + private static double GetRingMatchScore(IList list) { double lScore = 0; List listMap = (List)list[0]; @@ -736,7 +741,7 @@ private double GetRingMatchScore(IList list) return lScore; } - private double GetEnergy(IAtomContainer educt, IAtomContainer product) + private static double GetEnergy(IAtomContainer educt, IAtomContainer product) { double eEnergy = 0.0; BondEnergies bondEnergy = BondEnergies.Instance; @@ -754,7 +759,7 @@ private double GetEnergy(IAtomContainer educt, IAtomContainer product) return (eEnergy + pEnergy); } - private double GetBondEnergy(IBond bond, BondEnergies bondEnergy) + private static double GetBondEnergy(IBond bond, BondEnergies bondEnergy) { double energy = 0.0; if ((bond.Atoms[0].IsPlaced == true && bond.Atoms[1].IsPlaced == false) @@ -766,7 +771,7 @@ private double GetBondEnergy(IBond bond, BondEnergies bondEnergy) return energy; } - private double GetRingMatch(IRingSet rings, List atoms) + private static double GetRingMatch(IRingSet rings, List atoms) { double score = 0.0; foreach (var a in atoms) @@ -782,8 +787,7 @@ private double GetRingMatch(IRingSet rings, List atoms) return score; } - private bool GetStereoBondChargeMatch(IDictionary stereoScoreMap, - IDictionary> allStereoMCS, IDictionary> allStereoAtomMCS) + private bool GetStereoBondChargeMatch(IDictionary stereoScoreMap, IReadOnlyDictionary> allStereoMCS, IReadOnlyDictionary> allStereoAtomMCS) { bool stereoMatchFlag = false; IAtomContainer reactant = rMol; @@ -797,10 +801,10 @@ private bool GetStereoBondChargeMatch(IDictionary stereoScoreMap, { double score = 0.0; // Console.Out.WriteLine("\nStart score " + score); - IDictionary atomsMCS = allStereoMCS[key]; - IDictionary atomMapMCS = allStereoAtomMCS[key]; + var atomsMCS = allStereoMCS[key]; + var atomMapMCS = allStereoAtomMCS[key]; score = GetAtomScore(score, atomMapMCS, reactant, product); - IDictionary bondMaps = MakeBondMapsOfAtomMaps(rMol, pMol, atomsMCS); + var bondMaps = MakeBondMapsOfAtomMaps(rMol, pMol, atomsMCS); if (rMol.Bonds.Count > 1 && pMol.Bonds.Count > 1) { @@ -822,10 +826,10 @@ private bool GetStereoBondChargeMatch(IDictionary stereoScoreMap, return stereoMatchFlag; } - private int GetFragmentCount(IAtomContainer molecule) + private static int GetFragmentCount(IAtomContainer molecule) { bool fragmentFlag = true; - var fragmentMolSet = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var fragmentMolSet = ChemObjectBuilder.Instance.NewAtomContainerSet(); int countFrag = 0; if (molecule.Atoms.Count > 0) { @@ -915,33 +919,26 @@ public static int ConvertBondStereo(IBond bond) /// public static BondStereo ConvertStereo(int stereoValue) { - BondStereo stereo = BondStereo.None; - if (stereoValue == 1) - { - // up bond - stereo = BondStereo.Up; - } - else if (stereoValue == 6) - { - // down bond - stereo = BondStereo.Down; - } - else if (stereoValue == 0) - { - // bond has no stereochemistry - stereo = BondStereo.None; - } - else if (stereoValue == 4) - { - //up or down bond - stereo = BondStereo.UpOrDown; - } - else if (stereoValue == 3) - { - //e or z undefined - stereo = BondStereo.EOrZ; + switch (stereoValue) + { + case 1: + // up bond + return BondStereo.Up; + case 6: + // down bond + return BondStereo.Down; + case 0: + // bond has no stereochemistry + return BondStereo.None; + case 4: + //up or down bond + return BondStereo.UpOrDown; + case 3: + //e or z undefined + return BondStereo.EOrZ; + default: + return BondStereo.None; } - return stereo; } } } diff --git a/NCDK/SMSD/Filters/PostFilter.cs b/NCDK/SMSD/Filters/PostFilter.cs index 69b4aef8..9d7cbd5c 100644 --- a/NCDK/SMSD/Filters/PostFilter.cs +++ b/NCDK/SMSD/Filters/PostFilter.cs @@ -41,7 +41,7 @@ namespace NCDK.SMSD.Filters // @cdk.githash // @author Syed Asad Rahman [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] - public class PostFilter + public static class PostFilter { /// /// Creates a new instance of Post Filter and removes @@ -49,7 +49,7 @@ public class PostFilter /// /// /// Filtered non-redundant mappings - public static IList> Filter(IList> mappings) + public static IReadOnlyList> Filter(IList> mappings) { FinalMappings finalMappings = FinalMappings.Instance; if (mappings != null && mappings.Count != 0) @@ -59,14 +59,14 @@ public static IList> Filter(IList> mappings) } else { - finalMappings.Set(new List>()); + finalMappings.Set(new List>()); } return finalMappings.GetFinalMapping(); } private static DictionaryEqualityComparer DictionaryEqualityComparer_int_int { get; } = new DictionaryEqualityComparer(); - private static bool HasMap(IDictionary newMap, List> nonRedundantMapping) + private static bool HasMap(IReadOnlyDictionary newMap, IReadOnlyList> nonRedundantMapping) { foreach (var storedMap in nonRedundantMapping) { @@ -78,12 +78,12 @@ private static bool HasMap(IDictionary newMap, List> RemoveRedundantMapping(IList> mappingOrg) + private static List> RemoveRedundantMapping(IList> mappingOrg) { - List> nonRedundantMapping = new List>(); + var nonRedundantMapping = new List>(); foreach (var mapping in mappingOrg) { - IDictionary newMap = GetMappingMapFromList(mapping); + var newMap = GetMappingMapFromList(mapping); if (!HasMap(newMap, nonRedundantMapping)) { nonRedundantMapping.Add(newMap); @@ -92,9 +92,9 @@ private static List> RemoveRedundantMapping(IList GetMappingMapFromList(IList list) + private static SortedDictionary GetMappingMapFromList(IReadOnlyList list) { - IDictionary newMap = new SortedDictionary(); + var newMap = new SortedDictionary(); for (int index = 0; index < list.Count; index += 2) { newMap[list[index]] = list[index + 1]; diff --git a/NCDK/SMSD/Global/TimeOut.cs b/NCDK/SMSD/Globals/TimeOut.cs similarity index 98% rename from NCDK/SMSD/Global/TimeOut.cs rename to NCDK/SMSD/Globals/TimeOut.cs index 4d867fe5..dcd43df3 100644 --- a/NCDK/SMSD/Global/TimeOut.cs +++ b/NCDK/SMSD/Globals/TimeOut.cs @@ -1,5 +1,4 @@ /* - * * Copyright (C) 2006-2010 Syed Asad Rahman * * Contact: cdk-devel@lists.sourceforge.net @@ -22,10 +21,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using System; using System.Runtime.CompilerServices; -namespace NCDK.SMSD.Global +namespace NCDK.SMSD.Globals { /// /// Class that manages MCS timeout. diff --git a/NCDK/SMSD/Helper/FinalMappings.cs b/NCDK/SMSD/Helper/FinalMappings.cs index 5e60c0e7..78b3bc6d 100644 --- a/NCDK/SMSD/Helper/FinalMappings.cs +++ b/NCDK/SMSD/Helper/FinalMappings.cs @@ -36,12 +36,12 @@ namespace NCDK.SMSD.Helper // @author Syed Asad Rahman public class FinalMappings : IFinalMapping { - private static List> mappings = null; + private static List> mappings = null; private static FinalMappings instance = null; protected internal FinalMappings() { - mappings = new List>(); + mappings = new List>(); } /// @@ -61,7 +61,7 @@ public static FinalMappings Instance } [MethodImpl(MethodImplOptions.Synchronized)] - public void Add(IDictionary mapping) + public void Add(IReadOnlyDictionary mapping) { mappings.Add(mapping); } @@ -71,7 +71,7 @@ public void Add(IDictionary mapping) /// /// list of mappings [MethodImpl(MethodImplOptions.Synchronized)] - public void Set(IList> list) + public void Set(IList> list) { this.Clear(); mappings.AddRange(list); @@ -83,12 +83,12 @@ public void Clear() mappings.Clear(); } - public IList> GetFinalMapping() + public IReadOnlyList> GetFinalMapping() { return mappings; } - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { return mappings.GetEnumerator(); } diff --git a/NCDK/SMSD/IFinalMapping.cs b/NCDK/SMSD/IFinalMapping.cs index b444d711..14dc351c 100644 --- a/NCDK/SMSD/IFinalMapping.cs +++ b/NCDK/SMSD/IFinalMapping.cs @@ -33,22 +33,21 @@ namespace NCDK.SMSD // @cdk.githash // @author Syed Asad Rahman [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] - public interface IFinalMapping : IEnumerable> + public interface IFinalMapping : IEnumerable> { - /// /// Adds mapping to the mapping list /// /// List of all MCS mapping between a given /// reactant and product - void Add(IDictionary mapping); + void Add(IReadOnlyDictionary mapping); /// /// Sets mapping list /// List of all MCS mapping between a given /// reactant and product /// - void Set(IList> list); + void Set(IList> list); /// /// clear the mapping @@ -59,7 +58,7 @@ public interface IFinalMapping : IEnumerable> /// Returns the stored mappings /// /// get of MCS mapping List - IList> GetFinalMapping(); + IReadOnlyList> GetFinalMapping(); /// /// Returns number of stored mappings diff --git a/NCDK/SMSD/IMCSBase.cs b/NCDK/SMSD/IMCSBase.cs index 2633c055..4797ebae 100644 --- a/NCDK/SMSD/IMCSBase.cs +++ b/NCDK/SMSD/IMCSBase.cs @@ -60,7 +60,7 @@ public interface IMCSBase /// and map.Value for the target molecule /// /// All possible MCS atom Mappings - IList> GetAllAtomMapping(); + IReadOnlyList> GetAllAtomMapping(); /// /// Returns all plausible mappings between query and target molecules. @@ -69,19 +69,19 @@ public interface IMCSBase /// and map.Value for the target molecule /// /// All possible MCS Mapping Index - IList> GetAllMapping(); + IReadOnlyList> GetAllMapping(); /// /// Returns one of the best matches with atoms mapped. /// /// Best Atom Mapping - IDictionary GetFirstAtomMapping(); + IReadOnlyDictionary GetFirstAtomMapping(); /// /// Returns one of the best matches with atom indexes mapped. /// /// Best Mapping Index - IDictionary GetFirstMapping(); + IReadOnlyDictionary GetFirstMapping(); } } diff --git a/NCDK/SMSD/Isomorphism.cs b/NCDK/SMSD/Isomorphism.cs index 0c533d55..6f7c22e1 100644 --- a/NCDK/SMSD/Isomorphism.cs +++ b/NCDK/SMSD/Isomorphism.cs @@ -25,11 +25,11 @@ using NCDK.Isomorphisms.Matchers; using NCDK.SMSD.Algorithms.MCSPluses; -using NCDK.SMSD.Algorithms.RGraph; -using NCDK.SMSD.Algorithms.Single; +using NCDK.SMSD.Algorithms.RGraphs; +using NCDK.SMSD.Algorithms.Singles; using NCDK.SMSD.Algorithms.VFLib; using NCDK.SMSD.Filters; -using NCDK.SMSD.Global; +using NCDK.SMSD.Globals; using NCDK.SMSD.Tools; using System; using System.Collections.Generic; @@ -73,20 +73,19 @@ namespace NCDK.SMSD [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] public sealed class Isomorphism : AbstractMCS { - private List> allMCS = null; - private IDictionary firstSolution = null; - private List> allAtomMCS = null; - private IDictionary firstAtomMCS = null; - private List> allBondMCS = null; - private IDictionary firstBondMCS = null; + private List> allMCS = null; + private SortedDictionary firstSolution = null; + private List> allAtomMCS = null; + private Dictionary firstAtomMCS = null; + private IReadOnlyList> allBondMCS = null; private MolHandler rMol = null; private IQueryAtomContainer queryMol = null; private MolHandler pMol = null; private IAtomContainer pAC = null; - private IList stereoScore = null; - private IList fragmentSize = null; - private IList bEnergies = null; - private Algorithm algorithmType; + private IReadOnlyList stereoScore = null; + private IReadOnlyList fragmentSize = null; + private IReadOnlyList bEnergies = null; + private readonly Algorithm algorithmType; private bool removeHydrogen = false; private bool subGraph = false; @@ -107,11 +106,11 @@ public Isomorphism(Algorithm algorithmType, bool bondTypeFlag) { this.algorithmType = algorithmType; firstSolution = new SortedDictionary(); - allMCS = new List>(); - allAtomMCS = new List>(); + allMCS = new List>(); + allAtomMCS = new List>(); firstAtomMCS = new Dictionary(); - allBondMCS = new List>(); - firstBondMCS = new Dictionary(); + allBondMCS = new List>(); + FirstBondMap = new Dictionary(); SetTime(bondTypeFlag); IsMatchBonds = bondTypeFlag; @@ -166,9 +165,8 @@ private void MCSBuilder(IQueryAtomContainer mol1, IAtomContainer mol2) if (allAtomMCS.Count != 0 && firstAtomMCS.Count != 0 && firstAtomMCS.Count > 1) { AllBondMaps = MakeBondMapsOfAtomMaps(mol1, mol2, allAtomMCS); - var firstMap = AllBondMaps.FirstOrDefault(); - if (firstMap != null) - SetFirstBondMap(firstMap); + if (AllBondMaps.Count != 0) + SetFirstBondMap(AllBondMaps[0]); } } @@ -179,10 +177,11 @@ private void MCSBuilder(IQueryAtomContainer mol1, IAtomContainer mol2) /// mappings between source and target molecule atoms /// bond maps between source and target molecules based on the atoms /// - public static List> MakeBondMapsOfAtomMaps(IAtomContainer ac1, IAtomContainer ac2, - List> mappings) + public static IReadOnlyList> MakeBondMapsOfAtomMaps( + IAtomContainer ac1, IAtomContainer ac2, + IReadOnlyList> mappings) { - List> bondMaps = new List>(); + List> bondMaps = new List>(); foreach (var mapping in mappings) { bondMaps.Add(MakeBondMapOfAtomMap(ac1, ac2, mapping)); @@ -198,10 +197,11 @@ public static List> MakeBondMapsOfAtomMaps(IAtomContai /// mappings between source and target molecule atoms /// bond map between source and target molecules based on the atoms /// - public static IDictionary MakeBondMapOfAtomMap(IAtomContainer ac1, IAtomContainer ac2, - IDictionary mapping) + public static IReadOnlyDictionary MakeBondMapOfAtomMap( + IAtomContainer ac1, IAtomContainer ac2, + IReadOnlyDictionary mapping) { - IDictionary maps = new Dictionary(); + var maps = new Dictionary(); foreach (var mapS in mapping) { @@ -228,10 +228,7 @@ public static IDictionary MakeBondMapOfAtomMap(IAtomContainer ac1, } } - // Console.Out.WriteLine("bond Map size:" + maps.Count); - return maps; - } private void ChooseAlgorithm(int rBondCount, int pBondCount) @@ -445,7 +442,7 @@ private void SingleMapping() allAtomMCS.AddRange(mcs.GetAllAtomMapping()); } - private int GetHCount(IAtomContainer molecule) + private static int GetHCount(IAtomContainer molecule) { int count = 0; foreach (var atom in molecule.Atoms) @@ -567,12 +564,12 @@ private void SetTime(bool bondTypeFlag) } } - public bool IsTimeOut() + public static bool IsTimeOut() { return TimeOut.Instance.Enabled; } - public void ReSetTimeOut() + public static void ResetTimeOut() { TimeOut.Instance.Enabled = false; } @@ -680,25 +677,25 @@ public override void SetChemFilters(bool stereoFilter, bool fragmentFilter, bool } [MethodImpl(MethodImplOptions.Synchronized)] - public override IDictionary GetFirstMapping() + public override IReadOnlyDictionary GetFirstMapping() { return firstSolution.Count == 0 ? null : firstSolution; } [MethodImpl(MethodImplOptions.Synchronized)] - public override IList> GetAllMapping() + public override IReadOnlyList> GetAllMapping() { return allMCS.Count == 0 ? null : allMCS; } [MethodImpl(MethodImplOptions.Synchronized)] - public override IDictionary GetFirstAtomMapping() + public override IReadOnlyDictionary GetFirstAtomMapping() { return firstAtomMCS.Count == 0 ? null : firstAtomMCS; } [MethodImpl(MethodImplOptions.Synchronized)] - public override IList> GetAllAtomMapping() + public override IReadOnlyList> GetAllAtomMapping() { return allAtomMCS.Count == 0 ? null : allAtomMCS; } @@ -895,7 +892,7 @@ public override double GetEuclideanDistance() public bool IsMatchBonds { get; set; } - public List> AllBondMaps + public IReadOnlyList> AllBondMaps { get { @@ -907,15 +904,15 @@ public List> AllBondMaps } } - public IDictionary FirstBondMap => firstBondMCS; + public IReadOnlyDictionary FirstBondMap { get; private set; } = null; /// /// /// /// The firstBondMCS to set - private void SetFirstBondMap(IDictionary firstBondMCS) + private void SetFirstBondMap(IReadOnlyDictionary firstBondMCS) { - this.firstBondMCS = firstBondMCS; + this.FirstBondMap = firstBondMCS; } } } diff --git a/NCDK/SMSD/Labelling/AbstractReactionLabeller.cs b/NCDK/SMSD/Labelling/AbstractReactionLabeller.cs index 16356aab..9fbd6754 100644 --- a/NCDK/SMSD/Labelling/AbstractReactionLabeller.cs +++ b/NCDK/SMSD/Labelling/AbstractReactionLabeller.cs @@ -1,7 +1,8 @@ -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; +using System.Globalization; namespace NCDK.SMSD.Labelling { @@ -12,32 +13,32 @@ public class AbstractReactionLabeller /// /// A nasty hack necessary to get around a bug in the CDK /// - private bool fixAtomMappingCastType = false; + private readonly bool fixAtomMappingCastType = false; - private void FixAtomMapping(IAtomContainer canonicalForm) + private static void FixAtomMapping(IAtomContainer canonicalForm) { foreach (var a in canonicalForm.Atoms) { string v = a.GetProperty(CDKPropertyName.AtomAtomMapping); if (v != null) { - a.SetProperty(CDKPropertyName.AtomAtomMapping, int.Parse(v)); + a.SetProperty(CDKPropertyName.AtomAtomMapping, int.Parse(v, NumberFormatInfo.InvariantInfo)); } } } - private IDictionary AtomAtomMap(IReaction reaction, IReaction clone, IDictionary permutationMap) + private static IReadOnlyDictionary AtomAtomMap(IReaction reaction, IReaction clone, IReadOnlyDictionary permutationMap) { // create a Map of corresponding atoms for molecules // (key: original Atom, value: clone Atom) - IDictionary atomAtom = new Dictionary(); + var atomAtom = new Dictionary(); var reactants = reaction.Reactants; var clonedReactants = clone.Reactants; for (int i = 0; i < reactants.Count; ++i) { - IAtomContainer mol = reactants[i]; - IAtomContainer mol2 = clonedReactants[i]; - int[] permutation = permutationMap[mol2]; + var mol = reactants[i]; + var mol2 = clonedReactants[i]; + var permutation = permutationMap[mol2]; for (int j = 0; j < mol.Atoms.Count; ++j) { atomAtom[mol.Atoms[j]] = mol2.Atoms[permutation[j]]; @@ -47,9 +48,9 @@ private IDictionary AtomAtomMap(IReaction reaction, IReaction clon var clonedProducts = clone.Products; for (int i = 0; i < products.Count; ++i) { - IAtomContainer mol = products[i]; - IAtomContainer mol2 = clonedProducts[i]; - int[] permutation = permutationMap[mol2]; + var mol = products[i]; + var mol2 = clonedProducts[i]; + var permutation = permutationMap[mol2]; for (int j = 0; j < mol.Atoms.Count; ++j) { atomAtom[mol.Atoms[j]] = mol2.Atoms[permutation[j]]; @@ -58,29 +59,29 @@ private IDictionary AtomAtomMap(IReaction reaction, IReaction clon foreach (var key in atomAtom.Keys) { - IAtomContainer keyAC = ReactionManipulator.GetRelevantAtomContainer(reaction, key); - int keyIndex = keyAC.Atoms.IndexOf(key); - IAtom value = atomAtom[key]; - IAtomContainer valueAC = ReactionManipulator.GetRelevantAtomContainer(clone, value); - int valueIndex = valueAC.Atoms.IndexOf(value); + var keyAC = ReactionManipulator.GetRelevantAtomContainer(reaction, key); + var keyIndex = keyAC.Atoms.IndexOf(key); + var value = atomAtom[key]; + var valueAC = ReactionManipulator.GetRelevantAtomContainer(clone, value); + var valueIndex = valueAC.Atoms.IndexOf(value); Console.Out.WriteLine("key " + keyIndex + key.Symbol + " mapped to " + valueIndex + value.Symbol); } return atomAtom; } - private List CloneMappings(IReaction reaction, IDictionary atomAtomMap) + private static List CloneMappings(IReaction reaction, IReadOnlyDictionary atomAtomMap) { // clone the mappings - int numberOfMappings = reaction.Mappings.Count; - List map = new List(); + var numberOfMappings = reaction.Mappings.Count; + var map = new List(); for (int mappingIndex = 0; mappingIndex < numberOfMappings; mappingIndex++) { - IMapping mapping = reaction.Mappings[mappingIndex]; - IChemObject keyChemObj0 = mapping[0]; - IChemObject keyChemObj1 = mapping[1]; - IChemObject co0 = (IChemObject)atomAtomMap[(IAtom)keyChemObj0]; - IChemObject co1 = (IChemObject)atomAtomMap[(IAtom)keyChemObj1]; + var mapping = reaction.Mappings[mappingIndex]; + var keyChemObj0 = mapping[0]; + var keyChemObj1 = mapping[1]; + var co0 = (IChemObject)atomAtomMap[(IAtom)keyChemObj0]; + var co1 = (IChemObject)atomAtomMap[(IAtom)keyChemObj1]; map.Add(new Mapping(co0, co1)); } return map; @@ -88,17 +89,17 @@ private List CloneMappings(IReaction reaction, IDictionary { - IDictionary indexMap; + private readonly IReadOnlyDictionary indexMap; - public MappingSorter(IDictionary indexMap) + public MappingSorter(IReadOnlyDictionary indexMap) { this.indexMap = indexMap; } public int Compare(IMapping o1, IMapping o2) { - IChemObject o10 = o1[0]; - IChemObject o20 = o2[0]; + var o10 = o1[0]; + var o20 = o2[0]; return indexMap[o10].CompareTo(indexMap[o20]); } } @@ -108,12 +109,11 @@ public int Compare(IMapping o1, IMapping o2) /// in the mapping (which is assumed to be the reactant). /// /// - private void CloneAndSortMappings(IReaction reaction, IReaction copyOfReaction, - IDictionary permutationMap) + private static void CloneAndSortMappings(IReaction reaction, IReaction copyOfReaction, + IReadOnlyDictionary permutationMap) { - // make a lookup for the indices of the atoms in the copy - IDictionary indexMap = new Dictionary(); + var indexMap = new Dictionary(); var all = ReactionManipulator.GetAllAtomContainers(copyOfReaction); int globalIndex = 0; foreach (var ac in all) @@ -125,8 +125,8 @@ private void CloneAndSortMappings(IReaction reaction, IReaction copyOfReaction, } } - IDictionary atomAtomMap = AtomAtomMap(reaction, copyOfReaction, permutationMap); - List map = CloneMappings(reaction, atomAtomMap); + var atomAtomMap = AtomAtomMap(reaction, copyOfReaction, permutationMap); + var map = CloneMappings(reaction, atomAtomMap); var mappingSorter = new MappingSorter(indexMap); map.Sort(mappingSorter); @@ -143,31 +143,31 @@ private void CloneAndSortMappings(IReaction reaction, IReaction copyOfReaction, public IReaction LabelReaction(IReaction reaction, ICanonicalMoleculeLabeller labeller) { Console.Out.WriteLine("labelling"); - IReaction canonReaction = new Reaction(); + var canonReaction = new Reaction(); - IDictionary permutationMap = new Dictionary(); + var permutationMap = new Dictionary(); - IChemObjectSet canonicalProducts = Default.ChemObjectBuilder.Instance.NewChemObjectSet(); + var canonicalProducts = ChemObjectBuilder.Instance.NewChemObjectSet(); foreach (var product in reaction.Products) { - IAtomContainer canonicalForm = labeller.GetCanonicalMolecule(product); + var canonicalForm = labeller.GetCanonicalMolecule(product); if (fixAtomMappingCastType) { FixAtomMapping(canonicalForm); } - IAtomContainer canonicalMolecule = canonicalForm.Builder.NewAtomContainer(canonicalForm); + var canonicalMolecule = canonicalForm.Builder.NewAtomContainer(canonicalForm); permutationMap[canonicalMolecule] = labeller.GetCanonicalPermutation(product); canonicalProducts.Add(canonicalMolecule); } - IChemObjectSet canonicalReactants = Default.ChemObjectBuilder.Instance.NewChemObjectSet(); + var canonicalReactants = ChemObjectBuilder.Instance.NewChemObjectSet(); foreach (var reactant in reaction.Reactants) { - IAtomContainer canonicalForm = labeller.GetCanonicalMolecule(reactant); + var canonicalForm = labeller.GetCanonicalMolecule(reactant); if (fixAtomMappingCastType) { FixAtomMapping(canonicalForm); } - IAtomContainer canonicalMolecule = canonicalForm.Builder.NewAtomContainer(canonicalForm); + var canonicalMolecule = canonicalForm.Builder.NewAtomContainer(canonicalForm); permutationMap[canonicalMolecule] = labeller.GetCanonicalPermutation(reactant); canonicalReactants.Add(canonicalMolecule); } diff --git a/NCDK/SMSD/Labelling/AtomContainerAtomPermutor.cs b/NCDK/SMSD/Labelling/AtomContainerAtomPermutor.cs index d09545f3..0028e3d6 100644 --- a/NCDK/SMSD/Labelling/AtomContainerAtomPermutor.cs +++ b/NCDK/SMSD/Labelling/AtomContainerAtomPermutor.cs @@ -8,7 +8,7 @@ namespace NCDK.SMSD.Labelling // @cdk.githash public class AtomContainerAtomPermutor : Permutor, IEnumerable { - private IAtomContainer original; + private readonly IAtomContainer original; public AtomContainerAtomPermutor(IAtomContainer atomContainer) : base(atomContainer.Atoms.Count) diff --git a/NCDK/SMSD/Labelling/AtomContainerPrinter.cs b/NCDK/SMSD/Labelling/AtomContainerPrinter.cs index 8e754e80..141d063b 100644 --- a/NCDK/SMSD/Labelling/AtomContainerPrinter.cs +++ b/NCDK/SMSD/Labelling/AtomContainerPrinter.cs @@ -6,7 +6,7 @@ namespace NCDK.SMSD.Labelling { // @cdk.module smsd // @cdk.githash - public class AtomContainerPrinter + public static class AtomContainerPrinter { private class Edge : IComparable { @@ -43,7 +43,7 @@ public override string ToString() } } - public string ToString(IAtomContainer atomContainer) + public static string ToString(IAtomContainer atomContainer) { StringBuilder sb = new StringBuilder(); foreach (var atom in atomContainer.Atoms) diff --git a/NCDK/SMSD/Labelling/CanonicalLabellingAdaptor.cs b/NCDK/SMSD/Labelling/CanonicalLabellingAdaptor.cs index 94cd7dac..ea1d9274 100644 --- a/NCDK/SMSD/Labelling/CanonicalLabellingAdaptor.cs +++ b/NCDK/SMSD/Labelling/CanonicalLabellingAdaptor.cs @@ -21,7 +21,7 @@ public int[] GetCanonicalPermutation(IAtomContainer container) for (int i = 0; i < n; i++) { IAtom a = container.Atoms[i]; - int x = (int)a.GetProperty(InvPair.CanonicalLabelKey); + int x = (int)a.GetProperty(InvPair.CanonicalLabelPropertyKey); perm[i] = x - 1; } return perm; diff --git a/NCDK/SMSD/Labelling/ICanonicalMoleculeLabeller.cs b/NCDK/SMSD/Labelling/ICanonicalMoleculeLabeller.cs index 8c110228..e650e506 100644 --- a/NCDK/SMSD/Labelling/ICanonicalMoleculeLabeller.cs +++ b/NCDK/SMSD/Labelling/ICanonicalMoleculeLabeller.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace NCDK.SMSD.Labelling { diff --git a/NCDK/SMSD/Ring/HanserRingFinder.cs b/NCDK/SMSD/Rings/HanserRingFinder.cs similarity index 99% rename from NCDK/SMSD/Ring/HanserRingFinder.cs rename to NCDK/SMSD/Rings/HanserRingFinder.cs index 54eb6e33..d1091378 100644 --- a/NCDK/SMSD/Ring/HanserRingFinder.cs +++ b/NCDK/SMSD/Rings/HanserRingFinder.cs @@ -48,7 +48,7 @@ using System.Collections.Generic; -namespace NCDK.SMSD.Ring +namespace NCDK.SMSD.Rings { /// /// Finds the Set of all Rings. This is an implementation of the algorithm diff --git a/NCDK/SMSD/Ring/IRingFinder.cs b/NCDK/SMSD/Rings/IRingFinder.cs similarity index 99% rename from NCDK/SMSD/Ring/IRingFinder.cs rename to NCDK/SMSD/Rings/IRingFinder.cs index 3e24a957..9e666b41 100644 --- a/NCDK/SMSD/Ring/IRingFinder.cs +++ b/NCDK/SMSD/Rings/IRingFinder.cs @@ -49,7 +49,7 @@ using System; using System.Collections.Generic; -namespace NCDK.SMSD.Ring +namespace NCDK.SMSD.Rings { // @cdk.module smsd // @cdk.githash diff --git a/NCDK/SMSD/Ring/PathEdge.cs b/NCDK/SMSD/Rings/PathEdge.cs similarity index 98% rename from NCDK/SMSD/Ring/PathEdge.cs rename to NCDK/SMSD/Rings/PathEdge.cs index 5c23a059..e8bb9171 100644 --- a/NCDK/SMSD/Ring/PathEdge.cs +++ b/NCDK/SMSD/Rings/PathEdge.cs @@ -49,7 +49,7 @@ using System; using System.Collections.Generic; -namespace NCDK.SMSD.Ring +namespace NCDK.SMSD.Rings { // @cdk.module smsd // @cdk.githash @@ -105,7 +105,7 @@ public PathEdge Splice(PathEdge other) return new PathEdge(newAtoms); } - private bool IsRealPath(List atoms) + private static bool IsRealPath(List atoms) { for (int i = 1; i < atoms.Count - 1; i++) { diff --git a/NCDK/SMSD/Ring/PathGraph.cs b/NCDK/SMSD/Rings/PathGraph.cs similarity index 98% rename from NCDK/SMSD/Ring/PathGraph.cs rename to NCDK/SMSD/Rings/PathGraph.cs index 62e86dd2..cdc5bf2d 100644 --- a/NCDK/SMSD/Ring/PathGraph.cs +++ b/NCDK/SMSD/Rings/PathGraph.cs @@ -50,7 +50,7 @@ using System.Collections.Generic; using System.Linq; -namespace NCDK.SMSD.Ring +namespace NCDK.SMSD.Rings { // @cdk.module smsd // @cdk.githash @@ -120,7 +120,7 @@ public IList Remove(IAtom atom) return result; } - private IEnumerable SpliceEdges(List edges) + private static IEnumerable SpliceEdges(List edges) { for (int i = 0; i < edges.Count; i++) { diff --git a/NCDK/SMSD/Ring/RingFilter.cs b/NCDK/SMSD/Rings/RingFilter.cs similarity index 99% rename from NCDK/SMSD/Ring/RingFilter.cs rename to NCDK/SMSD/Rings/RingFilter.cs index 6be535d7..9080e4ab 100644 --- a/NCDK/SMSD/Ring/RingFilter.cs +++ b/NCDK/SMSD/Rings/RingFilter.cs @@ -50,7 +50,7 @@ using System; using System.Collections.Generic; -namespace NCDK.SMSD.Ring +namespace NCDK.SMSD.Rings { // @cdk.module smsd // @cdk.githash diff --git a/NCDK/SMSD/Tools/BondEnergies.cs b/NCDK/SMSD/Tools/BondEnergies.cs index a5b6c776..dcfb2fc5 100644 --- a/NCDK/SMSD/Tools/BondEnergies.cs +++ b/NCDK/SMSD/Tools/BondEnergies.cs @@ -222,7 +222,7 @@ protected internal BondEnergies() /// (single, double etc) /// bond energy /// - public int GetEnergies(IAtom sourceAtom, IAtom targetAtom, BondOrder bondOrder) + public virtual int GetEnergies(IAtom sourceAtom, IAtom targetAtom, BondOrder bondOrder) { int dKJPerMol = -1; @@ -253,7 +253,7 @@ public int GetEnergies(IAtom sourceAtom, IAtom targetAtom, BondOrder bondOrder) /// (single, double etc) /// bond energy /// - public int GetEnergies(string sourceAtom, string targetAtom, BondOrder bondOrder) + public static int GetEnergies(string sourceAtom, string targetAtom, BondOrder bondOrder) { int dKJPerMol = -1; @@ -283,7 +283,7 @@ public int GetEnergies(string sourceAtom, string targetAtom, BondOrder bondOrder /// (single, double etc) /// bond energy /// - public int GetEnergies(IBond bond) + public static int GetEnergies(IBond bond) { int dKJPerMol = -1; foreach (var entry in bondEngergies) @@ -297,7 +297,7 @@ public int GetEnergies(IBond bond) return dKJPerMol; } - private int SetHydrogenBlock(int key) + private static int SetHydrogenBlock(int key) { bondEngergies[key++] = new BondEnergy("H", "H", BondOrder.Single, 432); bondEngergies[key++] = new BondEnergy("H", "B", BondOrder.Single, 389); @@ -319,9 +319,8 @@ private int SetHydrogenBlock(int key) return key; } - private int SetGroup13(int key) + private static int SetGroup13(int key) { - bondEngergies[key++] = new BondEnergy("B", "B", BondOrder.Single, 293); bondEngergies[key++] = new BondEnergy("B", "O", BondOrder.Single, 536); bondEngergies[key++] = new BondEnergy("B", "F", BondOrder.Single, 613); @@ -330,7 +329,7 @@ private int SetGroup13(int key) return key; } - private int SetGroup14Part1(int key) + private static int SetGroup14Part1(int key) { bondEngergies[key++] = new BondEnergy("C", "C", BondOrder.Single, 346); bondEngergies[key++] = new BondEnergy("C", "C", BondOrder.Double, 602); @@ -356,7 +355,7 @@ private int SetGroup14Part1(int key) return key; } - private int SetGroup14Part2(int key) + private static int SetGroup14Part2(int key) { bondEngergies[key++] = new BondEnergy("Si", "Si", BondOrder.Single, 222); @@ -387,7 +386,7 @@ private int SetGroup14Part2(int key) return key; } - private int SetGroup15(int key) + private static int SetGroup15(int key) { bondEngergies[key++] = new BondEnergy("N", "N", BondOrder.Single, 167); bondEngergies[key++] = new BondEnergy("N", "N", BondOrder.Double, 418); @@ -423,7 +422,7 @@ private int SetGroup15(int key) } - private int SetGroup16(int key) + private static int SetGroup16(int key) { bondEngergies[key++] = new BondEnergy("O", "O", BondOrder.Single, 142); @@ -441,7 +440,7 @@ private int SetGroup16(int key) } - private int SetGroup17(int key) + private static int SetGroup17(int key) { bondEngergies[key++] = new BondEnergy("F", "F", BondOrder.Single, 155); bondEngergies[key++] = new BondEnergy("Cl", "Cl", BondOrder.Single, 240); @@ -457,7 +456,7 @@ private int SetGroup17(int key) } - private int SetGroup18(int key) + private static int SetGroup18(int key) { bondEngergies[key++] = new BondEnergy("Kr", "F", BondOrder.Single, 50); bondEngergies[key++] = new BondEnergy("Xe", "O", BondOrder.Single, 84); diff --git a/NCDK/SMSD/Tools/ExtAtomContainerManipulator.cs b/NCDK/SMSD/Tools/ExtAtomContainerManipulator.cs index 0aee5635..e2799d3d 100644 --- a/NCDK/SMSD/Tools/ExtAtomContainerManipulator.cs +++ b/NCDK/SMSD/Tools/ExtAtomContainerManipulator.cs @@ -42,7 +42,7 @@ namespace NCDK.SMSD.Tools // @cdk.module smsd // @cdk.githash // @author Syed Asad Rahman - public class ExtAtomContainerManipulator + public static class ExtAtomContainerManipulator { private static void PrintAtoms(IAtomContainer mol) { @@ -155,7 +155,7 @@ public static int GetExplicitHydrogenCount(IAtomContainer atomContainer, IAtom a foreach (var iAtom in atomContainer.GetConnectedAtoms(atom)) { IAtom connectedAtom = iAtom; - if (connectedAtom.Symbol.Equals("H")) + if (string.Equals(connectedAtom.Symbol, "H", StringComparison.Ordinal)) { hCount++; } @@ -199,7 +199,7 @@ public static IAtomContainer RemoveHydrogensExceptSingleAndPreserveAtomID(IAtomC List remove = new List(); // lists removed Hs. foreach (var atom in atomContainer.Atoms) { - if (atom.Symbol.Equals("H")) + if (string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) remove.Add(atom); } foreach (var a in remove) diff --git a/NCDK/SMSD/Tools/MolHandler.cs b/NCDK/SMSD/Tools/MolHandler.cs index 3a82ce4d..23524756 100644 --- a/NCDK/SMSD/Tools/MolHandler.cs +++ b/NCDK/SMSD/Tools/MolHandler.cs @@ -24,9 +24,9 @@ */ using NCDK.Aromaticities; -using NCDK.Default; using NCDK.Geometries; using NCDK.IO; +using NCDK.Silent; using NCDK.SMSD.Labelling; using NCDK.Tools; using System; diff --git a/NCDK/SMSD/Tools/MoleculeSanityCheck.cs b/NCDK/SMSD/Tools/MoleculeSanityCheck.cs index 5b85ceb0..9417487f 100644 --- a/NCDK/SMSD/Tools/MoleculeSanityCheck.cs +++ b/NCDK/SMSD/Tools/MoleculeSanityCheck.cs @@ -26,6 +26,7 @@ using NCDK.Aromaticities; using NCDK.Graphs; using NCDK.RingSearches; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -39,7 +40,7 @@ namespace NCDK.SMSD.Tools // @cdk.githash // @author Syed Asad Rahman [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd . ")] - public class MoleculeSanityCheck + public static class MoleculeSanityCheck { /// /// Modules for cleaning a molecule @@ -51,7 +52,7 @@ public static IAtomContainer CheckAndCleanMolecule(IAtomContainer molecule) bool isMarkush = false; foreach (var atom in molecule.Atoms) { - if (atom.Symbol.Equals("R")) + if (string.Equals(atom.Symbol, "R", StringComparison.Ordinal)) { isMarkush = true; break; @@ -76,8 +77,8 @@ public static IAtomContainer CheckAndCleanMolecule(IAtomContainer molecule) } else { - IAtomContainer frag1 = fragments[0]; - IAtomContainer frag2 = fragments[1]; + var frag1 = fragments[0]; + var frag2 = fragments[1]; if (frag1.Atoms.Count > frag2.Atoms.Count) { molecule = frag1; @@ -104,7 +105,7 @@ public static void Configure(IAtomContainer mol) IRingSet ringSet = null; try { - AllRingsFinder arf = new AllRingsFinder(); + var arf = new AllRingsFinder(); ringSet = arf.FindAllRings(mol); } catch (Exception e) @@ -115,7 +116,7 @@ public static void Configure(IAtomContainer mol) try { // figure out which atoms are in aromatic rings: - CDKHydrogenAdder cdk = CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance); + var cdk = CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance); ExtAtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); cdk.AddImplicitHydrogens(mol); diff --git a/NCDK/SMSD/Tools/TimeManager.cs b/NCDK/SMSD/Tools/TimeManager.cs index c49e1cbc..4ba07eb4 100644 --- a/NCDK/SMSD/Tools/TimeManager.cs +++ b/NCDK/SMSD/Tools/TimeManager.cs @@ -34,7 +34,7 @@ namespace NCDK.SMSD.Tools [Obsolete("SMSD has been deprecated from the CDK with a newer, more recent version of SMSD is available at http://github.com/asad/smsd .")] public class TimeManager { - private DateTime startTime; + private readonly DateTime startTime; //private SimpleDateFormat dateFormat; /// diff --git a/NCDK/Sgroups/SgroupKey.cs b/NCDK/Sgroups/SgroupKey.cs index bdfd9dd4..6de8a0ad 100644 --- a/NCDK/Sgroups/SgroupKey.cs +++ b/NCDK/Sgroups/SgroupKey.cs @@ -21,10 +21,6 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ -using System.Collections.Generic; -using System.Linq; -using static NCDK.Sgroups.SgroupKey; - namespace NCDK.Sgroups { /// @@ -52,10 +48,5 @@ public enum SgroupKey CtabParentAtomList, CtabComponentNumber, } - - public static class SgroupKeyTools - { - public static IReadOnlyList Values { get; } = System.Enum.GetValues(typeof(SgroupKey)).Cast().ToArray(); - } } diff --git a/NCDK/Sgroups/SgroupType.cs b/NCDK/Sgroups/SgroupType.cs index 596c78dc..398e1e20 100644 --- a/NCDK/Sgroups/SgroupType.cs +++ b/NCDK/Sgroups/SgroupType.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using System.Reflection; namespace NCDK.Sgroups @@ -126,49 +127,4 @@ public enum SgroupType // extension for handling positional variation and distributed coordination bonds ExtMulticenter, } - - public static class SgroupTypeTools - { - private static readonly string[] ctabKeys = new string[] - { - "", - "SUP", - "MUL", - "SRU", - "MON", - "MOD", - "COP", - "MER", - "CRO", - "GRA", - "ANY", - "COM", - "MIX", - "FOR", - "DAT", - "GEN", - "N/A", - }; - - private static readonly Dictionary map; - - static SgroupTypeTools() - { - map = new Dictionary(); - for (int i = 0; i < ctabKeys.Length; i++) - { - map.Add(ctabKeys[i], (SgroupType)i); - } - } - - public static string Key(this SgroupType value) - => ctabKeys[(int)value]; - - public static SgroupType Parse(string str) - { - if (!map.TryGetValue(str, out SgroupType o)) - return SgroupType.CtabGeneric; - return o; - } - } } diff --git a/NCDK/Signatures/AtomSignature.cs b/NCDK/Signatures/AtomSignature.cs index 3d515ce6..3e3471e2 100644 --- a/NCDK/Signatures/AtomSignature.cs +++ b/NCDK/Signatures/AtomSignature.cs @@ -209,27 +209,21 @@ public override string GetVertexSymbol(int vertexIndex) /// public override int ConvertEdgeLabelToColor(string edgeLabel) { - if (edgeLabel.Equals("")) + switch (edgeLabel) { - return 1; + case "": + return 1; + case "=": + return 2; + case "#": + return 3; + case "$": + return 4; + case "p": + return 5; + default: + return 0; } - else if (edgeLabel.Equals("=")) - { - return 2; - } - else if (edgeLabel.Equals("#")) - { - return 3; - } - else if (edgeLabel.Equals("$")) - { - return 4; - } - else if (edgeLabel.Equals("p")) - { - return 5; - } - return 0; } } } diff --git a/NCDK/Signatures/MoleculeFromSignatureBuilder.cs b/NCDK/Signatures/MoleculeFromSignatureBuilder.cs index 8bff1e27..aa36b5d5 100644 --- a/NCDK/Signatures/MoleculeFromSignatureBuilder.cs +++ b/NCDK/Signatures/MoleculeFromSignatureBuilder.cs @@ -22,6 +22,7 @@ */ using NCDK.FaulonSignatures; +using System; namespace NCDK.Signatures { @@ -53,27 +54,26 @@ public MoleculeFromSignatureBuilder(IChemObjectBuilder builder) } /// - public override void MakeEdge(int vertexIndex1, int vertexIndex2, string vertexSymbol1, string vertexSymbol2, - string edgeLabel) + public override void MakeEdge(int vertexIndex1, int vertexIndex2, string vertexSymbol1, string vertexSymbol2, string edgeLabel) { - if (edgeLabel.Equals("")) + switch (edgeLabel) { - container.AddBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Single); - } - else if (edgeLabel.Equals("=")) - { - container.AddBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Double); - } - else if (edgeLabel.Equals("#")) - { - container.AddBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Triple); - } - else if (edgeLabel.Equals("p")) - { - IBond bond = builder.NewBond(container.Atoms[vertexIndex1], - container.Atoms[vertexIndex2], BondOrder.Single); - bond.IsAromatic = true; - container.Bonds.Add(bond); + case "": + container.AddBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Single); + break; + case "=": + container.AddBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Double); + break; + case "#": + container.AddBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Triple); + break; + case "p": + IBond bond = builder.NewBond(container.Atoms[vertexIndex1], container.Atoms[vertexIndex2], BondOrder.Single); + bond.IsAromatic = true; + container.Bonds.Add(bond); + break; + default: + break; } } diff --git a/NCDK/Signatures/MoleculeSignature.cs b/NCDK/Signatures/MoleculeSignature.cs index e2e4379c..7c6cb4b1 100644 --- a/NCDK/Signatures/MoleculeSignature.cs +++ b/NCDK/Signatures/MoleculeSignature.cs @@ -70,7 +70,7 @@ public class MoleculeSignature : AbstractGraphSignature /// /// The molecule to use when making atom signatures /// - private IAtomContainer molecule; + private readonly IAtomContainer molecule; /// /// Creates a signature that represents this molecule. @@ -175,7 +175,7 @@ public string ToCanonicalSignatureString(int height) for (int i = 0; i < GetVertexCount(); i++) { string signatureForI = SignatureStringForVertex(i, height); - if (canonicalSignature == null || canonicalSignature.CompareTo(signatureForI) < 0) + if (canonicalSignature == null || string.CompareOrdinal(canonicalSignature, signatureForI) < 0) { canonicalSignature = signatureForI; } diff --git a/NCDK/Signatures/Orbit.cs b/NCDK/Signatures/Orbit.cs index a2ce6358..3a783eb0 100644 --- a/NCDK/Signatures/Orbit.cs +++ b/NCDK/Signatures/Orbit.cs @@ -37,31 +37,18 @@ namespace NCDK.Signatures // @cdk.githash public class Orbit : IEnumerable, ICloneable { - /// - /// The atom indices in this orbit - /// - private List atomIndices; - - /// - /// The label that all the atoms in the orbit share - /// - private string label; - - /// - /// The maximum height of the signature string - /// - private int height; - + private readonly List atomIndices; + public Orbit(string label, int height) { - this.label = label; + this.Label = label; this.atomIndices = new List(); - this.height = height; + this.Height = height; } public IEnumerator GetEnumerator() { - return this.atomIndices.GetEnumerator(); + return this.AtomIndices.GetEnumerator(); throw new NotImplementedException(); } @@ -72,8 +59,8 @@ IEnumerator IEnumerable.GetEnumerator() public object Clone() { - Orbit orbit = new Orbit(this.label, this.height); - foreach (var i in this.atomIndices) + Orbit orbit = new Orbit(this.Label, this.Height); + foreach (var i in this.AtomIndices) { orbit.atomIndices.Add(i); } @@ -92,12 +79,12 @@ public void Sort() /// /// The height of the signature of this orbit. /// - public int Height => this.height; + public int Height { get; } /// /// All the atom indices as a list. /// - public List AtomIndices => this.atomIndices; + public IReadOnlyList AtomIndices => atomIndices; /// /// Adds an atom index to the orbit. @@ -115,7 +102,7 @@ public void AddAtomAt(int atomIndex) /// if it has this label public bool HasLabel(string otherLabel) { - return this.label.Equals(otherLabel); + return this.Label.Equals(otherLabel, StringComparison.Ordinal); } /// @@ -124,13 +111,13 @@ public bool HasLabel(string otherLabel) /// if there are no atom indices in the orbit public bool IsEmpty() { - return !this.atomIndices.Any(); + return !this.AtomIndices.Any(); } /// /// The first atom index of the orbit. /// - public int FirstAtom => this.atomIndices[0]; + public int FirstAtom => this.AtomIndices[0]; /// /// Removes an atom index from the orbit. @@ -144,7 +131,7 @@ public void Remove(int atomIndex) /// /// The label of the orbit. /// - public string Label => this.label; + public string Label { get; } /// /// Checks to see if the orbit contains this atom index. @@ -153,12 +140,12 @@ public void Remove(int atomIndex) /// if the orbit contains this atom index public bool Contains(int atomIndex) { - return this.atomIndices.Contains(atomIndex); + return this.AtomIndices.Contains(atomIndex); } public override string ToString() { - return label + " " + Arrays.DeepToString(atomIndices.ToArray()); + return Label + " " + Arrays.DeepToString(AtomIndices.ToArray()); } } } diff --git a/NCDK/Similarity/LingoSimilarity.cs b/NCDK/Similarity/LingoSimilarity.cs index 0b2077ef..742452ea 100644 --- a/NCDK/Similarity/LingoSimilarity.cs +++ b/NCDK/Similarity/LingoSimilarity.cs @@ -39,16 +39,14 @@ namespace NCDK.Similarity // @cdk.keyword lingo // @cdk.keyword similarity, tanimoto // @cdk.module fingerprint - public class LingoSimilarity + public static class LingoSimilarity { - private LingoSimilarity() { } - /// /// Evaluate the LINGO similarity between two key,value sty;e fingerprints. /// The value will range from 0.0 to 1.0. /// /// similarity - public static double Calculate(IDictionary features1, IDictionary features2) + public static double Calculate(IReadOnlyDictionary features1, IReadOnlyDictionary features2) { var keys = features1.Keys.Union(features2.Keys).ToList(); diff --git a/NCDK/Similarity/Tanimoto.cs b/NCDK/Similarity/Tanimoto.cs index 24f7034b..92c2e87e 100644 --- a/NCDK/Similarity/Tanimoto.cs +++ b/NCDK/Similarity/Tanimoto.cs @@ -85,7 +85,7 @@ public static double Calculate(BitArray bitset1, BitArray bitset2) /// if bitsets are not of the same length public static double Calculate(IBitFingerprint fingerprint1, IBitFingerprint fingerprint2) { - if (fingerprint1.Count != fingerprint2.Count) + if (fingerprint1.Length != fingerprint2.Length) { throw new ArgumentException("Fingerprints must have the same size"); } @@ -139,7 +139,7 @@ public static double Calculate(double[] features1, double[] features2) /// The first feature map /// The second feature map /// The Tanimoto coefficient - public static double Calculate(IDictionary features1, IDictionary features2) + public static double Calculate(IReadOnlyDictionary features1, IReadOnlyDictionary features2) { var common = features1.Keys.Intersect(features2.Keys); double xy = 0, x = 0, y = 0; diff --git a/NCDK/Smiles/BeamToCDK.cs b/NCDK/Smiles/BeamToCDK.cs index 246213da..a6d1a22a 100644 --- a/NCDK/Smiles/BeamToCDK.cs +++ b/NCDK/Smiles/BeamToCDK.cs @@ -165,8 +165,7 @@ public IAtomContainer ToAtomContainer(Graph g, bool kekule) bond.Order = BondOrder.Quadruple; break; default: - throw new ArgumentException("Edge label " + edge.Bond - + "cannot be converted to a CDK bond order"); + throw new ArgumentException($"Edge label {edge.Bond} cannot be converted to a CDK bond order"); } } @@ -239,11 +238,12 @@ public IAtomContainer ToAtomContainer(Graph g, bool kekule) /// /// Beam graph object (for directional bonds) /// The atom-container built from the Beam graph - private void AddDoubleBondStereochemistry(Graph g, IAtomContainer ac) + private static void AddDoubleBondStereochemistry(Graph g, IAtomContainer ac) { foreach (var e in g.Edges) { - if (e.Bond != Bond.Double) continue; + if (e.Bond != Bond.Double) + continue; int u = e.Either(); int v = e.Other(u); @@ -259,15 +259,18 @@ private void AddDoubleBondStereochemistry(Graph g, IAtomContainer ac) // if the directions (relative to the double bond) are the // same then they are on the same side - otherwise they // are opposite - DoubleBondConformation conformation = first.GetBond(u) == second.GetBond(v) ? DoubleBondConformation.Together : DoubleBondConformation.Opposite; + var conformation = first.GetBond(u) == second.GetBond(v) ? DoubleBondConformation.Together : DoubleBondConformation.Opposite; // get the stereo bond and build up the ligands for the // stereo-element - linear search could be improved with // map or API change to double bond element - IBond db = ac.GetBond(ac.Atoms[u], ac.Atoms[v]); + var db = ac.GetBond(ac.Atoms[u], ac.Atoms[v]); - IBond[] ligands = new IBond[]{ac.GetBond(ac.Atoms[u], ac.Atoms[first.Other(u)]), - ac.GetBond(ac.Atoms[v], ac.Atoms[second.Other(v)])}; + var ligands = new IBond[] + { + ac.GetBond(ac.Atoms[u], ac.Atoms[first.Other(u)]), + ac.GetBond(ac.Atoms[v], ac.Atoms[second.Other(v)]) + }; ac.StereoElements.Add(new DoubleBondStereochemistry(db, ligands, conformation)); } @@ -276,10 +279,9 @@ private void AddDoubleBondStereochemistry(Graph g, IAtomContainer ac) { Beam.Configuration uConf = g.ConfigurationOf(u); Beam.Configuration vConf = g.ConfigurationOf(v); - if (uConf.Type == Beam.Configuration.ConfigurationType.DoubleBond && - vConf.Type == Beam.Configuration.ConfigurationType.DoubleBond) + if (uConf.Type == Beam.Configuration.ConfigurationType.DoubleBond + && vConf.Type == Beam.Configuration.ConfigurationType.DoubleBond) { - int[] nbrs = new int[6]; int[] uNbrs = g.Neighbors(u); int[] vNbrs = g.Neighbors(v); @@ -372,7 +374,7 @@ private void AddDoubleBondStereochemistry(Graph g, IAtomContainer ac) /// graph from Beam /// the vertex for which to find /// first directional edge (or if none) - private Edge FindDirectionalEdge(Graph g, int u) + private static Edge FindDirectionalEdge(Graph g, int u) { var edges = g.GetEdges(u); if (edges.Count == 1) @@ -394,14 +396,15 @@ private Edge FindDirectionalEdge(Graph g, int u) /// array of the CDK atoms (pre-converted) /// the configuration of the neighbors (vs) for the order they are given /// tetrahedral stereo element for addition to an atom container - private IReadOnlyStereoElement NewTetrahedral(int u, int[] vs, IAtom[] atoms, Beam.Configuration c) + private static IStereoElement NewTetrahedral(int u, int[] vs, IAtom[] atoms, Beam.Configuration c) { // no way to handle tetrahedral configurations with implicit // hydrogen or lone pair at the moment if (vs.Length != 4) { // sanity check - if (vs.Length != 3) return null; + if (vs.Length != 3) + return null; // there is an implicit hydrogen (or lone-pair) we insert the // central atom in sorted position @@ -409,12 +412,12 @@ private IReadOnlyStereoElement NewTetrahedral(int u, i } // @TH1/@TH2 = anti-clockwise and clockwise respectively - TetrahedralStereo stereo = c == Beam.Configuration.TH1 ? TetrahedralStereo.AntiClockwise : TetrahedralStereo.Clockwise; + var stereo = c == Beam.Configuration.TH1 ? TetrahedralStereo.AntiClockwise : TetrahedralStereo.Clockwise; return new TetrahedralChirality(atoms[u], new IAtom[] { atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]] }, stereo); } - private IReadOnlyStereoElement NewSquarePlanar(int u, int[] vs, IAtom[] atoms, Configuration c) + private static IStereoElement NewSquarePlanar(int u, int[] vs, IAtom[] atoms, Configuration c) { if (vs.Length != 4) return null; @@ -423,36 +426,32 @@ private IReadOnlyStereoElement NewSquarePlanar(int u, switch (c.Ordinal) { case Configuration.O.SP1: - order = new StereoElement(StereoElement.Classes.SquarePlanar, 1); + order = new StereoElement(StereoClass.SquarePlanar, 1); break; case Configuration.O.SP2: - order = new StereoElement(StereoElement.Classes.SquarePlanar, 2); + order = new StereoElement(StereoClass.SquarePlanar, 2); break; case Configuration.O.SP3: - order = new StereoElement(StereoElement.Classes.SquarePlanar, 3); + order = new StereoElement(StereoClass.SquarePlanar, 3); break; default: return null; } - return new SquarePlanar(atoms[u], - new IAtom[] { atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]] }, - order); + return new SquarePlanar(atoms[u], new IAtom[] { atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]] }, order); } - private IReadOnlyStereoElement NewTrigonalBipyramidal(int u, int[] vs, IAtom[] atoms, Configuration c) + private static IStereoElement NewTrigonalBipyramidal(int u, int[] vs, IAtom[] atoms, Configuration c) { if (vs.Length != 5) return null; int order = 1 + c.Ordinal - Configuration.TB1.Ordinal; if (order < 1 || order > 20) return null; - return new TrigonalBipyramidal(atoms[u], - new IAtom[] { atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]], atoms[vs[4]] }, - order); + return new TrigonalBipyramidal(atoms[u], new IAtom[] { atoms[vs[0]], atoms[vs[1]], atoms[vs[2]], atoms[vs[3]], atoms[vs[4]] }, order); } - private IReadOnlyStereoElement NewOctahedral(int u, int[] vs, IAtom[] atoms, Configuration c) + private static IStereoElement NewOctahedral(int u, int[] vs, IAtom[] atoms, Configuration c) { if (vs.Length != 6) return null; @@ -469,7 +468,7 @@ private IReadOnlyStereoElement NewOctahedral(int u, in order); } - private IReadOnlyStereoElement NewExtendedTetrahedral(int u, Graph g, IAtom[] atoms) + private static IStereoElement NewExtendedTetrahedral(int u, Graph g, IAtom[] atoms) { int[] terminals = g.Neighbors(u); int[] xs = new int[] { -1, terminals[0], -1, terminals[1] }; @@ -528,11 +527,14 @@ public IAtom ToCDKAtom(Beam.IAtom beamAtom, int hCount) cdkAtom.ImplicitHydrogenCount = hCount; cdkAtom.FormalCharge = beamAtom.Charge; - if (beamAtom.Isotope >= 0) cdkAtom.MassNumber = beamAtom.Isotope; + if (beamAtom.Isotope >= 0) + cdkAtom.MassNumber = beamAtom.Isotope; - if (beamAtom.IsAromatic()) cdkAtom.IsAromatic = true; + if (beamAtom.IsAromatic()) + cdkAtom.IsAromatic = true; - if (beamAtom.AtomClass > 0) cdkAtom.SetProperty(CDKPropertyName.AtomAtomMapping, beamAtom.AtomClass); + if (beamAtom.AtomClass > 0) + cdkAtom.SetProperty(CDKPropertyName.AtomAtomMapping, beamAtom.AtomClass); return cdkAtom; } diff --git a/NCDK/Smiles/CDKToBeam.cs b/NCDK/Smiles/CDKToBeam.cs index 4723b9f9..d3292b5a 100644 --- a/NCDK/Smiles/CDKToBeam.cs +++ b/NCDK/Smiles/CDKToBeam.cs @@ -23,6 +23,7 @@ */ using NCDK.Beam; +using NCDK.Config; using NCDK.Stereo; using System; using System.Collections.Generic; @@ -58,15 +59,15 @@ internal sealed class CDKToBeam /// Whether to convert the molecule with isotope and stereo information - /// Isomeric SMILES. /// - private readonly SmiFlavor flavour; + private readonly SmiFlavors flavour; /// Create a isomeric and aromatic converter. internal CDKToBeam() - : this(SmiFlavor.AtomicMass | SmiFlavor.AtomAtomMap | SmiFlavor.UseAromaticSymbols) + : this(SmiFlavors.AtomicMass | SmiFlavors.AtomAtomMap | SmiFlavors.UseAromaticSymbols) { } - internal CDKToBeam(SmiFlavor flavour) + internal CDKToBeam(SmiFlavors flavour) { this.flavour = flavour; } @@ -98,7 +99,7 @@ internal Edge ToBeamEdge(IBond b, IDictionary indices) /// /// an atom container instance /// the Beam ChemicalGraph for additional manipulation - internal static Graph ToBeamGraph(IAtomContainer ac, SmiFlavor flavour) + internal static Graph ToBeamGraph(IAtomContainer ac, SmiFlavors flavour) { int order = ac.Atoms.Count; @@ -117,21 +118,21 @@ internal static Graph ToBeamGraph(IAtomContainer ac, SmiFlavor flavour) } // configure stereo-chemistry by encoding the stereo-elements - if (SmiFlavors.IsSet(flavour, SmiFlavor.Stereo)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.Stereo)) { foreach (var se in ac.StereoElements) { - if (SmiFlavors.IsSet(flavour, SmiFlavor.StereoTetrahedral) && + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.StereoTetrahedral) && se is ITetrahedralChirality) { AddTetrahedralConfiguration((ITetrahedralChirality)se, gb, indices); } - else if (SmiFlavors.IsSet(flavour, SmiFlavor.StereoCisTrans) && + else if (SmiFlavorTool.IsSet(flavour, SmiFlavors.StereoCisTrans) && se is IDoubleBondStereochemistry) { AddGeometricConfiguration((IDoubleBondStereochemistry)se, flavour, gb, indices); } - else if (SmiFlavors.IsSet(flavour, SmiFlavor.StereoExTetrahedral) && + else if (SmiFlavorTool.IsSet(flavour, SmiFlavors.StereoExTetrahedral) && se is ExtendedTetrahedral) { AddExtendedTetrahedralConfiguration((ExtendedTetrahedral)se, gb, indices); @@ -160,8 +161,8 @@ internal static Graph ToBeamGraph(IAtomContainer ac, SmiFlavor flavour) case 17: return 35; case 53: return 127; default: - Config.IsotopeFactory isotopes = Config.Isotopes.Instance; - IIsotope isotope = isotopes.GetMajorIsotope(e.Symbol); + var isotopes = BODRIsotopeFactory.Instance; + var isotope = isotopes.GetMajorIsotope(e.Symbol); if (isotope != null) return isotope.MassNumber; return null; @@ -182,9 +183,9 @@ internal static Graph ToBeamGraph(IAtomContainer ac, SmiFlavor flavour) /// cdk Atom instance /// a Beam atom /// the atom had an undefined symbol or implicit hydrogen count - static Beam.IAtom ToBeamAtom(IAtom a, SmiFlavor flavour) + static Beam.IAtom ToBeamAtom(IAtom a, SmiFlavors flavour) { - bool aromatic = SmiFlavors.IsSet(flavour, SmiFlavor.UseAromaticSymbols) && a.IsAromatic; + bool aromatic = SmiFlavorTool.IsSet(flavour, SmiFlavors.UseAromaticSymbols) && a.IsAromatic; int? charge = a.FormalCharge; string symbol = CheckNotNull(a.Symbol, "An atom had an undefined symbol"); @@ -207,7 +208,7 @@ static Beam.IAtom ToBeamAtom(IAtom a, SmiFlavor flavour) if (charge.HasValue) ab.Charge(charge.Value); // use the mass number to specify isotope? - if (SmiFlavors.IsSet(flavour, SmiFlavor.AtomicMass | SmiFlavor.AtomicMassStrict)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.AtomicMass | SmiFlavors.AtomicMassStrict)) { var massNumber = a.MassNumber; if (massNumber != null) @@ -217,7 +218,7 @@ static Beam.IAtom ToBeamAtom(IAtom a, SmiFlavor flavour) } int? atomClass = a.GetProperty(CDKPropertyName.AtomAtomMapping); - if (SmiFlavors.IsSet(flavour, SmiFlavor.AtomAtomMap) && atomClass != null) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.AtomAtomMap) && atomClass != null) { ab.AtomClass(atomClass.Value); } @@ -233,7 +234,7 @@ static Beam.IAtom ToBeamAtom(IAtom a, SmiFlavor flavour) /// a Beam edge /// the bond did not have 2 atoms or an unsupported order /// the bond order was undefined - internal static Edge ToBeamEdge(IBond b, SmiFlavor flavour, IDictionary indices) + internal static Edge ToBeamEdge(IBond b, SmiFlavors flavour, IDictionary indices) { CheckArgument(b.Atoms.Count == 2, "Invalid number of atoms on bond"); @@ -250,9 +251,9 @@ internal static Edge ToBeamEdge(IBond b, SmiFlavor flavour, IDictionarythe edge label for the Beam edge /// the bond order was null and the bond was not-aromatic /// the bond order could not be converted - private static Bond ToBeamEdgeLabel(IBond b, SmiFlavor flavour) + private static Bond ToBeamEdgeLabel(IBond b, SmiFlavors flavour) { - if (SmiFlavors.IsSet(flavour, SmiFlavor.UseAromaticSymbols) && b.IsAromatic) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.UseAromaticSymbols) && b.IsAromatic) { if (!b.Begin.IsAromatic || !b.End.IsAromatic) throw new InvalidOperationException("Aromatic bond connects non-aromatic atomic atoms"); @@ -284,13 +285,13 @@ private static Bond ToBeamEdgeLabel(IBond b, SmiFlavor flavour) /// stereo element specifying double-bond configuration /// the current graph builder /// atom indices - private static void AddGeometricConfiguration(IDoubleBondStereochemistry dbs, SmiFlavor flavour, GraphBuilder gb, IDictionary indices) + private static void AddGeometricConfiguration(IDoubleBondStereochemistry dbs, SmiFlavors flavour, GraphBuilder gb, IDictionary indices) { IBond db = dbs.StereoBond; var bs = dbs.Bonds; // don't try to set a configuration on aromatic bonds - if (SmiFlavors.IsSet(flavour, SmiFlavor.UseAromaticSymbols) && db.IsAromatic) return; + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.UseAromaticSymbols) && db.IsAromatic) return; int u = indices[db.Begin]; int v = indices[db.End]; @@ -336,10 +337,9 @@ private static void AddTetrahedralConfiguration(ITetrahedralChirality tc, GraphB /// stereo element specifying tetrahedral configuration /// the current graph builder /// atom indices - private static void AddExtendedTetrahedralConfiguration(ExtendedTetrahedral et, GraphBuilder gb, - IDictionary indices) + private static void AddExtendedTetrahedralConfiguration(ExtendedTetrahedral et, GraphBuilder gb, IDictionary indices) { - IAtom[] ligands = et.Peripherals; + var ligands = et.Peripherals; int u = indices[et.Focus]; int[] vs = new int[]{ diff --git a/NCDK/Smiles/CxSmilesGenerator.cs b/NCDK/Smiles/CxSmilesGenerator.cs index f92cd908..0793156d 100644 --- a/NCDK/Smiles/CxSmilesGenerator.cs +++ b/NCDK/Smiles/CxSmilesGenerator.cs @@ -24,6 +24,7 @@ using NCDK.Common.Primitives; using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; using static NCDK.Smiles.CxSmilesState; @@ -53,7 +54,7 @@ private static string Encode_alias(string label) } else { - sb.Append("&#").Append(c.ToString()).Append(";"); + sb.Append("&#").Append(new string(new[] { c })).Append(";"); } } return sb.ToString(); @@ -72,9 +73,9 @@ private static int Compare(Comparison comp, List a, List b) return alen.CompareTo(blen); } - internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] components, int[] ordering) + internal static string Generate(CxSmilesState state, SmiFlavors opts, int[] components, int[] ordering) { - if (!SmiFlavors.IsSet(opts, SmiFlavor.CxSmilesWithCoords)) + if (!SmiFlavorTool.IsSet(opts, SmiFlavors.CxSmilesWithCoords)) return ""; int[] invorder = Inverse(ordering); @@ -83,11 +84,11 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo sb.Append(' '); sb.Append('|'); - Comparison invComp = (a, b) => invorder[a].CompareTo(invorder[b]); - Comparison comp = (a, b) => ordering[a].CompareTo(ordering[b]); + //int invComp(int a, int b) => invorder[a].CompareTo(invorder[b]); + int comp(int a, int b) => ordering[a].CompareTo(ordering[b]); // Fragment Grouping - if (SmiFlavors.IsSet(opts, SmiFlavor.CxFragmentGroup) && + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxFragmentGroup) && state.fragGroups != null && state.fragGroups.Any()) { int maxCompId = 0; @@ -110,7 +111,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo for (int i = 0; i < compMap.Length; i++) compMap[i]--; - Comparison compComp = (a, b) => compMap[a].CompareTo(compMap[b]); + int compComp(int a, int b) => compMap[a].CompareTo(compMap[b]); List> fragGroupCpy = new List>(state.fragGroups); foreach (var idxs in fragGroupCpy) @@ -128,7 +129,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo } // Atom Labels - if (SmiFlavors.IsSet(opts, SmiFlavor.CxAtomLabel) && + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxAtomLabel) && state.atomLabels != null && state.atomLabels.Any()) { if (sb.Length > 2) @@ -137,8 +138,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo int nonempty_cnt = 0; foreach (int idx in invorder) { - string label; - if (!state.atomLabels.TryGetValue(idx, out label)) + if (!state.atomLabels.TryGetValue(idx, out string label)) label = ""; else nonempty_cnt++; sb.Append(Encode_alias(label)); @@ -151,7 +151,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo } // Atom Values - if (SmiFlavors.IsSet(opts, SmiFlavor.CxAtomValue) && + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxAtomValue) && state.atomValues != null && state.atomValues.Any()) { @@ -174,14 +174,14 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo } // 2D/3D Coordinates - if (SmiFlavors.IsSet(opts, SmiFlavor.CxCoordinates) && - state.AtomCoords != null && state.AtomCoords.Any()) + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxCoordinates) && + state.atomCoords != null && state.atomCoords.Any()) { if (sb.Length > 2) sb.Append(','); sb.Append('('); for (int i = 0; i < ordering.Length; i++) { - double[] xyz = state.AtomCoords[invorder[i]]; + double[] xyz = state.atomCoords[invorder[i]]; if (i != 0) sb.Append(';'); if (xyz[0] != 0) sb.Append(Strings.ToSimpleString(xyz[0], 2)); @@ -196,7 +196,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo } // Multi-center/Positional variation bonds - if (SmiFlavors.IsSet(opts, SmiFlavor.CxMulticenter) && + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxMulticenter) && state.positionVar != null && state.positionVar.Any()) { if (sb.Length > 2) sb.Append(','); @@ -221,7 +221,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo } // *CCO* |$_AP1;;;;_AP2$,Sg:n:1,2,3::ht| - if (SmiFlavors.IsSet(opts, SmiFlavor.CxPolymer) && + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxPolymer) && state.sgroups != null && state.sgroups.Any()) { var sgroups = new List(state.sgroups); @@ -232,8 +232,9 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo sgroups.Sort((a, b) => { int cmp = 0; - cmp = a.type.CompareTo(b.type); - if (cmp != 0) return cmp; + cmp = string.CompareOrdinal(a.type, b.type); + if (cmp != 0) + return cmp; cmp = CxSmilesGenerator.Compare(comp, a.atomset, b.atomset); return cmp; }); @@ -256,14 +257,13 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo } // [C]1[CH][CH]CCC1 |^1:1,2,^3:0| - if (SmiFlavors.IsSet(opts, SmiFlavor.CxRadical) && + if (SmiFlavorTool.IsSet(opts, SmiFlavors.CxRadical) && state.atomRads != null && state.atomRads.Any()) { var radinv = new SortedDictionary>(); foreach (var e in state.atomRads) { - List idxs; - if (!radinv.TryGetValue(e.Value, out idxs)) + if (!radinv.TryGetValue(e.Value, out List idxs)) radinv[e.Value] = idxs = new List(); idxs.Add(e.Key); } @@ -292,7 +292,7 @@ internal static string Generate(CxSmilesState state, SmiFlavor opts, int[] compo private static void AppendIntegers(int[] invorder, char sep, StringBuilder sb, List vals) { if (vals.Any()) - sb.Append(string.Join(sep.ToString(), vals.Select(v => invorder[v].ToString()))); + sb.Append(string.Join(new string(new[] { sep }), vals.Select(v => invorder[v].ToString(NumberFormatInfo.InvariantInfo)))); } } } diff --git a/NCDK/Smiles/CxSmilesParser.cs b/NCDK/Smiles/CxSmilesParser.cs index 214bd64b..40a085bd 100644 --- a/NCDK/Smiles/CxSmilesParser.cs +++ b/NCDK/Smiles/CxSmilesParser.cs @@ -165,11 +165,10 @@ private static double ReadDouble(CharIter iter) /// parse was a success (or not) private static bool ProcessCoords(CharIter iter, CxSmilesState state) { - if (state.AtomCoords == null) - state.AtomCoords = new List(); + if (state.atomCoords == null) + state.atomCoords = new List(); while (iter.HasNext()) { - // end of coordinate list if (iter.Curr() == ')') { @@ -188,7 +187,7 @@ private static bool ProcessCoords(CharIter iter, CxSmilesState state) iter.NextIf(';'); state.coordFlag = state.coordFlag || z != 0; - state.AtomCoords.Add(new double[] { x, y, z }); + state.atomCoords.Add(new double[] { x, y, z }); } return false; } @@ -204,7 +203,7 @@ private static bool ProcessFragmentGrouping(CharIter iter, CxSmilesState state) { if (state.fragGroups == null) state.fragGroups = new List>(); - IList dest = new List(); + var dest = new List(); while (iter.HasNext()) { dest.Clear(); @@ -231,17 +230,16 @@ private static bool IsSgroupDelim(char c) private static bool ProcessDataSgroups(CharIter iter, CxSmilesState state) { - if (state.dataSgroups == null) state.dataSgroups = new List(4); - IList atomset = new List(); + var atomset = new List(); if (!ProcessIntList(iter, CommaSeparatorChar, atomset)) return false; if (!iter.NextIf(':')) return false; - int beg = iter.pos; + var beg = iter.pos; while (iter.HasNext() && !IsSgroupDelim(iter.Curr())) iter.Next(); string field = Unescape(iter.Substr(beg, iter.pos)); @@ -262,7 +260,7 @@ private static bool ProcessDataSgroups(CharIter iter, CxSmilesState state) beg = iter.pos; while (iter.HasNext() && !IsSgroupDelim(iter.Curr())) iter.Next(); - string operator_ = Unescape(iter.Substr(beg, iter.pos)); + var operator_ = Unescape(iter.Substr(beg, iter.pos)); if (!iter.NextIf(':')) { @@ -273,7 +271,7 @@ private static bool ProcessDataSgroups(CharIter iter, CxSmilesState state) beg = iter.pos; while (iter.HasNext() && !IsSgroupDelim(iter.Curr())) iter.Next(); - string unit = Unescape(iter.Substr(beg, iter.pos)); + var unit = Unescape(iter.Substr(beg, iter.pos)); if (!iter.NextIf(':')) { @@ -301,13 +299,13 @@ private static bool ProcessPolymerSgroups(CharIter iter, CxSmilesState state) { if (state.sgroups == null) state.sgroups = new List(); - int beg = iter.pos; + var beg = iter.pos; while (iter.HasNext() && !IsSgroupDelim(iter.Curr())) iter.Next(); - string keyword = iter.Substr(beg, iter.pos); + var keyword = iter.Substr(beg, iter.pos); if (!iter.NextIf(':')) return false; - IList atomset = new List(); + var atomset = new List(); if (!ProcessIntList(iter, CommaSeparatorChar, atomset)) return false; @@ -365,7 +363,7 @@ private static bool ProcessPositionalVariation(CharIter iter, CxSmilesState stat int beg = ProcessUnsignedInt(iter); if (!iter.NextIf(':')) return false; - IList endpoints = new List(6); + var endpoints = new List(6); if (!ProcessIntList(iter, DotSeparatorChar, endpoints)) return false; iter.NextIf(','); @@ -418,7 +416,7 @@ private static bool ProcessRadicals(CharIter iter, CxSmilesState state) } if (!iter.NextIf(':')) return false; - IList dest = new List(4); + var dest = new List(4); if (!ProcessIntList(iter, CommaSeparatorChar, dest)) return false; foreach (var atomidx in dest) @@ -604,7 +602,7 @@ private static int ProcessUnsignedInt(CharIter iter) /// the separator /// output /// int-list was successfully processed - private static bool ProcessIntList(CharIter iter, char sep, IList dest) + private static bool ProcessIntList(CharIter iter, char sep, List dest) { while (iter.HasNext()) { diff --git a/NCDK/Smiles/CxSmilesState.cs b/NCDK/Smiles/CxSmilesState.cs index 8df53064..bc2fa0af 100644 --- a/NCDK/Smiles/CxSmilesState.cs +++ b/NCDK/Smiles/CxSmilesState.cs @@ -35,14 +35,14 @@ namespace NCDK.Smiles /// internal sealed class CxSmilesState { - public IDictionary atomLabels = null; - public IDictionary atomValues = null; - public IList AtomCoords { get; set; } = null; - public IList> fragGroups = null; - public IDictionary atomRads = null; - public IDictionary> positionVar = null; - public IList sgroups = null; - public IList dataSgroups = null; + public SortedDictionary atomLabels = null; + public SortedDictionary atomValues = null; + public List atomCoords = null; + public List> fragGroups = null; + public SortedDictionary atomRads = null; + public SortedDictionary> positionVar = null; + public List sgroups = null; + public List dataSgroups = null; public bool coordFlag = false; public enum Radical @@ -58,7 +58,7 @@ public enum Radical public sealed class DataSgroup { - readonly IList atoms; + readonly IReadOnlyList atoms; readonly string field; readonly string value; readonly string operator_; @@ -67,7 +67,7 @@ public sealed class DataSgroup readonly string tag; - public DataSgroup(IList atoms, string field, string value, string operator_, string unit, string tag) + public DataSgroup(IReadOnlyList atoms, string field, string value, string operator_, string unit, string tag) { this.atoms = atoms; this.field = field; @@ -79,17 +79,20 @@ public DataSgroup(IList atoms, string field, string value, string operator_ public override bool Equals(Object o) { - DataSgroup that = o as DataSgroup; - if (that == null) + if (!(o is DataSgroup that)) return false; - if (atoms != null ? !Compares.AreEqual(atoms, that.atoms) : that.atoms != null) return false; - if (field != null ? !field.Equals(that.field) : that.field != null) return false; - if (value != null ? !value.Equals(that.value) : that.value != null) return false; - if (operator_ != null ? !operator_.Equals(that.operator_) : that.operator_ != null) return false; - if (unit != null ? !unit.Equals(that.unit) : that.unit != null) return false; - return tag != null ? tag.Equals(that.tag) : that.tag == null; - + if (atoms != null ? !Compares.AreEqual(atoms, that.atoms) : that.atoms != null) + return false; + if (field != null ? !field.Equals(that.field, StringComparison.Ordinal) : that.field != null) + return false; + if (value != null ? !value.Equals(that.value, StringComparison.Ordinal) : that.value != null) + return false; + if (operator_ != null ? !operator_.Equals(that.operator_, StringComparison.Ordinal) : that.operator_ != null) + return false; + if (unit != null ? !unit.Equals(that.unit, StringComparison.Ordinal) : that.unit != null) + return false; + return tag != null ? tag.Equals(that.tag, StringComparison.Ordinal) : that.tag == null; } @@ -138,14 +141,13 @@ public PolymerSgroup(string type, IList atomset, string subscript, string s public override bool Equals(Object o) { - PolymerSgroup that = o as PolymerSgroup; - if (that == null) + if (!(o is PolymerSgroup that)) return false; - return type.Equals(that.type) && + return type.Equals(that.type, StringComparison.Ordinal) && Compares.AreEqual(atomset, that.atomset) && - subscript.Equals(that.subscript) && - supscript.Equals(that.supscript); + subscript.Equals(that.subscript, StringComparison.Ordinal) && + supscript.Equals(that.supscript, StringComparison.Ordinal); } public override int GetHashCode() @@ -169,14 +171,14 @@ public override string ToString() } internal string Type => type; - internal IList AtomSet => atomset; + internal List AtomSet => atomset; internal string Subscript => subscript; internal string Supscript => supscript; } static string Escape(string str) { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { char c = str[i]; diff --git a/NCDK/Smiles/DeduceBondSystemTool.cs b/NCDK/Smiles/DeduceBondSystemTool.cs index a51a5f8f..71481269 100644 --- a/NCDK/Smiles/DeduceBondSystemTool.cs +++ b/NCDK/Smiles/DeduceBondSystemTool.cs @@ -31,6 +31,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; namespace NCDK.Smiles { @@ -61,7 +62,7 @@ public class DeduceBondSystemTool /// /// if the next or running calculation should be interrupted. /// - public bool Interrupted; + public bool Interrupted { get; set; } /// /// Constructor for the DeduceBondSystemTool object. @@ -93,12 +94,12 @@ public bool IsOK(IAtomContainer m) // into account rings larger than 7 atoms. See FixAromaticBondOrders(). IRingSet rs = allRingsFinder.FindAllRings(m, 7); StoreRingSystem(m, rs); - bool StructureOK = this.IsStructureOK(m); - IRingSet irs = this.RemoveExtraRings(m); + bool StructureOK = IsStructureOK(m); + IRingSet irs = RemoveExtraRings(m); if (irs == null) throw new CDKException("error in AllRingsFinder.findAllRings"); - int count = this.GetBadCount(m, irs); + int count = GetBadCount(m, irs); return StructureOK && count == 0; } @@ -134,7 +135,7 @@ public IAtomContainer FixAromaticBondOrders(IAtomContainer atomContainer) //this.counter=0;// counter which keeps track of all current possibilities for placing double bonds - this.FixPyridineNOxides(atomContainer, ringSet); + FixPyridineNOxides(atomContainer, ringSet); for (int i = 0; i <= ringSet.Count - 1; i++) { @@ -159,24 +160,14 @@ public IAtomContainer FixAromaticBondOrders(IAtomContainer atomContainer) else { //TODO: what about other rings systems? - Debug.WriteLine("Found ring of size: " + ring.Atoms.Count); + Debug.WriteLine($"Found ring of size: {ring.Atoms.Count}"); } } IChemObjectSet som = atomContainer.Builder.NewAtomContainerSet(); - // int number=1; // total number of possibilities - // - // for (int ii=0;ii<=MasterList.Count-1;ii++) { - // List ringlist=(List)MasterList[ii]; - // number*=ringlist.Count; - // } - // Debug.WriteLine("number= "+number); - int[] choices; - //if (number> 1000000) return null; - choices = new int[MasterList.Count]; if (MasterList.Count > 0) @@ -193,46 +184,40 @@ public IAtomContainer FixAromaticBondOrders(IAtomContainer atomContainer) for (int i = 0; i <= som.Count - 1; i++) { - IAtomContainer mol = som[i]; - ringSet = RemoveExtraRings(mol); - - if (ringSet == null) continue; - + if (ringSet == null) + continue; int count = GetBadCount(mol, ringSet); - //Debug.WriteLine(i + "\t" + count); - if (count < mincount) { mincount = count; best = i; } - } if (som.Count > 0) return som[best]; return atomContainer; } - private void FixPyridineNOxides(IAtomContainer atomContainer, IRingSet ringSet) + private static void FixPyridineNOxides(IAtomContainer atomContainer, IRingSet ringSet) { //convert n(=O) to [n+][O-] - for (int i = 0; i < atomContainer.Atoms.Count; i++) { IAtom ai = atomContainer.Atoms[i]; - if (ai.Symbol.Equals("N") && (ai.FormalCharge == null || ai.FormalCharge == 0)) + if (string.Equals(ai.Symbol, "N", StringComparison.Ordinal) + && (ai.FormalCharge == null || ai.FormalCharge == 0)) { if (InRingSet(ai, ringSet)) { IEnumerable ca = atomContainer.GetConnectedAtoms(ai); foreach (var caj in ca) { - if (caj.Symbol.Equals("O") - && atomContainer.GetBond(ai, caj).Order == BondOrder.Double) + if (caj.Symbol.Equals("O", StringComparison.Ordinal) + && atomContainer.GetBond(ai, caj).Order == BondOrder.Double) { ai.FormalCharge = 1; caj.FormalCharge = -1; @@ -244,27 +229,23 @@ private void FixPyridineNOxides(IAtomContainer atomContainer, IRingSet ringSet) } // end for (int i=0;i al) + private static void ApplyBonds(IAtomContainer m, IList al) { - //Debug.WriteLine(""); - for (int i = 0; i <= al.Count - 1; i++) { string s = al[i]; string s1 = s.Substring(0, s.IndexOf('-')); string s2 = s.Substring(s.IndexOf('-') + 1); - int i1 = int.Parse(s1); - int i2 = int.Parse(s2); - - //Debug.WriteLine(s1+"\t"+s2); + int i1 = int.Parse(s1, NumberFormatInfo.InvariantInfo); + int i2 = int.Parse(s2, NumberFormatInfo.InvariantInfo); IBond b = m.GetBond(m.Atoms[i1], m.Atoms[i2]); b.Order = BondOrder.Double; } } - private void FiveMemberedRingPossibilities(IAtomContainer m, IRing r, IList>> MasterList) + private static void FiveMemberedRingPossibilities(IAtomContainer m, IRing r, IList>> MasterList) { // 5 possibilities for placing 2 double bonds // 5 possibilities for placing 1 double bond @@ -274,7 +255,6 @@ private void FiveMemberedRingPossibilities(IAtomContainer m, IRing r, IList al1 = new List(); @@ -310,26 +290,24 @@ private void FiveMemberedRingPossibilities(IAtomContainer m, IRing r, IList> mal = new List>(); - - mal.Add(al1); - mal.Add(al2); - mal.Add(al3); - mal.Add(al4); - mal.Add(al5); - - mal.Add(al6); - mal.Add(al7); - mal.Add(al8); - mal.Add(al9); - mal.Add(al10); - - // mal.Add(al11); + List> mal = new List> + { + al1, + al2, + al3, + al4, + al5, + al6, + al7, + al8, + al9, + al10 + }; MasterList.Add(mal); } - private void SixMemberedRingPossibilities(IAtomContainer m, IRing r, IList>> MasterList) + private static void SixMemberedRingPossibilities(IAtomContainer m, IRing r, IList>> MasterList) { // 2 possibilities for placing 3 double bonds // 6 possibilities for placing 2 double bonds @@ -410,33 +388,32 @@ private void SixMemberedRingPossibilities(IAtomContainer m, IRing r, IList> mal = new List>(); - - mal.Add(al1); - mal.Add(al2); - - mal.Add(al3); - mal.Add(al4); - mal.Add(al5); - mal.Add(al6); - mal.Add(al7); - mal.Add(al8); - mal.Add(al9); - mal.Add(al10); - mal.Add(al11); - - mal.Add(al12); - mal.Add(al13); - mal.Add(al14); - mal.Add(al15); - mal.Add(al16); - mal.Add(al17); - mal.Add(al18); + List> mal = new List> + { + al1, + al2, + al3, + al4, + al5, + al6, + al7, + al8, + al9, + al10, + al11, + al12, + al13, + al14, + al15, + al16, + al17, + al18 + }; MasterList.Add(mal); } - private void SevenMemberedRingPossibilities(IAtomContainer m, IRing r, IList>> MasterList) + private static void SevenMemberedRingPossibilities(IAtomContainer m, IRing r, IList>> MasterList) { // for now only consider case where have 3 double bonds @@ -477,18 +454,19 @@ private void SevenMemberedRingPossibilities(IAtomContainer m, IRing r, IList> mal = new List>(); - - mal.Add(al1); - mal.Add(al2); - mal.Add(al3); - mal.Add(al4); - mal.Add(al5); + List> mal = new List> + { + al1, + al2, + al3, + al4, + al5 + }; MasterList.Add(mal); } - private int GetBadCount(IAtomContainer atomContainer, IRingSet ringSet) + private static int GetBadCount(IAtomContainer atomContainer, IRingSet ringSet) { // finds count of nitrogens in the rings that have 4 bonds // to non hydrogen atoms and one to hydrogen @@ -502,17 +480,13 @@ private int GetBadCount(IAtomContainer atomContainer, IRingSet ringSet) { IAtom atom = atomContainer.Atoms[j]; - //Debug.WriteLine(mol.GetBondOrderSum(a)); - if (InRingSet(atom, ringSet)) { - //Debug.WriteLine("in ring set"); - if (atom.Symbol.Equals("N")) + if (string.Equals(atom.Symbol, "N", StringComparison.Ordinal)) { if (atom.FormalCharge == 0) { - // Debug.WriteLine(mol.GetBondOrderSum(a)); if (atomContainer.GetBondOrderSum(atom) == 4) { count++; // @@ -547,7 +521,7 @@ private int GetBadCount(IAtomContainer atomContainer, IRingSet ringSet) } } } - else if (atom.Symbol.Equals("S")) + else if (string.Equals(atom.Symbol, "S", StringComparison.Ordinal)) { if (atomContainer.GetBondOrderSum(atom) > 2) { @@ -556,12 +530,11 @@ private int GetBadCount(IAtomContainer atomContainer, IRingSet ringSet) } } } - //Debug.WriteLine("here bad count = " + count); return count; } - private bool InRingSet(IAtom atom, IRingSet ringSet) + private static bool InRingSet(IAtom atom, IRingSet ringSet) { for (int i = 0; i < ringSet.Count; i++) { @@ -571,21 +544,9 @@ private bool InRingSet(IAtom atom, IRingSet ringSet) return false; } - /// - /// - /// - /// Start time in ticks. - /// - /// - /// - /// - /// - /// private IAtomContainer Loop(long starttime, IAtomContainer atomContainer, int index, IList>> MasterList, int[] choices, IChemObjectSet som) { - //Debug.WriteLine(System.CurrentTimeMillis()); - long time = DateTime.Now.Ticks; long diff = time - starttime; @@ -612,8 +573,6 @@ private IAtomContainer Loop(long starttime, IAtomContainer atomContainer, int in if (index == MasterList.Count - 1) { - //Debug.WriteLine(choices[0]+"\t"+choices[1]); - IAtomContainer mnew = null; try { @@ -629,24 +588,18 @@ private IAtomContainer Loop(long starttime, IAtomContainer atomContainer, int in { IList> ringlist2 = MasterList[j]; IList bondlist = ringlist2[choices[j]]; - // Debug.WriteLine(j+"\t"+choices[j]); ApplyBonds(mnew, bondlist); } - // Debug.WriteLine(""); if (IsStructureOK(mnew)) { - IRingSet rs = this.RemoveExtraRings(mnew); // need to redo this since created new atomContainer (mnew) + IRingSet rs = RemoveExtraRings(mnew); // need to redo this since created new atomContainer (mnew) if (rs != null) { - int count = this.GetBadCount(mnew, rs); - // Debug.WriteLine("bad count="+count); - + int count = GetBadCount(mnew, rs); if (count == 0) { - // Debug.WriteLine("found match after "+counter+" - // iterations"); return mnew; // dont worry about adding to set // just finish } @@ -680,7 +633,8 @@ private bool IsStructureOK(IAtomContainer atomContainer) foreach (var atom in atomContainer.Atoms) { IAtomType matched = matcher.FindMatchingAtomType(atomContainer, atom); - if (matched == null || matched.AtomTypeName.Equals("X")) return false; + if (matched == null || matched.AtomTypeName.Equals("X", StringComparison.Ordinal)) + return false; } IRingSet ringSet = RecoverRingSystem(atomContainer); @@ -705,17 +659,12 @@ private bool IsStructureOK(IAtomContainer atomContainer) } // Figure out which rings we want to make sure are aromatic: - bool[] Check = this.FindRingsToCheck(ringSet); - - // for (int i=0;i<=Check.Length-1;i++) { - // Debug.WriteLine(i+"\t"+rs[i].Atoms.Count+"\t"+Check[i]); - // } + bool[] Check = FindRingsToCheck(ringSet); for (int i = 0; i <= ringSet.Count - 1; i++) { IRing ring = (IRing)ringSet[i]; - //Debug.WriteLine(k+"\t"+r.Atoms.Count+"\t"+r.IsAromatic); if (Check[i]) { @@ -753,16 +702,12 @@ private bool IsStructureOK(IAtomContainer atomContainer) /// /// The AtomContainer from which we want to remove rings /// The set of reduced rings - private IRingSet RemoveExtraRings(IAtomContainer m) + private static IRingSet RemoveExtraRings(IAtomContainer m) { try { IRingSet rs = Cycles.FindSSSR(m).ToRingSet(); - //remove rings which dont have all aromatic atoms (according to hybridization set by lower case symbols in smiles): - - //Debug.WriteLine("numrings="+rs.Count); - for (int i = 0; i <= rs.Count - 1; i++) { IRing r = (IRing)rs[i]; @@ -780,14 +725,14 @@ private IRingSet RemoveExtraRings(IAtomContainer m) { //Debug.WriteLine(j+"\t"+r.GetAtomAt(j).Symbol+"\t"+r.GetAtomAt(j).Hybridization); if (r.Atoms[j].Hybridization.IsUnset() - || !(r.Atoms[j].Hybridization == Hybridization.SP2 || + || !(r.Atoms[j].Hybridization == Hybridization.SP2 || r.Atoms[j].Hybridization == Hybridization.Planar3)) { rs.RemoveAt(i); i--; // go back goto iloop; // NonSP2Count++; - // if (r.Atoms[j].Symbol.Equals("C")) { + // if (string.Equals(r.Atoms[j].Symbol, "C", StringComparison.Ordinal)) { // rs.RemoveAtomContainer(i); // i--; // go back // continue iloop; @@ -812,7 +757,7 @@ private IRingSet RemoveExtraRings(IAtomContainer m) } } - private bool[] FindRingsToCheck(IRingSet rs) + private static bool[] FindRingsToCheck(IRingSet rs) { bool[] Check = new bool[rs.Count]; @@ -820,7 +765,7 @@ private bool[] FindRingsToCheck(IRingSet rs) { Check[i] = true; } - + for (int i = 0; i <= rs.Count - 1; i++) { IRing r = (IRing)rs[i]; @@ -837,11 +782,11 @@ private bool[] FindRingsToCheck(IRingSet rs) { // Debug.WriteLine(j+"\t"+r.GetAtomAt(j).Symbol+"\t"+r.GetAtomAt(j).Hybridization); - if (r.Atoms[j].Hybridization.IsUnset() || + if (r.Atoms[j].Hybridization.IsUnset() || r.Atoms[j].Hybridization != Hybridization.SP2) { NonSP2Count++; - if (r.Atoms[j].Symbol.Equals("C")) + if (string.Equals(r.Atoms[j].Symbol, "C", StringComparison.Ordinal)) { Check[i] = false; goto iloop; diff --git a/NCDK/Smiles/FixBondOrdersTool.cs b/NCDK/Smiles/FixBondOrdersTool.cs index 23b5c6f5..d272e787 100644 --- a/NCDK/Smiles/FixBondOrdersTool.cs +++ b/NCDK/Smiles/FixBondOrdersTool.cs @@ -26,6 +26,7 @@ using NCDK.Tools; using System; using System.Collections.Generic; +using System.Linq; namespace NCDK.Smiles { @@ -58,18 +59,13 @@ namespace NCDK.Smiles // @cdk.module smiles // @cdk.githash [Obsolete("Use " + nameof(Aromaticities.Kekulization))] - public class FixBondOrdersTool + public static class FixBondOrdersTool { - /// - /// if the next or running calculation should be interrupted. - /// - public bool Interrupted; - private class Matrix { - private int[] mArray; - private int rowCount; - private int columnCount; + private readonly int[] mArray; + private readonly int rowCount; + private readonly int columnCount; public Matrix(int rows, int cols) { @@ -138,17 +134,12 @@ public int GetCols() } } - /// - /// Constructor for the FixBondOrdersTool object. - /// - public FixBondOrdersTool() { } - /// /// Function to add double/single bond order information for molecules having rings containing all atoms marked or hybridisation. /// /// The to kekulise /// The with Kekulé structure - public IAtomContainer KekuliseAromaticRings(IAtomContainer molecule) + public static IAtomContainer KekuliseAromaticRings(IAtomContainer molecule) { IAtomContainer mNew = null; mNew = (IAtomContainer)molecule.Clone(); @@ -174,8 +165,8 @@ public IAtomContainer KekuliseAromaticRings(IAtomContainer molecule) } //We need to establish which rings share bonds and set up sets of such interdependant rings - IList rBondsArray = null; - IList> ringGroups = null; + List rBondsArray = null; + List> ringGroups = null; //Start by getting a list (same dimensions and ordering as ring set) of all the ring bond numbers in the reduced ring set rBondsArray = GetRingSystem(mNew, ringSet); @@ -190,14 +181,14 @@ public IAtomContainer KekuliseAromaticRings(IAtomContainer molecule) SetAllRingBondsSingleOrder(ringGroups[i], ringSet); //Set up lists of atoms, bonds and atom pairs for this ringGroup - IList atomNos = null; + List atomNos = null; atomNos = GetAtomNosForRingGroup(mNew, ringGroups[i], ringSet); - IList bondNos = null; + List bondNos = null; bondNos = GetBondNosForRingGroup(mNew, ringGroups[i], ringSet); //Array of same dimensions as bondNos (cols in Matrix) - IList atomNoPairs = null; + List atomNoPairs = null; atomNoPairs = GetAtomNoPairsForRingGroup(mNew, bondNos); //Set up adjacency Matrix @@ -225,7 +216,7 @@ public IAtomContainer KekuliseAromaticRings(IAtomContainer molecule) } //Array of same dimensions as atomNos (rows in Matrix) - IList freeValencies = null; + List freeValencies = null; freeValencies = GetFreeValenciesForRingGroup(mNew, atomNos, M, ringSet); //Array of "answers" @@ -257,7 +248,7 @@ public IAtomContainer KekuliseAromaticRings(IAtomContainer molecule) /// /// The from which we want to remove rings /// The set of reduced rings - private IRingSet RemoveExtraRings(IAtomContainer m) + private static IRingSet RemoveExtraRings(IAtomContainer m) { IRingSet rs = Cycles.FindSSSR(m).ToRingSet(); @@ -294,7 +285,7 @@ private IRingSet RemoveExtraRings(IAtomContainer m) /// The IAtomContainer for which to store the IRingSet. /// The IRingSet to store /// The List of int arrays for the bond numbers of each ringSet - private IList GetRingSystem(IAtomContainer mol, IRingSet ringSet) + private static List GetRingSystem(IAtomContainer mol, IRingSet ringSet) { List bondsArray; bondsArray = new List(); @@ -316,10 +307,10 @@ private IList GetRingSystem(IAtomContainer mol, IRingSet ringSet) /// /// /// A List of Lists each containing the ring indices of a set of fused rings - private IList> AssignRingGroups(IList rBondsArray) + private static List> AssignRingGroups(List rBondsArray) { - IList> ringGroups; - ringGroups = new List>(); + List> ringGroups; + ringGroups = new List>(); for (int i = 0; i < rBondsArray.Count - 1; i++) { //for each ring except the last in rBondsArray for (int j = 0; j < rBondsArray[i].Length; j++) @@ -366,7 +357,7 @@ private IList> AssignRingGroups(IList rBondsArray) return ringGroups; } - private bool CombineGroups(IList> ringGroups) + private static bool CombineGroups(List> ringGroups) { for (int i = 0; i < ringGroups.Count - 1; i++) { @@ -398,7 +389,7 @@ private bool CombineGroups(IList> ringGroups) /// Sets all bonds in an to single order. /// /// True for success - private bool SetAllRingBondsSingleOrder(IList ringGroup, IRingSet ringSet) + private static bool SetAllRingBondsSingleOrder(List ringGroup, IRingSet ringSet) { foreach (var i in ringGroup) { @@ -414,7 +405,7 @@ private bool SetAllRingBondsSingleOrder(IList ringGroup, IRingSet ringSet) /// Gets the List of atom nos corresponding to a particular set of fused rings. /// /// List of atom numbers for each set - private IList GetAtomNosForRingGroup(IAtomContainer molecule, IList ringGroup, IRingSet ringSet) + private static List GetAtomNosForRingGroup(IAtomContainer molecule, List ringGroup, IRingSet ringSet) { List atc = new List(); foreach (var i in ringGroup) @@ -441,7 +432,7 @@ private IList GetAtomNosForRingGroup(IAtomContainer molecule, IList ri /// Gets the List of bond nos corresponding to a particular set of fused rings. /// /// List of bond numbers for each set - private IList GetBondNosForRingGroup(IAtomContainer molecule, IList ringGroup, IRingSet ringSet) + private static List GetBondNosForRingGroup(IAtomContainer molecule, List ringGroup, IRingSet ringSet) { List btc = new List(); foreach (var i in ringGroup) @@ -468,7 +459,7 @@ private IList GetBondNosForRingGroup(IAtomContainer molecule, IList ri /// Gets List of atom number pairs for each bond in a list of bonds for the molecule. /// /// List of atom pairs - private IList GetAtomNoPairsForRingGroup(IAtomContainer molecule, IList bondsToCheck) + private static List GetAtomNoPairsForRingGroup(IAtomContainer molecule, List bondsToCheck) { List aptc = new List(); foreach (var i in bondsToCheck) @@ -485,7 +476,7 @@ private IList GetAtomNoPairsForRingGroup(IAtomContainer molecule, IList /// The List of free valencies available for extra ring bonding - private IList GetFreeValenciesForRingGroup(IAtomContainer molecule, IList atomsToCheck, Matrix M, IRingSet rs) + private static List GetFreeValenciesForRingGroup(IAtomContainer molecule, List atomsToCheck, Matrix M, IRingSet rs) { List fvtc = new List(); for (int i = 0; i < atomsToCheck.Count; i++) @@ -493,10 +484,9 @@ private IList GetFreeValenciesForRingGroup(IAtomContainer molecule, IList GetFreeValenciesForRingGroup(IAtomContainer molecule, IList GetFreeValenciesForRingGroup(IAtomContainer molecule, IList /// True or false for success or failure - private bool SolveMatrix(Matrix M, IList atomNos, IList bondNos, IList freeValencies, IList atomNoPairs, IList bondOrder) + private static bool SolveMatrix(Matrix M, List atomNos, List bondNos, List freeValencies, List atomNoPairs, List bondOrder) { // Look for bonds that need to be a certain order List solved = new List(); diff --git a/NCDK/Smiles/InvPair.cs b/NCDK/Smiles/InvPair.cs index 516312a2..ce52831b 100644 --- a/NCDK/Smiles/InvPair.cs +++ b/NCDK/Smiles/InvPair.cs @@ -41,9 +41,15 @@ namespace NCDK.Smiles [Serializable] public class InvPair { - /// The description used to set the invariance numbers in the atom's property - public const string InvariancePairKey = "InvariancePair"; - public const string CanonicalLabelKey = "CanonicalLabel"; + /// + /// The description used to set the invariance numbers in the atom's property + /// + public const string InvariancePairPropertyKey = "InvariancePair"; + + /// + /// The description used to set the canonical numbers in the atom's property + /// + public const string CanonicalLabelPropertyKey = "CanonicalLabel"; public long Last { get; set; } = 0; @@ -60,23 +66,19 @@ public class InvPair public IAtom Atom { get; set; } - private int prime; - public InvPair() { } public InvPair(long current, IAtom atom) { Curr = current; Atom = atom; - atom.SetProperty(InvariancePairKey, this); + atom.SetProperty(InvariancePairPropertyKey, this); } public override bool Equals(object obj) { - if (obj is InvPair) + if (obj is InvPair o) { - InvPair o = (InvPair)obj; - // Debug.WriteLine("Last " + last + "o.last " + o.Last + " curr " + curr + " o.curr " + o.Curr + " equals " +(last == o.Last && curr == o.Curr)); return (Last == o.Last && Curr == o.Curr); } else @@ -92,7 +94,7 @@ public override int GetHashCode() public void Commit() { - Atom.SetProperty(CanonicalLabelKey, Curr); + Atom.SetProperty(CanonicalLabelPropertyKey, Curr); } /// @@ -107,7 +109,7 @@ public override string ToString() /// /// The prime number based on the current seed. /// - public int Prime => prime; + public int Prime { get; private set; } /// /// Sets the prime number based on the current seed. @@ -121,7 +123,7 @@ public override string ToString() /// public void SetPrime() { - prime = Primes.GetPrimeAt((int)Curr - 1); + Prime = Primes.GetPrimeAt((int)Curr - 1); } } } diff --git a/NCDK/Smiles/SMARTS/Parser/ASTAliphatic.cs b/NCDK/Smiles/SMARTS/Parser/ASTAliphatic.cs index 9ae9b395..b061f946 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTAliphatic.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTAliphatic.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTAliphatic : SimpleNode + internal class ASTAliphatic : SimpleNode { public ASTAliphatic(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTAnyAtom.cs b/NCDK/Smiles/SMARTS/Parser/ASTAnyAtom.cs index 0570c30a..8f4441b9 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTAnyAtom.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTAnyAtom.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTAnyAtom : SimpleNode + internal class ASTAnyAtom : SimpleNode { public ASTAnyAtom(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTAromatic.cs b/NCDK/Smiles/SMARTS/Parser/ASTAromatic.cs index 43a9fdaa..3396150f 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTAromatic.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTAromatic.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTAromatic : SimpleNode + internal class ASTAromatic : SimpleNode { public ASTAromatic(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTAtom.cs b/NCDK/Smiles/SMARTS/Parser/ASTAtom.cs index c9911f2e..9db7c18b 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTAtom.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTAtom.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTAtom : SimpleNode + internal class ASTAtom : SimpleNode { public ASTAtom(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTAtomicMass.cs b/NCDK/Smiles/SMARTS/Parser/ASTAtomicMass.cs index df7e1c1b..486e04c9 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTAtomicMass.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTAtomicMass.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTAtomicMass : SimpleNode + internal class ASTAtomicMass : SimpleNode { public ASTAtomicMass(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTAtomicNumber.cs b/NCDK/Smiles/SMARTS/Parser/ASTAtomicNumber.cs index 4258e2a7..90813f77 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTAtomicNumber.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTAtomicNumber.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTAtomicNumber : SimpleNode + internal class ASTAtomicNumber : SimpleNode { public ASTAtomicNumber(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTCharge.cs b/NCDK/Smiles/SMARTS/Parser/ASTCharge.cs index 67ba1f6b..9f566803 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTCharge.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTCharge.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTCharge : SimpleNode + internal class ASTCharge : SimpleNode { /// /// The charge value. diff --git a/NCDK/Smiles/SMARTS/Parser/ASTChirality.cs b/NCDK/Smiles/SMARTS/Parser/ASTChirality.cs index 05114d94..5efd3d9c 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTChirality.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTChirality.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTChirality : SimpleNode + internal class ASTChirality : SimpleNode { public bool IsUnspecified { get; set; } = false; public bool IsClockwise { get; set; } = true; diff --git a/NCDK/Smiles/SMARTS/Parser/ASTElement.cs b/NCDK/Smiles/SMARTS/Parser/ASTElement.cs index bedf6a01..48f04ed5 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTElement.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTElement.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTElement : SimpleNode + internal class ASTElement : SimpleNode { public ASTElement(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTExplicitAtom.cs b/NCDK/Smiles/SMARTS/Parser/ASTExplicitAtom.cs index 3e35638d..debd2a6d 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTExplicitAtom.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTExplicitAtom.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTExplicitAtom : SimpleNode + internal class ASTExplicitAtom : SimpleNode { public ASTExplicitAtom(int id) : base(id) @@ -16,7 +14,6 @@ public ASTExplicitAtom(SMARTSParser p, int id) { } - /// /// The element symbol. /// diff --git a/NCDK/Smiles/SMARTS/Parser/ASTExplicitConnectivity.cs b/NCDK/Smiles/SMARTS/Parser/ASTExplicitConnectivity.cs index 9467d866..9bce6ac6 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTExplicitConnectivity.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTExplicitConnectivity.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTExplicitConnectivity : SimpleNode + internal class ASTExplicitConnectivity : SimpleNode { public ASTExplicitConnectivity(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndBond.cs b/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndBond.cs index c2779a53..d51740e1 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndBond.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndBond.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTExplicitHighAndBond : SimpleNode + internal class ASTExplicitHighAndBond : SimpleNode { public ASTExplicitHighAndBond(int id) : base(id) @@ -16,7 +14,6 @@ public ASTExplicitHighAndBond(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndExpression.cs index f5fb1c43..c7472aa6 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTExplicitHighAndExpression.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTExplicitHighAndExpression : SimpleNode + internal class ASTExplicitHighAndExpression : SimpleNode { public ASTExplicitHighAndExpression(int id) : base(id) @@ -16,7 +14,6 @@ public ASTExplicitHighAndExpression(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTGroup.cs b/NCDK/Smiles/SMARTS/Parser/ASTGroup.cs index 870b368b..f51697a5 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTGroup.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTGroup.cs @@ -4,14 +4,9 @@ namespace NCDK.Smiles.SMARTS.Parser { - public class ASTGroup : SimpleNode + internal class ASTGroup : SimpleNode { - internal const int ROLE_REACTANT = ReactionRoleQueryAtom.ROLE_REACTANT; - internal const int ROLE_AGENT = ReactionRoleQueryAtom.ROLE_AGENT; - internal const int ROLE_PRODUCT = ReactionRoleQueryAtom.ROLE_PRODUCT; - internal const int ROLE_ANY = ReactionRoleQueryAtom.ROLE_ANY; - - private int role = ROLE_ANY; + public ReactionRoles Role { get; set; } = ReactionRoles.Any; public ASTGroup(int id) : base(id) @@ -23,16 +18,6 @@ public ASTGroup(SMARTSParser p, int id) { } - public void SetRole(int role) - { - this.role = role; - } - - public int GetRole() - { - return this.role; - } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTHybrdizationNumber.cs b/NCDK/Smiles/SMARTS/Parser/ASTHybrdizationNumber.cs index 477e1e62..5ddfc9fb 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTHybrdizationNumber.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTHybrdizationNumber.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTHybrdizationNumber : SimpleNode + internal class ASTHybrdizationNumber : SimpleNode { public ASTHybrdizationNumber(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTImplicitHCount.cs b/NCDK/Smiles/SMARTS/Parser/ASTImplicitHCount.cs index 79e12cff..cef0eeb3 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTImplicitHCount.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTImplicitHCount.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTImplicitHCount : SimpleNode + internal class ASTImplicitHCount : SimpleNode { public ASTImplicitHCount(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndBond.cs b/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndBond.cs index 2ac9285b..b56f433d 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndBond.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndBond.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTImplicitHighAndBond : SimpleNode + internal class ASTImplicitHighAndBond : SimpleNode { public ASTImplicitHighAndBond(int id) : base(id) @@ -16,7 +14,6 @@ public ASTImplicitHighAndBond(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndExpression.cs index ddc550dc..5356fa5a 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTImplicitHighAndExpression.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTImplicitHighAndExpression : SimpleNode + internal class ASTImplicitHighAndExpression : SimpleNode { public ASTImplicitHighAndExpression(int id) : base(id) @@ -16,7 +14,6 @@ public ASTImplicitHighAndExpression(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTLowAndBond.cs b/NCDK/Smiles/SMARTS/Parser/ASTLowAndBond.cs index 46f10cd4..df983a76 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTLowAndBond.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTLowAndBond.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTLowAndBond : SimpleNode + internal class ASTLowAndBond : SimpleNode { public ASTLowAndBond(int id) : base(id) @@ -16,7 +14,6 @@ public ASTLowAndBond(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTLowAndExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTLowAndExpression.cs index babd20f0..7f6a0139 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTLowAndExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTLowAndExpression.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTLowAndExpression : SimpleNode + internal class ASTLowAndExpression : SimpleNode { private int mapIdx = 0; @@ -34,9 +32,9 @@ public override object JjtAccept(ISMARTSParserVisitor visitor, object data) return visitor.Visit(this, data); } - public void InsertLeafChild(Node node) + public void InsertLeafChild(INode node) { - Node firstNode = this.JjtGetChild(0); + INode firstNode = this.JjtGetChild(0); while (!(firstNode is ASTImplicitHighAndExpression)) { firstNode = firstNode.JjtGetChild(0); } diff --git a/NCDK/Smiles/SMARTS/Parser/ASTNonCHHeavyAtom.cs b/NCDK/Smiles/SMARTS/Parser/ASTNonCHHeavyAtom.cs index 1209376c..e0aade0d 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTNonCHHeavyAtom.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTNonCHHeavyAtom.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTNonCHHeavyAtom : SimpleNode + internal class ASTNonCHHeavyAtom : SimpleNode { public ASTNonCHHeavyAtom(int id) : base(id) @@ -16,7 +14,6 @@ public ASTNonCHHeavyAtom(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTNotBond.cs b/NCDK/Smiles/SMARTS/Parser/ASTNotBond.cs index 6ba79192..27ed38cd 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTNotBond.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTNotBond.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTNotBond : SimpleNode + internal class ASTNotBond : SimpleNode { public int Type { get; set; } @@ -17,7 +16,6 @@ public ASTNotBond(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTNotExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTNotExpression.cs index 5f846b1f..45287ab5 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTNotExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTNotExpression.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTNotExpression : SimpleNode + internal class ASTNotExpression : SimpleNode { public int Type { get; set;} diff --git a/NCDK/Smiles/SMARTS/Parser/ASTOrBond.cs b/NCDK/Smiles/SMARTS/Parser/ASTOrBond.cs index d4d894b9..0b22e69a 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTOrBond.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTOrBond.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTOrBond : SimpleNode + internal class ASTOrBond : SimpleNode { public ASTOrBond(int id) : base(id) @@ -16,7 +14,6 @@ public ASTOrBond(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTOrExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTOrExpression.cs index 69170d1b..672c1336 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTOrExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTOrExpression.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTOrExpression : SimpleNode + internal class ASTOrExpression : SimpleNode { public ASTOrExpression(int id) : base(id) @@ -16,7 +14,6 @@ public ASTOrExpression(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTPeriodicGroupNumber.cs b/NCDK/Smiles/SMARTS/Parser/ASTPeriodicGroupNumber.cs index ca89673c..1b68956b 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTPeriodicGroupNumber.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTPeriodicGroupNumber.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTPeriodicGroupNumber : SimpleNode + internal class ASTPeriodicGroupNumber : SimpleNode { /// /// The periodic table group number for this element. @@ -18,7 +17,6 @@ public ASTPeriodicGroupNumber(SMARTSParser p, int id) { } - /// Accept the visitor. public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/ASTPrimitiveAtomExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTPrimitiveAtomExpression.cs index a992bf31..c8192598 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTPrimitiveAtomExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTPrimitiveAtomExpression.cs @@ -17,7 +17,6 @@ */ namespace NCDK.Smiles.SMARTS.Parser { - /// /// An AST node. It represents one type of atomic primitive notation in smarts. /// @@ -26,7 +25,7 @@ namespace NCDK.Smiles.SMARTS.Parser // @cdk.module smarts // @cdk.githash // @cdk.keyword SMARTS - public class ASTPrimitiveAtomExpression : SimpleNode + internal class ASTPrimitiveAtomExpression : SimpleNode { /// /// Creates a new instance. diff --git a/NCDK/Smiles/SMARTS/Parser/ASTReaction.cs b/NCDK/Smiles/SMARTS/Parser/ASTReaction.cs index e355ca18..e572d6b4 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTReaction.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTReaction.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTReaction : SimpleNode + internal class ASTReaction : SimpleNode { public ASTReaction(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTRecursiveSmartsExpression.cs b/NCDK/Smiles/SMARTS/Parser/ASTRecursiveSmartsExpression.cs index 102a48f4..d6aa95c8 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTRecursiveSmartsExpression.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTRecursiveSmartsExpression.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTRecursiveSmartsExpression : SimpleNode + internal class ASTRecursiveSmartsExpression : SimpleNode { public ASTRecursiveSmartsExpression(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTRingConnectivity.cs b/NCDK/Smiles/SMARTS/Parser/ASTRingConnectivity.cs index eed6e9a5..1a957dbf 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTRingConnectivity.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTRingConnectivity.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTRingConnectivity : SimpleNode + internal class ASTRingConnectivity : SimpleNode { /// /// The number of ring connections. diff --git a/NCDK/Smiles/SMARTS/Parser/ASTRingIdentifier.cs b/NCDK/Smiles/SMARTS/Parser/ASTRingIdentifier.cs index 81a79808..dc0af6a2 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTRingIdentifier.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTRingIdentifier.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTRingIdentifier : SimpleNode + internal class ASTRingIdentifier : SimpleNode { public ASTRingIdentifier(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTRingMembership.cs b/NCDK/Smiles/SMARTS/Parser/ASTRingMembership.cs index 439ed969..4ee62e85 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTRingMembership.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTRingMembership.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTRingMembership : SimpleNode + internal class ASTRingMembership : SimpleNode { public ASTRingMembership(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTSimpleBond.cs b/NCDK/Smiles/SMARTS/Parser/ASTSimpleBond.cs index 802bbed8..2bea4cc4 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTSimpleBond.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTSimpleBond.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTSimpleBond : SimpleNode + internal class ASTSimpleBond : SimpleNode { public ASTSimpleBond(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTSmallestRingSize.cs b/NCDK/Smiles/SMARTS/Parser/ASTSmallestRingSize.cs index fbdf72eb..57c0e7fb 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTSmallestRingSize.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTSmallestRingSize.cs @@ -1,26 +1,28 @@ /* Generated By:JJTree: Do not edit this line. ASTSmallestRingSize.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ -namespace NCDK.Smiles.SMARTS.Parser { +namespace NCDK.Smiles.SMARTS.Parser +{ + internal class ASTSmallestRingSize : SimpleNode + { + public ASTSmallestRingSize(int id) + : base(id) + { + } -public -class ASTSmallestRingSize : SimpleNode { - public ASTSmallestRingSize(int id) - : base(id) { - } - - public ASTSmallestRingSize(SMARTSParser p, int id) - : base(p, id) { - } + public ASTSmallestRingSize(SMARTSParser p, int id) + : base(p, id) + { + } /// /// The smallest SSSR size. /// public int Size { get; set; } - /// Accept the visitor. - public override object JjtAccept(ISMARTSParserVisitor visitor, object data) { - return visitor.Visit(this, data); - } -} + public override object JjtAccept(ISMARTSParserVisitor visitor, object data) + { + return visitor.Visit(this, data); + } + } } diff --git a/NCDK/Smiles/SMARTS/Parser/ASTSmarts.cs b/NCDK/Smiles/SMARTS/Parser/ASTSmarts.cs index a8b46dbc..4a5fcbdc 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTSmarts.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTSmarts.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTSmarts : SimpleNode + internal class ASTSmarts : SimpleNode { public ASTSmarts(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTStart.cs b/NCDK/Smiles/SMARTS/Parser/ASTStart.cs index df0707a6..569a53bd 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTStart.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTStart.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTStart : SimpleNode + internal class ASTStart : SimpleNode { public ASTStart(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTTotalConnectivity.cs b/NCDK/Smiles/SMARTS/Parser/ASTTotalConnectivity.cs index 5be2114b..3e90efaf 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTTotalConnectivity.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTTotalConnectivity.cs @@ -2,8 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class ASTTotalConnectivity : SimpleNode + internal class ASTTotalConnectivity : SimpleNode { public ASTTotalConnectivity(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTTotalHCount.cs b/NCDK/Smiles/SMARTS/Parser/ASTTotalHCount.cs index 6ad4a37f..6534244a 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTTotalHCount.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTTotalHCount.cs @@ -1,9 +1,36 @@ /* Generated By:JJTree: Do not edit this line. ASTTotalHCount.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser -{ +{ /* Generated By:JJTree: Do not edit this line. ASTSmallestRingSize.java Version 4.3 */ + /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ + namespace NCDK.Smiles.SMARTS.Parser + { + internal class ASTSmallestRingSize : SimpleNode + { + public ASTSmallestRingSize(int id) + : base(id) + { + } + + public ASTSmallestRingSize(SMARTSParser p, int id) + : base(p, id) + { + } + + /// + /// The smallest SSSR size. + /// + public int Size { get; set; } + + + /// Accept the visitor. + public override object JjtAccept(ISMARTSParserVisitor visitor, object data) + { + return visitor.Visit(this, data); + } + } + } - public class ASTTotalHCount : SimpleNode { public ASTTotalHCount(int id) diff --git a/NCDK/Smiles/SMARTS/Parser/ASTValence.cs b/NCDK/Smiles/SMARTS/Parser/ASTValence.cs index 63ec9bc0..73746d3c 100644 --- a/NCDK/Smiles/SMARTS/Parser/ASTValence.cs +++ b/NCDK/Smiles/SMARTS/Parser/ASTValence.cs @@ -2,9 +2,7 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - - public - class ASTValence : SimpleNode + internal class ASTValence : SimpleNode { public ASTValence(int id) : base(id) diff --git a/NCDK/Smiles/SMARTS/Parser/ISMARTSParserVisitor.cs b/NCDK/Smiles/SMARTS/Parser/ISMARTSParserVisitor.cs index 50ac7ae0..75b8087f 100644 --- a/NCDK/Smiles/SMARTS/Parser/ISMARTSParserVisitor.cs +++ b/NCDK/Smiles/SMARTS/Parser/ISMARTSParserVisitor.cs @@ -1,7 +1,7 @@ /* Generated By:JavaCC: Do not edit this line. SMARTSParserVisitor.java Version 5.0 */ namespace NCDK.Smiles.SMARTS.Parser { - public interface ISMARTSParserVisitor + internal interface ISMARTSParserVisitor { object Visit(SimpleNode node, object data); object Visit(ASTStart node, object data); diff --git a/NCDK/Smiles/SMARTS/Parser/JJTSMARTSParserState.cs b/NCDK/Smiles/SMARTS/Parser/JJTSMARTSParserState.cs index 5f406352..ed3d8eaf 100644 --- a/NCDK/Smiles/SMARTS/Parser/JJTSMARTSParserState.cs +++ b/NCDK/Smiles/SMARTS/Parser/JJTSMARTSParserState.cs @@ -3,9 +3,9 @@ namespace NCDK.Smiles.SMARTS.Parser { - public class JJTSMARTSParserState + internal class JJTSMARTSParserState { - private IList nodes; + private IList nodes; private IList marks; private int sp; // number of nodes on stack @@ -14,7 +14,7 @@ public class JJTSMARTSParserState public JJTSMARTSParserState() { - nodes = new List(); + nodes = new List(); marks = new List(); sp = 0; mk = 0; @@ -40,13 +40,13 @@ public void Reset() /* Returns the root node of the AST. It only makes sense to call this after a successful parse. */ - public Node RootNode() + public INode RootNode() { return nodes[0]; } /* Pushes a node on to the stack. */ - public void PushNode(Node n) + public void PushNode(INode n) { nodes.Add(n); ++sp; @@ -54,7 +54,7 @@ public void PushNode(Node n) /* Returns the node on the top of the stack, and remove it from the stack. */ - public Node PopNode() + public INode PopNode() { if (--sp < mk) { @@ -67,7 +67,7 @@ public Node PopNode() } /* Returns the node currently on the top of the stack. */ - public Node PeekNode() + public INode PeekNode() { return nodes[nodes.Count - 1]; } @@ -80,7 +80,7 @@ public int NodeArity() } - public void ClearNodeScope(Node n) + public void ClearNodeScope(INode n) { while (sp > mk) { @@ -90,7 +90,7 @@ public void ClearNodeScope(Node n) marks.RemoveAt(marks.Count - 1); } - public void OpenNodeScope(Node n) + public void OpenNodeScope(INode n) { marks.Add(mk); mk = sp; @@ -102,13 +102,13 @@ public void OpenNodeScope(Node n) children. That number of nodes are popped from the stack and made the children of the definite node. Then the definite node is pushed on to the stack. */ - public void CloseNodeScope(Node n, int num) + public void CloseNodeScope(INode n, int num) { mk = marks[marks.Count - 1]; marks.RemoveAt(marks.Count - 1); while (num-- > 0) { - Node c = PopNode(); + INode c = PopNode(); c.JjtSetParent(n); n.JjtAddChild(c, num); } @@ -123,7 +123,7 @@ the nodes that have been pushed since the node was opened are made children of the conditional node, which is then pushed on to the stack. If the condition is false the node is not constructed and they are left on the stack. */ - public void CloseNodeScope(Node n, bool condition) + public void CloseNodeScope(INode n, bool condition) { if (condition) { @@ -132,7 +132,7 @@ public void CloseNodeScope(Node n, bool condition) marks.RemoveAt(marks.Count - 1); while (a-- > 0) { - Node c = PopNode(); + INode c = PopNode(); c.JjtSetParent(n); n.JjtAddChild(c, a); } diff --git a/NCDK/Smiles/SMARTS/Parser/Node.cs b/NCDK/Smiles/SMARTS/Parser/Node.cs index feebdd26..97283f8b 100644 --- a/NCDK/Smiles/SMARTS/Parser/Node.cs +++ b/NCDK/Smiles/SMARTS/Parser/Node.cs @@ -30,7 +30,7 @@ namespace NCDK.Smiles.SMARTS.Parser /// between nodes. /// // Automatically generated by JJTree - public interface Node + internal interface INode { /// This method is called after the node has been made the current node. It indicates that child nodes can now be added to it. void JjtOpen(); @@ -39,15 +39,15 @@ public interface Node void JjtClose(); /// This pair of methods are used to inform the node of its parent. - void JjtSetParent(Node n); + void JjtSetParent(INode n); - Node JjtGetParent(); + INode JjtGetParent(); /// This method tells the node to add its argument to the node's list of children. - void JjtAddChild(Node n, int i); + void JjtAddChild(INode n, int i); /// This method returns a child node. The children are numbered from zero, left to right. - Node JjtGetChild(int i); + INode JjtGetChild(int i); /// Return the number of children the node has. int JjtGetNumChildren(); diff --git a/NCDK/Smiles/SMARTS/Parser/ParseException.cs b/NCDK/Smiles/SMARTS/Parser/ParseException.cs index d428baf6..fa6d4941 100644 --- a/NCDK/Smiles/SMARTS/Parser/ParseException.cs +++ b/NCDK/Smiles/SMARTS/Parser/ParseException.cs @@ -17,7 +17,9 @@ * Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * (or see http://www.gnu.org/copyleft/lesser.html) */ + using System; +using System.Collections.Generic; using System.Text; namespace NCDK.Smiles.SMARTS.Parser @@ -32,7 +34,7 @@ namespace NCDK.Smiles.SMARTS.Parser /// You can modify this class to customize your error reporting /// mechanisms so long as you retain the public fields. /// - public class ParseException : System.Exception + public class ParseException : Exception { /// /// This constructor is used by the method "generateParseException" @@ -40,56 +42,51 @@ public class ParseException : System.Exception /// a new object of this type with the fields "currentToken", /// "expectedTokenSequences", and "tokenImage" set. /// - public ParseException(Token currentTokenVal, + internal ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, - string[] tokenImageVal + IReadOnlyList tokenImageVal ) : base(Initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal)) { - currentToken = currentTokenVal; - expectedTokenSequences = expectedTokenSequencesVal; - tokenImage = tokenImageVal; + CurrentToken = currentTokenVal; + ExpectedTokenSequences = expectedTokenSequencesVal; + TokenImage = tokenImageVal; } - /// - /// The following constructors are for use by you for whatever - /// purpose you can think of. Constructing the exception in this - /// manner makes the exception behave in the normal way - i.e., as - /// documented in the class "Throwable". The fields "errorToken", - /// "expectedTokenSequences", and "tokenImage" do not contain - /// relevant information. The JavaCC generated code does not use - /// these constructors. - /// - public ParseException() : base() - { } + { + } - /// Constructor with message. public ParseException(string message) : base(message) - { } + { + } + + public ParseException(string message, Exception innerException) : base(message, innerException) + { + } /// /// This is the last token that has been consumed successfully. If /// this object has been created due to a parse error, the token - /// followng this token will (therefore) be the first error token. + /// following this token will (therefore) be the first error token. /// - public Token currentToken; + internal Token CurrentToken { get; set; } /// /// Each entry in this array is an array of integers. Each array /// of integers represents a sequence of tokens (by their ordinal /// values) that is expected at this point of the parse. /// - public int[][] expectedTokenSequences; + public IReadOnlyList> ExpectedTokenSequences { get; set; } /// /// This is a reference to the "tokenImage" array of the generated /// parser within which the parse error occurred. This array is /// defined in the generated ...Constants interface. /// - public string[] tokenImage; + public IReadOnlyList TokenImage { get; set; } /// /// It uses "currentToken" and "expectedTokenSequences" to generate a parse @@ -99,23 +96,23 @@ public ParseException(string message) /// gets displayed. /// private static string Initialise(Token currentToken, - int[][] expectedTokenSequences, - string[] tokenImage) + IReadOnlyList> expectedTokenSequences, + IReadOnlyList tokenImage) { string eol = System.Environment.NewLine; StringBuilder expected = new StringBuilder(); int maxSize = 0; - for (int i = 0; i < expectedTokenSequences.Length; i++) + for (int i = 0; i < expectedTokenSequences.Count; i++) { - if (maxSize < expectedTokenSequences[i].Length) + if (maxSize < expectedTokenSequences[i].Count) { - maxSize = expectedTokenSequences[i].Length; + maxSize = expectedTokenSequences[i].Count; } - for (int j = 0; j < expectedTokenSequences[i].Length; j++) + for (int j = 0; j < expectedTokenSequences[i].Count; j++) { expected.Append(tokenImage[expectedTokenSequences[i][j]]).Append(' '); } - if (expectedTokenSequences[i][expectedTokenSequences[i].Length - 1] != 0) + if (expectedTokenSequences[i][expectedTokenSequences[i].Count - 1] != 0) { expected.Append("..."); } @@ -133,13 +130,13 @@ private static string Initialise(Token currentToken, } retval += " " + tokenImage[tok.kind]; retval += " \""; - retval += Add_escapes(tok.image); + retval += AddEscapes(tok.image); retval += " \""; tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; - if (expectedTokenSequences.Length == 1) + if (expectedTokenSequences.Count == 1) { retval += "Was expecting:" + eol + " "; } @@ -151,17 +148,12 @@ private static string Initialise(Token currentToken, return retval; } - /// - /// The end of line string for this machine. - /// - protected string eol = System.Environment.NewLine; - /// /// Used to convert raw characters to their escaped version /// when these raw version cannot be used as part of an ASCII /// string literal. /// - static string Add_escapes(string str) + static string AddEscapes(string str) { StringBuilder retval = new StringBuilder(); char ch; diff --git a/NCDK/Smiles/SMARTS/Parser/SMARTSParser.cs b/NCDK/Smiles/SMARTS/Parser/SMARTSParser.cs index 57a34c9d..4832d179 100644 --- a/NCDK/Smiles/SMARTS/Parser/SMARTSParser.cs +++ b/NCDK/Smiles/SMARTS/Parser/SMARTSParser.cs @@ -20,8 +20,10 @@ */ using NCDK.Isomorphisms.Matchers; +using NCDK.Isomorphisms.Matchers.SMARTS; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Text; using static NCDK.Smiles.SMARTS.Parser.SMARTSParserConstants; @@ -51,7 +53,7 @@ namespace NCDK.Smiles.SMARTS.Parser // @cdk.module smarts // @cdk.keyword SMARTS // @cdk.keyword substructure search - public class SMARTSParser/*@bgen(jjtree)*/ + internal class SMARTSParser/*@bgen(jjtree)*/ {/*@bgen(jjtree)*/ protected JJTSMARTSParserState jjtree = new JJTSMARTSParserState(); private int componentId = 0; @@ -213,7 +215,7 @@ public void ReactionExpression() case 147: Jj_consume_token(147); if (jjtree.NodeArity() > 0) - ((ASTGroup)jjtree.PeekNode()).SetRole(ASTGroup.ROLE_REACTANT); + ((ASTGroup)jjtree.PeekNode()).Role = ReactionRoles.Reactant; switch ((jj_ntk == -1) ? Jj_ntk() : jj_ntk) { case c: @@ -239,7 +241,7 @@ public void ReactionExpression() case L_BRACKET: case L_PAREN: GroupExpression(); - ((ASTGroup)jjtree.PeekNode()).SetRole(ASTGroup.ROLE_AGENT); + ((ASTGroup)jjtree.PeekNode()).Role = ReactionRoles.Agent; break; default: jj_la1[2] = jj_gen; @@ -271,7 +273,7 @@ public void ReactionExpression() case L_BRACKET: case L_PAREN: GroupExpression(); - ((ASTGroup)jjtree.PeekNode()).SetRole(ASTGroup.ROLE_PRODUCT); + ((ASTGroup)jjtree.PeekNode()).Role = ReactionRoles.Product; break; default: jj_la1[3] = jj_gen; @@ -767,7 +769,7 @@ public ASTAtom AtomExpression() } } break_label_5: - ((ASTLowAndExpression)jjtree.PeekNode()).SetMapIdx(int.Parse(mapidx.ToString())); + ((ASTLowAndExpression)jjtree.PeekNode()).SetMapIdx(int.Parse(mapidx.ToString(), NumberFormatInfo.InvariantInfo)); break; default: jj_la1[18] = jj_gen; @@ -777,11 +779,11 @@ public ASTAtom AtomExpression() token_source.SwitchTo(SMARTSParserConstants.Default); rightBracket = token; Token HToken = null; // If the LowAndExpression is "[H]", change it to an ExplicitAtom - if (firstToken.image.Equals("H")) + if (string.Equals(firstToken.image, "H", StringComparison.Ordinal)) { HToken = firstToken; } - else if (massNode != null && massNode.Mass <= 3 && secondToken != null && secondToken.image.Equals("H")) + else if (massNode != null && massNode.Mass <= 3 && secondToken != null && string.Equals(secondToken.image, "H", StringComparison.Ordinal)) { HToken = secondToken; } @@ -2046,7 +2048,7 @@ public void TotalHCount() } } break_label_6: - jjtn000.Count = int.Parse(digits.ToString()); + jjtn000.Count = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[35] = jj_gen; @@ -2091,7 +2093,7 @@ public void ImplicitHCount() } } break_label_7: - jjtn000.Count = int.Parse(digits.ToString()); + jjtn000.Count = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[37] = jj_gen; @@ -2136,7 +2138,7 @@ public void ExplicitConnectivity() } } break_label_8: - jjtn000.NumOfConnection = int.Parse(digits.ToString()); + jjtn000.NumOfConnection = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[39] = jj_gen; @@ -2179,7 +2181,7 @@ public void AtomicNumber() break_label_9: jjtree.CloseNodeScope(jjtn000, true); jjtc000 = false; - jjtn000.Number = int.Parse(digits.ToString()); + jjtn000.Number = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); } finally { @@ -2202,7 +2204,7 @@ public void HybridizationNumber() Jj_consume_token(DIGIT); jjtree.CloseNodeScope(jjtn000, true); jjtc000 = false; - int tmp = int.Parse(token.image); + int tmp = int.Parse(token.image, NumberFormatInfo.InvariantInfo); if (tmp < 1 || tmp > 8) { if (true) throw new ParseException("Hybridization number must be between 1 & 8"); } jjtn000.HybridizationNumber = tmp; } @@ -2246,7 +2248,7 @@ public void Charge() } } break_label_10: - jjtn000.Charge = int.Parse(digits.ToString()); + jjtn000.Charge = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[42] = jj_gen; @@ -2279,7 +2281,7 @@ public void Charge() } } break_label_11: - jjtn000.Charge = int.Parse(digits.ToString()); + jjtn000.Charge = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[44] = jj_gen; @@ -2414,7 +2416,7 @@ public void RingConnectivity() } } break_label_12: - jjtn000.NumOfConnection = int.Parse(token.image); + jjtn000.NumOfConnection = int.Parse(token.image, NumberFormatInfo.InvariantInfo); break; default: jj_la1[47] = jj_gen; @@ -2458,9 +2460,9 @@ public void PeriodicGroupNumber() break_label_13: jjtree.CloseNodeScope(jjtn000, true); jjtc000 = false; - int tmpInt = int.Parse(digits.ToString()); + int tmpInt = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); if (tmpInt < 1 || tmpInt > 18) { if (true) throw new ParseException("Invalid group number"); } - jjtn000.GroupNumber = int.Parse(digits.ToString()); + jjtn000.GroupNumber = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); } finally { @@ -2500,7 +2502,7 @@ public void TotalConnectivity() } } break_label_14: - jjtn000.NumOfConnection = int.Parse(digits.ToString()); + jjtn000.NumOfConnection = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[50] = jj_gen; @@ -2545,7 +2547,7 @@ public void Valence() } } break_label_15: - jjtn000.Order = int.Parse(digits.ToString()); + jjtn000.Order = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[52] = jj_gen; @@ -2590,7 +2592,7 @@ public void RingMembership() } } break_label_16: - jjtn000.NumOfMembership = int.Parse(digits.ToString()); + jjtn000.NumOfMembership = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[54] = jj_gen; @@ -2635,7 +2637,7 @@ public void SmallestRingSize() } } break_label_17: - jjtn000.Size = int.Parse(digits.ToString()); + jjtn000.Size = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); break; default: jj_la1[56] = jj_gen; @@ -2753,7 +2755,7 @@ public void AtomicMass() break_label_18: jjtree.CloseNodeScope(jjtn000, true); jjtc000 = false; - jjtn000.Mass = int.Parse(digits.ToString()); + jjtn000.Mass = int.Parse(digits.ToString(), NumberFormatInfo.InvariantInfo); } finally { @@ -3357,7 +3359,7 @@ public SMARTSParser(Stream stream) : this(stream, null) /// Constructor with InputStream and supplied encoding public SMARTSParser(Stream stream, string encoding) { - try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch (ArgumentException e) { throw e; } + try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch (ArgumentException) { throw; } token_source = new SMARTSParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; @@ -3374,7 +3376,7 @@ public void ReInit(Stream stream) /// Reinitialise. public void ReInit(Stream stream, string encoding) { - try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch (ArgumentException e) { throw e; } + try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch (ArgumentException) { throw; } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; @@ -3461,7 +3463,9 @@ private Token Jj_consume_token(int kind) throw GenerateParseException(); } - sealed class LookaheadSuccess : Exception { } +#pragma warning disable CA1064 + private sealed class LookaheadSuccess : Exception { } +#pragma warning restore CA1064 readonly private LookaheadSuccess jj_ls = new LookaheadSuccess(); private bool Jj_scan_token(int kind) { @@ -3492,7 +3496,6 @@ private bool Jj_scan_token(int kind) return false; } - /// Get the next Token. public Token GetNextToken() { @@ -3526,7 +3529,7 @@ private int Jj_ntk() private IList jj_expentries = new List(); private int[] jj_expentry; private int jj_kind = -1; - private int[] jj_lasttokens = new int[100]; + private readonly int[] jj_lasttokens = new int[100]; private int jj_endpos; private void Jj_add_error_token(int kind, int pos) @@ -3626,17 +3629,7 @@ public ParseException GenerateParseException() { exptokseq[i] = jj_expentries[i]; } - return new ParseException(token, exptokseq, tokenImage); - } - - /// Enable tracing. - public void Enable_tracing() - { - } - - /// Disable tracing. - public void Disable_tracing() - { + return new ParseException(token, exptokseq, TokenImage); } private void Jj_rescan_token() diff --git a/NCDK/Smiles/SMARTS/Parser/SMARTSParserConstants.cs b/NCDK/Smiles/SMARTS/Parser/SMARTSParserConstants.cs index 72dcf989..d96d1c79 100644 --- a/NCDK/Smiles/SMARTS/Parser/SMARTSParserConstants.cs +++ b/NCDK/Smiles/SMARTS/Parser/SMARTSParserConstants.cs @@ -16,13 +16,16 @@ * Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * (or see http://www.gnu.org/copyleft/lesser.html) */ + +using System.Collections.Generic; + namespace NCDK.Smiles.SMARTS.Parser { /// /// Token literal values and constants. /// Generated by org.javacc.parser.OtherFilesGen#Start() /// - public static class SMARTSParserConstants + internal static class SMARTSParserConstants { /// End of File. public const int EOF = 0; @@ -325,7 +328,8 @@ public static class SMARTSParserConstants public const int Default = 1; /// Literal token values. - public static readonly string[] tokenImage = new string[] { + public static IReadOnlyList TokenImage = new string[] + { "", "", "\";\"", diff --git a/NCDK/Smiles/SMARTS/Parser/SMARTSParserTokenManager.cs b/NCDK/Smiles/SMARTS/Parser/SMARTSParserTokenManager.cs index 30a7222f..651aa1f6 100644 --- a/NCDK/Smiles/SMARTS/Parser/SMARTSParserTokenManager.cs +++ b/NCDK/Smiles/SMARTS/Parser/SMARTSParserTokenManager.cs @@ -19,7 +19,7 @@ namespace NCDK.Smiles.SMARTS.Parser { /// Token Manager. - public class SMARTSParserTokenManager + internal class SMARTSParserTokenManager { // Required by SetState void Backup(int n) { input_stream.Backup(n); } @@ -29,7 +29,7 @@ public class SMARTSParserTokenManager /// Set debug output. public void SetDebugStream(System.IO.Stream ds) { debugStream = ds; } - private int JjStopStringLiteralDfa_1(int pos, long active0, long active1, long active2) + private static int JjStopStringLiteralDfa_1(int pos, long active0, long active1, long active2) { switch (pos) { @@ -446,7 +446,7 @@ private int JjMoveNfa_1(int startState, int curPos) catch (System.IO.IOException) { return curPos; } } } - private int JjStopStringLiteralDfa_0(int pos, long active0, long active1, long active2) + private static int JjStopStringLiteralDfa_0(int pos, long active0, long active1, long active2) { switch (pos) { @@ -930,8 +930,7 @@ private int JjMoveNfa_0(int startState, int curPos) catch (System.IO.IOException) { return curPos; } } } - static readonly int[] jjnextStates = { - }; + static readonly int[] jjnextStates = System.Array.Empty(); /// Token literal values. public static readonly string[] jjstrLiteralImages = new string[] { @@ -1024,7 +1023,7 @@ public void ReInit(SimpleCharStream stream, int lexState) public void SwitchTo(int lexState) { if (lexState >= 2 || lexState < 0) - throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.ErrorCodes.InvalidLexicalState); + throw new TokenManagerException("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenManagerException.ErrorCodes.InvalidLexicalState); else curLexState = lexState; } @@ -1054,7 +1053,7 @@ protected Token JjFillToken() } int curLexState = 1; - int defaultLexState = 1; + const int defaultLexState = 1; int jjnewStateCnt; int jjround; int jjmatchedPos; @@ -1123,7 +1122,7 @@ public Token GetNextToken() input_stream.Backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } - throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.ErrorCodes.LexicalError); + throw new TokenManagerException(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenManagerException.ErrorCodes.LexicalError); } } diff --git a/NCDK/Smiles/SMARTS/Parser/SimpleCharStream.cs b/NCDK/Smiles/SMARTS/Parser/SimpleCharStream.cs index c0d1d448..7e2b0224 100644 --- a/NCDK/Smiles/SMARTS/Parser/SimpleCharStream.cs +++ b/NCDK/Smiles/SMARTS/Parser/SimpleCharStream.cs @@ -17,43 +17,42 @@ * Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * (or see http://www.gnu.org/copyleft/lesser.html) */ +using System; + namespace NCDK.Smiles.SMARTS.Parser { - /// /// An implementation of interface CharStream, where the stream is assumed to /// contain only ASCII characters (without unicode processing). /// - public class SimpleCharStream { /// Whether parser is static. public const bool staticFlag = false; - int bufsize; - int available; - int tokenBegin; + private int bufsize; + private int available; + private int tokenBegin; /// Position in buffer. - public int bufpos = -1; - protected int[] bufline; - protected int[] bufcolumn; + private int bufpos = -1; + private int[] bufline; + private int[] bufcolumn; - protected int column = 0; - protected int line = 1; + private int column = 0; + private int line = 1; - protected bool prevCharIsCR = false; - protected bool prevCharIsLF = false; + private bool prevCharIsCR = false; + private bool prevCharIsLF = false; - protected System.IO.TextReader inputStream; + private System.IO.TextReader inputStream; - protected char[] buffer; - protected int maxNextCharInd = 0; - protected int inBuf = 0; - protected int tabSize = 8; + private char[] buffer; + private int maxNextCharInd = 0; + private int inBuf = 0; + private int tabSize = 8; protected void SetTabSize(int i) { tabSize = i; } protected int GetTabSize(int i) { return tabSize; } - protected void ExpandBuff(bool wrapAround) { char[] newbuffer = new char[bufsize + 2048]; @@ -64,40 +63,39 @@ protected void ExpandBuff(bool wrapAround) { if (wrapAround) { - System.Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - System.Array.Copy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); + Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + Array.Copy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; - System.Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - System.Array.Copy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); + Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + Array.Copy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; - System.Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - System.Array.Copy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); + Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + Array.Copy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { - System.Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; - System.Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; - System.Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } - catch (System.Exception t) + catch (Exception t) { - throw new System.Exception(t.Message); + throw new Exception(t.Message); } - bufsize += 2048; available = bufsize; tokenBegin = 0; @@ -139,7 +137,7 @@ protected void FillBuff() maxNextCharInd += i; return; } - catch (System.Exception ee) + catch (Exception ee) { var e = ee; if (e is System.ObjectDisposedException) @@ -227,13 +225,13 @@ public char ReadChar() return c; } - [System.Obsolete()] + [Obsolete] public int GetColumn() { return bufcolumn[bufpos]; } - [System.Obsolete()] + [Obsolete] public int GetLine() { return bufline[bufpos]; @@ -416,12 +414,12 @@ public char[] GetSuffix(int len) char[] ret = new char[len]; if ((bufpos + 1) >= len) - System.Array.Copy(buffer, bufpos - len + 1, ret, 0, len); + Array.Copy(buffer, bufpos - len + 1, ret, 0, len); else { - System.Array.Copy(buffer, bufsize - (len - bufpos - 1), ret, 0, + Array.Copy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); - System.Array.Copy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); + Array.Copy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; diff --git a/NCDK/Smiles/SMARTS/Parser/SimpleNode.cs b/NCDK/Smiles/SMARTS/Parser/SimpleNode.cs index 78110f35..a6149dca 100644 --- a/NCDK/Smiles/SMARTS/Parser/SimpleNode.cs +++ b/NCDK/Smiles/SMARTS/Parser/SimpleNode.cs @@ -2,14 +2,13 @@ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ namespace NCDK.Smiles.SMARTS.Parser { - public - class SimpleNode : Node + internal class SimpleNode : INode { - protected Node parent; - protected Node[] children; - protected int id; - protected object value; - protected SMARTSParser parser; + private INode parent; + private INode[] children; + private readonly int id; + private object value; + private readonly SMARTSParser parser; public SimpleNode(int i) { @@ -30,18 +29,18 @@ public void JjtClose() { } - public void JjtSetParent(Node n) { parent = n; } - public Node JjtGetParent() { return parent; } + public void JjtSetParent(INode n) { parent = n; } + public INode JjtGetParent() { return parent; } - public void JjtAddChild(Node n, int i) + public void JjtAddChild(INode n, int i) { if (children == null) { - children = new Node[i + 1]; + children = new INode[i + 1]; } else if (i >= children.Length) { - Node[] c = new Node[i + 1]; + INode[] c = new INode[i + 1]; System.Array.Copy(children, 0, c, 0, children.Length); children = c; } @@ -51,7 +50,7 @@ public void JjtAddChild(Node n, int i) public void JjtRemoveChild(int i) { if (i >= children.Length) return; - Node[] c = new Node[children.Length - 1]; + INode[] c = new INode[children.Length - 1]; System.Array.Copy(children, 0, c, 0, i); if (i < c.Length) { @@ -60,7 +59,7 @@ public void JjtRemoveChild(int i) children = c; } - public Node JjtGetChild(int i) + public INode JjtGetChild(int i) { return children[i]; } diff --git a/NCDK/Smiles/SMARTS/Parser/Smarts2MQLVisitor.cs b/NCDK/Smiles/SMARTS/Parser/Smarts2MQLVisitor.cs index 5df3bee8..fff153b7 100644 --- a/NCDK/Smiles/SMARTS/Parser/Smarts2MQLVisitor.cs +++ b/NCDK/Smiles/SMARTS/Parser/Smarts2MQLVisitor.cs @@ -15,6 +15,8 @@ * Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * (or see http://www.gnu.org/copyleft/lesser.html) */ +using System; + namespace NCDK.Smiles.SMARTS.Parser { /// @@ -26,7 +28,7 @@ namespace NCDK.Smiles.SMARTS.Parser // @cdk.module smarts // @cdk.githash // @cdk.keyword SMARTS AST - public class Smarts2MQLVisitor : ISMARTSParserVisitor + internal class Smarts2MQLVisitor : ISMARTSParserVisitor { public object Visit(ASTRingIdentifier node, object data) { @@ -68,7 +70,7 @@ public object Visit(ASTSmarts node, object data) string local = ""; for (int i = 0; i < node.JjtGetNumChildren(); i++) { - Node child = node.JjtGetChild(i); + INode child = node.JjtGetChild(i); if (child is ASTAtom) { local = (string)child.JjtAccept(this, local); @@ -76,7 +78,7 @@ public object Visit(ASTSmarts node, object data) else if (child is ASTLowAndBond) { i++; - Node nextChild = node.JjtGetChild(i); // the next child should + INode nextChild = node.JjtGetChild(i); // the next child should // be another smarts string bond = (string)child.JjtAccept(this, local); local = local + bond; @@ -84,12 +86,14 @@ public object Visit(ASTSmarts node, object data) } else if (child is ASTSmarts) { // implicit single bond - if (!"".Equals(local)) local = local + "-"; + if (local.Length != 0) + local = local + "-"; local = (string)child.JjtAccept(this, local); } else if (child is ASTExplicitAtom) { - if (!"".Equals(local)) local = local + "-"; + if (local.Length != 0) + local = local + "-"; local = (string)child.JjtAccept(this, local); } } @@ -179,11 +183,11 @@ public object Visit(ASTLowAndExpression node, object data) return left; } string right = (string)node.JjtGetChild(1).JjtAccept(this, data); - if ("".Equals(left)) + if (left.Length == 0) { return right; } - else if ("".Equals(right)) + else if (right.Length == 0) { return left; } @@ -201,11 +205,11 @@ public object Visit(ASTOrExpression node, object data) return left; } string right = (string)node.JjtGetChild(1).JjtAccept(this, data); - if ("".Equals(left)) + if (left.Length == 0) { return right; } - else if ("".Equals(right)) + else if (right.Length == 0) { return left; } @@ -224,11 +228,11 @@ public object Visit(ASTExplicitHighAndExpression node, object data) return left; } string right = (string)node.JjtGetChild(1).JjtAccept(this, data); - if ("".Equals(left)) + if (left.Length == 0) { return right; } - else if ("".Equals(right)) + else if (right.Length == 0) { return left; } @@ -247,11 +251,11 @@ public object Visit(ASTImplicitHighAndExpression node, object data) return left; } string right = (string)node.JjtGetChild(1).JjtAccept(this, data); - if ("".Equals(left)) + if (left.Length == 0) { return right; } - else if ("".Equals(right)) + else if (right.Length == 0) { return left; } diff --git a/NCDK/Smiles/SMARTS/Parser/SmartsDumpVisitor.cs b/NCDK/Smiles/SMARTS/Parser/SmartsDumpVisitor.cs index 57765336..c7fb4efc 100644 --- a/NCDK/Smiles/SMARTS/Parser/SmartsDumpVisitor.cs +++ b/NCDK/Smiles/SMARTS/Parser/SmartsDumpVisitor.cs @@ -27,7 +27,7 @@ namespace NCDK.Smiles.SMARTS.Parser // @cdk.module smarts // @cdk.githash // @cdk.keyword SMARTS AST - public class SmartsDumpVisitor : ISMARTSParserVisitor + internal class SmartsDumpVisitor : ISMARTSParserVisitor { public object Visit(ASTRingIdentifier node, object data) { diff --git a/NCDK/Smiles/SMARTS/Parser/SmartsQueryVisitor.cs b/NCDK/Smiles/SMARTS/Parser/SmartsQueryVisitor.cs index 988b2c37..2e31109c 100644 --- a/NCDK/Smiles/SMARTS/Parser/SmartsQueryVisitor.cs +++ b/NCDK/Smiles/SMARTS/Parser/SmartsQueryVisitor.cs @@ -46,7 +46,7 @@ namespace NCDK.Smiles.SMARTS.Parser // @cdk.module smarts // @cdk.githash // @cdk.keyword SMARTS AST - public class SmartsQueryVisitor : ISMARTSParserVisitor + internal class SmartsQueryVisitor : ISMARTSParserVisitor { // current atoms with a ring identifier private RingIdentifierAtom[] ringAtoms; @@ -65,7 +65,7 @@ public class SmartsQueryVisitor : ISMARTSParserVisitor /// /// Lookup of atom indices. /// - private BitArray tetrahedral = new BitArray(0); + private readonly BitArray tetrahedral = new BitArray(0); /// /// Stores the directional '/' or '\' bonds. Speeds up looking for double @@ -205,23 +205,23 @@ public object Visit(ASTReaction node, object data) group.JjtAccept(this, query); // fill in the roles for newly create atoms - if (group.GetRole() != ASTGroup.ROLE_ANY) + if (group.Role != ReactionRoles.Any) { IQueryAtom roleQueryAtom = null; ReactionRole? role = null; // use single instances - switch (group.GetRole()) + switch (group.Role) { - case ASTGroup.ROLE_REACTANT: + case ReactionRoles.Reactant: roleQueryAtom = ReactionRoleQueryAtom.RoleReactant; role = ReactionRole.Reactant; break; - case ASTGroup.ROLE_AGENT: + case ReactionRoles.Agent: roleQueryAtom = ReactionRoleQueryAtom.RoleAgent; role = ReactionRole.Agent; break; - case ASTGroup.ROLE_PRODUCT: + case ReactionRoles.Product: roleQueryAtom = ReactionRoleQueryAtom.RoleProduct; role = ReactionRole.Product; break; @@ -253,7 +253,7 @@ public object Visit(ASTGroup node, object data) fullQuery = new QueryAtomContainer(builder); // keeps track of component grouping - int[] components = fullQuery.GetProperty(ComponentGrouping.Key, new int[0]); + int[] components = fullQuery.GetProperty(ComponentGrouping.Key, Array.Empty()); int maxId = 0; if (components.Length > 0) { @@ -377,7 +377,7 @@ public object Visit(ASTSmarts node, object data) // now process the rest of the bonds/atoms for (int i = 1; i < node.JjtGetNumChildren(); i++) { - Node child = node.JjtGetChild(i); + INode child = node.JjtGetChild(i); if (child is ASTLowAndBond) { bond = (SMARTSBond)child.JjtAccept(this, data); @@ -573,7 +573,7 @@ public object Visit(ASTRecursiveSmartsExpression node, object data) return new RecursiveSmartsAtom((IQueryAtomContainer)node.JjtGetChild(0).JjtAccept(recursiveVisitor, null)); } - public ASTStart GetRoot(Node node) + public ASTStart GetRoot(INode node) { if (node is ASTStart) { @@ -586,15 +586,21 @@ public object Visit(ASTElement node, object data) { string symbol = node.Symbol; SMARTSAtom atom; - if ("o".Equals(symbol) || "n".Equals(symbol) || "c".Equals(symbol) || "s".Equals(symbol) || "p".Equals(symbol) - || "as".Equals(symbol) || "se".Equals(symbol)) - { - string atomSymbol = symbol.Substring(0, 1).ToUpperInvariant() + symbol.Substring(1); - atom = new AromaticSymbolAtom(atomSymbol, builder); - } - else - { - atom = new AliphaticSymbolAtom(symbol, builder); + switch (symbol) + { + case "o": + case "n": + case "c": + case "s": + case "p": + case "as": + case "se": + string atomSymbol = symbol.Substring(0, 1).ToUpperInvariant() + symbol.Substring(1); + atom = new AromaticSymbolAtom(atomSymbol, builder); + break; + default: + atom = new AliphaticSymbolAtom(symbol, builder); + break; } return atom; } @@ -762,51 +768,51 @@ public object Visit(ASTExplicitAtom node, object data) { IQueryAtom atom = null; string symbol = node.Symbol; - if ("*".Equals(symbol)) - { - atom = new AnyAtom(builder); - } - else if ("A".Equals(symbol)) - { - atom = new AliphaticAtom(builder); - } - else if ("a".Equals(symbol)) - { - atom = new AromaticAtom(builder); - } - else if ("o".Equals(symbol) || "n".Equals(symbol) || "c".Equals(symbol) || "s".Equals(symbol) - || "p".Equals(symbol) || "as".Equals(symbol) || "se".Equals(symbol)) - { - string atomSymbol = symbol.Substring(0, 1).ToUpperInvariant() + symbol.Substring(1); - atom = new AromaticSymbolAtom(atomSymbol, builder); - } - else if ("H".Equals(symbol)) - { - atom = new HydrogenAtom(builder) - { - Symbol = symbol.ToUpperInvariant(), - MassNumber = 1 - }; - } - else if ("D".Equals(symbol)) - { - atom = new HydrogenAtom(builder) - { - Symbol = symbol.ToUpperInvariant(), - MassNumber = 2 - }; - } - else if ("T".Equals(symbol)) - { - atom = new HydrogenAtom(builder) - { - Symbol = symbol.ToUpperInvariant(), - MassNumber = 3 - }; - } - else + switch (symbol) { - atom = new AliphaticSymbolAtom(symbol, builder); + case "*": + atom = new AnyAtom(builder); + break; + case "A": + atom = new AliphaticAtom(builder); + break; + case "a": + atom = new AromaticAtom(builder); + break; + case "o": + case "n": + case "c": + case "s": + case "p": + case "as": + case "se": + string atomSymbol = symbol.Substring(0, 1).ToUpperInvariant() + symbol.Substring(1); + atom = new AromaticSymbolAtom(atomSymbol, builder); + break; + case "H": + atom = new HydrogenAtom(builder) + { + Symbol = symbol.ToUpperInvariant(), + MassNumber = 1 + }; + break; + case "D": + atom = new HydrogenAtom(builder) + { + Symbol = symbol.ToUpperInvariant(), + MassNumber = 2 + }; + break; + case "T": + atom = new HydrogenAtom(builder) + { + Symbol = symbol.ToUpperInvariant(), + MassNumber = 3 + }; + break; + default: + atom = new AliphaticSymbolAtom(symbol, builder); + break; } return atom; } diff --git a/NCDK/Smiles/SMARTS/Parser/Token.cs b/NCDK/Smiles/SMARTS/Parser/Token.cs index 5db592aa..b11474d7 100644 --- a/NCDK/Smiles/SMARTS/Parser/Token.cs +++ b/NCDK/Smiles/SMARTS/Parser/Token.cs @@ -17,15 +17,13 @@ * Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * (or see http://www.gnu.org/copyleft/lesser.html) */ -using System; namespace NCDK.Smiles.SMARTS.Parser { /// /// Describes the input token stream. /// - [Serializable] - public class Token + internal class Token { /// /// An integer that describes the kind of this token. This numbering @@ -80,7 +78,7 @@ public class Token /// Any subclass of Token that actually wants to return a non-null value can /// override this method as appropriate. /// - public object Value => null; + public object value = null; /// /// No-argument constructor diff --git a/NCDK/Smiles/SMARTS/Parser/TokenMgrError.cs b/NCDK/Smiles/SMARTS/Parser/TokenMgrError.cs index 917aa58e..93e2b481 100644 --- a/NCDK/Smiles/SMARTS/Parser/TokenMgrError.cs +++ b/NCDK/Smiles/SMARTS/Parser/TokenMgrError.cs @@ -17,13 +17,14 @@ * Foundation, 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * (or see http://www.gnu.org/copyleft/lesser.html) */ + using System; using System.Text; namespace NCDK.Smiles.SMARTS.Parser { /// Token Manager Error. - public class TokenMgrError : Exception + public class TokenManagerException : Exception { /// /// Ordinals for various reasons why an Error of this type can be thrown. @@ -136,7 +137,7 @@ protected static string LexicalError(bool EOFSeen, int lexState, int errorLine, return ("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + - (EOFSeen ? " " : ("\"" + AddEscapes(curChar.ToString()) + "\"") + " (" + (int)curChar + "), ") + + (EOFSeen ? " " : ("\"" + AddEscapes(new string(new[] { curChar })) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + AddEscapes(errorAfter) + "\""); } @@ -158,20 +159,28 @@ protected static string LexicalError(bool EOFSeen, int lexState, int errorLine, // Constructors of various flavors follow. /// No arg constructor. - public TokenMgrError() + public TokenManagerException() { } /// Constructor with message and reason. - internal TokenMgrError(string message, ErrorCodes reason) + internal TokenManagerException(string message, ErrorCodes reason) : base(message) { errorCode = reason; } /// Full Constructor. - internal TokenMgrError(bool EOFSeen, int lexState, int errorLine, int errorColumn, string errorAfter, char curChar, ErrorCodes reason) + internal TokenManagerException(bool EOFSeen, int lexState, int errorLine, int errorColumn, string errorAfter, char curChar, ErrorCodes reason) : this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason) { } + + public TokenManagerException(string message) : base(message) + { + } + + public TokenManagerException(string message, Exception innerException) : base(message, innerException) + { + } } } diff --git a/NCDK/Smiles/SMARTS/SMARTSQueryTool.cs b/NCDK/Smiles/SMARTS/SMARTSQueryTool.cs index 833c273c..66c9d4af 100644 --- a/NCDK/Smiles/SMARTS/SMARTSQueryTool.cs +++ b/NCDK/Smiles/SMARTS/SMARTSQueryTool.cs @@ -122,7 +122,7 @@ public class SMARTSQueryTool private string smarts; private IAtomContainer atomContainer = null; private QueryAtomContainer query = null; - private IList mappings; + private List mappings; /// /// Defines which set of rings to define rings in the target. @@ -203,7 +203,7 @@ public override IRingSet ComputeRingSet(IAtomContainer m) /// the molecules being tests are known to all have the same aromaticity /// model. /// - private bool skipAromaticity = false; + private readonly bool skipAromaticity = false; // a simplistic cache to store parsed SMARTS queries private int MAX_ENTRIES = 20; @@ -224,7 +224,7 @@ public SMARTSQueryTool(string smarts, IChemObjectBuilder builder) { InitializeQuery(); } - catch (TokenMgrError error) + catch (TokenManagerException error) { throw new ArgumentException("Error parsing SMARTS", error); } @@ -322,7 +322,7 @@ public string Smarts /// initializing ( ring perception, aromaticity etc.) the molecule each time. If however, you modify the molecule /// between such multiple matchings you should use the other form of this method to force initialization. /// - /// The target moleculoe + /// The target molecule /// true if the pattern is found in the target molecule, false otherwise /// if there is an error in ring, aromaticity or isomorphism perception /// @@ -400,12 +400,11 @@ public bool Matches(IAtomContainer atomContainer, bool forceInitialization) /// molecule, that match the query pattern /// /// A List of List of atom indices in the target molecule - public IList> GetMatchingAtoms() + public IEnumerable> GetMatchingAtoms() { - List> matched = new List>(mappings.Count); foreach (var mapping in mappings) - matched.Add(mapping); - return matched; + yield return mapping; + yield break; } /// @@ -417,18 +416,18 @@ public IList> GetMatchingAtoms() /// /// /// A List of List of atom indices in the target molecule - public IList> GetUniqueMatchingAtoms() + public IEnumerable> GetUniqueMatchingAtoms() { - List> matched = new List>(mappings.Count); - HashSet atomSets = new HashSet(BitArrays.EqualityComparer); + var atomSets = new HashSet(BitArrays.EqualityComparer); foreach (var mapping in mappings) { BitArray atomSet = new BitArray(0); foreach (var x in mapping) BitArrays.SetValue(atomSet, x, true); - if (atomSets.Add(atomSet)) matched.Add(mapping); + if (atomSets.Add(atomSet)) + yield return mapping; } - return matched; + yield break; } /// @@ -470,41 +469,5 @@ private void InitializeQuery() cache[smarts] = query; } } - - private IList> MatchedAtoms(IList> bondMapping, IAtomContainer atomContainer) - { - List> atomMapping = new List>(); - // loop over each mapping - foreach (var mapping in bondMapping) - { - SortedSet tmp = new SortedSet(); - IAtom atom1 = null; - IAtom atom2 = null; - // loop over this mapping - foreach (var map in mapping) - { - int bondID = map.Id1; - - // get the atoms in this bond - IBond bond = atomContainer.Bonds[bondID]; - atom1 = bond.Begin; - atom2 = bond.End; - - int idx1 = atomContainer.Atoms.IndexOf(atom1); - int idx2 = atomContainer.Atoms.IndexOf(atom2); - - if (!tmp.Contains(idx1)) tmp.Add(idx1); - if (!tmp.Contains(idx2)) tmp.Add(idx2); - } - if (tmp.Count == query.Atoms.Count) atomMapping.Add(tmp); - - // If there is only one bond, check if it matches both ways. - if (mapping.Count == 1 && atom1.AtomicNumber.Equals(atom2.AtomicNumber)) - { - atomMapping.Add(new SortedSet(tmp)); - } - } - return atomMapping; - } } } diff --git a/NCDK/Smiles/SMARTS/SmartsAtomAtomMapFilter.cs b/NCDK/Smiles/SMARTS/SmartsAtomAtomMapFilter.cs index 5b31b4ea..39457d1a 100644 --- a/NCDK/Smiles/SMARTS/SmartsAtomAtomMapFilter.cs +++ b/NCDK/Smiles/SMARTS/SmartsAtomAtomMapFilter.cs @@ -99,7 +99,7 @@ internal SmartsAtomAtomMapFilter(IAtomContainer query, IAtomContainer target) /// /// atom /// mapidx, 0 if undefined - private int Mapidx(IAtom atom) + private static int Mapidx(IAtom atom) { int mapidx = atom.GetProperty(CDKPropertyName.AtomAtomMapping, 0); return mapidx; @@ -110,7 +110,7 @@ private int Mapidx(IAtom atom) /// /// atom /// mapidx, None if undefined - private ReactionRole Role(IAtom atom) + private static ReactionRole Role(IAtom atom) { ReactionRole role = atom.GetProperty(CDKPropertyName.ReactionRole, ReactionRole.None); return role; diff --git a/NCDK/Smiles/SMARTS/SmartsPattern.cs b/NCDK/Smiles/SMARTS/SmartsPattern.cs index 38ebc934..33c0ddd4 100644 --- a/NCDK/Smiles/SMARTS/SmartsPattern.cs +++ b/NCDK/Smiles/SMARTS/SmartsPattern.cs @@ -21,14 +21,13 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ + using NCDK.Aromaticities; using NCDK.Graphs; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers.SMARTS; using NCDK.Smiles.SMARTS.Parser; -using System; using System.Diagnostics; -using System.IO; using System.Linq; namespace NCDK.Smiles.SMARTS @@ -59,14 +58,14 @@ public sealed class SmartsPattern : Pattern private readonly bool ringInfo, hasStereo, hasCompGrp, hasRxnMap; /// Aromaticity model. - private readonly Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.Or(Cycles.AllFinder, Cycles.RelevantFinder)); + private readonly Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.Or(Cycles.AllSimpleFinder, Cycles.RelevantFinder)); /// /// Internal constructor. /// /// pattern /// the builder - /// the pattern could not be parsed + /// the pattern could not be parsed private SmartsPattern(string smarts, IChemObjectBuilder builder) { #if !DEBUG @@ -76,9 +75,9 @@ private SmartsPattern(string smarts, IChemObjectBuilder builder) this.query = SMARTSParser.Parse(smarts, builder); } #if !DEBUG - catch (Exception e) + catch (System.Exception e) { - throw new IOException(e.Message); + throw new System.IO.IOException(e.Message); } #endif this.pattern = Pattern.FindSubstructure(query); @@ -163,7 +162,7 @@ public override Mappings MatchAll(IAtomContainer target) /// SMARTS pattern string /// chem object builder used to create objects /// a new pattern - /// the smarts could not be parsed + /// the smarts could not be parsed public static SmartsPattern Create(string smarts, IChemObjectBuilder builder) { return new SmartsPattern(smarts, builder); @@ -174,7 +173,7 @@ public static SmartsPattern Create(string smarts, IChemObjectBuilder builder) /// /// SMARTS pattern string /// a SMARTS pattern - /// problem with SMARTS string syntax/semantics + /// problem with SMARTS string syntax/semantics public static SmartsPattern Create(string smarts) { return new SmartsPattern(smarts, null); diff --git a/NCDK/Smiles/SmiFlavor.cs b/NCDK/Smiles/SmiFlavor.cs index 14ec1d85..068a63ff 100644 --- a/NCDK/Smiles/SmiFlavor.cs +++ b/NCDK/Smiles/SmiFlavor.cs @@ -25,9 +25,9 @@ namespace NCDK.Smiles { - internal static class SmiFlavors + internal static class SmiFlavorTool { - internal static bool IsSet(this SmiFlavor opts, SmiFlavor opt) + internal static bool IsSet(this SmiFlavors opts, SmiFlavors opt) { return (opts & opt) != 0; } @@ -37,7 +37,7 @@ internal static bool IsSet(this SmiFlavor opts, SmiFlavor opt) /// Flags for customising SMILES generation. /// [Flags] - public enum SmiFlavor + public enum SmiFlavors { /// /// Output SMILES in a canonical order. The order is not guaranteed to be @@ -45,11 +45,13 @@ public enum SmiFlavor /// Canonical = 0x001, + InChI = 0x002, + /// /// Output SMILES in a canonical order using the InChI labelling algorithm. /// /// - InChILabelling = 0x003, + InChILabelling = Canonical | InChI, /// /// Output atom-atom mapping for reactions and atom classes for molecules. The @@ -215,5 +217,5 @@ public enum SmiFlavor /// /// UniversalSmiles = InChILabelling | Isomeric, - } // end of SmiFlavor + } // end of SmiFlavors } diff --git a/NCDK/Smiles/SmilesGenerator.cs b/NCDK/Smiles/SmilesGenerator.cs index 3d690a8e..11386138 100644 --- a/NCDK/Smiles/SmilesGenerator.cs +++ b/NCDK/Smiles/SmilesGenerator.cs @@ -56,13 +56,13 @@ namespace NCDK.Smiles /// produces the same SMILES. Isotope and stereochemistry is encoded. /// /// - /// To output a given flavour the flags in are used: - /// - /// provides more fine grained control, for example, - /// for the following is equivalent to : + /// To output a given flavour the flags in are used: + /// + /// provides more fine grained control, for example, + /// for the following is equivalent to : /// /// Bitwise logic can be used such that we can remove options: - /// "^" + /// "^" /// will generate isomeric SMILES without atomic mass. /// /// @@ -102,8 +102,8 @@ namespace NCDK.Smiles /// can ignore it. /// /// - /// The two aggregate flavours are and . - /// As with other flavours, fine grain control is possible . + /// The two aggregate flavours are and . + /// As with other flavours, fine grain control is possible . /// /// * the unique SMILES generation uses a fast equitable labelling procedure /// and as such there are some structures which may not be unique. The number @@ -123,27 +123,27 @@ namespace NCDK.Smiles // @cdk.githash public sealed class SmilesGenerator { - private readonly SmiFlavor flavour; + private readonly SmiFlavors flavour; /// - /// Create the SMILES generator, the default output is described by: + /// Create the SMILES generator, the default output is described by: /// but is best to choose/set this flavor. /// - /// - [Obsolete("Use " + nameof(SmilesGenerator) + "(int) configuring with " + nameof(SmiFlavor) + ".")] + /// + [Obsolete("Use " + nameof(SmilesGenerator) + "(int) configuring with " + nameof(SmiFlavors) + ".")] public SmilesGenerator() - : this(SmiFlavor.Default) + : this(SmiFlavors.Default) { } /// - /// Create a SMILES generator with the specified . + /// Create a SMILES generator with the specified . /// /// /// /// - /// SMILES flavour flags - public SmilesGenerator(SmiFlavor flavour) + /// SMILES flavour flags + public SmilesGenerator(SmiFlavors flavour) { this.flavour = flavour; } @@ -152,14 +152,14 @@ public SmilesGenerator(SmiFlavor flavour) /// Derived a new generator that writes aromatic atoms in lower case. /// /// - /// The preferred way of doing this is now to use the constructor: + /// The preferred way of doing this is now to use the constructor: /// /// /// a generator for aromatic SMILES [Obsolete("Configure with " + nameof(SmilesGenerator))] public SmilesGenerator Aromatic() { - return new SmilesGenerator(this.flavour | SmiFlavor.UseAromaticSymbols); + return new SmilesGenerator(this.flavour | SmiFlavors.UseAromaticSymbols); } /// @@ -168,14 +168,14 @@ public SmilesGenerator Aromatic() /// property. This method returns a new SmilesGenerator to use. /// /// - /// The preferred way of doing this is now to use the constructor: + /// The preferred way of doing this is now to use the constructor: /// /// /// a generator for SMILES with atom classes [Obsolete("Configure with " + nameof(SmilesGenerator))] public SmilesGenerator WithAtomClasses() { - return new SmilesGenerator(this.flavour | SmiFlavor.AtomAtomMap); + return new SmilesGenerator(this.flavour | SmiFlavors.AtomAtomMap); } /// @@ -187,7 +187,7 @@ public SmilesGenerator WithAtomClasses() /// a new arbitrary SMILES generator public static SmilesGenerator Generic() { - return new SmilesGenerator(SmiFlavor.Generic); + return new SmilesGenerator(SmiFlavors.Generic); } /// @@ -198,7 +198,7 @@ public static SmilesGenerator Generic() /// a new isomeric SMILES generator public static SmilesGenerator Isomeric() { - return new SmilesGenerator(SmiFlavor.Isomeric); + return new SmilesGenerator(SmiFlavors.Isomeric); } /// @@ -208,7 +208,7 @@ public static SmilesGenerator Isomeric() /// a new unique SMILES generator public static SmilesGenerator Unique() { - return new SmilesGenerator(SmiFlavor.Unique); + return new SmilesGenerator(SmiFlavors.Unique); } /// @@ -223,7 +223,7 @@ public static SmilesGenerator Unique() /// a new absolute SMILES generator public static SmilesGenerator CreateAbsolute() { - return new SmilesGenerator(SmiFlavor.Absolute); + return new SmilesGenerator(SmiFlavors.Absolute); } /// @@ -316,7 +316,7 @@ public string Create(IAtomContainer molecule, int[] order) /// array to store the output order of atoms /// the SMILES string /// a valid SMILES could not be created - public static string Create(IAtomContainer molecule, SmiFlavor flavour, int[] order) + public static string Create(IAtomContainer molecule, SmiFlavors flavour, int[] order) { try { @@ -326,14 +326,14 @@ public static string Create(IAtomContainer molecule, SmiFlavor flavour, int[] or Graph g = CDKToBeam.ToBeamGraph(molecule, flavour); // apply the canonical labelling - if (SmiFlavors.IsSet(flavour, SmiFlavor.Canonical)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.Canonical)) { // determine the output order int[] labels = Labels(flavour, molecule); g = g.Permute(labels).Resonate(); - if (SmiFlavors.IsSet(flavour, SmiFlavor.StereoCisTrans)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.StereoCisTrans)) { // FIXME: required to ensure canonical double bond labelling g.Sort(new Graph.VisitHighOrderFirst()); @@ -356,10 +356,9 @@ public static string Create(IAtomContainer molecule, SmiFlavor flavour, int[] or canorder[i] = order[labels[i]]; System.Array.Copy(canorder, 0, order, 0, order.Length); - if (SmiFlavors.IsSet(flavour, SmiFlavor.CxSmilesWithCoords)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.CxSmilesWithCoords)) { - smiles += CxSmilesGenerator.Generate(GetCxSmilesState(flavour, molecule), - flavour, null, order); + smiles += CxSmilesGenerator.Generate(GetCxSmilesState(flavour, molecule), flavour, null, order); } return smiles; @@ -368,7 +367,7 @@ public static string Create(IAtomContainer molecule, SmiFlavor flavour, int[] or { string smiles = g.ToSmiles(order); - if (SmiFlavors.IsSet(flavour, SmiFlavor.CxSmilesWithCoords)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.CxSmilesWithCoords)) { smiles += CxSmilesGenerator.Generate(GetCxSmilesState(flavour, molecule), flavour, null, order); } @@ -405,9 +404,9 @@ public string Create(IReaction reaction) } // utility method that safely collects the Sgroup from a molecule - private void SafeAddSgroups(List sgroups, IAtomContainer mol) + private static void SafeAddSgroups(List sgroups, IAtomContainer mol) { - IList molSgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var molSgroups = mol.GetCtabSgroups(); if (molSgroups != null) foreach (var g in molSgroups) sgroups.Add(g); @@ -460,9 +459,9 @@ public string Create(IReaction reaction, int[] ordering) } // we need to make sure we generate without the CXSMILES layers - string smi = Create(reactantPart, flavour & ~SmiFlavor.CxSmilesWithCoords, reactantOrder) + ">" + - Create(agentPart, flavour & ~SmiFlavor.CxSmilesWithCoords, agentOrder) + ">" + - Create(productPart, flavour & ~SmiFlavor.CxSmilesWithCoords, productOrder); + string smi = Create(reactantPart, flavour & ~SmiFlavors.CxSmilesWithCoords, reactantOrder) + ">" + + Create(agentPart, flavour & ~SmiFlavors.CxSmilesWithCoords, agentOrder) + ">" + + Create(productPart, flavour & ~SmiFlavors.CxSmilesWithCoords, productOrder); // copy ordering back to unified array and adjust values int agentBeg = reactantOrder.Length; @@ -476,23 +475,22 @@ public string Create(IReaction reaction, int[] ordering) for (int i = agentEnd; i < prodEnd; i++) ordering[i] += agentEnd; - if (SmiFlavors.IsSet(flavour, SmiFlavor.CxSmilesWithCoords)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.CxSmilesWithCoords)) { - IAtomContainer unified = reaction.Builder.NewAtomContainer(); + var unified = reaction.Builder.NewAtomContainer(); unified.Add(reactantPart); unified.Add(agentPart); unified.Add(productPart); - unified.SetProperty(CDKPropertyName.CtabSgroups, sgroups); + unified.SetCtabSgroups(sgroups); // base CXSMILES state information - CxSmilesState cxstate = GetCxSmilesState(flavour, unified); + var cxstate = GetCxSmilesState(flavour, unified); int[] components = null; // extra state info on fragment grouping, specific to reactions - if (SmiFlavors.IsSet(flavour, SmiFlavor.CxFragmentGroup)) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.CxFragmentGroup)) { - cxstate.fragGroups = new List>(); // calculate the connected components @@ -532,10 +530,8 @@ public string Create(IReaction reaction, int[] ordering) cxstate.fragGroups.Add(new List(tmp)); beg = end; } - } - smi += CxSmilesGenerator.Generate(cxstate, flavour, components, ordering); } @@ -561,12 +557,12 @@ public void SetUseAromaticityFlag(bool useAromaticityFlag) /// the molecule to /// the permutation /// - private static int[] Labels(SmiFlavor flavour, IAtomContainer molecule) + private static int[] Labels(SmiFlavors flavour, IAtomContainer molecule) { // FIXME: use SmiOpt.InChiLabelling - long[] labels = SmiFlavors.IsSet(flavour, SmiFlavor.Isomeric) ? InChINumbers(molecule) + var labels = SmiFlavorTool.IsSet(flavour, SmiFlavors.Isomeric) ? InChINumbers(molecule) : Canon.Label(molecule, GraphUtil.ToAdjList(molecule)); - int[] cpy = new int[labels.Length]; + var cpy = new int[labels.Length]; for (int i = 0; i < labels.Length; i++) cpy[i] = (int)labels[i] - 1; return cpy; @@ -603,16 +599,15 @@ private static long[] InChINumbers(IAtomContainer container) } catch (FileNotFoundException) { - throw new CDKException("The cdk-inchi module is not loaded," - + " this module is need when generating absolute SMILES."); + throw new CDKException("The cdk-inchi module is not loaded, this module is need when generating absolute SMILES."); } catch (TypeLoadException e) { - throw new CDKException("The method " + mname + " was not found", e); + throw new CDKException($"The method {mname} was not found", e); } catch (TargetInvocationException e) { - throw new CDKException("An InChI could not be generated and used to canonise SMILES: " + e.Message, e); + throw new CDKException($"An InChI could not be generated and used to canonise SMILES: {e.Message}", e); } finally { @@ -659,11 +654,11 @@ private static List ToAtomIdxs(ICollection atoms, IDictionary(), + atomCoords = new List(), coordFlag = false }; @@ -676,7 +671,7 @@ private static CxSmilesState GetCxSmilesState(SmiFlavor flavour, IAtomContainer if (atom is IPseudoAtom) { if (state.atomLabels == null) - state.atomLabels = new Dictionary(); + state.atomLabels = new SortedDictionary(); IPseudoAtom pseudo = (IPseudoAtom)atom; if (pseudo.AttachPointNum > 0) @@ -685,7 +680,7 @@ private static CxSmilesState GetCxSmilesState(SmiFlavor flavour, IAtomContainer } else { - if (!"*".Equals(pseudo.Label)) + if (!"*".Equals(pseudo.Label, StringComparison.Ordinal)) state.atomLabels[idx] = pseudo.Label; } } @@ -693,7 +688,7 @@ private static CxSmilesState GetCxSmilesState(SmiFlavor flavour, IAtomContainer if (comment != null) { if (state.atomValues == null) - state.atomValues = new Dictionary(); + state.atomValues = new SortedDictionary(); state.atomValues[idx] = comment.ToString(); } atomidx[atom] = idx; @@ -701,29 +696,29 @@ private static CxSmilesState GetCxSmilesState(SmiFlavor flavour, IAtomContainer var p2 = atom.Point2D; var p3 = atom.Point3D; - if (SmiFlavors.IsSet(flavour, SmiFlavor.Cx2dCoordinates) && p2 != null) + if (SmiFlavorTool.IsSet(flavour, SmiFlavors.Cx2dCoordinates) && p2 != null) { - state.AtomCoords.Add(new double[] { p2.Value.X, p2.Value.Y, 0 }); + state.atomCoords.Add(new double[] { p2.Value.X, p2.Value.Y, 0 }); state.coordFlag = true; } - else if (SmiFlavors.IsSet(flavour, SmiFlavor.Cx3dCoordinates) && p3 != null) + else if (SmiFlavorTool.IsSet(flavour, SmiFlavors.Cx3dCoordinates) && p3 != null) { - state.AtomCoords.Add(new double[] { p3.Value.X, p3.Value.Y, p3.Value.Z }); + state.atomCoords.Add(new double[] { p3.Value.X, p3.Value.Y, p3.Value.Z }); state.coordFlag = true; } - else if (SmiFlavors.IsSet(flavour, SmiFlavor.CxCoordinates)) + else if (SmiFlavorTool.IsSet(flavour, SmiFlavors.CxCoordinates)) { - state.AtomCoords.Add(new double[3]); + state.atomCoords.Add(new double[3]); } } if (!state.coordFlag) - state.AtomCoords = null; + state.atomCoords = null; // radicals if (mol.SingleElectrons.Count > 0) { - state.atomRads = new Dictionary(); + state.atomRads = new SortedDictionary(); foreach (ISingleElectron radical in mol.SingleElectrons) { // 0->1, 1->2, 2->3 @@ -740,11 +735,11 @@ private static CxSmilesState GetCxSmilesState(SmiFlavor flavour, IAtomContainer } } - IList sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); if (sgroups != null) { state.sgroups = new List(); - state.positionVar = new Dictionary>(); + state.positionVar = new SortedDictionary>(); foreach (Sgroup sgroup in sgroups) { switch (sgroup.Type) @@ -848,7 +843,7 @@ private static string GetSgroupPolymerKey(Sgroup sgroup) case SgroupType.CtabGraft: return "grf"; default: - throw new ArgumentException(); + throw new ArgumentException($"{sgroup.Type} is not proper."); } } } diff --git a/NCDK/Smiles/SmilesParser.cs b/NCDK/Smiles/SmilesParser.cs index 705d1fe6..cde136f3 100644 --- a/NCDK/Smiles/SmilesParser.cs +++ b/NCDK/Smiles/SmilesParser.cs @@ -30,6 +30,7 @@ using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; @@ -212,8 +213,7 @@ private IAtomContainer ParseSmiles(string smiles, bool isRxnPart) // convert the Beam object model to the CDK - note exception thrown // if a kekule structure could not be assigned. - IAtomContainer mol = beamToCDK.ToAtomContainer(kekulise ? g.Kekule() : g, - kekulise); + var mol = beamToCDK.ToAtomContainer(kekulise ? g.Kekule() : g, kekulise); if (!isRxnPart) { @@ -225,18 +225,18 @@ private IAtomContainer ParseSmiles(string smiles, bool isRxnPart) catch (Exception e) { // e.StackTrace - throw new NCDK.InvalidSmilesException("Error parsing CXSMILES:" + e.Message); + throw new InvalidSmilesException($"Error parsing CXSMILES: {e.Message}"); } } return mol; } catch (IOException e) { - throw new NCDK.InvalidSmilesException("could not parse '" + smiles + "', " + e.Message); + throw new InvalidSmilesException($"could not parse '{smiles}', {e.Message}"); } catch (Exception) { - throw new NCDK.InvalidSmilesException("could not parse '" + smiles + "'"); + throw new InvalidSmilesException($"could not parse '{smiles}'"); } } @@ -245,11 +245,11 @@ private IAtomContainer ParseSmiles(string smiles, bool isRxnPart) /// /// value /// the integer value - private int ParseIntSafe(string val) + private static int ParseIntSafe(string val) { try { - return int.Parse(val); + return int.Parse(val, NumberFormatInfo.InvariantInfo); } catch (FormatException) { @@ -270,12 +270,11 @@ private void ParseMolCXSMILES(string title, IAtomContainer mol) { if ((pos = CxSmilesParser.ProcessCx(title, cxstate = new CxSmilesState())) >= 0) { - // set the correct title mol.Title = title.Substring(pos); - IDictionary atomToMol = new Dictionary(mol.Atoms.Count); - IList atoms = new List(mol.Atoms.Count); + var atomToMol = new Dictionary(mol.Atoms.Count); + var atoms = new List(mol.Atoms.Count); foreach (var atom in mol.Atoms) { @@ -304,8 +303,8 @@ private void ParseRxnCXSMILES(string title, IReaction rxn) // set the correct title rxn.SetProperty(CDKPropertyName.Title, title.Substring(pos)); - IDictionary atomToMol = new Dictionary(100); - IList atoms = new List(); + var atomToMol = new Dictionary(100); + var atoms = new List(); HandleFragmentGrouping(rxn, cxstate); // merge all together @@ -345,7 +344,7 @@ private void ParseRxnCXSMILES(string title, IReaction rxn) /// /// reaction /// state - private void HandleFragmentGrouping(IReaction rxn, CxSmilesState cxstate) + private static void HandleFragmentGrouping(IReaction rxn, CxSmilesState cxstate) { // repartition/merge fragments if (cxstate.fragGroups != null) @@ -355,8 +354,8 @@ private void HandleFragmentGrouping(IReaction rxn, CxSmilesState cxstate) int product = 3; // note we don't use a list for fragmap as the indexes need to stay consistent - IDictionary fragMap = new SortedDictionary(); - IDictionary roleMap = new Dictionary(); + var fragMap = new SortedDictionary(); + var roleMap = new Dictionary(); foreach (var mol in rxn.Reactants) { @@ -376,11 +375,11 @@ private void HandleFragmentGrouping(IReaction rxn, CxSmilesState cxstate) // check validity of group bool invalid = false; - ICollection visit = new HashSet(); + var visit = new HashSet(); foreach (var grouping in cxstate.fragGroups) { - IAtomContainer dest = fragMap[grouping[0]]; + var dest = fragMap[grouping[0]]; if (dest == null) continue; if (visit.Contains(grouping[0])) @@ -393,7 +392,7 @@ private void HandleFragmentGrouping(IReaction rxn, CxSmilesState cxstate) invalid = true; else visit.Add(grouping[i]); - IAtomContainer src = fragMap[grouping[i]]; + var src = fragMap[grouping[i]]; if (src != null) { dest.Add(src); @@ -436,8 +435,8 @@ private void HandleFragmentGrouping(IReaction rxn, CxSmilesState cxstate) /// the CXSMILES state to read from private void AssignCxSmilesInfo(IChemObjectBuilder bldr, IChemObject chemObj, - IList atoms, - IDictionary atomToMol, + List atoms, + Dictionary atomToMol, CxSmilesState cxstate) { // atom-labels - must be done first as we replace atoms @@ -449,8 +448,8 @@ private void AssignCxSmilesInfo(IChemObjectBuilder bldr, if (e.Key >= atoms.Count) continue; - IAtom old = atoms[e.Key]; - IPseudoAtom pseudo = bldr.NewPseudoAtom(); + var old = atoms[e.Key]; + var pseudo = bldr.NewPseudoAtom(); string val = e.Value; // specialised label handling @@ -462,7 +461,7 @@ private void AssignCxSmilesInfo(IChemObjectBuilder bldr, pseudo.Label = val; pseudo.AtomicNumber = 0; pseudo.ImplicitHydrogenCount = 0; - IAtomContainer mol = atomToMol[old]; + var mol = atomToMol[old]; AtomContainerManipulator.ReplaceAtomByAtom(mol, old, pseudo); atomToMol.Add(pseudo, mol); atoms[e.Key] = pseudo; @@ -477,25 +476,25 @@ private void AssignCxSmilesInfo(IChemObjectBuilder bldr, } // atom-coordinates - if (cxstate.AtomCoords != null) + if (cxstate.atomCoords != null) { int numAtoms = atoms.Count; - int numCoords = cxstate.AtomCoords.Count; + int numCoords = cxstate.atomCoords.Count; int lim = Math.Min(numAtoms, numCoords); if (cxstate.coordFlag) { for (int i = 0; i < lim; i++) atoms[i].Point3D = new Vector3( - cxstate.AtomCoords[i][0], - cxstate.AtomCoords[i][1], - cxstate.AtomCoords[i][2]); + cxstate.atomCoords[i][0], + cxstate.atomCoords[i][1], + cxstate.atomCoords[i][2]); } else { for (int i = 0; i < lim; i++) atoms[i].Point2D = new Vector2( - cxstate.AtomCoords[i][0], - cxstate.AtomCoords[i][1]); + cxstate.atomCoords[i][0], + cxstate.atomCoords[i][1]); } } @@ -528,26 +527,23 @@ private void AssignCxSmilesInfo(IChemObjectBuilder bldr, count = 3; break; } - IAtom atom = atoms[e.Key]; - IAtomContainer mol = atomToMol[atom]; + var atom = atoms[e.Key]; + var mol = atomToMol[atom]; while (count-- > 0) mol.SingleElectrons.Add(bldr.NewSingleElectron(atom)); } } - IMultiDictionary sgroupMap = new MultiDictionary(); + var sgroupMap = new MultiDictionary(); // positional-variation if (cxstate.positionVar != null) { foreach (var e in cxstate.positionVar) { - Sgroup sgroup = new Sgroup - { - Type = SgroupType.ExtMulticenter - }; - IAtom beg = atoms[e.Key]; - IAtomContainer mol = atomToMol[beg]; + var sgroup = new Sgroup { Type = SgroupType.ExtMulticenter }; + var beg = atoms[e.Key]; + var mol = atomToMol[beg]; var bonds = mol.GetConnectedBonds(beg); if (bonds.Count() == 0) continue; // bad @@ -576,16 +572,15 @@ private void AssignCxSmilesInfo(IChemObjectBuilder bldr, { foreach (var psgroup in cxstate.sgroups) { - Sgroup sgroup = new Sgroup(); - - ICollection atomset = new HashSet(); + var sgroup = new Sgroup(); + var atomset = new HashSet(); IAtomContainer mol = null; foreach (var idx in psgroup.AtomSet) { if (idx >= atoms.Count) continue; - IAtom atom = atoms[idx]; - IAtomContainer amol = atomToMol[atom]; + var atom = atoms[idx]; + var amol = atomToMol[atom]; if (mol == null) mol = amol; @@ -670,7 +665,7 @@ private void AssignCxSmilesInfo(IChemObjectBuilder bldr, // assign Sgroups foreach (var e in sgroupMap) - e.Key.SetProperty(CDKPropertyName.CtabSgroups, new List(e.Value)); + e.Key.SetCtabSgroups(new List(e.Value)); } /// diff --git a/NCDK/Stereo/AbstractStereo.cs b/NCDK/Stereo/AbstractStereo.cs index 3c582f04..b3c200a1 100644 --- a/NCDK/Stereo/AbstractStereo.cs +++ b/NCDK/Stereo/AbstractStereo.cs @@ -23,7 +23,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; namespace NCDK.Stereo { @@ -37,18 +36,18 @@ public abstract class AbstractStereo private List carriers; private IChemObjectBuilder builder; - internal AbstractStereo(TF focus, IList carriers, StereoElement value) + internal AbstractStereo(TF focus, IReadOnlyList carriers, StereoElement value) { if (focus == null) - throw new ArgumentNullException("Focus of stereochemistry can not be null!"); + throw new ArgumentNullException(nameof(focus), "Focus of stereochemistry can not be null!"); if (carriers == null) - throw new ArgumentNullException("Carriers of the configuration can not be null!"); + throw new ArgumentNullException(nameof(carriers), "Carriers of the configuration can not be null!"); if (carriers.Count != value.CarrierLength) throw new ArgumentException($"Unexpected number of stereo carriers! expected {value.CarrierLength} was {carriers.Count}"); foreach (TC carrier in carriers) { if (carrier == null) - throw new ArgumentNullException("A carrier was undefined!"); + throw new ArgumentNullException(nameof(carriers), "A carrier was undefined!"); } this.value = value; this.focus = focus; @@ -60,19 +59,20 @@ internal AbstractStereo(TF focus, IList carriers, StereoElement value) public virtual TF Focus => focus; /// - public virtual IList Carriers => carriers; - - /// - public IReadOnlyList ReadOnlyCarriers => new ReadOnlyCollection(Carriers); + public IReadOnlyList Carriers + { + get => carriers; + set => carriers = new List(value); + } /// - public virtual StereoElement.Classes Class => value.Class; + public virtual StereoClass Class => value.Class; /// - public virtual StereoElement.Configuration Configure + public virtual StereoConfigurations Configure { - get { return value.Configure; } - set { this.value.Configure = value; } + get => value.Configuration; + set => this.value.Configuration = value; } /// @@ -97,7 +97,7 @@ public virtual ICDKObject Clone(CDKObjectMap map) if (!map.TryGetValue(focus, out TF newfocus)) newfocus = focus; - List newcarriers = carriers; + var newcarriers = carriers; for (int i = 0; i < newcarriers.Count; i++) { if (map.TryGetValue(newcarriers[i], out TC newcarrier)) @@ -119,7 +119,7 @@ public virtual object Clone() return Clone(new CDKObjectMap()); } - protected abstract IStereoElement Create(TF focus, IList carriers, StereoElement stereo); + protected abstract IStereoElement Create(TF focus, IReadOnlyList carriers, StereoElement stereo); /// public virtual IChemObjectBuilder Builder @@ -146,10 +146,10 @@ public virtual IChemObjectBuilder Builder internal const int F = 5; // apply the inverse of a permutation - protected static T[] InvApply(T[] src, int[] perm) + internal static T[] InvApply(IReadOnlyList src, int[] perm) { - T[] res = new T[src.Length]; - for (int i = 0; i < src.Length; i++) + T[] res = new T[src.Count]; + for (int i = 0; i < src.Count; i++) res[i] = src[perm[i]]; return res; } diff --git a/NCDK/Stereo/Atropisomeric.cs b/NCDK/Stereo/Atropisomeric.cs index e2f2da75..e80a17fa 100644 --- a/NCDK/Stereo/Atropisomeric.cs +++ b/NCDK/Stereo/Atropisomeric.cs @@ -61,16 +61,16 @@ public class Atropisomeric /// /// the focus bond /// the carriers - /// the configuration or - public Atropisomeric(IBond focus, IEnumerable carriers, StereoElement.Configuration value) - : base(focus, carriers.ToList(), new StereoElement(StereoElement.Classes.Atropisomeric, value)) + /// the configuration or + public Atropisomeric(IBond focus, IEnumerable carriers, StereoConfigurations value) + : base(focus, carriers.ToList(), new StereoElement(StereoClass.Atropisomeric, value)) { } /// - protected override IStereoElement Create(IBond focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IBond focus, IReadOnlyList carriers, StereoElement stereo) { - return new Atropisomeric(focus, carriers.ToArray(), stereo.Configure); + return new Atropisomeric(focus, carriers.ToArray(), stereo.Configuration); } } } diff --git a/NCDK/Stereo/CyclicCarbohydrateRecognition.cs b/NCDK/Stereo/CyclicCarbohydrateRecognition.cs index 5d77fcac..d35c905a 100644 --- a/NCDK/Stereo/CyclicCarbohydrateRecognition.cs +++ b/NCDK/Stereo/CyclicCarbohydrateRecognition.cs @@ -84,49 +84,48 @@ public CyclicCarbohydrateRecognition(IAtomContainer container, /// /// the types of projections to recognise /// recognised stereocenters - public IList> Recognise(ICollection projections) + public IEnumerable> Recognise(ICollection projections) { if (!projections.Contains(Projection.Haworth) && !projections.Contains(Projection.Chair)) - return Array.Empty>(); + yield break; - var elements = new List>(); - - RingSearch ringSearch = new RingSearch(container, graph); + var ringSearch = new RingSearch(container, graph); foreach (var isolated in ringSearch.Isolated()) { if (isolated.Length < 5 || isolated.Length > 7) continue; - int[] cycle = Arrays.CopyOf(GraphUtil.Cycle(graph, isolated), + var cycle = Arrays.CopyOf(GraphUtil.Cycle(graph, isolated), isolated.Length); - Vector2[] points = CoordinatesOfCycle(cycle, container); - Turn[] turns = GetTurns(points); - WoundProjection projection = WoundProjection.OfTurns(turns); + var points = CoordinatesOfCycle(cycle, container); + var turns = GetTurns(points); + var projection = WoundProjection.OfTurns(turns); if (!projections.Contains(projection.Projection)) continue; - // ring is not aligned correctly for haworth + // ring is not aligned correctly for Haworth if (projection.Projection == Projection.Haworth && !CheckHaworthAlignment(points)) continue; - Vector2 horizontalXy = HorizontalOffset(points, turns, projection.Projection); + var horizontalXy = HorizontalOffset(points, turns, projection.Projection); // near vertical, should also flag as potentially ambiguous if (1 - Math.Abs(horizontalXy.Y) < QuartCardinalityThreshold) continue; - int[] above = (int[])cycle.Clone(); - int[] below = (int[])cycle.Clone(); + var above = (int[])cycle.Clone(); + var below = (int[])cycle.Clone(); if (!AssignSubstituents(cycle, above, below, projection, horizontalXy)) continue; - elements.AddRange(NewTetrahedralCenters(cycle, above, below, projection)); + foreach (var center in NewTetrahedralCenters(cycle, above, below, projection)) + yield return center; } - return elements; + yield break; } /// @@ -136,18 +135,19 @@ public IList> Recognise(ICollec /// array of turns (left, right) or null if a parallel line was found public static Turn[] GetTurns(Vector2[] points) { - Turn[] turns = new Turn[points.Length]; + var turns = new Turn[points.Length]; // cycle of size 6 is [1,2,3,4,5,6] not closed for (int i = 1; i <= points.Length; i++) { - Vector2 prevXy = points[i - 1]; - Vector2 currXy = points[i % points.Length]; - Vector2 nextXy = points[(i + 1) % points.Length]; - int parity = (int)Math.Sign(Det(prevXy.X, prevXy.Y, + var prevXy = points[i - 1]; + var currXy = points[i % points.Length]; + var nextXy = points[(i + 1) % points.Length]; + var parity = (int)Math.Sign(Det(prevXy.X, prevXy.Y, currXy.X, currXy.Y, nextXy.X, nextXy.Y)); - if (parity == 0) return null; + if (parity == 0) + return null; turns[i % points.Length] = parity < 0 ? Turn.Right : Turn.Left; } @@ -166,10 +166,10 @@ public static Turn[] GetTurns(Vector2[] points) /// offset from the horizontal axis /// assignment okay (true), not okay (false) private bool AssignSubstituents(int[] cycle, - int[] above, - int[] below, - WoundProjection projection, - Vector2 horizontalXy) + int[] above, + int[] below, + WoundProjection projection, + Vector2 horizontalXy) { bool haworth = projection.Projection == Projection.Haworth; @@ -177,7 +177,6 @@ private bool AssignSubstituents(int[] cycle, for (int i = 1; i <= cycle.Length; i++) { - int j = i % cycle.Length; int prev = cycle[i - 1]; @@ -190,22 +189,24 @@ private bool AssignSubstituents(int[] cycle, if (ws.Length > 2 || ws.Length < 1) continue; - Vector2 centerXy = container.Atoms[curr].Point2D.Value; + var centerXy = container.Atoms[curr].Point2D.Value; // determine the direction of each substituent foreach (var w in ws) { - Vector2 otherXy = container.Atoms[w].Point2D.Value; - Direction direction = ObtainDirection(centerXy, otherXy, horizontalXy, haworth); + var otherXy = container.Atoms[w].Point2D.Value; + var direction = ObtainDirection(centerXy, otherXy, horizontalXy, haworth); switch (direction) { case Direction.Up: - if (above[j] != curr) return false; + if (above[j] != curr) + return false; above[j] = w; break; case Direction.Down: - if (below[j] != curr) return false; + if (below[j] != curr) + return false; below[j] = w; break; case Direction.Other: @@ -229,9 +230,9 @@ private bool AssignSubstituents(int[] cycle, /// vertices below the cycle /// type of projection /// zero of more stereocenters - private IList NewTetrahedralCenters(int[] cycle, int[] above, int[] below, WoundProjection type) + private IReadOnlyList NewTetrahedralCenters(int[] cycle, int[] above, int[] below, WoundProjection type) { - List centers = new List(cycle.Length); + var centers = new List(cycle.Length); for (int i = 1; i <= cycle.Length; i++) { @@ -274,7 +275,7 @@ private IList NewTetrahedralCenters(int[] cycle, int[] ab /// coordinates of the cycle private static Vector2[] CoordinatesOfCycle(int[] cycle, IAtomContainer container) { - Vector2[] points = new Vector2[cycle.Length]; + var points = new Vector2[cycle.Length]; for (int i = 0; i < cycle.Length; i++) { points[i] = container.Atoms[cycle[i]].Point2D.Value; @@ -293,7 +294,7 @@ private static Vector2[] CoordinatesOfCycle(int[] cycle, IAtomContainer containe private static int[] Filter(int[] org, int skip1, int skip2) { int n = 0; - int[] dest = new int[org.Length - 2]; + var dest = new int[org.Length - 2]; foreach (var w in org) { if (w != skip1 && w != skip2) dest[n++] = w; @@ -313,11 +314,11 @@ private static int[] Filter(int[] org, int skip1, int skip2) /// the direction (up, down, other) private static Direction ObtainDirection(Vector2 centerXy, Vector2 substituentXy, Vector2 horizontalXy, bool haworth) { - double deltaX = substituentXy.X - centerXy.X; - double deltaY = substituentXy.Y - centerXy.Y; + var deltaX = substituentXy.X - centerXy.X; + var deltaY = substituentXy.Y - centerXy.Y; // normalise vector length so threshold is independent of length - double mag = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); + var mag = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); deltaX /= mag; deltaY /= mag; @@ -349,14 +350,14 @@ private static Direction ObtainDirection(Vector2 centerXy, Vector2 substituentXy /// /// the points of atoms in the ring /// whether the Haworth alignment is correct - private bool CheckHaworthAlignment(Vector2[] points) + private static bool CheckHaworthAlignment(Vector2[] points) { for (int i = 0; i < points.Length; i++) { - Vector2 curr = points[i]; - Vector2 next = points[(i + 1) % points.Length]; + var curr = points[i]; + var next = points[(i + 1) % points.Length]; - double deltaY = curr.Y - next.Y; + var deltaY = curr.Y - next.Y; if (Math.Abs(deltaY) < CardinalityThreshold) return true; @@ -374,7 +375,7 @@ private bool CheckHaworthAlignment(Vector2[] points) /// the turns in the cycle (left/right) /// the type of projection /// the horizontal offset - private Vector2 HorizontalOffset(Vector2[] points, Turn[] turns, Projection projection) + private static Vector2 HorizontalOffset(Vector2[] points, Turn[] turns, Projection projection) { // Haworth must currently be drawn vertically, I have seen them drawn // slanted but it's difficult to determine which way the projection @@ -383,15 +384,15 @@ private Vector2 HorizontalOffset(Vector2[] points, Turn[] turns, Projection proj return Vector2.Zero; // the atoms either side of a central atom are our reference - int offset = ChairCenterOffset(turns); - int prev = (offset + 5) % 6; - int next = (offset + 7) % 6; + var offset = ChairCenterOffset(turns); + var prev = (offset + 5) % 6; + var next = (offset + 7) % 6; // and the axis formed by these atoms is our horizontal reference which // we normalise - double deltaX = points[prev].X - points[next].X; - double deltaY = points[prev].Y - points[next].Y; - double mag = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); + var deltaX = points[prev].X - points[next].X; + var deltaY = points[prev].Y - points[next].Y; + var mag = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); deltaX /= mag; deltaY /= mag; @@ -444,9 +445,9 @@ private static double Det(double xa, double ya, double xb, double yb, double xc, /// the bond is a planar sigma bond private static bool IsPlanarSigmaBond(IBond bond) { - return bond != null && - BondOrder.Single.Equals(bond.Order) && - BondStereo.None.Equals(bond.Stereo); + return bond != null + && BondOrder.Single.Equals(bond.Order) + && BondStereo.None.Equals(bond.Stereo); } /// @@ -484,11 +485,11 @@ private class WoundProjection public Projection Projection { get; private set; } public TetrahedralStereo Winding { get; private set; } - private readonly static IDictionary map; + private readonly static Dictionary map = MakeMap(); - static WoundProjection() + private static Dictionary MakeMap() { - map = new Dictionary + var map = new Dictionary { // Haworth |V| = 5 { new Key(Turn.Left, Turn.Left, Turn.Left, Turn.Left, Turn.Left), HaworthAnticlockwise }, @@ -524,6 +525,7 @@ static WoundProjection() { new Key(Turn.Right, Turn.Right, Turn.Left, Turn.Left, Turn.Right, Turn.Right), BoatClockwise }, { new Key(Turn.Right, Turn.Left, Turn.Left, Turn.Right, Turn.Right, Turn.Right), BoatClockwise } }; + return map; } public WoundProjection(Projection projection, TetrahedralStereo winding) @@ -553,8 +555,8 @@ internal Key(params Turn[] turns) public override bool Equals(object o) { - Key key = o as Key; - if (key == null) return false; + if (!(o is Key key)) + return false; return Arrays.AreEqual(turns, key.turns); } diff --git a/NCDK/Stereo/DoubleBondStereochemistry.cs b/NCDK/Stereo/DoubleBondStereochemistry.cs index 2d5d5cb9..c10d5869 100644 --- a/NCDK/Stereo/DoubleBondStereochemistry.cs +++ b/NCDK/Stereo/DoubleBondStereochemistry.cs @@ -46,21 +46,21 @@ public DoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBond { } - public DoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBonds, StereoElement.Configuration configure) - : base(stereoBond, ligandBonds.ToList(), new StereoElement(StereoElement.Classes.CisTrans, configure)) + public DoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBonds, StereoConfigurations configure) + : base(stereoBond, ligandBonds.ToList(), new StereoElement(StereoClass.CisTrans, configure)) { } public DoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBonds, StereoElement stereo) - : this(stereoBond, ligandBonds, stereo.Configure) + : this(stereoBond, ligandBonds, stereo.Configuration) { } - public virtual IReadOnlyList Bonds => new ReadOnlyCollection(new List(Carriers)); + public virtual IReadOnlyList Bonds => Carriers; public virtual IBond StereoBond => Focus; public virtual DoubleBondConformation Stereo => Configure.ToConformation(); - protected override IStereoElement Create(IBond focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IBond focus, IReadOnlyList carriers, StereoElement stereo) { return new DoubleBondStereochemistry(focus, carriers, stereo); } diff --git a/NCDK/Stereo/ExtendedTetrahedral.cs b/NCDK/Stereo/ExtendedTetrahedral.cs index a325b187..387eb723 100644 --- a/NCDK/Stereo/ExtendedTetrahedral.cs +++ b/NCDK/Stereo/ExtendedTetrahedral.cs @@ -92,13 +92,13 @@ public ExtendedTetrahedral(IAtom focus, IEnumerable peripherals, Tetrahed { } - ExtendedTetrahedral(IAtom focus, IEnumerable peripherals, StereoElement.Configuration configure) - : base(focus, peripherals.ToList(), new StereoElement(StereoElement.Classes.Allenal, configure)) + ExtendedTetrahedral(IAtom focus, IEnumerable peripherals, StereoConfigurations configure) + : base(focus, peripherals.ToList(), new StereoElement(StereoClass.Allenal, configure)) { } ExtendedTetrahedral(IAtom focus, IEnumerable peripherals, StereoElement stereo) - : this(focus, peripherals, stereo.Configure) + : this(focus, peripherals, stereo.Configuration) { } @@ -107,7 +107,7 @@ public ExtendedTetrahedral(IAtom focus, IEnumerable peripherals, Tetrahed /// atoms in the cumulated system. /// /// the peripheral atoms - public IAtom[] Peripherals => Carriers.ToArray(); + public IReadOnlyList Peripherals => Carriers; /// /// The winding of the peripherals, when viewed from the first atom. @@ -146,10 +146,11 @@ public IAtom[] FindTerminalAtoms(IAtomContainer container) { var focusBonds = container.GetConnectedBonds(Focus).ToList(); - if (focusBonds.Count != 2) throw new ArgumentException("focus must have exactly 2 neighbors"); + if (focusBonds.Count != 2) + throw new ArgumentException("focus must have exactly 2 neighbors"); - IAtom left = focusBonds[0].GetOther(Focus); - IAtom right = focusBonds[1].GetOther(Focus); + var left = focusBonds[0].GetOther(Focus); + var right = focusBonds[1].GetOther(Focus); var leftAtoms = container.GetConnectedAtoms(left); var carriers = Carriers; @@ -164,7 +165,7 @@ public IAtom[] FindTerminalAtoms(IAtomContainer container) } } - protected override IStereoElement Create(IAtom focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IAtom focus, IReadOnlyList carriers, StereoElement stereo) { return new ExtendedTetrahedral(focus, carriers, stereo); } diff --git a/NCDK/Stereo/FischerRecognition.cs b/NCDK/Stereo/FischerRecognition.cs index 3fa9f876..d8a332fb 100644 --- a/NCDK/Stereo/FischerRecognition.cs +++ b/NCDK/Stereo/FischerRecognition.cs @@ -21,12 +21,12 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ + using NCDK.Config; +using NCDK.Graphs; using NCDK.RingSearches; using System; using System.Collections.Generic; -using NCDK.Numerics; -using static NCDK.Graphs.GraphUtil; namespace NCDK.Stereo { @@ -82,12 +82,11 @@ internal sealed class FischerRecognition /// /// Required information to recognise stereochemistry. - /// + /// /// input structure /// adjacency list representation /// edge to bond index /// location and type of asymmetries - /// public FischerRecognition(IAtomContainer container, int[][] graph, EdgeToBondMap bonds, @@ -99,55 +98,51 @@ public FischerRecognition(IAtomContainer container, this.stereocenters = stereocenters; } - - /// /// Recognise the tetrahedral stereochemistry in the provided structure. - /// + /// /// allowed projection types /// zero of more stereo elements - /// - public IList> Recognise(ICollection projections) + public IEnumerable> Recognise(ICollection projections) { if (!projections.Contains(Projection.Fischer)) - return Array.Empty>(); + return Array.Empty>(); // build atom index and only recognize 2D depictions - IDictionary atomToIndex = new Dictionary(); + var atomToIndex = new Dictionary(); foreach (var atom in container.Atoms) { if (atom.Point2D == null) - return Array.Empty>(); + return Array.Empty>(); atomToIndex.Add(atom, atomToIndex.Count); } - RingSearch ringSearch = new RingSearch(container, graph); + var ringSearch = new RingSearch(container, graph); - var elements = new List>(5); + var elements = new List>(5); for (int v = 0; v < container.Atoms.Count; v++) { - IAtom focus = container.Atoms[v]; - ChemicalElement elem = ChemicalElement.OfNumber(focus.AtomicNumber.Value); + var focus = container.Atoms[v]; + var elem = ChemicalElement.OfNumber(focus.AtomicNumber.Value); if (elem != ChemicalElements.Carbon) continue; if (ringSearch.Cyclic(v)) continue; - if (stereocenters.ElementType(v) != Stereocenters.CoordinateType.Tetracoordinate) + if (stereocenters.ElementType(v) != CoordinateType.Tetracoordinate) continue; if (!stereocenters.IsStereocenter(v)) continue; - ITetrahedralChirality element = NewTetrahedralCenter(focus, - Neighbors(v, graph, bonds)); + var element = NewTetrahedralCenter(focus, Neighbors(v, graph, bonds)); if (element == null) continue; // east/west bonds must be to terminal atoms - IAtom east = element.Ligands[EAST]; - IAtom west = element.Ligands[WEST]; + var east = element.Ligands[EAST]; + var west = element.Ligands[WEST]; if (east != focus && !IsTerminal(east, atomToIndex)) continue; @@ -165,18 +160,18 @@ public IList> Recognise(ICollec /// Create a new tetrahedral stereocenter of the given focus and neighboring /// bonds. This is an internal method and is presumed the atom can support /// tetrahedral stereochemistry and it has three or four explicit neighbors. - /// + /// + /// /// The stereo element is only created if the local arrangement looks like /// a Fischer projection. - /// + /// /// central atom /// adjacent bonds /// a stereo element, or null if one could not be created - /// public static ITetrahedralChirality NewTetrahedralCenter(IAtom focus, IBond[] bonds) { // obtain the bonds of a centre arranged by cardinal direction - IBond[] cardinalBonds = CardinalBonds(focus, bonds); + var cardinalBonds = CardinalBonds(focus, bonds); if (cardinalBonds == null) return null; @@ -191,7 +186,7 @@ public static ITetrahedralChirality NewTetrahedralCenter(IAtom focus, IBond[] bo // the neighbors of our tetrahedral centre, the EAST or WEST may // be missing so we initialise these with the implicit (focus) - IAtom[] neighbors = new IAtom[]{cardinalBonds[NORTH].GetOther(focus), + var neighbors = new IAtom[]{cardinalBonds[NORTH].GetOther(focus), focus, cardinalBonds[SOUTH].GetOther(focus), focus}; @@ -224,23 +219,21 @@ public static ITetrahedralChirality NewTetrahedralCenter(IAtom focus, IBond[] bo /// Arrange the bonds adjacent to an atom (focus) in cardinal direction. The /// cardinal directions are that of a compass. Bonds are checked as to /// whether they are horizontal or vertical within a predefined threshold. - /// + /// /// an atom /// bonds adjacent to the atom - /// array of bonds organised (N,E,S,W), or null if a bond was found - /// that exceeded the threshold - /// + /// array of bonds organised (N,E,S,W), or null if a bond was found + /// that exceeded the threshold public static IBond[] CardinalBonds(IAtom focus, IBond[] bonds) { - - Vector2 centerXy = focus.Point2D.Value; - IBond[] cardinal = new IBond[4]; + var centerXy = focus.Point2D.Value; + var cardinal = new IBond[4]; foreach (var bond in bonds) { - IAtom other = bond.GetOther(focus); - Vector2 otherXy = other.Point2D.Value; + var other = bond.GetOther(focus); + var otherXy = other.Point2D.Value; double deltaX = otherXy.X - centerXy.X; double deltaY = otherXy.Y - centerXy.Y; @@ -275,11 +268,10 @@ public static IBond[] CardinalBonds(IAtom focus, IBond[] bonds) /// /// Is the atom terminal having only one connection. - /// + /// /// an atom /// a map of atoms to index /// the atom is terminal - /// private bool IsTerminal(IAtom atom, IDictionary atomToIndex) { return graph[atomToIndex[atom]].Length == 1; @@ -288,10 +280,9 @@ private bool IsTerminal(IAtom atom, IDictionary atomToIndex) /// /// Helper method determines if a bond is defined (not null) and whether /// it is a sigma (single) bond with no stereo attribute (wedge/hatch). - /// + /// /// the bond to test /// the bond is a planar sigma bond - /// private static bool IsPlanarSigmaBond(IBond bond) { return bond != null && @@ -302,16 +293,15 @@ private static bool IsPlanarSigmaBond(IBond bond) /// /// Helper method to obtain the neighbouring bonds from an adjacency list /// graph and edge->bond map. - /// + /// /// vertex /// graph (adj list) /// map of edges to bonds /// neighboring bonds - /// private static IBond[] Neighbors(int v, int[][] g, EdgeToBondMap bondMap) { - int[] ws = g[v]; - IBond[] bonds = new IBond[ws.Length]; + var ws = g[v]; + var bonds = new IBond[ws.Length]; for (int i = 0; i < ws.Length; i++) { bonds[i] = bondMap[v, ws[i]]; diff --git a/NCDK/Stereo/Octahedral.cs b/NCDK/Stereo/Octahedral.cs index ace1ff4e..b378a1da 100644 --- a/NCDK/Stereo/Octahedral.cs +++ b/NCDK/Stereo/Octahedral.cs @@ -278,15 +278,14 @@ public sealed class Octahedral : AbstractStereo /// the carriers /// the order of the configuration 0-30. public Octahedral(IAtom focus, IAtom[] carriers, int order) - : base(focus, carriers, new StereoElement(StereoElement.Classes.Octahedral, order)) + : base(focus, carriers, new StereoElement(StereoClass.Octahedral, order)) { if (order < 0 || order > 30) - throw new ArgumentOutOfRangeException("Invalid configuration order!" - + "Should be in range 1-30"); + throw new ArgumentOutOfRangeException(nameof(order), "Invalid configuration order! Should be in range 1-30"); } public Octahedral(IAtom focus, IAtom[] carriers, StereoElement stereo) - : this(focus, carriers, stereo.Configure.Order()) + : this(focus, carriers, stereo.Configuration.Order()) { } /// @@ -310,12 +309,12 @@ public Octahedral Normalize() throw new ArgumentException( "Invalid config order: " + cfg + ", octahedral should be" + "1 <= order <= 30!"); - IAtom[] carriers = InvApply(Carriers.ToArray(), PERMUTATIONS[cfg - 1]); + var carriers = InvApply(Carriers.ToArray(), PERMUTATIONS[cfg - 1]); return new Octahedral(Focus, carriers, 1); } /// - protected override IStereoElement Create(IAtom focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IAtom focus, IReadOnlyList carriers, StereoElement stereo) { return new Octahedral(focus, carriers.ToArray(), diff --git a/NCDK/Stereo/Projection.cs b/NCDK/Stereo/Projection.cs index 402c1b3f..2e6760da 100644 --- a/NCDK/Stereo/Projection.cs +++ b/NCDK/Stereo/Projection.cs @@ -40,7 +40,7 @@ public enum Projection /// Fischer projections are used for linear chain-form carbohydrates. /// They are drawn vertically with all atoms at right angles around stereocenters. /// - Fischer, + Fischer, /// /// Haworth projection are used to depict ring-form carbohydrates. diff --git a/NCDK/Stereo/SquarePlanar.cs b/NCDK/Stereo/SquarePlanar.cs index dd7786f6..64941cfa 100644 --- a/NCDK/Stereo/SquarePlanar.cs +++ b/NCDK/Stereo/SquarePlanar.cs @@ -68,23 +68,24 @@ namespace NCDK.Stereo /// public sealed class SquarePlanar : AbstractStereo { - private static readonly int[][] PERMUTATIONS = new int[][]{ - new[] - {A, B, C, D, A, D, C, B, - B, C, D, A, B, A, D, C, - C, D, A, B, C, B, A, D, - D, C, B, A, D, A, B, C}, // SP1 (U) - new[] - {A, C, B, D, A, D, B, C, - B, D, A, C, B, C, A, D, - C, A, D, B, C, B, D, A, - D, B, C, A, D, A, C, B}, // SP2 (4) - new[] - {A, B, D, C, A, C, D, B, - B, A, C, D, B, D, C, A, - C, D, B, A, C, A, B, D, - D, C, A, B, D, B, A, C}, // SP3 (Z) - }; + private static readonly int[][] PERMUTATIONS = new int[][] + { + new[] + {A, B, C, D, A, D, C, B, + B, C, D, A, B, A, D, C, + C, D, A, B, C, B, A, D, + D, C, B, A, D, A, B, C}, // SP1 (U) + new[] + {A, C, B, D, A, D, B, C, + B, D, A, C, B, C, A, D, + C, A, D, B, C, B, D, A, + D, B, C, A, D, A, C, B}, // SP2 (4) + new[] + {A, B, D, C, A, C, D, B, + B, A, C, D, B, D, C, A, + C, D, B, A, C, A, B, D, + D, C, A, B, D, B, A, C}, // SP3 (Z) + }; /// /// Create a square-planar configuration around a provided focus atom. The @@ -95,19 +96,17 @@ public sealed class SquarePlanar : AbstractStereo /// the carriers /// the configuration order, 1-3 public SquarePlanar(IAtom focus, IAtom[] carriers, int order) - : base(focus, carriers, new StereoElement(StereoElement.Classes.SquarePlanar, order)) + : base(focus, carriers, new StereoElement(StereoClass.SquarePlanar, order)) { if (Configure.Order() < 0 || Configure.Order() > 3) - throw new ArgumentOutOfRangeException("Invalid configuration order," - + "should be between 1-3"); + throw new ArgumentException("Invalid configuration order, should be between 1-3"); } public SquarePlanar(IAtom focus, IAtom[] carriers, StereoElement stereo) - : this(focus, carriers, stereo.Configure.Order()) + : this(focus, carriers, stereo.Configuration.Order()) { } - /// /// Normalize the configuration to the lowest configuration order (1) - /// U-shaped. @@ -118,15 +117,12 @@ public SquarePlanar Normalize() int cfg = Configure.Order(); if (cfg == 1) return this; - IAtom[] carriers = InvApply(Carriers.ToArray(), - PERMUTATIONS[cfg - 1]); - return new SquarePlanar(Focus, - carriers, - StereoElement.SquarePlanarU); + IAtom[] carriers = InvApply(Carriers, PERMUTATIONS[cfg - 1]); + return new SquarePlanar(Focus, carriers, StereoElement.SquarePlanarU); } /// - protected override IStereoElement Create(IAtom focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IAtom focus, IReadOnlyList carriers, StereoElement stereo) { return new SquarePlanar(focus, carriers.ToArray(), stereo); } diff --git a/NCDK/Stereo/StereoElementFactory.cs b/NCDK/Stereo/StereoElementFactory.cs index 671ca361..c0f80221 100644 --- a/NCDK/Stereo/StereoElementFactory.cs +++ b/NCDK/Stereo/StereoElementFactory.cs @@ -21,11 +21,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ + using NCDK.Graphs; +using NCDK.Numerics; using System; using System.Collections.Generic; -using NCDK.Numerics; -using static NCDK.Graphs.GraphUtil; namespace NCDK.Stereo { @@ -50,15 +50,15 @@ namespace NCDK.Stereo public abstract class StereoElementFactory { /// Native CDK structure representation. - protected readonly IAtomContainer container; + private readonly IAtomContainer container; /// Adjacency list graph representation. - protected readonly int[][] graph; + private readonly int[][] graph; /// A bond map for fast access to bond labels between two atom indices. - protected readonly EdgeToBondMap bondMap; + private readonly EdgeToBondMap bondMap; - protected readonly List projections = new List(); + private readonly List projections = new List(); /// /// Verify if created stereochemistry are actually stereo-centres. @@ -71,7 +71,7 @@ public abstract class StereoElementFactory /// an atom container /// adjacency list representation /// lookup bonds by atom index - protected StereoElementFactory(IAtomContainer container, int[][] graph, EdgeToBondMap bondMap) + internal StereoElementFactory(IAtomContainer container, int[][] graph, EdgeToBondMap bondMap) { this.container = container; this.graph = graph; @@ -101,16 +101,12 @@ private bool IsInSmallRing(IBond bond) { if (!bond.IsInRing) return false; - IAtom beg = bond.Begin; - IAtom end = bond.End; - bool[] mark = new bool[container.Atoms.Count]; - int bidx = container.Atoms.IndexOf(beg); - int eidx = container.Atoms.IndexOf(end); - return VisitSmallRing(mark, - bidx, - eidx, - bidx, - 1); + var beg = bond.Begin; + var end = bond.End; + var mark = new bool[container.Atoms.Count]; + var bidx = container.Atoms.IndexOf(beg); + var eidx = container.Atoms.IndexOf(end); + return VisitSmallRing(mark, bidx, eidx, bidx, 1); } /// @@ -119,69 +115,70 @@ private bool IsInSmallRing(IBond bond) /// Currently only and /// elements are created.. /// - /// a list of stereo elements - public IList> CreateAll() + /// stereo elements + public IEnumerable> CreateAll() { Cycles.MarkRingAtomsAndBonds(container); - Stereocenters centers = new Stereocenters(container, graph, bondMap); + var centers = new Stereocenters(container, graph, bondMap); if (check) - { centers.CheckSymmetry(); - } - - var elements = new List>(); // projection recognition (note no action in constructors) - FischerRecognition fischerRecon = new FischerRecognition(container, graph, bondMap, centers); - CyclicCarbohydrateRecognition cycleRecon = new CyclicCarbohydrateRecognition(container, graph, bondMap, centers); + var fischerRecon = new FischerRecognition(container, graph, bondMap, centers); + var cycleRecon = new CyclicCarbohydrateRecognition(container, graph, bondMap, centers); - elements.AddRange(fischerRecon.Recognise(projections)); - elements.AddRange(cycleRecon.Recognise(projections)); + foreach (var stereo in fischerRecon.Recognise(projections)) + yield return stereo; + foreach (var stereo in cycleRecon.Recognise(projections)) + yield return stereo; for (int v = 0; v < graph.Length; v++) { switch (centers.ElementType(v)) { // elongated tetrahedrals - case Stereocenters.CoordinateType.Bicoordinate: - int t0 = graph[v][0]; - int t1 = graph[v][1]; - if (centers.ElementType(t0) == Stereocenters.CoordinateType.Tricoordinate - && centers.ElementType(t1) == Stereocenters.CoordinateType.Tricoordinate) + case CoordinateType.Bicoordinate: + var t0 = graph[v][0]; + var t1 = graph[v][1]; + if (centers.ElementType(t0) == CoordinateType.Tricoordinate + && centers.ElementType(t1) == CoordinateType.Tricoordinate) { if (check && centers.IsStereocenter(t0) && centers.IsStereocenter(t1)) { var element = CreateExtendedTetrahedral(v, centers); - if (element != null) elements.Add(element); + if (element != null) + yield return element; } else { - var element_ = CreateExtendedTetrahedral(v, centers); - if (element_ != null) elements.Add(element_); + var element = CreateExtendedTetrahedral(v, centers); + if (element != null) + yield return element; } } break; // tetrahedrals - case Stereocenters.CoordinateType.Tetracoordinate: + case CoordinateType.Tetracoordinate: { var element = CreateTetrahedral(v, centers); - if (element != null) elements.Add(element); + if (element != null) + yield return element; } break; // aryl-aryl atropisomers - case Stereocenters.CoordinateType.Tricoordinate: + case CoordinateType.Tricoordinate: foreach (int w in graph[v]) { - IBond bond = bondMap[v, w]; + var bond = bondMap[v, w]; if (w > v && - centers.ElementType(w) == Stereocenters.CoordinateType.Tricoordinate && + centers.ElementType(w) == CoordinateType.Tricoordinate && bond.Order == BondOrder.Single && !bond.IsInRing && bond.Begin.IsInRing && bond.End.IsInRing) { var element = CreateAtropisomer(v, w, centers); if (element != null) - elements.Add(element); + yield return element; break; } } @@ -195,20 +192,22 @@ public IList> CreateAll() { switch (centers.ElementType(v)) { - // Cis/Trans double bonds - case Stereocenters.CoordinateType.Tricoordinate: + // cis/trans double bonds + case CoordinateType.Tricoordinate: if (!centers.IsStereocenter(v)) continue; foreach (int w in graph[v]) { - IBond bond = bondMap[v, w]; + var bond = bondMap[v, w]; if (w > v && bond.Order == BondOrder.Double) { - if (centers.ElementType(w) == Stereocenters.CoordinateType.Tricoordinate - && centers.IsStereocenter(w) && !IsInSmallRing(bond)) + if (centers.ElementType(w) == CoordinateType.Tricoordinate + && centers.IsStereocenter(w) + && !IsInSmallRing(bond)) { var element = CreateGeometric(v, w, centers); - if (element != null) elements.Add(element); + if (element != null) + yield return element; } break; } @@ -217,7 +216,7 @@ public IList> CreateAll() } } - return elements; + yield break; } /// @@ -242,7 +241,7 @@ public IList> CreateAll() /// other atom of single bond /// stereo centres /// new stereo element - public abstract IReadOnlyStereoElement CreateAtropisomer(int v, int w, Stereocenters stereocenters); + public abstract IStereoElement CreateAtropisomer(int v, int w, Stereocenters stereocenters); /// /// Create a tetrahedral element for the atom. If a tetrahedral element could @@ -334,8 +333,8 @@ public StereoElementFactory CheckSymmetry(bool check) /// the factory instance public static StereoElementFactory Using2DCoordinates(IAtomContainer container) { - EdgeToBondMap bondMap = EdgeToBondMap.WithSpaceFor(container); - int[][] graph = GraphUtil.ToAdjList(container, bondMap); + var bondMap = EdgeToBondMap.WithSpaceFor(container); + var graph = GraphUtil.ToAdjList(container, bondMap); return new StereoElementFactory2D(container, graph, bondMap); } @@ -347,8 +346,8 @@ public static StereoElementFactory Using2DCoordinates(IAtomContainer container) /// the factory instance public static StereoElementFactory Using3DCoordinates(IAtomContainer container) { - EdgeToBondMap bondMap = EdgeToBondMap.WithSpaceFor(container); - int[][] graph = GraphUtil.ToAdjList(container, bondMap); + var bondMap = EdgeToBondMap.WithSpaceFor(container); + var graph = GraphUtil.ToAdjList(container, bondMap); return new StereoElementFactory3D(container, graph, bondMap).CheckSymmetry(true); } @@ -392,12 +391,13 @@ public override IDoubleBondStereochemistry CreateGeometric(IBond bond, Stereocen /// public override ITetrahedralChirality CreateTetrahedral(int v, Stereocenters stereocenters) { - IAtom focus = container.Atoms[v]; + var focus = container.Atoms[v]; - if (HasUnspecifiedParity(focus)) return null; + if (HasUnspecifiedParity(focus)) + return null; - IAtom[] neighbors = new IAtom[4]; - int[] elevation = new int[4]; + var neighbors = new IAtom[4]; + var elevation = new int[4]; neighbors[3] = focus; @@ -406,21 +406,24 @@ public override ITetrahedralChirality CreateTetrahedral(int v, Stereocenters ste foreach (var w in graph[v]) { - IBond bond = bondMap[v, w]; + var bond = bondMap[v, w]; // wavy bond - if (IsUnspecified(bond)) return null; + if (IsUnspecified(bond)) + return null; neighbors[n] = container.Atoms[w]; elevation[n] = ElevationOf(focus, bond); - if (elevation[n] != 0) nonplanar = true; + if (elevation[n] != 0) + nonplanar = true; n++; } // too few/many neighbors - if (n < 3 || n > 4) return null; + if (n < 3 || n > 4) + return null; // TODO: verify valid wedge/hatch configurations using similar procedure // to NonPlanarBonds in the cdk-sdg package. @@ -428,11 +431,11 @@ public override ITetrahedralChirality CreateTetrahedral(int v, Stereocenters ste // no up/down bonds present - check for inverted down/hatch if (!nonplanar) { - int[] ws = graph[v]; + var ws = graph[v]; for (int i = 0; i < ws.Length; i++) { - int w = ws[i]; - IBond bond = bondMap[v, w]; + var w = ws[i]; + var bond = bondMap[v, w]; // we have already previously checked whether 'v' is at the // 'point' and so these must be inverse (fat-end @ @@ -442,7 +445,8 @@ public override ITetrahedralChirality CreateTetrahedral(int v, Stereocenters ste // we stick to the 'point' end convention but can // interpret if the bond isn't connected to another // stereocenter - otherwise it's ambiguous! - if (stereocenters.IsStereocenter(w)) continue; + if (stereocenters.IsStereocenter(w)) + continue; elevation[i] = -1; nonplanar = true; @@ -453,11 +457,12 @@ public override ITetrahedralChirality CreateTetrahedral(int v, Stereocenters ste if (!nonplanar) return null; } - int parity = Parity(focus, neighbors, elevation); + var parity = Parity(focus, neighbors, elevation); - if (parity == 0) return null; + if (parity == 0) + return null; - TetrahedralStereo winding = parity > 0 ? TetrahedralStereo.AntiClockwise : TetrahedralStereo.Clockwise; + var winding = parity > 0 ? TetrahedralStereo.AntiClockwise : TetrahedralStereo.Clockwise; return new TetrahedralChirality(focus, neighbors, winding); } @@ -476,7 +481,7 @@ private static bool IsWedged(IBond bond) } } - public override IReadOnlyStereoElement CreateAtropisomer(int u, int v, Stereocenters stereocenters) + public override IStereoElement CreateAtropisomer(int u, int v, Stereocenters stereocenters) { IAtom end1 = container.Atoms[u]; IAtom end2 = container.Atoms[v]; @@ -506,8 +511,8 @@ public override IReadOnlyStereoElement CreateAtropisom if (sum1 + sum2 < 17) return null; - IAtom[] carriers = new IAtom[4]; - int[] elevation = new int[4]; + var carriers = new IAtom[4]; + var elevation = new int[4]; int n = 0; foreach (int w in graph[u]) @@ -581,7 +586,7 @@ public override IReadOnlyStereoElement CreateAtropisom tmp.Point2D = new Vector2((end1.Point2D.Value.X + end2.Point2D.Value.X) / 2, (end2.Point2D.Value.Y + end2.Point2D.Value.Y) / 2); int parity = Parity(tmp, carriers, elevation); - var cfg = parity > 0 ? StereoElement.Configuration.Left : StereoElement.Configuration.Right; + var cfg = parity > 0 ? StereoConfigurations.Left : StereoConfigurations.Right; return new Atropisomeric(container.GetBond(end1, end2), carriers, cfg); } @@ -694,7 +699,7 @@ public override ExtendedTetrahedral CreateExtendedTetrahedral(int v, Stereocente /// /// a bond /// the bond has unspecified stereochemistry - private bool IsUnspecified(IBond bond) + private static bool IsUnspecified(IBond bond) { switch (bond.Stereo) { @@ -713,7 +718,7 @@ private bool IsUnspecified(IBond bond) /// atoms around the double bonded atom, 0: substituent, 1: /// other substituent (or focus), 2: double bonded atom /// the parity of the atoms - private int Parity(IAtom[] atoms) + private static int Parity(IAtom[] atoms) { if (atoms.Length != 3) throw new ArgumentException("incorrect number of atoms"); @@ -737,7 +742,7 @@ private int Parity(IAtom[] atoms) /// the atoms surrounding the central focus atom /// the elevations of each atom /// the parity (winding) - private int Parity(IAtom focus, IAtom[] atoms, int[] elevations) + private static int Parity(IAtom focus, IAtom[] atoms, int[] elevations) { if (atoms.Length != 4) throw new ArgumentException("incorrect number of atoms"); @@ -760,7 +765,7 @@ private int Parity(IAtom focus, IAtom[] atoms, int[] elevations) /// the base of the vector /// the point of the vector /// the unit vector - private Vector2 ToUnitVector(Vector2 from, Vector2 to) + private static Vector2 ToUnitVector(Vector2 from, Vector2 to) { if (from == to) return Vector2.Zero; @@ -775,7 +780,7 @@ private Vector2 ToUnitVector(Vector2 from, Vector2 to) /// locations in the plane /// elevations above/below the plane /// the determinant (signed volume of tetrahedron) - private double Parity(Vector2[] coordinates, int[] elevations) + private static double Parity(Vector2[] coordinates, int[] elevations) { double x1 = coordinates[0].X; double x2 = coordinates[1].X; @@ -823,7 +828,7 @@ private static void MoveToBack(int[] vs, int v) /// a focus of stereochemistry /// a bond connecting the focus to a substituent /// the elevation of the connected atom, +1 above, -1 below, 0 planar - private int ElevationOf(IAtom focus, IBond bond) + private static int ElevationOf(IAtom focus, IBond bond) { switch (bond.Stereo) { @@ -898,7 +903,7 @@ public override ITetrahedralChirality CreateTetrahedral(int v, Stereocenters ste return new TetrahedralChirality(focus, neighbors, winding); } - public override IReadOnlyStereoElement CreateAtropisomer(int u, int v, Stereocenters stereocenters) + public override IStereoElement CreateAtropisomer(int u, int v, Stereocenters stereocenters) { IAtom end1 = container.Atoms[u]; IAtom end2 = container.Atoms[v]; @@ -975,7 +980,7 @@ public override IReadOnlyStereoElement CreateAtropisom return null; int parity = Parity(carriers); - var cfg = parity > 0 ? StereoElement.Configuration.Left : StereoElement.Configuration.Right; + var cfg = parity > 0 ? StereoConfigurations.Left : StereoConfigurations.Right; return new Atropisomeric(container.GetBond(end1, end2), carriers, cfg); } @@ -1054,7 +1059,7 @@ public override ExtendedTetrahedral CreateExtendedTetrahedral(int v, Stereocente return new ExtendedTetrahedral(focus, neighbors, winding); } - private bool IsColinear(IAtom focus, IAtom[] terminals) + private static bool IsColinear(IAtom focus, IAtom[] terminals) { var vec0 = new Vector3(terminals[0].Point3D.Value.X - focus.Point3D.Value.X, terminals[0].Point3D.Value.Y - focus.Point3D.Value.Y, @@ -1083,7 +1088,7 @@ private static double Det(double xa, double ya, double xb, double yb, double xc, /// an atom sigma bonded to u /// an atom sigma bonded to v /// the parity of the atoms - private int Parity(Vector3 u, Vector3 v, Vector3 x, Vector3 w) + private static int Parity(Vector3 u, Vector3 v, Vector3 x, Vector3 w) { // create three vectors, v->u, v->w and u->x double[] vu = ToVector(v, u); @@ -1112,7 +1117,7 @@ private int Parity(Vector3 u, Vector3 v, Vector3 x, Vector3 w) /// /// the atoms surrounding the central focus atom /// the parity (winding) - private int Parity(IAtom[] atoms) + private static int Parity(IAtom[] atoms) { if (atoms.Length != 4) throw new ArgumentException("incorrect number of atoms"); diff --git a/NCDK/Stereo/StereoTool.cs b/NCDK/Stereo/StereoTool.cs index 43424af9..8cf50208 100644 --- a/NCDK/Stereo/StereoTool.cs +++ b/NCDK/Stereo/StereoTool.cs @@ -21,7 +21,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Common.Mathematics; + using NCDK.Numerics; namespace NCDK.Stereo @@ -35,17 +35,8 @@ namespace NCDK.Stereo // @author maclean // @cdk.module standard // @cdk.githash - public class StereoTool + public static class StereoTool { - /// - /// Currently unused, but intended for the StereoTool to indicate what it - /// 'means' by an assignment of some atoms to a class. - /// - public enum StereoClass - { - Tetrahedral, SquarePlanar, TrigonalBipyramidal, Octahedral - } - /// /// The handedness of a tetrahedron, in terms of the point-plane distance /// of three of the corners, compared to the fourth. diff --git a/NCDK/Stereo/Stereocenters.cs b/NCDK/Stereo/Stereocenters.cs index 10608de3..4ba05405 100644 --- a/NCDK/Stereo/Stereocenters.cs +++ b/NCDK/Stereo/Stereocenters.cs @@ -29,7 +29,6 @@ using System; using System.Collections; using System.Collections.Generic; -using static NCDK.Graphs.GraphUtil; namespace NCDK.Stereo { @@ -122,10 +121,10 @@ public sealed class Stereocenters private readonly EdgeToBondMap bondMap; /// the type of stereo center - indexed by atom. - private CenterType[] stereocenters; + private readonly CenterType[] stereocenters; /// the stereo elements - indexed by atom. - private StereoElement[] elements; + private readonly StereoElement[] elements; /// basic cycle information (i.e. is atom/bond cyclic) and cycle systems. private readonly RingSearch ringSearch; @@ -144,9 +143,9 @@ public sealed class Stereocenters /// the stereocenters public static Stereocenters Of(IAtomContainer container) { - EdgeToBondMap bondMap = EdgeToBondMap.WithSpaceFor(container); - int[][] g = GraphUtil.ToAdjList(container, bondMap); - Stereocenters stereocenters = new Stereocenters(container, g, bondMap); + var bondMap = EdgeToBondMap.WithSpaceFor(container); + var g = GraphUtil.ToAdjList(container, bondMap); + var stereocenters = new Stereocenters(container, g, bondMap); stereocenters.CheckSymmetry(); return stereocenters; } @@ -158,7 +157,7 @@ public static Stereocenters Of(IAtomContainer container) /// native CDK structure representation /// graph representation (adjacency list) /// fast lookup bonds by atom index - public Stereocenters(IAtomContainer container, int[][] graph, EdgeToBondMap bondMap) + internal Stereocenters(IAtomContainer container, int[][] graph, EdgeToBondMap bondMap) { this.container = container; this.bondMap = bondMap; @@ -368,7 +367,7 @@ private void LabelTrueCenters(int[] symmetry) { if (stereocenters[v] == CenterType.Potential) { - int[] ws = elements[v].neighbors; + var ws = elements[v].neighbors; int nUnique = 0; bool terminal = true; @@ -410,14 +409,13 @@ private void LabelTrueCenters(int[] symmetry) private void LabelIsolatedPara(int[] symmetry) { // auxiliary array, has the symmetry class already been 'visited' - bool[] visited = new bool[symmetry.Length + 1]; + var visited = new bool[symmetry.Length + 1]; foreach (var isolated in ringSearch.Isolated()) { - - List potential = new List(); - List trueCentres = new List(); - BitArray cyclic = new BitArray(1000); + var potential = new List(); + var trueCentres = new List(); + var cyclic = new BitArray(1000); foreach (var v in isolated) { @@ -439,44 +437,48 @@ private void LabelIsolatedPara(int[] symmetry) List paraElements = new List(); foreach (var element in potential) { - if (element.type == CoordinateType.Tetracoordinate) + switch (element.type) { - - int[] ws = element.neighbors; - int nUnique = 0; - bool terminal = true; - - foreach (var w in ws) - { - if (!cyclic[w]) + case CoordinateType.Tetracoordinate: { - if (!visited[symmetry[w]]) - { - visited[symmetry[w]] = true; - nUnique++; - } - else + int[] ws = element.neighbors; + int nUnique = 0; + bool terminal = true; + + foreach (var w in ws) { - if (g[w].Length > 1) terminal = false; + if (!cyclic[w]) + { + if (!visited[symmetry[w]]) + { + visited[symmetry[w]] = true; + nUnique++; + } + else + { + if (g[w].Length > 1) terminal = false; + } + } } - } - } - // reset for next element - foreach (var w in ws) - visited[symmetry[w]] = false; + // reset for next element + foreach (var w in ws) + visited[symmetry[w]] = false; - int deg = g[element.focus].Length; + int deg = g[element.focus].Length; - if (deg == 3 || (deg == 4 && nUnique == 2)) paraElements.Add(element); + if (deg == 3 || (deg == 4 && nUnique == 2)) paraElements.Add(element); - // remove those we know cannot possibly be stereocenters - if (deg == 4 && nUnique == 1 && terminal) stereocenters[element.focus] = CenterType.None; - } - else if (element.type == CoordinateType.Tricoordinate) - { - Tricoordinate either = (Tricoordinate)element; - if (stereocenters[either.other] == CenterType.True) paraElements.Add(element); + // remove those we know cannot possibly be stereocenters + if (deg == 4 && nUnique == 1 && terminal) stereocenters[element.focus] = CenterType.None; + } + break; + case CoordinateType.Tricoordinate: + { + Tricoordinate either = (Tricoordinate)element; + if (stereocenters[either.other] == CenterType.True) paraElements.Add(element); + } + break; } } @@ -514,7 +516,7 @@ private CoordinateType SupportedType(int i, int v, int d, int h, int x) // x: connected atoms // q: formal charge - int q = Charge(atom); + var q = Charge(atom); // more than one hydrogen if (checkSymmetry && h > 1) @@ -601,8 +603,8 @@ private bool VerifyTerminalHCount(int v) if (!checkSymmetry) return true; - int[] counts = new int[6]; - int[][] atoms = Arrays.CreateJagged(6, g[v].Length); + var counts = new int[6]; + var atoms = Arrays.CreateJagged(6, g[v].Length); bool found = false; @@ -613,11 +615,13 @@ private bool VerifyTerminalHCount(int v) found = found || (idx > 0 && counts[idx] > 1); } - if (!found) return true; + if (!found) + return true; for (int i = 1; i < counts.Length; i++) { - if (counts[i] < 2) continue; + if (counts[i] < 2) + continue; int terminalCount = 0; int terminalHCount = 0; @@ -625,7 +629,7 @@ private bool VerifyTerminalHCount(int v) for (int j = 0; j < counts[i]; j++) { int hCount = 0; - int[] ws = g[atoms[i][j]]; + var ws = g[atoms[i][j]]; foreach (var w in g[atoms[i][j]]) { IAtom atom = container.Atoms[w]; @@ -643,7 +647,8 @@ private bool VerifyTerminalHCount(int v) } } - if (terminalCount > 1 && terminalHCount > 0) return false; + if (terminalCount > 1 && terminalHCount > 0) + return false; } return true; @@ -684,7 +689,7 @@ private static int IndexNeighbor(IAtom atom) /// the atom is a member of a 3 member ring private bool InThreeMemberRing(int v) { - BitArray adj = new BitArray(0); + var adj = new BitArray(0); foreach (var w in g[v]) BitArrays.SetValue(adj, w, true); // is a neighbors neighbor adjacent? @@ -712,9 +717,11 @@ private bool IsBridgeHeadNitrogen(int v) /// the atomic number of the atom private static int GetAtomicNumber(IAtom a) { - int? elem = a.AtomicNumber; - if (elem != null) return elem.Value; - if (a is IPseudoAtom) return 0; + var elem = a.AtomicNumber; + if (elem != null) + return elem.Value; + if (a is IPseudoAtom) + return 0; throw new ArgumentException("an atom had an undefieind atomic number"); } @@ -738,49 +745,12 @@ private static int Charge(IAtom a) /// the array cast to int values private static int[] ToIntArray(long[] org) { - int[] cpy = new int[org.Length]; + var cpy = new int[org.Length]; for (int i = 0; i < cpy.Length; i++) cpy[i] = (int)org[i]; return cpy; } - /// Defines the type of a stereocenter. - public enum CenterType - { - /// Atom is a true stereo-centre. - True, - - /// Atom resembles a stereo-centre (para). - Para, - - /// Atom is a potential stereo-centre - Potential, - - /// Non stereo-centre. - None, - } - - public enum CoordinateType - { - /// An atom within a cumulated system. (not yet supported) - Bicoordinate, - - /// - /// A potentially stereogenic atom with 3 neighbors - one atom in a - /// geometric centres or cumulated system (allene, cumulene). - /// - Tricoordinate, - - /// - /// A potentially stereogenic atom with 4 neighbors - tetrahedral - /// centres. - /// - Tetracoordinate, - - /// A non-stereogenic atom. - None - } - /// /// Internal stereo element representation. We need to define the sides of a /// double bond separately and want to avoid reflection (is) by using @@ -848,5 +818,41 @@ public Tricoordinate(int v, int w, int[] neighbors) } } } -} + public enum CoordinateType + { + /// A non-stereogenic atom. + None = 0, + + /// An atom within a cumulated system. (not yet supported) + Bicoordinate, + + /// + /// A potentially stereogenic atom with 3 neighbors - one atom in a + /// geometric centres or cumulated system (allene, cumulene). + /// + Tricoordinate, + + /// + /// A potentially stereogenic atom with 4 neighbors - tetrahedral + /// centres. + /// + Tetracoordinate, + } + + /// Defines the type of a stereocenter. + public enum CenterType + { + /// Non stereo-centre. + None = 0, + + /// Atom is a true stereo-centre. + True, + + /// Atom resembles a stereo-centre (para). + Para, + + /// Atom is a potential stereo-centre + Potential, + } +} diff --git a/NCDK/Stereo/TetrahedralChirality.cs b/NCDK/Stereo/TetrahedralChirality.cs index 115d8ede..7f6f88c0 100644 --- a/NCDK/Stereo/TetrahedralChirality.cs +++ b/NCDK/Stereo/TetrahedralChirality.cs @@ -37,25 +37,29 @@ namespace NCDK.Stereo public class TetrahedralChirality : AbstractStereo, ITetrahedralChirality { - public TetrahedralChirality(IAtom chiralAtom, IEnumerable ligands, TetrahedralStereo stereo) + public TetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligands, TetrahedralStereo stereo) : this(chiralAtom, ligands, stereo.ToConfiguration()) { } - public TetrahedralChirality(IAtom chiralAtom, IEnumerable ligands, StereoElement.Configuration configure) - : base(chiralAtom, ligands.ToList(), new StereoElement(StereoElement.Classes.Tetrahedral, configure)) + public TetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligands, StereoConfigurations configure) + : base(chiralAtom, ligands.ToList(), new StereoElement(StereoClass.Tetrahedral, configure)) { } - public TetrahedralChirality(IAtom chiralAtom, IEnumerable ligands, StereoElement stereo) - : this(chiralAtom, ligands, stereo.Configure) + public TetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligands, StereoElement stereo) + : this(chiralAtom, ligands, stereo.Configuration) { } /// /// An array of ligand atoms around the chiral atom. /// - public virtual IList Ligands => Carriers; + public virtual IReadOnlyList Ligands + { + get => Carriers; + set => Carriers = value; + } /// /// Atom that is the chirality center. @@ -71,7 +75,7 @@ public virtual TetrahedralStereo Stereo set { Configure = value.ToConfiguration(); } } - protected override IStereoElement Create(IAtom focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IAtom focus, IReadOnlyList carriers, StereoElement stereo) { return new TetrahedralChirality(focus, carriers, stereo); } diff --git a/NCDK/Stereo/TrigonalBipyramidal.cs b/NCDK/Stereo/TrigonalBipyramidal.cs index e2429367..b08f75e7 100644 --- a/NCDK/Stereo/TrigonalBipyramidal.cs +++ b/NCDK/Stereo/TrigonalBipyramidal.cs @@ -52,67 +52,67 @@ namespace NCDK.Stereo public sealed class TrigonalBipyramidal : AbstractStereo { private static readonly int[][] PERMUTATIONS = new int[][]{ - new[] - {A, B, C, D, E, A, C, D, B, E, A, D, B, C, E, - E, D, C, B, A, E, B, D, C, A, E, C, B, D, A }, // TB1 a -> e @ - new[] - {A, D, C, B, E, A, C, B, D, E, A, B, D, C, E, - E, B, C, D, A, E, D, B, C, A, E, C, D, B, A }, // TB2 a -> e @@ - new[] - {A, B, C, E, D, A, C, E, B, D, A, E, B, C, D, - D, E, C, B, A, D, B, E, C, A, D, C, B, E, A }, // TB3 a -> d @ - new[] - {A, E, C, B, D, A, C, B, E, D, A, B, E, C, D, - D, B, C, E, A, D, E, B, C, A, D, C, E, B, A }, // TB4 a -> d @@ - new[] - {A, B, D, E, C, A, D, E, B, C, A, E, B, D, C, - C, E, D, B, A, C, B, E, D, A, C, D, B, E, A }, // TB5 a -> c @ - new[] - {A, E, D, B, C, A, D, B, E, C, A, B, E, D, C, - C, B, D, E, A, C, E, B, D, A, C, D, E, B, A }, // TB6 a -> c @@ - new[] - {A, C, D, E, B, A, D, E, C, B, A, E, C, D, B, - B, E, D, C, A, B, C, E, D, A, B, D, C, E, A }, // TB7 a -> b @ - new[] - {A, E, D, C, B, A, D, C, E, B, A, C, E, D, B, - B, C, D, E, A, B, E, C, D, A, B, D, E, C, A }, // TB8 a -> b @@ - new[] - {B, A, C, D, E, B, C, D, A, E, B, D, A, C, E, - E, D, C, A, B, E, A, D, C, B, E, C, A, D, B }, // TB9 b -> e @ - new[] - {B, A, C, E, D, B, C, E, A, D, B, E, A, C, D, - D, E, C, A, B, D, A, E, C, B, D, C, A, E, B }, // TB10 b -> d @ - new[] - {B, D, C, A, E, B, C, A, D, E, B, A, D, C, E, - E, A, C, D, B, E, D, A, C, B, E, C, D, A, B }, // TB11 b -> e @@ - new[] - {B, E, C, A, D, B, C, A, E, D, B, A, E, C, D, - D, A, C, E, B, D, E, A, C, B, D, C, E, A, B }, // TB12 b -> d @@ - new[] - {B, A, D, E, C, B, D, E, A, C, B, E, A, D, C, - C, E, D, A, B, C, A, E, D, B, C, D, A, E, B }, // TB13 b -> c @ - new[] - {B, E, D, A, C, B, D, A, E, C, B, A, E, D, C, - C, A, D, E, B, C, E, A, D, B, C, D, E, A, B }, // TB14 b -> c @@ - new[] - {C, A, B, D, E, C, B, D, A, E, C, D, A, B, E, - E, D, B, A, C, E, A, D, B, C, E, B, A, D, C }, // TB15 c -> e @ - new[] - {C, A, B, E, D, C, B, E, A, D, C, E, A, B, D, - D, E, B, A, C, D, A, E, B, C, D, B, A, E, C }, // TB16 c -> d @ - new[] - {D, A, B, C, E, D, B, C, A, E, D, C, A, B, E, - E, C, B, A, D, E, A, C, B, D, E, B, A, C, D }, // TB17 d -> e @ - new[] - {D, C, B, A, E, D, B, A, C, E, D, A, C, B, E, - E, A, B, C, D, E, C, A, B, D, E, B, C, A, D }, // TB18 d -> e @@ - new[] - {C, E, B, A, D, C, B, A, E, D, C, A, E, B, D, - D, A, B, E, C, D, E, A, B, C, D, B, E, A, C }, // TB19 c -> d @@ - new[] - {C, D, B, A, E, C, B, A, D, E, C, A, D, B, E, - E, A, B, D, C, E, D, A, B, C, E, B, D, A, C }, // TB20 c -> e @@ - }; + new[] + {A, B, C, D, E, A, C, D, B, E, A, D, B, C, E, + E, D, C, B, A, E, B, D, C, A, E, C, B, D, A }, // TB1 a -> e @ + new[] + {A, D, C, B, E, A, C, B, D, E, A, B, D, C, E, + E, B, C, D, A, E, D, B, C, A, E, C, D, B, A }, // TB2 a -> e @@ + new[] + {A, B, C, E, D, A, C, E, B, D, A, E, B, C, D, + D, E, C, B, A, D, B, E, C, A, D, C, B, E, A }, // TB3 a -> d @ + new[] + {A, E, C, B, D, A, C, B, E, D, A, B, E, C, D, + D, B, C, E, A, D, E, B, C, A, D, C, E, B, A }, // TB4 a -> d @@ + new[] + {A, B, D, E, C, A, D, E, B, C, A, E, B, D, C, + C, E, D, B, A, C, B, E, D, A, C, D, B, E, A }, // TB5 a -> c @ + new[] + {A, E, D, B, C, A, D, B, E, C, A, B, E, D, C, + C, B, D, E, A, C, E, B, D, A, C, D, E, B, A }, // TB6 a -> c @@ + new[] + {A, C, D, E, B, A, D, E, C, B, A, E, C, D, B, + B, E, D, C, A, B, C, E, D, A, B, D, C, E, A }, // TB7 a -> b @ + new[] + {A, E, D, C, B, A, D, C, E, B, A, C, E, D, B, + B, C, D, E, A, B, E, C, D, A, B, D, E, C, A }, // TB8 a -> b @@ + new[] + {B, A, C, D, E, B, C, D, A, E, B, D, A, C, E, + E, D, C, A, B, E, A, D, C, B, E, C, A, D, B }, // TB9 b -> e @ + new[] + {B, A, C, E, D, B, C, E, A, D, B, E, A, C, D, + D, E, C, A, B, D, A, E, C, B, D, C, A, E, B }, // TB10 b -> d @ + new[] + {B, D, C, A, E, B, C, A, D, E, B, A, D, C, E, + E, A, C, D, B, E, D, A, C, B, E, C, D, A, B }, // TB11 b -> e @@ + new[] + {B, E, C, A, D, B, C, A, E, D, B, A, E, C, D, + D, A, C, E, B, D, E, A, C, B, D, C, E, A, B }, // TB12 b -> d @@ + new[] + {B, A, D, E, C, B, D, E, A, C, B, E, A, D, C, + C, E, D, A, B, C, A, E, D, B, C, D, A, E, B }, // TB13 b -> c @ + new[] + {B, E, D, A, C, B, D, A, E, C, B, A, E, D, C, + C, A, D, E, B, C, E, A, D, B, C, D, E, A, B }, // TB14 b -> c @@ + new[] + {C, A, B, D, E, C, B, D, A, E, C, D, A, B, E, + E, D, B, A, C, E, A, D, B, C, E, B, A, D, C }, // TB15 c -> e @ + new[] + {C, A, B, E, D, C, B, E, A, D, C, E, A, B, D, + D, E, B, A, C, D, A, E, B, C, D, B, A, E, C }, // TB16 c -> d @ + new[] + {D, A, B, C, E, D, B, C, A, E, D, C, A, B, E, + E, C, B, A, D, E, A, C, B, D, E, B, A, C, D }, // TB17 d -> e @ + new[] + {D, C, B, A, E, D, B, A, C, E, D, A, C, B, E, + E, A, B, C, D, E, C, A, B, D, E, B, C, A, D }, // TB18 d -> e @@ + new[] + {C, E, B, A, D, C, B, A, E, D, C, A, E, B, D, + D, A, B, E, C, D, E, A, B, C, D, B, E, A, C }, // TB19 c -> d @@ + new[] + {C, D, B, A, E, C, B, A, D, E, C, A, D, B, E, + E, A, B, D, C, E, D, A, B, C, E, B, D, A, C }, // TB20 c -> e @@ + }; /// /// Create a new trigonal bipyramidal configuration. @@ -120,17 +120,19 @@ public sealed class TrigonalBipyramidal : AbstractStereo /// the focus /// the carriers /// the order (1-20) - public TrigonalBipyramidal(IAtom focus, IAtom[] carriers, int order) - : base(focus, carriers, new StereoElement(StereoElement.Classes.TrigonalBipyramidal, order)) + public TrigonalBipyramidal(IAtom focus, IReadOnlyList carriers, int order) + : base(focus, carriers, new StereoElement(StereoClass.TrigonalBipyramidal, order)) { + if (order < 0 || order > 20) + throw new ArgumentOutOfRangeException(nameof(order)); if (Configure.Order() < 0 || Configure.Order() > 20) - throw new ArgumentOutOfRangeException("Invalid configuration order," - + "should be between 1-20"); + throw new InvalidOperationException("Invalid configuration order, should be between 1-20"); } - public TrigonalBipyramidal(IAtom focus, IAtom[] carriers, StereoElement stereo) - : this(focus, carriers, stereo.Configure.Order()) - { } + public TrigonalBipyramidal(IAtom focus, IReadOnlyList carriers, StereoElement stereo) + : this(focus, carriers, stereo.Configuration.Order()) + { + } /// /// Normalize the configuration to the lowest configuration order (1) - @@ -143,15 +145,12 @@ public TrigonalBipyramidal Normalize() int cfg = Configure.Order(); if (cfg == 1) return this; - IAtom[] carriers = InvApply(Carriers.ToArray(), - PERMUTATIONS[cfg - 1]); - return new TrigonalBipyramidal(Focus, - carriers, - 1); + var carriers = InvApply(Carriers, PERMUTATIONS[cfg - 1]); + return new TrigonalBipyramidal(Focus, carriers, 1); } /// - protected override IStereoElement Create(IAtom focus, IList carriers, StereoElement stereo) + protected override IStereoElement Create(IAtom focus, IReadOnlyList carriers, StereoElement stereo) { return new TrigonalBipyramidal(focus, carriers.ToArray(), stereo); } diff --git a/NCDK/StereoElement.cs b/NCDK/StereoElement.cs index 96f6dbc5..ff1d5205 100644 --- a/NCDK/StereoElement.cs +++ b/NCDK/StereoElement.cs @@ -18,128 +18,125 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Reflection; using static NCDK.StereoElement; namespace NCDK { - public struct StereoElement - { - /// - /// The configuration is stored as an integral value. Although the common - /// geometries like tetrahedral and cis/trans bonds only have 2 possible - /// configurations (e.g. left vs right) more complex geometries like square - /// planar and octahedral require more to describe. For convenience the - /// constants and are provided but are synonymous - /// with the values 1 (odd) and 2 (even). - /// - /// - /// Special values (e.g. 0) may be used to represent unknown/unspecified or - /// racemic in future but are currently undefined. - /// - [Obfuscation(ApplyToMembers = true, Exclude = true)] - public enum Configuration - : short - { - Unset = 0, - Left = 1, - Right = 2, - Opposite = Left, - Together = Right, - } + /// + /// There stereo class defines the type of stereochemistry/geometry that is + /// captured. The stereo class is also defined as a integral value. The + /// following classes are available with varied support through out the + /// toolkit. + /// + /// + [Obfuscation(ApplyToMembers = true, Exclude = true)] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028: Enum Storage should be Int32", Justification = "Ignored")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1717: Only FlagsAttribute enums should have plural names", Justification = "Ignored")] + public enum StereoClass : short + { + Unset = 0, - /// - /// There stereo class defines the type of stereochemistry/geometry that is - /// captured. The stereo class is also defined as a integral value. The - /// following classes are available with varied support through out the - /// toolkit. - /// - /// - [Obfuscation(ApplyToMembers = true, Exclude = true)] - public enum Classes - : short - { - Unset = 0, + /// Geometric CisTrans (e.g. but-2-ene) + CisTrans = 0x21, - /// Geometric CisTrans (e.g. but-2-ene) - CisTrans = 0x21, + /// Tetrahedral (T-4) (e.g. butan-2-ol) + Tetrahedral = 0x42, - /// Tetrahedral (T-4) (e.g. butan-2-ol) - Tetrahedral = 0x42, + /// ExtendedTetrahedral (e.g. 2,3-pentadiene) + Allenal = 0x43, - /// ExtendedTetrahedral (e.g. 2,3-pentadiene) - Allenal = 0x43, + /// Atropisomeric (e.g. BiNAP) + Atropisomeric = 0x44, - /// Atropisomeric (e.g. BiNAP) - Atropisomeric = 0x44, + /// Square Planar (SP-4) (e.g. cisplatin) + SquarePlanar = 0x45, - /// Square Planar (SP-4) (e.g. cisplatin) - SquarePlanar = 0x45, + /// Square Pyramidal (SPY-5) + SquarePyramidal = 0x51, - /// Square Pyramidal (SPY-5) - SquarePyramidal = 0x51, + /// Trigonal Bipyramidal (TBPY-5) + TrigonalBipyramidal = 0x52, - /// Trigonal Bipyramidal (TBPY-5) - TrigonalBipyramidal = 0x52, + /// Octahedral (OC-6) + Octahedral = 0x61, - /// Octahedral (OC-6) - Octahedral = 0x61, + /// Pentagonal Bipyramidal (PBPY-7) + PentagonalBipyramidal = 0x71, - /// Pentagonal Bipyramidal (PBPY-7) - PentagonalBipyramidal = 0x71, + /// Hexagonal Bipyramidal (HBPY-8) + HexagonalBipyramidal = 0x81, - /// Hexagonal Bipyramidal (HBPY-8) - HexagonalBipyramidal = 0x81, + /// Heptagonal Bipyramidal (HBPY-9) + HeptagonalBipyramidal = 0x91, + } - /// Heptagonal Bipyramidal (HBPY-9) - HeptagonalBipyramidal = 0x91, - } + /// + /// The configuration is stored as an integral value. Although the common + /// geometries like tetrahedral and cis/trans bonds only have 2 possible + /// configurations (e.g. left vs right) more complex geometries like square + /// planar and octahedral require more to describe. For convenience the + /// constants and are provided but are synonymous + /// with the values 1 (odd) and 2 (even). + /// + /// + /// Special values (e.g. 0) may be used to represent unknown/unspecified or + /// racemic in future but are currently undefined. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028: Enum Storage should be Int32", Justification = "Ignored")] + [Obfuscation(ApplyToMembers = true, Exclude = true)] + [Flags] + public enum StereoConfigurations : short + { + Unset = 0, + Left = 1, + Right = 2, - Classes cls; - Configuration configure; + Opposite = Left, + Together = Right, + } - public Classes Class => cls; + public struct StereoElement : IEquatable + { + public StereoClass Class { get; private set; } + public StereoConfigurations Configuration { get; set; } - public Configuration Configure + public StereoElement(StereoClass cls) { - get { return configure; } - set { configure = value; } + this.Class = cls; + this.Configuration = StereoConfigurations.Unset; } - public StereoElement(Classes cls) + public StereoElement(StereoConfigurations configure) { - this.cls = cls; - this.configure = Configuration.Unset; + this.Class = StereoClass.Unset; + this.Configuration = configure; } - public StereoElement(Configuration configure) + public StereoElement(StereoClass cls, StereoConfigurations configure) { - this.cls = Classes.Unset; - this.configure = configure; + this.Class = cls; + this.Configuration = configure; } - public StereoElement(Classes cls, Configuration configure) + public StereoElement(StereoClass cls, int configure) + : this(cls, (StereoConfigurations)configure) { - this.cls = cls; - this.configure = configure; } - public StereoElement(Classes cls, int configure) - : this(cls, (Configuration)configure) - { } - /* * Important! The forth nibble of the stereo-class defines the number of * carriers (or coordination number) the third nibble just increments when * there are two geometries with the same number of carriers. */ - public int CarrierLength => cls.GetLength(); + public int CarrierLength => Class.GetLength(); public static bool operator ==(StereoElement a, StereoElement b) { - return a.configure == b.configure && a.cls == b.cls; + return a.Configuration == b.Configuration && a.Class == b.Class; } public static bool operator !=(StereoElement a, StereoElement b) @@ -156,38 +153,43 @@ public override bool Equals(object obj) public override string ToString() { - return cls.ToString() + " " + configure.ToString(); + return Class.ToString() + " " + Configuration.ToString(); } public override int GetHashCode() { - return cls.GetHashCode() << 16 + configure.GetHashCode(); + return Class.GetHashCode() << 16 + Configuration.GetHashCode(); } /// Square Planar Configuration in U Shape - public static readonly StereoElement SquarePlanarU = new StereoElement(Classes.SquarePlanar, 1); + public static readonly StereoElement SquarePlanarU = new StereoElement(StereoClass.SquarePlanar, 1); /// Square Planar Configuration in 4 Shape - public static readonly StereoElement SquarePlanar4 = new StereoElement(Classes.SquarePlanar, 2); + public static readonly StereoElement SquarePlanar4 = new StereoElement(StereoClass.SquarePlanar, 2); /// Square Planar Configuration in Z Shape - public static readonly StereoElement SquarePlanarZ = new StereoElement(Classes.SquarePlanar, 3); + public static readonly StereoElement SquarePlanarZ = new StereoElement(StereoClass.SquarePlanar, 3); + + public bool Equals(StereoElement other) + { + return this == other; + } } public static class StereoElementTools { - public static int GetLength(this Classes value) + public static int GetLength(this StereoClass value) => (int)(((uint)value) >> 4); /// /// The configuration order of the stereochemistry. /// - public static short Order(this Configuration value) + public static short Order(this StereoConfigurations value) => (short)value; - public static Configuration Flip(this Configuration value) + public static StereoConfigurations Flip(this StereoConfigurations value) { - return (Configuration)((int)value ^ 0x3); + return (StereoConfigurations)((int)value ^ 0x3); } } } diff --git a/NCDK/StructGen/MathTools.cs b/NCDK/StructGen/MathTools.cs index 6eed7216..b4c60c93 100644 --- a/NCDK/StructGen/MathTools.cs +++ b/NCDK/StructGen/MathTools.cs @@ -35,7 +35,8 @@ internal static double Max(double[] values) { double max = values[0]; foreach (var value in values) - if (value > max) max = value; + if (value > max) + max = value; return max; } @@ -48,7 +49,8 @@ internal static double Min(double[] values) { double min = values[0]; foreach (var value in values) - if (value < min) min = value; + if (value < min) + min = value; return min; } diff --git a/NCDK/StructGen/RandomGenerator.cs b/NCDK/StructGen/RandomGenerator.cs index d10fb7de..b5f6a2c4 100644 --- a/NCDK/StructGen/RandomGenerator.cs +++ b/NCDK/StructGen/RandomGenerator.cs @@ -29,13 +29,13 @@ namespace NCDK.StructGen { /// - /// RandomGenerator is a generator of constitutional isomers. It needs to be + /// is a generator of constitutional isomers. It needs to be /// provided with a starting constitution and it makes random moves in /// constitutional space from there. /// This generator was first suggested by J.-L. Faulon cdk-cite-FAU96. /// /// - /// Unlike the VicinitySampler, this methods does not sample + /// Unlike the , this methods does not sample /// the full Faulon vicinity. /// /// @@ -46,8 +46,8 @@ public class RandomGenerator { private static System.Random random = new System.Random(); - private IAtomContainer proposedStructure = null; private IAtomContainer molecule = null; + private IAtomContainer proposedStructure = null; private IAtomContainer trial = null; /// @@ -56,7 +56,7 @@ public class RandomGenerator /// The starting structure public RandomGenerator(IAtomContainer molecule) { - SetMolecule(molecule); + this.molecule = molecule; } /// @@ -70,7 +70,7 @@ public IAtomContainer ProposeStructure() Debug.WriteLine("RandomGenerator->ProposeStructure() Start"); do { - trial = (IAtomContainer)molecule.Clone(); + trial = (IAtomContainer)Molecule.Clone(); Mutate(trial); Debug.WriteLine("BondCounts: " + string.Join(" ", trial.Atoms.Select(n => trial.GetConnectedBonds(n).Count()))); Debug.WriteLine("BondOrderSums: " + string.Join(" ", trial.Atoms.Select(n => trial.GetBondOrderSum(n)))); @@ -96,7 +96,7 @@ public void AcceptStructure() /// pattern between them according to rules described /// in "Faulon, JCICS 1996, 36, 731". /// - public void Mutate(IAtomContainer ac) + public virtual void Mutate(IAtomContainer ac) { Debug.WriteLine("RandomGenerator->Mutate() Start"); int nrOfAtoms = ac.Atoms.Count; @@ -123,7 +123,7 @@ public void Mutate(IAtomContainer ac) x2 = (int)(random.NextDouble() * nrOfAtoms); y1 = (int)(random.NextDouble() * nrOfAtoms); y2 = (int)(random.NextDouble() * nrOfAtoms); - Debug.WriteLine("RandomGenerator->Mutate(): x1, x2, y1, y2: " + x1 + ", " + x2 + ", " + y1 + ", " + y2); + Debug.WriteLine($"RandomGenerator->Mutate(): x1, x2, y1, y2: {x1}, {x2}, {y1}, {y2}"); } while (!(x1 != x2 && x1 != y1 && x1 != y2 && x2 != y1 && x2 != y2 && y1 != y2)); ax1 = ac.Atoms[x1]; ay1 = ac.Atoms[y1]; @@ -174,8 +174,7 @@ public void Mutate(IAtomContainer ac) { a22 = 0; } - Debug.WriteLine("RandomGenerator->Mutate()->The old bond orders: a11, a12, a21, a22: " + +a11 + ", " + a12 - + ", " + a21 + ", " + a22); + Debug.WriteLine($"RandomGenerator->Mutate()->The old bond orders: a11, a12, a21, a22: {a11}, {a12}, {a21}, {a22}"); } while (nonZeroBondsCounter < 2); /* Compute the range for b11 (see Faulons formulae for details) */ @@ -185,9 +184,9 @@ public void Mutate(IAtomContainer ac) upperborder = MathTools.Min(cmin); /* Randomly choose b11 != a11 in the range max > r > min */ Debug.WriteLine("*** New Try ***"); - Debug.WriteLine("a11 = ", a11); - Debug.WriteLine("upperborder = ", upperborder); - Debug.WriteLine("lowerborder = ", lowerborder); + Debug.WriteLine($"a11 = {a11}"); + Debug.WriteLine($"upperborder = {upperborder}"); + Debug.WriteLine($"lowerborder = {lowerborder}"); choiceCounter = 0; for (double f = lowerborder; f <= upperborder; f++) { @@ -202,12 +201,12 @@ public void Mutate(IAtomContainer ac) b11 = choices[(int)(random.NextDouble() * choiceCounter)]; } - Debug.WriteLine("b11 = " + b11); + Debug.WriteLine($"b11 = {b11}"); } while (!(b11 != a11 && (b11 >= lowerborder && b11 <= upperborder))); - double b12 = a11 + a12 - b11; - double b21 = a11 + a21 - b11; - double b22 = a22 - a11 + b11; + var b12 = a11 + a12 - b11; + var b21 = a11 + a21 - b11; + var b22 = a22 - a11 + b11; if (b11 > 0) { @@ -277,24 +276,18 @@ public void Mutate(IAtomContainer ac) ac.Bonds.Remove(b4); } - Debug.WriteLine("a11 a12 a21 a22: " + a11 + " " + a12 + " " + a21 + " " + a22); - Debug.WriteLine("b11 b12 b21 b22: " + b11 + " " + b12 + " " + b21 + " " + b22); + Debug.WriteLine($"a11 a12 a21 a22: {a11} {a12} {a21} {a22}"); + Debug.WriteLine($"b11 b12 b21 b22: {b11} {b12} {b21} {b22}"); } /// - /// Assigns a starting structure to this generator. + /// The molecule which reflects the current state of this + /// stochastic structure generator. /// - /// a starting structure for this generator - public void SetMolecule(IAtomContainer molecule) + public IAtomContainer Molecule { - this.molecule = molecule; + get => molecule; + set => this.molecule = value; } - - /// - /// Returns the molecule which reflects the current state of this - /// stochastic structure generator. - /// - /// The molecule - public IAtomContainer Molecule => this.molecule; } } diff --git a/NCDK/StructGen/SingleStructureRandomGenerator.cs b/NCDK/StructGen/SingleStructureRandomGenerator.cs index 93b18d7e..6e8725d6 100644 --- a/NCDK/StructGen/SingleStructureRandomGenerator.cs +++ b/NCDK/StructGen/SingleStructureRandomGenerator.cs @@ -33,20 +33,22 @@ namespace NCDK.StructGen /// /// Randomly generates a single, connected, correctly bonded structure for /// a given molecular formula. + /// + /// + /// /// To see it working run the graphical - /// test org.openscience.cdk.test.SingleStructureRandomGeneratorTest + /// test SingleStructureRandomGeneratorTest /// and add more structures to the panel using the "More" button. - /// In order to use this class, use MFAnalyser to get an AtomContainer from + /// In order to use this class, use MFAnalyser to get an from /// a molecular formula string. - /// - /// + /// /// Assign hydrogen counts to each heavy atom. The hydrogens should not be /// in the atom pool but should be assigned implicitly to the heavy atoms in /// order to reduce computational cost. /// Assign this AtomContainer to the /// SingleStructureRandomGenerator and retrieve a randomly generated, but correctly bonded /// structure by using the Generate() method. You can then repeatedly call - /// the Generate() method in order to retrieve further structures. + /// the method in order to retrieve further structures. /// /// Agenda: /// @@ -74,59 +76,44 @@ public SingleStructureRandomGenerator(long seed) random = new Maths.Random(seed); } - /// - /// Constructor for the SingleStructureRandomGenerator object. - /// public SingleStructureRandomGenerator() : this((long)11000) - { } + { + } - /// - /// Sets the AtomContainer attribute of the SingleStructureRandomGenerator object. - /// - /// The new AtomContainer value - /// public void SetAtomContainer(IAtomContainer ac) { this.atomContainer = ac; } /// - /// Generates a random structure based on the atoms in the given IAtomContainer. + /// Generates a random structure based on the atoms in the given . /// public IAtomContainer Generate() { - bool structureFound = false; - bool bondFormed; - double order; - double max, cmax1, cmax2; int iteration = 0; - IAtom partner; - IAtom atom; + bool structureFound = false; do { iteration++; atomContainer.RemoveAllElectronContainers(); + bool bondFormed; do { bondFormed = false; - for (int f = 0; f < atomContainer.Atoms.Count; f++) + foreach (var atom in atomContainer.Atoms) { - atom = atomContainer.Atoms[f]; - if (!satCheck.IsSaturated(atom, atomContainer)) { - partner = GetAnotherUnsaturatedNode(atom); + var 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); - Debug.WriteLine("Forming bond of order ", order); - atomContainer.Bonds.Add(atomContainer.Builder.NewBond(atom, partner, - BondManipulator.CreateBondOrder(order))); + var cmax1 = satCheck.GetCurrentMaxBondOrder(atom, atomContainer); + var cmax2 = satCheck.GetCurrentMaxBondOrder(partner, atomContainer); + var max = Math.Min(cmax1, cmax2); + var order = Math.Min(Math.Max(1.0, random.NextInt((int)Math.Round(max))), 3.0); + Debug.WriteLine($"Forming bond of order {order}"); + atomContainer.Bonds.Add(atomContainer.Builder.NewBond(atom, partner, BondManipulator.CreateBondOrder(order))); bondFormed = true; } } @@ -137,33 +124,28 @@ public IAtomContainer Generate() structureFound = true; } } while (!structureFound && iteration < 20); - Debug.WriteLine("Structure found after #iterations: ", iteration); + Debug.WriteLine($"Structure found after #iterations: {iteration}"); return atomContainer.Builder.NewAtomContainer(atomContainer); } - /// - /// Gets the AnotherUnsaturatedNode attribute of the SingleStructureRandomGenerator object. - /// - /// The AnotherUnsaturatedNode value private IAtom GetAnotherUnsaturatedNode(IAtom exclusionAtom) { - IAtom atom; - int next = random.NextInt(atomContainer.Atoms.Count); + var next = random.NextInt(atomContainer.Atoms.Count); for (int f = next; f < atomContainer.Atoms.Count; f++) { - atom = atomContainer.Atoms[f]; + var atom = atomContainer.Atoms[f]; if (!satCheck.IsSaturated(atom, atomContainer) && exclusionAtom != atom - && !atomContainer.GetConnectedAtoms(exclusionAtom).Contains(atom)) + && !atomContainer.GetConnectedAtoms(exclusionAtom).Contains(atom)) { return atom; } } for (int f = 0; f < next; f++) { - atom = atomContainer.Atoms[f]; + var atom = atomContainer.Atoms[f]; if (!satCheck.IsSaturated(atom, atomContainer) && exclusionAtom != atom - && !atomContainer.GetConnectedAtoms(exclusionAtom).Contains(atom)) + && !atomContainer.GetConnectedAtoms(exclusionAtom).Contains(atom)) { return atom; } diff --git a/NCDK/StructGen/Stochastic/Operator/ChemGraph.cs b/NCDK/StructGen/Stochastic/Operators/ChemGraph.cs similarity index 75% rename from NCDK/StructGen/Stochastic/Operator/ChemGraph.cs rename to NCDK/StructGen/Stochastic/Operators/ChemGraph.cs index 3b432564..ccf6f149 100644 --- a/NCDK/StructGen/Stochastic/Operator/ChemGraph.cs +++ b/NCDK/StructGen/Stochastic/Operators/ChemGraph.cs @@ -25,57 +25,55 @@ using NCDK.Maths; using System.Collections.Generic; -namespace NCDK.StructGen.Stochastic.Operator +namespace NCDK.StructGen.Stochastic.Operators { // @cdk.module structgen // @cdk.githash public class ChemGraph { /* Number of atoms in this structure */ - protected int dim; - /* Number of atoms needed to form subgraph */ + private readonly int dim; + + /// + /// Number of atoms needed to form subgraph + /// public int NumAtoms { get; set; } - protected double[][] contab; + + private readonly double[][] contab; + /* Number of atoms that have been traversed */ - protected int travIndex; + private int travIndex; + /* Flag: true if atom visited during a traversal */ - protected bool[] visited; - /* Depth first traversal of the graph */ - public IList Subgraph { get; set; } + private bool[] visited; public ChemGraph(IAtomContainer chrom) { dim = chrom.Atoms.Count; NumAtoms = (int)(dim / 2); - //contab = Arrays.CreateJagged(dim, dim); // Maybe CDK's bug contab = ConnectionMatrix.GetMatrix(chrom); } - public IList PickDFGraph() + public IEnumerable PickDFGraph() { //depth first search from a randomly selected atom - travIndex = 0; - Subgraph = new List(); visited = new bool[dim]; for (int atom = 0; atom < dim; atom++) visited[atom] = false; int seedAtom = RandomNumbersTool.RandomInt(0, dim - 1); - RecursiveDFT(seedAtom); - - return Subgraph; + foreach (int atom in RecursiveDFT(seedAtom)) + yield return atom; + yield break; } - private void RecursiveDFT(int atom) + private IEnumerable RecursiveDFT(int atom) { if ((travIndex < NumAtoms) && (!visited[atom])) { - Subgraph.Add(atom); travIndex++; visited[atom] = true; - // for (int nextAtom = 0; nextAtom < dim; nextAtom++) //not generalized - // if (contab[atom][nextAtom] != 0) RecursiveDFT(nextAtom); List adjSet = new List(); for (int nextAtom = 0; nextAtom < dim; nextAtom++) { @@ -87,37 +85,38 @@ private void RecursiveDFT(int atom) while (adjSet.Count > 0) { int adjIndex = RandomNumbersTool.RandomInt(0, adjSet.Count - 1); - RecursiveDFT(adjSet[adjIndex]); + foreach (int i in RecursiveDFT(adjSet[adjIndex])) + yield return i; adjSet.RemoveAt(adjIndex); } } + yield break; } - public IList PickBFGraph() + public IEnumerable PickBFGraph() { //breadth first search from a randomly selected atom - travIndex = 0; - Subgraph = new List(); visited = new bool[dim]; for (int atom = 0; atom < dim; atom++) visited[atom] = false; int seedAtom = RandomNumbersTool.RandomInt(0, dim - 1); - List atomQueue = new List - { - seedAtom - }; + var atomQueue = new List { seedAtom }; visited[seedAtom] = true; - while (atomQueue.Count != 0 && Subgraph.Count < NumAtoms) + int count = 0; + while (atomQueue.Count != 0 && count < NumAtoms) { int foreAtom = atomQueue[0]; - Subgraph.Add(foreAtom); + + yield return foreAtom; + count++; + atomQueue.RemoveAt(0); travIndex++; - List adjSet = new List(); + var adjSet = new List(); for (int nextAtom = 0; nextAtom < dim; nextAtom++) { if (((int)contab[foreAtom][nextAtom] != 0) && (!visited[nextAtom])) @@ -133,7 +132,7 @@ public IList PickBFGraph() adjSet.RemoveAt(adjIndex); } } - return Subgraph; + yield break; } } } diff --git a/NCDK/StructGen/Stochastic/Operator/CrossoverMachine.cs b/NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs similarity index 83% rename from NCDK/StructGen/Stochastic/Operator/CrossoverMachine.cs rename to NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs index 9897363a..461a59e0 100644 --- a/NCDK/StructGen/Stochastic/Operator/CrossoverMachine.cs +++ b/NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs @@ -21,8 +21,9 @@ using NCDK.Maths; using NCDK.Tools; using System.Collections.Generic; +using System.Linq; -namespace NCDK.StructGen.Stochastic.Operator +namespace NCDK.StructGen.Stochastic.Operators { /// /// Modified molecular structures by applying crossover operator on a pair of parent structures @@ -49,7 +50,7 @@ public enum SplitMode } /// selects a partitioning mode - SplitMode splitMode = SplitMode.BreadthFirst; + readonly SplitMode splitMode = SplitMode.BreadthFirst; /// selects a partitioning scale int numatoms = 5; @@ -61,24 +62,26 @@ public CrossoverMachine() /// /// Performs the n point crossover of two . + /// + /// /// Precondition: The atoms in the molecules are ordered by properties to /// preserve (e. g. atom symbol). Due to its randomized nature, this method - /// fails in around 3% of all cases. A CDKException with message "Could not + /// fails in around 3% of all cases. A with message "Could not /// mate these properly" will then be thrown. - /// + /// /// The children. - /// if it was not possible to form offsprings. - public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) + /// if it was not possible to form off springs. + public IReadOnlyList DoCrossover(IAtomContainer dad, IAtomContainer mom) { int tries = 0; while (true) { int dim = dad.Atoms.Count; - IAtomContainer[] redChild = new IAtomContainer[2]; - IAtomContainer[] blueChild = new IAtomContainer[2]; + var redChild = new IAtomContainer[2]; + var blueChild = new IAtomContainer[2]; - IList redAtoms = new List(); - IList blueAtoms = new List(); + var redAtoms = new List(); + var blueAtoms = new List(); // randomly divide atoms into two parts: redAtoms and blueAtoms. if (splitMode == SplitMode.Random) @@ -97,18 +100,15 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) else { // split graph using depth/breadth first traverse - ChemGraph graph = new ChemGraph(dad) - { - NumAtoms = numatoms - }; + var graph = new ChemGraph(dad) { NumAtoms = numatoms }; if (splitMode == SplitMode.DepthFirst) { - redAtoms = graph.PickDFGraph(); + redAtoms = graph.PickDFGraph().ToList(); } else { //this is SPLIT_MODE_BREADTH_FIRST - redAtoms = graph.PickBFGraph(); + redAtoms = graph.PickBFGraph().ToList(); } for (int i = 0; i < dim; i++) @@ -126,7 +126,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) redChild[1] = dad.Builder.NewAtomContainer(mom); blueChild[1] = dad.Builder.NewAtomContainer(mom); - List blueAtomsInRedChild0 = new List(); + var blueAtomsInRedChild0 = new List(); for (int j = 0; j < blueAtoms.Count; j++) { blueAtomsInRedChild0.Add(redChild[0].Atoms[(int)blueAtoms[j]]); @@ -135,7 +135,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) { redChild[0].RemoveAtom(blueAtomsInRedChild0[j]); } - List blueAtomsInRedChild1 = new List(); + var blueAtomsInRedChild1 = new List(); for (int j = 0; j < blueAtoms.Count; j++) { blueAtomsInRedChild1.Add(redChild[1].Atoms[(int)blueAtoms[j]]); @@ -144,7 +144,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) { redChild[1].RemoveAtom(blueAtomsInRedChild1[j]); } - List redAtomsInBlueChild0 = new List(); + var redAtomsInBlueChild0 = new List(); for (int j = 0; j < redAtoms.Count; j++) { redAtomsInBlueChild0.Add(blueChild[0].Atoms[(int)redAtoms[j]]); @@ -153,7 +153,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) { blueChild[0].RemoveAtom(redAtomsInBlueChild0[j]); } - List redAtomsInBlueChild1 = new List(); + var redAtomsInBlueChild1 = new List(); for (int j = 0; j < redAtoms.Count; j++) { redAtomsInBlueChild1.Add(blueChild[1].Atoms[(int)redAtoms[j]]); @@ -164,7 +164,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) } //if the two fragments of one and only one parent have an uneven number //of attachment points, we need to rearrange them - SaturationChecker satCheck = new SaturationChecker(); + var satCheck = new SaturationChecker(); double red1attachpoints = 0; for (int i = 0; i < redChild[0].Atoms.Count; i++) { @@ -179,8 +179,8 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) if (red1attachpoints % 2 == 1 ^ red2attachpoints % 2 == 1) { isok = false; - IAtomContainer firstToBalance = redChild[1]; - IAtomContainer secondToBalance = blueChild[0]; + var firstToBalance = redChild[1]; + var secondToBalance = blueChild[0]; if (red1attachpoints % 2 == 1) { firstToBalance = redChild[0]; @@ -192,7 +192,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) foreach (var atom in firstToBalance.Atoms) { if (satCheck.GetCurrentMaxBondOrder(atom, firstToBalance) % 2 == 1 - && firstToBalance.GetBondOrderSum(atom) % 2 == 0) + && firstToBalance.GetBondOrderSum(atom) % 2 == 0) { //we remove this from it's current container and add it to the other one firstToBalance.RemoveAtom(atom); @@ -206,7 +206,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) if (isok) { //combine the fragments crosswise - IChemObjectSet[] newstrucs = new IChemObjectSet[2]; + var newstrucs = new IChemObjectSet[2]; newstrucs[0] = dad.Builder.NewAtomContainerSet(); newstrucs[0].AddRange(ConnectivityChecker.PartitionIntoMolecules(redChild[0])); newstrucs[0].AddRange(ConnectivityChecker.PartitionIntoMolecules(blueChild[1])); @@ -215,7 +215,7 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) newstrucs[1].AddRange(ConnectivityChecker.PartitionIntoMolecules(blueChild[0])); //and merge - List children = new List(2); + var children = new List(2); for (int f = 0; f < 2; f++) { var structrue = pfsm.Generate2(newstrucs[f]); @@ -226,8 +226,10 @@ public IList DoCrossover(IAtomContainer dad, IAtomContainer mom) children.Add(structrue); } } - if (children.Count == 2 && ConnectivityChecker.IsConnected(children[0]) - && ConnectivityChecker.IsConnected(children[1])) return children; + if (children.Count == 2 + && ConnectivityChecker.IsConnected(children[0]) + && ConnectivityChecker.IsConnected(children[1])) + return children; } tries++; if (tries > 20) diff --git a/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs b/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs index 0299f056..135d4348 100644 --- a/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs +++ b/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs @@ -54,10 +54,14 @@ public PartialFilledStructureMerger() /// /// Randomly generates a single, connected, correctly bonded structure from - /// a number of fragments. IMPORTANT: The AtomContainers in the set must be - /// connected. If an AtomContainer is disconnected, no valid result will - /// be formed + /// a number of fragments. /// + /// + /// + /// The in the set must be + /// connected. If an is disconnected, no valid result will + /// + /// /// The fragments to generate for. /// The newly formed structure. /// No valid result could be formed." @@ -65,7 +69,7 @@ public IAtomContainer Generate(IChemObjectSet atomContainers) { var container = Generate2(atomContainers); if (container == null) - throw new CDKException("Could not combine the fragments to combine a valid, satured structure"); + throw new CDKException("Could not combine the fragments to combine a valid, saturated structure"); return container; } @@ -87,19 +91,18 @@ internal IAtomContainer Generate2(IChemObjectSet atomContainers) if (ac == null) continue; - foreach (var atom in AtomContainerManipulator.GetAtomArray(ac)) + foreach (var atom in ac.Atoms.ToList()) { if (!satCheck.IsSaturated(atom, ac)) { - IAtom partner = GetAnotherUnsaturatedNode(atom, ac, atomContainers); + var partner = GetAnotherUnsaturatedNode(atom, ac, atomContainers); if (partner != null) { - IAtomContainer toadd = AtomContainerSetManipulator.GetRelevantAtomContainer( - atomContainers, partner); - double cmax1 = satCheck.GetCurrentMaxBondOrder(atom, ac); - double cmax2 = satCheck.GetCurrentMaxBondOrder(partner, toadd); - double max = Math.Min(cmax1, cmax2); - double order = Math.Min(Math.Max(1.0, max), 3.0);//(double)Math.Round(Math.Random() * max) + var toadd = AtomContainerSetManipulator.GetRelevantAtomContainer( atomContainers, partner); + var cmax1 = satCheck.GetCurrentMaxBondOrder(atom, ac); + var cmax2 = satCheck.GetCurrentMaxBondOrder(partner, toadd); + var max = Math.Min(cmax1, cmax2); + var order = Math.Min(Math.Max(1.0, max), 3.0);//(double)Math.Round(Math.Random() * max) Debug.WriteLine($"cmax1, cmax2, max, order: {cmax1}, {cmax2}, {max}, {order}"); if (toadd != ac) { @@ -118,7 +121,7 @@ internal IAtomContainer Generate2(IChemObjectSet atomContainers) } } while (bondFormed); if (atomContainers.Count == 1 - && satCheck.AllSaturated(atomContainers[0])) + && satCheck.AllSaturated(atomContainers[0])) { structureFound = true; } @@ -133,13 +136,11 @@ internal IAtomContainer Generate2(IChemObjectSet atomContainers) } /// - /// Gets a randomly selected unsaturated atom from the set. If there are any, it will be from another - /// container than exclusionAtom. + /// Gets a randomly selected unsaturated atom from the set. If there are any, it will be from another + /// container than exclusionAtom. /// /// The unsaturated atom. - private IAtom GetAnotherUnsaturatedNode(IAtom exclusionAtom, - IAtomContainer exclusionAtomContainer, - IChemObjectSet atomContainers) + private IAtom GetAnotherUnsaturatedNode(IAtom exclusionAtom, IAtomContainer exclusionAtomContainer, IChemObjectSet atomContainers) { IAtom atom; @@ -159,12 +160,13 @@ private IAtom GetAnotherUnsaturatedNode(IAtom exclusionAtom, } } { - int next = exclusionAtomContainer.Atoms.Count;//(int) (Math.random() * ac.getAtomCount()); + var next = exclusionAtomContainer.Atoms.Count;//(int) (Math.random() * ac.getAtomCount()); for (int f = 0; f < next; f++) { atom = exclusionAtomContainer.Atoms[f]; - if (!satCheck.IsSaturated(atom, exclusionAtomContainer) && exclusionAtom != atom - && !exclusionAtomContainer.GetConnectedAtoms(exclusionAtom).Contains(atom)) + if (!satCheck.IsSaturated(atom, exclusionAtomContainer) + && exclusionAtom != atom + && !exclusionAtomContainer.GetConnectedAtoms(exclusionAtom).Contains(atom)) { return atom; } diff --git a/NCDK/StructGen/VicinitySampler.cs b/NCDK/StructGen/VicinitySampler.cs index feb667c6..7bcad0ca 100644 --- a/NCDK/StructGen/VicinitySampler.cs +++ b/NCDK/StructGen/VicinitySampler.cs @@ -39,7 +39,7 @@ namespace NCDK.StructGen // @cdk.module structgen // @cdk.githash // @cdk.bug 1632610 - public class VicinitySampler + public static class VicinitySampler { /// /// Choose any possible quadruple of the set of atoms diff --git a/NCDK/TT/AdductFormula.tt b/NCDK/TT/AdductFormula.tt index 3a2a775f..0a2cea56 100644 --- a/NCDK/TT/AdductFormula.tt +++ b/NCDK/TT/AdductFormula.tt @@ -27,6 +27,8 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +#pragma warning disable CA1710 // Identifiers should have correct suffix + <# foreach (var ns in namespaces) { @@ -117,7 +119,6 @@ namespace <#= ns.NS #> public virtual int? Charge { get { return components.Select(n => n.Charge ?? 0).Sum(); } - set { new FieldAccessException(); } } /// @@ -132,12 +133,12 @@ namespace <#= ns.NS #> } /// - /// The the number of different isotopes in this adduct formula + /// The number of different isotopes in this adduct formula /// public virtual int IsotopeCount => IsotopesList().Count; /// - /// An IEnumerator for looping over all isotopes in this adduct formula. + /// An for looping over all isotopes in this adduct formula. /// public virtual IEnumerable GetIsotopes() => IsotopesList(); @@ -147,7 +148,7 @@ namespace <#= ns.NS #> /// A List with the isotopes in this adduct formula private List IsotopesList() { - List isotopes = new List(); + var isotopes = new List(); foreach (var component in components) { foreach (var isotope in component.Isotopes) @@ -158,30 +159,31 @@ namespace <#= ns.NS #> } /// - /// Returns an Iterable for looping over all IMolecularFormula + /// Returns an enumerator for looping over all /// in this adduct formula. /// - /// An Iterable with the IMolecularFormula in this adduct formula + /// An enumerator with the in this adduct formula public virtual IEnumerator GetEnumerator() => components.GetEnumerator(); /// - /// The number of MolecularFormulas in this AdductFormula. + /// The number of s in this AdductFormula. /// +#pragma warning disable CA1721 // Property names should not match get methods public virtual int Count => components.Count; +#pragma warning restore CA1721 // Property names should not match get methods /// - /// True, if the AdductFormula contains the given IMolecularFormula object. - /// - /// The IMolecularFormula this AdductFormula is searched for - /// True, if the AdductFormula contains the given IMolecularFormula object + /// if the contains the given object. /// + /// The this is searched for + /// if the contains the given object public virtual bool Contains(IMolecularFormula formula) { return components.Contains(formula); } /// - /// The MolecularFormula at position in the hemObject. + /// The at position in the hemObject. /// /// The position of the IMolecularFormula to be returned. /// The IMolecularFormula at position . @@ -192,7 +194,7 @@ namespace <#= ns.NS #> } /// - /// Removes all IMolecularFormula from this chemObject. + /// Removes all from this object. /// public virtual void Clear() { @@ -200,9 +202,9 @@ namespace <#= ns.NS #> } /// - /// Removes an IMolecularFormula from this chemObject. + /// Removes an from this object. /// - /// The IMolecularFormula to be removed from this chemObject + /// The to be removed from this object public virtual bool Remove(IMolecularFormula formula) { return components.Remove(formula); @@ -223,15 +225,6 @@ namespace <#= ns.NS #> /// The cloned object public virtual object Clone() { - // /* it is not a super class of chemObject */ - // AdductFormula clone = (AdductFormula) base.Clone(); - // // start from scratch - // clone.Clear(); - // // clone all molecularFormulas - // IEnumerator iterForm = this; - // while(iterForm.MoveNext()){ - // clone.AddMolecularFormula((IMolecularFormula) iterForm.Next().Clone()); - // } AdductFormula clone = new AdductFormula(); foreach (var form in this) { @@ -252,7 +245,7 @@ namespace <#= ns.NS #> /// The first Isotope to compare /// The second Isotope to compare /// True, if both isotope are the same - private bool IsTheSame(IIsotope isotopeOne, IIsotope isotopeTwo) + private static bool IsTheSame(IIsotope isotopeOne, IIsotope isotopeTwo) { // XXX - floating point equality! if (isotopeOne.Symbol != isotopeTwo.Symbol) return false; @@ -290,7 +283,7 @@ namespace <#= ns.NS #> public bool IsReadOnly => ((IList)(components)).IsReadOnly; public IChemObjectBuilder Builder - => <#= ns.NS #>.ChemObjectBuilder.Instance; + => ChemObjectBuilder.Instance; } } <# diff --git a/NCDK/TT/AdductFormula.tt.cs b/NCDK/TT/AdductFormula.tt.cs index 02a1910e..c0ee8e57 100644 --- a/NCDK/TT/AdductFormula.tt.cs +++ b/NCDK/TT/AdductFormula.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2017 Kazuya Ujihara @@ -28,6 +29,8 @@ using System.Collections.Generic; using System.Linq; +#pragma warning disable CA1710 // Identifiers should have correct suffix + namespace NCDK.Default { /// @@ -114,7 +117,6 @@ public virtual bool Contains(IIsotope isotope) public virtual int? Charge { get { return components.Select(n => n.Charge ?? 0).Sum(); } - set { new FieldAccessException(); } } /// @@ -129,12 +131,12 @@ public virtual int GetCount(IIsotope isotope) } /// - /// The the number of different isotopes in this adduct formula + /// The number of different isotopes in this adduct formula /// public virtual int IsotopeCount => IsotopesList().Count; /// - /// An IEnumerator for looping over all isotopes in this adduct formula. + /// An for looping over all isotopes in this adduct formula. /// public virtual IEnumerable GetIsotopes() => IsotopesList(); @@ -144,7 +146,7 @@ public virtual int GetCount(IIsotope isotope) /// A List with the isotopes in this adduct formula private List IsotopesList() { - List isotopes = new List(); + var isotopes = new List(); foreach (var component in components) { foreach (var isotope in component.Isotopes) @@ -155,30 +157,31 @@ private List IsotopesList() } /// - /// Returns an Iterable for looping over all IMolecularFormula + /// Returns an enumerator for looping over all /// in this adduct formula. /// - /// An Iterable with the IMolecularFormula in this adduct formula + /// An enumerator with the in this adduct formula public virtual IEnumerator GetEnumerator() => components.GetEnumerator(); /// - /// The number of MolecularFormulas in this AdductFormula. + /// The number of s in this AdductFormula. /// +#pragma warning disable CA1721 // Property names should not match get methods public virtual int Count => components.Count; +#pragma warning restore CA1721 // Property names should not match get methods /// - /// True, if the AdductFormula contains the given IMolecularFormula object. - /// - /// The IMolecularFormula this AdductFormula is searched for - /// True, if the AdductFormula contains the given IMolecularFormula object + /// if the contains the given object. /// + /// The this is searched for + /// if the contains the given object public virtual bool Contains(IMolecularFormula formula) { return components.Contains(formula); } /// - /// The MolecularFormula at position in the hemObject. + /// The at position in the hemObject. /// /// The position of the IMolecularFormula to be returned. /// The IMolecularFormula at position . @@ -189,7 +192,7 @@ public virtual IMolecularFormula this[int position] } /// - /// Removes all IMolecularFormula from this chemObject. + /// Removes all from this object. /// public virtual void Clear() { @@ -197,9 +200,9 @@ public virtual void Clear() } /// - /// Removes an IMolecularFormula from this chemObject. + /// Removes an from this object. /// - /// The IMolecularFormula to be removed from this chemObject + /// The to be removed from this object public virtual bool Remove(IMolecularFormula formula) { return components.Remove(formula); @@ -220,15 +223,6 @@ public virtual void RemoveAt(int position) /// The cloned object public virtual object Clone() { - // /* it is not a super class of chemObject */ - // AdductFormula clone = (AdductFormula) base.Clone(); - // // start from scratch - // clone.Clear(); - // // clone all molecularFormulas - // IEnumerator iterForm = this; - // while(iterForm.MoveNext()){ - // clone.AddMolecularFormula((IMolecularFormula) iterForm.Next().Clone()); - // } AdductFormula clone = new AdductFormula(); foreach (var form in this) { @@ -249,7 +243,7 @@ public ICDKObject Clone(CDKObjectMap map) /// The first Isotope to compare /// The second Isotope to compare /// True, if both isotope are the same - private bool IsTheSame(IIsotope isotopeOne, IIsotope isotopeTwo) + private static bool IsTheSame(IIsotope isotopeOne, IIsotope isotopeTwo) { // XXX - floating point equality! if (isotopeOne.Symbol != isotopeTwo.Symbol) return false; @@ -287,7 +281,7 @@ public void CopyTo(IMolecularFormula[] array, int arrayIndex) public bool IsReadOnly => ((IList)(components)).IsReadOnly; public IChemObjectBuilder Builder - => NCDK.Default.ChemObjectBuilder.Instance; + => ChemObjectBuilder.Instance; } } namespace NCDK.Silent @@ -376,7 +370,6 @@ public virtual bool Contains(IIsotope isotope) public virtual int? Charge { get { return components.Select(n => n.Charge ?? 0).Sum(); } - set { new FieldAccessException(); } } /// @@ -391,12 +384,12 @@ public virtual int GetCount(IIsotope isotope) } /// - /// The the number of different isotopes in this adduct formula + /// The number of different isotopes in this adduct formula /// public virtual int IsotopeCount => IsotopesList().Count; /// - /// An IEnumerator for looping over all isotopes in this adduct formula. + /// An for looping over all isotopes in this adduct formula. /// public virtual IEnumerable GetIsotopes() => IsotopesList(); @@ -406,7 +399,7 @@ public virtual int GetCount(IIsotope isotope) /// A List with the isotopes in this adduct formula private List IsotopesList() { - List isotopes = new List(); + var isotopes = new List(); foreach (var component in components) { foreach (var isotope in component.Isotopes) @@ -417,30 +410,31 @@ private List IsotopesList() } /// - /// Returns an Iterable for looping over all IMolecularFormula + /// Returns an enumerator for looping over all /// in this adduct formula. /// - /// An Iterable with the IMolecularFormula in this adduct formula + /// An enumerator with the in this adduct formula public virtual IEnumerator GetEnumerator() => components.GetEnumerator(); /// - /// The number of MolecularFormulas in this AdductFormula. + /// The number of s in this AdductFormula. /// +#pragma warning disable CA1721 // Property names should not match get methods public virtual int Count => components.Count; +#pragma warning restore CA1721 // Property names should not match get methods /// - /// True, if the AdductFormula contains the given IMolecularFormula object. - /// - /// The IMolecularFormula this AdductFormula is searched for - /// True, if the AdductFormula contains the given IMolecularFormula object + /// if the contains the given object. /// + /// The this is searched for + /// if the contains the given object public virtual bool Contains(IMolecularFormula formula) { return components.Contains(formula); } /// - /// The MolecularFormula at position in the hemObject. + /// The at position in the hemObject. /// /// The position of the IMolecularFormula to be returned. /// The IMolecularFormula at position . @@ -451,7 +445,7 @@ public virtual IMolecularFormula this[int position] } /// - /// Removes all IMolecularFormula from this chemObject. + /// Removes all from this object. /// public virtual void Clear() { @@ -459,9 +453,9 @@ public virtual void Clear() } /// - /// Removes an IMolecularFormula from this chemObject. + /// Removes an from this object. /// - /// The IMolecularFormula to be removed from this chemObject + /// The to be removed from this object public virtual bool Remove(IMolecularFormula formula) { return components.Remove(formula); @@ -482,15 +476,6 @@ public virtual void RemoveAt(int position) /// The cloned object public virtual object Clone() { - // /* it is not a super class of chemObject */ - // AdductFormula clone = (AdductFormula) base.Clone(); - // // start from scratch - // clone.Clear(); - // // clone all molecularFormulas - // IEnumerator iterForm = this; - // while(iterForm.MoveNext()){ - // clone.AddMolecularFormula((IMolecularFormula) iterForm.Next().Clone()); - // } AdductFormula clone = new AdductFormula(); foreach (var form in this) { @@ -511,7 +496,7 @@ public ICDKObject Clone(CDKObjectMap map) /// The first Isotope to compare /// The second Isotope to compare /// True, if both isotope are the same - private bool IsTheSame(IIsotope isotopeOne, IIsotope isotopeTwo) + private static bool IsTheSame(IIsotope isotopeOne, IIsotope isotopeTwo) { // XXX - floating point equality! if (isotopeOne.Symbol != isotopeTwo.Symbol) return false; @@ -549,6 +534,6 @@ public void CopyTo(IMolecularFormula[] array, int arrayIndex) public bool IsReadOnly => ((IList)(components)).IsReadOnly; public IChemObjectBuilder Builder - => NCDK.Silent.ChemObjectBuilder.Instance; + => ChemObjectBuilder.Instance; } } diff --git a/NCDK/TT/AminoAcid.tt.cs b/NCDK/TT/AminoAcid.tt.cs index dabbc52f..f5d30bab 100644 --- a/NCDK/TT/AminoAcid.tt.cs +++ b/NCDK/TT/AminoAcid.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara diff --git a/NCDK/TT/Association.tt b/NCDK/TT/Association.tt index 2af3c0eb..37a0ba6d 100644 --- a/NCDK/TT/Association.tt +++ b/NCDK/TT/Association.tt @@ -44,10 +44,12 @@ namespace <#= ns.NS #> [Serializable] public class Association : ElectronContainer, IChemObjectListener { + private readonly ObservableChemObjectCollection associatedAtoms; + /// /// The atoms which take part in the association. /// - public IList AssociatedAtoms { get; protected set; } + public IList AssociatedAtoms => associatedAtoms; /// /// Constructs an association between two Atom's. @@ -57,7 +59,8 @@ namespace <#= ns.NS #> /// public Association(IAtom atom1, IAtom atom2) : this(new[] { atom1, atom2 }) - { } + { + } /// /// Constructs an empty association. @@ -65,11 +68,12 @@ namespace <#= ns.NS #> /// public Association() : this(Array.Empty()) - { } + { + } public Association(IEnumerable atoms) { - AssociatedAtoms = CreateObservableChemObjectCollection(atoms); + associatedAtoms = CreateObservableChemObjectCollection(atoms); } private ObservableChemObjectCollection CreateObservableChemObjectCollection(IEnumerable objs) diff --git a/NCDK/TT/Association.tt.cs b/NCDK/TT/Association.tt.cs index 8d2fbaaf..0d693332 100644 --- a/NCDK/TT/Association.tt.cs +++ b/NCDK/TT/Association.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -41,10 +42,12 @@ namespace NCDK.Default [Serializable] public class Association : ElectronContainer, IChemObjectListener { + private readonly ObservableChemObjectCollection associatedAtoms; + /// /// The atoms which take part in the association. /// - public IList AssociatedAtoms { get; protected set; } + public IList AssociatedAtoms => associatedAtoms; /// /// Constructs an association between two Atom's. @@ -54,7 +57,8 @@ public class Association : ElectronContainer, IChemObjectListener /// public Association(IAtom atom1, IAtom atom2) : this(new[] { atom1, atom2 }) - { } + { + } /// /// Constructs an empty association. @@ -62,11 +66,12 @@ public Association(IAtom atom1, IAtom atom2) /// public Association() : this(Array.Empty()) - { } + { + } public Association(IEnumerable atoms) { - AssociatedAtoms = CreateObservableChemObjectCollection(atoms); + associatedAtoms = CreateObservableChemObjectCollection(atoms); } private ObservableChemObjectCollection CreateObservableChemObjectCollection(IEnumerable objs) @@ -113,10 +118,12 @@ namespace NCDK.Silent [Serializable] public class Association : ElectronContainer, IChemObjectListener { + private readonly ObservableChemObjectCollection associatedAtoms; + /// /// The atoms which take part in the association. /// - public IList AssociatedAtoms { get; protected set; } + public IList AssociatedAtoms => associatedAtoms; /// /// Constructs an association between two Atom's. @@ -126,7 +133,8 @@ public class Association : ElectronContainer, IChemObjectListener /// public Association(IAtom atom1, IAtom atom2) : this(new[] { atom1, atom2 }) - { } + { + } /// /// Constructs an empty association. @@ -134,11 +142,12 @@ public Association(IAtom atom1, IAtom atom2) /// public Association() : this(Array.Empty()) - { } + { + } public Association(IEnumerable atoms) { - AssociatedAtoms = CreateObservableChemObjectCollection(atoms); + associatedAtoms = CreateObservableChemObjectCollection(atoms); } private ObservableChemObjectCollection CreateObservableChemObjectCollection(IEnumerable objs) diff --git a/NCDK/TT/Atom.tt b/NCDK/TT/Atom.tt index 6a02c624..cf461231 100644 --- a/NCDK/TT/Atom.tt +++ b/NCDK/TT/Atom.tt @@ -26,10 +26,12 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using NCDK.Config; using NCDK.Numerics; using System; using System.Collections.Generic; +using System.Runtime.Serialization; using System.Text; <# @@ -44,32 +46,25 @@ namespace <#= ns.NS #> /// /// An Atom class is instantiated with at least the atom symbol: /// - /// Atom a = new Atom("C"); + /// Atom a = new Atom("C"); /// /// /// Once instantiated all field not filled by passing parameters - /// to the constructor are null. Atoms can be configured by using - /// the IsotopeFactory.configure() method: + /// to the constructor are . Atoms can be configured by using + /// the method: /// - /// IsotopeFactory factory = SomeIsotopeFactory.GetInstance(a.Builder); - /// factory.Configure(a); + /// IsotopeFactory factory = SomeIsotopeFactory.GetInstance(a.Builder); + /// factory.Configure(a); /// - /// - /// More examples about using this class can be found in the - /// Junit test for this class. /// /// // @cdk.githash // @author steinbeck // @cdk.created 2000-10-02 // @cdk.keyword atom - [Serializable] public class Atom - : AtomType, IAtom + : AtomType, IAtom, ISerializable { - // Let's keep this exact specification of what kind of point2d we're talking - // of here, since there are so many around in the java standard api - internal double? charge; internal int? implicitHydrogenCount; internal Vector2? point2D; @@ -78,6 +73,40 @@ namespace <#= ns.NS #> internal int stereoParity; internal bool isSingleOrDouble; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(charge), charge); + info.AddNullableValue(nameof(implicitHydrogenCount), implicitHydrogenCount); + info.AddNullableValue(nameof(point2D), point2D); + info.AddNullableValue(nameof(point3D), point3D); + info.AddNullableValue(nameof(fractionalPoint3D), fractionalPoint3D); + info.AddValue(nameof(stereoParity), stereoParity); + info.AddValue(nameof(isSingleOrDouble), isSingleOrDouble); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected Atom(SerializationInfo info, StreamingContext context) + : base(info, context) + { + charge = info.GetNullable(nameof(charge)); + implicitHydrogenCount = info.GetNullable(nameof(implicitHydrogenCount)); + + covalentRadius = info.GetNullable(nameof(covalentRadius)); + hybridization = (Hybridization)info.GetInt32(nameof(hybridization)); + valency = info.GetNullable(nameof(valency)); + formalNeighbourCount = info.GetNullable(nameof(formalNeighbourCount)); + atomTypeName = info.GetString(nameof(atomTypeName)); + isHydrogenBondAcceptor = info.GetBoolean(nameof(isHydrogenBondAcceptor)); + isHydrogenBondDonor = info.GetBoolean(nameof(isHydrogenBondDonor)); + isAliphatic = info.GetBoolean(nameof(isAliphatic)); + isAromatic = info.GetBoolean(nameof(isAromatic)); + isInRing = info.GetBoolean(nameof(isInRing)); + isReactiveCenter = info.GetBoolean(nameof(isReactiveCenter)); + } + + /// /// Constructs an completely unset Atom. /// @@ -120,8 +149,8 @@ namespace <#= ns.NS #> /// Constructs an Atom from a string containing an element symbol and optionally /// the atomic mass, hydrogen count, and formal charge. /// - /// - /// The symbol grammar allows + /// + /// The symbol grammar allows /// easy construction from common symbols, for example: /// /// @@ -137,7 +166,7 @@ namespace <#= ns.NS #> /// hcnt := 'H' \d+ /// fchg := '+' \d+? | '-' \d+? /// - /// + /// /// string with the element symbol public Atom(string symbol) : base((string)null) { @@ -194,24 +223,24 @@ namespace <#= ns.NS #> } } - /// - public virtual IAtomContainer Container => null; + /// + public virtual IAtomContainer Container => null; - /// - public virtual int Index => -1; + /// + public virtual int Index => -1; - /// - public virtual IReadOnlyList Bonds - { - get { throw new NotSupportedException(); } - } + /// + public virtual IReadOnlyList Bonds + { + get { throw new NotSupportedException(); } + } - /// - public IBond GetBond(IAtom atom) - { - throw new InvalidOperationException(); - } - + /// + public IBond GetBond(IAtom atom) + { + throw new InvalidOperationException(); + } + /// /// The partial charge of this atom. /// @@ -318,9 +347,8 @@ namespace <#= ns.NS #> /// public override bool Compare(object obj) { - var aa = obj as IAtom; - // XXX: floating point comparision! - return aa != null && base.Compare(obj) + // XXX: floating point comparision! + return obj is IAtom aa && base.Compare(obj) && Point2D == aa.Point2D && Point3D == aa.Point3D && ImplicitHydrogenCount == aa.ImplicitHydrogenCount @@ -379,7 +407,7 @@ namespace <#= ns.NS #> private static bool ParseAtomSymbol(IAtom atom, string str) { - ChemicalElement elem; + ChemicalElement elem; int len = str.Length; int pos = 0; @@ -389,60 +417,36 @@ namespace <#= ns.NS #> int hcnt = 0; int chg = 0; + // optional mass + if (pos < len && IsDigit(str[pos])) { -<# if (!ns.IsSilent) { #> - // optional mass - if (pos < len && IsDigit(str[pos])) - { - mass = (str[pos++] - '0'); - while (pos < len && IsDigit(str[pos])) - mass = 10 * mass + (str[pos++] - '0'); - } -<# } else { #> - elem = ChemicalElement.OfString(str); - if (elem != ChemicalElements.Unknown) - { - atom.AtomicNumber = elem.AtomicNumber; - atom.Symbol = elem.Symbol; - return true; - } -<# } #> - else if ("R".Equals(str)) - { - atom.AtomicNumber = 0; - atom.Symbol = "R"; - return true; - } - else if ("*".Equals(str)) - { - atom.AtomicNumber = 0; - atom.Symbol = "*"; - return true; - } - else if ("D".Equals(str)) - { - atom.AtomicNumber = 1; - atom.MassNumber = 2; - atom.Symbol = "H"; - return true; - } - else if ("T".Equals(str)) + mass = (str[pos++] - '0'); + while (pos < len && IsDigit(str[pos])) + mass = 10 * mass + (str[pos++] - '0'); + } + else + { + switch (str) { - atom.AtomicNumber = 1; - atom.MassNumber = 3; - atom.Symbol = "H"; - return true; + case "R": + atom.AtomicNumber = 0; + atom.Symbol = "R"; + return true; + case "*": + atom.AtomicNumber = 0; + atom.Symbol = "*"; + return true; + case "D": + atom.AtomicNumber = 1; + atom.MassNumber = 2; + atom.Symbol = "H"; + return true; + case "T": + atom.AtomicNumber = 1; + atom.MassNumber = 3; + atom.Symbol = "H"; + return true; } - -<# if (ns.IsSilent) { #> - // optional mass - if (pos < len && IsDigit(str[pos])) - { - mass = (str[pos++] - '0'); - while (pos < len && IsDigit(str[pos])) - mass = 10 * mass + (str[pos++] - '0'); - } -<# } #> } // atom symbol @@ -523,19 +527,19 @@ namespace <#= ns.NS #> return pos == len && len > 0; } - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - - /// - public override bool Equals(object obj) - { - if (obj is AtomRef) - return base.Equals(((AtomRef) obj).Deref()); - return base.Equals(obj); - } + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + + /// + public override bool Equals(object other) + { + if (other is AtomRef) + return base.Equals(((AtomRef)other).Deref()); + return base.Equals(other); + } } } <# diff --git a/NCDK/TT/Atom.tt.cs b/NCDK/TT/Atom.tt.cs index 6a0e5770..dc4a5ff8 100644 --- a/NCDK/TT/Atom.tt.cs +++ b/NCDK/TT/Atom.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -27,10 +28,12 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using NCDK.Config; using NCDK.Numerics; using System; using System.Collections.Generic; +using System.Runtime.Serialization; using System.Text; namespace NCDK.Default @@ -41,32 +44,25 @@ namespace NCDK.Default /// /// An Atom class is instantiated with at least the atom symbol: /// - /// Atom a = new Atom("C"); + /// Atom a = new Atom("C"); /// /// /// Once instantiated all field not filled by passing parameters - /// to the constructor are null. Atoms can be configured by using - /// the IsotopeFactory.configure() method: + /// to the constructor are . Atoms can be configured by using + /// the method: /// - /// IsotopeFactory factory = SomeIsotopeFactory.GetInstance(a.Builder); - /// factory.Configure(a); + /// IsotopeFactory factory = SomeIsotopeFactory.GetInstance(a.Builder); + /// factory.Configure(a); /// - /// - /// More examples about using this class can be found in the - /// Junit test for this class. /// /// // @cdk.githash // @author steinbeck // @cdk.created 2000-10-02 // @cdk.keyword atom - [Serializable] public class Atom - : AtomType, IAtom + : AtomType, IAtom, ISerializable { - // Let's keep this exact specification of what kind of point2d we're talking - // of here, since there are so many around in the java standard api - internal double? charge; internal int? implicitHydrogenCount; internal Vector2? point2D; @@ -75,6 +71,40 @@ public class Atom internal int stereoParity; internal bool isSingleOrDouble; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(charge), charge); + info.AddNullableValue(nameof(implicitHydrogenCount), implicitHydrogenCount); + info.AddNullableValue(nameof(point2D), point2D); + info.AddNullableValue(nameof(point3D), point3D); + info.AddNullableValue(nameof(fractionalPoint3D), fractionalPoint3D); + info.AddValue(nameof(stereoParity), stereoParity); + info.AddValue(nameof(isSingleOrDouble), isSingleOrDouble); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected Atom(SerializationInfo info, StreamingContext context) + : base(info, context) + { + charge = info.GetNullable(nameof(charge)); + implicitHydrogenCount = info.GetNullable(nameof(implicitHydrogenCount)); + + covalentRadius = info.GetNullable(nameof(covalentRadius)); + hybridization = (Hybridization)info.GetInt32(nameof(hybridization)); + valency = info.GetNullable(nameof(valency)); + formalNeighbourCount = info.GetNullable(nameof(formalNeighbourCount)); + atomTypeName = info.GetString(nameof(atomTypeName)); + isHydrogenBondAcceptor = info.GetBoolean(nameof(isHydrogenBondAcceptor)); + isHydrogenBondDonor = info.GetBoolean(nameof(isHydrogenBondDonor)); + isAliphatic = info.GetBoolean(nameof(isAliphatic)); + isAromatic = info.GetBoolean(nameof(isAromatic)); + isInRing = info.GetBoolean(nameof(isInRing)); + isReactiveCenter = info.GetBoolean(nameof(isReactiveCenter)); + } + + /// /// Constructs an completely unset Atom. /// @@ -117,8 +147,8 @@ public Atom(int elem, int hcnt, int fchg) : base((string)null) /// Constructs an Atom from a string containing an element symbol and optionally /// the atomic mass, hydrogen count, and formal charge. /// - /// - /// The symbol grammar allows + /// + /// The symbol grammar allows /// easy construction from common symbols, for example: /// /// @@ -134,7 +164,7 @@ public Atom(int elem, int hcnt, int fchg) : base((string)null) /// hcnt := 'H' \d+ /// fchg := '+' \d+? | '-' \d+? /// - /// + /// /// string with the element symbol public Atom(string symbol) : base((string)null) { @@ -191,24 +221,24 @@ public Atom(IElement element) } } - /// - public virtual IAtomContainer Container => null; + /// + public virtual IAtomContainer Container => null; - /// - public virtual int Index => -1; + /// + public virtual int Index => -1; - /// - public virtual IReadOnlyList Bonds - { - get { throw new NotSupportedException(); } - } + /// + public virtual IReadOnlyList Bonds + { + get { throw new NotSupportedException(); } + } - /// - public IBond GetBond(IAtom atom) - { - throw new InvalidOperationException(); - } - + /// + public IBond GetBond(IAtom atom) + { + throw new InvalidOperationException(); + } + /// /// The partial charge of this atom. /// @@ -301,9 +331,8 @@ public bool IsSingleOrDouble /// public override bool Compare(object obj) { - var aa = obj as IAtom; - // XXX: floating point comparision! - return aa != null && base.Compare(obj) + // XXX: floating point comparision! + return obj is IAtom aa && base.Compare(obj) && Point2D == aa.Point2D && Point3D == aa.Point3D && ImplicitHydrogenCount == aa.ImplicitHydrogenCount @@ -362,7 +391,7 @@ private static bool IsDigit(char c) private static bool ParseAtomSymbol(IAtom atom, string str) { - ChemicalElement elem; + ChemicalElement elem; int len = str.Length; int pos = 0; @@ -372,41 +401,36 @@ private static bool ParseAtomSymbol(IAtom atom, string str) int hcnt = 0; int chg = 0; + // optional mass + if (pos < len && IsDigit(str[pos])) { - // optional mass - if (pos < len && IsDigit(str[pos])) - { - mass = (str[pos++] - '0'); - while (pos < len && IsDigit(str[pos])) - mass = 10 * mass + (str[pos++] - '0'); - } - else if ("R".Equals(str)) - { - atom.AtomicNumber = 0; - atom.Symbol = "R"; - return true; - } - else if ("*".Equals(str)) - { - atom.AtomicNumber = 0; - atom.Symbol = "*"; - return true; - } - else if ("D".Equals(str)) - { - atom.AtomicNumber = 1; - atom.MassNumber = 2; - atom.Symbol = "H"; - return true; - } - else if ("T".Equals(str)) + mass = (str[pos++] - '0'); + while (pos < len && IsDigit(str[pos])) + mass = 10 * mass + (str[pos++] - '0'); + } + else + { + switch (str) { - atom.AtomicNumber = 1; - atom.MassNumber = 3; - atom.Symbol = "H"; - return true; + case "R": + atom.AtomicNumber = 0; + atom.Symbol = "R"; + return true; + case "*": + atom.AtomicNumber = 0; + atom.Symbol = "*"; + return true; + case "D": + atom.AtomicNumber = 1; + atom.MassNumber = 2; + atom.Symbol = "H"; + return true; + case "T": + atom.AtomicNumber = 1; + atom.MassNumber = 3; + atom.Symbol = "H"; + return true; } - } // atom symbol @@ -487,19 +511,19 @@ private static bool ParseAtomSymbol(IAtom atom, string str) return pos == len && len > 0; } - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } - /// - public override bool Equals(object obj) - { - if (obj is AtomRef) - return base.Equals(((AtomRef) obj).Deref()); - return base.Equals(obj); - } + /// + public override bool Equals(object other) + { + if (other is AtomRef) + return base.Equals(((AtomRef)other).Deref()); + return base.Equals(other); + } } } namespace NCDK.Silent @@ -510,32 +534,25 @@ namespace NCDK.Silent /// /// An Atom class is instantiated with at least the atom symbol: /// - /// Atom a = new Atom("C"); + /// Atom a = new Atom("C"); /// /// /// Once instantiated all field not filled by passing parameters - /// to the constructor are null. Atoms can be configured by using - /// the IsotopeFactory.configure() method: + /// to the constructor are . Atoms can be configured by using + /// the method: /// - /// IsotopeFactory factory = SomeIsotopeFactory.GetInstance(a.Builder); - /// factory.Configure(a); + /// IsotopeFactory factory = SomeIsotopeFactory.GetInstance(a.Builder); + /// factory.Configure(a); /// - /// - /// More examples about using this class can be found in the - /// Junit test for this class. /// /// // @cdk.githash // @author steinbeck // @cdk.created 2000-10-02 // @cdk.keyword atom - [Serializable] public class Atom - : AtomType, IAtom + : AtomType, IAtom, ISerializable { - // Let's keep this exact specification of what kind of point2d we're talking - // of here, since there are so many around in the java standard api - internal double? charge; internal int? implicitHydrogenCount; internal Vector2? point2D; @@ -544,6 +561,40 @@ public class Atom internal int stereoParity; internal bool isSingleOrDouble; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(charge), charge); + info.AddNullableValue(nameof(implicitHydrogenCount), implicitHydrogenCount); + info.AddNullableValue(nameof(point2D), point2D); + info.AddNullableValue(nameof(point3D), point3D); + info.AddNullableValue(nameof(fractionalPoint3D), fractionalPoint3D); + info.AddValue(nameof(stereoParity), stereoParity); + info.AddValue(nameof(isSingleOrDouble), isSingleOrDouble); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected Atom(SerializationInfo info, StreamingContext context) + : base(info, context) + { + charge = info.GetNullable(nameof(charge)); + implicitHydrogenCount = info.GetNullable(nameof(implicitHydrogenCount)); + + covalentRadius = info.GetNullable(nameof(covalentRadius)); + hybridization = (Hybridization)info.GetInt32(nameof(hybridization)); + valency = info.GetNullable(nameof(valency)); + formalNeighbourCount = info.GetNullable(nameof(formalNeighbourCount)); + atomTypeName = info.GetString(nameof(atomTypeName)); + isHydrogenBondAcceptor = info.GetBoolean(nameof(isHydrogenBondAcceptor)); + isHydrogenBondDonor = info.GetBoolean(nameof(isHydrogenBondDonor)); + isAliphatic = info.GetBoolean(nameof(isAliphatic)); + isAromatic = info.GetBoolean(nameof(isAromatic)); + isInRing = info.GetBoolean(nameof(isInRing)); + isReactiveCenter = info.GetBoolean(nameof(isReactiveCenter)); + } + + /// /// Constructs an completely unset Atom. /// @@ -586,8 +637,8 @@ public Atom(int elem, int hcnt, int fchg) : base((string)null) /// Constructs an Atom from a string containing an element symbol and optionally /// the atomic mass, hydrogen count, and formal charge. /// - /// - /// The symbol grammar allows + /// + /// The symbol grammar allows /// easy construction from common symbols, for example: /// /// @@ -603,7 +654,7 @@ public Atom(int elem, int hcnt, int fchg) : base((string)null) /// hcnt := 'H' \d+ /// fchg := '+' \d+? | '-' \d+? /// - /// + /// /// string with the element symbol public Atom(string symbol) : base((string)null) { @@ -660,24 +711,24 @@ public Atom(IElement element) } } - /// - public virtual IAtomContainer Container => null; + /// + public virtual IAtomContainer Container => null; - /// - public virtual int Index => -1; + /// + public virtual int Index => -1; - /// - public virtual IReadOnlyList Bonds - { - get { throw new NotSupportedException(); } - } + /// + public virtual IReadOnlyList Bonds + { + get { throw new NotSupportedException(); } + } - /// - public IBond GetBond(IAtom atom) - { - throw new InvalidOperationException(); - } - + /// + public IBond GetBond(IAtom atom) + { + throw new InvalidOperationException(); + } + /// /// The partial charge of this atom. /// @@ -763,9 +814,8 @@ public bool IsSingleOrDouble /// public override bool Compare(object obj) { - var aa = obj as IAtom; - // XXX: floating point comparision! - return aa != null && base.Compare(obj) + // XXX: floating point comparision! + return obj is IAtom aa && base.Compare(obj) && Point2D == aa.Point2D && Point3D == aa.Point3D && ImplicitHydrogenCount == aa.ImplicitHydrogenCount @@ -824,7 +874,7 @@ private static bool IsDigit(char c) private static bool ParseAtomSymbol(IAtom atom, string str) { - ChemicalElement elem; + ChemicalElement elem; int len = str.Length; int pos = 0; @@ -834,48 +884,36 @@ private static bool ParseAtomSymbol(IAtom atom, string str) int hcnt = 0; int chg = 0; + // optional mass + if (pos < len && IsDigit(str[pos])) { - elem = ChemicalElement.OfString(str); - if (elem != ChemicalElements.Unknown) - { - atom.AtomicNumber = elem.AtomicNumber; - atom.Symbol = elem.Symbol; - return true; - } - else if ("R".Equals(str)) - { - atom.AtomicNumber = 0; - atom.Symbol = "R"; - return true; - } - else if ("*".Equals(str)) - { - atom.AtomicNumber = 0; - atom.Symbol = "*"; - return true; - } - else if ("D".Equals(str)) - { - atom.AtomicNumber = 1; - atom.MassNumber = 2; - atom.Symbol = "H"; - return true; - } - else if ("T".Equals(str)) + mass = (str[pos++] - '0'); + while (pos < len && IsDigit(str[pos])) + mass = 10 * mass + (str[pos++] - '0'); + } + else + { + switch (str) { - atom.AtomicNumber = 1; - atom.MassNumber = 3; - atom.Symbol = "H"; - return true; + case "R": + atom.AtomicNumber = 0; + atom.Symbol = "R"; + return true; + case "*": + atom.AtomicNumber = 0; + atom.Symbol = "*"; + return true; + case "D": + atom.AtomicNumber = 1; + atom.MassNumber = 2; + atom.Symbol = "H"; + return true; + case "T": + atom.AtomicNumber = 1; + atom.MassNumber = 3; + atom.Symbol = "H"; + return true; } - - // optional mass - if (pos < len && IsDigit(str[pos])) - { - mass = (str[pos++] - '0'); - while (pos < len && IsDigit(str[pos])) - mass = 10 * mass + (str[pos++] - '0'); - } } // atom symbol @@ -956,18 +994,18 @@ private static bool ParseAtomSymbol(IAtom atom, string str) return pos == len && len > 0; } - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } - /// - public override bool Equals(object obj) - { - if (obj is AtomRef) - return base.Equals(((AtomRef) obj).Deref()); - return base.Equals(obj); - } + /// + public override bool Equals(object other) + { + if (other is AtomRef) + return base.Equals(((AtomRef)other).Deref()); + return base.Equals(other); + } } } diff --git a/NCDK/TT/AtomContainer.tt b/NCDK/TT/AtomContainer.tt index 5fa61c44..206b371f 100644 --- a/NCDK/TT/AtomContainer.tt +++ b/NCDK/TT/AtomContainer.tt @@ -29,6 +29,8 @@ using System.Linq; using NCDK.Sgroups; using NCDK.Tools.Manipulator; +#pragma warning disable CA1710 // Identifiers should have correct suffix + <# foreach (var ns in namespaces) { @@ -36,15 +38,14 @@ foreach (var ns in namespaces) namespace <#= ns.NS #> { /// - /// Base class for all chemical objects that maintain a list of Atoms and - /// ElectronContainers. + /// Base class for all chemical objects that maintain a list of s and s. /// /// /// Looping over all Bonds in the AtomContainer is typically done like: /// /// foreach (IBond aBond in atomContainer.Bonds) /// { - /// // do something + /// // do something /// } /// /// @@ -55,10 +56,38 @@ namespace <#= ns.NS #> public partial class AtomContainer : ChemObject, IAtomContainer, IChemObjectListener { - private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(true); + private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(true); + + /// + /// Atoms contained by this object. + /// + internal ObservableChemObjectCollection_IAtom atoms; + + /// + /// Bonds contained by this object. + /// + internal ObservableChemObjectCollection bonds; + + /// + /// Lone pairs contained by this object. + /// + internal ObservableChemObjectCollection lonePairs; + + /// + /// Single electrons contained by this object. + /// + internal ObservableChemObjectCollection singleElectrons; + + /// + /// Stereo elements contained by this object. + /// + internal List> stereoElements; - /// - public override IChemObjectBuilder Builder => builder; + internal bool isAromatic; + internal bool isSingleOrDouble; + + /// + public override IChemObjectBuilder Builder => builder; internal class ObservableChemObjectCollection_IAtom : ObservableChemObjectCollection @@ -69,26 +98,27 @@ namespace <#= ns.NS #> : base(parent, atoms) { this.parent = parent; - AllowDuplicate = false; + AllowDuplicate = false; } public override IAtom this[int index] { get => base[index]; + set { if (index >= base.Count) - throw new IndexOutOfRangeException("No atom at index: " + index); + throw new ArgumentOutOfRangeException($"No atom at index:{index}"); int aidx = base.IndexOf(value); if (aidx >= 0) - throw new ArgumentException("Atom already in container at index: " + index, nameof(value)); + throw new InvalidOperationException($"Atom already in container at index: {index}"); IAtom oldAtom = base[index]; base[index] = value; - <# if (!ns.IsSilent) { #> + <# if (!ns.IsSilent) { #> value.Listeners.Add(parent); oldAtom.Listeners.Remove(parent); - <# } #> + <# } #> // replace in electron containers foreach (var bond in parent.bonds) @@ -114,8 +144,8 @@ namespace <#= ns.NS #> // update stereo CDKObjectMap map = null; - List> oldStereo = null; - List> newStereo = null; + List> oldStereo = null; + List> newStereo = null; foreach (var se in parent.stereoElements) { @@ -123,15 +153,15 @@ namespace <#= ns.NS #> { if (oldStereo == null) { - oldStereo = new List>(); - newStereo = new List>(); + oldStereo = new List>(); + newStereo = new List>(); map = new CDKObjectMap(); foreach (var a in list) map.Add(a, a); map.Set(oldAtom, value); } oldStereo.Add(se); - newStereo.Add((IReadOnlyStereoElement)se.Clone(map)); + newStereo.Add((IStereoElement)se.Clone(map)); } } if (oldStereo != null) @@ -142,47 +172,19 @@ namespace <#= ns.NS #> parent.stereoElements.Add(stereo); } - <# if (!ns.IsSilent) { #> + <# if (!ns.IsSilent) { #> parent.NotifyChanged(); - <# } #> + <# } #> } } } - /// - /// Atoms contained by this object. - /// - internal ObservableChemObjectCollection_IAtom atoms; - - /// - /// Bonds contained by this object. - /// - internal ObservableChemObjectCollection bonds; - - /// - /// Lone pairs contained by this object. - /// - internal ObservableChemObjectCollection lonePairs; - - /// - /// Single electrons contained by this object. - /// - internal ObservableChemObjectCollection singleElectrons; - - /// - /// Stereo elements contained by this object. - /// - internal List> stereoElements; - - internal bool isAromatic; - internal bool isSingleOrDouble; - private void Init( ObservableChemObjectCollection_IAtom atoms, ObservableChemObjectCollection bonds, ObservableChemObjectCollection lonePairs, ObservableChemObjectCollection singleElectrons, - List> stereoElements) + List> stereoElements) { this.atoms = atoms; this.bonds = bonds; @@ -196,14 +198,14 @@ namespace <#= ns.NS #> IEnumerable bonds, IEnumerable lonePairs, IEnumerable singleElectrons, - IEnumerable> stereoElements) + IEnumerable> stereoElements) { Init( new ObservableChemObjectCollection_IAtom(this, atoms ?? Array.Empty()), CreateObservableChemObjectCollection(bonds ?? Array.Empty(), true), CreateObservableChemObjectCollection(lonePairs ?? Array.Empty(), true), CreateObservableChemObjectCollection(singleElectrons ?? Array.Empty(), true), - new List>(stereoElements ?? Array.Empty>()) + new List>(stereoElements ?? Array.Empty>()) ); } @@ -227,7 +229,7 @@ var thisListener = ns.IsSilent ? "null" : "this"; bonds, Array.Empty(), Array.Empty(), - Array.Empty>()) + Array.Empty>()) { } /// @@ -239,7 +241,7 @@ var thisListener = ns.IsSilent ? "null" : "this"; Array.Empty(), Array.Empty(), Array.Empty(), - Array.Empty>()) + Array.Empty>()) { } /// @@ -296,7 +298,7 @@ var thisListener = ns.IsSilent ? "null" : "this"; public virtual IList SingleElectrons => singleElectrons; /// - public virtual ICollection> StereoElements => stereoElements; + public virtual ICollection> StereoElements => stereoElements; /// /// Returns the bond that connects the two given atoms. @@ -369,59 +371,59 @@ var thisListener = ns.IsSilent ? "null" : "this"; /// public virtual BondOrder GetMaximumBondOrder(IAtom atom) { - BondOrder max = BondOrder.Unset; - foreach (IBond bond in Bonds) - { - if (!bond.Contains(atom)) - continue; - if (max == BondOrder.Unset || bond.Order.Numeric() > max.Numeric()) - { - max = bond.Order; - } - } - if (max == BondOrder.Unset) - { - if (!Contains(atom)) - throw new NoSuchAtomException("Atom does not belong to this container!"); - if (atom.ImplicitHydrogenCount != null && - atom.ImplicitHydrogenCount > 0) - max = BondOrder.Single; - else - max = BondOrder.Unset; - } - return max; + BondOrder max = BondOrder.Unset; + foreach (IBond bond in Bonds) + { + if (!bond.Contains(atom)) + continue; + if (max == BondOrder.Unset || bond.Order.Numeric() > max.Numeric()) + { + max = bond.Order; + } + } + if (max == BondOrder.Unset) + { + if (!Contains(atom)) + throw new NoSuchAtomException("Atom does not belong to this container!"); + if (atom.ImplicitHydrogenCount != null && + atom.ImplicitHydrogenCount > 0) + max = BondOrder.Single; + else + max = BondOrder.Unset; + } + return max; } /// public virtual BondOrder GetMinimumBondOrder(IAtom atom) { - BondOrder min = BondOrder.Unset; - foreach (IBond bond in Bonds) - { - if (!bond.Contains(atom)) - continue; - if (min == BondOrder.Unset || bond.Order.Numeric() < min.Numeric()) - { - min = bond.Order; - } - } - if (min == BondOrder.Unset) - { - if (!Contains(atom)) - throw new NoSuchAtomException("Atom does not belong to this container!"); - if (atom.ImplicitHydrogenCount != null && - atom.ImplicitHydrogenCount > 0) - min = BondOrder.Single; - else - min = BondOrder.Unset; - } - return min; + BondOrder min = BondOrder.Unset; + foreach (IBond bond in Bonds) + { + if (!bond.Contains(atom)) + continue; + if (min == BondOrder.Unset || bond.Order.Numeric() < min.Numeric()) + { + min = bond.Order; + } + } + if (min == BondOrder.Unset) + { + if (!Contains(atom)) + throw new NoSuchAtomException("Atom does not belong to this container!"); + if (atom.ImplicitHydrogenCount != null && + atom.ImplicitHydrogenCount > 0) + min = BondOrder.Single; + else + min = BondOrder.Unset; + } + return min; } /// public virtual void Add(IAtomContainer that) { - foreach (IAtom atom in that.Atoms) + foreach (IAtom atom in that.Atoms) atom.IsVisited = false; foreach (IBond bond in that.Bonds) bond.IsVisited = false; @@ -498,15 +500,15 @@ var thisListener = ns.IsSilent ? "null" : "this"; } /// - [Obsolete] + [Obsolete("Use " + nameof(RemoveAtom))] public virtual void RemoveAtomAndConnectedElectronContainers(IAtom atom) { - RemoveAtom(atom); - } + RemoveAtom(atom); + } - /// + /// public virtual void RemoveAtom(IAtom atom) - { + { { var toRemove = bonds.Where(bond => bond.Contains(atom)).ToList(); foreach (var bond in toRemove) @@ -533,11 +535,11 @@ var thisListener = ns.IsSilent ? "null" : "this"; <# if (!ns.IsSilent) { #> NotifyChanged(); <# } #> } - /// - public virtual void RemoveAtom(int pos) - { - RemoveAtom(Atoms[pos]); - } + /// + public virtual void RemoveAtom(int pos) + { + RemoveAtom(Atoms[pos]); + } /// public virtual void RemoveAllElements() @@ -631,7 +633,7 @@ var thisListener = ns.IsSilent ? "null" : "this"; return sb.ToString(); } - private void Append(StringBuilder sb, ICollection os, string tag) + private static void Append(StringBuilder sb, ICollection os, string tag) { if (os.Count > 0) { @@ -649,14 +651,13 @@ var thisListener = ns.IsSilent ? "null" : "this"; clone.bonds = CreateObservableChemObjectCollection(bonds.Where(n => n != null).Select(n => (IBond)n.Clone(map)), true); clone.lonePairs = CreateObservableChemObjectCollection(lonePairs.Where(n => n != null).Select(n => (ILonePair)n.Clone(map)), true); clone.singleElectrons = CreateObservableChemObjectCollection(singleElectrons.Where(n => n != null).Select(n => (ISingleElectron)n.Clone(map)), true); - clone.stereoElements = new List>(stereoElements.Select(n => (IReadOnlyStereoElement)n.Clone(map))); + clone.stereoElements = new List>(stereoElements.Select(n => (IStereoElement)n.Clone(map))); // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, map)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, map)); } return clone; @@ -678,14 +679,14 @@ var thisListener = ns.IsSilent ? "null" : "this"; public void SetAtoms(IEnumerable atoms) { this.atoms.Clear(); - this.atoms.AddRange(atoms); + this.atoms.AddRange(atoms); } /// public void SetBonds(IEnumerable bonds) { this.bonds.Clear(); - this.bonds.AddRange(bonds); + this.bonds.AddRange(bonds); } /// @@ -693,10 +694,10 @@ var thisListener = ns.IsSilent ? "null" : "this"; /// public virtual string Title - { - get { return GetProperty(CDKPropertyName.Title); } - set { SetProperty(CDKPropertyName.Title, value); } - } + { + get { return GetProperty(CDKPropertyName.Title); } + set { SetProperty(CDKPropertyName.Title, value); } + } } } <# diff --git a/NCDK/TT/AtomContainer.tt.cs b/NCDK/TT/AtomContainer.tt.cs index 1ffdd9d6..51a5c187 100644 --- a/NCDK/TT/AtomContainer.tt.cs +++ b/NCDK/TT/AtomContainer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -30,18 +31,19 @@ using NCDK.Sgroups; using NCDK.Tools.Manipulator; +#pragma warning disable CA1710 // Identifiers should have correct suffix + namespace NCDK.Default { /// - /// Base class for all chemical objects that maintain a list of Atoms and - /// ElectronContainers. + /// Base class for all chemical objects that maintain a list of s and s. /// /// /// Looping over all Bonds in the AtomContainer is typically done like: /// /// foreach (IBond aBond in atomContainer.Bonds) /// { - /// // do something + /// // do something /// } /// /// @@ -52,10 +54,38 @@ namespace NCDK.Default public partial class AtomContainer : ChemObject, IAtomContainer, IChemObjectListener { - private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(true); + private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(true); + + /// + /// Atoms contained by this object. + /// + internal ObservableChemObjectCollection_IAtom atoms; + + /// + /// Bonds contained by this object. + /// + internal ObservableChemObjectCollection bonds; + + /// + /// Lone pairs contained by this object. + /// + internal ObservableChemObjectCollection lonePairs; + + /// + /// Single electrons contained by this object. + /// + internal ObservableChemObjectCollection singleElectrons; + + /// + /// Stereo elements contained by this object. + /// + internal List> stereoElements; - /// - public override IChemObjectBuilder Builder => builder; + internal bool isAromatic; + internal bool isSingleOrDouble; + + /// + public override IChemObjectBuilder Builder => builder; internal class ObservableChemObjectCollection_IAtom : ObservableChemObjectCollection @@ -66,26 +96,27 @@ public ObservableChemObjectCollection_IAtom(AtomContainer parent, IEnumerable base[index]; + set { if (index >= base.Count) - throw new IndexOutOfRangeException("No atom at index: " + index); + throw new ArgumentOutOfRangeException($"No atom at index:{index}"); int aidx = base.IndexOf(value); if (aidx >= 0) - throw new ArgumentException("Atom already in container at index: " + index, nameof(value)); + throw new InvalidOperationException($"Atom already in container at index: {index}"); IAtom oldAtom = base[index]; base[index] = value; - + value.Listeners.Add(parent); oldAtom.Listeners.Remove(parent); - + // replace in electron containers foreach (var bond in parent.bonds) @@ -111,8 +142,8 @@ public override IAtom this[int index] // update stereo CDKObjectMap map = null; - List> oldStereo = null; - List> newStereo = null; + List> oldStereo = null; + List> newStereo = null; foreach (var se in parent.stereoElements) { @@ -120,15 +151,15 @@ public override IAtom this[int index] { if (oldStereo == null) { - oldStereo = new List>(); - newStereo = new List>(); + oldStereo = new List>(); + newStereo = new List>(); map = new CDKObjectMap(); foreach (var a in list) map.Add(a, a); map.Set(oldAtom, value); } oldStereo.Add(se); - newStereo.Add((IReadOnlyStereoElement)se.Clone(map)); + newStereo.Add((IStereoElement)se.Clone(map)); } } if (oldStereo != null) @@ -139,47 +170,19 @@ public override IAtom this[int index] parent.stereoElements.Add(stereo); } - + parent.NotifyChanged(); - + } } } - /// - /// Atoms contained by this object. - /// - internal ObservableChemObjectCollection_IAtom atoms; - - /// - /// Bonds contained by this object. - /// - internal ObservableChemObjectCollection bonds; - - /// - /// Lone pairs contained by this object. - /// - internal ObservableChemObjectCollection lonePairs; - - /// - /// Single electrons contained by this object. - /// - internal ObservableChemObjectCollection singleElectrons; - - /// - /// Stereo elements contained by this object. - /// - internal List> stereoElements; - - internal bool isAromatic; - internal bool isSingleOrDouble; - private void Init( ObservableChemObjectCollection_IAtom atoms, ObservableChemObjectCollection bonds, ObservableChemObjectCollection lonePairs, ObservableChemObjectCollection singleElectrons, - List> stereoElements) + List> stereoElements) { this.atoms = atoms; this.bonds = bonds; @@ -193,14 +196,14 @@ public AtomContainer( IEnumerable bonds, IEnumerable lonePairs, IEnumerable singleElectrons, - IEnumerable> stereoElements) + IEnumerable> stereoElements) { Init( new ObservableChemObjectCollection_IAtom(this, atoms ?? Array.Empty()), CreateObservableChemObjectCollection(bonds ?? Array.Empty(), true), CreateObservableChemObjectCollection(lonePairs ?? Array.Empty(), true), CreateObservableChemObjectCollection(singleElectrons ?? Array.Empty(), true), - new List>(stereoElements ?? Array.Empty>()) + new List>(stereoElements ?? Array.Empty>()) ); } @@ -222,7 +225,7 @@ public AtomContainer( bonds, Array.Empty(), Array.Empty(), - Array.Empty>()) + Array.Empty>()) { } /// @@ -234,7 +237,7 @@ public AtomContainer() Array.Empty(), Array.Empty(), Array.Empty(), - Array.Empty>()) + Array.Empty>()) { } /// @@ -287,7 +290,7 @@ public virtual bool IsSingleOrDouble public virtual IList SingleElectrons => singleElectrons; /// - public virtual ICollection> StereoElements => stereoElements; + public virtual ICollection> StereoElements => stereoElements; /// /// Returns the bond that connects the two given atoms. @@ -360,59 +363,59 @@ public virtual double GetBondOrderSum(IAtom atom) /// public virtual BondOrder GetMaximumBondOrder(IAtom atom) { - BondOrder max = BondOrder.Unset; - foreach (IBond bond in Bonds) - { - if (!bond.Contains(atom)) - continue; - if (max == BondOrder.Unset || bond.Order.Numeric() > max.Numeric()) - { - max = bond.Order; - } - } - if (max == BondOrder.Unset) - { - if (!Contains(atom)) - throw new NoSuchAtomException("Atom does not belong to this container!"); - if (atom.ImplicitHydrogenCount != null && - atom.ImplicitHydrogenCount > 0) - max = BondOrder.Single; - else - max = BondOrder.Unset; - } - return max; + BondOrder max = BondOrder.Unset; + foreach (IBond bond in Bonds) + { + if (!bond.Contains(atom)) + continue; + if (max == BondOrder.Unset || bond.Order.Numeric() > max.Numeric()) + { + max = bond.Order; + } + } + if (max == BondOrder.Unset) + { + if (!Contains(atom)) + throw new NoSuchAtomException("Atom does not belong to this container!"); + if (atom.ImplicitHydrogenCount != null && + atom.ImplicitHydrogenCount > 0) + max = BondOrder.Single; + else + max = BondOrder.Unset; + } + return max; } /// public virtual BondOrder GetMinimumBondOrder(IAtom atom) { - BondOrder min = BondOrder.Unset; - foreach (IBond bond in Bonds) - { - if (!bond.Contains(atom)) - continue; - if (min == BondOrder.Unset || bond.Order.Numeric() < min.Numeric()) - { - min = bond.Order; - } - } - if (min == BondOrder.Unset) - { - if (!Contains(atom)) - throw new NoSuchAtomException("Atom does not belong to this container!"); - if (atom.ImplicitHydrogenCount != null && - atom.ImplicitHydrogenCount > 0) - min = BondOrder.Single; - else - min = BondOrder.Unset; - } - return min; + BondOrder min = BondOrder.Unset; + foreach (IBond bond in Bonds) + { + if (!bond.Contains(atom)) + continue; + if (min == BondOrder.Unset || bond.Order.Numeric() < min.Numeric()) + { + min = bond.Order; + } + } + if (min == BondOrder.Unset) + { + if (!Contains(atom)) + throw new NoSuchAtomException("Atom does not belong to this container!"); + if (atom.ImplicitHydrogenCount != null && + atom.ImplicitHydrogenCount > 0) + min = BondOrder.Single; + else + min = BondOrder.Unset; + } + return min; } /// public virtual void Add(IAtomContainer that) { - foreach (IAtom atom in that.Atoms) + foreach (IAtom atom in that.Atoms) atom.IsVisited = false; foreach (IBond bond in that.Bonds) bond.IsVisited = false; @@ -488,15 +491,15 @@ public virtual void Remove(IElectronContainer electronContainer) } /// - [Obsolete] + [Obsolete("Use " + nameof(RemoveAtom))] public virtual void RemoveAtomAndConnectedElectronContainers(IAtom atom) { - RemoveAtom(atom); - } + RemoveAtom(atom); + } - /// + /// public virtual void RemoveAtom(IAtom atom) - { + { { var toRemove = bonds.Where(bond => bond.Contains(atom)).ToList(); foreach (var bond in toRemove) @@ -522,11 +525,11 @@ public virtual void RemoveAtom(IAtom atom) NotifyChanged(); } - /// - public virtual void RemoveAtom(int pos) - { - RemoveAtom(Atoms[pos]); - } + /// + public virtual void RemoveAtom(int pos) + { + RemoveAtom(Atoms[pos]); + } /// public virtual void RemoveAllElements() @@ -618,7 +621,7 @@ internal virtual string ToStringInner() return sb.ToString(); } - private void Append(StringBuilder sb, ICollection os, string tag) + private static void Append(StringBuilder sb, ICollection os, string tag) { if (os.Count > 0) { @@ -636,14 +639,13 @@ public override ICDKObject Clone(CDKObjectMap map) clone.bonds = CreateObservableChemObjectCollection(bonds.Where(n => n != null).Select(n => (IBond)n.Clone(map)), true); clone.lonePairs = CreateObservableChemObjectCollection(lonePairs.Where(n => n != null).Select(n => (ILonePair)n.Clone(map)), true); clone.singleElectrons = CreateObservableChemObjectCollection(singleElectrons.Where(n => n != null).Select(n => (ISingleElectron)n.Clone(map)), true); - clone.stereoElements = new List>(stereoElements.Select(n => (IReadOnlyStereoElement)n.Clone(map))); + clone.stereoElements = new List>(stereoElements.Select(n => (IStereoElement)n.Clone(map))); // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, map)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, map)); } return clone; @@ -664,14 +666,14 @@ public void OnStateChanged(ChemObjectChangeEventArgs evt) public void SetAtoms(IEnumerable atoms) { this.atoms.Clear(); - this.atoms.AddRange(atoms); + this.atoms.AddRange(atoms); } /// public void SetBonds(IEnumerable bonds) { this.bonds.Clear(); - this.bonds.AddRange(bonds); + this.bonds.AddRange(bonds); } /// @@ -679,24 +681,23 @@ public void SetBonds(IEnumerable bonds) /// public virtual string Title - { - get { return GetProperty(CDKPropertyName.Title); } - set { SetProperty(CDKPropertyName.Title, value); } - } + { + get { return GetProperty(CDKPropertyName.Title); } + set { SetProperty(CDKPropertyName.Title, value); } + } } } namespace NCDK.Silent { /// - /// Base class for all chemical objects that maintain a list of Atoms and - /// ElectronContainers. + /// Base class for all chemical objects that maintain a list of s and s. /// /// /// Looping over all Bonds in the AtomContainer is typically done like: /// /// foreach (IBond aBond in atomContainer.Bonds) /// { - /// // do something + /// // do something /// } /// /// @@ -707,10 +708,38 @@ namespace NCDK.Silent public partial class AtomContainer : ChemObject, IAtomContainer, IChemObjectListener { - private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(true); + private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(true); + + /// + /// Atoms contained by this object. + /// + internal ObservableChemObjectCollection_IAtom atoms; + + /// + /// Bonds contained by this object. + /// + internal ObservableChemObjectCollection bonds; + + /// + /// Lone pairs contained by this object. + /// + internal ObservableChemObjectCollection lonePairs; + + /// + /// Single electrons contained by this object. + /// + internal ObservableChemObjectCollection singleElectrons; + + /// + /// Stereo elements contained by this object. + /// + internal List> stereoElements; - /// - public override IChemObjectBuilder Builder => builder; + internal bool isAromatic; + internal bool isSingleOrDouble; + + /// + public override IChemObjectBuilder Builder => builder; internal class ObservableChemObjectCollection_IAtom : ObservableChemObjectCollection @@ -721,23 +750,24 @@ public ObservableChemObjectCollection_IAtom(AtomContainer parent, IEnumerable base[index]; + set { if (index >= base.Count) - throw new IndexOutOfRangeException("No atom at index: " + index); + throw new ArgumentOutOfRangeException($"No atom at index:{index}"); int aidx = base.IndexOf(value); if (aidx >= 0) - throw new ArgumentException("Atom already in container at index: " + index, nameof(value)); + throw new InvalidOperationException($"Atom already in container at index: {index}"); IAtom oldAtom = base[index]; base[index] = value; - + // replace in electron containers foreach (var bond in parent.bonds) @@ -763,8 +793,8 @@ public override IAtom this[int index] // update stereo CDKObjectMap map = null; - List> oldStereo = null; - List> newStereo = null; + List> oldStereo = null; + List> newStereo = null; foreach (var se in parent.stereoElements) { @@ -772,15 +802,15 @@ public override IAtom this[int index] { if (oldStereo == null) { - oldStereo = new List>(); - newStereo = new List>(); + oldStereo = new List>(); + newStereo = new List>(); map = new CDKObjectMap(); foreach (var a in list) map.Add(a, a); map.Set(oldAtom, value); } oldStereo.Add(se); - newStereo.Add((IReadOnlyStereoElement)se.Clone(map)); + newStereo.Add((IStereoElement)se.Clone(map)); } } if (oldStereo != null) @@ -791,45 +821,17 @@ public override IAtom this[int index] parent.stereoElements.Add(stereo); } - + } } } - /// - /// Atoms contained by this object. - /// - internal ObservableChemObjectCollection_IAtom atoms; - - /// - /// Bonds contained by this object. - /// - internal ObservableChemObjectCollection bonds; - - /// - /// Lone pairs contained by this object. - /// - internal ObservableChemObjectCollection lonePairs; - - /// - /// Single electrons contained by this object. - /// - internal ObservableChemObjectCollection singleElectrons; - - /// - /// Stereo elements contained by this object. - /// - internal List> stereoElements; - - internal bool isAromatic; - internal bool isSingleOrDouble; - private void Init( ObservableChemObjectCollection_IAtom atoms, ObservableChemObjectCollection bonds, ObservableChemObjectCollection lonePairs, ObservableChemObjectCollection singleElectrons, - List> stereoElements) + List> stereoElements) { this.atoms = atoms; this.bonds = bonds; @@ -843,14 +845,14 @@ public AtomContainer( IEnumerable bonds, IEnumerable lonePairs, IEnumerable singleElectrons, - IEnumerable> stereoElements) + IEnumerable> stereoElements) { Init( new ObservableChemObjectCollection_IAtom(this, atoms ?? Array.Empty()), CreateObservableChemObjectCollection(bonds ?? Array.Empty(), true), CreateObservableChemObjectCollection(lonePairs ?? Array.Empty(), true), CreateObservableChemObjectCollection(singleElectrons ?? Array.Empty(), true), - new List>(stereoElements ?? Array.Empty>()) + new List>(stereoElements ?? Array.Empty>()) ); } @@ -872,7 +874,7 @@ public AtomContainer( bonds, Array.Empty(), Array.Empty(), - Array.Empty>()) + Array.Empty>()) { } /// @@ -884,7 +886,7 @@ public AtomContainer() Array.Empty(), Array.Empty(), Array.Empty(), - Array.Empty>()) + Array.Empty>()) { } /// @@ -935,7 +937,7 @@ public virtual bool IsSingleOrDouble public virtual IList SingleElectrons => singleElectrons; /// - public virtual ICollection> StereoElements => stereoElements; + public virtual ICollection> StereoElements => stereoElements; /// /// Returns the bond that connects the two given atoms. @@ -1008,59 +1010,59 @@ public virtual double GetBondOrderSum(IAtom atom) /// public virtual BondOrder GetMaximumBondOrder(IAtom atom) { - BondOrder max = BondOrder.Unset; - foreach (IBond bond in Bonds) - { - if (!bond.Contains(atom)) - continue; - if (max == BondOrder.Unset || bond.Order.Numeric() > max.Numeric()) - { - max = bond.Order; - } - } - if (max == BondOrder.Unset) - { - if (!Contains(atom)) - throw new NoSuchAtomException("Atom does not belong to this container!"); - if (atom.ImplicitHydrogenCount != null && - atom.ImplicitHydrogenCount > 0) - max = BondOrder.Single; - else - max = BondOrder.Unset; - } - return max; + BondOrder max = BondOrder.Unset; + foreach (IBond bond in Bonds) + { + if (!bond.Contains(atom)) + continue; + if (max == BondOrder.Unset || bond.Order.Numeric() > max.Numeric()) + { + max = bond.Order; + } + } + if (max == BondOrder.Unset) + { + if (!Contains(atom)) + throw new NoSuchAtomException("Atom does not belong to this container!"); + if (atom.ImplicitHydrogenCount != null && + atom.ImplicitHydrogenCount > 0) + max = BondOrder.Single; + else + max = BondOrder.Unset; + } + return max; } /// public virtual BondOrder GetMinimumBondOrder(IAtom atom) { - BondOrder min = BondOrder.Unset; - foreach (IBond bond in Bonds) - { - if (!bond.Contains(atom)) - continue; - if (min == BondOrder.Unset || bond.Order.Numeric() < min.Numeric()) - { - min = bond.Order; - } - } - if (min == BondOrder.Unset) - { - if (!Contains(atom)) - throw new NoSuchAtomException("Atom does not belong to this container!"); - if (atom.ImplicitHydrogenCount != null && - atom.ImplicitHydrogenCount > 0) - min = BondOrder.Single; - else - min = BondOrder.Unset; - } - return min; + BondOrder min = BondOrder.Unset; + foreach (IBond bond in Bonds) + { + if (!bond.Contains(atom)) + continue; + if (min == BondOrder.Unset || bond.Order.Numeric() < min.Numeric()) + { + min = bond.Order; + } + } + if (min == BondOrder.Unset) + { + if (!Contains(atom)) + throw new NoSuchAtomException("Atom does not belong to this container!"); + if (atom.ImplicitHydrogenCount != null && + atom.ImplicitHydrogenCount > 0) + min = BondOrder.Single; + else + min = BondOrder.Unset; + } + return min; } /// public virtual void Add(IAtomContainer that) { - foreach (IAtom atom in that.Atoms) + foreach (IAtom atom in that.Atoms) atom.IsVisited = false; foreach (IBond bond in that.Bonds) bond.IsVisited = false; @@ -1136,15 +1138,15 @@ public virtual void Remove(IElectronContainer electronContainer) } /// - [Obsolete] + [Obsolete("Use " + nameof(RemoveAtom))] public virtual void RemoveAtomAndConnectedElectronContainers(IAtom atom) { - RemoveAtom(atom); - } + RemoveAtom(atom); + } - /// + /// public virtual void RemoveAtom(IAtom atom) - { + { { var toRemove = bonds.Where(bond => bond.Contains(atom)).ToList(); foreach (var bond in toRemove) @@ -1170,11 +1172,11 @@ public virtual void RemoveAtom(IAtom atom) } - /// - public virtual void RemoveAtom(int pos) - { - RemoveAtom(Atoms[pos]); - } + /// + public virtual void RemoveAtom(int pos) + { + RemoveAtom(Atoms[pos]); + } /// public virtual void RemoveAllElements() @@ -1266,7 +1268,7 @@ internal virtual string ToStringInner() return sb.ToString(); } - private void Append(StringBuilder sb, ICollection os, string tag) + private static void Append(StringBuilder sb, ICollection os, string tag) { if (os.Count > 0) { @@ -1284,14 +1286,13 @@ public override ICDKObject Clone(CDKObjectMap map) clone.bonds = CreateObservableChemObjectCollection(bonds.Where(n => n != null).Select(n => (IBond)n.Clone(map)), true); clone.lonePairs = CreateObservableChemObjectCollection(lonePairs.Where(n => n != null).Select(n => (ILonePair)n.Clone(map)), true); clone.singleElectrons = CreateObservableChemObjectCollection(singleElectrons.Where(n => n != null).Select(n => (ISingleElectron)n.Clone(map)), true); - clone.stereoElements = new List>(stereoElements.Select(n => (IReadOnlyStereoElement)n.Clone(map))); + clone.stereoElements = new List>(stereoElements.Select(n => (IStereoElement)n.Clone(map))); // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, map)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, map)); } return clone; @@ -1312,14 +1313,14 @@ public void OnStateChanged(ChemObjectChangeEventArgs evt) public void SetAtoms(IEnumerable atoms) { this.atoms.Clear(); - this.atoms.AddRange(atoms); + this.atoms.AddRange(atoms); } /// public void SetBonds(IEnumerable bonds) { this.bonds.Clear(); - this.bonds.AddRange(bonds); + this.bonds.AddRange(bonds); } /// @@ -1327,9 +1328,9 @@ public void SetBonds(IEnumerable bonds) /// public virtual string Title - { - get { return GetProperty(CDKPropertyName.Title); } - set { SetProperty(CDKPropertyName.Title, value); } - } + { + get { return GetProperty(CDKPropertyName.Title); } + set { SetProperty(CDKPropertyName.Title, value); } + } } } diff --git a/NCDK/TT/AtomContainer2.tt b/NCDK/TT/AtomContainer2.tt index d601eb32..996d13c4 100644 --- a/NCDK/TT/AtomContainer2.tt +++ b/NCDK/TT/AtomContainer2.tt @@ -37,6 +37,8 @@ using System.Diagnostics; using System.Linq; using System.Text; +#pragma warning disable CA1710 // Identifiers should have correct suffix + <# foreach (var ns in namespaces) { @@ -49,18 +51,16 @@ namespace <#= ns.NS #> // @author John Mayfield internal sealed class AtomContainer2 : ChemObject, IAtomContainer { - private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(false); - - /// - public override IChemObjectBuilder Builder => builder; + private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(false); - private const int DEFAULT_CAPACITY = 20; + /// + public override IChemObjectBuilder Builder => builder; internal List atoms; internal List bonds; internal ObservableChemObjectCollection lonepairs; internal ObservableChemObjectCollection electrons; - internal List> stereo; + internal List> stereo; internal bool isAromatic; internal bool isSingleOrDouble; @@ -72,7 +72,7 @@ namespace <#= ns.NS #> public IList LonePairs { get; private set; } public IList SingleElectrons { get; private set; } // TODO: handle notification - public ICollection> StereoElements { get; private set; } + public ICollection> StereoElements { get; private set; } /// /// Create a new container with the specified capacities. @@ -90,7 +90,7 @@ namespace <#= ns.NS #> this.bonds = new List(numBonds); this.lonepairs = new ObservableChemObjectCollection(numLonePairs, this); this.electrons = new ObservableChemObjectCollection(numSingleElectrons, this); - this.stereo = new List>(); + this.stereo = new List>(); this.Atoms = new BaseAtomRef_Collection(this); this.Bonds = new BaseBondRef_Collection(this); @@ -243,18 +243,18 @@ namespace <#= ns.NS #> internal BaseAtomRef GetBegin() => beg; internal BaseAtomRef GetEnd() => end; - private IList internalAtoms; + private IList internalAtoms; - /// - public override IList Atoms - { - get - { - if (internalAtoms == null) - internalAtoms = new InternalAtoms(this, base.Atoms); - return internalAtoms; - } - } + /// + public override IList Atoms + { + get + { + if (internalAtoms == null) + internalAtoms = new InternalAtoms(this, base.Atoms); + return internalAtoms; + } + } internal class InternalAtoms : IList { @@ -473,13 +473,13 @@ namespace <#= ns.NS #> public int Count => list.Count; public bool IsReadOnly => false; public abstract void Add(TInterface item); - public abstract void Clear(); + public abstract void Clear(); public bool Contains(TInterface item) => list.Contains((TRef)item); public void CopyTo(TInterface[] array, int arrayIndex) { for (int i = 0; i < list.Count; i++) array[arrayIndex + i] = list[i]; - } + } public IEnumerator GetEnumerator() => list.Cast().GetEnumerator(); public abstract int IndexOf(TInterface atom); public void Insert(int index, TInterface item) @@ -487,7 +487,7 @@ namespace <#= ns.NS #> list.Insert(index, default(TRef)); this[index] = item; } - public abstract bool Remove(TInterface item); + public abstract bool Remove(TInterface item); public abstract void RemoveAt(int index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } @@ -507,7 +507,7 @@ namespace <#= ns.NS #> get { if (index >= this.parent.atoms.Count) - throw new ArgumentOutOfRangeException("No atom at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), $"No atom at index: {index}"); return parent.atoms[index]; } @@ -517,9 +517,9 @@ namespace <#= ns.NS #> if (atom == null) throw new NullReferenceException("Null atom provided"); if (parent.atoms.Contains(atom)) - throw new ArgumentException(nameof(value), "Atom already in container at index: " + this.IndexOf(atom)); + throw new InvalidOperationException($"Atom already in container at index: {this.IndexOf(atom)}"); if (index < 0 || index >= parent.atoms.Count) - throw new IndexOutOfRangeException("No current atom at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), $"No current atom at index: {index}"); BaseAtomRef rep = parent.NewAtomRef(atom); BaseAtomRef org = parent.atoms[index]; parent.atoms[index] = rep; @@ -552,7 +552,7 @@ namespace <#= ns.NS #> { var map = new CDKObjectMap(); map.Add(org, rep); - parent.stereo[i] = (IReadOnlyStereoElement)se.Clone(map); + parent.stereo[i] = (IStereoElement)se.Clone(map); } } <# if (!ns.IsSilent) { #> @@ -587,7 +587,7 @@ namespace <#= ns.NS #> <# if (!ns.IsSilent) { #> parent.atoms[index].Listeners.Remove(parent); <# } #> - parent.atoms[index].SetIndex(-1); + parent.atoms[index].SetIndex(-1); for (int i = index; i < parent.atoms.Count - 1; i++) { parent.atoms[i] = parent.atoms[i + 1]; @@ -610,17 +610,17 @@ namespace <#= ns.NS #> return false; } - public override void Clear() - { + public override void Clear() + { <# if (!ns.IsSilent) { #> foreach (var item in parent.atoms) item.Listeners.Remove(parent); <# } #> parent.atoms.Clear(); <# if (!ns.IsSilent) { #> - parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); + parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); <# } #> - } + } } internal class BaseBondRef_Collection : A_Collection @@ -638,7 +638,7 @@ namespace <#= ns.NS #> get { if (index >= parent.bonds.Count) - throw new ArgumentOutOfRangeException("No bond at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), "No bond at index: " + index); return parent.bonds[index]; } @@ -662,7 +662,7 @@ namespace <#= ns.NS #> parent.bonds.Add(bref); bref.Listeners.Add(parent); <# if (!ns.IsSilent) { #> - parent.NotifyChanged(); + parent.NotifyChanged(); <# } #> } @@ -670,7 +670,7 @@ namespace <#= ns.NS #> { BondRef bond = null; bond = parent.bonds[index]; - parent.bonds[index].SetIndex(-1); + parent.bonds[index].SetIndex(-1); for (int i = index; i < parent.bonds.Count - 1; i++) { parent.bonds[i] = parent.bonds[i + 1]; @@ -680,7 +680,7 @@ namespace <#= ns.NS #> parent.DelFromEndpoints(bond); <# if (!ns.IsSilent) { #> bond.Listeners.Remove(parent); - parent.NotifyChanged(); + parent.NotifyChanged(); <# } #> } @@ -695,19 +695,19 @@ namespace <#= ns.NS #> return false; } - public override void Clear() - { + public override void Clear() + { <# if (!ns.IsSilent) { #> foreach (var item in parent.bonds) item.Listeners.Remove(parent); <# } #> parent.bonds.Clear(); - parent.ClearAdjacency(); + parent.ClearAdjacency(); <# if (!ns.IsSilent) { #> - parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); + parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); <# } #> - } - } + } + } internal static IAtom Unbox(IAtom atom) { @@ -726,7 +726,7 @@ namespace <#= ns.NS #> internal BaseAtomRef GetAtomRefUnsafe(IAtom atom) { if (atom.Container == this && - atom.Index != -1 && + atom.Index != -1 && atoms[atom.Index] == atom) return (BaseAtomRef)atom; atom = Unbox(atom); @@ -776,7 +776,7 @@ namespace <#= ns.NS #> private BondRef GetBondRefUnsafe(IBond bond) { if (bond.Container == this && - bond.Index != -1 && + bond.Index != -1 && bonds[bond.Index] == bond) return (BondRef)bond; bond = Unbox(bond); @@ -842,7 +842,7 @@ namespace <#= ns.NS #> for (int i = 0; i < newatoms.Count; i++) { - if (i >= atoms.Count) + if (i >= atoms.Count) atoms.Add(null); if (newatoms[i].Container == this) @@ -853,8 +853,8 @@ namespace <#= ns.NS #> else { <# if (!ns.IsSilent) { #> - if (atoms[i] != null) - atoms[i].Listeners.Remove(this); + if (atoms[i] != null) + atoms[i].Listeners.Remove(this); <# } #> atoms[i] = NewAtomRef(newatoms[i]); atoms[i].SetIndex(i); @@ -865,16 +865,16 @@ namespace <#= ns.NS #> } } - // delete rest of the array - { - for (int i = atoms.Count - 1; i >= newatoms.Count; i--) - { + // delete rest of the array + { + for (int i = atoms.Count - 1; i >= newatoms.Count; i--) + { <# if (!ns.IsSilent) { #> - atoms[i].Listeners.Remove(this); + atoms[i].Listeners.Remove(this); <# } #> - atoms.RemoveAt(i); - } - } + atoms.RemoveAt(i); + } + } // ensure adjacency information is in sync, this code is only // called if the bonds are non-empty and 'external' atoms have been @@ -887,7 +887,7 @@ namespace <#= ns.NS #> } <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -895,34 +895,34 @@ namespace <#= ns.NS #> { var newbonds = newbonds_.ToList(); - // replace existing bonds to clear their adjacency - if (bonds.Count > 0) - { - ClearAdjacency(); - } + // replace existing bonds to clear their adjacency + if (bonds.Count > 0) + { + ClearAdjacency(); + } - for (int i = 0; i < newbonds.Count; i++) - { - if (i >= bonds.Count) + for (int i = 0; i < newbonds.Count; i++) + { + if (i >= bonds.Count) bonds.Add(null); - BaseBondRef bondRef = NewBondRef(newbonds[i]); - bondRef.SetIndex(i); - AddToEndpoints(bondRef); + BaseBondRef bondRef = NewBondRef(newbonds[i]); + bondRef.SetIndex(i); + AddToEndpoints(bondRef); <# if (!ns.IsSilent) { #> - if (bonds[i] != null) - bonds[i].Listeners.Remove(this); + if (bonds[i] != null) + bonds[i].Listeners.Remove(this); <# } #> - bonds[i] = bondRef; + bonds[i] = bondRef; <# if (!ns.IsSilent) { #> - bondRef.Listeners.Add(this); + bondRef.Listeners.Add(this); <# } #> - } - for (int i = bonds.Count - 1; i >= newbonds.Count; i--) - bonds.RemoveAt(i); + } + for (int i = bonds.Count - 1; i >= newbonds.Count; i--) + bonds.RemoveAt(i); <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -956,8 +956,8 @@ namespace <#= ns.NS #> public IBond GetBond(IAtom beg, IAtom end) { - AtomRef begref = GetAtomRefUnsafe(beg); - return begref?.GetBond(end); + AtomRef begref = GetAtomRefUnsafe(beg); + return begref?.GetBond(end); } public int GetAtomCount() @@ -1129,7 +1129,7 @@ namespace <#= ns.NS #> SingleElectrons.Add(singleElectron); <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -1153,7 +1153,7 @@ namespace <#= ns.NS #> } <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -1170,7 +1170,7 @@ namespace <#= ns.NS #> Atoms.Remove(atom); <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -1233,11 +1233,11 @@ namespace <#= ns.NS #> DelFromEndpoints(bonds[i]); } } - { - for (int j = bonds.Count - 1; j >= newNumBonds; j--) - bonds.RemoveAt(j); - } - } + { + for (int j = bonds.Count - 1; j >= newNumBonds; j--) + bonds.RemoveAt(j); + } + } // update single electrons int newNumSingleElectrons = 0; @@ -1277,7 +1277,7 @@ namespace <#= ns.NS #> lonepairs.RemoveAt(j); } - var atomElements = new List>(); + var atomElements = new List>(); foreach (var element in stereo) { if (element.Contains(atom)) atomElements.Add(element); @@ -1285,7 +1285,7 @@ namespace <#= ns.NS #> foreach (var ae in atomElements) stereo.Remove(ae); - Atoms.RemoveAt(atomref.Index); + Atoms.RemoveAt(atomref.Index); } } @@ -1304,7 +1304,7 @@ namespace <#= ns.NS #> atoms.Clear(); stereo.Clear(); <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -1321,7 +1321,7 @@ namespace <#= ns.NS #> electrons.Clear(); <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -1330,7 +1330,7 @@ namespace <#= ns.NS #> bonds.Clear(); ClearAdjacency(); <# if (!ns.IsSilent) { #> - NotifyChanged(); + NotifyChanged(); <# } #> } @@ -1394,7 +1394,7 @@ namespace <#= ns.NS #> return sb.ToString(); } - private void Append(StringBuilder sb, ICollection os, string tag) + private static void Append(StringBuilder sb, ICollection os, string tag) { if (os.Count > 0) { @@ -1407,7 +1407,7 @@ namespace <#= ns.NS #> /// public override ICDKObject Clone(CDKObjectMap map) { - CDKObjectMap refmap = new CDKObjectMap(); + CDKObjectMap refmap = new CDKObjectMap(); // this is pretty wasteful as we need to delete most the data // we can't simply create an empty instance as the sub classes (e.g. AminoAcid) @@ -1420,7 +1420,7 @@ namespace <#= ns.NS #> clone.bonds = new List(); clone.lonepairs = new ObservableChemObjectCollection(clone); clone.electrons = new ObservableChemObjectCollection(clone); - clone.stereo = new List>(); + clone.stereo = new List>(); clone.Atoms = new BaseAtomRef_Collection(clone); clone.Bonds = new BaseBondRef_Collection(clone); clone.LonePairs = clone.lonepairs; @@ -1485,15 +1485,14 @@ namespace <#= ns.NS #> // map each stereo element to a new instance in the clone foreach (var element in stereo) { - clone.StereoElements.Add((IReadOnlyStereoElement)element.Clone(refmap)); + clone.StereoElements.Add((IStereoElement)element.Clone(refmap)); } - // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + // update sgroups + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, refmap)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, refmap)); } return clone; @@ -1503,7 +1502,7 @@ namespace <#= ns.NS #> public void OnStateChanged(ChemObjectChangeEventArgs evt) { <# if (!ns.IsSilent) { #> - NotifyChanged(evt); + NotifyChanged(evt); <# } #> } diff --git a/NCDK/TT/AtomContainer2.tt.cs b/NCDK/TT/AtomContainer2.tt.cs index 3ceb3438..a1fb1c97 100644 --- a/NCDK/TT/AtomContainer2.tt.cs +++ b/NCDK/TT/AtomContainer2.tt.cs @@ -1,6 +1,7 @@  + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2017 Kazuya Ujihara @@ -38,6 +39,8 @@ using System.Linq; using System.Text; +#pragma warning disable CA1710 // Identifiers should have correct suffix + namespace NCDK.Default { /// @@ -46,18 +49,16 @@ namespace NCDK.Default // @author John Mayfield internal sealed class AtomContainer2 : ChemObject, IAtomContainer { - private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(false); + private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(false); - /// - public override IChemObjectBuilder Builder => builder; - - private const int DEFAULT_CAPACITY = 20; + /// + public override IChemObjectBuilder Builder => builder; internal List atoms; internal List bonds; internal ObservableChemObjectCollection lonepairs; internal ObservableChemObjectCollection electrons; - internal List> stereo; + internal List> stereo; internal bool isAromatic; internal bool isSingleOrDouble; @@ -69,7 +70,7 @@ internal sealed class AtomContainer2 : ChemObject, IAtomContainer public IList LonePairs { get; private set; } public IList SingleElectrons { get; private set; } // TODO: handle notification - public ICollection> StereoElements { get; private set; } + public ICollection> StereoElements { get; private set; } /// /// Create a new container with the specified capacities. @@ -87,7 +88,7 @@ public AtomContainer2(int numAtoms, this.bonds = new List(numBonds); this.lonepairs = new ObservableChemObjectCollection(numLonePairs, this); this.electrons = new ObservableChemObjectCollection(numSingleElectrons, this); - this.stereo = new List>(); + this.stereo = new List>(); this.Atoms = new BaseAtomRef_Collection(this); this.Bonds = new BaseBondRef_Collection(this); @@ -236,18 +237,18 @@ public void SetIndex(int index) internal BaseAtomRef GetBegin() => beg; internal BaseAtomRef GetEnd() => end; - private IList internalAtoms; + private IList internalAtoms; - /// - public override IList Atoms - { - get - { - if (internalAtoms == null) - internalAtoms = new InternalAtoms(this, base.Atoms); - return internalAtoms; - } - } + /// + public override IList Atoms + { + get + { + if (internalAtoms == null) + internalAtoms = new InternalAtoms(this, base.Atoms); + return internalAtoms; + } + } internal class InternalAtoms : IList { @@ -466,13 +467,13 @@ public A_Collection(List list) public int Count => list.Count; public bool IsReadOnly => false; public abstract void Add(TInterface item); - public abstract void Clear(); + public abstract void Clear(); public bool Contains(TInterface item) => list.Contains((TRef)item); public void CopyTo(TInterface[] array, int arrayIndex) { for (int i = 0; i < list.Count; i++) array[arrayIndex + i] = list[i]; - } + } public IEnumerator GetEnumerator() => list.Cast().GetEnumerator(); public abstract int IndexOf(TInterface atom); public void Insert(int index, TInterface item) @@ -480,7 +481,7 @@ public void Insert(int index, TInterface item) list.Insert(index, default(TRef)); this[index] = item; } - public abstract bool Remove(TInterface item); + public abstract bool Remove(TInterface item); public abstract void RemoveAt(int index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } @@ -500,7 +501,7 @@ public override IAtom this[int index] get { if (index >= this.parent.atoms.Count) - throw new ArgumentOutOfRangeException("No atom at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), $"No atom at index: {index}"); return parent.atoms[index]; } @@ -510,9 +511,9 @@ public override IAtom this[int index] if (atom == null) throw new NullReferenceException("Null atom provided"); if (parent.atoms.Contains(atom)) - throw new ArgumentException(nameof(value), "Atom already in container at index: " + this.IndexOf(atom)); + throw new InvalidOperationException($"Atom already in container at index: {this.IndexOf(atom)}"); if (index < 0 || index >= parent.atoms.Count) - throw new IndexOutOfRangeException("No current atom at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), $"No current atom at index: {index}"); BaseAtomRef rep = parent.NewAtomRef(atom); BaseAtomRef org = parent.atoms[index]; parent.atoms[index] = rep; @@ -545,7 +546,7 @@ public override IAtom this[int index] { var map = new CDKObjectMap(); map.Add(org, rep); - parent.stereo[i] = (IReadOnlyStereoElement)se.Clone(map); + parent.stereo[i] = (IStereoElement)se.Clone(map); } } org.Listeners.Remove(parent); @@ -574,7 +575,7 @@ public override void Add(IAtom atom) public override void RemoveAt(int index) { parent.atoms[index].Listeners.Remove(parent); - parent.atoms[index].SetIndex(-1); + parent.atoms[index].SetIndex(-1); for (int i = index; i < parent.atoms.Count - 1; i++) { parent.atoms[i] = parent.atoms[i + 1]; @@ -595,13 +596,13 @@ public override bool Remove(IAtom item) return false; } - public override void Clear() - { + public override void Clear() + { foreach (var item in parent.atoms) item.Listeners.Remove(parent); parent.atoms.Clear(); - parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); - } + parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); + } } internal class BaseBondRef_Collection : A_Collection @@ -619,7 +620,7 @@ public override IBond this[int index] get { if (index >= parent.bonds.Count) - throw new ArgumentOutOfRangeException("No bond at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), "No bond at index: " + index); return parent.bonds[index]; } @@ -642,14 +643,14 @@ public override void Add(IBond bond) parent.AddToEndpoints(bref); parent.bonds.Add(bref); bref.Listeners.Add(parent); - parent.NotifyChanged(); + parent.NotifyChanged(); } public override void RemoveAt(int index) { BondRef bond = null; bond = parent.bonds[index]; - parent.bonds[index].SetIndex(-1); + parent.bonds[index].SetIndex(-1); for (int i = index; i < parent.bonds.Count - 1; i++) { parent.bonds[i] = parent.bonds[i + 1]; @@ -658,7 +659,7 @@ public override void RemoveAt(int index) parent.bonds.RemoveAt(parent.bonds.Count - 1); parent.DelFromEndpoints(bond); bond.Listeners.Remove(parent); - parent.NotifyChanged(); + parent.NotifyChanged(); } public override bool Remove(IBond item) @@ -672,15 +673,15 @@ public override bool Remove(IBond item) return false; } - public override void Clear() - { + public override void Clear() + { foreach (var item in parent.bonds) item.Listeners.Remove(parent); parent.bonds.Clear(); - parent.ClearAdjacency(); - parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); - } - } + parent.ClearAdjacency(); + parent.OnStateChanged(new ChemObjectChangeEventArgs(this)); + } + } internal static IAtom Unbox(IAtom atom) { @@ -699,7 +700,7 @@ internal static IBond Unbox(IBond bond) internal BaseAtomRef GetAtomRefUnsafe(IAtom atom) { if (atom.Container == this && - atom.Index != -1 && + atom.Index != -1 && atoms[atom.Index] == atom) return (BaseAtomRef)atom; atom = Unbox(atom); @@ -749,7 +750,7 @@ internal BaseAtomRef NewAtomRef(IAtom atom) private BondRef GetBondRefUnsafe(IBond bond) { if (bond.Container == this && - bond.Index != -1 && + bond.Index != -1 && bonds[bond.Index] == bond) return (BondRef)bond; bond = Unbox(bond); @@ -815,7 +816,7 @@ public void SetAtoms(IEnumerable newatoms_) for (int i = 0; i < newatoms.Count; i++) { - if (i >= atoms.Count) + if (i >= atoms.Count) atoms.Add(null); if (newatoms[i].Container == this) @@ -825,8 +826,8 @@ public void SetAtoms(IEnumerable newatoms_) } else { - if (atoms[i] != null) - atoms[i].Listeners.Remove(this); + if (atoms[i] != null) + atoms[i].Listeners.Remove(this); atoms[i] = NewAtomRef(newatoms[i]); atoms[i].SetIndex(i); atoms[i].Listeners.Add(this); @@ -834,14 +835,14 @@ public void SetAtoms(IEnumerable newatoms_) } } - // delete rest of the array - { - for (int i = atoms.Count - 1; i >= newatoms.Count; i--) - { - atoms[i].Listeners.Remove(this); - atoms.RemoveAt(i); - } - } + // delete rest of the array + { + for (int i = atoms.Count - 1; i >= newatoms.Count; i--) + { + atoms[i].Listeners.Remove(this); + atoms.RemoveAt(i); + } + } // ensure adjacency information is in sync, this code is only // called if the bonds are non-empty and 'external' atoms have been @@ -853,36 +854,36 @@ public void SetAtoms(IEnumerable newatoms_) AddToEndpoints(bonds[i]); } - NotifyChanged(); + NotifyChanged(); } public void SetBonds(IEnumerable newbonds_) { var newbonds = newbonds_.ToList(); - // replace existing bonds to clear their adjacency - if (bonds.Count > 0) - { - ClearAdjacency(); - } + // replace existing bonds to clear their adjacency + if (bonds.Count > 0) + { + ClearAdjacency(); + } - for (int i = 0; i < newbonds.Count; i++) - { - if (i >= bonds.Count) + for (int i = 0; i < newbonds.Count; i++) + { + if (i >= bonds.Count) bonds.Add(null); - BaseBondRef bondRef = NewBondRef(newbonds[i]); - bondRef.SetIndex(i); - AddToEndpoints(bondRef); - if (bonds[i] != null) - bonds[i].Listeners.Remove(this); - bonds[i] = bondRef; - bondRef.Listeners.Add(this); - } - for (int i = bonds.Count - 1; i >= newbonds.Count; i--) - bonds.RemoveAt(i); + BaseBondRef bondRef = NewBondRef(newbonds[i]); + bondRef.SetIndex(i); + AddToEndpoints(bondRef); + if (bonds[i] != null) + bonds[i].Listeners.Remove(this); + bonds[i] = bondRef; + bondRef.Listeners.Add(this); + } + for (int i = bonds.Count - 1; i >= newbonds.Count; i--) + bonds.RemoveAt(i); - NotifyChanged(); + NotifyChanged(); } public int IndexOf(ISingleElectron electron) @@ -915,8 +916,8 @@ public IElectronContainer GetElectronContainer(int number) public IBond GetBond(IAtom beg, IAtom end) { - AtomRef begref = GetAtomRefUnsafe(beg); - return begref?.GetBond(end); + AtomRef begref = GetAtomRefUnsafe(beg); + return begref?.GetBond(end); } public int GetAtomCount() @@ -1087,7 +1088,7 @@ public void Add(IAtomContainer that) foreach (var singleElectron in that.SingleElectrons.Where(singleElectron => !Contains(singleElectron))) SingleElectrons.Add(singleElectron); - NotifyChanged(); + NotifyChanged(); } /// @@ -1109,7 +1110,7 @@ public void AddElectronContainer(IElectronContainer electronContainer) return; } - NotifyChanged(); + NotifyChanged(); } /// @@ -1124,7 +1125,7 @@ public void Remove(IAtomContainer atomContainer) foreach (var atom in atomContainer.Atoms) Atoms.Remove(atom); - NotifyChanged(); + NotifyChanged(); } public IBond RemoveBond(IAtom beg, IAtom end) @@ -1186,11 +1187,11 @@ public void RemoveAtom(IAtom atom) DelFromEndpoints(bonds[i]); } } - { - for (int j = bonds.Count - 1; j >= newNumBonds; j--) - bonds.RemoveAt(j); - } - } + { + for (int j = bonds.Count - 1; j >= newNumBonds; j--) + bonds.RemoveAt(j); + } + } // update single electrons int newNumSingleElectrons = 0; @@ -1230,7 +1231,7 @@ public void RemoveAtom(IAtom atom) lonepairs.RemoveAt(j); } - var atomElements = new List>(); + var atomElements = new List>(); foreach (var element in stereo) { if (element.Contains(atom)) atomElements.Add(element); @@ -1238,7 +1239,7 @@ public void RemoveAtom(IAtom atom) foreach (var ae in atomElements) stereo.Remove(ae); - Atoms.RemoveAt(atomref.Index); + Atoms.RemoveAt(atomref.Index); } } @@ -1256,7 +1257,7 @@ public void RemoveAllElements() atom.Listeners?.Remove(this); atoms.Clear(); stereo.Clear(); - NotifyChanged(); + NotifyChanged(); } public void RemoveAllElectronContainers() @@ -1269,14 +1270,14 @@ public void RemoveAllElectronContainers() lonepairs.Clear(); electrons.Clear(); - NotifyChanged(); + NotifyChanged(); } public void RemoveAllBonds() { bonds.Clear(); ClearAdjacency(); - NotifyChanged(); + NotifyChanged(); } /// @@ -1339,7 +1340,7 @@ internal string ToStringInner() return sb.ToString(); } - private void Append(StringBuilder sb, ICollection os, string tag) + private static void Append(StringBuilder sb, ICollection os, string tag) { if (os.Count > 0) { @@ -1352,7 +1353,7 @@ private void Append(StringBuilder sb, ICollection os, string tag) /// public override ICDKObject Clone(CDKObjectMap map) { - CDKObjectMap refmap = new CDKObjectMap(); + CDKObjectMap refmap = new CDKObjectMap(); // this is pretty wasteful as we need to delete most the data // we can't simply create an empty instance as the sub classes (e.g. AminoAcid) @@ -1365,7 +1366,7 @@ public override ICDKObject Clone(CDKObjectMap map) clone.bonds = new List(); clone.lonepairs = new ObservableChemObjectCollection(clone); clone.electrons = new ObservableChemObjectCollection(clone); - clone.stereo = new List>(); + clone.stereo = new List>(); clone.Atoms = new BaseAtomRef_Collection(clone); clone.Bonds = new BaseBondRef_Collection(clone); clone.LonePairs = clone.lonepairs; @@ -1430,15 +1431,14 @@ public override ICDKObject Clone(CDKObjectMap map) // map each stereo element to a new instance in the clone foreach (var element in stereo) { - clone.StereoElements.Add((IReadOnlyStereoElement)element.Clone(refmap)); + clone.StereoElements.Add((IStereoElement)element.Clone(refmap)); } - // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + // update sgroups + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, refmap)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, refmap)); } return clone; @@ -1447,7 +1447,7 @@ public override ICDKObject Clone(CDKObjectMap map) /// public void OnStateChanged(ChemObjectChangeEventArgs evt) { - NotifyChanged(evt); + NotifyChanged(evt); } /// @@ -1462,18 +1462,16 @@ namespace NCDK.Silent // @author John Mayfield internal sealed class AtomContainer2 : ChemObject, IAtomContainer { - private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(false); + private static readonly IChemObjectBuilder builder = new ChemObjectBuilder(false); - /// - public override IChemObjectBuilder Builder => builder; - - private const int DEFAULT_CAPACITY = 20; + /// + public override IChemObjectBuilder Builder => builder; internal List atoms; internal List bonds; internal ObservableChemObjectCollection lonepairs; internal ObservableChemObjectCollection electrons; - internal List> stereo; + internal List> stereo; internal bool isAromatic; internal bool isSingleOrDouble; @@ -1485,7 +1483,7 @@ internal sealed class AtomContainer2 : ChemObject, IAtomContainer public IList LonePairs { get; private set; } public IList SingleElectrons { get; private set; } // TODO: handle notification - public ICollection> StereoElements { get; private set; } + public ICollection> StereoElements { get; private set; } /// /// Create a new container with the specified capacities. @@ -1503,7 +1501,7 @@ public AtomContainer2(int numAtoms, this.bonds = new List(numBonds); this.lonepairs = new ObservableChemObjectCollection(numLonePairs, this); this.electrons = new ObservableChemObjectCollection(numSingleElectrons, this); - this.stereo = new List>(); + this.stereo = new List>(); this.Atoms = new BaseAtomRef_Collection(this); this.Bonds = new BaseBondRef_Collection(this); @@ -1650,18 +1648,18 @@ public void SetIndex(int index) internal BaseAtomRef GetBegin() => beg; internal BaseAtomRef GetEnd() => end; - private IList internalAtoms; + private IList internalAtoms; - /// - public override IList Atoms - { - get - { - if (internalAtoms == null) - internalAtoms = new InternalAtoms(this, base.Atoms); - return internalAtoms; - } - } + /// + public override IList Atoms + { + get + { + if (internalAtoms == null) + internalAtoms = new InternalAtoms(this, base.Atoms); + return internalAtoms; + } + } internal class InternalAtoms : IList { @@ -1880,13 +1878,13 @@ public A_Collection(List list) public int Count => list.Count; public bool IsReadOnly => false; public abstract void Add(TInterface item); - public abstract void Clear(); + public abstract void Clear(); public bool Contains(TInterface item) => list.Contains((TRef)item); public void CopyTo(TInterface[] array, int arrayIndex) { for (int i = 0; i < list.Count; i++) array[arrayIndex + i] = list[i]; - } + } public IEnumerator GetEnumerator() => list.Cast().GetEnumerator(); public abstract int IndexOf(TInterface atom); public void Insert(int index, TInterface item) @@ -1894,7 +1892,7 @@ public void Insert(int index, TInterface item) list.Insert(index, default(TRef)); this[index] = item; } - public abstract bool Remove(TInterface item); + public abstract bool Remove(TInterface item); public abstract void RemoveAt(int index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } @@ -1914,7 +1912,7 @@ public override IAtom this[int index] get { if (index >= this.parent.atoms.Count) - throw new ArgumentOutOfRangeException("No atom at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), $"No atom at index: {index}"); return parent.atoms[index]; } @@ -1924,9 +1922,9 @@ public override IAtom this[int index] if (atom == null) throw new NullReferenceException("Null atom provided"); if (parent.atoms.Contains(atom)) - throw new ArgumentException(nameof(value), "Atom already in container at index: " + this.IndexOf(atom)); + throw new InvalidOperationException($"Atom already in container at index: {this.IndexOf(atom)}"); if (index < 0 || index >= parent.atoms.Count) - throw new IndexOutOfRangeException("No current atom at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), $"No current atom at index: {index}"); BaseAtomRef rep = parent.NewAtomRef(atom); BaseAtomRef org = parent.atoms[index]; parent.atoms[index] = rep; @@ -1959,7 +1957,7 @@ public override IAtom this[int index] { var map = new CDKObjectMap(); map.Add(org, rep); - parent.stereo[i] = (IReadOnlyStereoElement)se.Clone(map); + parent.stereo[i] = (IStereoElement)se.Clone(map); } } } @@ -1982,7 +1980,7 @@ public override void Add(IAtom atom) public override void RemoveAt(int index) { - parent.atoms[index].SetIndex(-1); + parent.atoms[index].SetIndex(-1); for (int i = index; i < parent.atoms.Count - 1; i++) { parent.atoms[i] = parent.atoms[i + 1]; @@ -2002,10 +2000,10 @@ public override bool Remove(IAtom item) return false; } - public override void Clear() - { + public override void Clear() + { parent.atoms.Clear(); - } + } } internal class BaseBondRef_Collection : A_Collection @@ -2023,7 +2021,7 @@ public override IBond this[int index] get { if (index >= parent.bonds.Count) - throw new ArgumentOutOfRangeException("No bond at index: " + index); + throw new ArgumentOutOfRangeException(nameof(index), "No bond at index: " + index); return parent.bonds[index]; } @@ -2052,7 +2050,7 @@ public override void RemoveAt(int index) { BondRef bond = null; bond = parent.bonds[index]; - parent.bonds[index].SetIndex(-1); + parent.bonds[index].SetIndex(-1); for (int i = index; i < parent.bonds.Count - 1; i++) { parent.bonds[i] = parent.bonds[i + 1]; @@ -2073,12 +2071,12 @@ public override bool Remove(IBond item) return false; } - public override void Clear() - { + public override void Clear() + { parent.bonds.Clear(); - parent.ClearAdjacency(); - } - } + parent.ClearAdjacency(); + } + } internal static IAtom Unbox(IAtom atom) { @@ -2097,7 +2095,7 @@ internal static IBond Unbox(IBond bond) internal BaseAtomRef GetAtomRefUnsafe(IAtom atom) { if (atom.Container == this && - atom.Index != -1 && + atom.Index != -1 && atoms[atom.Index] == atom) return (BaseAtomRef)atom; atom = Unbox(atom); @@ -2147,7 +2145,7 @@ internal BaseAtomRef NewAtomRef(IAtom atom) private BondRef GetBondRefUnsafe(IBond bond) { if (bond.Container == this && - bond.Index != -1 && + bond.Index != -1 && bonds[bond.Index] == bond) return (BondRef)bond; bond = Unbox(bond); @@ -2213,7 +2211,7 @@ public void SetAtoms(IEnumerable newatoms_) for (int i = 0; i < newatoms.Count; i++) { - if (i >= atoms.Count) + if (i >= atoms.Count) atoms.Add(null); if (newatoms[i].Container == this) @@ -2229,13 +2227,13 @@ public void SetAtoms(IEnumerable newatoms_) } } - // delete rest of the array - { - for (int i = atoms.Count - 1; i >= newatoms.Count; i--) - { - atoms.RemoveAt(i); - } - } + // delete rest of the array + { + for (int i = atoms.Count - 1; i >= newatoms.Count; i--) + { + atoms.RemoveAt(i); + } + } // ensure adjacency information is in sync, this code is only // called if the bonds are non-empty and 'external' atoms have been @@ -2253,24 +2251,24 @@ public void SetBonds(IEnumerable newbonds_) { var newbonds = newbonds_.ToList(); - // replace existing bonds to clear their adjacency - if (bonds.Count > 0) - { - ClearAdjacency(); - } + // replace existing bonds to clear their adjacency + if (bonds.Count > 0) + { + ClearAdjacency(); + } - for (int i = 0; i < newbonds.Count; i++) - { - if (i >= bonds.Count) + for (int i = 0; i < newbonds.Count; i++) + { + if (i >= bonds.Count) bonds.Add(null); - BaseBondRef bondRef = NewBondRef(newbonds[i]); - bondRef.SetIndex(i); - AddToEndpoints(bondRef); - bonds[i] = bondRef; - } - for (int i = bonds.Count - 1; i >= newbonds.Count; i--) - bonds.RemoveAt(i); + BaseBondRef bondRef = NewBondRef(newbonds[i]); + bondRef.SetIndex(i); + AddToEndpoints(bondRef); + bonds[i] = bondRef; + } + for (int i = bonds.Count - 1; i >= newbonds.Count; i--) + bonds.RemoveAt(i); } @@ -2304,8 +2302,8 @@ public IElectronContainer GetElectronContainer(int number) public IBond GetBond(IAtom beg, IAtom end) { - AtomRef begref = GetAtomRefUnsafe(beg); - return begref?.GetBond(end); + AtomRef begref = GetAtomRefUnsafe(beg); + return begref?.GetBond(end); } public int GetAtomCount() @@ -2572,11 +2570,11 @@ public void RemoveAtom(IAtom atom) DelFromEndpoints(bonds[i]); } } - { - for (int j = bonds.Count - 1; j >= newNumBonds; j--) - bonds.RemoveAt(j); - } - } + { + for (int j = bonds.Count - 1; j >= newNumBonds; j--) + bonds.RemoveAt(j); + } + } // update single electrons int newNumSingleElectrons = 0; @@ -2616,7 +2614,7 @@ public void RemoveAtom(IAtom atom) lonepairs.RemoveAt(j); } - var atomElements = new List>(); + var atomElements = new List>(); foreach (var element in stereo) { if (element.Contains(atom)) atomElements.Add(element); @@ -2624,7 +2622,7 @@ public void RemoveAtom(IAtom atom) foreach (var ae in atomElements) stereo.Remove(ae); - Atoms.RemoveAt(atomref.Index); + Atoms.RemoveAt(atomref.Index); } } @@ -2718,7 +2716,7 @@ internal string ToStringInner() return sb.ToString(); } - private void Append(StringBuilder sb, ICollection os, string tag) + private static void Append(StringBuilder sb, ICollection os, string tag) { if (os.Count > 0) { @@ -2731,7 +2729,7 @@ private void Append(StringBuilder sb, ICollection os, string tag) /// public override ICDKObject Clone(CDKObjectMap map) { - CDKObjectMap refmap = new CDKObjectMap(); + CDKObjectMap refmap = new CDKObjectMap(); // this is pretty wasteful as we need to delete most the data // we can't simply create an empty instance as the sub classes (e.g. AminoAcid) @@ -2744,7 +2742,7 @@ public override ICDKObject Clone(CDKObjectMap map) clone.bonds = new List(); clone.lonepairs = new ObservableChemObjectCollection(clone); clone.electrons = new ObservableChemObjectCollection(clone); - clone.stereo = new List>(); + clone.stereo = new List>(); clone.Atoms = new BaseAtomRef_Collection(clone); clone.Bonds = new BaseBondRef_Collection(clone); clone.LonePairs = clone.lonepairs; @@ -2809,15 +2807,14 @@ public override ICDKObject Clone(CDKObjectMap map) // map each stereo element to a new instance in the clone foreach (var element in stereo) { - clone.StereoElements.Add((IReadOnlyStereoElement)element.Clone(refmap)); + clone.StereoElements.Add((IStereoElement)element.Clone(refmap)); } - // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + // update sgroups + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, refmap)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, refmap)); } return clone; diff --git a/NCDK/TT/AtomContainerSet.tt b/NCDK/TT/AtomContainerSet.tt index 4c0f1847..923cf164 100644 --- a/NCDK/TT/AtomContainerSet.tt +++ b/NCDK/TT/AtomContainerSet.tt @@ -31,19 +31,21 @@ using System.Linq; using System.Collections.ObjectModel; using System.Collections; +#pragma warning disable CA1710 // Identifiers should have correct suffix + <# foreach (var ns in namespaces) { #> namespace <#= ns.NS #> { - public class AtomContainerSet - : ChemObjectSet, IAtomContainerSet - { - public AtomContainerSet() - : base() - {} - } + public class AtomContainerSet + : ChemObjectSet, IAtomContainerSet + { + public AtomContainerSet() + : base() + {} + } /// /// A set of AtomContainers. @@ -57,7 +59,7 @@ namespace <#= ns.NS #> where T : IChemObject { internal IList atomContainers; - internal IList multipliers; + internal List multipliers; /// Constructs an empty ChemObjectSet. public ChemObjectSet() @@ -147,7 +149,7 @@ namespace <#= ns.NS #> <# if (!ns.IsSilent) { #> NotifyChanged(); <# } #> } - public IReadOnlyList GetMultipliers() => new ReadOnlyCollection(multipliers); + public IReadOnlyList GetMultipliers() => multipliers; /// /// Sets the multipliers of the AtomContainers. @@ -309,8 +311,8 @@ namespace <#= ns.NS #> class CompareRefByIndex : IComparer { - ChemObjectSet parent; - IComparer comparator; + private readonly ChemObjectSet parent; + private IComparer comparator; public CompareRefByIndex(ChemObjectSet parent, IComparer comparator) { diff --git a/NCDK/TT/AtomContainerSet.tt.cs b/NCDK/TT/AtomContainerSet.tt.cs index 42ddcebe..3d91ec98 100644 --- a/NCDK/TT/AtomContainerSet.tt.cs +++ b/NCDK/TT/AtomContainerSet.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -32,15 +33,17 @@ using System.Collections.ObjectModel; using System.Collections; +#pragma warning disable CA1710 // Identifiers should have correct suffix + namespace NCDK.Default { - public class AtomContainerSet - : ChemObjectSet, IAtomContainerSet - { - public AtomContainerSet() - : base() - {} - } + public class AtomContainerSet + : ChemObjectSet, IAtomContainerSet + { + public AtomContainerSet() + : base() + {} + } /// /// A set of AtomContainers. @@ -54,7 +57,7 @@ public class ChemObjectSet where T : IChemObject { internal IList atomContainers; - internal IList multipliers; + internal List multipliers; /// Constructs an empty ChemObjectSet. public ChemObjectSet() @@ -142,7 +145,7 @@ public void SetMultiplier(int position, double? multiplier) multipliers[position] = multiplier; NotifyChanged(); } - public IReadOnlyList GetMultipliers() => new ReadOnlyCollection(multipliers); + public IReadOnlyList GetMultipliers() => multipliers; /// /// Sets the multipliers of the AtomContainers. @@ -302,8 +305,8 @@ public void CopyTo(T[] array, int arrayIndex) class CompareRefByIndex : IComparer { - ChemObjectSet parent; - IComparer comparator; + private readonly ChemObjectSet parent; + private IComparer comparator; public CompareRefByIndex(ChemObjectSet parent, IComparer comparator) { @@ -320,13 +323,13 @@ public int Compare(int o1, int o2) } namespace NCDK.Silent { - public class AtomContainerSet - : ChemObjectSet, IAtomContainerSet - { - public AtomContainerSet() - : base() - {} - } + public class AtomContainerSet + : ChemObjectSet, IAtomContainerSet + { + public AtomContainerSet() + : base() + {} + } /// /// A set of AtomContainers. @@ -340,7 +343,7 @@ public class ChemObjectSet where T : IChemObject { internal IList atomContainers; - internal IList multipliers; + internal List multipliers; /// Constructs an empty ChemObjectSet. public ChemObjectSet() @@ -428,7 +431,7 @@ public void SetMultiplier(int position, double? multiplier) multipliers[position] = multiplier; } - public IReadOnlyList GetMultipliers() => new ReadOnlyCollection(multipliers); + public IReadOnlyList GetMultipliers() => multipliers; /// /// Sets the multipliers of the AtomContainers. @@ -588,8 +591,8 @@ public void CopyTo(T[] array, int arrayIndex) class CompareRefByIndex : IComparer { - ChemObjectSet parent; - IComparer comparator; + private readonly ChemObjectSet parent; + private IComparer comparator; public CompareRefByIndex(ChemObjectSet parent, IComparer comparator) { diff --git a/NCDK/TT/AtomType.tt b/NCDK/TT/AtomType.tt index 77cf6ac8..26e25282 100644 --- a/NCDK/TT/AtomType.tt +++ b/NCDK/TT/AtomType.tt @@ -30,7 +30,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using System; +using NCDK.Common.Serialization; +using System.Runtime.Serialization; using System.Text; <# @@ -49,17 +50,16 @@ namespace <#= ns.NS #> // @cdk.created 2001-08-08 // @cdk.githash // @cdk.keyword atom, type - [Serializable] public class AtomType - : Isotope, IAtomType + : Isotope, IAtomType, ISerializable { /// - /// The maximum bond order allowed for this atom type. + /// The maximum bond order allowed for this atom type. /// internal BondOrder maxBondOrder; /// - /// The maximum sum of all bond orders allowed for this atom type. + /// The maximum sum of all bond orders allowed for this atom type. /// internal double? bondOrderSum; @@ -69,28 +69,28 @@ namespace <#= ns.NS #> internal double? covalentRadius; /// - /// The formal charge of the atom with CDKConstants.UNSET as default. Implements RFC #6. + /// The formal charge of the atom with CDKConstants.UNSET as default. Implements RFC #6. /// /// - /// Note that some constructors ( and - /// ) will explicitly set this field to 0 + /// Note that some constructors ( and + /// ) will explicitly set this field to 0 /// internal int? formalCharge; /// - /// The hybridization state of this atom with CDKConstants.HYBRIDIZATION_UNSET + /// The hybridization state of this atom with /// as default. /// internal Hybridization hybridization; /// - /// The electron Valency of this atom with CDKConstants.UNSET as default. + /// The electron valency of this atom with as default. /// internal int? valency; /// - /// The formal number of neighbours this atom type can have with CDKConstants_UNSET - /// as default. This includes explicitely and implicitely connected atoms, including + /// The formal number of neighbours this atom type can have with + /// as default. This includes explicitly and implicitly connected atoms, including /// implicit hydrogens. /// internal int? formalNeighbourCount; @@ -103,12 +103,53 @@ namespace <#= ns.NS #> internal bool isInRing; internal bool isReactiveCenter; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(maxBondOrder), maxBondOrder); + info.AddNullableValue(nameof(bondOrderSum), bondOrderSum); + info.AddNullableValue(nameof(covalentRadius), covalentRadius); + info.AddNullableValue(nameof(formalCharge), formalCharge); + info.AddValue(nameof(hybridization), hybridization); + info.AddNullableValue(nameof(valency), valency); + info.AddNullableValue(nameof(formalNeighbourCount), formalNeighbourCount); + info.AddValue(nameof(atomTypeName), atomTypeName); + info.AddValue(nameof(isHydrogenBondAcceptor), isHydrogenBondAcceptor); + info.AddValue(nameof(isHydrogenBondDonor), isHydrogenBondDonor); + info.AddValue(nameof(isAliphatic), isAliphatic); + info.AddValue(nameof(isAromatic), isAromatic); + info.AddValue(nameof(isInRing), isInRing); + info.AddValue(nameof(isReactiveCenter), isReactiveCenter); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected AtomType(SerializationInfo info, StreamingContext context) + : base(info, context) + { + maxBondOrder = (BondOrder)info.GetInt32(nameof(maxBondOrder)); + bondOrderSum = info.GetNullable(nameof(bondOrderSum)); + covalentRadius = info.GetNullable(nameof(covalentRadius)); + formalCharge = info.GetNullable(nameof(formalCharge)); + hybridization = (Hybridization)info.GetInt32(nameof(hybridization)); + valency = info.GetNullable(nameof(valency)); + formalNeighbourCount = info.GetNullable(nameof(formalNeighbourCount)); + atomTypeName = info.GetString(nameof(atomTypeName)); + isHydrogenBondAcceptor = info.GetBoolean(nameof(isHydrogenBondAcceptor)); + isHydrogenBondDonor = info.GetBoolean(nameof(isHydrogenBondDonor)); + isAliphatic = info.GetBoolean(nameof(isAliphatic)); + isAromatic = info.GetBoolean(nameof(isAromatic)); + isInRing = info.GetBoolean(nameof(isInRing)); + isReactiveCenter = info.GetBoolean(nameof(isReactiveCenter)); + } + /// /// Constructor for the AtomType object. - /// + /// + /// /// Defaults to a zero formal charge. All /// other fields are set to or unset. - /// + /// /// Symbol of the atom public AtomType(string elementSymbol) : base(elementSymbol) @@ -255,8 +296,7 @@ namespace <#= ns.NS #> /// true if the atom types are equal public override bool Compare(object obj) { - var o = obj as IAtomType; - return o != null && base.Compare(obj) + return obj is IAtomType o && base.Compare(obj) && AtomTypeName == o.AtomTypeName && MaxBondOrder == o.MaxBondOrder && BondOrderSum == o.BondOrderSum; diff --git a/NCDK/TT/AtomType.tt.cs b/NCDK/TT/AtomType.tt.cs index da2a59b9..59ac1cb9 100644 --- a/NCDK/TT/AtomType.tt.cs +++ b/NCDK/TT/AtomType.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -31,7 +32,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using System; +using NCDK.Common.Serialization; +using System.Runtime.Serialization; using System.Text; namespace NCDK.Default @@ -46,17 +48,16 @@ namespace NCDK.Default // @cdk.created 2001-08-08 // @cdk.githash // @cdk.keyword atom, type - [Serializable] public class AtomType - : Isotope, IAtomType + : Isotope, IAtomType, ISerializable { /// - /// The maximum bond order allowed for this atom type. + /// The maximum bond order allowed for this atom type. /// internal BondOrder maxBondOrder; /// - /// The maximum sum of all bond orders allowed for this atom type. + /// The maximum sum of all bond orders allowed for this atom type. /// internal double? bondOrderSum; @@ -66,28 +67,28 @@ public class AtomType internal double? covalentRadius; /// - /// The formal charge of the atom with CDKConstants.UNSET as default. Implements RFC #6. + /// The formal charge of the atom with CDKConstants.UNSET as default. Implements RFC #6. /// /// - /// Note that some constructors ( and - /// ) will explicitly set this field to 0 + /// Note that some constructors ( and + /// ) will explicitly set this field to 0 /// internal int? formalCharge; /// - /// The hybridization state of this atom with CDKConstants.HYBRIDIZATION_UNSET + /// The hybridization state of this atom with /// as default. /// internal Hybridization hybridization; /// - /// The electron Valency of this atom with CDKConstants.UNSET as default. + /// The electron valency of this atom with as default. /// internal int? valency; /// - /// The formal number of neighbours this atom type can have with CDKConstants_UNSET - /// as default. This includes explicitely and implicitely connected atoms, including + /// The formal number of neighbours this atom type can have with + /// as default. This includes explicitly and implicitly connected atoms, including /// implicit hydrogens. /// internal int? formalNeighbourCount; @@ -100,12 +101,53 @@ public class AtomType internal bool isInRing; internal bool isReactiveCenter; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(maxBondOrder), maxBondOrder); + info.AddNullableValue(nameof(bondOrderSum), bondOrderSum); + info.AddNullableValue(nameof(covalentRadius), covalentRadius); + info.AddNullableValue(nameof(formalCharge), formalCharge); + info.AddValue(nameof(hybridization), hybridization); + info.AddNullableValue(nameof(valency), valency); + info.AddNullableValue(nameof(formalNeighbourCount), formalNeighbourCount); + info.AddValue(nameof(atomTypeName), atomTypeName); + info.AddValue(nameof(isHydrogenBondAcceptor), isHydrogenBondAcceptor); + info.AddValue(nameof(isHydrogenBondDonor), isHydrogenBondDonor); + info.AddValue(nameof(isAliphatic), isAliphatic); + info.AddValue(nameof(isAromatic), isAromatic); + info.AddValue(nameof(isInRing), isInRing); + info.AddValue(nameof(isReactiveCenter), isReactiveCenter); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected AtomType(SerializationInfo info, StreamingContext context) + : base(info, context) + { + maxBondOrder = (BondOrder)info.GetInt32(nameof(maxBondOrder)); + bondOrderSum = info.GetNullable(nameof(bondOrderSum)); + covalentRadius = info.GetNullable(nameof(covalentRadius)); + formalCharge = info.GetNullable(nameof(formalCharge)); + hybridization = (Hybridization)info.GetInt32(nameof(hybridization)); + valency = info.GetNullable(nameof(valency)); + formalNeighbourCount = info.GetNullable(nameof(formalNeighbourCount)); + atomTypeName = info.GetString(nameof(atomTypeName)); + isHydrogenBondAcceptor = info.GetBoolean(nameof(isHydrogenBondAcceptor)); + isHydrogenBondDonor = info.GetBoolean(nameof(isHydrogenBondDonor)); + isAliphatic = info.GetBoolean(nameof(isAliphatic)); + isAromatic = info.GetBoolean(nameof(isAromatic)); + isInRing = info.GetBoolean(nameof(isInRing)); + isReactiveCenter = info.GetBoolean(nameof(isReactiveCenter)); + } + /// /// Constructor for the AtomType object. - /// + /// + /// /// Defaults to a zero formal charge. All /// other fields are set to or unset. - /// + /// /// Symbol of the atom public AtomType(string elementSymbol) : base(elementSymbol) @@ -240,8 +282,7 @@ public virtual Hybridization Hybridization /// true if the atom types are equal public override bool Compare(object obj) { - var o = obj as IAtomType; - return o != null && base.Compare(obj) + return obj is IAtomType o && base.Compare(obj) && AtomTypeName == o.AtomTypeName && MaxBondOrder == o.MaxBondOrder && BondOrderSum == o.BondOrderSum; @@ -371,17 +412,16 @@ namespace NCDK.Silent // @cdk.created 2001-08-08 // @cdk.githash // @cdk.keyword atom, type - [Serializable] public class AtomType - : Isotope, IAtomType + : Isotope, IAtomType, ISerializable { /// - /// The maximum bond order allowed for this atom type. + /// The maximum bond order allowed for this atom type. /// internal BondOrder maxBondOrder; /// - /// The maximum sum of all bond orders allowed for this atom type. + /// The maximum sum of all bond orders allowed for this atom type. /// internal double? bondOrderSum; @@ -391,28 +431,28 @@ public class AtomType internal double? covalentRadius; /// - /// The formal charge of the atom with CDKConstants.UNSET as default. Implements RFC #6. + /// The formal charge of the atom with CDKConstants.UNSET as default. Implements RFC #6. /// /// - /// Note that some constructors ( and - /// ) will explicitly set this field to 0 + /// Note that some constructors ( and + /// ) will explicitly set this field to 0 /// internal int? formalCharge; /// - /// The hybridization state of this atom with CDKConstants.HYBRIDIZATION_UNSET + /// The hybridization state of this atom with /// as default. /// internal Hybridization hybridization; /// - /// The electron Valency of this atom with CDKConstants.UNSET as default. + /// The electron valency of this atom with as default. /// internal int? valency; /// - /// The formal number of neighbours this atom type can have with CDKConstants_UNSET - /// as default. This includes explicitely and implicitely connected atoms, including + /// The formal number of neighbours this atom type can have with + /// as default. This includes explicitly and implicitly connected atoms, including /// implicit hydrogens. /// internal int? formalNeighbourCount; @@ -425,12 +465,53 @@ public class AtomType internal bool isInRing; internal bool isReactiveCenter; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(maxBondOrder), maxBondOrder); + info.AddNullableValue(nameof(bondOrderSum), bondOrderSum); + info.AddNullableValue(nameof(covalentRadius), covalentRadius); + info.AddNullableValue(nameof(formalCharge), formalCharge); + info.AddValue(nameof(hybridization), hybridization); + info.AddNullableValue(nameof(valency), valency); + info.AddNullableValue(nameof(formalNeighbourCount), formalNeighbourCount); + info.AddValue(nameof(atomTypeName), atomTypeName); + info.AddValue(nameof(isHydrogenBondAcceptor), isHydrogenBondAcceptor); + info.AddValue(nameof(isHydrogenBondDonor), isHydrogenBondDonor); + info.AddValue(nameof(isAliphatic), isAliphatic); + info.AddValue(nameof(isAromatic), isAromatic); + info.AddValue(nameof(isInRing), isInRing); + info.AddValue(nameof(isReactiveCenter), isReactiveCenter); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected AtomType(SerializationInfo info, StreamingContext context) + : base(info, context) + { + maxBondOrder = (BondOrder)info.GetInt32(nameof(maxBondOrder)); + bondOrderSum = info.GetNullable(nameof(bondOrderSum)); + covalentRadius = info.GetNullable(nameof(covalentRadius)); + formalCharge = info.GetNullable(nameof(formalCharge)); + hybridization = (Hybridization)info.GetInt32(nameof(hybridization)); + valency = info.GetNullable(nameof(valency)); + formalNeighbourCount = info.GetNullable(nameof(formalNeighbourCount)); + atomTypeName = info.GetString(nameof(atomTypeName)); + isHydrogenBondAcceptor = info.GetBoolean(nameof(isHydrogenBondAcceptor)); + isHydrogenBondDonor = info.GetBoolean(nameof(isHydrogenBondDonor)); + isAliphatic = info.GetBoolean(nameof(isAliphatic)); + isAromatic = info.GetBoolean(nameof(isAromatic)); + isInRing = info.GetBoolean(nameof(isInRing)); + isReactiveCenter = info.GetBoolean(nameof(isReactiveCenter)); + } + /// /// Constructor for the AtomType object. - /// + /// + /// /// Defaults to a zero formal charge. All /// other fields are set to or unset. - /// + /// /// Symbol of the atom public AtomType(string elementSymbol) : base(elementSymbol) @@ -559,8 +640,7 @@ public virtual Hybridization Hybridization /// true if the atom types are equal public override bool Compare(object obj) { - var o = obj as IAtomType; - return o != null && base.Compare(obj) + return obj is IAtomType o && base.Compare(obj) && AtomTypeName == o.AtomTypeName && MaxBondOrder == o.MaxBondOrder && BondOrderSum == o.BondOrderSum; diff --git a/NCDK/TT/BioPolymer.tt b/NCDK/TT/BioPolymer.tt index bc570f36..29707c8e 100644 --- a/NCDK/TT/BioPolymer.tt +++ b/NCDK/TT/BioPolymer.tt @@ -41,10 +41,10 @@ namespace <#= ns.NS #> public class BioPolymer : Polymer, IBioPolymer { - private IDictionary strands; + private Dictionary strands; public BioPolymer() - : base() + : base() { strands = new Dictionary(); } @@ -167,7 +167,7 @@ namespace <#= ns.NS #> } } - public IDictionary GetStrandMap() + public IReadOnlyDictionary GetStrandMap() { return strands; } diff --git a/NCDK/TT/BioPolymer.tt.cs b/NCDK/TT/BioPolymer.tt.cs index 514d7ce1..01181fe9 100644 --- a/NCDK/TT/BioPolymer.tt.cs +++ b/NCDK/TT/BioPolymer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -38,10 +39,10 @@ namespace NCDK.Default public class BioPolymer : Polymer, IBioPolymer { - private IDictionary strands; + private Dictionary strands; public BioPolymer() - : base() + : base() { strands = new Dictionary(); } @@ -164,7 +165,7 @@ public void RemoveStrand(string name) } } - public IDictionary GetStrandMap() + public IReadOnlyDictionary GetStrandMap() { return strands; } @@ -199,10 +200,10 @@ namespace NCDK.Silent public class BioPolymer : Polymer, IBioPolymer { - private IDictionary strands; + private Dictionary strands; public BioPolymer() - : base() + : base() { strands = new Dictionary(); } @@ -325,7 +326,7 @@ public void RemoveStrand(string name) } } - public IDictionary GetStrandMap() + public IReadOnlyDictionary GetStrandMap() { return strands; } diff --git a/NCDK/TT/Bond.tt b/NCDK/TT/Bond.tt index 45431097..1dede8a6 100644 --- a/NCDK/TT/Bond.tt +++ b/NCDK/TT/Bond.tt @@ -144,20 +144,20 @@ namespace <#= ns.NS #> if (atoms == null) { <# if (ns.IsSilent) { #> - this.atoms = new List(2); + this.atoms = new List(2); <# } else { #> - this.atoms = new ObservableChemObjectCollection(2, this); + this.atoms = new ObservableChemObjectCollection(2, this); <# } #> } else { <# if (ns.IsSilent) { #> - int n = Math.Min(atoms.Count(), 2); - var list = new List(n); - list.AddRange(atoms); - this.atoms = list; + int n = Math.Min(atoms.Count(), 2); + var list = new List(n); + list.AddRange(atoms); + this.atoms = list; <# } else { #> - this.atoms = new ObservableChemObjectCollection(this, atoms); + this.atoms = new ObservableChemObjectCollection(this, atoms); <# } #> } } @@ -165,13 +165,13 @@ namespace <#= ns.NS #> /// public virtual IList Atoms => atoms; - /// - public virtual int Index => -1; + /// + public virtual int Index => -1; - /// - public virtual IAtomContainer Container => null; + /// + public virtual IAtomContainer Container => null; - /// + /// public IAtom Begin => atoms.Count < 1 ? null : atoms[0]; /// @@ -198,7 +198,7 @@ namespace <#= ns.NS #> { if (!atoms.Contains(atom)) return null; - return atoms.Where(n => n != atom); + return atoms.Where(n => n != atom); } /// @@ -216,8 +216,8 @@ namespace <#= ns.NS #> /// /// Sets the array of atoms making up this bond. /// - /// An array of atoms that forms this bond - /// + /// An array of atoms that forms this bond + /// public virtual void SetAtoms(IEnumerable atoms) { this.atoms.Clear(); @@ -372,19 +372,19 @@ namespace <#= ns.NS #> return clone; } - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } - /// - public override bool Equals(object obj) - { - if (obj is BondRef) - return base.Equals(((BondRef) obj).Deref()); - return base.Equals(obj); - } + /// + public override bool Equals(object other) + { + if (other is BondRef) + return base.Equals(((BondRef)other).Deref()); + return base.Equals(other); + } public override string ToString() { @@ -408,11 +408,10 @@ namespace <#= ns.NS #> /// Compares a bond with this bond. /// /// Object of type Bond - /// true if the bond is equal to this bond + /// if the bond is equal to this bond public override bool Compare(object obj) { - var bond = obj as Bond; - if (bond == null) + if (!(obj is Bond bond)) return false; return !atoms.Any(atom => !bond.Contains(atom)); // bond order is ignored diff --git a/NCDK/TT/Bond.tt.cs b/NCDK/TT/Bond.tt.cs index 68db029e..bb80c231 100644 --- a/NCDK/TT/Bond.tt.cs +++ b/NCDK/TT/Bond.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -140,24 +141,24 @@ private void InitAtoms(IEnumerable atoms) { if (atoms == null) { - this.atoms = new ObservableChemObjectCollection(2, this); + this.atoms = new ObservableChemObjectCollection(2, this); } else { - this.atoms = new ObservableChemObjectCollection(this, atoms); + this.atoms = new ObservableChemObjectCollection(this, atoms); } } /// public virtual IList Atoms => atoms; - /// - public virtual int Index => -1; + /// + public virtual int Index => -1; - /// - public virtual IAtomContainer Container => null; + /// + public virtual IAtomContainer Container => null; - /// + /// public IAtom Begin => atoms.Count < 1 ? null : atoms[0]; /// @@ -184,7 +185,7 @@ public virtual IEnumerable GetConnectedAtoms(IAtom atom) { if (!atoms.Contains(atom)) return null; - return atoms.Where(n => n != atom); + return atoms.Where(n => n != atom); } /// @@ -202,8 +203,8 @@ public virtual bool Contains(IAtom atom) /// /// Sets the array of atoms making up this bond. /// - /// An array of atoms that forms this bond - /// + /// An array of atoms that forms this bond + /// public virtual void SetAtoms(IEnumerable atoms) { this.atoms.Clear(); @@ -344,19 +345,19 @@ public override ICDKObject Clone(CDKObjectMap map) return clone; } - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } - /// - public override bool Equals(object obj) - { - if (obj is BondRef) - return base.Equals(((BondRef) obj).Deref()); - return base.Equals(obj); - } + /// + public override bool Equals(object other) + { + if (other is BondRef) + return base.Equals(((BondRef)other).Deref()); + return base.Equals(other); + } public override string ToString() { @@ -380,11 +381,10 @@ public override string ToString() /// Compares a bond with this bond. /// /// Object of type Bond - /// true if the bond is equal to this bond + /// if the bond is equal to this bond public override bool Compare(object obj) { - var bond = obj as Bond; - if (bond == null) + if (!(obj is Bond bond)) return false; return !atoms.Any(atom => !bond.Contains(atom)); // bond order is ignored @@ -518,27 +518,27 @@ private void InitAtoms(IEnumerable atoms) { if (atoms == null) { - this.atoms = new List(2); + this.atoms = new List(2); } else { - int n = Math.Min(atoms.Count(), 2); - var list = new List(n); - list.AddRange(atoms); - this.atoms = list; + int n = Math.Min(atoms.Count(), 2); + var list = new List(n); + list.AddRange(atoms); + this.atoms = list; } } /// public virtual IList Atoms => atoms; - /// - public virtual int Index => -1; + /// + public virtual int Index => -1; - /// - public virtual IAtomContainer Container => null; + /// + public virtual IAtomContainer Container => null; - /// + /// public IAtom Begin => atoms.Count < 1 ? null : atoms[0]; /// @@ -565,7 +565,7 @@ public virtual IEnumerable GetConnectedAtoms(IAtom atom) { if (!atoms.Contains(atom)) return null; - return atoms.Where(n => n != atom); + return atoms.Where(n => n != atom); } /// @@ -583,8 +583,8 @@ public virtual bool Contains(IAtom atom) /// /// Sets the array of atoms making up this bond. /// - /// An array of atoms that forms this bond - /// + /// An array of atoms that forms this bond + /// public virtual void SetAtoms(IEnumerable atoms) { this.atoms.Clear(); @@ -718,19 +718,19 @@ public override ICDKObject Clone(CDKObjectMap map) return clone; } - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } - /// - public override bool Equals(object obj) - { - if (obj is BondRef) - return base.Equals(((BondRef) obj).Deref()); - return base.Equals(obj); - } + /// + public override bool Equals(object other) + { + if (other is BondRef) + return base.Equals(((BondRef)other).Deref()); + return base.Equals(other); + } public override string ToString() { @@ -754,11 +754,10 @@ public override string ToString() /// Compares a bond with this bond. /// /// Object of type Bond - /// true if the bond is equal to this bond + /// if the bond is equal to this bond public override bool Compare(object obj) { - var bond = obj as Bond; - if (bond == null) + if (!(obj is Bond bond)) return false; return !atoms.Any(atom => !bond.Contains(atom)); // bond order is ignored diff --git a/NCDK/TT/ChemFile.tt b/NCDK/TT/ChemFile.tt index fc01b894..1c33521f 100644 --- a/NCDK/TT/ChemFile.tt +++ b/NCDK/TT/ChemFile.tt @@ -27,6 +27,8 @@ using System.Collections; using System.Collections.Generic; using System.Text; +#pragma warning disable CA1710 // Identifiers should have correct suffix + <# foreach (var ns in namespaces) { @@ -40,14 +42,14 @@ namespace <#= ns.NS #> /// // @author steinbeck // @cdk.githash - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ChemFile : ChemObject, IChemFile, IChemObjectListener { /// /// List of ChemSquences. /// - protected IList chemSequences = new List(); + private IList chemSequences = new List(); /// /// Constructs an empty ChemFile. diff --git a/NCDK/TT/ChemFile.tt.cs b/NCDK/TT/ChemFile.tt.cs index 2f662758..14abe057 100644 --- a/NCDK/TT/ChemFile.tt.cs +++ b/NCDK/TT/ChemFile.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -28,6 +29,8 @@ using System.Collections.Generic; using System.Text; +#pragma warning disable CA1710 // Identifiers should have correct suffix + namespace NCDK.Default { /// @@ -37,14 +40,14 @@ namespace NCDK.Default /// // @author steinbeck // @cdk.githash - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ChemFile : ChemObject, IChemFile, IChemObjectListener { /// /// List of ChemSquences. /// - protected IList chemSequences = new List(); + private IList chemSequences = new List(); /// /// Constructs an empty ChemFile. @@ -195,14 +198,14 @@ namespace NCDK.Silent /// // @author steinbeck // @cdk.githash - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ChemFile : ChemObject, IChemFile, IChemObjectListener { /// /// List of ChemSquences. /// - protected IList chemSequences = new List(); + private IList chemSequences = new List(); /// /// Constructs an empty ChemFile. diff --git a/NCDK/TT/ChemModel.tt.cs b/NCDK/TT/ChemModel.tt.cs index d963f3be..03a60980 100644 --- a/NCDK/TT/ChemModel.tt.cs +++ b/NCDK/TT/ChemModel.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara diff --git a/NCDK/TT/ChemObject.tt b/NCDK/TT/ChemObject.tt index 7eaaaead..bf19868a 100644 --- a/NCDK/TT/ChemObject.tt +++ b/NCDK/TT/ChemObject.tt @@ -28,8 +28,9 @@ */ using NCDK.Common.Collections; -using System; using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Security.Permissions; <# foreach (var ns in namespaces) @@ -46,11 +47,34 @@ namespace <#= ns.NS #> // @author steinbeck // @cdk.githash // @cdk.module data - [Serializable] public class ChemObject - : IChemObject + : IChemObject, ISerializable { + private bool isPlaced; + private bool isVisited; + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue(nameof(isPlaced), isPlaced); + info.AddValue(nameof(isVisited), isVisited); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected ChemObject(SerializationInfo info, StreamingContext context) + { + isPlaced = info.GetBoolean(nameof(isPlaced)); + isVisited = info.GetBoolean(nameof(isVisited)); + } + + [System.NonSerialized] private ICollection listeners; + + [System.NonSerialized] + private bool notification = true; + + public virtual IChemObjectBuilder Builder => ChemObjectBuilder.Instance; + /// /// List for listener administration. /// @@ -67,10 +91,13 @@ namespace <#= ns.NS #> return listeners; } } - public bool Notification { get; set; } = true; - public virtual IChemObjectBuilder Builder => ChemObjectBuilder.Instance; - private bool isPlaced; + public bool Notification + { + get => notification; + set => notification = value; + } + public bool IsPlaced { get { return isPlaced; } @@ -83,7 +110,6 @@ namespace <#= ns.NS #> } } - private bool isVisited; /// /// Flag is set if chemobject has been visited /// diff --git a/NCDK/TT/ChemObject.tt.cs b/NCDK/TT/ChemObject.tt.cs index ef9f70dc..e723be93 100644 --- a/NCDK/TT/ChemObject.tt.cs +++ b/NCDK/TT/ChemObject.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -29,8 +30,9 @@ */ using NCDK.Common.Collections; -using System; using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Security.Permissions; namespace NCDK.Default { @@ -42,11 +44,34 @@ namespace NCDK.Default // @author steinbeck // @cdk.githash // @cdk.module data - [Serializable] public class ChemObject - : IChemObject + : IChemObject, ISerializable { + private bool isPlaced; + private bool isVisited; + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue(nameof(isPlaced), isPlaced); + info.AddValue(nameof(isVisited), isVisited); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected ChemObject(SerializationInfo info, StreamingContext context) + { + isPlaced = info.GetBoolean(nameof(isPlaced)); + isVisited = info.GetBoolean(nameof(isVisited)); + } + + [System.NonSerialized] private ICollection listeners; + + [System.NonSerialized] + private bool notification = true; + + public virtual IChemObjectBuilder Builder => ChemObjectBuilder.Instance; + /// /// List for listener administration. /// @@ -59,10 +84,13 @@ public ICollection Listeners return listeners; } } - public bool Notification { get; set; } = true; - public virtual IChemObjectBuilder Builder => ChemObjectBuilder.Instance; - private bool isPlaced; + public bool Notification + { + get => notification; + set => notification = value; + } + public bool IsPlaced { get { return isPlaced; } @@ -73,7 +101,6 @@ public bool IsPlaced } } - private bool isVisited; /// /// Flag is set if chemobject has been visited /// @@ -152,7 +179,7 @@ public virtual void NotifyChanged(ChemObjectChangeEventArgs evt) /// /// A dictionary for the storage of any kind of properties of this object. /// - IDictionary properties; + private Dictionary properties; private void InitProperties() { @@ -160,7 +187,7 @@ private void InitProperties() } /// - public virtual void SetProperty(object description, object property) + public virtual void SetProperty(object description, object value) { #if DEBUG if (description != null && !AcceptablePropertyKeyTypes.Contains(description.GetType())) @@ -168,7 +195,7 @@ public virtual void SetProperty(object description, object property) #endif if (this.properties == null) InitProperties(); - properties[description] = property; + properties[description] = value; NotifyChanged(); } @@ -210,10 +237,10 @@ public virtual T GetProperty(object description, T defaultValue) return defaultValue; } - private static readonly IDictionary emptyProperties = new System.Collections.ObjectModel.ReadOnlyDictionary(new Dictionary(0)); + private static readonly IReadOnlyDictionary emptyProperties = NCDK.Common.Collections.Dictionaries.Empty(); /// - public virtual IDictionary GetProperties() + public virtual IReadOnlyDictionary GetProperties() { if (this.properties == null) return emptyProperties; @@ -294,11 +321,34 @@ namespace NCDK.Silent // @author steinbeck // @cdk.githash // @cdk.module data - [Serializable] public class ChemObject - : IChemObject + : IChemObject, ISerializable { + private bool isPlaced; + private bool isVisited; + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue(nameof(isPlaced), isPlaced); + info.AddValue(nameof(isVisited), isVisited); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected ChemObject(SerializationInfo info, StreamingContext context) + { + isPlaced = info.GetBoolean(nameof(isPlaced)); + isVisited = info.GetBoolean(nameof(isVisited)); + } + + [System.NonSerialized] private ICollection listeners; + + [System.NonSerialized] + private bool notification = true; + + public virtual IChemObjectBuilder Builder => ChemObjectBuilder.Instance; + /// /// List for listener administration. /// @@ -311,10 +361,13 @@ public ICollection Listeners return listeners; } } - public bool Notification { get; set; } = true; - public virtual IChemObjectBuilder Builder => ChemObjectBuilder.Instance; - private bool isPlaced; + public bool Notification + { + get => notification; + set => notification = value; + } + public bool IsPlaced { get { return isPlaced; } @@ -324,7 +377,6 @@ public bool IsPlaced } } - private bool isVisited; /// /// Flag is set if chemobject has been visited /// @@ -393,7 +445,7 @@ public virtual void NotifyChanged(ChemObjectChangeEventArgs evt) /// /// A dictionary for the storage of any kind of properties of this object. /// - IDictionary properties; + private Dictionary properties; private void InitProperties() { @@ -401,7 +453,7 @@ private void InitProperties() } /// - public virtual void SetProperty(object description, object property) + public virtual void SetProperty(object description, object value) { #if DEBUG if (description != null && !AcceptablePropertyKeyTypes.Contains(description.GetType())) @@ -409,7 +461,7 @@ public virtual void SetProperty(object description, object property) #endif if (this.properties == null) InitProperties(); - properties[description] = property; + properties[description] = value; } /// @@ -448,10 +500,10 @@ public virtual T GetProperty(object description, T defaultValue) return defaultValue; } - private static readonly IDictionary emptyProperties = new System.Collections.ObjectModel.ReadOnlyDictionary(new Dictionary(0)); + private static readonly IReadOnlyDictionary emptyProperties = NCDK.Common.Collections.Dictionaries.Empty(); /// - public virtual IDictionary GetProperties() + public virtual IReadOnlyDictionary GetProperties() { if (this.properties == null) return emptyProperties; diff --git a/NCDK/TT/ChemObjectBuilder.tt b/NCDK/TT/ChemObjectBuilder.tt index ead901ce..f6953320 100644 --- a/NCDK/TT/ChemObjectBuilder.tt +++ b/NCDK/TT/ChemObjectBuilder.tt @@ -58,23 +58,23 @@ namespace <#= ns.NS #> private bool LegacyAtomContainer { get; set; } - internal ChemObjectBuilder() - { + internal ChemObjectBuilder() + { var val = System.Environment.GetEnvironmentVariable("NCDKUseLegacyAtomContainer"); if (string.IsNullOrWhiteSpace(val)) LegacyAtomContainer = false; else { val = val.Trim(); - switch (val.ToLowerInvariant()) + switch (val.ToUpperInvariant()) { - case "t": - case "true": + case "T": + case "TRUE": case "1": LegacyAtomContainer = true; break; - case "f": - case "false": + case "F": + case "FALSE": case "0": LegacyAtomContainer = false; break; @@ -82,21 +82,23 @@ namespace <#= ns.NS #> throw new InvalidOperationException("Invalid value, expected true/false: " + val); } } - } + } - internal ChemObjectBuilder(bool legacyAtomContainer) - { - this.LegacyAtomContainer = legacyAtomContainer; - } + internal ChemObjectBuilder(bool legacyAtomContainer) + { + this.LegacyAtomContainer = legacyAtomContainer; + } +#pragma warning disable CA1822 public T New() where T : IAtomContainer, new() => new T(); +#pragma warning restore // elements public IAtom NewAtom() => new Atom(); public IAtom NewAtom(IElement element) => new Atom(element); - public IAtom NewAtom(int elem) => new Atom(elem); - public IAtom NewAtom(int elem, int hcnt) => new Atom(elem, hcnt); - public IAtom NewAtom(int elem, int hcnt, int fchg) => new Atom(elem, hcnt, fchg); + public IAtom NewAtom(int elem) => new Atom(elem); + public IAtom NewAtom(int elem, int hcnt) => new Atom(elem, hcnt); + public IAtom NewAtom(int elem, int hcnt, int fchg) => new Atom(elem, hcnt, fchg); public IAtom NewAtom(string elementSymbol) => new Atom(elementSymbol); public IAtom NewAtom(string elementSymbol, Vector2 point2d) => new Atom(elementSymbol, point2d); public IAtom NewAtom(string elementSymbol, Vector3 point3d) => new Atom(elementSymbol, point3d); @@ -177,21 +179,21 @@ namespace <#= ns.NS #> public ISubstance NewSubstance() => new Substance(); // stereo components (requires some modification after instantiation) - public ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IEnumerable ligandAtoms, TetrahedralStereo chirality) + public ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligandAtoms, TetrahedralStereo chirality) { var o = new TetrahedralChirality(chiralAtom, ligandAtoms, chirality) - { - Builder = this, - }; + { + Builder = this, + }; return o; } public IDoubleBondStereochemistry CreateDoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBonds, DoubleBondConformation stereo) { var o = new DoubleBondStereochemistry(stereoBond, ligandBonds, stereo) - { - Builder = this, - }; + { + Builder = this, + }; return o; } diff --git a/NCDK/TT/ChemObjectBuilder.tt.cs b/NCDK/TT/ChemObjectBuilder.tt.cs index 414a4d4c..b73fd72d 100644 --- a/NCDK/TT/ChemObjectBuilder.tt.cs +++ b/NCDK/TT/ChemObjectBuilder.tt.cs @@ -1,6 +1,7 @@  + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -55,23 +56,23 @@ public sealed class ChemObjectBuilder private bool LegacyAtomContainer { get; set; } - internal ChemObjectBuilder() - { + internal ChemObjectBuilder() + { var val = System.Environment.GetEnvironmentVariable("NCDKUseLegacyAtomContainer"); if (string.IsNullOrWhiteSpace(val)) LegacyAtomContainer = false; else { val = val.Trim(); - switch (val.ToLowerInvariant()) + switch (val.ToUpperInvariant()) { - case "t": - case "true": + case "T": + case "TRUE": case "1": LegacyAtomContainer = true; break; - case "f": - case "false": + case "F": + case "FALSE": case "0": LegacyAtomContainer = false; break; @@ -79,21 +80,23 @@ internal ChemObjectBuilder() throw new InvalidOperationException("Invalid value, expected true/false: " + val); } } - } + } - internal ChemObjectBuilder(bool legacyAtomContainer) - { - this.LegacyAtomContainer = legacyAtomContainer; - } + internal ChemObjectBuilder(bool legacyAtomContainer) + { + this.LegacyAtomContainer = legacyAtomContainer; + } +#pragma warning disable CA1822 public T New() where T : IAtomContainer, new() => new T(); +#pragma warning restore // elements public IAtom NewAtom() => new Atom(); public IAtom NewAtom(IElement element) => new Atom(element); - public IAtom NewAtom(int elem) => new Atom(elem); - public IAtom NewAtom(int elem, int hcnt) => new Atom(elem, hcnt); - public IAtom NewAtom(int elem, int hcnt, int fchg) => new Atom(elem, hcnt, fchg); + public IAtom NewAtom(int elem) => new Atom(elem); + public IAtom NewAtom(int elem, int hcnt) => new Atom(elem, hcnt); + public IAtom NewAtom(int elem, int hcnt, int fchg) => new Atom(elem, hcnt, fchg); public IAtom NewAtom(string elementSymbol) => new Atom(elementSymbol); public IAtom NewAtom(string elementSymbol, Vector2 point2d) => new Atom(elementSymbol, point2d); public IAtom NewAtom(string elementSymbol, Vector3 point3d) => new Atom(elementSymbol, point3d); @@ -174,21 +177,21 @@ internal ChemObjectBuilder(bool legacyAtomContainer) public ISubstance NewSubstance() => new Substance(); // stereo components (requires some modification after instantiation) - public ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IEnumerable ligandAtoms, TetrahedralStereo chirality) + public ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligandAtoms, TetrahedralStereo chirality) { var o = new TetrahedralChirality(chiralAtom, ligandAtoms, chirality) - { - Builder = this, - }; + { + Builder = this, + }; return o; } public IDoubleBondStereochemistry CreateDoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBonds, DoubleBondConformation stereo) { var o = new DoubleBondStereochemistry(stereoBond, ligandBonds, stereo) - { - Builder = this, - }; + { + Builder = this, + }; return o; } @@ -223,23 +226,23 @@ public sealed class ChemObjectBuilder private bool LegacyAtomContainer { get; set; } - internal ChemObjectBuilder() - { + internal ChemObjectBuilder() + { var val = System.Environment.GetEnvironmentVariable("NCDKUseLegacyAtomContainer"); if (string.IsNullOrWhiteSpace(val)) LegacyAtomContainer = false; else { val = val.Trim(); - switch (val.ToLowerInvariant()) + switch (val.ToUpperInvariant()) { - case "t": - case "true": + case "T": + case "TRUE": case "1": LegacyAtomContainer = true; break; - case "f": - case "false": + case "F": + case "FALSE": case "0": LegacyAtomContainer = false; break; @@ -247,21 +250,23 @@ internal ChemObjectBuilder() throw new InvalidOperationException("Invalid value, expected true/false: " + val); } } - } + } - internal ChemObjectBuilder(bool legacyAtomContainer) - { - this.LegacyAtomContainer = legacyAtomContainer; - } + internal ChemObjectBuilder(bool legacyAtomContainer) + { + this.LegacyAtomContainer = legacyAtomContainer; + } +#pragma warning disable CA1822 public T New() where T : IAtomContainer, new() => new T(); +#pragma warning restore // elements public IAtom NewAtom() => new Atom(); public IAtom NewAtom(IElement element) => new Atom(element); - public IAtom NewAtom(int elem) => new Atom(elem); - public IAtom NewAtom(int elem, int hcnt) => new Atom(elem, hcnt); - public IAtom NewAtom(int elem, int hcnt, int fchg) => new Atom(elem, hcnt, fchg); + public IAtom NewAtom(int elem) => new Atom(elem); + public IAtom NewAtom(int elem, int hcnt) => new Atom(elem, hcnt); + public IAtom NewAtom(int elem, int hcnt, int fchg) => new Atom(elem, hcnt, fchg); public IAtom NewAtom(string elementSymbol) => new Atom(elementSymbol); public IAtom NewAtom(string elementSymbol, Vector2 point2d) => new Atom(elementSymbol, point2d); public IAtom NewAtom(string elementSymbol, Vector3 point3d) => new Atom(elementSymbol, point3d); @@ -342,21 +347,21 @@ internal ChemObjectBuilder(bool legacyAtomContainer) public ISubstance NewSubstance() => new Substance(); // stereo components (requires some modification after instantiation) - public ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IEnumerable ligandAtoms, TetrahedralStereo chirality) + public ITetrahedralChirality NewTetrahedralChirality(IAtom chiralAtom, IReadOnlyList ligandAtoms, TetrahedralStereo chirality) { var o = new TetrahedralChirality(chiralAtom, ligandAtoms, chirality) - { - Builder = this, - }; + { + Builder = this, + }; return o; } public IDoubleBondStereochemistry CreateDoubleBondStereochemistry(IBond stereoBond, IEnumerable ligandBonds, DoubleBondConformation stereo) { var o = new DoubleBondStereochemistry(stereoBond, ligandBonds, stereo) - { - Builder = this, - }; + { + Builder = this, + }; return o; } diff --git a/NCDK/TT/ChemSequence.tt b/NCDK/TT/ChemSequence.tt index 57f1d204..283d9d9c 100644 --- a/NCDK/TT/ChemSequence.tt +++ b/NCDK/TT/ChemSequence.tt @@ -41,7 +41,8 @@ namespace <#= ns.NS #> // @cdk.githash // @cdk.keyword animation // @cdk.keyword reaction - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] + [Serializable] public class ChemSequence : ChemObject, IChemSequence, IChemObjectListener, ICloneable { diff --git a/NCDK/TT/ChemSequence.tt.cs b/NCDK/TT/ChemSequence.tt.cs index 6027f468..50db3fa4 100644 --- a/NCDK/TT/ChemSequence.tt.cs +++ b/NCDK/TT/ChemSequence.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -38,7 +39,8 @@ namespace NCDK.Default // @cdk.githash // @cdk.keyword animation // @cdk.keyword reaction - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] + [Serializable] public class ChemSequence : ChemObject, IChemSequence, IChemObjectListener, ICloneable { @@ -137,7 +139,8 @@ namespace NCDK.Silent // @cdk.githash // @cdk.keyword animation // @cdk.keyword reaction - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] + [Serializable] public class ChemSequence : ChemObject, IChemSequence, IChemObjectListener, ICloneable { diff --git a/NCDK/TT/Crystal.tt b/NCDK/TT/Crystal.tt index be966b2c..10086a51 100644 --- a/NCDK/TT/Crystal.tt +++ b/NCDK/TT/Crystal.tt @@ -43,6 +43,7 @@ namespace <#= ns.NS #> /// // @cdk.githash // @cdk.keyword crystal + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Crystal : AtomContainer, ICrystal, ICloneable diff --git a/NCDK/TT/Crystal.tt.cs b/NCDK/TT/Crystal.tt.cs index 7be4d2fc..3a34f7fc 100644 --- a/NCDK/TT/Crystal.tt.cs +++ b/NCDK/TT/Crystal.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -40,6 +41,7 @@ namespace NCDK.Default /// // @cdk.githash // @cdk.keyword crystal + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Crystal : AtomContainer, ICrystal, ICloneable @@ -151,6 +153,7 @@ namespace NCDK.Silent /// // @cdk.githash // @cdk.keyword crystal + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Crystal : AtomContainer, ICrystal, ICloneable diff --git a/NCDK/TT/ElectronContainer.tt b/NCDK/TT/ElectronContainer.tt index 3e60e0be..404616af 100644 --- a/NCDK/TT/ElectronContainer.tt +++ b/NCDK/TT/ElectronContainer.tt @@ -22,7 +22,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using System; +using System.Runtime.Serialization; +using System.Security.Permissions; using System.Text; <# @@ -38,15 +41,29 @@ namespace <#= ns.NS #> // @cdk.keyword orbital // @cdk.keyword lone-pair // @cdk.keyword bond - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ElectronContainer - : ChemObject, IElectronContainer, ICloneable + : ChemObject, IElectronContainer, ICloneable, ISerializable { /// /// Constructs an empty ElectronContainer. /// private int? electronCount = 0; + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(electronCount), electronCount); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected ElectronContainer(SerializationInfo info, StreamingContext context) + : base(info, context) + { + electronCount = info.GetNullable(nameof(electronCount)); + } + /// /// Returns the number of electrons in this electron container. /// diff --git a/NCDK/TT/ElectronContainer.tt.cs b/NCDK/TT/ElectronContainer.tt.cs index ad80b774..84f6436c 100644 --- a/NCDK/TT/ElectronContainer.tt.cs +++ b/NCDK/TT/ElectronContainer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -23,7 +24,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using System; +using System.Runtime.Serialization; +using System.Security.Permissions; using System.Text; namespace NCDK.Default @@ -35,15 +39,29 @@ namespace NCDK.Default // @cdk.keyword orbital // @cdk.keyword lone-pair // @cdk.keyword bond - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ElectronContainer - : ChemObject, IElectronContainer, ICloneable + : ChemObject, IElectronContainer, ICloneable, ISerializable { /// /// Constructs an empty ElectronContainer. /// private int? electronCount = 0; + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(electronCount), electronCount); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected ElectronContainer(SerializationInfo info, StreamingContext context) + : base(info, context) + { + electronCount = info.GetNullable(nameof(electronCount)); + } + /// /// Returns the number of electrons in this electron container. /// @@ -87,15 +105,29 @@ namespace NCDK.Silent // @cdk.keyword orbital // @cdk.keyword lone-pair // @cdk.keyword bond - [Serializable] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ElectronContainer - : ChemObject, IElectronContainer, ICloneable + : ChemObject, IElectronContainer, ICloneable, ISerializable { /// /// Constructs an empty ElectronContainer. /// private int? electronCount = 0; + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(electronCount), electronCount); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected ElectronContainer(SerializationInfo info, StreamingContext context) + : base(info, context) + { + electronCount = info.GetNullable(nameof(electronCount)); + } + /// /// Returns the number of electrons in this electron container. /// diff --git a/NCDK/TT/Element.tt b/NCDK/TT/Element.tt index d6e3854a..8495a540 100644 --- a/NCDK/TT/Element.tt +++ b/NCDK/TT/Element.tt @@ -22,9 +22,11 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using NCDK.Config; using System; -using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Security.Permissions; using System.Text; <# @@ -43,9 +45,8 @@ namespace <#= ns.NS #> /// // @cdk.githash // @cdk.keyword element - [Serializable] public class Element - : ChemObject, IElement, ICloneable + : ChemObject, IElement, ICloneable, ISerializable { /// The element symbol for this element as listed in the periodic table. internal string symbol; @@ -53,6 +54,22 @@ namespace <#= ns.NS #> /// The atomic number for this element giving their position in the periodic table. internal int? atomicNumber; + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(symbol), symbol); + info.AddNullableValue(nameof(atomicNumber), atomicNumber); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected Element(SerializationInfo info, StreamingContext context) + : base(info, context) + { + symbol = info.GetString(nameof(symbol)); + atomicNumber = info.GetNullable(nameof(atomicNumber)); + } + /// /// Constructs an empty Element. /// @@ -102,7 +119,7 @@ namespace <#= ns.NS #> /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Elements can be configured by using /// the method: - /// + /// /// public virtual int? AtomicNumber { @@ -155,8 +172,7 @@ namespace <#= ns.NS #> /// true if the atom types are equal public override bool Compare(object obj) { - var elem = obj as Element; - if (elem == null) + if (!(obj is Element elem)) return false; if (!base.Compare(obj)) return false; diff --git a/NCDK/TT/Element.tt.cs b/NCDK/TT/Element.tt.cs index 469920ff..6440635e 100644 --- a/NCDK/TT/Element.tt.cs +++ b/NCDK/TT/Element.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -23,9 +24,11 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using NCDK.Config; using System; -using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Security.Permissions; using System.Text; namespace NCDK.Default @@ -40,9 +43,8 @@ namespace NCDK.Default /// // @cdk.githash // @cdk.keyword element - [Serializable] public class Element - : ChemObject, IElement, ICloneable + : ChemObject, IElement, ICloneable, ISerializable { /// The element symbol for this element as listed in the periodic table. internal string symbol; @@ -50,6 +52,22 @@ public class Element /// The atomic number for this element giving their position in the periodic table. internal int? atomicNumber; + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(symbol), symbol); + info.AddNullableValue(nameof(atomicNumber), atomicNumber); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected Element(SerializationInfo info, StreamingContext context) + : base(info, context) + { + symbol = info.GetString(nameof(symbol)); + atomicNumber = info.GetNullable(nameof(atomicNumber)); + } + /// /// Constructs an empty Element. /// @@ -99,7 +117,7 @@ public Element(string symbol, int? atomicNumber) /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Elements can be configured by using /// the method: - /// + /// /// public virtual int? AtomicNumber { @@ -148,8 +166,7 @@ public override string ToString() /// true if the atom types are equal public override bool Compare(object obj) { - var elem = obj as Element; - if (elem == null) + if (!(obj is Element elem)) return false; if (!base.Compare(obj)) return false; @@ -169,9 +186,8 @@ namespace NCDK.Silent /// // @cdk.githash // @cdk.keyword element - [Serializable] public class Element - : ChemObject, IElement, ICloneable + : ChemObject, IElement, ICloneable, ISerializable { /// The element symbol for this element as listed in the periodic table. internal string symbol; @@ -179,6 +195,22 @@ public class Element /// The atomic number for this element giving their position in the periodic table. internal int? atomicNumber; + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue(nameof(symbol), symbol); + info.AddNullableValue(nameof(atomicNumber), atomicNumber); + } + + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + protected Element(SerializationInfo info, StreamingContext context) + : base(info, context) + { + symbol = info.GetString(nameof(symbol)); + atomicNumber = info.GetNullable(nameof(atomicNumber)); + } + /// /// Constructs an empty Element. /// @@ -228,7 +260,7 @@ public Element(string symbol, int? atomicNumber) /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Elements can be configured by using /// the method: - /// + /// /// public virtual int? AtomicNumber { @@ -275,8 +307,7 @@ public override string ToString() /// true if the atom types are equal public override bool Compare(object obj) { - var elem = obj as Element; - if (elem == null) + if (!(obj is Element elem)) return false; if (!base.Compare(obj)) return false; diff --git a/NCDK/TT/EnzymeResidueLocator.tt.cs b/NCDK/TT/EnzymeResidueLocator.tt.cs index e5a0a2e3..c2a9ca2e 100644 --- a/NCDK/TT/EnzymeResidueLocator.tt.cs +++ b/NCDK/TT/EnzymeResidueLocator.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara diff --git a/NCDK/TT/FragmentAtom.tt.cs b/NCDK/TT/FragmentAtom.tt.cs index b54c4921..0afab217 100644 --- a/NCDK/TT/FragmentAtom.tt.cs +++ b/NCDK/TT/FragmentAtom.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara diff --git a/NCDK/TT/Isotope.tt b/NCDK/TT/Isotope.tt index f9bb96ae..7a28c76b 100644 --- a/NCDK/TT/Isotope.tt +++ b/NCDK/TT/Isotope.tt @@ -26,8 +26,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using System; -using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; @@ -42,26 +42,44 @@ namespace <#= ns.NS #> /// /// /// For example, an carbon 13 isotope can be created with: - /// + /// /// A full specification can be constructed with: - /// + /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using /// the method: - /// + /// /// // @cdk.githash // @author steinbeck // @cdk.created 2001-08-21 // @cdk.keyword isotope - [Serializable] public class Isotope - : Element, IIsotope, ICloneable + : Element, IIsotope, ICloneable, ISerializable { private double? naturalAbundance; private double? exactMass; private int? massNumber; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(naturalAbundance), naturalAbundance); + info.AddNullableValue(nameof(exactMass), exactMass); + info.AddNullableValue(nameof(massNumber), massNumber); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected Isotope(SerializationInfo info, StreamingContext context) + : base(info, context) + { + symbol = info.GetString(nameof(symbol)); + naturalAbundance = info.GetNullable(nameof(naturalAbundance)); + exactMass = info.GetNullable(nameof(exactMass)); + massNumber = info.GetNullable(nameof(massNumber)); + } + /// /// Constructor for the Isotope object. /// @@ -120,11 +138,11 @@ namespace <#= ns.NS #> /// abundance and mass number are copied too. /// /// to copy information from - public Isotope(IElement element) + public Isotope(IElement element) : base(element) { if (element is IIsotope isotope) - { + { this.exactMass = isotope.ExactMass; this.naturalAbundance = isotope.NaturalAbundance; this.massNumber = isotope.MassNumber; @@ -137,8 +155,8 @@ namespace <#= ns.NS #> /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual double? NaturalAbundance { @@ -158,8 +176,8 @@ namespace <#= ns.NS #> /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual double? ExactMass { @@ -179,8 +197,8 @@ namespace <#= ns.NS #> /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual int? MassNumber { @@ -216,8 +234,7 @@ namespace <#= ns.NS #> /// true if the isotopes are equal public override bool Compare(object obj) { - var isotope = obj as Isotope; - return isotope != null && base.Compare(obj) + return obj is Isotope isotope && base.Compare(obj) && isotope.MassNumber == MassNumber && NearlyEquals(isotope.ExactMass, ExactMass) && NearlyEquals(isotope.NaturalAbundance, NaturalAbundance); diff --git a/NCDK/TT/Isotope.tt.cs b/NCDK/TT/Isotope.tt.cs index f7da2525..98601c08 100644 --- a/NCDK/TT/Isotope.tt.cs +++ b/NCDK/TT/Isotope.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -27,8 +28,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Common.Serialization; using System; -using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; @@ -39,26 +40,44 @@ namespace NCDK.Default /// /// /// For example, an carbon 13 isotope can be created with: - /// + /// /// A full specification can be constructed with: - /// + /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using /// the method: - /// + /// /// // @cdk.githash // @author steinbeck // @cdk.created 2001-08-21 // @cdk.keyword isotope - [Serializable] public class Isotope - : Element, IIsotope, ICloneable + : Element, IIsotope, ICloneable, ISerializable { private double? naturalAbundance; private double? exactMass; private int? massNumber; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(naturalAbundance), naturalAbundance); + info.AddNullableValue(nameof(exactMass), exactMass); + info.AddNullableValue(nameof(massNumber), massNumber); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected Isotope(SerializationInfo info, StreamingContext context) + : base(info, context) + { + symbol = info.GetString(nameof(symbol)); + naturalAbundance = info.GetNullable(nameof(naturalAbundance)); + exactMass = info.GetNullable(nameof(exactMass)); + massNumber = info.GetNullable(nameof(massNumber)); + } + /// /// Constructor for the Isotope object. /// @@ -117,11 +136,11 @@ public Isotope(string elementSymbol, int massNumber) /// abundance and mass number are copied too. /// /// to copy information from - public Isotope(IElement element) + public Isotope(IElement element) : base(element) { if (element is IIsotope isotope) - { + { this.exactMass = isotope.ExactMass; this.naturalAbundance = isotope.NaturalAbundance; this.massNumber = isotope.MassNumber; @@ -134,8 +153,8 @@ public Isotope(IElement element) /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual double? NaturalAbundance { @@ -153,8 +172,8 @@ public virtual double? NaturalAbundance /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual double? ExactMass { @@ -172,8 +191,8 @@ public virtual double? ExactMass /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual int? MassNumber { @@ -207,8 +226,7 @@ public override string ToString() /// true if the isotopes are equal public override bool Compare(object obj) { - var isotope = obj as Isotope; - return isotope != null && base.Compare(obj) + return obj is Isotope isotope && base.Compare(obj) && isotope.MassNumber == MassNumber && NearlyEquals(isotope.ExactMass, ExactMass) && NearlyEquals(isotope.NaturalAbundance, NaturalAbundance); @@ -232,26 +250,44 @@ namespace NCDK.Silent /// /// /// For example, an carbon 13 isotope can be created with: - /// + /// /// A full specification can be constructed with: - /// + /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using /// the method: - /// + /// /// // @cdk.githash // @author steinbeck // @cdk.created 2001-08-21 // @cdk.keyword isotope - [Serializable] public class Isotope - : Element, IIsotope, ICloneable + : Element, IIsotope, ICloneable, ISerializable { private double? naturalAbundance; private double? exactMass; private int? massNumber; + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddNullableValue(nameof(naturalAbundance), naturalAbundance); + info.AddNullableValue(nameof(exactMass), exactMass); + info.AddNullableValue(nameof(massNumber), massNumber); + } + + [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)] + protected Isotope(SerializationInfo info, StreamingContext context) + : base(info, context) + { + symbol = info.GetString(nameof(symbol)); + naturalAbundance = info.GetNullable(nameof(naturalAbundance)); + exactMass = info.GetNullable(nameof(exactMass)); + massNumber = info.GetNullable(nameof(massNumber)); + } + /// /// Constructor for the Isotope object. /// @@ -310,11 +346,11 @@ public Isotope(string elementSymbol, int massNumber) /// abundance and mass number are copied too. /// /// to copy information from - public Isotope(IElement element) + public Isotope(IElement element) : base(element) { if (element is IIsotope isotope) - { + { this.exactMass = isotope.ExactMass; this.naturalAbundance = isotope.NaturalAbundance; this.massNumber = isotope.MassNumber; @@ -327,8 +363,8 @@ public Isotope(IElement element) /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual double? NaturalAbundance { @@ -345,8 +381,8 @@ public virtual double? NaturalAbundance /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual double? ExactMass { @@ -363,8 +399,8 @@ public virtual double? ExactMass /// /// Once instantiated all field not filled by passing parameters /// to the constructor are null. Isotopes can be configured by using - /// the method: - /// + /// the method: + /// /// public virtual int? MassNumber { @@ -397,8 +433,7 @@ public override string ToString() /// true if the isotopes are equal public override bool Compare(object obj) { - var isotope = obj as Isotope; - return isotope != null && base.Compare(obj) + return obj is Isotope isotope && base.Compare(obj) && isotope.MassNumber == MassNumber && NearlyEquals(isotope.ExactMass, ExactMass) && NearlyEquals(isotope.NaturalAbundance, NaturalAbundance); diff --git a/NCDK/TT/LonePair.tt b/NCDK/TT/LonePair.tt index c0ed412b..4e67df52 100644 --- a/NCDK/TT/LonePair.tt +++ b/NCDK/TT/LonePair.tt @@ -44,10 +44,10 @@ namespace <#= ns.NS #> : ElectronContainer, ILonePair, ICloneable { /// Number of electrons in the lone pair. - protected readonly int electronCount = 2; + private readonly int electronCount = 2; /// The atom with which this lone pair is associated. - protected IAtom atom; + private IAtom atom; /// /// Constructs an unconnected lone pair. diff --git a/NCDK/TT/LonePair.tt.cs b/NCDK/TT/LonePair.tt.cs index 211fb53b..95036fd8 100644 --- a/NCDK/TT/LonePair.tt.cs +++ b/NCDK/TT/LonePair.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -41,10 +42,10 @@ public class LonePair : ElectronContainer, ILonePair, ICloneable { /// Number of electrons in the lone pair. - protected readonly int electronCount = 2; + private readonly int electronCount = 2; /// The atom with which this lone pair is associated. - protected IAtom atom; + private IAtom atom; /// /// Constructs an unconnected lone pair. @@ -135,10 +136,10 @@ public class LonePair : ElectronContainer, ILonePair, ICloneable { /// Number of electrons in the lone pair. - protected readonly int electronCount = 2; + private readonly int electronCount = 2; /// The atom with which this lone pair is associated. - protected IAtom atom; + private IAtom atom; /// /// Constructs an unconnected lone pair. diff --git a/NCDK/TT/Mapping.tt.cs b/NCDK/TT/Mapping.tt.cs index 90b18ff4..88c68198 100644 --- a/NCDK/TT/Mapping.tt.cs +++ b/NCDK/TT/Mapping.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara diff --git a/NCDK/TT/Monomer.tt b/NCDK/TT/Monomer.tt index 1fd4ca9b..fd3c882d 100644 --- a/NCDK/TT/Monomer.tt +++ b/NCDK/TT/Monomer.tt @@ -43,6 +43,7 @@ namespace <#= ns.NS #> // @author Edgar Luttmann // @cdk.created 2001-08-06 // @cdk.keyword monomer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Monomer : AtomContainer, IMonomer, ICloneable diff --git a/NCDK/TT/Monomer.tt.cs b/NCDK/TT/Monomer.tt.cs index 4867937d..22e20f4b 100644 --- a/NCDK/TT/Monomer.tt.cs +++ b/NCDK/TT/Monomer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -40,6 +41,7 @@ namespace NCDK.Default // @author Edgar Luttmann // @cdk.created 2001-08-06 // @cdk.keyword monomer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Monomer : AtomContainer, IMonomer, ICloneable @@ -102,6 +104,7 @@ namespace NCDK.Silent // @author Edgar Luttmann // @cdk.created 2001-08-06 // @cdk.keyword monomer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Monomer : AtomContainer, IMonomer, ICloneable diff --git a/NCDK/TT/PDBAtom.tt b/NCDK/TT/PDBAtom.tt index c25c29f8..3b9d1297 100644 --- a/NCDK/TT/PDBAtom.tt +++ b/NCDK/TT/PDBAtom.tt @@ -93,7 +93,7 @@ namespace <#= ns.NS #> Oxt = false; HetAtom = false; - base.ImplicitHydrogenCount = null; + base.ImplicitHydrogenCount = null; base.Charge = 0.0; base.FormalCharge = 0; } diff --git a/NCDK/TT/PDBAtom.tt.cs b/NCDK/TT/PDBAtom.tt.cs index 82fd4bd0..b5b6354e 100644 --- a/NCDK/TT/PDBAtom.tt.cs +++ b/NCDK/TT/PDBAtom.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -90,7 +91,7 @@ private void InitValues() Oxt = false; HetAtom = false; - base.ImplicitHydrogenCount = null; + base.ImplicitHydrogenCount = null; base.Charge = 0.0; base.FormalCharge = 0; } @@ -244,7 +245,7 @@ private void InitValues() Oxt = false; HetAtom = false; - base.ImplicitHydrogenCount = null; + base.ImplicitHydrogenCount = null; base.Charge = 0.0; base.FormalCharge = 0; } diff --git a/NCDK/TT/PDBMonomer.tt b/NCDK/TT/PDBMonomer.tt index 65ca6c61..3289d92e 100644 --- a/NCDK/TT/PDBMonomer.tt +++ b/NCDK/TT/PDBMonomer.tt @@ -26,10 +26,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Silent; using System; using System.Collections.Generic; using System.Linq; -using NCDK.Default; using System.Text; <# diff --git a/NCDK/TT/PDBMonomer.tt.cs b/NCDK/TT/PDBMonomer.tt.cs index 55fb7c12..21e213e9 100644 --- a/NCDK/TT/PDBMonomer.tt.cs +++ b/NCDK/TT/PDBMonomer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -27,10 +28,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Silent; using System; using System.Collections.Generic; using System.Linq; -using NCDK.Default; using System.Text; namespace NCDK.Default diff --git a/NCDK/TT/PDBPolymer.tt b/NCDK/TT/PDBPolymer.tt index 74aa4dd0..73060367 100644 --- a/NCDK/TT/PDBPolymer.tt +++ b/NCDK/TT/PDBPolymer.tt @@ -26,10 +26,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Silent; using System; using System.Collections.Generic; using System.Linq; -using NCDK.Default; using System.Text; <# diff --git a/NCDK/TT/PDBPolymer.tt.cs b/NCDK/TT/PDBPolymer.tt.cs index 091d3551..16a45305 100644 --- a/NCDK/TT/PDBPolymer.tt.cs +++ b/NCDK/TT/PDBPolymer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -27,10 +28,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Silent; using System; using System.Collections.Generic; using System.Linq; -using NCDK.Default; using System.Text; namespace NCDK.Default diff --git a/NCDK/TT/PDBStrand.tt b/NCDK/TT/PDBStrand.tt index 780843c3..b7fb03f1 100644 --- a/NCDK/TT/PDBStrand.tt +++ b/NCDK/TT/PDBStrand.tt @@ -26,7 +26,6 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Default; using System.Collections.Generic; using System.Text; @@ -46,6 +45,7 @@ namespace <#= ns.NS #> // @author Egon Willighagen // @cdk.created 2006-04-19 // @cdk.keyword polymer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class PDBStrand : Strand { List sequentialListOfMonomers; diff --git a/NCDK/TT/PDBStrand.tt.cs b/NCDK/TT/PDBStrand.tt.cs index d8f5bd24..22e13f67 100644 --- a/NCDK/TT/PDBStrand.tt.cs +++ b/NCDK/TT/PDBStrand.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -27,7 +28,6 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Default; using System.Collections.Generic; using System.Text; @@ -43,6 +43,7 @@ namespace NCDK.Default // @author Egon Willighagen // @cdk.created 2006-04-19 // @cdk.keyword polymer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class PDBStrand : Strand { List sequentialListOfMonomers; @@ -103,6 +104,7 @@ namespace NCDK.Silent // @author Egon Willighagen // @cdk.created 2006-04-19 // @cdk.keyword polymer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class PDBStrand : Strand { List sequentialListOfMonomers; diff --git a/NCDK/TT/PDBStructure.tt.cs b/NCDK/TT/PDBStructure.tt.cs index 3ae5e101..9234e483 100644 --- a/NCDK/TT/PDBStructure.tt.cs +++ b/NCDK/TT/PDBStructure.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara diff --git a/NCDK/TT/Polymer.tt b/NCDK/TT/Polymer.tt index 731e4b4c..494eaf69 100644 --- a/NCDK/TT/Polymer.tt +++ b/NCDK/TT/Polymer.tt @@ -48,6 +48,7 @@ namespace <#= ns.NS #> // @author Martin Eklund // @cdk.created 2001-08-06 // @cdk.keyword polymer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Polymer : AtomContainer, IPolymer @@ -87,7 +88,7 @@ namespace <#= ns.NS #> /// public virtual IEnumerable> GetMonomerMap() { - return monomers.Where(n => n.Key != ""); + return monomers.Where(n => n.Key.Length != 0); } /// @@ -136,12 +137,11 @@ namespace <#= ns.NS #> clone.monomers.Add(name, cloned); } - // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + // update sgroups + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, map)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, map)); } return clone; diff --git a/NCDK/TT/Polymer.tt.cs b/NCDK/TT/Polymer.tt.cs index 4ba8c0a5..a03484f6 100644 --- a/NCDK/TT/Polymer.tt.cs +++ b/NCDK/TT/Polymer.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -45,6 +46,7 @@ namespace NCDK.Default // @author Martin Eklund // @cdk.created 2001-08-06 // @cdk.keyword polymer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Polymer : AtomContainer, IPolymer @@ -84,7 +86,7 @@ public void AddAtom(IAtom oAtom, IMonomer oMonomer) /// public virtual IEnumerable> GetMonomerMap() { - return monomers.Where(n => n.Key != ""); + return monomers.Where(n => n.Key.Length != 0); } /// @@ -133,12 +135,11 @@ public override ICDKObject Clone(CDKObjectMap map) clone.monomers.Add(name, cloned); } - // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + // update sgroups + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, map)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, map)); } return clone; @@ -156,6 +157,7 @@ namespace NCDK.Silent // @author Martin Eklund // @cdk.created 2001-08-06 // @cdk.keyword polymer + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Polymer : AtomContainer, IPolymer @@ -195,7 +197,7 @@ public void AddAtom(IAtom oAtom, IMonomer oMonomer) /// public virtual IEnumerable> GetMonomerMap() { - return monomers.Where(n => n.Key != ""); + return monomers.Where(n => n.Key.Length != 0); } /// @@ -244,12 +246,11 @@ public override ICDKObject Clone(CDKObjectMap map) clone.monomers.Add(name, cloned); } - // update sgroups - var sgroups = GetProperty>(CDKPropertyName.CtabSgroups); + // update sgroups + var sgroups = this.GetCtabSgroups(); if (sgroups != null) { - clone.SetProperty(CDKPropertyName.CtabSgroups, - SgroupManipulator.Copy(sgroups, map)); + clone.SetCtabSgroups(SgroupManipulator.Copy(sgroups, map)); } return clone; diff --git a/NCDK/TT/PseudoAtom.tt b/NCDK/TT/PseudoAtom.tt index 0bbbd3bb..8d03591f 100644 --- a/NCDK/TT/PseudoAtom.tt +++ b/NCDK/TT/PseudoAtom.tt @@ -38,6 +38,7 @@ namespace <#= ns.NS #> { /// // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class PseudoAtom : Atom, ICloneable, IPseudoAtom diff --git a/NCDK/TT/PseudoAtom.tt.cs b/NCDK/TT/PseudoAtom.tt.cs index b0967d73..6f18a8bb 100644 --- a/NCDK/TT/PseudoAtom.tt.cs +++ b/NCDK/TT/PseudoAtom.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -35,6 +36,7 @@ namespace NCDK.Default { /// // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class PseudoAtom : Atom, ICloneable, IPseudoAtom @@ -147,6 +149,7 @@ namespace NCDK.Silent { /// // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class PseudoAtom : Atom, ICloneable, IPseudoAtom diff --git a/NCDK/TT/Reaction.tt b/NCDK/TT/Reaction.tt index a30831a7..ed3c88a6 100644 --- a/NCDK/TT/Reaction.tt +++ b/NCDK/TT/Reaction.tt @@ -29,7 +29,6 @@ using System; using System.Collections.Generic; using System.Text; -using System.Collections.ObjectModel; <# foreach (var ns in namespaces) @@ -39,6 +38,7 @@ namespace <#= ns.NS #> { /// // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Reaction : ChemObject, IReaction, ICloneable @@ -55,7 +55,7 @@ namespace <#= ns.NS #> /// public IChemObjectSet Agents => agents; - private IList mappings; + private List mappings; /// public IList Mappings => mappings; @@ -103,11 +103,11 @@ namespace <#= ns.NS #> var clone_agents = (IChemObjectSet)agents.Clone(map); var clone_products = (IChemObjectSet)products.Clone(map); - var clone_mappings = new ObservableCollection(); + var clone_mappings = new List(); foreach (var mapping in mappings) clone_mappings.Add((IMapping)mapping.Clone(map)); - Reaction clone = (Reaction)base.Clone(map); + var clone = (Reaction)base.Clone(map); clone.reactants = clone_reactants; clone.agents = clone_agents; clone.products = clone_products; diff --git a/NCDK/TT/Reaction.tt.cs b/NCDK/TT/Reaction.tt.cs index 4057cdb8..e8abb852 100644 --- a/NCDK/TT/Reaction.tt.cs +++ b/NCDK/TT/Reaction.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -30,12 +31,12 @@ using System; using System.Collections.Generic; using System.Text; -using System.Collections.ObjectModel; namespace NCDK.Default { /// // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Reaction : ChemObject, IReaction, ICloneable @@ -52,7 +53,7 @@ public class Reaction /// public IChemObjectSet Agents => agents; - private IList mappings; + private List mappings; /// public IList Mappings => mappings; @@ -99,11 +100,11 @@ public override ICDKObject Clone(CDKObjectMap map) var clone_agents = (IChemObjectSet)agents.Clone(map); var clone_products = (IChemObjectSet)products.Clone(map); - var clone_mappings = new ObservableCollection(); + var clone_mappings = new List(); foreach (var mapping in mappings) clone_mappings.Add((IMapping)mapping.Clone(map)); - Reaction clone = (Reaction)base.Clone(map); + var clone = (Reaction)base.Clone(map); clone.reactants = clone_reactants; clone.agents = clone_agents; clone.products = clone_products; @@ -117,6 +118,7 @@ namespace NCDK.Silent { /// // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Reaction : ChemObject, IReaction, ICloneable @@ -133,7 +135,7 @@ public class Reaction /// public IChemObjectSet Agents => agents; - private IList mappings; + private List mappings; /// public IList Mappings => mappings; @@ -180,11 +182,11 @@ public override ICDKObject Clone(CDKObjectMap map) var clone_agents = (IChemObjectSet)agents.Clone(map); var clone_products = (IChemObjectSet)products.Clone(map); - var clone_mappings = new ObservableCollection(); + var clone_mappings = new List(); foreach (var mapping in mappings) clone_mappings.Add((IMapping)mapping.Clone(map)); - Reaction clone = (Reaction)base.Clone(map); + var clone = (Reaction)base.Clone(map); clone.reactants = clone_reactants; clone.agents = clone_agents; clone.products = clone_products; diff --git a/NCDK/TT/ReactionChain.tt b/NCDK/TT/ReactionChain.tt index b8ea40a2..e59ed6bc 100644 --- a/NCDK/TT/ReactionChain.tt +++ b/NCDK/TT/ReactionChain.tt @@ -37,6 +37,7 @@ namespace <#= ns.NS #> // @author miguelrojasch // @cdk.module extra // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ReactionChain : ReactionSet { Dictionary hashMapChain = new Dictionary(); diff --git a/NCDK/TT/ReactionChain.tt.cs b/NCDK/TT/ReactionChain.tt.cs index 909b46af..9d805a28 100644 --- a/NCDK/TT/ReactionChain.tt.cs +++ b/NCDK/TT/ReactionChain.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2006-2007 Miguel Rojas * * Contact: cdk-devel@lists.sourceforge.net @@ -34,6 +35,7 @@ namespace NCDK.Default // @author miguelrojasch // @cdk.module extra // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ReactionChain : ReactionSet { Dictionary hashMapChain = new Dictionary(); @@ -98,6 +100,7 @@ namespace NCDK.Silent // @author miguelrojasch // @cdk.module extra // @cdk.githash + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ReactionChain : ReactionSet { Dictionary hashMapChain = new Dictionary(); diff --git a/NCDK/TT/ReactionScheme.tt b/NCDK/TT/ReactionScheme.tt index e4d0a9eb..c52fa4a4 100644 --- a/NCDK/TT/ReactionScheme.tt +++ b/NCDK/TT/ReactionScheme.tt @@ -36,6 +36,7 @@ namespace <#= ns.NS #> /// some way but without hard coded semantics. /// // @author miguelrojasch + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ReactionScheme : ReactionSet, IReactionScheme { /// diff --git a/NCDK/TT/ReactionScheme.tt.cs b/NCDK/TT/ReactionScheme.tt.cs index 48f9f555..b07a657b 100644 --- a/NCDK/TT/ReactionScheme.tt.cs +++ b/NCDK/TT/ReactionScheme.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -33,6 +34,7 @@ namespace NCDK.Default /// some way but without hard coded semantics. /// // @author miguelrojasch + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ReactionScheme : ReactionSet, IReactionScheme { /// @@ -88,6 +90,7 @@ namespace NCDK.Silent /// some way but without hard coded semantics. /// // @author miguelrojasch + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public class ReactionScheme : ReactionSet, IReactionScheme { /// diff --git a/NCDK/TT/ReactionSet.tt b/NCDK/TT/ReactionSet.tt index f24aad02..7f731a8e 100644 --- a/NCDK/TT/ReactionSet.tt +++ b/NCDK/TT/ReactionSet.tt @@ -58,6 +58,7 @@ namespace <#= ns.NS #> // @cdk.module silent // @cdk.githash // @cdk.keyword reaction + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class ReactionSet : ChemObject, IReactionSet, IChemObjectListener, ICloneable diff --git a/NCDK/TT/ReactionSet.tt.cs b/NCDK/TT/ReactionSet.tt.cs index 8788604a..17041821 100644 --- a/NCDK/TT/ReactionSet.tt.cs +++ b/NCDK/TT/ReactionSet.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -55,6 +56,7 @@ namespace NCDK.Default // @cdk.module silent // @cdk.githash // @cdk.keyword reaction + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class ReactionSet : ChemObject, IReactionSet, IChemObjectListener, ICloneable @@ -196,6 +198,7 @@ namespace NCDK.Silent // @cdk.module silent // @cdk.githash // @cdk.keyword reaction + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class ReactionSet : ChemObject, IReactionSet, IChemObjectListener, ICloneable diff --git a/NCDK/TT/Ring.tt b/NCDK/TT/Ring.tt index 05056c26..04ca90bd 100644 --- a/NCDK/TT/Ring.tt +++ b/NCDK/TT/Ring.tt @@ -33,16 +33,17 @@ foreach (var ns in namespaces) #> namespace <#= ns.NS #> { - /// - /// Class representing a ring structure in a molecule. - /// A ring is a linear sequence of - /// N atoms interconnected to each other by covalent bonds, - /// such that atom i (1 < i < N) is bonded to - /// atom i-1 and atom i + 1 and atom 1 is bonded to atom N and atom 2. - /// - // @cdk.module data - // @cdk.githash - // @cdk.keyword ring + /// + /// Class representing a ring structure in a molecule. + /// A ring is a linear sequence of + /// N atoms interconnected to each other by covalent bonds, + /// such that atom i (1 < i < N) is bonded to + /// atom i-1 and atom i + 1 and atom 1 is bonded to atom N and atom 2. + /// + // @cdk.module data + // @cdk.githash + // @cdk.keyword ring + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Ring : AtomContainer, IRing @@ -112,7 +113,7 @@ namespace <#= ns.NS #> /// /// The sum of all bond orders in the ring. /// - public int BondOrderSum + public int GetBondOrderSum() => bonds.Where(n => !n.Order.IsUnset()).Select(n => n.Order.Numeric()).Sum(); public override string ToString() diff --git a/NCDK/TT/Ring.tt.cs b/NCDK/TT/Ring.tt.cs index a5ee0ec6..19f5b1cf 100644 --- a/NCDK/TT/Ring.tt.cs +++ b/NCDK/TT/Ring.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -30,16 +31,17 @@ namespace NCDK.Default { - /// - /// Class representing a ring structure in a molecule. - /// A ring is a linear sequence of - /// N atoms interconnected to each other by covalent bonds, - /// such that atom i (1 < i < N) is bonded to - /// atom i-1 and atom i + 1 and atom 1 is bonded to atom N and atom 2. - /// - // @cdk.module data - // @cdk.githash - // @cdk.keyword ring + /// + /// Class representing a ring structure in a molecule. + /// A ring is a linear sequence of + /// N atoms interconnected to each other by covalent bonds, + /// such that atom i (1 < i < N) is bonded to + /// atom i-1 and atom i + 1 and atom 1 is bonded to atom N and atom 2. + /// + // @cdk.module data + // @cdk.githash + // @cdk.keyword ring + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Ring : AtomContainer, IRing @@ -109,7 +111,7 @@ public IBond GetNextBond(IBond bond, IAtom atom) /// /// The sum of all bond orders in the ring. /// - public int BondOrderSum + public int GetBondOrderSum() => bonds.Where(n => !n.Order.IsUnset()).Select(n => n.Order.Numeric()).Sum(); public override string ToString() @@ -129,16 +131,17 @@ public override ICDKObject Clone(CDKObjectMap map) } namespace NCDK.Silent { - /// - /// Class representing a ring structure in a molecule. - /// A ring is a linear sequence of - /// N atoms interconnected to each other by covalent bonds, - /// such that atom i (1 < i < N) is bonded to - /// atom i-1 and atom i + 1 and atom 1 is bonded to atom N and atom 2. - /// - // @cdk.module data - // @cdk.githash - // @cdk.keyword ring + /// + /// Class representing a ring structure in a molecule. + /// A ring is a linear sequence of + /// N atoms interconnected to each other by covalent bonds, + /// such that atom i (1 < i < N) is bonded to + /// atom i-1 and atom i + 1 and atom 1 is bonded to atom N and atom 2. + /// + // @cdk.module data + // @cdk.githash + // @cdk.keyword ring + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Ring : AtomContainer, IRing @@ -208,7 +211,7 @@ public IBond GetNextBond(IBond bond, IAtom atom) /// /// The sum of all bond orders in the ring. /// - public int BondOrderSum + public int GetBondOrderSum() => bonds.Where(n => !n.Order.IsUnset()).Select(n => n.Order.Numeric()).Sum(); public override string ToString() diff --git a/NCDK/TT/RingSet.tt b/NCDK/TT/RingSet.tt index 0a457166..c7371aa2 100644 --- a/NCDK/TT/RingSet.tt +++ b/NCDK/TT/RingSet.tt @@ -39,6 +39,7 @@ namespace <#= ns.NS #> // @cdk.module silent // @cdk.githash // @cdk.keyword ring, set of + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class RingSet : ChemObjectSet, IRingSet, ICloneable diff --git a/NCDK/TT/RingSet.tt.cs b/NCDK/TT/RingSet.tt.cs index 9a1cedd5..a047e924 100644 --- a/NCDK/TT/RingSet.tt.cs +++ b/NCDK/TT/RingSet.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -36,6 +37,7 @@ namespace NCDK.Default // @cdk.module silent // @cdk.githash // @cdk.keyword ring, set of + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class RingSet : ChemObjectSet, IRingSet, ICloneable @@ -128,6 +130,7 @@ namespace NCDK.Silent // @cdk.module silent // @cdk.githash // @cdk.keyword ring, set of + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class RingSet : ChemObjectSet, IRingSet, ICloneable diff --git a/NCDK/TT/SingleElectron.tt b/NCDK/TT/SingleElectron.tt index c7345902..b26f234b 100644 --- a/NCDK/TT/SingleElectron.tt +++ b/NCDK/TT/SingleElectron.tt @@ -48,11 +48,12 @@ namespace <#= ns.NS #> // @cdk.githash // @cdk.keyword radical // @cdk.keyword electron, unpaired + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class SingleElectron : ElectronContainer, ISingleElectron, ICloneable { - protected IAtom atom; + private IAtom atom; /// /// Constructs an single electron orbital on an Atom. diff --git a/NCDK/TT/SingleElectron.tt.cs b/NCDK/TT/SingleElectron.tt.cs index 84c51b14..703ce6c3 100644 --- a/NCDK/TT/SingleElectron.tt.cs +++ b/NCDK/TT/SingleElectron.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -45,11 +46,12 @@ namespace NCDK.Default // @cdk.githash // @cdk.keyword radical // @cdk.keyword electron, unpaired + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class SingleElectron : ElectronContainer, ISingleElectron, ICloneable { - protected IAtom atom; + private IAtom atom; /// /// Constructs an single electron orbital on an Atom. @@ -137,11 +139,12 @@ namespace NCDK.Silent // @cdk.githash // @cdk.keyword radical // @cdk.keyword electron, unpaired + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class SingleElectron : ElectronContainer, ISingleElectron, ICloneable { - protected IAtom atom; + private IAtom atom; /// /// Constructs an single electron orbital on an Atom. diff --git a/NCDK/TT/Strand.tt b/NCDK/TT/Strand.tt index c9a2a6fb..80d2a2ca 100644 --- a/NCDK/TT/Strand.tt +++ b/NCDK/TT/Strand.tt @@ -47,11 +47,12 @@ namespace <#= ns.NS #> // @cdk.created 2004-12-20 // @author Martin Eklund // @author Ola Spjuth + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Strand : AtomContainer, IStrand { - private IDictionary monomers = new Dictionary(); + private Dictionary monomers = new Dictionary(); /// /// The strand name. @@ -66,7 +67,7 @@ namespace <#= ns.NS #> public Strand() : base() { - Monomer oMonomer = new Monomer + Monomer oMonomer = new Monomer { MonomerName = "", MonomerType = "Unknown" @@ -104,12 +105,12 @@ namespace <#= ns.NS #> } } - private class ReadOnlyNonEmptyDictionary + private class ReadOnlyNonEmptyDictionary : IReadOnlyDictionary { - IDictionary dictionary; + IReadOnlyDictionary dictionary; - public ReadOnlyNonEmptyDictionary(IDictionary dictionary) + public ReadOnlyNonEmptyDictionary(IReadOnlyDictionary dictionary) { this.dictionary = dictionary; } @@ -122,7 +123,7 @@ namespace <#= ns.NS #> public IEnumerator> GetEnumerator() { foreach (var pair in dictionary) - if (pair.Key != "") + if (pair.Key.Length != 0) yield return pair; yield break; } diff --git a/NCDK/TT/Strand.tt.cs b/NCDK/TT/Strand.tt.cs index 28cb1628..e7867dc8 100644 --- a/NCDK/TT/Strand.tt.cs +++ b/NCDK/TT/Strand.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -44,11 +45,12 @@ namespace NCDK.Default // @cdk.created 2004-12-20 // @author Martin Eklund // @author Ola Spjuth + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Strand : AtomContainer, IStrand { - private IDictionary monomers = new Dictionary(); + private Dictionary monomers = new Dictionary(); /// /// The strand name. @@ -63,7 +65,7 @@ public class Strand public Strand() : base() { - Monomer oMonomer = new Monomer + Monomer oMonomer = new Monomer { MonomerName = "", MonomerType = "Unknown" @@ -101,12 +103,12 @@ public virtual void AddAtom(IAtom oAtom, IMonomer oMonomer) } } - private class ReadOnlyNonEmptyDictionary + private class ReadOnlyNonEmptyDictionary : IReadOnlyDictionary { - IDictionary dictionary; + IReadOnlyDictionary dictionary; - public ReadOnlyNonEmptyDictionary(IDictionary dictionary) + public ReadOnlyNonEmptyDictionary(IReadOnlyDictionary dictionary) { this.dictionary = dictionary; } @@ -119,7 +121,7 @@ public ReadOnlyNonEmptyDictionary(IDictionary dictionary) public IEnumerator> GetEnumerator() { foreach (var pair in dictionary) - if (pair.Key != "") + if (pair.Key.Length != 0) yield return pair; yield break; } @@ -195,11 +197,12 @@ namespace NCDK.Silent // @cdk.created 2004-12-20 // @author Martin Eklund // @author Ola Spjuth + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Strand : AtomContainer, IStrand { - private IDictionary monomers = new Dictionary(); + private Dictionary monomers = new Dictionary(); /// /// The strand name. @@ -214,7 +217,7 @@ public class Strand public Strand() : base() { - Monomer oMonomer = new Monomer + Monomer oMonomer = new Monomer { MonomerName = "", MonomerType = "Unknown" @@ -252,12 +255,12 @@ public virtual void AddAtom(IAtom oAtom, IMonomer oMonomer) } } - private class ReadOnlyNonEmptyDictionary + private class ReadOnlyNonEmptyDictionary : IReadOnlyDictionary { - IDictionary dictionary; + IReadOnlyDictionary dictionary; - public ReadOnlyNonEmptyDictionary(IDictionary dictionary) + public ReadOnlyNonEmptyDictionary(IReadOnlyDictionary dictionary) { this.dictionary = dictionary; } @@ -270,7 +273,7 @@ public ReadOnlyNonEmptyDictionary(IDictionary dictionary) public IEnumerator> GetEnumerator() { foreach (var pair in dictionary) - if (pair.Key != "") + if (pair.Key.Length != 0) yield return pair; yield break; } diff --git a/NCDK/TT/Substance.tt b/NCDK/TT/Substance.tt index 6fb8f0f7..09425fa5 100644 --- a/NCDK/TT/Substance.tt +++ b/NCDK/TT/Substance.tt @@ -30,6 +30,7 @@ foreach (var ns in namespaces) #> namespace <#= ns.NS #> { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Substance : ChemObjectSet, ISubstance, ICloneable diff --git a/NCDK/TT/Substance.tt.cs b/NCDK/TT/Substance.tt.cs index 92fd3f96..1327b301 100644 --- a/NCDK/TT/Substance.tt.cs +++ b/NCDK/TT/Substance.tt.cs @@ -1,6 +1,7 @@ + // .NET Framework port by Kazuya Ujihara // Copyright (C) 2016-2017 Kazuya Ujihara @@ -27,6 +28,7 @@ namespace NCDK.Default { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Substance : ChemObjectSet, ISubstance, ICloneable @@ -39,6 +41,7 @@ public Substance() } namespace NCDK.Silent { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [Serializable] public class Substance : ChemObjectSet, ISubstance, ICloneable diff --git a/NCDK/Tautomers/InChITautomerGenerator.cs b/NCDK/Tautomers/InChITautomerGenerator.cs index fb77544e..00c5a29a 100644 --- a/NCDK/Tautomers/InChITautomerGenerator.cs +++ b/NCDK/Tautomers/InChITautomerGenerator.cs @@ -30,6 +30,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Linq; using System.Text.RegularExpressions; @@ -50,7 +51,7 @@ namespace NCDK.Tautomers // @cdk.githash public sealed class InChITautomerGenerator { - private static readonly SmilesGenerator CANSMI = new SmilesGenerator(SmiFlavor.Canonical); + private static readonly SmilesGenerator CANSMI = new SmilesGenerator(SmiFlavors.Canonical); [Flags] public enum Options @@ -161,7 +162,7 @@ private List GetTautomers(IAtomContainer mol, string inchi, long { for (int i = 0; i < amap.Length; i++) { - mol.Atoms[i].Id = amap[i].ToString(); + mol.Atoms[i].Id = amap[i].ToString(NumberFormatInfo.InvariantInfo); } mol = AtomContainerManipulator.SuppressHydrogens(mol); } @@ -187,9 +188,9 @@ private List GetTautomers(IAtomContainer mol, string inchi, long /// user input InChI /// user input molecule /// indicating position and atom - private IDictionary GetElementsByPosition(string inputInchi, IAtomContainer inputMolecule) + private static Dictionary GetElementsByPosition(string inputInchi, IAtomContainer inputMolecule) { - IDictionary inchiAtomsByPosition = new Dictionary(); + var inchiAtomsByPosition = new Dictionary(); int position = 0; string inchi = inputInchi; @@ -209,13 +210,13 @@ private IDictionary GetElementsByPosition(string inputInchi, IAtomCo foreach (Match match in formulaPattern.Matches(formula)) { string elementSymbol = match.Groups["symbol"].Value; - if (!elementSymbol.Equals("H")) + if (!string.Equals(elementSymbol, "H", StringComparison.Ordinal)) { int elementCnt = 1; { string cnt = match.Groups["cnt"].Value; - if (cnt != "") - elementCnt = int.Parse(cnt); + if (cnt.Length != 0) + elementCnt = int.Parse(cnt, NumberFormatInfo.InvariantInfo); } for (int i = 0; i < elementCnt; i++) @@ -242,7 +243,7 @@ private IDictionary GetElementsByPosition(string inputInchi, IAtomCo /// user input molecule /// /// molecule with single bonds and no hydrogens. - private IAtomContainer ConnectAtoms(string inputInchi, IAtomContainer inputMolecule, IDictionary inchiAtomsByPosition) + private static IAtomContainer ConnectAtoms(string inputInchi, IAtomContainer inputMolecule, IDictionary inchiAtomsByPosition) { string inchi = inputInchi; inchi = inchi.Substring(inchi.IndexOf('/') + 1); @@ -328,7 +329,7 @@ private IAtomContainer ConnectAtoms(string inputInchi, IAtomContainer inputMolec /// molecule (bare) as defined in InChI /// user input molecule /// - private void MapInputMoleculeToInChIMolgraph(IAtomContainer inchiMolGraph, IAtomContainer mol) + private static void MapInputMoleculeToInChIMolgraph(IAtomContainer inchiMolGraph, IAtomContainer mol) { var iter = VentoFoggia.FindIdentical(inchiMolGraph, AtomMatcher.CreateElementMatcher(), BondMatcher.CreateAnyMatcher()) .MatchAll(mol) @@ -372,14 +373,14 @@ private void MapInputMoleculeToInChIMolgraph(IAtomContainer inchiMolGraph, IAtom /// list of positions where mobile H can attach /// InChI input /// overall count of hydrogens to be dispersed over the positions - private int ParseMobileHydrogens(List mobHydrAttachPositions, string inputInchi) + private static int ParseMobileHydrogens(List mobHydrAttachPositions, string inputInchi) { int totalMobHydrCount = 0; string hydrogens = ""; string inchi = inputInchi; - if (inchi.IndexOf("/h") != -1) + if (inchi.IndexOf("/h", StringComparison.Ordinal) != -1) { - hydrogens = inchi.Substring(inchi.IndexOf("/h") + 2); + hydrogens = inchi.Substring(inchi.IndexOf("/h", StringComparison.Ordinal) + 2); if (hydrogens.IndexOf('/') != -1) { hydrogens = hydrogens.Substring(0, hydrogens.IndexOf('/')); @@ -402,9 +403,9 @@ private int ParseMobileHydrogens(List mobHydrAttachPositions, string inputI // ...(H2-,19,20,22) foreach (Match subMatch in subPattern.Matches(head)) { - if (!subMatch.Value.Equals("")) + if (subMatch.Value.Length != 0) { - mobHCount += int.Parse(subMatch.Value); + mobHCount += int.Parse(subMatch.Value, NumberFormatInfo.InvariantInfo); } } totalMobHydrCount += mobHCount; @@ -412,7 +413,7 @@ private int ParseMobileHydrogens(List mobHydrAttachPositions, string inputI var tokens = mobileHGroup.Split(','); foreach (var token in tokens) { - var position = int.Parse(token); + var position = int.Parse(token, NumberFormatInfo.InvariantInfo); mobHydrAttachPositions.Add(position); } } @@ -446,7 +447,7 @@ private List ConstructTautomers(IAtomContainer inputMolecule, Li foreach (var atom in skeleton.Atoms) { atomRemoved = false; - int position = int.Parse(atom.Id); + int position = int.Parse(atom.Id, NumberFormatInfo.InvariantInfo); if (!mobHydrAttachPositions.Contains(position) && atom.Hybridization.Equals(Hybridization.SP3)) { @@ -573,7 +574,7 @@ private List ConstructTautomers(IAtomContainer inputMolecule, Li { foreach (var atom1 in tautomer.Atoms) { - if (atom1.Id.Equals(skAtom1.Id)) + if (string.Equals(atom1.Id, skAtom1.Id, StringComparison.Ordinal)) { atom1.ImplicitHydrogenCount = skAtom1.ImplicitHydrogenCount; for (int bondIdx = 0; bondIdx < tautomerSkeleton.Bonds.Count; bondIdx++) @@ -584,7 +585,7 @@ private List ConstructTautomers(IAtomContainer inputMolecule, Li IAtom skAtom2 = skBond.GetOther(skAtom1); foreach (var atom2 in tautomer.Atoms) { - if (atom2.Id.Equals(skAtom2.Id)) + if (string.Equals(atom2.Id, skAtom2.Id, StringComparison.Ordinal)) { IBond tautBond = tautomer.GetBond(atom1, atom2); if (dblBondPositions.Contains(bondIdx)) @@ -620,7 +621,7 @@ private List ConstructTautomers(IAtomContainer inputMolecule, Li /// molecule set of tautomers with possible duplicates /// tautomers same set with duplicates removed /// unable to calculate canonical SMILES - private List RemoveDuplicates(List tautomers) + private static List RemoveDuplicates(List tautomers) { ISet cansmis = new HashSet(); List result = new List(); @@ -629,7 +630,7 @@ private List RemoveDuplicates(List tautomers) if (cansmis.Add(CANSMI.Create(tautomer))) result.Add(tautomer); } - Debug.WriteLine("# tautomers after clean up : " + tautomers.Count); + Debug.WriteLine($"# tautomers after clean up : {tautomers.Count}"); return result; } @@ -680,12 +681,13 @@ private void CombineHydrogenPositions(IList taken, List> combina /// input container /// InChI atom table position /// atom on the position - private IAtom FindAtomByPosition(IAtomContainer container, int position) + private static IAtom FindAtomByPosition(IAtomContainer container, int position) { - string pos = position.ToString(); + string pos = position.ToString(NumberFormatInfo.InvariantInfo); foreach (var atom in container.Atoms) { - if (atom.Id.Equals(pos)) return atom; + if (string.Equals(atom.Id, pos, StringComparison.Ordinal)) + return atom; } return null; } @@ -756,7 +758,7 @@ private List TryDoubleBondCombinations(IAtomContainer container, int dblBon /// an atom in the container /// the container /// valence (bond order sum) of the atom - private int GetConnectivity(IAtom atom, IAtomContainer container) + private static int GetConnectivity(IAtom atom, IAtomContainer container) { int connectivity = 0; foreach (var bond in container.Bonds) diff --git a/NCDK/Templates/AminoAcids.cs b/NCDK/Templates/AminoAcids.cs index 1c33e53f..6121adb1 100644 --- a/NCDK/Templates/AminoAcids.cs +++ b/NCDK/Templates/AminoAcids.cs @@ -52,7 +52,9 @@ public static class AminoAcids private static readonly Dictionary singleLetterToThreeLetter; private static readonly Dictionary threeLetterToSingleLetter; +#pragma warning disable CA1810 // Initialize reference type static fields inline static AminoAcids() +#pragma warning restore CA1810 // Initialize reference type static fields inline { // Create set of AtomContainers proteinogenics = new AminoAcid[20]; @@ -68,7 +70,7 @@ static AminoAcids() int counter = 0; foreach (var ac in containersList) { - Debug.WriteLine("Adding AA: ", ac); + Debug.WriteLine($"Adding AA: {ac}"); // convert into an AminoAcid AminoAcid aminoAcid = new AminoAcid(); foreach (var next in ac.GetProperties().Keys) @@ -76,20 +78,20 @@ static AminoAcids() Debug.WriteLine("Prop: " + next.ToString()); if (next is DictRef dictRef) { - // Debug.WriteLine("DictRef type: " + dictRef.Type); - if (dictRef.Type.Equals("pdb:residueName")) + // Debug.WriteLine("DictRef type: " + dictRef.Type}"); + if (string.Equals(dictRef.Type, "pdb:residueName", StringComparison.Ordinal)) { aminoAcid.SetProperty(ResidueNameKey, ac.GetProperty(next).ToUpperInvariant()); aminoAcid.MonomerName = ac.GetProperty(next); } - else if (dictRef.Type.Equals("pdb:oneLetterCode")) + else if (string.Equals(dictRef.Type, "pdb:oneLetterCode", StringComparison.Ordinal)) { aminoAcid.SetProperty(ResidueNameShortKey, ac.GetProperty(next)); } - else if (dictRef.Type.Equals("pdb:id")) + else if (string.Equals(dictRef.Type, "pdb:id", StringComparison.Ordinal)) { aminoAcid.SetProperty(IdKey, ac.GetProperty(next)); - Debug.WriteLine("Set AA ID to: ", ac.GetProperty(next)); + Debug.WriteLine($"Set AA ID to: {ac.GetProperty(next)}"); } else { @@ -100,17 +102,17 @@ static AminoAcids() foreach (var atom in ac.Atoms) { string dictRef = atom.GetProperty("org.openscience.cdk.dict"); - if (dictRef != null && dictRef.Equals("pdb:nTerminus")) + switch (dictRef) { - aminoAcid.AddNTerminus(atom); - } - else if (dictRef != null && dictRef.Equals("pdb:cTerminus")) - { - aminoAcid.AddCTerminus(atom); - } - else - { - aminoAcid.Atoms.Add(atom); + case "pdb:nTerminus": + aminoAcid.AddNTerminus(atom); + break; + case "pdb:cTerminus": + aminoAcid.AddCTerminus(atom); + break; + default: + aminoAcid.Atoms.Add(atom); + break; } } foreach (var bond in ac.Bonds) diff --git a/NCDK/TetrahedralStereo.cs b/NCDK/TetrahedralStereo.cs index a70d9083..ddf48d58 100644 --- a/NCDK/TetrahedralStereo.cs +++ b/NCDK/TetrahedralStereo.cs @@ -57,26 +57,26 @@ public static TetrahedralStereo Invert(this TetrahedralStereo value) return value; } - public static StereoElement.Configuration ToConfiguration(this TetrahedralStereo value) + public static StereoConfigurations ToConfiguration(this TetrahedralStereo value) { switch (value) { case AntiClockwise: - return StereoElement.Configuration.Left; + return StereoConfigurations.Left; case Clockwise: - return StereoElement.Configuration.Right; + return StereoConfigurations.Right; default: throw new System.ArgumentException("Unknown enum value: " + value); } } - public static TetrahedralStereo ToStereo(this StereoElement.Configuration configure) + public static TetrahedralStereo ToStereo(this StereoConfigurations configure) { switch (configure) { - case StereoElement.Configuration.Left: + case StereoConfigurations.Left: return AntiClockwise; - case StereoElement.Configuration.Right: + case StereoConfigurations.Right: return Clockwise; default: throw new System.ArgumentException("Cannot map to enum value: " + configure); diff --git a/NCDK/Tools/AtomTypeAwareSaturationChecker.cs b/NCDK/Tools/AtomTypeAwareSaturationChecker.cs index 14c111db..f1aa576b 100644 --- a/NCDK/Tools/AtomTypeAwareSaturationChecker.cs +++ b/NCDK/Tools/AtomTypeAwareSaturationChecker.cs @@ -88,10 +88,7 @@ public void DecideBondOrder(IAtomContainer atomContainer, bool atomsSaturated) DecideBondOrder(atomContainer, bestGuess[0]); double satAtoms = ((bestGuess[1] * 1.0) / atomContainer.Atoms.Count) * 10000; satAtoms = Math.Round(satAtoms) / 100; - // Console.Out.WriteLine("Staring on bond "+bestGuess[0]+ - // " gives "+satAtoms+"% saturated atoms."); - Trace.TraceWarning("Can't find any solution where all atoms " + "are saturated. A best guess gives " - + satAtoms + "% Saturated atoms."); + Trace.TraceWarning($"Can't find any solution where all atoms are saturated. A best guess gives {satAtoms}% Saturated atoms."); return; } } @@ -163,7 +160,7 @@ private void DecideBondOrder(IAtomContainer atomContainer, int start) /// when no suitable solution can be found private void CheckBond(IAtomContainer atomContainer, int index) { - IBond bond = atomContainer.Bonds[index]; + var bond = atomContainer.Bonds[index]; if (bond != null && bond.IsSingleOrDouble) { @@ -206,9 +203,10 @@ private void SetMaxBondOrder(IBond bond, IAtomContainer atomContainer) /// The bond to check /// The that the bond belongs to /// True if it is possibly to increase the bond order - public bool BondOrderCanBeIncreased(IBond bond, IAtomContainer atomContainer) + public virtual bool BondOrderCanBeIncreased(IBond bond, IAtomContainer atomContainer) { - bool atom0isUnsaturated = false, atom1isUnsaturated = false; + bool atom0isUnsaturated = false; + bool atom1isUnsaturated = false; double sum; if (bond.Begin.BondOrderSum == null) { @@ -216,7 +214,8 @@ public bool BondOrderCanBeIncreased(IBond bond, IAtomContainer atomContainer) } else sum = bond.Begin.BondOrderSum.Value; - if (BondsUsed(bond.Begin, atomContainer) < sum) atom0isUnsaturated = true; + if (BondsUsed(bond.Begin, atomContainer) < sum) + atom0isUnsaturated = true; if (bond.End.BondOrderSum == null) { @@ -224,7 +223,8 @@ public bool BondOrderCanBeIncreased(IBond bond, IAtomContainer atomContainer) } else sum = bond.End.BondOrderSum.Value; - if (BondsUsed(bond.End, atomContainer) < sum) atom1isUnsaturated = true; + if (BondsUsed(bond.End, atomContainer) < sum) + atom1isUnsaturated = true; if (atom0isUnsaturated == atom1isUnsaturated) return atom0isUnsaturated; @@ -232,13 +232,15 @@ public bool BondOrderCanBeIncreased(IBond bond, IAtomContainer atomContainer) { // If one of the atoms is saturated and the other isn't, what do we // do then? Look at the bonds on each side and decide from that... - int myIndex = atomContainer.Bonds.IndexOf(bond); + var myIndex = atomContainer.Bonds.IndexOf(bond); // If it's the first bond, then just move on. - if (myIndex == 0) return false; + if (myIndex == 0) + return false; // If the previous bond is the reason it's no problem, so just move on... // TODO instead check if the atom that are in both bonds are saturated...? - if (atomContainer.Bonds[myIndex - 1].Order == BondOrder.Double) return false; + if (atomContainer.Bonds[myIndex - 1].Order == BondOrder.Double) + return false; // The only reason for trouble should now be that the next bond make // one of the atoms saturated, so lets throw an exception and @@ -260,12 +262,13 @@ public bool BondOrderCanBeIncreased(IBond bond, IAtomContainer atomContainer) /// The atom in question /// The molecule that the atom belongs to /// The bond order sum - private double GetAtomBondOrderSum(IAtom atom, IAtomContainer mol) + private static double GetAtomBondOrderSum(IAtom atom, IAtomContainer mol) { double sum = 0; foreach (var bond in mol.Bonds) - if (bond.Contains(atom)) sum += BondManipulator.DestroyBondOrder(bond.Order); + if (bond.Contains(atom)) + sum += BondManipulator.DestroyBondOrder(bond.Order); return sum; } @@ -277,10 +280,11 @@ private double GetAtomBondOrderSum(IAtom atom, IAtomContainer mol) /// The first bond /// The other bond /// True if any of the atoms in also are in - private bool IsConnected(IBond bond1, IBond bond2) + private static bool IsConnected(IBond bond1, IBond bond2) { foreach (var atom in bond1.Atoms) - if (bond2.Contains(atom)) return true; + if (bond2.Contains(atom)) + return true; return false; } @@ -291,7 +295,7 @@ private bool IsConnected(IBond bond1, IBond bond2) /// The to be investigated /// The max number of bonds the can have /// when the atom's valency is not set - public double GetMaxNoOfBonds(IAtom atom) + public virtual double GetMaxNoOfBonds(IAtom atom) { double noValenceElectrons = atom.Valency ?? -1; if (noValenceElectrons == -1) @@ -309,24 +313,22 @@ public double GetMaxNoOfBonds(IAtom atom) /// The atom to check /// The atomContainer containing the atom /// The number of bonds that the atom has - private double BondsUsed(IAtom atom, IAtomContainer atomContainer) + private static double BondsUsed(IAtom atom, IAtomContainer atomContainer) { int bondsToAtom = 0; foreach (var bond in atomContainer.Bonds) - if (bond.Contains(atom)) bondsToAtom += (int)BondManipulator.DestroyBondOrder(bond.Order); + if (bond.Contains(atom)) + bondsToAtom += (int)BondManipulator.DestroyBondOrder(bond.Order); int implicitHydrogens; if (atom.ImplicitHydrogenCount == null || atom.ImplicitHydrogenCount == null) { // Will probably only work with group 13-18, and not for helium... if (atom.Valency == null || atom.Valency == null) - throw new CDKException("Atom " + atom.AtomTypeName + " has not got the valency set."); + throw new CDKException($"Atom {atom.AtomTypeName} has not got the valency set."); if (atom.FormalNeighbourCount == null || atom.FormalNeighbourCount == null) - throw new CDKException("Atom " + atom.AtomTypeName - + " has not got the formal neighbour count set."); + throw new CDKException($"Atom {atom.AtomTypeName} has not got the formal neighbour count set."); implicitHydrogens = (8 - atom.Valency.Value) - atom.FormalNeighbourCount.Value; - string warningMessage = "Number of implicite hydrogens not set for atom " + atom.AtomTypeName - + ". Estimated it to: " + implicitHydrogens; - Trace.TraceWarning(warningMessage); + Trace.TraceWarning($"Number of implicit hydrogens not set for atom {atom.AtomTypeName}. Estimated it to: {implicitHydrogens}"); } else implicitHydrogens = atom.ImplicitHydrogenCount.Value; @@ -336,9 +338,7 @@ private double BondsUsed(IAtom atom, IAtomContainer atomContainer) if (atom.FormalCharge == null) { charge = 0; - string warningMessage = "Neither charge nor formal charge is set for atom " + atom.AtomTypeName - + ". Estimate it to: 0"; - Trace.TraceWarning(warningMessage); + Trace.TraceWarning($"Neither charge nor formal charge is set for atom {atom.AtomTypeName}. Estimate it to: 0"); } else charge = atom.FormalCharge.Value; @@ -372,13 +372,21 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) // @author Klas Jönsson private class CantDecideBondOrderException : CDKException { + public CantDecideBondOrderException() + { + } + /// /// Creates a new with a given message. /// /// Explanation about why the decision could not be made. - public CantDecideBondOrderException(string message) - : base(message) - { } + public CantDecideBondOrderException(string message) : base(message) + { + } + + public CantDecideBondOrderException(string message, Exception innerException) : base(message, innerException) + { + } } } } diff --git a/NCDK/Tools/AtomTypeTools.cs b/NCDK/Tools/AtomTypeTools.cs index fa9a8eb9..3df3dc7c 100644 --- a/NCDK/Tools/AtomTypeTools.cs +++ b/NCDK/Tools/AtomTypeTools.cs @@ -35,7 +35,8 @@ namespace NCDK.Tools // @cdk.created 2005-18-07 // @cdk.module extra // @cdk.githash - public class AtomTypeTools + [Obsolete("This is legacy")] + public static class AtomTypeTools { public const int NotInRing = 100; public const int PyrroleRing = 4; @@ -44,44 +45,43 @@ public class AtomTypeTools public const int PyridineRing = 10; public const int PyrimidineRing = 12; public const int BenzeneRing = 5; - HOSECodeGenerator hcg = null; - - /// - /// Constructor for the MMFF94AtomTypeMatcher object. - /// - public AtomTypeTools() - { - hcg = new HOSECodeGenerator(); - } - - public IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule) + static HOSECodeGenerator hcg = new HOSECodeGenerator(); + + private static readonly string PyrroleSmi = Cansmi(CDK.SilentSmilesParser.ParseSmiles("c1cc[nH]c1")); + private static readonly string FuranSmi = Cansmi(CDK.SilentSmilesParser.ParseSmiles("o1cccc1")); + private static readonly string ThiopheneSmi = Cansmi(CDK.SilentSmilesParser.ParseSmiles("c1ccsc1")); + private static readonly string PyridineSmi = Cansmi(CDK.SilentSmilesParser.ParseSmiles("c1ccncc1")); + private static readonly string PyrimidineSmi = Cansmi(CDK.SilentSmilesParser.ParseSmiles("c1cncnc1")); + private static readonly string BenzeneSmi = Cansmi(CDK.SilentSmilesParser.ParseSmiles("c1ccccc1")); + + public static IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule) { return AssignAtomTypePropertiesToAtom(molecule, true); } /// - /// Method assigns certain properties to an atom. Necessary for the atom type matching - /// Properties: - /// - /// aromaticity) + /// Method assigns certain properties to an atom. Necessary for the atom type matching + /// Properties: + /// + /// aromaticity /// ChemicalGroup (CDKChemicalRingGroupConstant) /// /// SSSR /// Ring/Group, ringSize, aromaticity /// SphericalMatcher (HoSe Code) /// - /// + /// /// /// - /// bool true/false true if aromaticity should be calculated + /// if aromaticity should be calculated /// sssrf ring set of the molecule - public IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule, bool aromaticity) + public static IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule, bool aromaticity) { - SmilesGenerator sg = new SmilesGenerator(); + var sg = new SmilesGenerator(); Debug.WriteLine("assignAtomTypePropertiesToAtom Start ..."); string hoseCode = ""; - IRingSet ringSetMolecule = Cycles.FindSSSR(molecule).ToRingSet(); + var ringSetMolecule = Cycles.FindSSSR(molecule).ToRingSet(); Debug.WriteLine(ringSetMolecule); if (aromaticity) @@ -92,15 +92,14 @@ public IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule, bool aro } catch (Exception cdk1) { - //Debug.WriteLine("AROMATICITYError: Cannot determine aromaticity due to: " + cdk1.ToString()); - Trace.TraceError("AROMATICITYError: Cannot determine aromaticity due to: " + cdk1.ToString()); + Trace.TraceError($"AROMATICITYError: Cannot determine aromaticity due to: {cdk1.ToString()}"); } } for (int i = 0; i < molecule.Atoms.Count; i++) { // FIXME: remove casting - IAtom atom2 = molecule.Atoms[i]; + var atom2 = molecule.Atoms[i]; //Atom aromatic is set by HueckelAromaticityDetector //Atom in ring? if (ringSetMolecule.Contains(atom2)) @@ -108,7 +107,7 @@ public IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule, bool aro var ringSetA = ringSetMolecule.Builder.NewRingSet(); ringSetA.AddRange(ringSetMolecule.GetRings(atom2)); RingSetManipulator.Sort(ringSetA); - IRing sring = (IRing)ringSetA.Last(); + var sring = ringSetA.Last(); atom2.SetProperty(CDKPropertyName.PartOfRingOfSize, sring.RingSize); atom2.SetProperty( CDKPropertyName.ChemicalGroupConstant, @@ -130,7 +129,7 @@ public IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule, bool aro } catch (CDKException ex1) { - throw new CDKException("Could not build HOSECode from atom " + i + " due to " + ex1.ToString(), ex1); + throw new CDKException($"Could not build HOSECode from atom {i} due to {ex1.ToString()}", ex1); } } return ringSetMolecule; @@ -152,10 +151,10 @@ private static string GetSubgraphSmiles(IAtomContainer subgraph, IAtomContainer foreach (var bond in subgraph.Bonds) bonds.Add(bond); - int?[] hCount = new int?[subgraph.Atoms.Count]; + var hCount = new int?[subgraph.Atoms.Count]; for (int i = 0; i < subgraph.Atoms.Count; i++) { - IAtom atom = subgraph.Atoms[i]; + var atom = subgraph.Atoms[i]; int removed = 0; foreach (var bond in molecule.GetConnectedBonds(atom)) { @@ -166,7 +165,7 @@ private static string GetSubgraphSmiles(IAtomContainer subgraph, IAtomContainer atom.ImplicitHydrogenCount = (hCount[i] == null ? removed : hCount[i] + removed); } - string smi = Cansmi(subgraph); + var smi = Cansmi(subgraph); // reset for fused rings! for (int i = 0; i < subgraph.Atoms.Count; i++) @@ -188,19 +187,6 @@ private static string Cansmi(IAtomContainer mol) return SmilesGenerator.Unique().Create(mol); } - private string PyrroleSmi = null; - private string FuranSmi = null; - private string ThiopheneSmi = null; - private string PyridineSmi = null; - private string PyrimidineSmi = null; - private string BenzeneSmi = null; - - private static string Smicache(string cached, SmilesParser smipar, string input) - { - if (cached != null) return cached; - return cached = Cansmi(smipar.ParseSmiles(input)); - } - /// /// Identifies ringSystem and returns a number which corresponds to /// CDKChemicalRingConstant @@ -208,30 +194,27 @@ private static string Smicache(string cached, SmilesParser smipar, string input) /// Ring class with the ring system /// smile of the ring system /// chemicalRingConstant - private int RingSystemClassifier(IRing ring, string smile) + private static int RingSystemClassifier(IRing ring, string smile) { - /* Console.Out.WriteLine("IN AtomTypeTools Smile:"+smile); */ - Debug.WriteLine("Comparing ring systems: SMILES=", smile); - - SmilesParser smipar = new SmilesParser(ring.Builder); - - if (smile.Equals(Smicache(PyrroleSmi, smipar, "c1cc[nH]c1"))) + Debug.WriteLine($"Comparing ring systems: SMILES={smile}"); + + if (smile.Equals(PyrroleSmi, StringComparison.Ordinal)) return PyrroleRing; - else if (smile.Equals(Smicache(FuranSmi, smipar, "o1cccc1"))) + else if (smile.Equals(FuranSmi, StringComparison.Ordinal)) return FuranRing; - else if (smile.Equals(Smicache(ThiopheneSmi, smipar, "c1ccsc1"))) + else if (smile.Equals(ThiopheneSmi, StringComparison.Ordinal)) return ThiopheneRing; - else if (smile.Equals(Smicache(PyridineSmi, smipar, "c1ccncc1"))) + else if (smile.Equals(PyridineSmi, StringComparison.Ordinal)) return PyridineRing; - else if (smile.Equals(Smicache(PyrimidineSmi, smipar, "c1cncnc1"))) + else if (smile.Equals(PyrimidineSmi, StringComparison.Ordinal)) return PyrimidineRing; - else if (smile.Equals(Smicache(BenzeneSmi, smipar, "c1ccccc1"))) + else if (smile.Equals(BenzeneSmi, StringComparison.Ordinal)) return BenzeneRing; int ncount = 0; foreach (var atom in ring.Atoms) { - if (atom.Symbol.Equals("N")) + if (string.Equals(atom.Symbol, "N", StringComparison.Ordinal)) { ncount = ncount + 1; } @@ -256,7 +239,7 @@ private int RingSystemClassifier(IRing ring, string smile) } } - private string RemoveAromaticityFlagsFromHoseCode(string hoseCode) + private static string RemoveAromaticityFlagsFromHoseCode(string hoseCode) { string hosecode = ""; for (int i = 0; i < hoseCode.Length; i++) diff --git a/NCDK/Tools/AtomicProperties.cs b/NCDK/Tools/AtomicProperties.cs index ef4f8dd3..b4bb2ddd 100644 --- a/NCDK/Tools/AtomicProperties.cs +++ b/NCDK/Tools/AtomicProperties.cs @@ -18,6 +18,7 @@ */ using System.Collections.Generic; +using System.Globalization; using System.IO; namespace NCDK.Tools @@ -31,92 +32,78 @@ namespace NCDK.Tools // @cdk.githash public class AtomicProperties { - private static AtomicProperties ap = null; + public static AtomicProperties Instance { get; } = new AtomicProperties(); - private IDictionary htMass = new Dictionary(); - private IDictionary htVdWVolume = new Dictionary(); - private IDictionary htElectronegativity = new Dictionary(); - private IDictionary htPolarizability = new Dictionary(); + private readonly Dictionary htMass = new Dictionary(); + private readonly Dictionary htVdWVolume = new Dictionary(); + private readonly Dictionary htElectronegativity = new Dictionary(); + private readonly Dictionary htPolarizability = new Dictionary(); private AtomicProperties() { string configFile = "NCDK.Config.Data.whim_weights.txt"; - using (var ins = ResourceLoader.GetAsStream(configFile)) - using (var bufferedReader = new StreamReader(ins)) + using (var bufferedReader = new StreamReader(ResourceLoader.GetAsStream(configFile))) { bufferedReader.ReadLine(); // header - string Line; + string line; while (true) { - Line = bufferedReader.ReadLine(); - if (Line == null) + line = bufferedReader.ReadLine(); + if (line == null) { break; } - string[] components = Line.Split('\t'); + string[] components = line.Split('\t'); string symbol = components[0]; - htMass[symbol] = double.Parse(components[1]); - htVdWVolume[symbol] = double.Parse(components[2]); - htElectronegativity[symbol] = double.Parse(components[3]); - htPolarizability[symbol] = double.Parse(components[4]); + htMass[symbol] = double.Parse(components[1], NumberFormatInfo.InvariantInfo); + htVdWVolume[symbol] = double.Parse(components[2], NumberFormatInfo.InvariantInfo); + htElectronegativity[symbol] = double.Parse(components[3], NumberFormatInfo.InvariantInfo); + htPolarizability[symbol] = double.Parse(components[4], NumberFormatInfo.InvariantInfo); } } } - public double GetVdWVolume(string symbol) + public virtual double GetVdWVolume(string symbol) { return htVdWVolume[symbol]; } - public double GetNormalizedVdWVolume(string symbol) + public virtual double GetNormalizedVdWVolume(string symbol) { return this.GetVdWVolume(symbol) / this.GetVdWVolume("C"); } - public double GetElectronegativity(string symbol) + public virtual double GetElectronegativity(string symbol) { return htElectronegativity[symbol]; } - public double GetNormalizedElectronegativity(string symbol) + public virtual double GetNormalizedElectronegativity(string symbol) { return this.GetElectronegativity(symbol) / this.GetElectronegativity("C"); } - public double GetPolarizability(string symbol) + public virtual double GetPolarizability(string symbol) { return htPolarizability[symbol]; } - public double GetNormalizedPolarizability(string symbol) + public virtual double GetNormalizedPolarizability(string symbol) { return this.GetPolarizability(symbol) / this.GetPolarizability("C"); } - public double GetMass(string symbol) + public virtual double GetMass(string symbol) { return htMass[symbol]; } - public double GetNormalizedMass(string symbol) + public virtual double GetNormalizedMass(string symbol) { return this.GetMass(symbol) / this.GetMass("C"); } - - public static AtomicProperties Instance - { - get - { - if (ap == null) - { - ap = new AtomicProperties(); - } - return ap; - } - } } } - diff --git a/NCDK/Tools/BremserOneSphereHOSECodePredictor.cs b/NCDK/Tools/BremserOneSphereHOSECodePredictor.cs index 7837c9c2..66c93e6a 100644 --- a/NCDK/Tools/BremserOneSphereHOSECodePredictor.cs +++ b/NCDK/Tools/BremserOneSphereHOSECodePredictor.cs @@ -31,7 +31,7 @@ namespace NCDK.Tools [Serializable] public class BremserOneSphereHOSECodePredictor { - Dictionary ht; + private Dictionary ht; public BremserOneSphereHOSECodePredictor() { @@ -99,15 +99,12 @@ public override string ToString() } - public string GetBibData() - { - string s = "The carbon NMR chemical shift prediction of this module \n"; - s += "is based on the 651 1-sphere HOSE-Code table published by W. Bremser in:\n"; - s += "W. Bremser, \"Expectation Ranges of 13C NMR Chemical Shifts\", \n"; - s += "Mag. Res. Chem., Vol. 23, No. 4, 1985, 271-275.\n"; - s += "It is important to understand, that these values are indeed not more than expectation ranges.\n"; - return s; - } + public static string BibData { get; } + = "The carbon NMR chemical shift prediction of this module \n" + + "is based on the 651 1-sphere HOSE-Code table published by W. Bremser in:\n" + + "W. Bremser, \"Expectation Ranges of 13C NMR Chemical Shifts\", \n" + + "Mag. Res. Chem., Vol. 23, No. 4, 1985, 271-275.\n" + + "It is important to understand, that these values are indeed not more than expectation ranges.\n"; private void PrepareHashTable() { diff --git a/NCDK/Tools/CDKHydrogenAdder.cs b/NCDK/Tools/CDKHydrogenAdder.cs index 70446104..23ef7d30 100644 --- a/NCDK/Tools/CDKHydrogenAdder.cs +++ b/NCDK/Tools/CDKHydrogenAdder.cs @@ -93,7 +93,7 @@ public void AddImplicitHydrogens(IAtomContainer container, IAtom atom) { if (atom.AtomTypeName == null) throw new CDKException("IAtom is not typed! " + atom.Symbol); - if ("X".Equals(atom.AtomTypeName)) + if (string.Equals("X", atom.AtomTypeName, StringComparison.Ordinal)) { if (atom.ImplicitHydrogenCount == null) atom.ImplicitHydrogenCount = 0; return; diff --git a/NCDK/Tools/CDKUtilities.cs b/NCDK/Tools/CDKUtilities.cs index 456a9710..542293be 100644 --- a/NCDK/Tools/CDKUtilities.cs +++ b/NCDK/Tools/CDKUtilities.cs @@ -34,7 +34,7 @@ namespace NCDK.Tools // @author Todd Martin // @cdk.module extra // @cdk.githash - public class CDKUtilities + public static class CDKUtilities { public static string FixSmiles(string Smiles) { @@ -56,7 +56,7 @@ private static bool FixNitroGroups(IAtomContainer m) for (int i = 0; i <= m.Atoms.Count - 1; i++) { IAtom a = m.Atoms[i]; - if (a.Symbol.Equals("N")) + if (string.Equals(a.Symbol, "N", StringComparison.Ordinal)) { var ca = m.GetConnectedAtoms(a).ToList(); @@ -68,7 +68,7 @@ private static bool FixNitroGroups(IAtomContainer m) for (int j = 0; j <= 2; j++) { - if (((IAtom)ca[j]).Symbol.Equals("O")) + if ((ca[j]).Symbol.Equals("O", StringComparison.Ordinal)) { count++; } @@ -81,7 +81,7 @@ private static bool FixNitroGroups(IAtomContainer m) for (int j = 0; j <= 2; j++) { IAtom caj = (IAtom)ca[j]; - if (caj.Symbol.Equals("O")) + if (string.Equals(caj.Symbol, "O", StringComparison.Ordinal)) { if (m.GetConnectedBonds(caj).Count() == 1) {// account for possibility of ONO2 @@ -127,7 +127,7 @@ public static bool FixNitroGroups2(IAtomContainer m) for (int i = 0; i <= m.Atoms.Count - 1; i++) { IAtom a = m.Atoms[i]; - if (a.Symbol.Equals("N")) + if (string.Equals(a.Symbol, "N", StringComparison.Ordinal)) { var ca = m.GetConnectedAtoms(a).ToList(); @@ -140,7 +140,7 @@ public static bool FixNitroGroups2(IAtomContainer m) for (int j = 0; j <= 2; j++) { IAtom caj = ca[j]; - if (caj.Symbol.Equals("O")) + if (string.Equals(caj.Symbol, "O", StringComparison.Ordinal)) { count++; } @@ -152,7 +152,7 @@ public static bool FixNitroGroups2(IAtomContainer m) for (int j = 0; j <= 2; j++) { IAtom caj = (IAtom)ca[j]; - if (caj.Symbol.Equals("O")) + if (string.Equals(caj.Symbol, "O", StringComparison.Ordinal)) { if (m.GetConnectedBonds(caj).Count() == 1) {// account for possibility of ONO2 @@ -268,7 +268,7 @@ public static void FixSulphurH(IAtomContainer m) { IAtom a = m.Atoms[i]; - if (a.Symbol.Equals("S")) + if (string.Equals(a.Symbol, "S", StringComparison.Ordinal)) { var connectedAtoms = m.GetConnectedAtoms(a); @@ -276,7 +276,7 @@ public static void FixSulphurH(IAtomContainer m) foreach (var conAtom in connectedAtoms) { - if (!conAtom.Symbol.Equals("H")) + if (!string.Equals(conAtom.Symbol, "H", StringComparison.Ordinal)) { IBond bond = m.GetBond(a, conAtom); if (bond.Order == BondOrder.Single) @@ -302,7 +302,7 @@ public static void FixSulphurH(IAtomContainer m) { foreach (var conAtom in connectedAtoms) { - if (conAtom.Symbol.Equals("H")) + if (string.Equals(conAtom.Symbol, "H", StringComparison.Ordinal)) { m.RemoveAtom(conAtom); } diff --git a/NCDK/Tools/DataFeatures.cs b/NCDK/Tools/DataFeatures.cs index 031eaf53..e3e8fbda 100644 --- a/NCDK/Tools/DataFeatures.cs +++ b/NCDK/Tools/DataFeatures.cs @@ -52,40 +52,40 @@ public enum DataFeatures // COORDINATE SYSTEMS /// @cdk.dictref bodf:coordinates2D - HAS_2D_COORDINATES = 1 << 0, + Has2DCoordinates = 1 << 0, /// @cdk.dictref bodf:coordinates3D - HAS_3D_COORDINATES = 1 << 1, + Has3DCoordinates = 1 << 1, /// @cdk.dictref bodf:fractionalUnitCellCoordinatesCoordinates - HAS_FRACTIONAL_CRYSTAL_COORDINATES = 1 << 2, + HasFractionalCrystalCoordinates = 1 << 2, // ATOMIC FEATURES // HAS_ATOMS ?? /// @cdk.dictref bodf:hasAtomElementSymbol - HAS_ATOM_ELEMENT_SYMBOL = 1 << 3, + HasAtomElementSymbol = 1 << 3, /// @cdk.dictref bodf:partialAtomicCharges - HAS_ATOM_PARTIAL_CHARGES = 1 << 4, + HasAtomPartialCharges = 1 << 4, /// @cdk.dictref bodf:formalAtomicCharges - HAS_ATOM_FORMAL_CHARGES = 1 << 5, + HasAtomFormalCharges = 1 << 5, /// FIXME: NOT YET IN BODF !!! - HAS_ATOM_HYBRIDIZATIONS = 1 << 6, + HasAtomHybridizations = 1 << 6, /// @cdk.dictref bodf:massNumbers - HAS_ATOM_MASS_NUMBERS = 1 << 7, + HasAtomMassNumbers = 1 << 7, /// @cdk.dictref bodf:isotopeNumbers - HAS_ATOM_ISOTOPE_NUMBERS = 1 << 8, + HasAtomIsotopeNumbers = 1 << 8, // GRAPH FEATURES /// @cdk.dictref bodf:graphRepresentation - HAS_GRAPH_REPRESENTATION = 1 << 9, + HasGraphRepresentation = 1 << 9, /// @cdk.dictref bodf:dietzRepresentation - HAS_DIETZ_REPRESENTATION = 1 << 10, + HasDietzRepresentation = 1 << 10, // MODEL FEATURES /// FIXME: NOT YET IN BODF !!! - HAS_UNITCELL_PARAMETERS = 1 << 11, + HasUnitcellParameters = 1 << 11, /// FIXME: NOT YET IN BODF !!! - HAS_REACTIONS = 1 << 12, + HasReactions = 1 << 12, } } diff --git a/NCDK/Tools/DataFeaturesTool.cs b/NCDK/Tools/DataFeaturesTool.cs index 63e981ed..482313ec 100644 --- a/NCDK/Tools/DataFeaturesTool.cs +++ b/NCDK/Tools/DataFeaturesTool.cs @@ -44,17 +44,17 @@ public static DataFeatures GetSupportedDataFeatures(IAtomContainer molecule) { DataFeatures features = DataFeatures.None; if (MoleculeFeaturesTool.HasElementSymbols(molecule)) - features = features | DataFeatures.HAS_ATOM_ELEMENT_SYMBOL; - if (GeometryUtil.Has2DCoordinates(molecule)) features = features | DataFeatures.HAS_2D_COORDINATES; - if (GeometryUtil.Has3DCoordinates(molecule)) features = features | DataFeatures.HAS_3D_COORDINATES; + features = features | DataFeatures.HasAtomElementSymbol; + if (GeometryUtil.Has2DCoordinates(molecule)) features = features | DataFeatures.Has2DCoordinates; + if (GeometryUtil.Has3DCoordinates(molecule)) features = features | DataFeatures.Has3DCoordinates; if (CrystalGeometryTools.HasCrystalCoordinates(molecule)) - features = features | DataFeatures.HAS_FRACTIONAL_CRYSTAL_COORDINATES; + features = features | DataFeatures.HasFractionalCrystalCoordinates; if (MoleculeFeaturesTool.HasFormalCharges(molecule)) - features = features | DataFeatures.HAS_ATOM_FORMAL_CHARGES; + features = features | DataFeatures.HasAtomFormalCharges; if (MoleculeFeaturesTool.HasPartialCharges(molecule)) - features = features | DataFeatures.HAS_ATOM_PARTIAL_CHARGES; + features = features | DataFeatures.HasAtomPartialCharges; if (MoleculeFeaturesTool.HasGraphRepresentation(molecule)) - features = features | DataFeatures.HAS_GRAPH_REPRESENTATION; + features = features | DataFeatures.HasGraphRepresentation; return features; } } diff --git a/NCDK/Tools/Diff/AtomContainerDiff.cs b/NCDK/Tools/Diff/AtomContainerDiff.cs index 329b9cc3..e45eda9e 100644 --- a/NCDK/Tools/Diff/AtomContainerDiff.cs +++ b/NCDK/Tools/Diff/AtomContainerDiff.cs @@ -60,9 +60,9 @@ public static IDifference Difference(IChemObject first, IChemObject second) { return null; } - IAtomContainer firstAC = (IAtomContainer)first; - IAtomContainer secondAC = (IAtomContainer)second; - ChemObjectDifference totalDiff = new ChemObjectDifference("AtomContainerDiff"); + var firstAC = (IAtomContainer)first; + var secondAC = (IAtomContainer)second; + var totalDiff = new ChemObjectDifference("AtomContainerDiff"); totalDiff.AddChild(IntegerDifference.Construct("atomCount", firstAC.Atoms.Count, secondAC.Atoms.Count)); if (firstAC.Atoms.Count == secondAC.Atoms.Count) { diff --git a/NCDK/Tools/Diff/Tree/AbstractDifference.cs b/NCDK/Tools/Diff/Tree/AbstractDifference.cs index ab116300..36a62b45 100644 --- a/NCDK/Tools/Diff/Tree/AbstractDifference.cs +++ b/NCDK/Tools/Diff/Tree/AbstractDifference.cs @@ -20,7 +20,7 @@ namespace NCDK.Tools.Diff.Tree { /// - /// Difference between two IChemObjects. + /// Difference between two s. /// // @author egonw // @cdk.module diff diff --git a/NCDK/Tools/Diff/Tree/AbstractDifferenceList.cs b/NCDK/Tools/Diff/Tree/AbstractDifferenceList.cs index 020728b2..eae58aef 100644 --- a/NCDK/Tools/Diff/Tree/AbstractDifferenceList.cs +++ b/NCDK/Tools/Diff/Tree/AbstractDifferenceList.cs @@ -29,7 +29,7 @@ namespace NCDK.Tools.Diff.Tree // @cdk.githash public abstract class AbstractDifferenceList : IDifferenceList { - protected List differences; + private List differences; protected AbstractDifferenceList() { diff --git a/NCDK/Tools/Diff/Tree/BooleanArrayDifference.cs b/NCDK/Tools/Diff/Tree/BooleanArrayDifference.cs index db4f340f..42655064 100644 --- a/NCDK/Tools/Diff/Tree/BooleanArrayDifference.cs +++ b/NCDK/Tools/Diff/Tree/BooleanArrayDifference.cs @@ -33,7 +33,7 @@ namespace NCDK.Tools.Diff.Tree public class BooleanArrayDifference : AbstractDifferenceList, IDifferenceList { - private string name; + private readonly string name; private BooleanArrayDifference(string name) { @@ -96,7 +96,8 @@ public static IDifference Construct(string name, bool[] first, bool[] second) /// a public override string ToString() { - if (differences.Count() == 0) return ""; + if (ChildCount() == 0) + return ""; var diffBuffer = new StringBuilder(); diffBuffer.Append(this.name).Append('{'); diff --git a/NCDK/Tools/Diff/Tree/ChemObjectDifference.cs b/NCDK/Tools/Diff/Tree/ChemObjectDifference.cs index 915e6cb8..51d0e059 100644 --- a/NCDK/Tools/Diff/Tree/ChemObjectDifference.cs +++ b/NCDK/Tools/Diff/Tree/ChemObjectDifference.cs @@ -31,9 +31,9 @@ namespace NCDK.Tools.Diff.Tree // @cdk.module diff // @cdk.githash public class ChemObjectDifference - : AbstractDifferenceList, IDifferenceList + : AbstractDifferenceList, IDifferenceList { - private string name; + private readonly string name; public ChemObjectDifference(string name) { @@ -42,28 +42,18 @@ public ChemObjectDifference(string name) /// /// Returns a representation for this . - /// - /// a /// - + /// A representation for this public override string ToString() { - if (differences.Count() == 0) return ""; + if (ChildCount() == 0) + return ""; - StringBuilder diffBuffer = new StringBuilder(); - diffBuffer.Append(this.name).Append('{'); - IEnumerable children = GetChildren(); - bool isFirst = true; - foreach (var child in children) - { - if (!isFirst) - { - diffBuffer.Append(", "); - isFirst = false; - } - diffBuffer.Append(child.ToString()); - } - diffBuffer.Append('}'); + var diffBuffer = new StringBuilder(); + diffBuffer.Append(this.name) + .Append('{') + .Append(string.Join(", ", GetChildren())) + .Append('}'); return diffBuffer.ToString(); } diff --git a/NCDK/Tools/Diff/Tree/Point2dDifference.cs b/NCDK/Tools/Diff/Tree/Point2dDifference.cs index d085154b..318c0bf1 100644 --- a/NCDK/Tools/Diff/Tree/Point2dDifference.cs +++ b/NCDK/Tools/Diff/Tree/Point2dDifference.cs @@ -32,7 +32,7 @@ namespace NCDK.Tools.Diff.Tree public class Point2DDifference : AbstractDifferenceList, IDifferenceList { - private string name; + private readonly string name; private Point2DDifference(string name) { @@ -66,7 +66,8 @@ public static IDifference Construct(string name, Vector2? first, Vector2? second /// a public override string ToString() { - if (differences.Count() == 0) return ""; + if (ChildCount() == 0) + return ""; StringBuilder diffBuffer = new StringBuilder(); diffBuffer.Append(this.name).Append('{'); diff --git a/NCDK/Tools/Diff/Tree/Point3dDifference.cs b/NCDK/Tools/Diff/Tree/Point3dDifference.cs index d130196c..2678e819 100644 --- a/NCDK/Tools/Diff/Tree/Point3dDifference.cs +++ b/NCDK/Tools/Diff/Tree/Point3dDifference.cs @@ -18,7 +18,6 @@ */ using NCDK.Numerics; -using System.Linq; using System.Text; namespace NCDK.Tools.Diff.Tree @@ -32,7 +31,7 @@ namespace NCDK.Tools.Diff.Tree public class Point3DDifference : AbstractDifferenceList, IDifferenceList { - private string name; + private readonly string name; private Point3DDifference(string name) { @@ -67,7 +66,8 @@ public static IDifference Construct(string name, Vector3? first, Vector3? second /// a public override string ToString() { - if (differences.Count() == 0) return ""; + if (ChildCount() == 0) + return ""; StringBuilder diffBuffer = new StringBuilder(); diffBuffer.Append(this.name).Append('{'); diff --git a/NCDK/Tools/Diff/Tree/StringDifference.cs b/NCDK/Tools/Diff/Tree/StringDifference.cs index 9d734f4a..c3ed8909 100644 --- a/NCDK/Tools/Diff/Tree/StringDifference.cs +++ b/NCDK/Tools/Diff/Tree/StringDifference.cs @@ -17,6 +17,8 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; + namespace NCDK.Tools.Diff.Tree { /// @@ -27,9 +29,9 @@ namespace NCDK.Tools.Diff.Tree // @cdk.githash public class StringDifference : IDifference { - private string name; - private string first; - private string second; + private readonly string name; + private readonly string first; + private readonly string second; private StringDifference(string name, string first, string second) { @@ -55,7 +57,7 @@ public static IDifference Construct(string name, string first, string second) { return new StringDifference(name, first, second); } - if (first.Equals(second)) + if (first.Equals(second, StringComparison.Ordinal)) { return null; // no difference } diff --git a/NCDK/Tools/ElementComparator.cs b/NCDK/Tools/ElementComparator.cs index 8e74ea2c..3a194cbe 100644 --- a/NCDK/Tools/ElementComparator.cs +++ b/NCDK/Tools/ElementComparator.cs @@ -46,42 +46,35 @@ public class ElementComparator : IComparer /// public int Compare(string o1, string o2) { - if (C_ELEMENT_SYMBOL.Equals(o1)) + switch (o1) { - if (C_ELEMENT_SYMBOL.Equals(o2)) - { - return 0; - } - else - { - return -1; - } - } - else if (H_ELEMENT_SYMBOL.Equals(o1)) - { - if (C_ELEMENT_SYMBOL.Equals(o2)) - { - return 1; - } - else if (H_ELEMENT_SYMBOL.Equals(o2)) - { - return 0; - } - else - { - return -1; - } - } - else - { - if (C_ELEMENT_SYMBOL.Equals(o2) || H_ELEMENT_SYMBOL.Equals(o2)) - { - return 1; - } - else - { - return string.Compare((string)o1, (string)o2, StringComparison.Ordinal); - } + case C_ELEMENT_SYMBOL: + switch (o2) + { + case C_ELEMENT_SYMBOL: + return 0; + default: + return -1; + } + case H_ELEMENT_SYMBOL: + switch (o2) + { + case C_ELEMENT_SYMBOL: + return 1; + case H_ELEMENT_SYMBOL: + return 0; + default: + return -1; + } + default: + switch (o2) + { + case C_ELEMENT_SYMBOL: + case H_ELEMENT_SYMBOL: + return 1; + default: + return string.Compare(o1, o2, StringComparison.Ordinal); + } } } } diff --git a/NCDK/Tools/GridGenerator.cs b/NCDK/Tools/GridGenerator.cs index e9ef7c55..ccee499c 100644 --- a/NCDK/Tools/GridGenerator.cs +++ b/NCDK/Tools/GridGenerator.cs @@ -172,7 +172,7 @@ public void InitializeGrid(double value) /// /// Method initialise the given Grid points with a value. /// - public double[][][] InitializeGrid(double[][][] Grid, double value) + public static double[][][] InitializeGrid(double[][][] Grid, double value) { for (int i = 0; i < Grid.Length; i++) { diff --git a/NCDK/Tools/HOSECodeAnalyser.cs b/NCDK/Tools/HOSECodeAnalyser.cs index 1dd3a996..5c91b6d1 100644 --- a/NCDK/Tools/HOSECodeAnalyser.cs +++ b/NCDK/Tools/HOSECodeAnalyser.cs @@ -42,9 +42,9 @@ namespace NCDK.Tools // @cdk.githash public static class HOSECodeAnalyser { - public static IList GetElements(string code) + public static IReadOnlyList GetElements(string code) { - List elementList = new List(); + var elementList = new List(); if (code.Length == 0) { @@ -76,17 +76,17 @@ public static IList GetElements(string code) if (!elementList.Contains(currentSymbol)) { // reverse HOSECodeGenerator.getElementSymbol translations - if (currentSymbol.Equals("Y")) + switch (currentSymbol) { - currentSymbol = "Br"; - } - else if (currentSymbol.Equals("X")) - { - currentSymbol = "Cl"; - } - else if (currentSymbol.Equals("Q")) - { - currentSymbol = "Si"; + case "Y": + currentSymbol = "Br"; + break; + case "X": + currentSymbol = "Cl"; + break; + case "Q": + currentSymbol = "Si"; + break; } elementList.Add(currentSymbol); } diff --git a/NCDK/Tools/HOSECodeGenerator.cs b/NCDK/Tools/HOSECodeGenerator.cs index c6e7c25b..eb9f0f20 100644 --- a/NCDK/Tools/HOSECodeGenerator.cs +++ b/NCDK/Tools/HOSECodeGenerator.cs @@ -38,75 +38,77 @@ namespace NCDK.Tools { /// /// Generates HOSE codes cdk-cite-BRE78. - /// IMPORTANT: Your molecule must contain implicit or explicit hydrogens - /// for this method to work properly. /// + /// + /// + /// Your molecule must contain implicit or explicit hydrogens + /// for this method to work properly. + /// + /// // @author steinbeck // @cdk.githash // @cdk.keyword HOSE code, spherical atom search // @cdk.created 2002-05-10 // @cdk.module standard - [Serializable] public class HOSECodeGenerator { /// /// Container for the nodes in a sphere. /// - protected List sphereNodes = null; - protected List sphereNodesWithAtoms = null; + private List sphereNodes; + private readonly List sphereNodesWithAtoms; /// /// Container for the node in the next sphere assembled in a recursive method /// and then passed to the next recursion to become . /// - protected List nextSphereNodes = null; + private List nextSphereNodes; /// /// Counter for the sphere in which we currently work. /// - protected int sphere = 0; + private int sphere = 0; /// /// How many spheres are we supposed inspect. /// - protected int maxSphere = 0; + private int maxSphere = 0; /// /// Here we store the spheres that we assemble, in order to parse them into a code later. /// - protected List[] spheres = null; - protected List[] spheresWithAtoms = null; + private List[] spheres; + private List[] spheresWithAtoms; /// /// The HOSECode string that we assemble /// - protected StringBuilder HOSECode = null; + private StringBuilder HOSECode = null; /// /// The molecular structure on which we work /// - protected IAtomContainer atomContainer; + private IAtomContainer atomContainer; /// /// Delimiters used to separate spheres in the output string. Bremser uses the /// sequence"(//)" for the first four spheres. /// - protected string[] sphereDelimiters = { "(", "/", "/", ")", "/", "/", "/", "/", "/", "/", "/", "/" }; + private readonly string[] sphereDelimiters = new string[] { "(", "/", "/", ")", "/", "/", "/", "/", "/", "/", "/", "/" }; /// /// The bond symbols used for bond orders "single", "double", "triple" and "aromatic" /// - protected string[] bondSymbols = { "", "", "=", "%", "*" }; - protected string centerCode = null; - public TreeNode rootNode = null; - private IAtomContainer acold = null; + private readonly string[] bondSymbols = new string[] { "", "", "=", "%", "*" }; + private string centerCode = null; + private TreeNode rootNode = null; + private readonly IAtomContainer acold = null; private IRingSet soar = null; /// /// The rank order for the given element symbols. /// - static readonly string[] rankedSymbols = {"C", "O", "N", "S", "P", "Si", "B", "F", "Cl", "Br", ";", "I", - "#", "&", "," }; + private static readonly string[] rankedSymbols = new string[] {"C", "O", "N", "S", "P", "Si", "B", "F", "Cl", "Br", ";", "I", "#", "&", "," }; /// /// The ranking values to be used for the symbols above. @@ -135,7 +137,7 @@ private void EnsureIsotopeFactory() { try { - isotopeFac = Isotopes.Instance; + isotopeFac = BODRIsotopeFactory.Instance; } catch (IOException e) { @@ -145,15 +147,15 @@ private void EnsureIsotopeFactory() } /// - /// This method is intended to be used to get the atoms around an atom in spheres. It is not used in this class, but is provided for other classes to use. - /// It also creates the HOSE code in HOSECode as a side-effect. + /// This method is intended to be used to get the atoms around an atom in spheres. It is not used in this class, but is provided for other classes to use. + /// It also creates the HOSE code in HOSECode as a side-effect. /// /// The with the molecular skeleton in which the root atom resides. /// The root atom for which to produce the spheres. /// The number of spheres to look at. /// Shall the center code have the ring size in it? Only use if you want to have the hose code later, else say false. - /// An array of . The list at i-1 contains the atoms at sphere i as s. - public IList[] GetSpheres(IAtomContainer ac, IAtom root, int noOfSpheres, bool ringsize) + /// An array of . The list at i-1 contains the atoms at sphere i as s. + public IReadOnlyList[] GetSpheres(IAtomContainer ac, IAtom root, int noOfSpheres, bool ringsize) { EnsureIsotopeFactory(); centerCode = ""; @@ -254,7 +256,7 @@ public string GetHOSECode(IAtomContainer ac, IAtom root, int noOfSpheres, bool r BreadthFirstSearch(root, true); CreateCode(); FillUpSphereDelimiters(); - Debug.WriteLine("HOSECodeGenerator -> HOSECode: ", HOSECode); + Debug.WriteLine($"HOSECodeGenerator -> HOSECode: {HOSECode}"); return HOSECode.ToString(); } @@ -284,13 +286,13 @@ private string GetRingcode(IAtom root, IAtomContainer ac) { if (bool_[i]) sb.Append(i + ""); } - if (sb.ToString() == string.Empty) + if (sb.Length == 0) return ""; else return "-" + sb.ToString(); } - private string CreateChargeCode(IAtom atom) + private static string CreateChargeCode(IAtom atom) { StringBuilder tempCode = new StringBuilder(); @@ -320,8 +322,8 @@ private string CreateChargeCode(IAtom atom) } /// - /// Prepares for a breadth first search within the . The actual - /// recursion is done in . + /// Prepares for a breadth first search within the . The actual + /// recursion is done in . /// /// The atom at which we start the search /// @@ -338,7 +340,7 @@ private void BreadthFirstSearch(IAtom root, bool addTreeNode) { try { - if (atom.Symbol.Equals("H")) continue; + if (string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) continue; bond = atomContainer.GetBond(root, atom); // In the first sphere the atoms are labeled with their own atom @@ -382,7 +384,8 @@ private void BreadthFirstSearch(IAtom root, bool addTreeNode) private void NextSphere(List sphereNodes) { spheres[sphere] = sphereNodes; - if (spheresWithAtoms != null) spheresWithAtoms[sphere] = sphereNodesWithAtoms; + if (spheresWithAtoms != null) + spheresWithAtoms[sphere] = sphereNodesWithAtoms; // From here we start assembling the next sphere IAtom node = null; @@ -393,10 +396,11 @@ private void NextSphere(List sphereNodes) for (int i = 0; i < sphereNodes.Count; i++) { treeNode = (TreeNode)sphereNodes[i]; - if (!("&;#:,".IndexOf(treeNode.symbol) >= 0)) + if (!("&;#:,".IndexOf(treeNode.symbol, StringComparison.Ordinal) >= 0)) { node = treeNode.Atom; - if (node.Symbol.Equals("H")) continue; + if (string.Equals(node.Symbol, "H", StringComparison.Ordinal)) + continue; var conAtoms = atomContainer.GetConnectedAtoms(node).ToList(); if (conAtoms.Count == 1) @@ -413,8 +417,8 @@ private void NextSphere(List sphereNodes) bond = atomContainer.GetBond(node, toNode); if (bond.IsAromatic) { - nextSphereNodes.Add(new TreeNode(this, toNode.Symbol, treeNode, toNode, 4, atomContainer - .GetConnectedBonds(toNode).Count(), treeNode.score)); + nextSphereNodes.Add( + new TreeNode(this, toNode.Symbol, treeNode, toNode, 4, atomContainer.GetConnectedBonds(toNode).Count(), treeNode.score)); } else { @@ -436,7 +440,7 @@ private void NextSphere(List sphereNodes) } } - public string MakeBremserCompliant(string code) + internal static string MakeBremserCompliant(string code) { int sepIndex = code.IndexOf(';'); if (sepIndex >= 0) @@ -447,8 +451,8 @@ public string MakeBremserCompliant(string code) } /// - /// After recursively having established the spheres and assigning each node an - /// appropriate score, we now generate the complete HOSE code. + /// After recursively having established the spheres and assigning each node an + /// appropriate score, we now generate the complete HOSE code. /// /// Thrown if something goes wrong private void CreateCode() @@ -516,7 +520,7 @@ private void CreateCode() } /// - /// Generates the string code for a given sphere. + /// Generates the string code for a given sphere. /// /// A vector of TreeNodes for which a string code is to be generated /// The SphereCode value @@ -582,7 +586,7 @@ private double GetElementRank(string symbol) { for (int f = 0; f < rankedSymbols.Length; f++) { - if (rankedSymbols[f].Equals(symbol)) + if (string.Equals(rankedSymbols[f], symbol, StringComparison.Ordinal)) { return symbolRankings[f]; } @@ -592,35 +596,31 @@ private double GetElementRank(string symbol) } /// - /// Returns the Bremser-compatible symbols for a given element. Silicon, for - /// example, is actually "Q". :-) + /// Returns the Bremser-compatible symbols for a given element. Silicon, for + /// example, is actually "Q". :-) /// /// The element symbol to be converted /// The converted symbol - private string GetElementSymbol(string sym) + private static string GetElementSymbol(string sym) { - if (sym.Equals("Si")) - { - return "Q"; + switch (sym) + { + case "Si": + return "Q"; + case "Cl": + return "X"; + case "Br": + return "Y"; + case ",": + return ""; + default: + return sym; } - if (sym.Equals("Cl")) - { - return "X"; - } - if (sym.Equals("Br")) - { - return "Y"; - } - if (sym.Equals(",")) - { - return ""; - } - return sym; } /// - /// Determines the ranking score for each node, allowing for a sorting of nodes - /// within one sphere. + /// Determines the ranking score for each node, allowing for a sorting of nodes + /// within one sphere. /// /// The nodes for which the score is to be calculated. /// Thrown if something goes wrong. @@ -643,15 +643,16 @@ private void CalculateNodeScores(List sphereNodes) } /// - /// Sorts the nodes (atoms) in the sphereNode vector according to their score. - /// This is used for the essential ranking of nodes in HOSE code sphere. + /// Sorts the nodes (atoms) in the sphereNode vector according to their score. + /// This is used for the essential ranking of nodes in HOSE code sphere. /// /// A vector with sphere nodes to be sorted. - private void SortNodesByScore(List sphereNodes) + private static void SortNodesByScore(List sphereNodes) { TreeNode obj; bool changed; - if (sphereNodes.Count == 0) return; + if (sphereNodes.Count == 0) + return; // Now we sort by score do @@ -673,18 +674,18 @@ private void SortNodesByScore(List sphereNodes) TreeNode temp = null; for (int i = 0; i < sphereNodes.Count; i++) { - temp = ((TreeNode)sphereNodes[i]); + temp = sphereNodes[i]; temp.sortOrder = sphereNodes.Count - i; } } /// - /// If we use less than four sphere, this fills up the code with the missing - /// delimiters such that we are compatible with Bremser's HOSE code table. + /// If we use less than four sphere, this fills up the code with the missing + /// delimiters such that we are compatible with Bremser's HOSE code table. /// private void FillUpSphereDelimiters() { - Debug.WriteLine("Sphere: " + sphere); + Debug.WriteLine($"Sphere: {sphere}"); for (int f = sphere; f < 4; f++) { HOSECode.Append(sphereDelimiters[f]); @@ -694,7 +695,7 @@ private void FillUpSphereDelimiters() class TreeNodeComparator : IComparer { /// - ///The compare method, compares by canonical label of atoms + /// The compare method, compares by canonical label of atoms /// /// The first TreeNode /// The second TreeNode @@ -710,24 +711,23 @@ public int Compare(TreeNode a, TreeNode b) /// /// a tree node to get the label from /// canonical label value - private long Label(TreeNode node) + private static long Label(TreeNode node) { if (node == null) return long.MinValue; IAtom atom = node.Atom; if (atom == null) return long.MinValue; // cast can be removed in master - long label = atom.GetProperty(InvPair.CanonicalLabelKey, long.MinValue); + long label = atom.GetProperty(InvPair.CanonicalLabelPropertyKey, long.MinValue); return label ; } } /// - /// Helper class for storing the properties of a node in our breadth first search. + /// Helper class for storing the properties of a node in our breadth first search. /// // @author steinbeck // @cdk.created 2002-11-16 - [Serializable] - public class TreeNode + internal class TreeNode { private HOSECodeGenerator parent; @@ -739,7 +739,7 @@ public class TreeNode internal long score; internal int ranking; internal int sortOrder = 1; - List childs = null; + private readonly List childs = null; internal string hSymbol = null; internal bool stopper = false; internal string stringscore = ""; @@ -778,8 +778,7 @@ public TreeNode(HOSECodeGenerator parent, string symbol, TreeNode source, IAtom /// , if the this 's atom object equals the one of the other public override bool Equals(object o) { - var n = o as TreeNode; - if (n == null) + if (!(o is TreeNode n)) return false; return this.atom == n.atom; } @@ -808,15 +807,12 @@ public override string ToString() } } - public IList GetNodesInSphere(int sphereNumber) + public IEnumerable GetNodesInSphere(int sphereNumber) { sphereNodes = spheres[sphereNumber - 1]; - List atoms = new List(); for (int g = 0; g < sphereNodes.Count; g++) - { - atoms.Add(((TreeNode)sphereNodes[g]).atom); - } - return (atoms); + yield return sphereNodes[g].atom; + yield break; } } } diff --git a/NCDK/Tools/IDCreator.cs b/NCDK/Tools/IDCreator.cs index ad529c9f..e1ce9671 100644 --- a/NCDK/Tools/IDCreator.cs +++ b/NCDK/Tools/IDCreator.cs @@ -73,7 +73,9 @@ public enum UniquePolicy /// /// New ID generation policy - to generate IDs unique only in a molecule /// +#pragma warning disable CA1720 // Identifier contains type name Object = 1, +#pragma warning restore CA1720 // Identifier contains type name } /// diff --git a/NCDK/Tools/LonePairElectronChecker.cs b/NCDK/Tools/LonePairElectronChecker.cs index b264422e..2642478c 100644 --- a/NCDK/Tools/LonePairElectronChecker.cs +++ b/NCDK/Tools/LonePairElectronChecker.cs @@ -34,23 +34,15 @@ namespace NCDK.Tools // @cdk.keyword saturation // @cdk.keyword atom, valency // @cdk.module standard - public class LonePairElectronChecker + public static class LonePairElectronChecker { - private static AtomTypeFactory factory; - - private void CreateAtomTypeFactory(IChemObjectBuilder builder) - { - if (factory == null) - { - factory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", builder); - } - } + private static AtomTypeFactory factory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", Silent.ChemObjectBuilder.Instance); /// /// Determines of all atoms on the AtomContainer have the /// right number the lone pair electrons. /// - public bool IsSaturated(IAtomContainer container) + public static bool IsSaturated(IAtomContainer container) { return AllSaturated(container); } @@ -59,12 +51,13 @@ public bool IsSaturated(IAtomContainer container) /// Determines of all atoms on the AtomContainer have /// the right number the lone pair electrons. /// - public bool AllSaturated(IAtomContainer ac) + public static bool AllSaturated(IAtomContainer ac) { Debug.WriteLine("Are all atoms saturated?"); for (int f = 0; f < ac.Atoms.Count; f++) { - if (!IsSaturated(ac.Atoms[f], ac)) return false; + if (!IsSaturated(ac.Atoms[f], ac)) + return false; } return true; } @@ -74,9 +67,8 @@ public bool AllSaturated(IAtomContainer ac) /// by comparing it with known AtomTypes. /// /// True, if it's right saturated - public bool IsSaturated(IAtom atom, IAtomContainer ac) + public static bool IsSaturated(IAtom atom, IAtomContainer ac) { - CreateAtomTypeFactory(ac.Builder); IAtomType atomType = factory.GetAtomType(atom.AtomTypeName); int lpCount = atomType.GetProperty(CDKPropertyName.LonePairCount); int foundLPCount = ac.GetConnectedLonePairs(atom).Count(); @@ -86,7 +78,7 @@ public bool IsSaturated(IAtom atom, IAtomContainer ac) /// /// Saturates a molecule by setting appropriate number lone pair electrons. /// - public void Saturate(IAtomContainer atomContainer) + public static void Saturate(IAtomContainer atomContainer) { Trace.TraceInformation("Saturating atomContainer by adjusting lone pair electrons..."); bool allSaturated = AllSaturated(atomContainer); @@ -102,7 +94,7 @@ public void Saturate(IAtomContainer atomContainer) /// /// Saturates an IAtom by adding the appropriate number lone pairs. /// - public void Saturate(IAtom atom, IAtomContainer ac) + public static void Saturate(IAtom atom, IAtomContainer ac) { Trace.TraceInformation("Saturating atom by adjusting lone pair electrons..."); IAtomType atomType = factory.GetAtomType(atom.AtomTypeName); diff --git a/NCDK/Tools/Manipulator/AminoAcidManipulator.cs b/NCDK/Tools/Manipulator/AminoAcidManipulator.cs index 52b7d537..f8aa68f8 100644 --- a/NCDK/Tools/Manipulator/AminoAcidManipulator.cs +++ b/NCDK/Tools/Manipulator/AminoAcidManipulator.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Collections.Generic; namespace NCDK.Tools.Manipulator @@ -52,7 +53,7 @@ public static void RemoveAcidicOxygen(IAminoAcid acid) { for (int j = 0; j < bond.Atoms.Count; j++) { - if (bond.Atoms[j].Symbol.Equals("O")) + if (string.Equals(bond.Atoms[j].Symbol, "O", StringComparison.Ordinal)) { // yes, we found a singly bonded oxygen! atomsToRemove.Add(bond.Atoms[j]); diff --git a/NCDK/Tools/Manipulator/AtomContainerComparator.cs b/NCDK/Tools/Manipulator/AtomContainerComparator.cs index 269313c9..5594c8e2 100644 --- a/NCDK/Tools/Manipulator/AtomContainerComparator.cs +++ b/NCDK/Tools/Manipulator/AtomContainerComparator.cs @@ -22,6 +22,7 @@ */ using NCDK.Config; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -138,16 +139,16 @@ public int Compare(T o1, T o2) /// if an error occurs with the IsotopeFactory /// the molecularweight (exact mass) of the major isotopes /// of all heavy atoms of the given IAtomContainer - private double GetMolecularWeight(T atomContainer) + private static double GetMolecularWeight(T atomContainer) { double mw = 0.0; try { - IsotopeFactory isotopeFactory = Isotopes.Instance; + IsotopeFactory isotopeFactory = BODRIsotopeFactory.Instance; foreach (var atom in atomContainer.Atoms) { - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { IIsotope majorIsotope = isotopeFactory.GetMajorIsotope(atom.Symbol); diff --git a/NCDK/Tools/Manipulator/AtomContainerManipulator.cs b/NCDK/Tools/Manipulator/AtomContainerManipulator.cs index 79a361af..d68ad74e 100644 --- a/NCDK/Tools/Manipulator/AtomContainerManipulator.cs +++ b/NCDK/Tools/Manipulator/AtomContainerManipulator.cs @@ -87,17 +87,18 @@ public static IAtomContainer ExtractSubstructure(IAtomContainer atomContainer, p } /// - /// Returns an atom in an atomcontainer identified by id + /// Returns an atom in an atom container identified by id /// - /// The AtomContainer to search in + /// The atom container to search in /// The id to search for - /// An atom having id id + /// An atom having /// There is no such atom public static IAtom GetAtomById(IAtomContainer ac, string id) { for (int i = 0; i < ac.Atoms.Count; i++) { - if (ac.Atoms[i].Id != null && ac.Atoms[i].Id.Equals(id)) return ac.Atoms[i]; + if (ac.Atoms[i].Id != null && string.Equals(ac.Atoms[i].Id, id, StringComparison.Ordinal)) + return ac.Atoms[i]; } throw new CDKException("no suc atom"); } @@ -118,11 +119,11 @@ public static bool ReplaceAtomByAtom(IAtomContainer container, IAtom oldAtom, IA if (idx < 0) return false; container.Atoms[idx] = newAtom ?? throw new ArgumentNullException(nameof(newAtom), "Replacement atom was null!"); - var sgrougs = container.GetProperty>(CDKPropertyName.CtabSgroups); + var sgrougs = container.GetCtabSgroups(); if (sgrougs != null) { bool updated = false; - List replaced = new List(); + var replaced = new List(); foreach (Sgroup org in sgrougs) { if (org.Atoms.Contains(oldAtom)) @@ -151,8 +152,7 @@ public static bool ReplaceAtomByAtom(IAtomContainer container, IAtom oldAtom, IA } if (updated) { - container.SetProperty(CDKPropertyName.CtabSgroups, - new ReadOnlyCollection(replaced)); + container.SetCtabSgroups(replaced); } } @@ -191,7 +191,7 @@ public static double GetTotalExactMass(IAtomContainer atomContainer) { try { - Isotopes isotopes = Isotopes.Instance; + var isotopes = BODRIsotopeFactory.Instance; double mass = 0.0; double hExactMass = isotopes.GetMajorIsotope(1).ExactMass.Value; foreach (var atom in atomContainer.Atoms) @@ -218,7 +218,7 @@ public static double GetMolecularWeight(IAtomContainer mol) { try { - Isotopes isotopes = Isotopes.Instance; + BODRIsotopeFactory isotopes = BODRIsotopeFactory.Instance; double hmass = isotopes.GetNaturalMass(ChemicalElements.Hydrogen.ToIElement()); double mw = 0.0; foreach (IAtom atom in mol.Atoms) @@ -260,7 +260,7 @@ public static double GetNaturalExactMass(IAtomContainer atomContainer) { try { - Isotopes isotopes = Isotopes.Instance; + BODRIsotopeFactory isotopes = BODRIsotopeFactory.Instance; double hydgrogenMass = isotopes.GetNaturalMass(ChemicalElements.Hydrogen.ToIElement()); double mass = 0.0; @@ -293,7 +293,7 @@ public static double GetTotalNaturalAbundance(IAtomContainer atomContainer) { try { - Isotopes isotopes = Isotopes.Instance; + BODRIsotopeFactory isotopes = BODRIsotopeFactory.Instance; double abundance = 1.0; double hAbundance = isotopes.GetMajorIsotope(1).NaturalAbundance.Value; @@ -374,11 +374,12 @@ public static int GetTotalPositiveFormalCharge(IAtomContainer atomContainer) /// if the provided container was null public static int GetTotalHydrogenCount(IAtomContainer container) { - if (container == null) throw new ArgumentNullException("null container provided"); + if (container == null) + throw new ArgumentNullException(nameof(container), "null container provided"); int hydrogens = 0; foreach (var atom in container.Atoms) { - if (ChemicalElements.Hydrogen.Symbol.Equals(atom.Symbol)) + if (ChemicalElements.Hydrogen.Symbol.Equals(atom.Symbol, StringComparison.Ordinal)) { hydrogens++; } @@ -432,7 +433,7 @@ public static int CountExplicitHydrogens(IAtomContainer atomContainer, IAtom ato int hCount = 0; foreach (var connected in atomContainer.GetConnectedAtoms(atom)) { - if (ChemicalElements.Hydrogen.Symbol.Equals(connected.Symbol)) + if (ChemicalElements.Hydrogen.Symbol.Equals(connected.Symbol, StringComparison.Ordinal)) { hCount++; } @@ -465,7 +466,7 @@ public static void ConvertImplicitToExplicitHydrogens(IAtomContainer atomContain foreach (var atom in atomContainer.Atoms) { - if (!atom.Symbol.Equals("H")) + if (!string.Equals(atom.Symbol, "H", StringComparison.Ordinal)) { int? hCount = atom.ImplicitHydrogenCount; if (hCount != null) @@ -489,15 +490,15 @@ public static void ConvertImplicitToExplicitHydrogens(IAtomContainer atomContain atomContainer.Bonds.Add(bond); // update stereo elements with an implicit part - var stereos = new List>(); + var stereos = new List>(); foreach (var stereo in atomContainer.StereoElements) { switch (stereo) { case ITetrahedralChirality tc: { - IAtom focus = tc.Focus; - IAtom[] carriers = tc.Carriers.ToArray(); + var focus = tc.Focus; + var carriers = tc.Carriers.ToArray(); // in sulfoxide - the implicit part of the tetrahedral centre // is a lone pair @@ -515,8 +516,8 @@ public static void ConvertImplicitToExplicitHydrogens(IAtomContainer atomContain break; case ExtendedTetrahedral tc: { - IAtom focus = tc.Focus; - IAtom[] carriers = tc.Carriers.ToArray(); + var focus = tc.Focus; + var carriers = tc.Carriers.ToArray(); // in sulfoxide - the implicit part of the tetrahedral centre // is a lone pair @@ -550,7 +551,7 @@ public static int CountHydrogens(IAtomContainer atomContainer, IAtom atom) public static IList GetAllIDs(IAtomContainer mol) { - IList idList = new List(); + var idList = new List(); if (mol != null) { if (mol.Id != null) idList.Add(mol.Id); @@ -577,10 +578,10 @@ public static IList GetAllIDs(IAtomContainer mol) public static IAtomContainer RemoveNonChiralHydrogens(IAtomContainer org) { var map = new CDKObjectMap(); // maps original atoms to clones. - IList orgAtomsToRemove = new List(); // lists removed Hs. + var orgAtomsToRemove = new List(); // lists removed Hs. // Clone atoms except those to be removed. - IAtomContainer cpy = (IAtomContainer)org.Clone(map); + var cpy = (IAtomContainer)org.Clone(map); int count = org.Atoms.Count; foreach (var atom in org.Atoms) @@ -592,7 +593,7 @@ public static IAtomContainer RemoveNonChiralHydrogens(IAtomContainer org) // test whether connected to a single hetero atom only, otherwise keep if (org.GetConnectedAtoms(atom).Count() == 1) { - IAtom neighbour = org.GetConnectedAtoms(atom).ElementAt(0); + var neighbour = org.GetConnectedAtoms(atom).ElementAt(0); // keep if the neighbouring hetero atom has stereo information, otherwise continue checking var stereoParity = neighbour.StereoParity; if (stereoParity == StereoAtomParities.Undefined) @@ -602,10 +603,11 @@ public static IAtomContainer RemoveNonChiralHydrogens(IAtomContainer org) foreach (var bond in org.GetConnectedBonds(neighbour)) { BondStereo bondStereo = bond.Stereo; - if (bondStereo != BondStereo.None) addToRemove = false; - IAtom neighboursNeighbour = bond.GetOther(neighbour); + if (bondStereo != BondStereo.None) + addToRemove = false; + var neighboursNeighbour = bond.GetOther(neighbour); // remove in any case if the hetero atom is connected to more than one hydrogen - if (neighboursNeighbour.Symbol.Equals("H") && neighboursNeighbour != atom) + if (neighboursNeighbour.Symbol.Equals("H", StringComparison.Ordinal) && neighboursNeighbour != atom) { addToRemove = true; break; @@ -620,7 +622,7 @@ public static IAtomContainer RemoveNonChiralHydrogens(IAtomContainer org) } // rescue any false positives, i.e., hydrogens that are stereo-relevant - // the use of IReadOnlyStereoElement is not fully integrated yet to describe stereo information + // the use of IStereoElement is not fully integrated yet to describe stereo information foreach (var stereoElement in org.StereoElements) { switch (stereoElement) @@ -629,7 +631,7 @@ public static IAtomContainer RemoveNonChiralHydrogens(IAtomContainer org) { foreach (var atom in tetChirality.Ligands) { - if (atom.Symbol.Equals("H") && orgAtomsToRemove.Contains(atom)) + if (atom.Symbol.Equals("H", StringComparison.Ordinal) && orgAtomsToRemove.Contains(atom)) { orgAtomsToRemove.Remove(atom); } @@ -668,7 +670,8 @@ public static IAtomContainer RemoveNonChiralHydrogens(IAtomContainer org) } foreach (var atom in cpy.Atoms) { - if (atom.ImplicitHydrogenCount == null) atom.ImplicitHydrogenCount = 0; + if (atom.ImplicitHydrogenCount == null) + atom.ImplicitHydrogenCount = 0; } return cpy; @@ -702,7 +705,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) bool anyHydrogenPresent = false; foreach (var atom in org.Atoms) { - if ("H".Equals(atom.Symbol)) + if (string.Equals("H", atom.Symbol, StringComparison.Ordinal)) { anyHydrogenPresent = true; break; @@ -714,7 +717,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) // crossing atoms, positional variation atoms etc ISet xatoms = new NCDK.Common.Collections.EmptySet(); - ICollection sgroups = org.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = org.GetCtabSgroups(); if (sgroups != null) { xatoms = new HashSet(); @@ -730,8 +733,8 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) // we need fast adjacency checks (to check for suppression and // update hydrogen counts) - GraphUtil.EdgeToBondMap bondmap = GraphUtil.EdgeToBondMap.WithSpaceFor(org); - int[][] graph = GraphUtil.ToAdjList(org, bondmap); + var bondmap = EdgeToBondMap.WithSpaceFor(org); + var graph = GraphUtil.ToAdjList(org, bondmap); int nOrgAtoms = org.Atoms.Count; int nOrgBonds = org.Bonds.Count; @@ -739,15 +742,15 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) int nCpyAtoms = 0; int nCpyBonds = 0; - ISet hydrogens = new HashSet(); - ISet bondsToHydrogens = new HashSet(); - IAtom[] cpyAtoms = new IAtom[nOrgAtoms]; + var hydrogens = new HashSet(); + var bondsToHydrogens = new HashSet(); + var cpyAtoms = new IAtom[nOrgAtoms]; // filter the original container atoms for those that can/can't // be suppressed for (int v = 0; v < nOrgAtoms; v++) { - IAtom atom = org.Atoms[v]; + var atom = org.Atoms[v]; if (SuppressibleHydrogen(org, graph, bondmap, v) && !xatoms.Contains(atom)) { @@ -768,8 +771,8 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) // we now update the bonds - we have auxiliary variable remaining that // bypasses the set membership checks if all suppressed bonds are found - IBond[] cpyBonds = new IBond[nOrgBonds - hydrogens.Count()]; - int remaining = hydrogens.Count(); + var cpyBonds = new IBond[nOrgBonds - hydrogens.Count()]; + var remaining = hydrogens.Count(); foreach (var bond in org.Bonds) { @@ -788,7 +791,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) org.SetBonds(cpyBonds); - var elements = new List>(); + var elements = new List>(); foreach (var se in org.StereoElements) { @@ -796,8 +799,8 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) { case ITetrahedralChirality tc: { - IAtom focus = tc.ChiralAtom; - var neighbors = tc.Ligands; + var focus = tc.ChiralAtom; + var neighbors = tc.Ligands.ToList(); bool updated = false; for (int i = 0; i < neighbors.Count; i++) { @@ -807,6 +810,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) updated = true; } } + tc.Ligands = neighbors; // no changes if (!updated) @@ -821,11 +825,11 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) break; case IDoubleBondStereochemistry db: { - DoubleBondConformation conformation = db.Stereo; + var conformation = db.Stereo; - IBond orgStereo = db.StereoBond; - IBond orgLeft = db.Bonds[0]; - IBond orgRight = db.Bonds[1]; + var orgStereo = db.StereoBond; + var orgLeft = db.Bonds[0]; + var orgRight = db.Bonds[1]; // we use the following variable names to refer to the // double bond atoms and substituents @@ -833,15 +837,15 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) // \ / // u = v - IAtom u = orgStereo.Begin; - IAtom v = orgStereo.End; - IAtom x = orgLeft.GetOther(u); - IAtom y = orgRight.GetOther(v); + var u = orgStereo.Begin; + var v = orgStereo.End; + var x = orgLeft.GetOther(u); + var y = orgRight.GetOther(v); // if xNew == x and yNew == y we don't need to find the // connecting bonds - IAtom xNew = x; - IAtom yNew = y; + var xNew = x; + var yNew = y; if (hydrogens.Contains(x)) { @@ -857,8 +861,8 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) // no other atoms connected, invalid double-bond configuration // is removed. example [2H]/C=C/[H] - if (x == null || y == null || - xNew == null || yNew == null) continue; + if (x == null || y == null || xNew == null || yNew == null) + continue; // no changes if (x.Equals(xNew) && y.Equals(yNew)) @@ -868,12 +872,10 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) } // XXX: may perform slow operations but works for now - IBond cpyLeft = !object.Equals(xNew, x) ? org.GetBond(u, xNew) : orgLeft; - IBond cpyRight = !object.Equals(yNew, y) ? org.GetBond(v, yNew) : orgRight; + var cpyLeft = !object.Equals(xNew, x) ? org.GetBond(u, xNew) : orgLeft; + var cpyRight = !object.Equals(yNew, y) ? org.GetBond(v, yNew) : orgRight; - elements.Add(new DoubleBondStereochemistry(orgStereo, - new IBond[] { cpyLeft, cpyRight }, - conformation)); + elements.Add(new DoubleBondStereochemistry(orgStereo, new IBond[] { cpyLeft, cpyRight }, conformation)); } break; case Atropisomeric a: @@ -891,7 +893,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) if (org.SingleElectrons.Count > 0) { - ICollection remove = new HashSet(); + var remove = new HashSet(); foreach (var se in org.SingleElectrons) { if (hydrogens.Contains(se.Atom)) remove.Add(se); @@ -904,7 +906,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) if (org.LonePairs.Count > 0) { - ICollection remove = new HashSet(); + var remove = new HashSet(); foreach (var lp in org.LonePairs) { if (hydrogens.Contains(lp.Atom)) remove.Add(lp); @@ -921,7 +923,7 @@ public static IAtomContainer SuppressHydrogens(IAtomContainer org) { if (sgroup.GetValue(SgroupKey.CtabParentAtomList) != null) { - ICollection pal = (ICollection)sgroup.GetValue(SgroupKey.CtabParentAtomList); + var pal = (ICollection)sgroup.GetValue(SgroupKey.CtabParentAtomList); foreach (var hydrogen in hydrogens) pal.Remove(hydrogen); } @@ -961,17 +963,21 @@ public static IAtomContainer RemoveHydrogens(IAtomContainer org) private static bool SuppressibleHydrogen(IAtomContainer container, IAtom atom) { // is the atom a hydrogen - if (!"H".Equals(atom.Symbol)) return false; + if (!"H".Equals(atom.Symbol, StringComparison.Ordinal)) + return false; // is the hydrogen an ion? - if (atom.FormalCharge != null && atom.FormalCharge != 0) return false; + if (atom.FormalCharge != null && atom.FormalCharge != 0) + return false; // is the hydrogen deuterium / tritium? - if (atom.MassNumber != null) return false; + if (atom.MassNumber != null) + return false; // molecule hydrogen with implicit H? - if (atom.ImplicitHydrogenCount != null && atom.ImplicitHydrogenCount != 0) return false; + if (atom.ImplicitHydrogenCount != null && atom.ImplicitHydrogenCount != 0) + return false; // molecule hydrogen var neighbors = container.GetConnectedAtoms(atom).ToList(); - if (neighbors.Count == 1 && (neighbors[0].Symbol.Equals("H") || - neighbors[0] is IPseudoAtom)) return false; + if (neighbors.Count == 1 && (neighbors[0].Symbol.Equals("H", StringComparison.Ordinal) || neighbors[0] is IPseudoAtom)) + return false; // what about bridging hydrogens? // hydrogens with atom-atom mapping? return true; @@ -1007,28 +1013,34 @@ private static void IncrementImplHydrogenCount(IAtom atom) /// adjacent list representation /// vertex (atom index) /// the atom is a hydrogen and it can be suppressed (implicit) - private static bool SuppressibleHydrogen(IAtomContainer container, int[][] graph, GraphUtil.EdgeToBondMap bondmap, int v) + private static bool SuppressibleHydrogen(IAtomContainer container, int[][] graph, EdgeToBondMap bondmap, int v) { - IAtom atom = container.Atoms[v]; + var atom = container.Atoms[v]; // is the atom a hydrogen - if (!"H".Equals(atom.Symbol)) return false; + if (!"H".Equals(atom.Symbol, StringComparison.Ordinal)) + return false; // is the hydrogen an ion? - if (atom.FormalCharge != null && atom.FormalCharge != 0) return false; + if (atom.FormalCharge != null && atom.FormalCharge != 0) + return false; // is the hydrogen deuterium / tritium? - if (atom.MassNumber != null) return false; + if (atom.MassNumber != null) + return false; // hydrogen is either not attached to 0 or 2 neighbors - if (graph[v].Length != 1) return false; + if (graph[v].Length != 1) + return false; // non-single bond - if (bondmap[v, graph[v][0]].Order != BondOrder.Single) return false; + if (bondmap[v, graph[v][0]].Order != BondOrder.Single) + return false; // okay the hydrogen has one neighbor, if that neighbor is a // hydrogen (i.e. molecular hydrogen) then we can not suppress it - if ("H".Equals(container.Atoms[graph[v][0]].Symbol)) + if (string.Equals("H", container.Atoms[graph[v][0]].Symbol, StringComparison.Ordinal)) return false; // can not nicely suppress hydrogens on pseudo atoms if (container.Atoms[graph[v][0]] is IPseudoAtom) return false; + return true; } @@ -1045,7 +1057,8 @@ private static IAtom FindOther(IAtomContainer container, IAtom atom, IAtom exclu { foreach (var neighbor in container.GetConnectedAtoms(atom)) { - if (!neighbor.Equals(exclude1) && !neighbor.Equals(exclude2)) return neighbor; + if (!neighbor.Equals(exclude1) && !neighbor.Equals(exclude2)) + return neighbor; } return null; } @@ -1069,21 +1082,21 @@ public static IAtomContainer RemoveHydrogensPreserveMultiplyBonded(IAtomContaine /// a list of H atoms to preserve. /// The mol without Hs. // @cdk.keyword hydrogens, removal - [Obsolete("not used by the internal API " + nameof(SuppressHydrogens) + "will now only suppress hydrogens that can be represent as a h count")] + [Obsolete("not used by the internal API " + nameof(SuppressHydrogens) + " will now only suppress hydrogens that can be represent as a h count")] private static IAtomContainer RemoveHydrogens(IAtomContainer ac, List preserve) { - IDictionary map = new Dictionary(); + var map = new Dictionary(); // maps original atoms to clones. - IList remove = new List(); + var remove = new List(); // lists removed Hs. // Clone atoms except those to be removed. - IAtomContainer mol = ac.Builder.NewAtomContainer(); + var mol = ac.Builder.NewAtomContainer(); int count = ac.Atoms.Count; for (int i = 0; i < count; i++) { // Clone/remove this atom? - IAtom atom = ac.Atoms[i]; + var atom = ac.Atoms[i]; if (!SuppressibleHydrogen(ac, atom) || preserve.Contains(atom)) { IAtom a = null; @@ -1104,9 +1117,9 @@ private static IAtomContainer RemoveHydrogens(IAtomContainer ac, List pre for (int i = 0; i < count; i++) { // Check bond. - IBond bond = ac.Bonds[i]; - IAtom atom0 = bond.Begin; - IAtom atom1 = bond.End; + var bond = ac.Bonds[i]; + var atom0 = bond.Begin; + var atom1 = bond.End; bool remove_bond = false; foreach (var atom in bond.Atoms) { @@ -1120,9 +1133,7 @@ private static IAtomContainer RemoveHydrogens(IAtomContainer ac, List pre // Clone/remove this bond? if (!remove_bond) { - // if (!remove.Contains(atoms[0]) && !remove.Contains(atoms[1])) - - IBond clone = (IBond)ac.Bonds[i].Clone(); + var clone = (IBond)ac.Bonds[i].Clone(); clone.SetAtoms(new[] { map[atom0], map[atom1] }); mol.Bonds.Add(clone); } @@ -1134,7 +1145,7 @@ private static IAtomContainer RemoveHydrogens(IAtomContainer ac, List pre // Process neighbours. foreach (var neighbor in ac.GetConnectedAtoms(Remove)) { - IAtom neighb = map[neighbor]; + var neighb = map[neighbor]; neighb.ImplicitHydrogenCount = neighb.ImplicitHydrogenCount + 1; } } @@ -1157,13 +1168,13 @@ public static void SetAtomProperties(IAtomContainer container, string propKey, o } /// - /// A method to remove ElectronContainerListeners. - /// ElectronContainerListeners are used to detect changes - /// in ElectronContainers (like bonds) and to notifiy - /// registered Listeners in the event of a change. - /// If an object looses interest in such changes, it should - /// unregister with this AtomContainer in order to improve - /// performance of this class. + /// A method to remove ElectronContainerListeners. + /// ElectronContainerListeners are used to detect changes + /// in ElectronContainers (like bonds) and to notify + /// registered Listeners in the event of a change. + /// If an object looses interest in such changes, it should + /// unregister with this AtomContainer in order to improve + /// performance of this class. /// public static void UnregIsterElectronContainerListeners(IAtomContainer container) { @@ -1173,13 +1184,13 @@ public static void UnregIsterElectronContainerListeners(IAtomContainer container } } /// - /// A method to remove AtomListeners. - /// AtomListeners are used to detect changes - /// in Atom objects within this AtomContainer and to notifiy - /// registered Listeners in the event of a change. - /// If an object looses interest in such changes, it should - /// unregister with this AtomContainer in order to improve - /// performance of this class. + /// A method to remove AtomListeners. + /// AtomListeners are used to detect changes + /// in Atom objects within this AtomContainer and to notify + /// registered Listeners in the event of a change. + /// If an object looses interest in such changes, it should + /// unregister with this AtomContainer in order to improve + /// performance of this class. /// public static void UnregIsterAtomListeners(IAtomContainer container) { @@ -1199,7 +1210,7 @@ public static void UnregIsterAtomListeners(IAtomContainer container) /// An AtomContainer containing the intersection between and public static IAtomContainer GetIntersection(IAtomContainer container1, IAtomContainer container2) { - IAtomContainer intersection = container1.Builder.NewAtomContainer(); + var intersection = container1.Builder.NewAtomContainer(); foreach (var atom1 in container1.Atoms) if (container2.Contains(atom1)) @@ -1211,66 +1222,6 @@ public static IAtomContainer GetIntersection(IAtomContainer container1, IAtomCon return intersection; } - /// - /// Constructs an array of Atom objects from an AtomContainer. - /// - /// The original AtomContainer. - /// The array of Atom objects. - public static IAtom[] GetAtomArray(IAtomContainer container) - { - return container.Atoms.ToArray(); - } - - /// - /// Constructs an array of Atom objects from a List of Atom objects. - /// - /// The original List. - /// The array of Atom objects. - public static IAtom[] GetAtomArray(IEnumerable list) - { - return list.ToArray(); - } - - /// - /// Constructs an array of Bond objects from an AtomContainer. - /// - /// The original AtomContainer. - /// The array of Bond objects. - public static IBond[] GetBondArray(IAtomContainer container) - { - return container.Bonds.ToArray(); - } - - /// - /// Constructs an array of Atom objects from a List of Atom objects. - /// - /// The original List. - /// The array of Atom objects. - public static IBond[] GetBondArray(IEnumerable list) - { - return list.ToArray(); - } - - /// - /// Constructs an array of Bond objects from an AtomContainer. - /// - /// The original AtomContainer. - /// The array of Bond objects. - public static IElectronContainer[] GetElectronContainerArray(IAtomContainer container) - { - return container.GetElectronContainers().ToArray(); - } - - /// - /// Constructs an array of Atom objects from a List of Atom objects. - /// - /// The original List. - /// The array of Atom objects. - public static IElectronContainer[] GetElectronContainerArray(IEnumerable list) - { - return list.ToArray(); - } - /// /// Convenience method to perceive atom types for all s in the /// , using the .If the @@ -1282,10 +1233,10 @@ public static IElectronContainer[] GetElectronContainerArray(IEnumerable public static void PercieveAtomTypesAndConfigureAtoms(IAtomContainer container) { - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); + var matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); foreach (var atom in container.Atoms) { - IAtomType matched = matcher.FindMatchingAtomType(container, atom); + var matched = matcher.FindMatchingAtomType(container, atom); if (matched != null) AtomTypeManipulator.Configure(atom, matched); } @@ -1301,10 +1252,10 @@ public static void PercieveAtomTypesAndConfigureAtoms(IAtomContainer container) /// public static void PercieveAtomTypesAndConfigureUnsetProperties(IAtomContainer container) { - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); + var matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); foreach (var atom in container.Atoms) { - IAtomType matched = matcher.FindMatchingAtomType(container, atom); + var matched = matcher.FindMatchingAtomType(container, atom); if (matched != null) AtomTypeManipulator.ConfigureUnsetProperties(atom, matched); } } @@ -1353,7 +1304,7 @@ public static int GetSingleBondEquivalentSum(IAtomContainer container) int sum = 0; foreach (var bond in container.Bonds) { - BondOrder order = bond.Order; + var order = bond.Order; if (!order.IsUnset()) { sum += order.Numeric(); @@ -1374,10 +1325,10 @@ public static BondOrder GetMaximumBondOrder(IAtomContainer container) // @cdk.keyword hydrogens, removal public static IList GetHeavyAtoms(IAtomContainer container) { - List newAc = new List(); + var newAc = new List(); for (int f = 0; f < container.Atoms.Count; f++) { - if (!container.Atoms[f].Symbol.Equals("H")) + if (!string.Equals(container.Atoms[f].Symbol, "H", StringComparison.Ordinal)) { newAc.Add(container.Atoms[f]); } @@ -1394,7 +1345,7 @@ public static IList GetHeavyAtoms(IAtomContainer container) [Obsolete("not all attributes are removed producing unexpected results, use " + nameof(Anonymise))] public static IAtomContainer CreateAllCarbonAllSingleNonAromaticBondAtomContainer(IAtomContainer atomContainer) { - IAtomContainer query = (IAtomContainer)atomContainer.Clone(); + var query = (IAtomContainer)atomContainer.Clone(); for (int i = 0; i < query.Bonds.Count; i++) { query.Bonds[i].Order = BondOrder.Single; @@ -1419,10 +1370,10 @@ public static IAtomContainer CreateAllCarbonAllSingleNonAromaticBondAtomContaine /// anonymised container public static IAtomContainer Anonymise(IAtomContainer src) { - IChemObjectBuilder builder = src.Builder; + var builder = src.Builder; - IAtom[] atoms = new IAtom[src.Atoms.Count]; - IBond[] bonds = new IBond[src.Bonds.Count]; + var atoms = new IAtom[src.Atoms.Count]; + var bonds = new IBond[src.Bonds.Count]; for (int i = 0; i < atoms.Length; i++) { @@ -1430,13 +1381,13 @@ public static IAtomContainer Anonymise(IAtomContainer src) } for (int i = 0; i < bonds.Length; i++) { - IBond bond = src.Bonds[i]; + var bond = src.Bonds[i]; int u = src.Atoms.IndexOf(bond.Begin); int v = src.Atoms.IndexOf(bond.End); bonds[i] = builder.NewBond(atoms[u], atoms[v]); } - IAtomContainer dest = builder.NewAtomContainer(atoms, bonds); + var dest = builder.NewAtomContainer(atoms, bonds); return dest; } @@ -1451,10 +1402,10 @@ public static IAtomContainer Anonymise(IAtomContainer src) /// the skeleton copy public static IAtomContainer Skeleton(IAtomContainer src) { - IChemObjectBuilder builder = src.Builder; + var builder = src.Builder; - IAtom[] atoms = new IAtom[src.Atoms.Count]; - IBond[] bonds = new IBond[src.Bonds.Count]; + var atoms = new IAtom[src.Atoms.Count]; + var bonds = new IBond[src.Bonds.Count]; for (int i = 0; i < atoms.Length; i++) { @@ -1462,13 +1413,13 @@ public static IAtomContainer Skeleton(IAtomContainer src) } for (int i = 0; i < bonds.Length; i++) { - IBond bond = src.Bonds[i]; - int u = src.Atoms.IndexOf(bond.Begin); - int v = src.Atoms.IndexOf(bond.End); + var bond = src.Bonds[i]; + var u = src.Atoms.IndexOf(bond.Begin); + var v = src.Atoms.IndexOf(bond.End); bonds[i] = builder.NewBond(atoms[u], atoms[v]); } - IAtomContainer dest = builder.NewAtomContainer(atoms, bonds); + var dest = builder.NewAtomContainer(atoms, bonds); return dest; } @@ -1484,7 +1435,7 @@ public static double GetBondOrderSum(IAtomContainer container, IAtom atom) double count = 0; foreach (var bond in container.GetConnectedBonds(atom)) { - BondOrder order = bond.Order; + var order = bond.Order; if (!order.IsUnset()) { count += order.Numeric(); @@ -1510,7 +1461,7 @@ public static IAtomContainer SetSingleOrDoubleFlags(IAtomContainer ac) // note - we could check for any aromatic bonds to avoid RingSearch but // RingSearch is fast enough it probably wouldn't do much to check // before hand - RingSearch rs = new RingSearch(ac); + var rs = new RingSearch(ac); bool singleOrDouble = false; foreach (var bond in rs.RingFragments().Bonds) { diff --git a/NCDK/Tools/Manipulator/AtomContainerSetManipulator.cs b/NCDK/Tools/Manipulator/AtomContainerSetManipulator.cs index 681ac843..9fb467c6 100644 --- a/NCDK/Tools/Manipulator/AtomContainerSetManipulator.cs +++ b/NCDK/Tools/Manipulator/AtomContainerSetManipulator.cs @@ -22,6 +22,7 @@ */ using NCDK.Graphs; +using System; using System.Collections.Generic; using System.Linq; @@ -248,7 +249,8 @@ public static bool ContainsByID(IEnumerable atomContainerSet, st { foreach (var ac in atomContainerSet) { - if (ac.Id != null && ac.Id.Equals(id)) return true; + if (id != null && string.Equals(ac.Id, id, StringComparison.Ordinal)) + return true; } return false; } diff --git a/NCDK/Tools/Manipulator/AtomTypeManipulator.cs b/NCDK/Tools/Manipulator/AtomTypeManipulator.cs index 6c4a7da7..e1ed83e6 100644 --- a/NCDK/Tools/Manipulator/AtomTypeManipulator.cs +++ b/NCDK/Tools/Manipulator/AtomTypeManipulator.cs @@ -47,7 +47,7 @@ public static void Configure(IAtom atom, IAtomType atomType) { throw new ArgumentException("The IAtomType was null."); } - if ("X".Equals(atomType.AtomTypeName)) + if (string.Equals("X", atomType.AtomTypeName, StringComparison.Ordinal)) { atom.AtomTypeName = "X"; return; @@ -110,7 +110,7 @@ public static void ConfigureUnsetProperties(IAtom atom, IAtomType atomType) { throw new ArgumentException("The IAtomType was null."); } - if ("X".Equals(atomType.AtomTypeName)) + if (string.Equals("X", atomType.AtomTypeName, StringComparison.Ordinal)) { if (atom.AtomTypeName == null) atom.AtomTypeName = "X"; return; diff --git a/NCDK/Tools/Manipulator/BondManipulator.cs b/NCDK/Tools/Manipulator/BondManipulator.cs index d2c9b2b6..0d50b4b7 100644 --- a/NCDK/Tools/Manipulator/BondManipulator.cs +++ b/NCDK/Tools/Manipulator/BondManipulator.cs @@ -205,8 +205,8 @@ public static BondOrder GetMaximumBondOrder(IEnumerable bonds) /// The maximum bond order found public static BondOrder GetMaximumBondOrder(IBond firstBond, IBond secondBond) { - if (firstBond == null || secondBond == null) - throw new ArgumentNullException("null instance of IBond provided"); + if (firstBond == null) throw new ArgumentNullException(nameof(firstBond)); + if (secondBond == null) throw new ArgumentNullException(nameof(secondBond)); return GetMaximumBondOrder(firstBond.Order, secondBond.Order); } diff --git a/NCDK/Tools/Manipulator/ChemFileManipulator.cs b/NCDK/Tools/Manipulator/ChemFileManipulator.cs index 1168ffbe..cf868ce4 100644 --- a/NCDK/Tools/Manipulator/ChemFileManipulator.cs +++ b/NCDK/Tools/Manipulator/ChemFileManipulator.cs @@ -32,7 +32,7 @@ namespace NCDK.Tools.Manipulator /// // @cdk.module standard // @cdk.githash - public class ChemFileManipulator + public static class ChemFileManipulator { /// /// Get the total number of atoms inside an IChemFile. diff --git a/NCDK/Tools/Manipulator/ChemModelManipulator.cs b/NCDK/Tools/Manipulator/ChemModelManipulator.cs index 1aa2b8af..e0d1ce3a 100644 --- a/NCDK/Tools/Manipulator/ChemModelManipulator.cs +++ b/NCDK/Tools/Manipulator/ChemModelManipulator.cs @@ -282,7 +282,7 @@ public static IReaction GetRelevantReaction(IChemModel chemModel, IAtom atom) /// public static IEnumerable GetAllAtomContainers(IChemModel chemModel) { - IChemObjectSet moleculeSet = chemModel.Builder.NewAtomContainerSet(); + var moleculeSet = chemModel.Builder.NewAtomContainerSet(); if (chemModel.MoleculeSet != null) { moleculeSet.AddRange(chemModel.MoleculeSet); diff --git a/NCDK/Tools/Manipulator/ChemSequenceManipulator.cs b/NCDK/Tools/Manipulator/ChemSequenceManipulator.cs index 0744f008..4bf7f208 100644 --- a/NCDK/Tools/Manipulator/ChemSequenceManipulator.cs +++ b/NCDK/Tools/Manipulator/ChemSequenceManipulator.cs @@ -70,7 +70,7 @@ public static int GetBondCount(IChemSequence sequence) /// public static List GetAllAtomContainers(IChemSequence sequence) { - List acList = new List(); + var acList = new List(); foreach (var model in sequence) { acList.AddRange(ChemModelManipulator.GetAllAtomContainers(model)); diff --git a/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs b/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs index 6eec636b..ea9b11fe 100644 --- a/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs +++ b/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs @@ -25,6 +25,7 @@ using NCDK.Config; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -69,7 +70,8 @@ public static int GetElementCount(IMolecularFormula formula, IElement element) int count = 0; foreach (var isotope in formula.Isotopes) { - if (isotope.Symbol.Equals(element.Symbol)) count += formula.GetCount(isotope); + if (isotope.Symbol.Equals(element.Symbol, StringComparison.Ordinal)) + count += formula.GetCount(isotope); } return count; } @@ -109,7 +111,8 @@ public static IEnumerable GetIsotopes(IMolecularFormula formula, IElem { foreach (var isotope in formula.Isotopes) { - if (isotope.Symbol.Equals(element.Symbol)) yield return isotope; + if (isotope.Symbol.Equals(element.Symbol, StringComparison.Ordinal)) + yield return isotope; } yield break; } @@ -143,7 +146,8 @@ public static bool ContainsElement(IMolecularFormula formula, IElement element) { foreach (var isotope in formula.Isotopes) { - if (element.Symbol.Equals(isotope.Symbol)) return true; + if (element.Symbol.Equals(isotope.Symbol, StringComparison.Ordinal)) + return true; } return false; @@ -173,20 +177,21 @@ public static IMolecularFormula RemoveElement(IMolecularFormula formula, IElemen /// A string containing the molecular formula /// /// - /// - /// - public static string GetString(IMolecularFormula formula, string[] orderElements, bool setOne) + /// + /// + public static string GetString(IMolecularFormula formula, IReadOnlyList orderElements, bool setOne) { - StringBuilder stringMF = new StringBuilder(); - IList isotopesList = PutInOrder(orderElements, formula); + var stringMF = new StringBuilder(); + var isotopesList = PutInOrder(orderElements, formula); // collect elements in a map - since different isotopes of the // same element will get repeated in the formula - List elemSet = new List(); + var elemSet = new List(); foreach (var isotope in isotopesList) { - string symbol = isotope.Symbol; - if (!elemSet.Contains(symbol)) elemSet.Add(symbol); + var symbol = isotope.Symbol; + if (!elemSet.Contains(symbol)) + elemSet.Add(symbol); } foreach (var elem in elemSet) @@ -194,10 +199,12 @@ public static string GetString(IMolecularFormula formula, string[] orderElements int count = 0; foreach (var isotope in formula.Isotopes) { - if (isotope.Symbol.Equals(elem)) count += formula.GetCount(isotope); + if (isotope.Symbol.Equals(elem, StringComparison.Ordinal)) + count += formula.GetCount(isotope); } stringMF.Append(elem); - if (!(count == 1 && !setOne)) stringMF.Append(count); + if (!(count == 1 && !setOne)) + stringMF.Append(count); } return stringMF.ToString(); } @@ -234,19 +241,18 @@ public static string GetString(IMolecularFormula formula) /// public static string GetString(IMolecularFormula formula, bool setOne) { - if (ContainsElement(formula, formula.Builder.NewElement("C"))) - return GetString(formula, GenerateOrderEle_Hill_WithCarbons(), setOne); + return GetString(formula, OrderEleHillWithCarbons, setOne); else - return GetString(formula, GenerateOrderEle_Hill_NoCarbons(), setOne); + return GetString(formula, OrderEleHillNoCarbons, setOne); } - public static IList PutInOrder(string[] orderElements, IMolecularFormula formula) + public static IReadOnlyList PutInOrder(IReadOnlyList orderElements, IMolecularFormula formula) { - List isotopesList = new List(); + var isotopesList = new List(); foreach (var orderElement in orderElements) { - IElement element = formula.Builder.NewElement(orderElement); + var element = formula.Builder.NewElement(orderElement); if (ContainsElement(formula, element)) { var isotopes = GetIsotopes(formula, element); @@ -262,9 +268,9 @@ public static IList PutInOrder(string[] orderElements, IMolecularFormu [Obsolete("Use" + nameof(GetString))] public static string GetHillString(IMolecularFormula formula) { - StringBuilder hillString = new StringBuilder(); + var hillString = new StringBuilder(); - IDictionary hillMap = new SortedDictionary(); + var hillMap = new SortedDictionary(); foreach (var isotope in formula.Isotopes) { string symbol = isotope.Symbol; @@ -297,7 +303,8 @@ public static string GetHillString(IMolecularFormula formula) { hillString.Append(key); count = hillMap[key]; - if (count > 1) hillString.Append(count); + if (count > 1) + hillString.Append(count); } return hillString.ToString(); } @@ -329,11 +336,10 @@ public static string GetHTML(IMolecularFormula formula) /// public static string GetHTML(IMolecularFormula formula, bool chargeB, bool isotopeB) { - string[] orderElements; - if (ContainsElement(formula, formula.Builder.NewElement("C"))) - orderElements = GenerateOrderEle_Hill_WithCarbons(); - else - orderElements = GenerateOrderEle_Hill_NoCarbons(); + var orderElements = + ContainsElement(formula, formula.Builder.NewElement("C")) + ? OrderEleHillWithCarbons + : OrderEleHillNoCarbons; return GetHTML(formula, orderElements, chargeB, isotopeB); } @@ -350,18 +356,18 @@ public static string GetHTML(IMolecularFormula formula, bool chargeB, bool isoto /// True, If it has to show the Isotope mass /// A HTML representation of the molecular formula /// - public static string GetHTML(IMolecularFormula formula, string[] orderElements, bool showCharge, bool showIsotopes) + public static string GetHTML(IMolecularFormula formula, IReadOnlyList orderElements, bool showCharge, bool showIsotopes) { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); foreach (var orderElement in orderElements) { - IElement element = formula.Builder.NewElement(orderElement); + var element = formula.Builder.NewElement(orderElement); if (ContainsElement(formula, element)) { if (!showIsotopes) { sb.Append(element.Symbol); - int n = GetElementCount(formula, element); + var n = GetElementCount(formula, element); if (n > 1) { sb.Append("").Append(n).Append(""); @@ -371,11 +377,11 @@ public static string GetHTML(IMolecularFormula formula, string[] orderElements, { foreach (var isotope in GetIsotopes(formula, element)) { - int? massNumber = isotope.MassNumber; + var massNumber = isotope.MassNumber; if (massNumber != null) sb.Append("").Append(massNumber).Append(""); sb.Append(isotope.Symbol); - int n = formula.GetCount(isotope); + var n = formula.GetCount(isotope); if (n > 1) { sb.Append("").Append(n).Append(""); @@ -387,7 +393,7 @@ public static string GetHTML(IMolecularFormula formula, string[] orderElements, if (showCharge) { - int? charge = formula.Charge; + var charge = formula.Charge; if (charge == null || charge == 0) { return sb.ToString(); @@ -437,8 +443,7 @@ public static IMolecularFormula GetMajorIsotopeMolecularFormula(string stringMF, return GetMolecularFormula(stringMF, true, builder); } - private static IMolecularFormula GetMolecularFormula(string stringMF, bool assumeMajorIsotope, - IChemObjectBuilder builder) + private static IMolecularFormula GetMolecularFormula(string stringMF, bool assumeMajorIsotope, IChemObjectBuilder builder) { IMolecularFormula formula = builder.NewMolecularFormula(); @@ -493,8 +498,8 @@ private static IMolecularFormula GetMolecularFormula(string stringMF, IMolecular char ThisChar; // Buffer for - string RecentElementSymbol = ""; - string RecentElementCountString = "0"; + var RecentElementSymbol = ""; + var RecentElementCountString = "0"; // string to be converted to an integer int RecentElementCount; @@ -514,7 +519,7 @@ private static IMolecularFormula GetMolecularFormula(string stringMF, IMolecular // // New Element begins // - RecentElementSymbol = ThisChar.ToString(); + RecentElementSymbol = new string(new[] { ThisChar }); RecentElementCountString = "0"; } if (ThisChar >= 'a' && ThisChar <= 'z') @@ -531,18 +536,18 @@ private static IMolecularFormula GetMolecularFormula(string stringMF, IMolecular if (f == stringMF.Length - 1 || (stringMF[f + 1] >= 'A' && stringMF[f + 1] <= 'Z')) { // Here an element symbol as well as its number should have been read completely - RecentElementCount = int.Parse(RecentElementCountString); + RecentElementCount = int.Parse(RecentElementCountString, NumberFormatInfo.InvariantInfo); if (RecentElementCount == 0) { RecentElementCount = 1; } - IIsotope isotope = formula.Builder.NewIsotope(RecentElementSymbol); + var isotope = formula.Builder.NewIsotope(RecentElementSymbol); if (assumeMajorIsotope) { try { - isotope = Isotopes.Instance.GetMajorIsotope(RecentElementSymbol); + isotope = BODRIsotopeFactory.Instance.GetMajorIsotope(RecentElementSymbol); } catch (IOException) { @@ -553,7 +558,8 @@ private static IMolecularFormula GetMolecularFormula(string stringMF, IMolecular } } - if (charge != null) formula.Charge = charge; + if (charge != null) + formula.Charge = charge; return formula; } @@ -564,7 +570,8 @@ private static IMolecularFormula GetMolecularFormula(string stringMF, IMolecular /// The corrected formula private static string CleanMFfromCharge(string formula) { - if (!(formula.Contains("[") && formula.Contains("]"))) return formula; + if (!(formula.Contains("[") && formula.Contains("]"))) + return formula; bool startBreak = false; string finalFormula = ""; for (int f = 0; f < formula.Length; f++) @@ -579,7 +586,8 @@ private static string CleanMFfromCharge(string formula) { break; } - else if (startBreak) finalFormula += thisChar; + else if (startBreak) + finalFormula += thisChar; } return finalFormula; } @@ -591,7 +599,6 @@ private static string CleanMFfromCharge(string formula) /// The charge private static int ExtractCharge(string formula) { - if (!(formula.Contains("[") && formula.Contains("]") && (formula.Contains("+") || formula.Contains(HYPHEN_STR) || formula.Contains(MINUS_STR)))) return 0; @@ -600,27 +607,36 @@ private static int ExtractCharge(string formula) for (int f = 0; f < formula.Length; f++) { char thisChar = formula[f]; - if (thisChar == ']') - { - // finish - finishBreak = true; - } - else if (thisChar == HYPHEN || thisChar == MINUS) + switch (thisChar) { - multiple = HYPHEN + multiple; - break; + case ']': + // finish + finishBreak = true; + break; + case HYPHEN: + case MINUS: + multiple = HYPHEN + multiple; + goto Exit_For; + case '+': + goto Exit_For; + default: + if (finishBreak) + { + multiple += thisChar; + } + break; } - else if (thisChar == '+') - { + } + Exit_For: + switch (multiple) + { + case "": + case HYPHEN_STR: + case MINUS_STR: + multiple += 1; break; - } - else if (finishBreak) - { - multiple += thisChar; - } } - if (multiple.Count() == 0 || multiple.Equals(HYPHEN_STR) || multiple.Equals(MINUS_STR)) multiple += 1; - return int.Parse(multiple); + return int.Parse(multiple, NumberFormatInfo.InvariantInfo); } /// @@ -639,7 +655,7 @@ public static double GetTotalExactMass(IMolecularFormula formula) { try { - IIsotope majorIsotope = Isotopes.Instance.GetMajorIsotope(isotope.Symbol); + var majorIsotope = BODRIsotopeFactory.Instance.GetMajorIsotope(isotope.Symbol); if (majorIsotope != null) { mass += majorIsotope.ExactMass.Value * formula.GetCount(isotope); @@ -653,7 +669,8 @@ public static double GetTotalExactMass(IMolecularFormula formula) else mass += isotope.ExactMass.Value * formula.GetCount(isotope); } - if (formula.Charge != null) mass = CorrectMass(mass, formula.Charge.Value); + if (formula.Charge != null) + mass = CorrectMass(mass, formula.Charge.Value); return mass; } @@ -666,10 +683,11 @@ public static double GetTotalExactMass(IMolecularFormula formula) /// The mass with the correction private static double CorrectMass(double mass, int charge) { - double massE = 0.00054857990927; + const double massE = 0.00054857990927; if (charge > 0) mass -= massE * charge; - else if (charge < 0) mass += massE * Math.Abs(charge); + else if (charge < 0) + mass += massE * Math.Abs(charge); return mass; } @@ -686,7 +704,7 @@ public static double GetTotalMassNumber(IMolecularFormula formula) { try { - IIsotope isotope2 = Isotopes.Instance.GetMajorIsotope(isotope.Symbol); + var isotope2 = BODRIsotopeFactory.Instance.GetMajorIsotope(isotope.Symbol); if (isotope2 != null) { mass += isotope2.MassNumber.Value * formula.GetCount(isotope); @@ -708,18 +726,10 @@ public static double GetTotalMassNumber(IMolecularFormula formula) public static double GetNaturalExactMass(IMolecularFormula formula) { double mass = 0.0; - IsotopeFactory factory; - try - { - factory = Isotopes.Instance; - } - catch (IOException) - { - throw new ApplicationException("Could not instantiate the IsotopeFactory."); - } + var factory = BODRIsotopeFactory.Instance; foreach (var isotope in formula.Isotopes) { - IElement isotopesElement = formula.Builder.NewElement(isotope); + var isotopesElement = formula.Builder.NewElement(isotope); mass += factory.GetNaturalMass(isotopesElement) * formula.GetCount(isotope); } return mass; @@ -733,18 +743,10 @@ public static double GetNaturalExactMass(IMolecularFormula formula) public static double GetMajorIsotopeMass(IMolecularFormula formula) { double mass = 0.0; - IsotopeFactory factory; - try - { - factory = Isotopes.Instance; - } - catch (IOException) - { - throw new ApplicationException("Could not instantiate the IsotopeFactory."); - } + var factory = BODRIsotopeFactory.Instance; foreach (var isotope in formula.Isotopes) { - IIsotope major = factory.GetMajorIsotope(isotope.Symbol); + var major = factory.GetMajorIsotope(isotope.Symbol); if (major != null) { mass += major.ExactMass.Value * formula.GetCount(isotope); @@ -764,7 +766,8 @@ public static double GetTotalNaturalAbundance(IMolecularFormula formula) double abundance = 1.0; foreach (var isotope in formula.Isotopes) { - if (isotope.NaturalAbundance == null) return 0.0; + if (isotope.NaturalAbundance == null) + return 0.0; abundance = abundance * Math.Pow(isotope.NaturalAbundance.Value, formula.GetCount(isotope)); } return abundance / Math.Pow(100, GetAtomCount(formula)); @@ -775,24 +778,20 @@ public static double GetTotalNaturalAbundance(IMolecularFormula formula) /// /// The IMolecularFormula to calculate /// The number of DBEs - /// if DBE cannot be be evaluated + /// if DBE cannot be evaluated // @cdk.keyword DBE // @cdk.keyword double bond equivalent public static double GetDBE(IMolecularFormula formula) { - int[] valencies = new int[5]; - IAtomContainer ac = GetAtomContainer(formula); - AtomTypeFactory factory = AtomTypeFactory.GetInstance( - "NCDK.Config.Data.structgen_atomtypes.xml", ac.Builder); + var valencies = new int[5]; + var ac = GetAtomContainer(formula); + var factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", ac.Builder); for (int f = 0; f < ac.Atoms.Count; f++) { var types = factory.GetAtomTypes(ac.Atoms[f].Symbol); if (types.Count() == 0) - throw new CDKException( - "Calculation of double bond equivalents not possible due to problems with element " - + ac.Atoms[f].Symbol); - // valencies[(int) (types[0].BondOrderSum + ac.Atoms[f].FormalCharge)]++; + throw new CDKException($"Calculation of double bond equivalents not possible due to problems with element {ac.Atoms[f].Symbol}"); valencies[(int)types.First().BondOrderSum.Value]++; } return 1 + (valencies[4]) + (valencies[3] / 2) - (valencies[1] / 2); @@ -808,14 +807,14 @@ public static double GetDBE(IMolecularFormula formula) /// public static IMolecularFormula GetMolecularFormula(IAtomContainer atomContainer) { - IMolecularFormula formula = atomContainer.Builder.NewMolecularFormula(); + var formula = atomContainer.Builder.NewMolecularFormula(); return GetMolecularFormula(atomContainer, formula); } /// /// Method that actually does the work of convert the atomContainer - /// to IMolecularFormula given a IMolecularFormula. + /// to IMolecularFormula given a . /// The hydrogens must be implicit. /// /// IAtomContainer object @@ -829,11 +828,13 @@ public static IMolecularFormula GetMolecularFormula(IAtomContainer atomContainer foreach (var iAtom in atomContainer.Atoms) { formula.Add(iAtom); - if (iAtom.FormalCharge != null) charge += iAtom.FormalCharge.Value; + if (iAtom.FormalCharge != null) + charge += iAtom.FormalCharge.Value; if (iAtom.ImplicitHydrogenCount != null && (iAtom.ImplicitHydrogenCount.Value > 0)) { - if (hAtom == null) hAtom = atomContainer.Builder.NewAtom("H"); + if (hAtom == null) + hAtom = atomContainer.Builder.NewAtom("H"); formula.Add(hAtom, iAtom.ImplicitHydrogenCount.Value); } } @@ -842,38 +843,34 @@ public static IMolecularFormula GetMolecularFormula(IAtomContainer atomContainer } /// - /// Method that actually does the work of convert the IMolecularFormula - /// to IAtomContainer. + /// Method that actually does the work of convert the + /// to . /// The hydrogens must be implicit. /// - /// IMolecularFormula object /// the filled AtomContainer /// public static IAtomContainer GetAtomContainer(IMolecularFormula formula) { - - IAtomContainer atomContainer = formula.Builder.NewAtomContainer(); + var atomContainer = formula.Builder.NewAtomContainer(); return GetAtomContainer(formula, atomContainer); } /// - /// Method that actually does the work of convert the IMolecularFormula - /// to IAtomContainer given a IAtomContainer. + /// Method that actually does the work of convert the + /// to given a . /// The hydrogens must be implicit. /// - /// IMolecularFormula object /// IAtomContainer to put the new Elements /// the filled AtomContainer /// public static IAtomContainer GetAtomContainer(IMolecularFormula formula, IAtomContainer atomContainer) { - foreach (var isotope in formula.Isotopes) { - int occur = formula.GetCount(isotope); + var occur = formula.GetCount(isotope); for (int i = 0; i < occur; i++) { - IAtom atom = formula.Builder.NewAtom(isotope); + var atom = formula.Builder.NewAtom(isotope); atomContainer.Atoms.Add(atom); } } @@ -889,8 +886,7 @@ public static IAtomContainer GetAtomContainer(IMolecularFormula formula, IAtomCo /// atoms wrapped in an atom container public static IAtomContainer GetAtomContainer(string formulaString, IChemObjectBuilder builder) { - return MolecularFormulaManipulator.GetAtomContainer(MolecularFormulaManipulator.GetMolecularFormula( - formulaString, builder)); + return MolecularFormulaManipulator.GetAtomContainer(MolecularFormulaManipulator.GetMolecularFormula(formulaString, builder)); } /// @@ -901,25 +897,25 @@ public static IAtomContainer GetAtomContainer(string formulaString, IChemObjectB /// with the tail-end of the periodic table in atom-number order and finally /// the generic R-group. /// - public static string[] OrderEle { get; } = new string[] + public static IReadOnlyList OrderEle { get; } = new string[] { - // Elements of life - "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", "He", "Be", "Li", - - // rest of periodic table, in atom-number order. - "Bi", "Po", "At", "Rn", - // row-7 elements (including f-block) - "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", - "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", - - // The "odd one out": an unspecified R-group - "R", + // Elements of life + "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", "He", "Be", "Li", + + // rest of periodic table, in atom-number order. + "Bi", "Po", "At", "Rn", + // row-7 elements (including f-block) + "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", + "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", + + // The "odd one out": an unspecified R-group + "R", }; /// @@ -927,19 +923,18 @@ public static IAtomContainer GetAtomContainer(string formulaString, IChemObjectB /// (i.e. strict alphabetical order, with one-letter elements preceding two-letter elements.) /// The generic R-group is treated specially and comes last. /// - /// Elements in Hill system order (strictly alphabetical), with generic R-groups last. - private static string[] GenerateOrderEle_Hill_NoCarbons() + private static IReadOnlyList OrderEleHillNoCarbons { get; } = new string[] { - return new string[]{"Ac", "Ag", "Al", "Am", "Ar", "As", "At", "Au", "B", "Ba", "Be", "Bh", "Bi", "Bk", "Br", - "C", "Ca", "Cd", "Ce", "Cf", "Cl", "Cm", "Cn", "Co", "Cr", "Cs", "Cu", "Db", "Ds", "Dy", "Er", "Es", - "Eu", "F", "Fe", "Fm", "Fr", "Ga", "Gd", "Ge", "H", "He", "Hf", "Hg", "Ho", "Hs", "I", "In", "Ir", "K", - "Kr", "La", "Li", "Lr", "Lu", "Md", "Mg", "Mn", "Mo", "Mt", "N", "Na", "Nb", "Nd", "Ne", "Ni", "No", - "Np", "O", "Os", "P", "Pa", "Pb", "Pd", "Pm", "Po", "Pr", "Pt", "Pu", "Ra", "Rb", "Re", "Rf", "Rg", - "Rh", "Rn", "Ru", "S", "Sb", "Sc", "Se", "Sg", "Si", "Sm", "Sn", "Sr", "Ta", "Tb", "Tc", "Te", "Th", - "Ti", "Tl", "Tm", "U", "V", "W", "Xe", "Y", "Yb", "Zn", "Zr", - // The "odd one out": an unspecified R-group - "R"}; - } + "Ac", "Ag", "Al", "Am", "Ar", "As", "At", "Au", "B", "Ba", "Be", "Bh", "Bi", "Bk", "Br", + "C", "Ca", "Cd", "Ce", "Cf", "Cl", "Cm", "Cn", "Co", "Cr", "Cs", "Cu", "Db", "Ds", "Dy", "Er", "Es", + "Eu", "F", "Fe", "Fm", "Fr", "Ga", "Gd", "Ge", "H", "He", "Hf", "Hg", "Ho", "Hs", "I", "In", "Ir", "K", + "Kr", "La", "Li", "Lr", "Lu", "Md", "Mg", "Mn", "Mo", "Mt", "N", "Na", "Nb", "Nd", "Ne", "Ni", "No", + "Np", "O", "Os", "P", "Pa", "Pb", "Pd", "Pm", "Po", "Pr", "Pt", "Pu", "Ra", "Rb", "Re", "Rf", "Rg", + "Rh", "Rn", "Ru", "S", "Sb", "Sc", "Se", "Sg", "Si", "Sm", "Sn", "Sr", "Ta", "Tb", "Tc", "Te", "Th", + "Ti", "Tl", "Tm", "U", "V", "W", "Xe", "Y", "Yb", "Zn", "Zr", + // The "odd one out": an unspecified R-group + "R" + }; /// /// Returns the Elements in Hill system order for carbon-containing formulas @@ -947,19 +942,18 @@ private static string[] GenerateOrderEle_Hill_NoCarbons() /// alphabetical order, with one-letter elements preceding two-letter elements.) /// The generic R-group is treated specially and comes last. /// - /// Elements in Hill system order with carbons and hydrogens first (and generic R-groups last). - private static string[] GenerateOrderEle_Hill_WithCarbons() + private static IReadOnlyList OrderEleHillWithCarbons { get; } = new string[] { - return new string[]{"C", "H", "Ac", "Ag", "Al", "Am", "Ar", "As", "At", "Au", "B", "Ba", "Be", "Bh", "Bi", - "Bk", "Br", "Ca", "Cd", "Ce", "Cf", "Cl", "Cm", "Cn", "Co", "Cr", "Cs", "Cu", "Db", "Ds", "Dy", "Er", - "Es", "Eu", "F", "Fe", "Fm", "Fr", "Ga", "Gd", "Ge", "He", "Hf", "Hg", "Ho", "Hs", "I", "In", "Ir", - "K", "Kr", "La", "Li", "Lr", "Lu", "Md", "Mg", "Mn", "Mo", "Mt", "N", "Na", "Nb", "Nd", "Ne", "Ni", - "No", "Np", "O", "Os", "P", "Pa", "Pb", "Pd", "Pm", "Po", "Pr", "Pt", "Pu", "Ra", "Rb", "Re", "Rf", - "Rg", "Rh", "Rn", "Ru", "S", "Sb", "Sc", "Se", "Sg", "Si", "Sm", "Sn", "Sr", "Ta", "Tb", "Tc", "Te", - "Th", "Ti", "Tl", "Tm", "U", "V", "W", "Xe", "Y", "Yb", "Zn", "Zr", - // The "odd one out": an unspecified R-group - "R"}; - } + "C", "H", "Ac", "Ag", "Al", "Am", "Ar", "As", "At", "Au", "B", "Ba", "Be", "Bh", "Bi", + "Bk", "Br", "Ca", "Cd", "Ce", "Cf", "Cl", "Cm", "Cn", "Co", "Cr", "Cs", "Cu", "Db", "Ds", "Dy", "Er", + "Es", "Eu", "F", "Fe", "Fm", "Fr", "Ga", "Gd", "Ge", "He", "Hf", "Hg", "Ho", "Hs", "I", "In", "Ir", + "K", "Kr", "La", "Li", "Lr", "Lu", "Md", "Mg", "Mn", "Mo", "Mt", "N", "Na", "Nb", "Nd", "Ne", "Ni", + "No", "Np", "O", "Os", "P", "Pa", "Pb", "Pd", "Pm", "Po", "Pr", "Pt", "Pu", "Ra", "Rb", "Re", "Rf", + "Rg", "Rh", "Rn", "Ru", "S", "Sb", "Sc", "Se", "Sg", "Si", "Sm", "Sn", "Sr", "Ta", "Tb", "Tc", "Te", + "Th", "Ti", "Tl", "Tm", "U", "V", "W", "Xe", "Y", "Yb", "Zn", "Zr", + // The "odd one out": an unspecified R-group + "R" + }; /// /// Compare two IMolecularFormula looking at type and number of IIsotope and @@ -970,23 +964,27 @@ private static string[] GenerateOrderEle_Hill_WithCarbons() /// True, if the both IMolecularFormula are the same public static bool Compare(IMolecularFormula formula1, IMolecularFormula formula2) { + if (formula1.Charge != formula2.Charge) + return false; - if (formula1.Charge != formula2.Charge) return false; - - if (formula1.Count != formula2.Count) return false; + if (formula1.IsotopesCount != formula2.IsotopesCount) + return false; foreach (var isotope in formula1.Isotopes) { - if (!formula2.Contains(isotope)) return false; - - if (formula1.GetCount(isotope) != formula2.GetCount(isotope)) return false; + if (!formula2.Contains(isotope)) + return false; + if (formula1.GetCount(isotope) != formula2.GetCount(isotope)) + return false; } foreach (var isotope in formula2.Isotopes) { - if (!formula1.Contains(isotope)) return false; - if (formula2.GetCount(isotope) != formula1.GetCount(isotope)) return false; + if (!formula1.Contains(isotope)) + return false; + if (formula2.GetCount(isotope) != formula1.GetCount(isotope)) + return false; } return true; @@ -1002,7 +1000,7 @@ public static IEnumerable GetHeavyElements(IMolecularFormula formula) { foreach (var element in Elements(formula)) { - if (!element.Symbol.Equals("H")) + if (!string.Equals(element.Symbol, "H", StringComparison.Ordinal)) { yield return element; } @@ -1026,7 +1024,8 @@ public static string SimplifyMolecularFormula(string formula) { newFormula = newFormula.Replace(" ", ""); } - if (!formula.Contains(".")) return BreakExtractor(formula); + if (!formula.Contains(".")) + return BreakExtractor(formula); List listMF = new List(); while (newFormula.Contains(".")) @@ -1036,29 +1035,31 @@ public static string SimplifyMolecularFormula(string formula) if (thisFormula[0] >= '0' && thisFormula[0] <= '9') thisFormula = MultipleExtractor(thisFormula); - if (thisFormula.Contains("(")) thisFormula = BreakExtractor(thisFormula); + if (thisFormula.Contains("(")) + thisFormula = BreakExtractor(thisFormula); listMF.Add(thisFormula); thisFormula = newFormula.Substring(pos + 1, newFormula.Length - (pos + 1)); if (!thisFormula.Contains(".")) { - if (thisFormula[0] >= '0' && thisFormula[0] <= '9') thisFormula = MultipleExtractor(thisFormula); - if (thisFormula.Contains("(")) thisFormula = BreakExtractor(thisFormula); + if (thisFormula.Contains("(")) + thisFormula = BreakExtractor(thisFormula); listMF.Add(thisFormula); } newFormula = thisFormula; } - if (newFormula.Contains("(")) newFormula = BreakExtractor(newFormula); + if (newFormula.Contains("(")) + newFormula = BreakExtractor(newFormula); string recentElementSymbol = ""; string recentElementCountString = "0"; - List eleSymb = new List(); - List eleCount = new List(); + var eleSymb = new List(); + var eleCount = new List(); for (int i = 0; i < listMF.Count; i++) { string thisFormula = listMF[i]; @@ -1069,7 +1070,7 @@ public static string SimplifyMolecularFormula(string formula) { if (thisChar >= 'A' && thisChar <= 'Z') { - recentElementSymbol = thisChar.ToString(); + recentElementSymbol = new string(new[] { thisChar }); recentElementCountString = "0"; } if (thisChar >= 'a' && thisChar <= 'z') @@ -1081,11 +1082,10 @@ public static string SimplifyMolecularFormula(string formula) recentElementCountString += thisChar; } } - if (f == thisFormula.Length - 1 - || (thisFormula[f + 1] >= 'A' && thisFormula[f + 1] <= 'Z')) + if (f == thisFormula.Length - 1 || (thisFormula[f + 1] >= 'A' && thisFormula[f + 1] <= 'Z')) { int posit = eleSymb.IndexOf(recentElementSymbol); - int count = int.Parse(recentElementCountString); + int count = int.Parse(recentElementCountString, NumberFormatInfo.InvariantInfo); if (posit == -1) { eleSymb.Add(recentElementSymbol); @@ -1093,28 +1093,28 @@ public static string SimplifyMolecularFormula(string formula) } else { - int countP = int.Parse(recentElementCountString); - if (countP == 0) countP = 1; + int countP = int.Parse(recentElementCountString, NumberFormatInfo.InvariantInfo); + if (countP == 0) + countP = 1; int countA = eleCount[posit]; - if (countA == 0) countA = 1; + if (countA == 0) + countA = 1; int value = countP + countA; eleCount.RemoveAt(posit); eleCount.Insert(posit, value); } - } } } string newF = ""; for (int i = 0; i < eleCount.Count; i++) { - string element = eleSymb[i]; - int num = eleCount[i]; + var element = eleSymb[i]; + var num = eleCount[i]; if (num == 0) newF += element; else newF += element + num; - } return newF; } @@ -1132,7 +1132,7 @@ private static string BreakExtractor(string formula) string multiple = "0"; for (int f = 0; f < formula.Length; f++) { - char thisChar = formula[f]; + var thisChar = formula[f]; if (thisChar == '(') { // start @@ -1152,7 +1152,7 @@ private static string BreakExtractor(string formula) } } - string finalformula = Muliplier(recentformula, int.Parse(multiple)); + var finalformula = Muliplier(recentformula, int.Parse(multiple, NumberFormatInfo.InvariantInfo)); return finalformula; } @@ -1164,8 +1164,8 @@ private static string BreakExtractor(string formula) /// Formula with the correction private static string MultipleExtractor(string formula) { - string recentCompoundCount = "0"; - string recentCompound = ""; + var recentCompoundCount = new StringBuilder("0"); + var recentCompound = new StringBuilder(); bool found = false; for (int f = 0; f < formula.Length; f++) @@ -1174,17 +1174,17 @@ private static string MultipleExtractor(string formula) if (thisChar >= '0' && thisChar <= '9') { if (!found) - recentCompoundCount += thisChar; + recentCompoundCount.Append(thisChar); else - recentCompound += thisChar; + recentCompound.Append(thisChar); } else { found = true; - recentCompound += thisChar; + recentCompound.Append(thisChar); } } - return Muliplier(recentCompound, int.Parse(recentCompoundCount)); + return Muliplier(recentCompound.ToString(), int.Parse(recentCompoundCount.ToString(), NumberFormatInfo.InvariantInfo)); } /// @@ -1195,9 +1195,9 @@ private static string MultipleExtractor(string formula) /// Formula with the correction private static string Muliplier(string formula, int factor) { - string finalformula = ""; - string recentElementSymbol = ""; - string recentElementCountString = "0"; + var finalformula = new StringBuilder(); + var recentElementSymbol = new StringBuilder(); + var recentElementCountString = new StringBuilder("0"); for (int f = 0; f < formula.Length; f++) { char thisChar = formula[f]; @@ -1205,28 +1205,28 @@ private static string Muliplier(string formula, int factor) { if (thisChar >= 'A' && thisChar <= 'Z') { - recentElementSymbol = thisChar.ToString(); - recentElementCountString = "0"; + recentElementSymbol = new StringBuilder().Append(thisChar); + recentElementCountString = new StringBuilder("0"); } if (thisChar >= 'a' && thisChar <= 'z') { - recentElementSymbol += thisChar; + recentElementSymbol.Append(thisChar); } if (thisChar >= '0' && thisChar <= '9') { - recentElementCountString += thisChar; + recentElementCountString.Append(thisChar); } } if (f == formula.Length - 1 || (formula[f + 1] >= 'A' && formula[f + 1] <= 'Z')) { - int recentElementCount = int.Parse(recentElementCountString); + int recentElementCount = int.Parse(recentElementCountString.ToString(), NumberFormatInfo.InvariantInfo); if (recentElementCount == 0) - finalformula += recentElementSymbol + factor; + finalformula.Append(recentElementSymbol).Append(factor); else - finalformula += recentElementSymbol + recentElementCount * factor; + finalformula.Append(recentElementSymbol).Append(recentElementCount * factor); } } - return finalformula; + return finalformula.ToString(); } /// @@ -1258,8 +1258,10 @@ private static string Muliplier(string formula, int factor) /// the protonation was be adjusted public static bool AdjustProtonation(IMolecularFormula mf, int hcnt) { - if (mf == null) throw new ArgumentNullException(nameof(mf), "No formula provided"); - if (hcnt == 0) return false; // no protons to add + if (mf == null) + throw new ArgumentNullException(nameof(mf), "No formula provided"); + if (hcnt == 0) + return false; // no protons to add IChemObjectBuilder bldr = mf.Builder; int chg = mf.Charge ?? 0; @@ -1269,7 +1271,7 @@ public static bool AdjustProtonation(IMolecularFormula mf, int hcnt) foreach (IIsotope iso in mf.Isotopes) { - if ("H".Equals(iso.Symbol)) + if (string.Equals("H", iso.Symbol, StringComparison.Ordinal)) { int count = mf.GetCount(iso); if (count < hcnt) diff --git a/NCDK/Tools/Manipulator/MolecularFormulaRangeManipulator.cs b/NCDK/Tools/Manipulator/MolecularFormulaRangeManipulator.cs index 081a0788..5a7b6e0e 100644 --- a/NCDK/Tools/Manipulator/MolecularFormulaRangeManipulator.cs +++ b/NCDK/Tools/Manipulator/MolecularFormulaRangeManipulator.cs @@ -75,7 +75,7 @@ public static MolecularFormulaRange GetRange(IMolecularFormulaSet mfSet) // looking for those Isotopes which are not contained which then should be 0. foreach (var mf in mfSet) { - if (mf.Count != mfRange.Count) + if (mf.IsotopesCount != mfRange.Count) { foreach (var isotope in mfRange.GetIsotopes().ToList()) { diff --git a/NCDK/Tools/Manipulator/ReactionManipulator.cs b/NCDK/Tools/Manipulator/ReactionManipulator.cs index c49d3d02..9d412986 100644 --- a/NCDK/Tools/Manipulator/ReactionManipulator.cs +++ b/NCDK/Tools/Manipulator/ReactionManipulator.cs @@ -516,7 +516,7 @@ public static ISet FindMappedBonds(IReaction reaction) } // fail fast if (!mappedReactantBonds.Any()) - return GenericCollections.GetEmptySet(); + return Sets.Empty(); foreach (IAtomContainer product in reaction.Products) { @@ -530,7 +530,7 @@ public static ISet FindMappedBonds(IReaction reaction) } // fail fast if (!mappedProductBonds.Any()) - return GenericCollections.GetEmptySet(); + return Sets.Empty(); // repeat above but now store any that are different or unmapped as being mapped foreach (IAtomContainer reactant in reaction.Reactants) diff --git a/NCDK/Tools/Manipulator/ReactionSetManipulator.cs b/NCDK/Tools/Manipulator/ReactionSetManipulator.cs index 82407d86..c733a87b 100644 --- a/NCDK/Tools/Manipulator/ReactionSetManipulator.cs +++ b/NCDK/Tools/Manipulator/ReactionSetManipulator.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using System; using System.Collections.Generic; namespace NCDK.Tools.Manipulator @@ -277,7 +278,7 @@ public static IReaction GetReactionByReactionID(IReactionSet reactionSet, string { foreach (var reaction in reactionSet) { - if (reaction.Id != null && reaction.Id.Equals(id)) + if (string.Equals(reaction.Id, id, StringComparison.Ordinal)) { return reaction; } diff --git a/NCDK/Tools/Manipulator/RingSetManipulator.cs b/NCDK/Tools/Manipulator/RingSetManipulator.cs index e3bfd10f..45082143 100644 --- a/NCDK/Tools/Manipulator/RingSetManipulator.cs +++ b/NCDK/Tools/Manipulator/RingSetManipulator.cs @@ -63,33 +63,31 @@ public static IAtomContainer GetAllInOneContainer(IRingSet ringSet) /// /// Returns the largest (number of atoms) ring set in a molecule - /// + /// /// RingSystems of a molecule /// The largestRingSet - /// - public static IRingSet GetLargestRingSet(IList ringSystems) + public static IRingSet GetLargestRingSet(IEnumerable ringSystems) { IRingSet largestRingSet = null; int atomNumber = 0; IAtomContainer container = null; - for (int i = 0; i < ringSystems.Count; i++) + foreach (var ringSystem in ringSystems) { - container = RingSetManipulator.GetAllInOneContainer(ringSystems[i]); + container = RingSetManipulator.GetAllInOneContainer(ringSystem); if (atomNumber < container.Atoms.Count) { atomNumber = container.Atoms.Count; - largestRingSet = ringSystems[i]; + largestRingSet = ringSystem; } } return largestRingSet; } /// - /// Return the total number of bonds over all the rings in the colllection. - /// + /// Return the total number of bonds over all the rings in the collection. + /// /// The collection of rings /// The total number of bonds - /// public static int GetBondCount(IRingSet set) { int count = 0; @@ -118,7 +116,7 @@ public static IEnumerable GetAllAtomContainers(IEnumerable ringSet) { var ringList = ringSet.ToList(); - ringList.Sort(new RingSizeComparator(RingSizeComparator.SMALL_FIRST)); + ringList.Sort(new RingSizeComparator(SortMode.SmallFirst)); ringSet.Clear(); foreach (var aRingList in ringList) ringSet.Add(aRingList); @@ -130,7 +128,7 @@ public static void Sort(IList ringSet) /// /// The collection of rings /// A bond which must be contained by the heaviest ring - /// The ring with the higest number of double bonds connected to a given bond + /// The ring with the highest number of double bonds connected to a given bond public static IRing GetHeaviestRing(IRingSet ringSet, IBond bond) { var rings = ringSet.GetRings(bond); @@ -138,10 +136,10 @@ public static IRing GetHeaviestRing(IRingSet ringSet, IBond bond) int maxOrderSum = 0; foreach (var ring1 in rings) { - if (maxOrderSum < ((IRing)ring1).BondOrderSum) + if (maxOrderSum < ((IRing)ring1).GetBondOrderSum()) { ring = (IRing)ring1; - maxOrderSum = ring.BondOrderSum; + maxOrderSum = ring.GetBondOrderSum(); } } return ring; @@ -169,7 +167,7 @@ public static IRing GetMostComplexRing(IChemObjectSet ringSet) for (int j = 0; j < ring1.Atoms.Count; j++) { atom1 = ring1.Atoms[j]; - /* Look at each of the other rings in the ringset */ + /* Look at each of the other rings in the ring set */ for (int k = i + 1; k < ringSet.Count; k++) { ring2 = (IRing)ringSet[k]; @@ -208,13 +206,13 @@ public static IRing GetMostComplexRing(IChemObjectSet ringSet) /// /// /// This method only returns meaningful results if and - /// are members of the same molecule for which the RingSet was calculated! + /// are members of the same molecule for which the ring set was calculated! /// /// /// The collection of rings /// The first atom /// The second atom - /// bool true if and share membership of at least one ring or ring system, false otherwise + /// if and share membership of at least one ring or ring system, false otherwise public static bool IsSameRing(IRingSet ringSet, IAtom atom1, IAtom atom2) { foreach (var atomContainer in ringSet) @@ -227,7 +225,7 @@ public static bool IsSameRing(IRingSet ringSet, IAtom atom1, IAtom atom2) /// /// Checks - and returns 'true' - if a certain ring is already - /// stored in the ringset. This is not a test for equality of Ring + /// stored in the ring set. This is not a test for equality of Ring /// objects, but compares all Bond objects of the ring. /// /// The ring to be tested if it is already stored @@ -236,9 +234,6 @@ public static bool IsSameRing(IRingSet ringSet, IAtom atom1, IAtom atom2) public static bool RingAlreadyInSet(IRing newRing, IRingSet ringSet) { IRing ring; - // IBond[] bonds; - // IBond[] newBonds; - // IBond bond; int equalCount; bool equals; for (int f = 0; f < ringSet.Count; f++) @@ -247,9 +242,6 @@ public static bool RingAlreadyInSet(IRing newRing, IRingSet ringSet) equalCount = 0; ring = (IRing)ringSet[f]; - // bonds = ring.Bonds; - // newBonds = newRing.Bonds; - if (ring.Bonds.Count == newRing.Bonds.Count) { foreach (var newBond in newRing.Bonds) @@ -278,9 +270,10 @@ public static bool RingAlreadyInSet(IRing newRing, IRingSet ringSet) /// /// Iterates over the rings in the ring set, and marks the ring /// aromatic if all atoms and all bonds are aromatic. - /// - /// This method assumes that aromaticity perception has been done before hand. /// + /// + /// This method assumes that aromaticity perception has been done before hand. + /// /// The collection of rings public static void MarkAromaticRings(IRingSet ringset) { diff --git a/NCDK/Tools/Manipulator/RingSizeComparator.cs b/NCDK/Tools/Manipulator/RingSizeComparator.cs index 6a8a087f..5b74fd06 100644 --- a/NCDK/Tools/Manipulator/RingSizeComparator.cs +++ b/NCDK/Tools/Manipulator/RingSizeComparator.cs @@ -25,23 +25,26 @@ namespace NCDK.Tools.Manipulator { - // @cdk.module standard - // @cdk.githash - public class RingSizeComparator : IComparer + public enum SortMode { /// Flag to denote that the set is order with the largest ring first - public const int LARGE_FIRST = 1; + LargeFirst = 1, + /// Flag to denote that the set is order with the smallest ring first - public const int SMALL_FIRST = 2; + SmallFirst = 2, + } - int sortOrder = SMALL_FIRST; + // @cdk.module standard + // @cdk.githash + public class RingSizeComparator : IComparer + { + private readonly SortMode sortOrder = SortMode.SmallFirst; /// /// Constructs a new comparator to sort rings by size. /// - /// Sort order: either RingSet.SMALL_FIRST or - /// RingSet.LARGE_FIRST. - public RingSizeComparator(int order) + /// Sort order: either or . + public RingSizeComparator(SortMode order) { sortOrder = order; } @@ -51,19 +54,19 @@ public int Compare(IRing object1, IRing object2) int size1 = object1.Atoms.Count; int size2 = object2.Atoms.Count; if (size1 == size2) return 0; - if (size1 > size2 && sortOrder == SMALL_FIRST) + if (size1 > size2 && sortOrder == SortMode.SmallFirst) { return 1; } - if (size1 > size2 && sortOrder == LARGE_FIRST) + if (size1 > size2 && sortOrder == SortMode.LargeFirst) { return -1; } - if (size1 < size2 && sortOrder == SMALL_FIRST) + if (size1 < size2 && sortOrder == SortMode.SmallFirst) { return -1; } - if (size1 < size2 && sortOrder == LARGE_FIRST) + if (size1 < size2 && sortOrder == SortMode.LargeFirst) { return 1; } diff --git a/NCDK/Tools/Manipulator/SgroupManipulator.cs b/NCDK/Tools/Manipulator/SgroupManipulator.cs index 9ee0b51c..3d54ec9d 100644 --- a/NCDK/Tools/Manipulator/SgroupManipulator.cs +++ b/NCDK/Tools/Manipulator/SgroupManipulator.cs @@ -59,25 +59,25 @@ private static T Get(CDKObjectMap map, T obj) where T : IChemObject /// collection of sgroups, can be null /// the replacement map, can be null /// list of copied sgroups, null if sgroups input was null - public static IList Copy(ICollection sgroups, CDKObjectMap replace) + public static IList Copy(IList sgroups, CDKObjectMap replace) { if (sgroups == null) return null; var sgroupMap = new Dictionary(); - foreach (Sgroup sgroup in sgroups) + foreach (var sgroup in sgroups) sgroupMap[sgroup] = new Sgroup(); foreach (var e in sgroupMap) { - Sgroup orgSgroup = e.Key; - Sgroup cpySgroup = e.Value; + var orgSgroup = e.Key; + var cpySgroup = e.Value; cpySgroup.Type = orgSgroup.Type; - foreach (IAtom atom in orgSgroup.Atoms) + foreach (var atom in orgSgroup.Atoms) cpySgroup.Atoms.Add(Get(replace, atom)); - foreach (IBond bond in orgSgroup.Bonds) + foreach (var bond in orgSgroup.Bonds) cpySgroup.Bonds.Add(Get(replace, bond)); - foreach (Sgroup parent in orgSgroup.Parents) + foreach (var parent in orgSgroup.Parents) cpySgroup.Parents.Add(sgroupMap[parent]); - foreach (SgroupKey key in SgroupKeyTools.Values) + foreach (var key in SgroupTool.SgroupKeyValues) { switch (key) { diff --git a/NCDK/Tools/ProteinBuilderTool.cs b/NCDK/Tools/ProteinBuilderTool.cs index c1f5c5a0..acbe057e 100644 --- a/NCDK/Tools/ProteinBuilderTool.cs +++ b/NCDK/Tools/ProteinBuilderTool.cs @@ -22,9 +22,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Silent; using NCDK.Templates; -using NCDK.Tools.Manipulator; -using System.Collections.Generic; +using System; using System.Diagnostics; using System.Linq; @@ -88,7 +88,7 @@ public static IBioPolymer AddAminoAcidAtCTerminus(IBioPolymer protein, IAminoAci /// /// Creates a BioPolymer from a sequence of amino acid as identified by a - /// the sequence of their one letter codes. It uses the + /// the sequence of their one letter codes. It uses the /// to create a data model. /// /// @@ -100,7 +100,7 @@ public static IBioPolymer AddAminoAcidAtCTerminus(IBioPolymer protein, IAminoAci /// public static IBioPolymer CreateProtein(string sequence) { - return CreateProtein(sequence, Default.ChemObjectBuilder.Instance); + return CreateProtein(sequence, ChemObjectBuilder.Instance); } /// @@ -111,23 +111,21 @@ public static IBioPolymer CreateProtein(string sequence) /// /// For example: /// - /// IBioPolymer protein = ProteinBuilderTool.CreateProtein( - /// "GAGA", Silent.ChemObjectBuilder.Instance - /// ); + /// IBioPolymer protein = ProteinBuilderTool.CreateProtein("GAGA", Silent.ChemObjectBuilder.Instance); /// /// /// public static IBioPolymer CreateProtein(string sequence, IChemObjectBuilder builder) { var templates = AminoAcids.MapBySingleCharCode; - IBioPolymer protein = builder.NewBioPolymer(); - IStrand strand = builder.NewStrand(); + var protein = builder.NewBioPolymer(); + var strand = builder.NewStrand(); IAminoAcid previousAA = null; for (int i = 0; i < sequence.Length; i++) { string aminoAcidCode = "" + sequence[i]; - Debug.WriteLine("Adding AA: " + aminoAcidCode); - if (aminoAcidCode.Equals(" ")) + Debug.WriteLine($"Adding AA: {aminoAcidCode}"); + if (string.Equals(aminoAcidCode, " ", StringComparison.Ordinal)) { // fine, just skip spaces } @@ -140,17 +138,17 @@ public static IBioPolymer CreateProtein(string sequence, IChemObjectBuilder buil } aminoAcid = (IAminoAcid)aminoAcid.Clone(); aminoAcid.MonomerName = aminoAcidCode + i; - Debug.WriteLine("protein: ", protein); - Debug.WriteLine("strand: ", strand); + Debug.WriteLine($"protein: {protein}"); + Debug.WriteLine($"strand: {strand}"); AddAminoAcidAtCTerminus(protein, aminoAcid, strand, previousAA); previousAA = aminoAcid; } } // add the last oxygen of the protein - IAtom oxygen = builder.NewAtom("O"); + var oxygen = builder.NewAtom("O"); // ... to amino acid previousAA.Atoms.Add(oxygen); - IBond bond = builder.NewBond(oxygen, previousAA.CTerminus, BondOrder.Single); + var bond = builder.NewBond(oxygen, previousAA.CTerminus, BondOrder.Single); previousAA.Bonds.Add(bond); // ... and to protein protein.AddAtom(oxygen, previousAA, strand); @@ -160,9 +158,9 @@ public static IBioPolymer CreateProtein(string sequence, IChemObjectBuilder buil private static IBioPolymer AddAminoAcid(IBioPolymer protein, IAminoAcid aaToAdd, IStrand strand) { - foreach (var atom in AtomContainerManipulator.GetAtomArray(aaToAdd)) + foreach (var atom in aaToAdd.Atoms) protein.AddAtom(atom, aaToAdd, strand); - foreach (var bond in AtomContainerManipulator.GetBondArray(aaToAdd)) + foreach (var bond in aaToAdd.Bonds) protein.Bonds.Add(bond); return protein; } diff --git a/NCDK/Tools/SaturationChecker.cs b/NCDK/Tools/SaturationChecker.cs index 55f5c8d5..a1ff221a 100644 --- a/NCDK/Tools/SaturationChecker.cs +++ b/NCDK/Tools/SaturationChecker.cs @@ -81,9 +81,9 @@ public bool HasPerfectConfiguration(IAtom atom, IAtomContainer ac) Debug.WriteLine("*** Checking for perfect configuration ***"); try { - Debug.WriteLine("Checking configuration of atom " + ac.Atoms.IndexOf(atom)); - Debug.WriteLine("Atom has bondOrderSum = " + bondOrderSum); - Debug.WriteLine("Atom has max = " + bondOrderSum); + Debug.WriteLine($"Checking configuration of atom {ac.Atoms.IndexOf(atom)}"); + Debug.WriteLine($"Atom has bondOrderSum = {bondOrderSum}"); + Debug.WriteLine($"Atom has max = {bondOrderSum}"); } catch (Exception) { @@ -94,7 +94,7 @@ public bool HasPerfectConfiguration(IAtom atom, IAtomContainer ac) { try { - Debug.WriteLine("Atom " + ac.Atoms.IndexOf(atom) + " has perfect configuration"); + Debug.WriteLine($"Atom {ac.Atoms.IndexOf(atom)} has perfect configuration"); } catch (Exception) { @@ -104,7 +104,7 @@ public bool HasPerfectConfiguration(IAtom atom, IAtomContainer ac) } try { - Debug.WriteLine("*** Atom " + ac.Atoms.IndexOf(atom) + " has imperfect configuration ***"); + Debug.WriteLine($"*** Atom {ac.Atoms.IndexOf(atom)} has imperfect configuration ***"); } catch (Exception) { @@ -139,8 +139,7 @@ public bool AllSaturated(IAtomContainer ac) /// public bool IsUnsaturated(IBond bond, IAtomContainer atomContainer) { - - IAtom[] atoms = BondManipulator.GetAtomArray(bond); + var atoms = BondManipulator.GetAtomArray(bond); bool isUnsaturated = true; for (int i = 0; i < atoms.Length; i++) { @@ -155,7 +154,7 @@ public bool IsUnsaturated(IBond bond, IAtomContainer atomContainer) /// public bool IsSaturated(IBond bond, IAtomContainer atomContainer) { - IAtom[] atoms = BondManipulator.GetAtomArray(bond); + var atoms = BondManipulator.GetAtomArray(bond); bool isSaturated = true; for (int i = 0; i < atoms.Length; i++) { @@ -165,14 +164,15 @@ public bool IsSaturated(IBond bond, IAtomContainer atomContainer) } /// - /// Checks whether an Atom is saturated by comparing it with known AtomTypes. + /// Checks whether an Atom is saturated by comparing it with known atom types. /// public bool IsSaturated(IAtom atom, IAtomContainer ac) { var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); - if (!atomTypes.Any()) return true; + if (!atomTypes.Any()) + return true; double bondOrderSum = 0; - BondOrder maxBondOrder = BondOrder.Unset; + var maxBondOrder = BondOrder.Unset; int hcount = 0; int charge = 0; bool isInited = false; @@ -198,7 +198,7 @@ public bool IsSaturated(IAtom atom, IAtomContainer ac) } } if (bondOrderSum - charge + hcount == atomType.BondOrderSum - && !BondManipulator.IsHigherOrder(maxBondOrder, atomType.MaxBondOrder)) + && !BondManipulator.IsHigherOrder(maxBondOrder, atomType.MaxBondOrder)) { Debug.WriteLine("*** Good ! ***"); return true; @@ -212,22 +212,23 @@ public bool IsSaturated(IAtom atom, IAtomContainer ac) /// Checks if the current atom has exceeded its bond order sum value. /// /// The Atom to check - /// The atomcontainer context + /// The atom container context /// oversaturated or not public bool IsOverSaturated(IAtom atom, IAtomContainer ac) { var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); - if (!atomTypes.Any()) return false; - double bondOrderSum = ac.GetBondOrderSum(atom); - BondOrder maxBondOrder = ac.GetMaximumBondOrder(atom); - int? hcount = atom.ImplicitHydrogenCount == null ? 0 : atom.ImplicitHydrogenCount; - int? charge = atom.FormalCharge == null ? 0 : atom.FormalCharge; + if (!atomTypes.Any()) + return false; + var bondOrderSum = ac.GetBondOrderSum(atom); + var maxBondOrder = ac.GetMaximumBondOrder(atom); + var hcount = atom.ImplicitHydrogenCount ?? 0; + var charge = atom.FormalCharge ?? 0; try { - Debug.WriteLine("*** Checking saturation of atom " + ac.Atoms.IndexOf(atom) + " ***"); - Debug.WriteLine("bondOrderSum: " + bondOrderSum); - Debug.WriteLine("maxBondOrder: " + maxBondOrder); - Debug.WriteLine("hcount: " + hcount); + Debug.WriteLine($"*** Checking saturation of atom {ac.Atoms.IndexOf(atom)} ***"); + Debug.WriteLine($"bondOrderSum: {bondOrderSum}"); + Debug.WriteLine($"maxBondOrder: {maxBondOrder}"); + Debug.WriteLine($"hcount: {hcount}"); } catch (Exception) { @@ -245,22 +246,23 @@ public bool IsOverSaturated(IAtom atom, IAtomContainer ac) } /// - /// Returns the currently maximum formable bond order for this atom. + /// Returns the currently maximum bond order for this atom. /// /// The atom to be checked /// The AtomContainer that provides the context - /// the currently maximum formable bond order for this atom + /// the currently maximum bond order for this atom public double GetCurrentMaxBondOrder(IAtom atom, IAtomContainer ac) { var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); - if (!atomTypes.Any()) return 0; - double bondOrderSum = ac.GetBondOrderSum(atom); - int? hcount = atom.ImplicitHydrogenCount == null ? 0 : atom.ImplicitHydrogenCount; + if (!atomTypes.Any()) + return 0; + var bondOrderSum = ac.GetBondOrderSum(atom); + var hcount = atom.ImplicitHydrogenCount ?? 0; double max = 0; double current = 0; foreach (var atomType in atomTypes) { - current = hcount.Value + bondOrderSum; + current = hcount + bondOrderSum; if (atomType.BondOrderSum - current > max) { max = atomType.BondOrderSum.Value - current; @@ -272,7 +274,7 @@ public double GetCurrentMaxBondOrder(IAtom atom, IAtomContainer ac) /// /// Resets the bond orders of all atoms to 1.0. /// - public void Unsaturate(IAtomContainer atomContainer) + private static void Unsaturate(IAtomContainer atomContainer) { foreach (var bond in atomContainer.Bonds) bond.Order = BondOrder.Single; @@ -281,7 +283,7 @@ public void Unsaturate(IAtomContainer atomContainer) /// /// Resets the bond order of the Bond to 1.0. /// - public void UnsaturateBonds(IAtomContainer container) + private static void UnsaturateBonds(IAtomContainer container) { foreach (var bond in container.Bonds) bond.Order = BondOrder.Single; @@ -289,7 +291,7 @@ public void UnsaturateBonds(IAtomContainer container) /// /// Saturates a molecule by setting appropriate bond orders. - /// This method is known to fail, especially on pyrolle-like compounds. + /// This method is known to fail, especially on pyrrole-like compounds. /// Consider using import org.openscience.cdk.smiles.DeduceBondSystemTool, which should work better /// // @cdk.keyword bond order, calculation @@ -300,17 +302,18 @@ public void NewSaturate(IAtomContainer atomContainer) bool allSaturated = AllSaturated(atomContainer); if (!allSaturated) { - IBond[] bonds = new IBond[atomContainer.Bonds.Count]; + var bonds = new IBond[atomContainer.Bonds.Count]; for (int i = 0; i < bonds.Length; i++) bonds[i] = atomContainer.Bonds[i]; - bool succeeded = NewSaturate(bonds, atomContainer); + var succeeded = NewSaturate(bonds, atomContainer); for (int i = 0; i < bonds.Length; i++) { if (bonds[i].Order == BondOrder.Double && bonds[i].IsAromatic - && (bonds[i].Begin.Symbol.Equals("N") && bonds[i].End.Symbol.Equals("N"))) + && (bonds[i].Begin.Symbol.Equals("N", StringComparison.Ordinal) + && bonds[i].End.Symbol.Equals("N", StringComparison.Ordinal))) { int atomtohandle = 0; - if (bonds[i].Begin.Symbol.Equals("N")) atomtohandle = 1; + if (string.Equals(bonds[i].Begin.Symbol, "N", StringComparison.Ordinal)) atomtohandle = 1; var bondstohandle = atomContainer.GetConnectedBonds(bonds[i].Atoms[atomtohandle]); foreach (var bond in bondstohandle) { @@ -332,20 +335,20 @@ public void NewSaturate(IAtomContainer atomContainer) /// /// Saturates a set of Bonds in an AtomContainer. - /// This method is known to fail, especially on pyrolle-like compounds. + /// This method is known to fail, especially on pyrrole-like compounds. /// Consider using import org.openscience.cdk.smiles.DeduceBondSystemTool, which should work better /// public bool NewSaturate(IBond[] bonds, IAtomContainer atomContainer) { - Debug.WriteLine("Saturating bond set of size: " + bonds.Length); + Debug.WriteLine($"Saturating bond set of size: {bonds.Length}"); bool bondsAreFullySaturated = true; if (bonds.Length > 0) { - IBond bond = bonds[0]; + var bond = bonds[0]; // determine bonds left - int leftBondCount = bonds.Length - 1; - IBond[] leftBonds = new IBond[leftBondCount]; + var leftBondCount = bonds.Length - 1; + var leftBonds = new IBond[leftBondCount]; Array.Copy(bonds, 1, leftBonds, 0, leftBondCount); // examine this bond @@ -353,12 +356,11 @@ public bool NewSaturate(IBond[] bonds, IAtomContainer atomContainer) { // either this bonds should be saturated or not - // try to leave this bond unsaturated and saturate the left bondssaturate this bond + // try to leave this bond unsaturated and saturate the left bonds saturate this bond if (leftBondCount > 0) { - Debug.WriteLine("Recursing with unsaturated bond with #bonds: " + leftBondCount); - bondsAreFullySaturated = NewSaturate(leftBonds, atomContainer) - && !IsUnsaturated(bond, atomContainer); + Debug.WriteLine($"Recursing with unsaturated bond with #bonds: {leftBondCount}"); + bondsAreFullySaturated = NewSaturate(leftBonds, atomContainer) && !IsUnsaturated(bond, atomContainer); } else { @@ -375,7 +377,7 @@ public bool NewSaturate(IBond[] bonds, IAtomContainer atomContainer) { if (leftBondCount > 0) { - Debug.WriteLine("Recursing with saturated bond with #bonds: " + leftBondCount); + Debug.WriteLine($"Recursing with saturated bond with #bonds: {leftBondCount}"); bondsAreFullySaturated = NewSaturate(leftBonds, atomContainer); } else @@ -396,7 +398,7 @@ public bool NewSaturate(IBond[] bonds, IAtomContainer atomContainer) Debug.WriteLine("This bond is already saturated."); if (leftBondCount > 0) { - Debug.WriteLine("Recursing with #bonds: " + leftBondCount); + Debug.WriteLine($"Recursing with #bonds: {leftBondCount}"); bondsAreFullySaturated = NewSaturate(leftBonds, atomContainer); } else @@ -410,9 +412,8 @@ public bool NewSaturate(IBond[] bonds, IAtomContainer atomContainer) // but, still recurse (if possible) if (leftBondCount > 0) { - Debug.WriteLine("Recursing with saturated bond with #bonds: " + leftBondCount); - bondsAreFullySaturated = NewSaturate(leftBonds, atomContainer) - && !IsUnsaturated(bond, atomContainer); + Debug.WriteLine($"Recursing with saturated bond with #bonds: {leftBondCount}"); + bondsAreFullySaturated = NewSaturate(leftBonds, atomContainer) && !IsUnsaturated(bond, atomContainer); } else { @@ -420,22 +421,22 @@ public bool NewSaturate(IBond[] bonds, IAtomContainer atomContainer) } } } - Debug.WriteLine("Is bond set fully saturated?: " + bondsAreFullySaturated); - Debug.WriteLine("Returning to level: " + (bonds.Length + 1)); + Debug.WriteLine($"Is bond set fully saturated?: {bondsAreFullySaturated}"); + Debug.WriteLine($"Returning to level: {(bonds.Length + 1)}"); return bondsAreFullySaturated; } /// /// Saturate atom by adjusting its bond orders. - /// This method is known to fail, especially on pyrolle-like compounds. + /// This method is known to fail, especially on pyrrole-like compounds. /// Consider using import org.openscience.cdk.smiles.DeduceBondSystemTool, which should work better /// public bool NewSaturate(IBond bond, IAtomContainer atomContainer) { - IAtom[] atoms = BondManipulator.GetAtomArray(bond); - IAtom atom = atoms[0]; - IAtom partner = atoms[1]; - Debug.WriteLine(" saturating bond: ", atom.Symbol, "-", partner.Symbol); + var atoms = BondManipulator.GetAtomArray(bond); + var atom = atoms[0]; + var partner = atoms[1]; + Debug.WriteLine($" saturating bond: {atom.Symbol}-{partner.Symbol}"); var atomTypes1 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(atom.Symbol); var atomTypes2 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(partner.Symbol); bool bondOrderIncreased = true; @@ -446,19 +447,19 @@ public bool NewSaturate(IBond bond, IAtomContainer atomContainer) foreach (var aType1 in atomTypes1) { if (bondOrderIncreased) break; - Debug.WriteLine(" condidering atom type: ", aType1); + Debug.WriteLine($" considering atom type: {aType1}"); if (CouldMatchAtomType(atomContainer, atom, aType1)) { - Debug.WriteLine(" trying atom type: ", aType1); + Debug.WriteLine($" trying atom type: {aType1}"); foreach (var aType2 in atomTypes2) { if (bondOrderIncreased) break; - Debug.WriteLine(" condidering partner type: ", aType1); + Debug.WriteLine($" considering partner type: {aType1}"); if (CouldMatchAtomType(atomContainer, partner, aType2)) { - Debug.WriteLine(" with atom type: ", aType2); + Debug.WriteLine($" with atom type: {aType2}"); if (!BondManipulator.IsLowerOrder(bond.Order, aType2.MaxBondOrder) - || !BondManipulator.IsLowerOrder(bond.Order, aType1.MaxBondOrder)) + || !BondManipulator.IsLowerOrder(bond.Order, aType1.MaxBondOrder)) { Debug.WriteLine("Bond order not increased: atoms has reached (or exceeded) maximum bond order for this atom type"); } @@ -466,7 +467,7 @@ public bool NewSaturate(IBond bond, IAtomContainer atomContainer) && BondManipulator.IsLowerOrder(bond.Order, aType1.MaxBondOrder)) { BondManipulator.IncreaseBondOrder(bond); - Debug.WriteLine("Bond order now " + bond.Order); + Debug.WriteLine($"Bond order now {bond.Order}"); bondOrderIncreased = true; } } @@ -478,11 +479,11 @@ public bool NewSaturate(IBond bond, IAtomContainer atomContainer) } /// - /// Determines if the atom can be of type AtomType. + /// Determines if the atom can be of atom type. /// - public bool CouldMatchAtomType(IAtomContainer atomContainer, IAtom atom, IAtomType atomType) + private static bool CouldMatchAtomType(IAtomContainer atomContainer, IAtom atom, IAtomType atomType) { - Debug.WriteLine(" ... matching atom ", atom.Symbol, " vs ", atomType); + Debug.WriteLine($" ... matching atom {atom.Symbol} vs {atomType}"); if (atomContainer.GetBondOrderSum(atom) + atom.ImplicitHydrogenCount < atomType.BondOrderSum) { Debug.WriteLine(" Match!"); @@ -495,7 +496,7 @@ public bool CouldMatchAtomType(IAtomContainer atomContainer, IAtom atom, IAtomTy /// /// The method is known to fail for certain compounds. For more information, see /// cdk.test.limitations package. - /// This method is known to fail, especially on pyrolle-like compounds. + /// This method is known to fail, especially on pyrrole-like compounds. /// Consider using import org.openscience.cdk.smiles.DeduceBondSystemTool, which should work better /// public void Saturate(IAtomContainer atomContainer) @@ -506,49 +507,43 @@ public void Saturate(IAtomContainer atomContainer) for (int f = 0; f < atomContainer.Atoms.Count; f++) { var atom = atomContainer.Atoms[f]; - Debug.WriteLine("symbol: ", atom.Symbol); + Debug.WriteLine($"symbol: {atom.Symbol}"); var atomTypes1 = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); var atomType1 = atomTypes1.FirstOrDefault(); if (atomType1 != null) { - Debug.WriteLine("first atom type: ", atomType1); + Debug.WriteLine($"first atom type: {atomType1}"); if (atomContainer.GetConnectedBonds(atom).Count() == i) { - int? hcount = atom.ImplicitHydrogenCount == null ? 0 : atom - .ImplicitHydrogenCount; - if (atom.IsAromatic - && atomContainer.GetBondOrderSum(atom) < atomType1.BondOrderSum - hcount) + var hcount = atom.ImplicitHydrogenCount ?? 0; + if (atom.IsAromatic + && atomContainer.GetBondOrderSum(atom) < atomType1.BondOrderSum - hcount) { var partners = atomContainer.GetConnectedAtoms(atom); foreach (var partner in partners) { - Debug.WriteLine("Atom has " + partners.Count() + " partners"); + Debug.WriteLine($"Atom has {partners.Count()} partners"); var atomType2 = GetAtomTypeFactory(atom.Builder).GetAtomTypes(partner.Symbol).FirstOrDefault(); - if (atomType2 == null) return; + if (atomType2 == null) + return; - hcount = partner.ImplicitHydrogenCount == null ? 0 : partner - .ImplicitHydrogenCount; + hcount = partner.ImplicitHydrogenCount ?? 0; if (atomContainer.GetBond(partner, atom).IsAromatic - && atomContainer.GetBondOrderSum(partner) < atomType2.BondOrderSum - - hcount) + && atomContainer.GetBondOrderSum(partner) < atomType2.BondOrderSum - hcount) { - Debug.WriteLine("Partner has " + atomContainer.GetBondOrderSum(partner) - + ", may have: " + atomType2.BondOrderSum); + Debug.WriteLine($"Partner has {atomContainer.GetBondOrderSum(partner)}, may have: {atomType2.BondOrderSum}"); var bond = atomContainer.GetBond(atom, partner); - Debug.WriteLine("Bond order was " + bond.Order); + Debug.WriteLine($"Bond order was {bond.Order}"); BondManipulator.IncreaseBondOrder(bond); - Debug.WriteLine("Bond order now " + bond.Order); + Debug.WriteLine($"Bond order now {bond.Order}"); break; } } } - double? bondOrderSum = atomType1.BondOrderSum == null ? 0.0 - : atomType1.BondOrderSum; - int? hydrogenCount = atom.ImplicitHydrogenCount == null ? 0 : atom - .ImplicitHydrogenCount; - double? atomContainerBondOrderSum = atomContainer.GetBondOrderSum(atom); - if (atomContainerBondOrderSum == null) atomContainerBondOrderSum = 0.0; + var bondOrderSum = atomType1.BondOrderSum ?? 0; + var hydrogenCount = atom.ImplicitHydrogenCount ?? 0; + var atomContainerBondOrderSum = atomContainer.GetBondOrderSum(atom); if (atomContainerBondOrderSum < bondOrderSum - hydrogenCount) { @@ -558,22 +553,20 @@ public void Saturate(IAtomContainer atomContainer) { Debug.WriteLine("Atom has " + partners.Count() + " partners"); var atomType2 = GetAtomTypeFactory(atom.Builder).GetAtomTypes(partner.Symbol).FirstOrDefault(); - if (atomType2 == null) return; + if (atomType2 == null) + return; - double? bos2 = atomType2.BondOrderSum; - int? hc2 = partner.ImplicitHydrogenCount; - double? acbos2 = atomContainer.GetBondOrderSum(partner); - if (bos2 == null) bos2 = 0.0; - if (hc2 == null) hc2 = 0; - if (acbos2 == null) acbos2 = 0.0; + var bos2 = atomType2.BondOrderSum ?? 0; + var hc2 = partner.ImplicitHydrogenCount ?? 0; + var acbos2 = atomContainer.GetBondOrderSum(partner); if (acbos2 < bos2 - hc2) { - Debug.WriteLine("Partner has " + acbos2 + ", may have: " + bos2); + Debug.WriteLine($"Partner has {acbos2}, may have: {bos2}"); var bond = atomContainer.GetBond(atom, partner); - Debug.WriteLine("Bond order was " + bond.Order); + Debug.WriteLine($"Bond order was {bond.Order}"); BondManipulator.IncreaseBondOrder(bond); - Debug.WriteLine("Bond order now " + bond.Order); + Debug.WriteLine($"Bond order now {bond.Order}"); break; } } @@ -586,23 +579,20 @@ public void Saturate(IAtomContainer atomContainer) public void SaturateRingSystems(IAtomContainer atomContainer) { - IRingSet rs0 = Cycles.FindSSSR(atomContainer.Builder.NewAtomContainer(atomContainer)) - .ToRingSet(); + var rs0 = Cycles.FindSSSR(atomContainer.Builder.NewAtomContainer(atomContainer)).ToRingSet(); var ringSets = RingPartitioner.PartitionRings(rs0); IAtom atom = null; - int[] temp; foreach (var rs in ringSets) { var containers = RingSetManipulator.GetAllAtomContainers(rs); foreach (var ac in containers) { - temp = new int[ac.Atoms.Count]; + var temp = new int[ac.Atoms.Count]; for (int g = 0; g < ac.Atoms.Count; g++) { atom = ac.Atoms[g]; temp[g] = atom.ImplicitHydrogenCount.Value; - atom.ImplicitHydrogenCount = (atomContainer.GetConnectedBonds(atom).Count() - - ac.GetConnectedBonds(atom).Count() - temp[g]); + atom.ImplicitHydrogenCount = (atomContainer.GetConnectedBonds(atom).Count() - ac.GetConnectedBonds(atom).Count() - temp[g]); } Saturate(ac); for (int g = 0; g < ac.Atoms.Count; g++) @@ -617,13 +607,9 @@ public void SaturateRingSystems(IAtomContainer atomContainer) /// /// Calculate the number of missing hydrogens by subtracting the number of /// bonds for the atom from the expected number of bonds. Charges are included - /// in the calculation. The number of expected bonds is defined by the AtomType - /// generated with the AtomTypeFactory. + /// in the calculation. The number of expected bonds is defined by the atom type + /// generated with the atom type factory. /// - /// Description of the Parameter - /// Description of the Parameter - /// Description of the Return Value - /// public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer container) { return this.CalculateNumberOfImplicitHydrogens(atom, container, false); @@ -631,12 +617,11 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer contain public int CalculateNumberOfImplicitHydrogens(IAtom atom) { - List bonds = new List(); + var bonds = new List(); return this.CalculateNumberOfImplicitHydrogens(atom, 0, 0, bonds, false); } - public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer container, - bool throwExceptionForUnknowAtom) + public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer container, bool throwExceptionForUnknowAtom) { return this.CalculateNumberOfImplicitHydrogens(atom, container.GetBondOrderSum(atom), container.GetConnectedSingleElectrons(atom).Count(), container.GetConnectedBonds(atom), @@ -649,22 +634,16 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer contain /// in the calculation. The number of expected bonds is defined by the AtomType /// generated with the AtomTypeFactory. /// - /// Description of the Parameter - /// - /// - /// /// Should an exception be thrown if an unknown atomtype is found or 0 returned ? - /// Description of the Return Value /// - public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, double singleElectronSum, - IEnumerable connectedBonds, bool throwExceptionForUnknowAtom) + public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, double singleElectronSum, IEnumerable connectedBonds, bool throwExceptionForUnknowAtom) { int missingHydrogen = 0; if (atom is IPseudoAtom) { // don't figure it out... it simply does not lack H's } - else if (atom.AtomicNumber != null && atom.AtomicNumber == 1 || atom.Symbol.Equals("H")) + else if (atom.AtomicNumber != null && atom.AtomicNumber == 1 || atom.Symbol.Equals("H", StringComparison.Ordinal)) { missingHydrogen = (int)(1 - bondOrderSum - singleElectronSum - atom.FormalCharge); } @@ -673,17 +652,13 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, d Trace.TraceInformation("Calculating number of missing hydrogen atoms"); // get default atom var defaultAtom = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol).FirstOrDefault(); - if (defaultAtom == null && throwExceptionForUnknowAtom) return 0; + if (defaultAtom == null && throwExceptionForUnknowAtom) + return 0; if (defaultAtom != null) { - Debug.WriteLine("DefAtom: ", defaultAtom); - - int? formalCharge = atom.FormalCharge; - if (formalCharge == null) formalCharge = 0; - - double? tmpBondOrderSum = defaultAtom.BondOrderSum; - if (tmpBondOrderSum == null) tmpBondOrderSum = 0.0; - + Debug.WriteLine($"DefAtom: {defaultAtom}"); + var formalCharge = atom.FormalCharge ?? 0; + var tmpBondOrderSum = defaultAtom.BondOrderSum ?? 0; missingHydrogen = (int)(tmpBondOrderSum - bondOrderSum - singleElectronSum + formalCharge); if (atom.IsAromatic) @@ -694,16 +669,17 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, d if (conBond.Order == BondOrder.Double || conBond.IsAromatic) subtractOne = false; } - if (subtractOne) missingHydrogen--; + if (subtractOne) + missingHydrogen--; } - Debug.WriteLine("Atom: ", atom.Symbol); - Debug.WriteLine(" max bond order: " + tmpBondOrderSum); - Debug.WriteLine(" bond order sum: " + bondOrderSum); - Debug.WriteLine(" charge : " + formalCharge); + Debug.WriteLine($"Atom: {atom.Symbol}"); + Debug.WriteLine($" max bond order: {tmpBondOrderSum}"); + Debug.WriteLine($" bond order sum: {bondOrderSum}"); + Debug.WriteLine($" charge : {formalCharge}"); } else { - Trace.TraceWarning("Could not find atom type for ", atom.Symbol); + Trace.TraceWarning($"Could not find atom type for {atom.Symbol}"); } } return missingHydrogen; diff --git a/NCDK/Tools/SmilesValencyChecker.cs b/NCDK/Tools/SmilesValencyChecker.cs index 551a3ff1..114c81ea 100644 --- a/NCDK/Tools/SmilesValencyChecker.cs +++ b/NCDK/Tools/SmilesValencyChecker.cs @@ -24,13 +24,14 @@ using NCDK.Config; using NCDK.Tools.Manipulator; using System; +using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NCDK.Tools { /// - /// Small customization of ValencyHybridChecker suggested by Todd Martin + /// Small customization of suggested by Todd Martin /// specially tuned for SMILES parsing. /// // @author Egon Willighagen @@ -40,17 +41,18 @@ namespace NCDK.Tools // @cdk.githash public class SmilesValencyChecker : IValencyChecker, IDeduceBondOrderTool { - private string atomTypeList = null; - protected AtomTypeFactory structgenATF; + private readonly string atomTypeList = null; + private AtomTypeFactory structgenATF; public SmilesValencyChecker() : this("NCDK.Dict.Data.cdk-atom-types.owl") - { } + { + } public SmilesValencyChecker(string atomTypeList) { this.atomTypeList = atomTypeList; - Trace.TraceInformation("Using configuration file: ", atomTypeList); + Trace.TraceInformation($"Using configuration file: {atomTypeList}"); } /// @@ -61,14 +63,14 @@ public SmilesValencyChecker(string atomTypeList) public void Saturate(IAtomContainer atomContainer) { Trace.TraceInformation("Saturating atomContainer by adjusting bond orders..."); - bool allSaturated = AllSaturated(atomContainer); + var allSaturated = AllSaturated(atomContainer); if (!allSaturated) { Trace.TraceInformation("Saturating bond orders is needed..."); - IBond[] bonds = new IBond[atomContainer.Bonds.Count]; + var bonds = new IBond[atomContainer.Bonds.Count]; for (int i = 0; i < bonds.Length; i++) bonds[i] = atomContainer.Bonds[i]; - bool succeeded = Saturate(bonds, atomContainer); + var succeeded = Saturate(bonds, atomContainer); if (!succeeded) { throw new CDKException("Could not saturate this atomContainer!"); @@ -79,21 +81,21 @@ public void Saturate(IAtomContainer atomContainer) /// /// Saturates a set of Bonds in an AtomContainer. /// - public bool Saturate(IBond[] bonds, IAtomContainer atomContainer) + public bool Saturate(IEnumerable bonds, IAtomContainer atomContainer) { - Debug.WriteLine("Saturating bond set of size: ", bonds.Length); - bool bondsAreFullySaturated = false; - if (bonds.Length > 0) + var _bonds = bonds.ToList(); + Debug.WriteLine($"Saturating bond set of size: {_bonds.Count}"); + var bondsAreFullySaturated = false; + if (_bonds.Count > 0) { - IBond bond = bonds[0]; + var bond = _bonds[0]; // determine bonds left - int leftBondCount = bonds.Length - 1; - IBond[] leftBonds = new IBond[leftBondCount]; - Array.Copy(bonds, 1, leftBonds, 0, leftBondCount); + var leftBondCount = _bonds.Count - 1; + var leftBonds = _bonds.ToList(); // examine this bond - Debug.WriteLine("Examining this bond: ", bond); + Debug.WriteLine($"Examining this bond: {bond}"); if (IsSaturated(bond, atomContainer)) { Debug.WriteLine("OK, bond is saturated, now try to saturate remaining bonds (if needed)"); @@ -107,8 +109,8 @@ public bool Saturate(IBond[] bonds, IAtomContainer atomContainer) // 2. saturate this one by saturating the rest Debug.WriteLine("Option 1: Saturating this bond directly, then trying to saturate rest"); // considering organic bonds, the max order is 3, so increase twice - bool bondOrderIncreased = SaturateByIncreasingBondOrder(bond, atomContainer); - bondsAreFullySaturated = bondOrderIncreased && Saturate(bonds, atomContainer); + var bondOrderIncreased = SaturateByIncreasingBondOrder(bond, atomContainer); + bondsAreFullySaturated = bondOrderIncreased && Saturate(_bonds, atomContainer); if (bondsAreFullySaturated) { Debug.WriteLine("Option 1: worked"); @@ -116,11 +118,13 @@ public bool Saturate(IBond[] bonds, IAtomContainer atomContainer) else { Debug.WriteLine("Option 1: failed. Trying option 2."); - Debug.WriteLine("Option 2: Saturing this bond by saturating the rest"); + Debug.WriteLine("Option 2: Saturating this bond by saturating the rest"); // revert the increase (if succeeded), then saturate the rest - if (bondOrderIncreased) UnsaturateByDecreasingBondOrder(bond); + if (bondOrderIncreased) + UnsaturateByDecreasingBondOrder(bond); bondsAreFullySaturated = Saturate(leftBonds, atomContainer) && IsSaturated(bond, atomContainer); - if (!bondsAreFullySaturated) Debug.WriteLine("Option 2: failed"); + if (!bondsAreFullySaturated) + Debug.WriteLine("Option 2: failed"); } } else @@ -137,7 +141,7 @@ public bool Saturate(IBond[] bonds, IAtomContainer atomContainer) return bondsAreFullySaturated; } - public bool UnsaturateByDecreasingBondOrder(IBond bond) + private static bool UnsaturateByDecreasingBondOrder(IBond bond) { if (bond.Order != BondOrder.Single) { @@ -156,14 +160,14 @@ public bool UnsaturateByDecreasingBondOrder(IBond bond) /// public bool IsUnsaturated(IBond bond, IAtomContainer atomContainer) { - Debug.WriteLine("isBondUnsaturated?: ", bond); - IAtom[] atoms = BondManipulator.GetAtomArray(bond); - bool isUnsaturated = true; + Debug.WriteLine($"isBondUnsaturated?: {bond}"); + var atoms = BondManipulator.GetAtomArray(bond); + var isUnsaturated = true; for (int i = 0; i < atoms.Length && isUnsaturated; i++) { isUnsaturated = isUnsaturated && !IsSaturated(atoms[i], atomContainer); } - Debug.WriteLine("Bond is unsaturated?: ", isUnsaturated); + Debug.WriteLine($"Bond is unsaturated?: {isUnsaturated}"); return isUnsaturated; } @@ -173,29 +177,29 @@ public bool IsUnsaturated(IBond bond, IAtomContainer atomContainer) /// true if the bond could be increased public bool SaturateByIncreasingBondOrder(IBond bond, IAtomContainer atomContainer) { - IAtom[] atoms = BondManipulator.GetAtomArray(bond); - IAtom atom = atoms[0]; - IAtom partner = atoms[1]; + var atoms = BondManipulator.GetAtomArray(bond); + var atom = atoms[0]; + var partner = atoms[1]; Debug.WriteLine(" saturating bond: ", atom.Symbol, "-", partner.Symbol); var atomTypes1 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(atom.Symbol); var atomTypes2 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(partner.Symbol); foreach (var aType1 in atomTypes1) { - Debug.WriteLine(" condidering atom type: ", aType1); + Debug.WriteLine($" considering atom type: {aType1}"); if (CouldMatchAtomType(atomContainer, atom, aType1)) { - Debug.WriteLine(" trying atom type: ", aType1); + Debug.WriteLine($" trying atom type: {aType1}"); foreach (var aType2 in atomTypes2) { - Debug.WriteLine(" condidering partner type: ", aType1); + Debug.WriteLine($" considering partner type: {aType1}"); if (CouldMatchAtomType(atomContainer, partner, aType2)) { - Debug.WriteLine(" with atom type: ", aType2); + Debug.WriteLine($" with atom type: {aType2}"); if (BondManipulator.IsLowerOrder(bond.Order, aType2.MaxBondOrder) && BondManipulator.IsLowerOrder(bond.Order, aType1.MaxBondOrder)) { bond.Order = BondManipulator.IncreaseBondOrder(bond.Order); - Debug.WriteLine("Bond order now ", bond.Order); + Debug.WriteLine($"Bond order now {bond.Order}"); return true; } } @@ -211,15 +215,15 @@ public bool SaturateByIncreasingBondOrder(IBond bond, IAtomContainer atomContain /// public bool IsSaturated(IBond bond, IAtomContainer atomContainer) { - Debug.WriteLine("isBondSaturated?: ", bond); - IAtom[] atoms = BondManipulator.GetAtomArray(bond); + Debug.WriteLine($"isBondSaturated?: {bond}"); + var atoms = BondManipulator.GetAtomArray(bond); bool isSaturated = true; for (int i = 0; i < atoms.Length; i++) { - Debug.WriteLine("IsSaturated(Bond, AC): atom I=", i); + Debug.WriteLine($"IsSaturated(Bond, AC): atom I={i}"); isSaturated = isSaturated && IsSaturated(atoms[i], atomContainer); } - Debug.WriteLine("IsSaturated(Bond, AC): result=", isSaturated); + Debug.WriteLine($"IsSaturated(Bond, AC): result={isSaturated}"); return isSaturated; } @@ -231,6 +235,11 @@ public bool IsSaturated(IAtomContainer container) return AllSaturated(container); } + /// + /// Check all atoms are saturated. + /// + /// to check. + /// if all atoms are saturated. public bool AllSaturated(IAtomContainer ac) { Debug.WriteLine("Are all atoms saturated?"); @@ -245,50 +254,45 @@ public bool AllSaturated(IAtomContainer ac) } /// - /// Determines if the atom can be of type AtomType. That is, it sees if this - /// AtomType only differs in bond orders, or implicit hydrogen count. + /// Determines if the atom can be of atom type. That is, it sees if this + /// atom type only differs in bond orders, or implicit hydrogen count. /// - public bool CouldMatchAtomType(IAtom atom, double bondOrderSum, BondOrder maxBondOrder, IAtomType type) + private static bool CouldMatchAtomType(IAtom atom, double bondOrderSum, BondOrder maxBondOrder, IAtomType type) { - Debug.WriteLine("couldMatchAtomType: ... matching atom ", atom, " vs ", type); - int hcount = atom.ImplicitHydrogenCount.Value; - int charge = atom.FormalCharge.Value; + Debug.WriteLine($"{nameof(CouldMatchAtomType)}: ... matching atom {atom} vs {type}"); + var hcount = atom.ImplicitHydrogenCount.Value; + var charge = atom.FormalCharge.Value; if (charge == type.FormalCharge) { - Debug.WriteLine("couldMatchAtomType: formal charge matches..."); - // if (atom.Hybridization == type.Hybridization) { - // Debug.WriteLine("couldMatchAtomType: hybridization is OK..."); + Debug.WriteLine($"{nameof(CouldMatchAtomType)}e: formal charge matches..."); if (bondOrderSum + hcount <= type.BondOrderSum) { - Debug.WriteLine("couldMatchAtomType: bond order sum is OK..."); + Debug.WriteLine($"{nameof(CouldMatchAtomType)}: bond order sum is OK..."); if (!BondManipulator.IsHigherOrder(maxBondOrder, type.MaxBondOrder)) { - Debug.WriteLine("couldMatchAtomType: max bond order is OK... We have a match!"); + Debug.WriteLine($"{nameof(CouldMatchAtomType)}: max bond order is OK... We have a match!"); return true; } } else { - Debug.WriteLine("couldMatchAtomType: no match", "" + (bondOrderSum + hcount), " > ", - "" + type.BondOrderSum); + Debug.WriteLine($"{nameof(CouldMatchAtomType)}: no match {(bondOrderSum + hcount)} > {type.BondOrderSum}"); } - // } } else { - Debug.WriteLine("couldMatchAtomType: formal charge does NOT match..."); + Debug.WriteLine($"{nameof(CouldMatchAtomType)}: formal charge does NOT match..."); } - Debug.WriteLine("couldMatchAtomType: No Match"); + Debug.WriteLine($"{nameof(CouldMatchAtomType)}e: No Match"); return false; } /// - /// Calculates the number of hydrogens that can be added to the given atom to fullfil + /// Calculates the number of hydrogens that can be added to the given atom to fulfil /// the atom's valency. It will return 0 for PseudoAtoms, and for atoms for which it /// does not have an entry in the configuration file. /// - public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, BondOrder maxBondOrder, - int neighbourCount) + public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, BondOrder maxBondOrder, int neighbourCount) { int missingHydrogens = 0; if (atom is IPseudoAtom) @@ -304,7 +308,7 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, B { if (CouldMatchAtomType(atom, bondOrderSum, maxBondOrder, type)) { - Debug.WriteLine("This type matches: ", type); + Debug.WriteLine($"This type matches: {type}"); int formalNeighbourCount = type.FormalNeighbourCount.Value; switch (type.Hybridization) { @@ -328,14 +332,14 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, B } } - Debug.WriteLine("missing hydrogens: ", missingHydrogens); + Debug.WriteLine($"missing hydrogens: {missingHydrogens}"); return missingHydrogens; } /// - /// Checks whether an Atom is saturated by comparing it with known AtomTypes. - /// It returns true if the atom is an PseudoAtom and when the element is not in the list. + /// Checks whether an atom is saturated by comparing it with known atom types. /// + /// if the atom is an pseudo atom and when the element is not in the list. public bool IsSaturated(IAtom atom, IAtomContainer container) { if (atom is IPseudoAtom) @@ -350,16 +354,16 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) Trace.TraceWarning("Missing entry in atom type list for ", atom.Symbol); return true; } - double bondOrderSum = container.GetBondOrderSum(atom); - BondOrder maxBondOrder = container.GetMaximumBondOrder(atom); - int hcount = atom.ImplicitHydrogenCount.Value; - int charge = atom.FormalCharge.Value; + var bondOrderSum = container.GetBondOrderSum(atom); + var maxBondOrder = container.GetMaximumBondOrder(atom); + var hcount = atom.ImplicitHydrogenCount.Value; + var charge = atom.FormalCharge.Value; - Debug.WriteLine("Checking saturation of atom ", atom.Symbol); - Debug.WriteLine("bondOrderSum: ", bondOrderSum); - Debug.WriteLine("maxBondOrder: ", maxBondOrder); - Debug.WriteLine("hcount: ", hcount); - Debug.WriteLine("charge: ", charge); + Debug.WriteLine($"Checking saturation of atom {atom.Symbol}"); + Debug.WriteLine($"bondOrderSum: {bondOrderSum}"); + Debug.WriteLine($"maxBondOrder: {maxBondOrder}"); + Debug.WriteLine($"hcount: {hcount}"); + Debug.WriteLine($"charge: {charge}"); bool elementPlusChargeMatches = false; foreach (var type in atomTypes) @@ -369,8 +373,8 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) if (bondOrderSum + hcount == type.BondOrderSum && !BondManipulator.IsHigherOrder(maxBondOrder, type.MaxBondOrder)) { - Debug.WriteLine("We have a match: ", type); - Debug.WriteLine("Atom is saturated: ", atom.Symbol); + Debug.WriteLine($"We have a match: {type}"); + Debug.WriteLine($"Atom is saturated: {atom.Symbol}"); return true; } else @@ -394,8 +398,7 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer container) { - return this.CalculateNumberOfImplicitHydrogens(atom, container.GetBondOrderSum(atom), - container.GetMaximumBondOrder(atom), container.GetConnectedBonds(atom).Count()); + return this.CalculateNumberOfImplicitHydrogens(atom, container.GetBondOrderSum(atom), container.GetMaximumBondOrder(atom), container.GetConnectedBonds(atom).Count()); } protected AtomTypeFactory GetAtomTypeFactory(IChemObjectBuilder builder) @@ -416,12 +419,13 @@ protected AtomTypeFactory GetAtomTypeFactory(IChemObjectBuilder builder) } /// - /// Determines if the atom can be of type AtomType. + /// Determines if the atom can be of type . That is, it sees if this + /// only differs in bond orders, or implicit hydrogen count. /// - public bool CouldMatchAtomType(IAtomContainer container, IAtom atom, IAtomType type) + private static bool CouldMatchAtomType(IAtomContainer container, IAtom atom, IAtomType type) { - double bondOrderSum = container.GetBondOrderSum(atom); - BondOrder maxBondOrder = container.GetMaximumBondOrder(atom); + var bondOrderSum = container.GetBondOrderSum(atom); + var maxBondOrder = container.GetMaximumBondOrder(atom); return CouldMatchAtomType(atom, bondOrderSum, maxBondOrder, type); } } diff --git a/NCDK/Tools/StructureResonanceGenerator.cs b/NCDK/Tools/StructureResonanceGenerator.cs index 876ba41f..a8c5eae2 100644 --- a/NCDK/Tools/StructureResonanceGenerator.cs +++ b/NCDK/Tools/StructureResonanceGenerator.cs @@ -58,7 +58,7 @@ namespace NCDK.Tools public class StructureResonanceGenerator { /// Generate resonance structure without looking at the symmetry - private bool lookingSymmetry; + private readonly bool lookingSymmetry; /// /// Construct an instance of StructureResonanceGenerator. Default restrictions @@ -84,10 +84,10 @@ public StructureResonanceGenerator(bool lookingSymmetry) } /// - /// The reactions that must be used in the generation of the resonance. + /// The reactions that must be used in the generation of the resonance. /// /// - public IList Reactions { get; set; } = new List(); + public IReadOnlyList Reactions { get; set; } /// /// The number maximal of resonance structures to be found. The @@ -106,11 +106,10 @@ public void SetDefaultReactions() private void CallDefaultReactions() { - List paramList = new List(); - IParameterReaction param = new SetReactionCenter - { - IsSetParameter = false - }; + var reactions = new List(); + + var paramList = new List(); + var param = new SetReactionCenter { IsSetParameter = false }; paramList.Add(param); IReactionProcess type = new SharingLonePairReaction(); @@ -122,14 +121,11 @@ private void CallDefaultReactions() { Console.Error.WriteLine(e.StackTrace); } - Reactions.Add(type); + reactions.Add(type); type = new PiBondingMovementReaction(); - List paramList2 = new List(); - IParameterReaction param2 = new SetReactionCenter - { - IsSetParameter = false - }; + var paramList2 = new List(); + var param2 = new SetReactionCenter { IsSetParameter = false }; paramList2.Add(param2); try { @@ -139,7 +135,7 @@ private void CallDefaultReactions() { Console.Error.WriteLine(e.StackTrace); } - Reactions.Add(type); + reactions.Add(type); type = new RearrangementAnionReaction(); try @@ -150,7 +146,7 @@ private void CallDefaultReactions() { Console.Error.WriteLine(e.StackTrace); } - Reactions.Add(type); + reactions.Add(type); type = new RearrangementCationReaction(); try @@ -161,7 +157,7 @@ private void CallDefaultReactions() { Console.Error.WriteLine(e.StackTrace); } - Reactions.Add(type); + reactions.Add(type); type = new RearrangementLonePairReaction(); try @@ -172,7 +168,7 @@ private void CallDefaultReactions() { Console.Error.WriteLine(e.StackTrace); } - Reactions.Add(type); + reactions.Add(type); type = new RearrangementRadicalReaction(); try @@ -183,8 +179,9 @@ private void CallDefaultReactions() { Console.Error.WriteLine(e.StackTrace); } - Reactions.Add(type); + reactions.Add(type); + this.Reactions = reactions; } /// @@ -200,20 +197,20 @@ public IChemObjectSet GetStructures(IAtomContainer molecule) for (int i = 0; i < setOfMol.Count; i++) { - IAtomContainer mol = setOfMol[i]; + var mol = setOfMol[i]; foreach (var aReactionsList in Reactions) { - IReactionProcess reaction = aReactionsList; + var reaction = aReactionsList; var setOfReactants = molecule.Builder.NewAtomContainerSet(); setOfReactants.Add(mol); try { - IReactionSet setOfReactions = reaction.Initiate(setOfReactants, null); + var setOfReactions = reaction.Initiate(setOfReactants, null); if (setOfReactions.Count != 0) for (int k = 0; k < setOfReactions.Count; k++) for (int j = 0; j < setOfReactions[k].Products.Count; j++) { - IAtomContainer product = setOfReactions[k].Products[j]; + var product = setOfReactions[k].Products[j]; if (!ExistAC(setOfMol, product)) { setOfMol.Add(product); @@ -245,13 +242,13 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) if (setOfMol.Count == 0) return setOfCont; /* extraction of all bonds which has been produced a changes of order */ - List bondList = new List(); + var bondList = new List(); for (int i = 1; i < setOfMol.Count; i++) { - IAtomContainer mol = setOfMol[i]; + var mol = setOfMol[i]; for (int j = 0; j < mol.Bonds.Count; j++) { - IBond bond = molecule.Bonds[j]; + var bond = molecule.Bonds[j]; if (!mol.Bonds[j].Order.Equals(bond.Order)) { if (!bondList.Contains(bond)) bondList.Add(bond); @@ -259,7 +256,8 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) } } - if (bondList.Count == 0) return null; + if (bondList.Count == 0) + return null; int[] flagBelonging = new int[bondList.Count]; for (int i = 0; i < flagBelonging.Length; i++) @@ -287,26 +285,28 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) } } - IBond bondA = newBondList[i]; + var bondA = newBondList[i]; for (int ato = 0; ato < 2; ato++) { - IAtom atomA1 = bondA.Atoms[ato]; + var atomA1 = bondA.Atoms[ato]; var bondA1s = molecule.GetConnectedBonds(atomA1); foreach (var bondB in bondA1s) { - if (!newBondList.Contains(bondB)) for (int k = 0; k < bondList.Count; k++) - if (bondList[k].Equals(bondB)) if (flagBelonging[k] == 0) + if (!newBondList.Contains(bondB)) + for (int k = 0; k < bondList.Count; k++) + if (bondList[k].Equals(bondB)) + if (flagBelonging[k] == 0) { flagBelonging[k] = maxGroup; pos++; newBondList.Add(bondB); position[pos] = k; - } } } //if it is final size and not all are added - if (newBondList.Count - 1 == i) for (int k = 0; k < bondList.Count; k++) + if (newBondList.Count - 1 == i) + for (int k = 0; k < bondList.Count; k++) if (!newBondList.Contains(bondList[k])) { newBondList.Add(bondList[k]); @@ -317,15 +317,18 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) /* creating containers according groups */ for (int i = 0; i < maxGroup; i++) { - IAtomContainer container = molecule.Builder.NewAtomContainer(); + var container = molecule.Builder.NewAtomContainer(); for (int j = 0; j < bondList.Count; j++) { - if (flagBelonging[j] != i + 1) continue; - IBond bond = bondList[j]; - IAtom atomA1 = bond.Atoms[0]; - IAtom atomA2 = bond.Atoms[1]; - if (!container.Contains(atomA1)) container.Atoms.Add(atomA1); - if (!container.Contains(atomA2)) container.Atoms.Add(atomA2); + if (flagBelonging[j] != i + 1) + continue; + var bond = bondList[j]; + var atomA1 = bond.Atoms[0]; + var atomA2 = bond.Atoms[1]; + if (!container.Contains(atomA1)) + container.Atoms.Add(atomA1); + if (!container.Contains(atomA2)) + container.Atoms.Add(atomA2); container.Bonds.Add(bond); } setOfCont.Add(container); @@ -344,11 +347,13 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) public IAtomContainer GetContainer(IAtomContainer molecule, IAtom atom) { var setOfCont = GetContainers(molecule); - if (setOfCont == null) return null; + if (setOfCont == null) + return null; foreach (var container in setOfCont) { - if (container.Contains(atom)) return container; + if (container.Contains(atom)) + return container; } return null; @@ -365,11 +370,13 @@ public IAtomContainer GetContainer(IAtomContainer molecule, IAtom atom) public IAtomContainer GetContainer(IAtomContainer molecule, IBond bond) { var setOfCont = GetContainers(molecule); - if (setOfCont == null) return null; + if (setOfCont == null) + return null; foreach (var container in setOfCont) { - if (container.Contains(bond)) return container; + if (container.Contains(bond)) + return container; } return null; @@ -394,7 +401,6 @@ private bool ExistAC(IChemObjectSet set, IAtomContainer atomCont } for (int i = 0; i < acClone.Atoms.Count; i++) - // if(acClone.Atoms[i].Id == null) acClone.Atoms[i].Id = "" + acClone.Atoms.IndexOf(acClone.Atoms[i]); if (lookingSymmetry) @@ -420,28 +426,28 @@ private bool ExistAC(IChemObjectSet set, IAtomContainer atomCont } for (int i = 0; i < set.Count; i++) { - IAtomContainer ss = set[i]; + var ss = set[i]; for (int j = 0; j < ss.Atoms.Count; j++) - // if(ss.Atoms[j].Id == null) ss.Atoms[j].Id = "" + ss.Atoms.IndexOf(ss.Atoms[j]); try { if (!lookingSymmetry) { - QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolChargeIDQueryContainer(acClone); + var qAC = QueryAtomContainerCreator.CreateSymbolChargeIDQueryContainer(acClone); if (new UniversalIsomorphismTester().IsIsomorph(ss, qAC)) { - QueryAtomContainer qAC2 = QueryAtomContainerCreator - .CreateSymbolAndBondOrderQueryContainer(acClone); - if (new UniversalIsomorphismTester().IsIsomorph(ss, qAC2)) return true; + var qAC2 = QueryAtomContainerCreator.CreateSymbolAndBondOrderQueryContainer(acClone); + if (new UniversalIsomorphismTester().IsIsomorph(ss, qAC2)) + return true; } } else { - QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(acClone); + var qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(acClone); Aromaticity.CDKLegacy.Apply(ss); - if (new UniversalIsomorphismTester().IsIsomorph(ss, qAC)) return true; + if (new UniversalIsomorphismTester().IsIsomorph(ss, qAC)) + return true; } } catch (CDKException e1) diff --git a/NCDK/UnsupportedChemObjectException.cs b/NCDK/UnsupportedChemObjectException.cs index 7b90c36a..a0e55f2c 100644 --- a/NCDK/UnsupportedChemObjectException.cs +++ b/NCDK/UnsupportedChemObjectException.cs @@ -27,8 +27,17 @@ namespace NCDK // @cdk.githash public class UnsupportedChemObjectException : CDKException { + public UnsupportedChemObjectException() + { + } + public UnsupportedChemObjectException(string message) : base(message) - { } + { + } + + public UnsupportedChemObjectException(string message, System.Exception innerException) : base(message, innerException) + { + } } } diff --git a/NCDK/Validate/BasicValidator.cs b/NCDK/Validate/BasicValidator.cs index 60112371..77927c5d 100644 --- a/NCDK/Validate/BasicValidator.cs +++ b/NCDK/Validate/BasicValidator.cs @@ -118,69 +118,72 @@ public override ValidationReport ValidateReaction(IReaction subject) // the Atom tests - private ValidationReport ValidateCharge(IAtom atom) + private static ValidationReport ValidateCharge(IAtom atom) { ValidationReport report = new ValidationReport(); ValidationTest tooCharged = new ValidationTest(atom, "Atom has an unlikely large positive or negative charge"); - if (atom.Symbol.Equals("O") || atom.Symbol.Equals("N") || atom.Symbol.Equals("C") - || atom.Symbol.Equals("H")) + switch (atom.Symbol) { - if (atom.FormalCharge == 0) - { - report.OKs.Add(tooCharged); - } - else - { - tooCharged.Details = $"Atom {atom.Symbol} has charge {atom.FormalCharge}"; - if (atom.FormalCharge < -3) - { - report.Errors.Add(tooCharged); - } - else if (atom.FormalCharge < -1) - { - report.Warnings.Add(tooCharged); - } - else if (atom.FormalCharge > 3) - { - report.Errors.Add(tooCharged); - } - else if (atom.FormalCharge > 1) - { - report.Warnings.Add(tooCharged); - } - } - } - else - { - if (atom.FormalCharge == 0) - { - report.OKs.Add(tooCharged); - } - else - { - tooCharged.Details = $"Atom {atom.Symbol} has charge {atom.FormalCharge}"; - if (atom.FormalCharge < -4) + case "O": + case "N": + case "C": + case "H": + if (atom.FormalCharge == 0) { - report.Errors.Add(tooCharged); + report.OKs.Add(tooCharged); } - else if (atom.FormalCharge < -3) + else { - report.Warnings.Add(tooCharged); + tooCharged.Details = $"Atom {atom.Symbol} has charge {atom.FormalCharge}"; + if (atom.FormalCharge < -3) + { + report.Errors.Add(tooCharged); + } + else if (atom.FormalCharge < -1) + { + report.Warnings.Add(tooCharged); + } + else if (atom.FormalCharge > 3) + { + report.Errors.Add(tooCharged); + } + else if (atom.FormalCharge > 1) + { + report.Warnings.Add(tooCharged); + } } - else if (atom.FormalCharge > 4) + break; + default: + if (atom.FormalCharge == 0) { - report.Errors.Add(tooCharged); + report.OKs.Add(tooCharged); } - else if (atom.FormalCharge > 3) + else { - report.Warnings.Add(tooCharged); + tooCharged.Details = $"Atom {atom.Symbol} has charge {atom.FormalCharge}"; + if (atom.FormalCharge < -4) + { + report.Errors.Add(tooCharged); + } + else if (atom.FormalCharge < -3) + { + report.Warnings.Add(tooCharged); + } + else if (atom.FormalCharge > 4) + { + report.Errors.Add(tooCharged); + } + else if (atom.FormalCharge > 3) + { + report.Warnings.Add(tooCharged); + } } - } + break; } return report; } - private ValidationReport ValidateHydrogenCount(IAtom atom) + private static ValidationReport ValidateHydrogenCount(IAtom atom) { ValidationReport report = new ValidationReport(); ValidationTest negativeHydrogenCount = new ValidationTest(atom, @@ -201,7 +204,7 @@ private ValidationReport ValidateHydrogenCount(IAtom atom) return report; } - private ValidationReport ValidatePseudoAtom(IAtom atom) + private static ValidationReport ValidatePseudoAtom(IAtom atom) { ValidationReport report = new ValidationReport(); ValidationTest isElementOrPseudo = new ValidationTest(atom, "Non-element atom must be of class PseudoAtom."); @@ -215,7 +218,7 @@ private ValidationReport ValidatePseudoAtom(IAtom atom) // check whether atom is really an element try { - IsotopeFactory isotopeFactory = Isotopes.Instance; + IsotopeFactory isotopeFactory = BODRIsotopeFactory.Instance; IElement element = isotopeFactory.GetElement(atom.Symbol); if (element == null) { @@ -239,7 +242,7 @@ private ValidationReport ValidatePseudoAtom(IAtom atom) // the Bond tests - private ValidationReport ValidateStereoChemistry(IBond bond) + private static ValidationReport ValidateStereoChemistry(IBond bond) { ValidationReport report = new ValidationReport(); ValidationTest bondStereo = new ValidationTest(bond, "Defining stereochemistry on bonds is not safe.", @@ -255,13 +258,13 @@ private ValidationReport ValidateStereoChemistry(IBond bond) return report; } - private ValidationReport ValidateMaxBondOrder(IBond bond) + private static ValidationReport ValidateMaxBondOrder(IBond bond) { ValidationReport report = new ValidationReport(); ValidationTest maxBO = new ValidationTest(bond, "Bond order exceeds the maximum for one of its atoms."); try { - AtomTypeFactory structgenATF = AtomTypeFactory.GetInstance("NCDK.Dict.cdk-atom-types.owl", bond.Builder); + var structgenATF = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", bond.Builder); for (int i = 0; i < bond.Atoms.Count; i++) { IAtom atom = bond.Atoms[i]; @@ -310,13 +313,13 @@ private ValidationReport ValidateMaxBondOrder(IBond bond) // the Isotope tests - public ValidationReport ValidateIsotopeExistence(IIsotope isotope) + public static ValidationReport ValidateIsotopeExistence(IIsotope isotope) { ValidationReport report = new ValidationReport(); ValidationTest isotopeExists = new ValidationTest(isotope, "Isotope with this mass number is not known for this element."); try { - IsotopeFactory isotopeFac = Isotopes.Instance; + IsotopeFactory isotopeFac = BODRIsotopeFactory.Instance; var isotopes = isotopeFac.GetIsotopes(isotope.Symbol); bool foundKnownIsotope = false; if (isotope.MassNumber != 0) @@ -348,13 +351,13 @@ public ValidationReport ValidateIsotopeExistence(IIsotope isotope) // the Molecule tests - private ValidationReport ValidateBondOrderSum(IAtom atom, IAtomContainer molecule) + private static ValidationReport ValidateBondOrderSum(IAtom atom, IAtomContainer molecule) { ValidationReport report = new ValidationReport(); ValidationTest checkBondSum = new ValidationTest(atom, "The atom's total bond order is too high."); try { - AtomTypeFactory structgenATF = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", atom.Builder); + var structgenATF = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", atom.Builder); int bos = (int)molecule.GetBondOrderSum(atom); var atomTypes = structgenATF.GetAtomTypes(atom.Symbol).ToList(); if (atomTypes.Count == 0) @@ -407,8 +410,7 @@ private ValidationReport ValidateBondOrderSum(IAtom atom, IAtomContainer molecul return report; } - private ValidationReport ValidateAtomCountConservation(IReaction reaction, IAtomContainer reactants, - IAtomContainer products) + private static ValidationReport ValidateAtomCountConservation(IReaction reaction, IAtomContainer reactants, IAtomContainer products) { ValidationReport report = new ValidationReport(); ValidationTest atomCount = new ValidationTest(reaction, "Atom count mismatch for reaction: the product side has a different atom count than the reactant side."); @@ -423,7 +425,7 @@ private ValidationReport ValidateAtomCountConservation(IReaction reaction, IAtom return report; } - private ValidationReport ValidateChargeConservation(IReaction reaction, IAtomContainer reactants, + private static ValidationReport ValidateChargeConservation(IReaction reaction, IAtomContainer reactants, IAtomContainer products) { ValidationReport report = new ValidationReport(); diff --git a/NCDK/Validate/CDKValidator.cs b/NCDK/Validate/CDKValidator.cs index f34d3f07..65c5d8ac 100644 --- a/NCDK/Validate/CDKValidator.cs +++ b/NCDK/Validate/CDKValidator.cs @@ -39,7 +39,7 @@ public override ValidationReport ValidateChemSequence(IChemSequence subject) return ValidateChemSequenceNulls(subject); } - private ValidationReport ValidateChemFileNulls(IChemFile chemFile) + private static ValidationReport ValidateChemFileNulls(IChemFile chemFile) { ValidationReport report = new ValidationReport(); ValidationTest hasNulls = new ValidationTest(chemFile, "ChemFile contains a null ChemSequence."); @@ -58,7 +58,7 @@ private ValidationReport ValidateChemFileNulls(IChemFile chemFile) return report; } - private ValidationReport ValidateChemSequenceNulls(IChemSequence sequence) + private static ValidationReport ValidateChemSequenceNulls(IChemSequence sequence) { ValidationReport report = new ValidationReport(); ValidationTest hasNulls = new ValidationTest(sequence, "ChemSequence contains a null ChemModel."); diff --git a/NCDK/Validate/DictionaryValidator.cs b/NCDK/Validate/DictionaryValidator.cs index d426fdbb..a453f391 100644 --- a/NCDK/Validate/DictionaryValidator.cs +++ b/NCDK/Validate/DictionaryValidator.cs @@ -63,7 +63,7 @@ public override ValidationReport ValidateChemObject(IChemObject subject) { report.OKs.Add(noNamespace); string dict = dictRef.Substring(0, index); - Debug.WriteLine("Looking for dictionary:" + dict); + Debug.WriteLine($"Looking for dictionary:{dict}"); if (db.HasDictionary(dict)) { report.OKs.Add(noDict); diff --git a/NCDK/Validate/IValidator.cs b/NCDK/Validate/IValidator.cs index 97cf05ad..7cf99b87 100644 --- a/NCDK/Validate/IValidator.cs +++ b/NCDK/Validate/IValidator.cs @@ -39,7 +39,7 @@ public interface IValidator ValidationReport ValidateChemModel(IChemModel subject); - ValidationReport ValidateChemObject(IChemObject obj); + ValidationReport ValidateChemObject(IChemObject o); ValidationReport ValidateChemSequence(IChemSequence subject); diff --git a/NCDK/Validate/ProblemMarker.cs b/NCDK/Validate/ProblemMarker.cs index 1093b881..b3bbe56f 100644 --- a/NCDK/Validate/ProblemMarker.cs +++ b/NCDK/Validate/ProblemMarker.cs @@ -34,30 +34,30 @@ public static class ProblemMarker public const string ErrorMarker = "NCDK.Validate.error"; public const string WarningMarker = "NCDK.Validate.warning"; - public static void MarkWithError(IChemObject obj) + public static void MarkWithError(IChemObject o) { - obj.SetProperty(ErrorMarker, true); + o.SetProperty(ErrorMarker, true); } - public static void MarkWithWarning(IChemObject obj) + public static void MarkWithWarning(IChemObject o) { - obj.SetProperty(WarningMarker, true); + o.SetProperty(WarningMarker, true); } - public static void UnMarkWithError(IChemObject obj) + public static void UnmarkWithError(IChemObject o) { - obj.RemoveProperty(ErrorMarker); + o.RemoveProperty(ErrorMarker); } - public static void UnMarkWithWarning(IChemObject obj) + public static void UnmarkWithWarning(IChemObject o) { - obj.RemoveProperty(WarningMarker); + o.RemoveProperty(WarningMarker); } - public static void Unmark(IChemObject obj) + public static void Unmark(IChemObject o) { - UnMarkWithWarning(obj); - UnMarkWithError(obj); + UnmarkWithWarning(o); + UnmarkWithError(o); } } } diff --git a/NCDK/Validate/ValidationTest.cs b/NCDK/Validate/ValidationTest.cs index 23df3e1a..5a9dca79 100644 --- a/NCDK/Validate/ValidationTest.cs +++ b/NCDK/Validate/ValidationTest.cs @@ -32,7 +32,7 @@ public class ValidationTest /// /// IChemObject which has the error. /// - public IChemObject Object { get; private set; } + public IChemObject ChemObject { get; private set; } /// /// string representation of the found error. @@ -44,13 +44,13 @@ public class ValidationTest /// public string Details { get; set; } - public ValidationTest(IChemObject obj, string error) : - this(obj, error, "") + public ValidationTest(IChemObject o, string error) : + this(o, error, "") { } - public ValidationTest(IChemObject obj, string error, string details) + public ValidationTest(IChemObject o, string error, string details) { - Object = obj; + ChemObject = o; Error = error; Details = details; } diff --git a/NCDK/io-formats.set b/NCDK/io-formats.set index b2f63e4e..8db79386 100644 --- a/NCDK/io-formats.set +++ b/NCDK/io-formats.set @@ -9,8 +9,8 @@ NCDK.IO.Formats.CacaoInternalFormat NCDK.IO.Formats.CACheFormat NCDK.IO.Formats.CDKOWLFormat NCDK.IO.Formats.CDKSourceCodeFormat -NCDK.IO.Formats.Chem3D_Cartesian_1Format -NCDK.IO.Formats.Chem3D_Cartesian_2Format +NCDK.IO.Formats.Chem3DCartesian1Format +NCDK.IO.Formats.Chem3DCartesian2Format NCDK.IO.Formats.ChemDrawFormat NCDK.IO.Formats.ChemtoolFormat NCDK.IO.Formats.CIFFormat @@ -23,7 +23,7 @@ NCDK.IO.Formats.CTXFormat NCDK.IO.Formats.DaltonFormat NCDK.IO.Formats.DMol3Format NCDK.IO.Formats.DOCK5Format -NCDK.IO.Formats.FenskeHall_ZMatrixFormat +NCDK.IO.Formats.FenskeHallZMatrixFormat NCDK.IO.Formats.FingerprintFormat NCDK.IO.Formats.GamessFormat NCDK.IO.Formats.Gaussian03Format diff --git a/NCDK/qsar-descriptors.set b/NCDK/qsar-descriptors.set index e74d930b..12b1b106 100644 --- a/NCDK/qsar-descriptors.set +++ b/NCDK/qsar-descriptors.set @@ -20,11 +20,11 @@ NCDK.QSAR.Descriptors.Atomic.PeriodicTablePositionDescriptor NCDK.QSAR.Descriptors.Atomic.PiElectronegativityDescriptor NCDK.QSAR.Descriptors.Atomic.ProtonAffinityHOSEDescriptor NCDK.QSAR.Descriptors.Atomic.ProtonTotalPartialChargeDescriptor -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_G3R -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GDR -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GHR -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GHR_topol -NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptor_GSR +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorG3R +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGDR +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGHR +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGHRTopology +NCDK.QSAR.Descriptors.Atomic.RDFProtonDescriptorGSR NCDK.QSAR.Descriptors.Atomic.SigmaElectronegativityDescriptor NCDK.QSAR.Descriptors.Atomic.StabilizationPlusChargeDescriptor NCDK.QSAR.Descriptors.Atomic.VdWRadiusDescriptor diff --git a/NCDKDisplay/Depict/Abbreviations.cs b/NCDKDisplay/Depict/Abbreviations.cs index 3fab7a91..2778d2b8 100644 --- a/NCDKDisplay/Depict/Abbreviations.cs +++ b/NCDKDisplay/Depict/Abbreviations.cs @@ -54,7 +54,7 @@ namespace NCDK.Depict /// on the resource. /// /// - /// + /// /// // @cdk.keyword abbreviate // @cdk.keyword depict @@ -68,10 +68,10 @@ public class Abbreviations : IEnumerable /// private const string String_Interpunct = "·"; - private readonly IDictionary connectedAbbreviations = new SortedDictionary(); - private readonly IDictionary disconnectedAbbreviations = new SortedDictionary(); - private readonly ISet labels = new LinkedHashSet(); - private readonly ISet disabled = new HashSet(); + private readonly SortedDictionary connectedAbbreviations = new SortedDictionary(); + private readonly SortedDictionary disconnectedAbbreviations = new SortedDictionary(); + private readonly LinkedHashSet labels = new LinkedHashSet(); + private readonly HashSet disabled = new HashSet(); private readonly SmilesGenerator usmigen = SmilesGenerator.Unique(); private readonly SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); @@ -235,8 +235,8 @@ private static List MakeCut(IBond cut, IAtomContainer mol, Dicti private static List GenerateFragments(IAtomContainer mol) { - EdgeToBondMap bmap = EdgeToBondMap.WithSpaceFor(mol); - int[][] adjlist = GraphUtil.ToAdjList(mol, bmap); + var bmap = EdgeToBondMap.WithSpaceFor(mol); + var adjlist = GraphUtil.ToAdjList(mol, bmap); Cycles.MarkRingAtomsAndBonds(mol, adjlist, bmap); @@ -275,7 +275,7 @@ public IList Generate(IAtomContainer mol) // mark which atoms have already been abbreviated or are // part of an existing Sgroup var usedAtoms = new HashSet(); - IList sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); if (sgroups != null) { foreach (var sgroup in sgroups) @@ -288,11 +288,11 @@ public IList Generate(IAtomContainer mol) { try { - IAtomContainer copy = AtomContainerManipulator.CopyAndSuppressedHydrogens(mol); + var copy = AtomContainerManipulator.CopyAndSuppressedHydrogens(mol); string cansmi = usmigen.Create(copy); if (disconnectedAbbreviations.TryGetValue(cansmi, out string label) && !disabled.Contains(label)) { - Sgroup sgroup = new Sgroup + var sgroup = new Sgroup { Type = SgroupType.CtabAbbreviation, Subscript = label @@ -303,17 +303,17 @@ public IList Generate(IAtomContainer mol) } else if (cansmi.Contains(".")) { - List complexAbbr = new List(4); // e.g. NEt3 - List simpleAbbr = new List(4); // e.g. HCl + var complexAbbr = new List(4); // e.g. NEt3 + var simpleAbbr = new List(4); // e.g. HCl foreach (IAtomContainer part in ConnectivityChecker.PartitionIntoMolecules(mol)) { if (part.Atoms.Count == 1) { - IAtom atom = part.Atoms[0]; + var atom = part.Atoms[0]; label = GetBasicElementSymbol(atom); if (label != null) { - Sgroup sgroup = new Sgroup + var sgroup = new Sgroup { Type = SgroupType.CtabAbbreviation, Subscript = label @@ -349,7 +349,7 @@ public IList Generate(IAtomContainer mol) if (complexAbbr.Any() && complexAbbr.Count + simpleAbbr.Count > 1) { - Sgroup combined = new Sgroup(); + var combined = new Sgroup(); label = null; complexAbbr.AddRange(simpleAbbr); foreach (Sgroup sgroup in complexAbbr) @@ -376,14 +376,14 @@ public IList Generate(IAtomContainer mol) } var newSgroups = new List(); - List fragments = GenerateFragments(mol); - MultiDictionary sgroupAdjs = new MultiDictionary(); + var fragments = GenerateFragments(mol); + var sgroupAdjs = new MultiDictionary(); foreach (var frag in fragments) { try { - string smi = usmigen.Create(AtomContainerManipulator.CopyAndSuppressedHydrogens(frag)); + var smi = usmigen.Create(AtomContainerManipulator.CopyAndSuppressedHydrogens(frag)); if (!connectedAbbreviations.TryGetValue(smi, out string label) || disabled.Contains(label)) continue; @@ -406,7 +406,7 @@ public IList Generate(IAtomContainer mol) continue; // create new abbreviation Sgroup - Sgroup sgroup = new Sgroup + var sgroup = new Sgroup { Type = SgroupType.CtabAbbreviation, Subscript = label @@ -417,7 +417,7 @@ public IList Generate(IAtomContainer mol) sgroup.Bonds.Add(attachBond); for (int i = 1; i < numAtoms; i++) { - IAtom atom = frag.Atoms[i]; + var atom = frag.Atoms[i]; usedAtoms.Add(atom); sgroup.Atoms.Add(atom); if (attachBond.Begin.Equals(atom)) @@ -455,7 +455,7 @@ public IList Generate(IAtomContainer mol) var newbonds = new HashSet(); xatoms.Add(attach); - List nbrSymbols = new List(); + var nbrSymbols = new List(); var todelete = new HashSet(); foreach (Sgroup sgroup in sgroupAdjs[attach]) { @@ -469,7 +469,7 @@ public IList Generate(IAtomContainer mol) todelete.Add(sgroup); } int numSGrpNbrs = nbrSymbols.Count; - foreach (IBond bond in mol.GetConnectedBonds(attach)) + foreach (var bond in mol.GetConnectedBonds(attach)) { if (!xbonds.Contains(bond)) { @@ -503,13 +503,13 @@ public IList Generate(IAtomContainer mol) // reject if no symbols // reject if no bonds (<1), except if all symbols are identical... (HashSet.size==1) // reject if more that 2 bonds - if (!nbrSymbols.Any() || - newbonds.Count < 1 && (new HashSet(nbrSymbols).Count != 1) || - newbonds.Count > 2) + if (!nbrSymbols.Any() + || newbonds.Count < 1 && (new HashSet(nbrSymbols).Count != 1) + || newbonds.Count > 2) continue; // create the symbol - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append(NewSymbol(attach.AtomicNumber.Value, hcount, newbonds.Count == 0)); string prev = null; int count = 0; @@ -562,7 +562,7 @@ public IList Generate(IAtomContainer mol) /// /// Count number of upper case chars. /// - private int CountUpper(String str) + private static int CountUpper(String str) { if (str == null) return 0; @@ -573,7 +573,7 @@ private int CountUpper(String str) return num; } - private bool ContainsChargeChar(String str) + private static bool ContainsChargeChar(String str) { for (int i = 0; i < str.Length; i++) { @@ -589,12 +589,12 @@ private bool ContainsChargeChar(String str) /// /// /// - private bool DigitAtEnd(string str) + private static bool DigitAtEnd(string str) { return char.IsDigit(str[str.Length - 1]); } - private string NewSymbol(int atomnum, int hcount, bool prefix) + private static string NewSymbol(int atomnum, int hcount, bool prefix) { StringBuilder sb = new StringBuilder(); var elem = ChemicalElement.OfNumber(atomnum); @@ -623,7 +623,7 @@ private string NewSymbol(int atomnum, int hcount, bool prefix) return sb.ToString(); } - private void AppendGroup(StringBuilder sb, String group, int coef, bool useParen) + private static void AppendGroup(StringBuilder sb, String group, int coef, bool useParen) { if (coef <= 0 || group == null || !group.Any()) return; @@ -650,7 +650,7 @@ private void AppendGroup(StringBuilder sb, String group, int coef, bool useParen public int Apply(IAtomContainer mol) { var newSgroups = Generate(mol); - var sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); if (sgroups == null) sgroups = new List(); @@ -665,7 +665,7 @@ public int Apply(IAtomContainer mol) if (!sgroup.Bonds.Any() || coverage < 0.4d) sgroups.Add(sgroup); } - mol.SetProperty(CDKPropertyName.CtabSgroups, new ReadOnlyCollection(sgroups)); + mol.SetCtabSgroups(sgroups); return sgroups.Count - prev; } @@ -677,7 +677,7 @@ public int Apply(IAtomContainer mol) /// molecule /// atom of molecule /// the query atom (null if attachment point) - private IQueryAtom MatchExact(IAtomContainer mol, IAtom atom) + private static IQueryAtom MatchExact(IAtomContainer mol, IAtom atom) { IChemObjectBuilder bldr = atom.Builder; @@ -713,7 +713,7 @@ private IQueryAtom MatchExact(IAtomContainer mol, IAtom atom) /// molecule /// query container /// - private IQueryAtomContainer MatchExact(IAtomContainer mol) + private static IQueryAtomContainer MatchExact(IAtomContainer mol) { IChemObjectBuilder bldr = mol.Builder; IQueryAtomContainer qry = new QueryAtomContainer(mol.Builder); diff --git a/NCDKDisplay/Depict/DepictionGenerator.cs b/NCDKDisplay/Depict/DepictionGenerator.cs index 76964806..dc0970fa 100644 --- a/NCDKDisplay/Depict/DepictionGenerator.cs +++ b/NCDKDisplay/Depict/DepictionGenerator.cs @@ -217,7 +217,7 @@ private RendererModel CreateModel() /// highlight the provided set of atoms and bonds in the depiction in the specified color /// depiction instance /// a depiction could not be generated - public Depiction Depict(IAtomContainer mol, IDictionary highlight = null) + public Depiction Depict(IAtomContainer mol, IReadOnlyDictionary highlight = null) { return Depict(new[] { mol }, 1, 1, highlight); } @@ -230,8 +230,8 @@ public Depiction Depict(IAtomContainer mol, IDictionary high /// molecules /// depiction /// a depiction could not be generated - /// - public Depiction Depict(IEnumerable mols, IDictionary highlight = null) + /// + public Depiction Depict(IEnumerable mols, IReadOnlyDictionary highlight = null) { var molList = mols.ToList(); var grid = Dimensions.DetermineGrid(molList.Count()); @@ -248,7 +248,7 @@ public Depiction Depict(IEnumerable mols, IDictionarynumber of columns /// depiction /// a depiction could not be generated - public Depiction Depict(IEnumerable mols, int nrow, int ncol, IDictionary highlight = null) + public Depiction Depict(IEnumerable mols, int nrow, int ncol, IReadOnlyDictionary highlight = null) { if (highlight == null) highlight = Dictionaries.Empty(); @@ -305,7 +305,7 @@ public Depiction Depict(IEnumerable mols, int nrow, int ncol, ID /// molecules /// coordinates /// - private void PrepareCoords(IEnumerable mols) + private static void PrepareCoords(IEnumerable mols) { foreach (IAtomContainer mol in mols) { @@ -353,7 +353,7 @@ private static void SetIfMissing(IChemObject chemObject, string key, string val) /// reaction instance /// depiction /// a depiction could not be generated - public Depiction Depict(IReaction rxn, IDictionary highlight = null) + public Depiction Depict(IReaction rxn, IReadOnlyDictionary highlight = null) { if (highlight == null) highlight = Dictionaries.Empty(); @@ -520,7 +520,7 @@ private Dictionary MakeHighlightAtomMap(List return colorMap; } - private int AccessAtomMap(IAtom atom) + private static int AccessAtomMap(IAtom atom) { var mapidx = atom.GetProperty(CDKPropertyName.AtomAtomMapping); if (mapidx == null) @@ -635,7 +635,7 @@ private Bounds GenerateReactionConditions(IReaction chemObj, Color fg, double sc /// a molecule /// if coordinates needed to be generated /// coordinates could not be generated - private bool Ensure2DLayout(IAtomContainer container) + private static bool Ensure2DLayout(IAtomContainer container) { if (!GeometryUtil.Has2DCoordinates(container)) { @@ -968,7 +968,7 @@ private double CaclModelScale(IReaction rxn) return CaclModelScale(mols); } - private double MedianBondLength(ICollection bonds) + private static double MedianBondLength(ICollection bonds) { if (!bonds.Any()) return 1.5; diff --git a/NCDKDisplay/Depict/MolGridDepiction.cs b/NCDKDisplay/Depict/MolGridDepiction.cs index 46588bbd..af44995a 100644 --- a/NCDKDisplay/Depict/MolGridDepiction.cs +++ b/NCDKDisplay/Depict/MolGridDepiction.cs @@ -73,7 +73,7 @@ public MolGridDepiction(RendererModel model, if (fromIndex >= toIndex) break; - List molsublist = molecules.GetRange(fromIndex, toIndex - fromIndex); + var molsublist = molecules.GetRange(fromIndex, toIndex - fromIndex); // need to pad list while (molsublist.Count < nCol) molsublist.Add(new Bounds()); @@ -97,15 +97,14 @@ public override Size Draw(DrawingContext drawingContext) double zoom = model.GetZoomFactor(); // row and col offsets for alignment - double[] yOffset = new double[nRow + 1]; - double[] xOffset = new double[nCol + 1]; - - Dimensions required = Dimensions.OfGrid(elements, yOffset, xOffset).Scale(scale * zoom); + var yOffset = new double[nRow + 1]; + var xOffset = new double[nCol + 1]; - Dimensions total = CalcTotalDimensions(margin, padding, required, null); - double fitting = CalcFitting(margin, padding, required, null); + var required = Dimensions.OfGrid(elements, yOffset, xOffset).Scale(scale * zoom); + var total = CalcTotalDimensions(margin, padding, required, null); + var fitting = CalcFitting(margin, padding, required, null); - IDrawVisitor visitor = WPFDrawVisitor.ForVectorGraphics(drawingContext); + var visitor = WPFDrawVisitor.ForVectorGraphics(drawingContext); if (model.GetBackgroundColor() != Colors.Transparent) visitor.Visit(new RectangleElement(new Point(0, 0), total.width, total.height, true, model.GetBackgroundColor()), Transform.Identity); @@ -147,8 +146,7 @@ private double CalcFitting(double margin, double padding, Dimensions required, s return 1; // no fitting Dimensions targetDim = dimensions; - targetDim = targetDim.Add(-2 * margin, -2 * margin) - .Add(-((nCol - 1) * padding), -((nRow - 1) * padding)); + targetDim = targetDim.Add(-2 * margin, -2 * margin).Add(-((nCol - 1) * padding), -((nRow - 1) * padding)); double resize = Math.Min(targetDim.width / required.width, targetDim.height / required.height); if (resize > 1 && !model.GetFitToScreen()) diff --git a/NCDKDisplay/Depict/SvgDrawVisitor.cs b/NCDKDisplay/Depict/SvgDrawVisitor.cs index 0ed21bf6..9829319b 100644 --- a/NCDKDisplay/Depict/SvgDrawVisitor.cs +++ b/NCDKDisplay/Depict/SvgDrawVisitor.cs @@ -113,12 +113,12 @@ private void TransformPoints(Point[] points) } } - private string ToString(double num) + private static string ToString(double num) { return FormatDecimal(num); } - private void AppendPoints(StringBuilder sb, Point[] points, int numPoints) + private static void AppendPoints(StringBuilder sb, Point[] points, int numPoints) { switch (numPoints) { @@ -154,7 +154,7 @@ private void AppendPoints(StringBuilder sb, Point[] points, int numPoints) } } - private void AppendRelativePoints(StringBuilder sb, Point[] points, Point vBase, int numPoints) + private static void AppendRelativePoints(StringBuilder sb, Point[] points, Point vBase, int numPoints) { switch (numPoints) { @@ -190,7 +190,7 @@ private void AppendRelativePoints(StringBuilder sb, Point[] points, Point vBase, } } - string ToString(Color col) + static string ToString(Color col) { if (col.A == 255) { diff --git a/NCDKDisplay/IncludeExamples.xml b/NCDKDisplay/IncludeExamples.xml index d22da048..1c52cb8b 100644 --- a/NCDKDisplay/IncludeExamples.xml +++ b/NCDKDisplay/IncludeExamples.xml @@ -2,7 +2,7 @@ ElectronDonation model = ElectronDonation.DaylightModel; - ICycleFinder cycles = Cycles.Or(Cycles.AllFinder, Cycles.GetAllFinder(6)); + ICycleFinder cycles = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(6)); Aromaticity aromaticity = new Aromaticity(model, cycles); // apply our configured model to each molecule @@ -18,13 +18,13 @@ // mimics the DoubleBondAcceptingAromaticityDetector Aromaticity aromaticity_exo = new Aromaticity(ElectronDonation.CDKAllowingExocyclicModel, Cycles.CDKAromaticSetFinder); // a good model for writing SMILES - Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); // a good model for writing MDL/Mol2 - Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllFinder); + Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllSimpleFinder); - Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); try @@ -39,7 +39,7 @@ - Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); try { @@ -59,7 +59,7 @@ - new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllFinder, Cycles.RelevantFinder)); + new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllSimpleFinder, Cycles.RelevantFinder)); @@ -106,7 +106,7 @@ - IsotopeFactory factory = XMLIsotopeFactory.GetInstance(Default.ChemObjectBuilder.Instance); + IsotopeFactory factory = XMLIsotopeFactory.GetInstance(ChemObjectBuilder.Instance); IIsotope major = factory.GetMajorIsotope("H"); @@ -193,21 +193,21 @@ var molecule = new AtomContainer(); var fingerprinter = new Fingerprinter(); var fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 1024 by default + Console.WriteLine(fingerprint.Length); // returns 1024 by default var molecule = new AtomContainer(); var fingerprinter = new HybridizationFingerprinter(); var fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 1024 by default + Console.WriteLine(fingerprint.Length); // returns 1024 by default var molecule = new AtomContainer(); IFingerprinter fingerprinter = new PubchemFingerprinter(Silent.ChemObjectBuilder.Instance); IBitFingerprint fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 881 + Console.WriteLine(fingerprint.Length); // returns 881 @@ -215,10 +215,10 @@ AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); var fingerprinter = new ShortestPathFingerprinter(); var fingerprint = fingerprinter.GetBitFingerprint(molecule); - Console.WriteLine(fingerprint.Count); // returns 1024 by default + Console.WriteLine(fingerprint.Length); // returns 1024 by default - + MmffAtomTypeMatcher mmffAtomTypes = new MmffAtomTypeMatcher(); foreach (var container in containers) { @@ -226,7 +226,7 @@ } - + IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); Mmff mmff = new Mmff(); mmff.AssignAtomTypes(mol); @@ -235,7 +235,7 @@ - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -258,7 +258,7 @@ - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -282,8 +282,8 @@ - AtomContainer ac1 = new AtomContainer(); // molecule 1 - AtomContainer ac2 = new AtomContainer(); // molecule 2 + var ac1 = new AtomContainer(); // molecule 1 + var ac2 = new AtomContainer(); // molecule 2 try { KabschAlignment sa = new KabschAlignment(ac1.Atoms, ac2.Atoms); @@ -347,10 +347,8 @@ - // Generate factory - if native code does not load - InChIGeneratorFactory factory = new InChIGeneratorFactory(); - // Get InChIToStructure - InChIToStructure intostruct = factory.GetInChIToStructure(inchi, Default.ChemObjectBuilder.Instance); + // Get InChIToStructure + InChIToStructure intostruct = InChIToStructure.FromInChI(inchi, ChemObjectBuilder.Instance); InChIReturnCode ret = intostruct.ReturnStatus; if (ret == InChIReturnCode.Warning) @@ -522,8 +520,8 @@ namespace NCDK.Graphs int fragmentCount = fragments.Count; - - ICycleFinder cf = Cycles.AllFinder; + + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -539,7 +537,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -555,7 +553,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -571,7 +569,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -587,7 +585,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -603,7 +601,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -619,7 +617,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -635,7 +633,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -651,7 +649,7 @@ namespace NCDK.Graphs - ICycleFinder cf = Cycles.AllFinder; + ICycleFinder cf = Cycles.AllSimpleFinder; foreach (var container in containers) { try @@ -668,12 +666,12 @@ namespace NCDK.Graphs // all cycles or all cycles size <= 6 - ICycleFinder cf = Cycles.Or(Cycles.AllFinder, Cycles.GetAllFinder(6)); + ICycleFinder cf = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(6)); // all cycles or relevant or essential - ICycleFinder cf = Cycles.Or(Cycles.AllFinder, Cycles.Or(Cycles.RelevantFinder, Cycles.EssentialFinder)); + ICycleFinder cf = Cycles.Or(Cycles.AllSimpleFinder, Cycles.Or(Cycles.RelevantFinder, Cycles.EssentialFinder)); @@ -1039,7 +1037,7 @@ namespace NCDK.Graphs string filename = "/Users/rguha/conf2.sdf"; using (var srm = new FileStream(filename, FileMode.Open)) { - IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(srm, Default.ChemObjectBuilder.Instance); + IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(srm, ChemObjectBuilder.Instance); foreach (var cc in reader) { // do something @@ -1051,7 +1049,7 @@ namespace NCDK.Graphs using (var srm = new FileStream("../zinc-structures/ZINC_subset3_3D_charged_wH_maxmin1000.sdf", FileMode.Open)) { - EnumerableSDFReader reader = new EnumerableSDFReader(srm, Default.ChemObjectBuilder.Instance); + EnumerableSDFReader reader = new EnumerableSDFReader(srm, ChemObjectBuilder.Instance); foreach (var molecule in reader) { // do something @@ -1062,7 +1060,7 @@ namespace NCDK.Graphs // create the manager and add a setting var manager = new SettingManager<BooleanIOSetting>(); - manager.Add(new BooleanIOSetting("Sample", IOSetting.Importance.Medium, "This is a sample?", "true")); + manager.Add(new BooleanIOSetting("Sample", Importance.Medium, "This is a sample?", "true")); // check the setting is present (case insensitive) if (manager.Has("sample")) @@ -1444,7 +1442,7 @@ namespace NCDK.Graphs - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride IAtomContainer SMILESquery = sp.ParseSmiles("CC"); // ethylene IQueryAtomContainer query = QueryAtomContainerCreator.CreateBasicQueryContainer(SMILESquery); @@ -1488,12 +1486,12 @@ namespace NCDK.Graphs - ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(Default.ChemObjectBuilder.Instance); + ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(ChemObjectBuilder.Instance); IAtomContainer molecule = mb3d.Generate3DCoordinates(mol, false); - QueryAtomContainer query = new QueryAtomContainer(Default.ChemObjectBuilder.Instance); + QueryAtomContainer query = new QueryAtomContainer(ChemObjectBuilder.Instance); PharmacophoreQueryAtom o = new PharmacophoreQueryAtom("D", "[OX1]"); PharmacophoreQueryAtom n1 = new PharmacophoreQueryAtom("A", "[N]"); @@ -1514,7 +1512,7 @@ namespace NCDK.Graphs string filename = "/Users/rguha/pcore1.sdf"; using (var srm = new FileStream(filename, FileMode.Open)) { - foreach (var conformers in new IEnumerableMDLConformerReader(srm, Default.ChemObjectBuilder.Instance)) + foreach (var conformers in new IEnumerableMDLConformerReader(srm, ChemObjectBuilder.Instance)) { bool firstTime = true; foreach (var conf in conformers) @@ -1553,9 +1551,9 @@ namespace NCDK.Graphs var classNames = DescriptorEngine.GetDescriptorClassNameByPackage("NCDK.QSRA.Descriptors.Moleculars", null); - DescriptorEngine engine = new DescriptorEngine(classNames, Default.ChemObjectBuilder.Instance); - var instances = engine.InstantiateDescriptors(classNames); - var specs = engine.InitializeSpecifications(instances); + DescriptorEngine engine = new DescriptorEngine(classNames, ChemObjectBuilder.Instance); + var instances = DescriptorEngine.InstantiateDescriptors(classNames); + var specs = instances.Select(n => n.Specification).ToList(); engine.SetDescriptorInstances(instances); engine.SetDescriptorSpecifications(specs); @@ -1585,7 +1583,7 @@ namespace NCDK.Graphs // using static NCDK.RingSearches.AllRingsFinder.Threshold; - AllRingsFinder arf = AllRingsFinder.UsingThreshold(PubChem_99); + AllRingsFinder arf = AllRingsFinder.UsingThreshold(Threshold.PubChem99); @@ -1660,7 +1658,7 @@ namespace NCDK.Graphs - IAtomContainer mol = new Smiles.SmilesParser(Default.ChemObjectBuilder.Instance).ParseSmiles("c1cc(cc2cc(ccc12)C3C4CC34)C6CC5CCC6(C5)"); + IAtomContainer mol = new Smiles.SmilesParser(ChemObjectBuilder.Instance).ParseSmiles("c1cc(cc2cc(ccc12)C3C4CC34)C6CC5CCC6(C5)"); RingSearch ringSearch = new RingSearch(mol); int[][] fused = ringSearch.Fused(); @@ -1686,6 +1684,24 @@ namespace NCDK.Graphs BitArray fingerprint1 = fingerprinter.GetBitFingerprint(molecule1).AsBitSet(); BitArray fingerprint2 = fingerprinter.GetBitFingerprint(molecule2).AsBitSet(); double tanimoto_coefficient = Tanimoto.Calculate(fingerprint1, fingerprint2); + + + + IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; + var smipar = new SmilesParser(bldr); + + IAtomContainer mol = smipar.ParseSmiles("[nH]1ccc2c1cccc2"); + var subsmarts = new SmartsFragmentExtractor(mol); + + string smarts; + // smarts=[nH1v3X3+0][cH1v4X3+0][cH1v4X3+0][cH0v4X3+0] + // hits =1 + smarts = subsmarts.Generate(new int[]{0,1,3,4}); + + subsmarts.SetMode(SubstructureSelectionMode.JCompoundMapper); + // smarts=n(ccc(a)a)a + // hits = 0 - one of the 'a' atoms needs to match the nitrogen + smarts = subsmarts.Generate(new int[]{0,1,3,4}); @@ -1701,14 +1717,14 @@ namespace NCDK.Graphs - SMARTSParser parser = new SMARTSParser(new StringReader("C*C")); - ASTStart ast = parser.Start(); - SmartsQueryVisitor visitor = new SmartsQueryVisitor(Silent.ChemObjectBuilder.Instance); + SMARTSParser parser = new SMARTSParser(new StringReader("C*C")); + ASTStart ast = parser.Start(); + SmartsQueryVisitor visitor = new SmartsQueryVisitor(Silent.ChemObjectBuilder.Instance); QueryAtomContainer query = (QueryAtomContainer)visitor.Visit(ast, null); - Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", Default.ChemObjectBuilder.Instance); + Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", ChemObjectBuilder.Instance); foreach (var ac in acs) { @@ -1720,7 +1736,7 @@ namespace NCDK.Graphs - Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", Default.ChemObjectBuilder.Instance); + Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", ChemObjectBuilder.Instance); foreach (var ac in acs) { @@ -1729,7 +1745,7 @@ namespace NCDK.Graphs - Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", Default.ChemObjectBuilder.Instance); + Pattern ptrn = SmartsPattern.Create("O[C@?H](C)CC", ChemObjectBuilder.Instance); int nUniqueHits = 0; foreach (var ac in acs) { @@ -1738,23 +1754,23 @@ namespace NCDK.Graphs - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); - SMARTSQueryTool querytool = new SMARTSQueryTool("O=CO", Silent.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("O=CO", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); if (status) { int nmatch = querytool.MatchesCount; - IList<IList<int>> mappings = querytool.GetMatchingAtoms(); - for (int i = 0; i < nmatch; i++) + var mappings = querytool.GetMatchingAtoms(); + foreach (var atomIndices in mappings) { - IList<int> atomIndices = mappings[i]; + // do something } } - SMARTSQueryTool sqt = new SMARTSQueryTool(someSmartsPattern, Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool(someSmartsPattern, ChemObjectBuilder.Instance); sqt.SetAromaticity(new Aromaticity(ElectronDonation.CDKModel, Cycles.CDKAromaticSetFinder)); foreach (var molecule in molecules) { @@ -1786,17 +1802,17 @@ namespace NCDK.Smiles } - - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Isomeric); + + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Isomeric); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo | SmiFlavor.AtomicMass); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo | SmiFlavors.AtomicMass); IAtomContainer ethanol = TestMoleculeFactory.MakeEthanol(); - sg = new SmilesGenerator(SmiFlavor.Generic); + sg = new SmilesGenerator(SmiFlavors.Generic); smi = sg.Create(ethanol); // CCO, C(C)O, C(O)C, or OCC sg = SmilesGenerator.Unique(); @@ -1807,10 +1823,10 @@ namespace NCDK.Smiles IAtomContainer benzene = TestMoleculeFactory.MakeBenzene(); // 'benzene' molecule has no arom flags, we always get Kekulé output - sg = new SmilesGenerator(SmiFlavor.Generic); + sg = new SmilesGenerator(SmiFlavors.Generic); smi = sg.Create(benzene); // C1=CC=CC=C1 - sg = new SmilesGenerator(SmiFlavor.Generic | SmiFlavor.UseAromaticSymbols); + sg = new SmilesGenerator(SmiFlavors.Generic | SmiFlavors.UseAromaticSymbols); smi = sg.Create(benzene); // C1=CC=CC=C1 flags not set! // Note, in practice we'd use an aromaticity algorithm @@ -1820,16 +1836,16 @@ namespace NCDK.Smiles b.IsAromatic = true; // 'benzene' molecule now has arom flags, we always get aromatic SMILES if we request it - sg = new SmilesGenerator(SmiFlavor.Generic); + sg = new SmilesGenerator(SmiFlavors.Generic); smi = sg.Create(benzene); // C1=CC=CC=C1 - sg = new SmilesGenerator(SmiFlavor.Generic | SmiFlavor.UseAromaticSymbols); + sg = new SmilesGenerator(SmiFlavors.Generic | SmiFlavors.UseAromaticSymbols); smi = sg.Create(benzene); // c1ccccc1 IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); - SmilesGenerator sg = new SmilesGenerator(SmiFlavor.Generic); + SmilesGenerator sg = new SmilesGenerator(SmiFlavors.Generic); int n = mol.Atoms.Count; int[] order = new int[n]; @@ -1848,11 +1864,11 @@ namespace NCDK.Smiles - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.UseAromaticSymbols); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.UseAromaticSymbols); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.AtomAtomMap); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.AtomAtomMap); smigen.CreateSMILES(container); // C[CH2:4]O second atom has class = 4 @@ -1916,8 +1932,8 @@ namespace NCDK.Smiles var c2 = m.Atoms[2].GetProperty<int>(CDKPropertyName.AtomAtomMapping); // null - - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride IAtomContainer SMILESquery = sp.ParseSmiles("CC"); // acetic acid anhydride IQueryAtomContainer query = QueryAtomContainerCreator.CreateBasicQueryContainer(SMILESquery); @@ -1925,7 +1941,7 @@ namespace NCDK.Smiles - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // Benzene IAtomContainer A1 = sp.ParseSmiles("C1=CC=CC=C1"); // Napthalene @@ -1960,7 +1976,7 @@ namespace NCDK.Smiles - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // Benzene IAtomContainer A1 = sp.ParseSmiles("C1=CC=CC=C1"); // Napthalene @@ -2082,7 +2098,7 @@ namespace NCDK.Smiles - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); parser.IsPreservingAromaticity = true; IAtomContainer biphenyl = parser.ParseSmiles("c1cccc(c1)c1ccccc1"); @@ -2119,7 +2135,7 @@ namespace NCDK.Smiles var features = new XYZFormat().SupportedDataFeatures; - bool has3DCoords = (features & HAS_3D_COORDINATES) == HAS_3D_COORDINATES; + bool has3DCoords = (features & DataFeatures.Has3DCoordinates) == DataFeatures.Has3DCoordinates; @@ -2162,7 +2178,7 @@ namespace NCDK.Smiles var reader = new IEnumerableMDLConformerReader( new FileStream(filename, FileMode.Open), - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); foreach (ConformerContainer cc in reader) { foreach (var conformer in cc) diff --git a/NCDKDisplay/NCDK.Display.csproj b/NCDKDisplay/NCDK.Display.csproj index ca358355..3a3ea509 100644 --- a/NCDKDisplay/NCDK.Display.csproj +++ b/NCDKDisplay/NCDK.Display.csproj @@ -63,6 +63,7 @@ + diff --git a/NCDKDisplay/Properties/AssemblyInfo.cs b/NCDKDisplay/Properties/AssemblyInfo.cs index 5b5db495..f9f4daa0 100644 --- a/NCDKDisplay/Properties/AssemblyInfo.cs +++ b/NCDKDisplay/Properties/AssemblyInfo.cs @@ -12,5 +12,5 @@ [assembly: AssemblyCompany("Kazuya Ujihara")] [assembly: AssemblyCopyright("Copyright © 2016-2018 Kazuya Ujihara")] [assembly: AssemblyTrademark("")] -[assembly: AssemblyVersion("1.3.1.0")] -[assembly: AssemblyFileVersion("1.3.1.0")] +[assembly: AssemblyVersion("1.4.0.0")] +[assembly: AssemblyFileVersion("1.4.0.0")] diff --git a/NCDKDisplay/Renderers/Colors/CDK2DAtomColors.cs b/NCDKDisplay/Renderers/Colors/CDK2DAtomColors.cs index 8b627f5a..fd488326 100644 --- a/NCDKDisplay/Renderers/Colors/CDK2DAtomColors.cs +++ b/NCDKDisplay/Renderers/Colors/CDK2DAtomColors.cs @@ -41,7 +41,6 @@ namespace NCDK.Renderers.Colors ///Jmol, Colors // @cdk.module render // @cdk.githash - [Serializable] public class CDK2DAtomColors : IAtomColorer { private static readonly Color hexD9FFFF = Color.FromRgb(0xD9, 0xFF, 0xFF); diff --git a/NCDKDisplay/Renderers/Generators/AtomMassGenerator.cs b/NCDKDisplay/Renderers/Generators/AtomMassGenerator.cs index 90f17ac1..15b23112 100644 --- a/NCDKDisplay/Renderers/Generators/AtomMassGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/AtomMassGenerator.cs @@ -45,7 +45,7 @@ public override bool ShowCarbon(IAtom atom, IAtomContainer container, RendererMo { try { - var expectedMassNumber = Isotopes.Instance.GetMajorIsotope(atom.Symbol).MassNumber; + var expectedMassNumber = BODRIsotopeFactory.Instance.GetMajorIsotope(atom.Symbol).MassNumber; if (massNumber != expectedMassNumber) return true; } catch (IOException e) diff --git a/NCDKDisplay/Renderers/Generators/BasicBondGenerator.cs b/NCDKDisplay/Renderers/Generators/BasicBondGenerator.cs index 838ca58e..4116a69e 100644 --- a/NCDKDisplay/Renderers/Generators/BasicBondGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/BasicBondGenerator.cs @@ -408,7 +408,7 @@ protected virtual bool BindsHydrogen(IBond bond) for (int i = 0; i < bond.Atoms.Count; i++) { IAtom atom = bond.Atoms[i]; - if ("H".Equals(atom.Symbol)) return true; + if (string.Equals("H", atom.Symbol, StringComparison.Ordinal)) return true; } return false; } diff --git a/NCDKDisplay/Renderers/Generators/ExtendedAtomGenerator.cs b/NCDKDisplay/Renderers/Generators/ExtendedAtomGenerator.cs index 6c5acc3c..54b261b8 100644 --- a/NCDKDisplay/Renderers/Generators/ExtendedAtomGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/ExtendedAtomGenerator.cs @@ -115,7 +115,7 @@ private void Decorate(TextGroupElement textGroup, IAtomContainer container, IAto { try { - IsotopeFactory factory = Isotopes.Instance; + IsotopeFactory factory = BODRIsotopeFactory.Instance; int majorMass = factory.GetMajorIsotope(atom.Symbol).MassNumber.Value; if (massNumber.Value != majorMass) { diff --git a/NCDKDisplay/Renderers/Generators/HighlightGenerator.cs b/NCDKDisplay/Renderers/Generators/HighlightGenerator.cs index 09e2d376..0911effd 100644 --- a/NCDKDisplay/Renderers/Generators/HighlightGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/HighlightGenerator.cs @@ -270,20 +270,6 @@ public static IPalette CreateAutoGenPalette(bool transparent) return new AutoGenerated(5, transparent ? 200 : 255); } - /// - /// Defines a color palette, the palette should provide a color the specified - /// identifier (id). - /// - public interface IPalette - { - /// - /// Obtain the color in index, id. - /// - /// the id of the color - /// a color - Color Color(int id); - } - /// /// A palette that allows one to define the precise colors of each class. The /// colors are passed in the constructor. diff --git a/NCDKDisplay/Renderers/Generators/IPalette.cs b/NCDKDisplay/Renderers/Generators/IPalette.cs new file mode 100644 index 00000000..415b6a59 --- /dev/null +++ b/NCDKDisplay/Renderers/Generators/IPalette.cs @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014 European Bioinformatics Institute (EMBL-EBI) + * John May + * + * Contact: cdk-devel@lists.sourceforge.net + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or (at + * your option) any later version. All we ask is that proper credit is given + * for our work, which includes - but is not limited to - adding the above + * copyright notice to the beginning of your source code files, and to any + * copyright notice that you may distribute with programs based on this work. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public + * License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U + */ + +using System.Windows.Media; + +namespace NCDK.Renderers.Generators +{ + /// + /// Defines a color palette, the palette should provide a color the specified + /// identifier (id). + /// + public interface IPalette + { + /// + /// Obtain the color in index, id. + /// + /// the id of the color + /// a color + Color Color(int id); + } +} diff --git a/NCDKDisplay/Renderers/Generators/ReactionArrowGenerator.cs b/NCDKDisplay/Renderers/Generators/ReactionArrowGenerator.cs index 66e43ddf..75172d72 100644 --- a/NCDKDisplay/Renderers/Generators/ReactionArrowGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/ReactionArrowGenerator.cs @@ -36,7 +36,8 @@ public IRenderingElement Generate(IReaction reaction, RendererModel model) var totalBoundsReactants = BoundsCalculator.CalculateBounds(reaction.Reactants); var totalBoundsProducts = BoundsCalculator.CalculateBounds(reaction.Products); - if (totalBoundsReactants == null || totalBoundsProducts == null) return null; + if (totalBoundsReactants == null || totalBoundsProducts == null) + return null; double separation = model.GetBondLength() / model.GetScale(); var foregroundColor = model.GetForegroundColor(); diff --git a/NCDKDisplay/Renderers/Generators/Standards/StandardAtomGenerator.cs b/NCDKDisplay/Renderers/Generators/Standards/StandardAtomGenerator.cs index a5dedc7f..c1af4fdd 100644 --- a/NCDKDisplay/Renderers/Generators/Standards/StandardAtomGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/Standards/StandardAtomGenerator.cs @@ -22,6 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ +using NCDK.Config; using System; using System.Collections.Generic; using System.IO; @@ -252,17 +253,17 @@ public AtomSymbol GeneratePseudoSymbol(string label, HydrogenPosition position) } } - private bool IsUpperCase(char c) + private static bool IsUpperCase(char c) { return c >= 'A' && c <= 'Z'; } - private bool IsLowerCase(char c) + private static bool IsLowerCase(char c) { return c >= 'a' && c <= 'z'; } - private bool IsDigit(char c) + private static bool IsDigit(char c) { return c >= '0' && c <= '9'; } @@ -538,11 +539,11 @@ private double HydrogenXDodge(int hydrogens, int mass, TextOutline elementLabel, /// atomic number /// atomic mass /// the mass is the major mass for the atomic number - private bool IsMajorIsotope(int number, int mass) + private static bool IsMajorIsotope(int number, int mass) { try { - IIsotope isotope = Config.Isotopes.Instance.GetMajorIsotope(number); + IIsotope isotope = BODRIsotopeFactory.Instance.GetMajorIsotope(number); return isotope != null && isotope.MassNumber.Equals(mass); } catch (IOException) diff --git a/NCDKDisplay/Renderers/Generators/Standards/StandardSgroupGenerator.cs b/NCDKDisplay/Renderers/Generators/Standards/StandardSgroupGenerator.cs index 2b65a815..34c9d9b8 100644 --- a/NCDKDisplay/Renderers/Generators/Standards/StandardSgroupGenerator.cs +++ b/NCDKDisplay/Renderers/Generators/Standards/StandardSgroupGenerator.cs @@ -83,7 +83,7 @@ public static IRenderingElement Generate(RendererModel parameters, double stroke /// a map that will hold symbol remapping public static void PrepareDisplayShortcuts(IAtomContainer container, IDictionary symbolRemap) { - var sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = container.GetCtabSgroups(); if (sgroups == null || !sgroups.Any()) return; @@ -270,7 +270,7 @@ private static void ContractAbbreviation(IAtomContainer container, IDictionary>(CDKPropertyName.CtabSgroups); + var sgroups = container.GetCtabSgroups(); if (sgroups == null || !sgroups.Any()) return result; @@ -392,7 +392,7 @@ private IRenderingElement GenerateAbbreviationSgroup(IAtomContainer mol, Sgroup /// /// the Sgroup /// the rendered elements (empty if no brackets defined) - private IRenderingElement GeneratePolymerSgroup(Sgroup sgroup, IDictionary symbolMap) + private IRenderingElement GeneratePolymerSgroup(Sgroup sgroup, IReadOnlyDictionary symbolMap) { // draw the brackets var brackets = (IList)sgroup.GetValue(SgroupKey.CtabBracket); @@ -408,11 +408,11 @@ private IRenderingElement GeneratePolymerSgroup(Sgroup sgroup, IDictionary brackets, - IDictionary symbols, + IReadOnlyDictionary symbols, string subscriptSuffix, string superscriptSuffix) { @@ -894,7 +894,7 @@ private GeneralPath CreateSquareBracket(Vector2 p1, Vector2 p2, Vector2 perp) return GeneralPath.OutlineOf(path, stroke, foreground); } - private static IDictionary BracketBondPairs(ICollection brackets, ICollection bonds) + private static IReadOnlyDictionary BracketBondPairs(ICollection brackets, ICollection bonds) { var pairs = new Dictionary(); @@ -930,7 +930,7 @@ private TextOutline MakeText(string subscriptSuffix, Vector2 b1p2, Vector2 b1pve return StandardGenerator.GenerateAnnotation(b1p2, subscriptSuffix, VecmathUtil.Negate(b1pvec), 1, labelScale, font, emSize, null).Resize(1 / scale, 1 / scale); } - private TextOutline LeftAlign(TextOutline outline) + private static TextOutline LeftAlign(TextOutline outline) { var center = outline.GetCenter(); var first = outline.GetFirstGlyphCenter(); diff --git a/NCDKDisplay/Renderers/RendererModelTools.tt b/NCDKDisplay/Renderers/RendererModelTools.tt index f968b894..3916315c 100644 --- a/NCDKDisplay/Renderers/RendererModelTools.tt +++ b/NCDKDisplay/Renderers/RendererModelTools.tt @@ -11,10 +11,10 @@ namespace NCDK.Renderers <# void P(string name, string type, string defaultValue, string comm) { - var e_comm = comm; - var e_defaultValue = defaultValue.Replace("<", "{").Replace(">", "}"); + var e_comm = comm; + var e_defaultValue = defaultValue.Replace("<", "{").Replace(">", "}"); #> - public static readonly <#= type #> Default<#= name #> = <#= defaultValue #>; + public static readonly <#= type #> Default<#= name #> = <#= defaultValue #>; /// /// Get <#= e_comm #>. Default value is <#= e_defaultValue #>. @@ -35,17 +35,17 @@ namespace NCDK.Renderers /// /// Set <#= e_comm #>. /// - public static void Set<#= name #>(this RendererModel model, <#= type #> value) + public static void Set<#= name #>(this RendererModel model, <#= type #> value) { const string key = "<#= name #>"; model.Parameters[key] = value; } - public static bool Has<#= name #>(this RendererModel model) - { + public static bool Has<#= name #>(this RendererModel model) + { const string key = "<#= name #>"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } <# } @@ -54,126 +54,126 @@ namespace NCDK.Renderers public static partial class RendererModelTools { <# - P("SelectionColor", "WPF.Media.Color", "WPF.Media.Color.FromRgb(0x49, 0xdf, 0xff)", "the color of a selection"); - P("ExternalHighlightColor", "WPF.Media.Color", "WPF.Media.Colors.Gray", "the color used to highlight external selections"); - P("Padding", "double", "16", "padding between molecules in a grid or row"); - P("ColorHash", "System.Collections.Generic.IDictionary", "new System.Collections.Generic.Dictionary()", "the color hash is used to color substructures"); - P("TitleFontScale", "double", "0.8", "size of title font relative compared to atom symbols"); - P("TitleColor", "WPF.Media.Color", "WPF.Media.Colors.Red", "color of title text"); - P("MarkedOutput", "bool", "true", "if format supports it (e.g. SVG) should marked up elements (id and classes) be output."); - - // - // Standard - // - - P("AtomColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "the color by which atom labels are drawn"); - P("AtomColorer", "IAtomColorer", "new UniColor(WPF.Media.Color.FromRgb(0x44, 0x44, 0x44))", " used to draw elements"); - P("Visibility", "SymbolVisibility", "NCDK.Renderers.Generators.Standards.SelectionVisibility.Disconnected(SymbolVisibility.IupacRecommendationsWithoutTerminalCarbon)", "defines which atoms have their symbol displayed"); - P("StrokeRatio", "double", "1", "defines the ratio of the stroke to the width of the stroke of the font used to depict atom symbols"); - P("BondSeparation", "double", "0.18", "defines the ratio of the separation between lines in double bonds as a percentage of length ()"); - P("SymbolMarginRatio", "double", "2", "defines the margin between an atom symbol and a connected bond based on the stroke width"); - P("WedgeRatio", "double", "6", "ratio of the wide end of wedge compared to the narrow end (stroke width)"); - P("HashSpacing", "double", "5", "the preferred spacing between lines in hashed bonds"); - P("WaveSpacing", "double", "5", "the spacing of waves (semi circles) drawn in wavy bonds with"); - P("DashSection", "int", "8", "the number of sections to render in a dashed 'unknown' bond"); - P("FancyBoldWedges", "bool", "true", "modify bold wedges to be flush with adjacent bonds"); - P("FancyHashedWedges", "bool", "true", "modify hashed wedges to be flush when there is a single adjacent bond"); - P("OuterGlowWidth", "double", "2", "the width of outer glow as a percentage of stroke width"); - P("Highlighting", "HighlightStyle", "HighlightStyle.None", "the style of highlight used to emphasis atoms and bonds"); - P("AnnotationColor", "WPF.Media.Color", "WPF.Media.Colors.Red", "the color of the atom numbers"); - P("AnnotationDistance", "double", "0.25", "the distance of atom numbers from their parent atom as a percentage of bond length"); - P("AnnotationFontScale", "double", "0.5", "annotation font size relative to element symbols"); - P("SgroupBracketDepth", "double", "0.18", "relative to bond length how deep are brackets drawn"); - P("SgroupFontScale", "double", "0.6", "scale Sgroup annotations relative to the normal font size (atom symbol)"); - P("OmitMajorIsotopes", "bool", "false", "whether Major Isotopes e.g. 12C, 16O should be omitted"); + P("SelectionColor", "WPF.Media.Color", "WPF.Media.Color.FromRgb(0x49, 0xdf, 0xff)", "the color of a selection"); + P("ExternalHighlightColor", "WPF.Media.Color", "WPF.Media.Colors.Gray", "the color used to highlight external selections"); + P("Padding", "double", "16", "padding between molecules in a grid or row"); + P("ColorHash", "System.Collections.Generic.IDictionary", "new System.Collections.Generic.Dictionary()", "the color hash is used to color substructures"); + P("TitleFontScale", "double", "0.8", "size of title font relative compared to atom symbols"); + P("TitleColor", "WPF.Media.Color", "WPF.Media.Colors.Red", "color of title text"); + P("MarkedOutput", "bool", "true", "if format supports it (e.g. SVG) should marked up elements (id and classes) be output."); + + // + // Standard + // + + P("AtomColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "the color by which atom labels are drawn"); + P("AtomColorer", "IAtomColorer", "new UniColor(WPF.Media.Color.FromRgb(0x44, 0x44, 0x44))", " used to draw elements"); + P("Visibility", "SymbolVisibility", "NCDK.Renderers.Generators.Standards.SelectionVisibility.Disconnected(SymbolVisibility.IupacRecommendationsWithoutTerminalCarbon)", "defines which atoms have their symbol displayed"); + P("StrokeRatio", "double", "1", "defines the ratio of the stroke to the width of the stroke of the font used to depict atom symbols"); + P("BondSeparation", "double", "0.18", "defines the ratio of the separation between lines in double bonds as a percentage of length ()"); + P("SymbolMarginRatio", "double", "2", "defines the margin between an atom symbol and a connected bond based on the stroke width"); + P("WedgeRatio", "double", "6", "ratio of the wide end of wedge compared to the narrow end (stroke width)"); + P("HashSpacing", "double", "5", "the preferred spacing between lines in hashed bonds"); + P("WaveSpacing", "double", "5", "the spacing of waves (semi circles) drawn in wavy bonds with"); + P("DashSection", "int", "8", "the number of sections to render in a dashed 'unknown' bond"); + P("FancyBoldWedges", "bool", "true", "modify bold wedges to be flush with adjacent bonds"); + P("FancyHashedWedges", "bool", "true", "modify hashed wedges to be flush when there is a single adjacent bond"); + P("OuterGlowWidth", "double", "2", "the width of outer glow as a percentage of stroke width"); + P("Highlighting", "HighlightStyle", "HighlightStyle.None", "the style of highlight used to emphasis atoms and bonds"); + P("AnnotationColor", "WPF.Media.Color", "WPF.Media.Colors.Red", "the color of the atom numbers"); + P("AnnotationDistance", "double", "0.25", "the distance of atom numbers from their parent atom as a percentage of bond length"); + P("AnnotationFontScale", "double", "0.5", "annotation font size relative to element symbols"); + P("SgroupBracketDepth", "double", "0.18", "relative to bond length how deep are brackets drawn"); + P("SgroupFontScale", "double", "0.6", "scale Sgroup annotations relative to the normal font size (atom symbol)"); + P("OmitMajorIsotopes", "bool", "false", "whether Major Isotopes e.g. 12C, 16O should be omitted"); // // BasicScene // - P("ArrowHeadWidth", "double", "10", "the width of the head of arrows"); - P("ShowTooltip", "bool", "false", "determines if tooltips are to be shown"); - P("ShowMoleculeTitle", "bool", "false", "determines if the molecule's title is depicted"); - P("ShowReactionTitle", "bool", "false", "determines if the reaction's title is depicted"); - P("FitToScreen", "bool", "false", "If , the scale is set such that the diagram fills the whole screen"); - P("Scale", "double", "1", "the scale is the factor to multiply model coordinates by to convert the coordinates to screen space coordinate, such that the entire structure fits the visible screen dimension"); - P("BackgroundColor", "WPF.Media.Color", "WPF.Media.Colors.White", "the background color of the drawn image"); - P("BondLength", "double", "40", "the length on the screen of a typical bond"); + P("ArrowHeadWidth", "double", "10", "the width of the head of arrows"); + P("ShowTooltip", "bool", "false", "determines if tooltips are to be shown"); + P("ShowMoleculeTitle", "bool", "false", "determines if the molecule's title is depicted"); + P("ShowReactionTitle", "bool", "false", "determines if the reaction's title is depicted"); + P("FitToScreen", "bool", "false", "If , the scale is set such that the diagram fills the whole screen"); + P("Scale", "double", "1", "the scale is the factor to multiply model coordinates by to convert the coordinates to screen space coordinate, such that the entire structure fits the visible screen dimension"); + P("BackgroundColor", "WPF.Media.Color", "WPF.Media.Colors.White", "the background color of the drawn image"); + P("BondLength", "double", "40", "the length on the screen of a typical bond"); P("ForegroundColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "the foreground color, with which objects are drawn"); P("UseAntiAliasing", "bool", "true", "if set to true, uses anti-aliasing for drawing"); P("Margin", "double", "10", "area on each of the four margins to keep empty"); P("UsedFontStyle", "Fonts.FontWeight", "Fonts.FontWeight.Normal", "the font style to use for text"); - P("FontName", "string", "\"Arial\"", "font name to use for text"); - P("ZoomFactor", "double", "1", "the zoom factor which is a user oriented parameter allowing the user to zoom in on parts of the molecule"); + P("FontName", "string", "\"Arial\"", "font name to use for text"); + P("ZoomFactor", "double", "1", "the zoom factor which is a user oriented parameter allowing the user to zoom in on parts of the molecule"); - // + // // Atom - // + // - P("AtomColorByType", "bool", "false", "triggers atoms to be colored by type when set to true"); - P("ShowExplicitHydrogens", "bool", "true", "boolean property that triggers explicit hydrogens to be drawn if set to true"); - P("ShowImplicitHydrogens", "bool", "false", "indicates implicit hydrogens should be depicted"); - P("AtomRadius", "double", "8", "magic number with unknown units that defines the radius around an atom, e.g. used for highlighting atoms"); - P("CompactAtom", "bool", "false", "atoms to be drawn as filled shapes"); - P("KekuleStructure", "bool", "false", "whether structures should be drawn as Kekulé structures, thus giving each carbon element explicitly, instead of not displaying the element symbol. Example C-C-C instead of /\""); - P("CompactShape", "AtomShapeType", "AtomShapeType.Square", "Shape to be used when drawing atoms in compact mode, as defined by the parameter"); - P("ShowEndCarbons", "bool", "false", "show carbons with only one (non-hydrogen) neighbor to be drawn with an element symbol"); - P("ShowAtomTypeNames", "bool", "false", "indicates atom type names should be given instead of element symbols"); + P("AtomColorByType", "bool", "false", "triggers atoms to be colored by type when set to true"); + P("ShowExplicitHydrogens", "bool", "true", "boolean property that triggers explicit hydrogens to be drawn if set to true"); + P("ShowImplicitHydrogens", "bool", "false", "indicates implicit hydrogens should be depicted"); + P("AtomRadius", "double", "8", "magic number with unknown units that defines the radius around an atom, e.g. used for highlighting atoms"); + P("CompactAtom", "bool", "false", "atoms to be drawn as filled shapes"); + P("KekuleStructure", "bool", "false", "whether structures should be drawn as Kekulé structures, thus giving each carbon element explicitly, instead of not displaying the element symbol. Example C-C-C instead of /\""); + P("CompactShape", "AtomShapeType", "AtomShapeType.Square", "Shape to be used when drawing atoms in compact mode, as defined by the parameter"); + P("ShowEndCarbons", "bool", "false", "show carbons with only one (non-hydrogen) neighbor to be drawn with an element symbol"); + P("ShowAtomTypeNames", "bool", "false", "indicates atom type names should be given instead of element symbols"); - // Atom number + // Atom number - P("AtomNumberTextColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "color to draw the atom numbers with"); - P("WillDrawAtomNumbers", "bool", "true", "indicating if atom numbers should be drawn, allowing this feature to be disabled temporarily"); - P("AtomNumberColorer", "IAtomColorer", "new CDK2DAtomColors()", "the color scheme by which to color the atom numbers"); - P("AtomNumberColorByType", "bool", "false", "indicate of the scheme will be used"); - P("AtomNumberOffset", "Vector2", "Vector2.Zero", "offset vector in screen space coordinates where the atom number label will be placed"); + P("AtomNumberTextColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "color to draw the atom numbers with"); + P("WillDrawAtomNumbers", "bool", "true", "indicating if atom numbers should be drawn, allowing this feature to be disabled temporarily"); + P("AtomNumberColorer", "IAtomColorer", "new CDK2DAtomColors()", "the color scheme by which to color the atom numbers"); + P("AtomNumberColorByType", "bool", "false", "indicate of the scheme will be used"); + P("AtomNumberOffset", "Vector2", "Vector2.Zero", "offset vector in screen space coordinates where the atom number label will be placed"); - // - // Bond - // + // + // Bond + // - // FIXME: bond width should be defined in world, not screen coordinates - P("BondWidth", "double", "1", "the width on screen of a bond"); - P("BondDistance", "double", "2", "the gap between double and triple bond lines on the screen"); - P("DefaultBondColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "the color to draw bonds if not other color is given"); - P("WedgeWidth", "double", "2", "the width on screen of the fat end of a wedge bond"); - P("TowardsRingCenterProportion", "double", "0.15", "the proportion to move in towards the ring center"); - P("ForceDelocalisedBondDisplay", "bool", "false", "Indicate delocalised/aromatic bonds should always be rendered, even when there is a valid Kekule structure. Delocalised bonds will either be rendered as a dashed bond to the side or as a circle/donut/life buoy inside small rings. This depiction is used by default when a bond does not have an order assigned (e.g. null/unset). Turning this option on means all delocalised bonds will be rendered this way. As recommended by IUPAC, their usage is discouraged and the Kekule representation is more clear."); + // FIXME: bond width should be defined in world, not screen coordinates + P("BondWidth", "double", "1", "the width on screen of a bond"); + P("BondDistance", "double", "2", "the gap between double and triple bond lines on the screen"); + P("DefaultBondColor", "WPF.Media.Color", "WPF.Media.Colors.Black", "the color to draw bonds if not other color is given"); + P("WedgeWidth", "double", "2", "the width on screen of the fat end of a wedge bond"); + P("TowardsRingCenterProportion", "double", "0.15", "the proportion to move in towards the ring center"); + P("ForceDelocalisedBondDisplay", "bool", "false", "Indicate delocalised/aromatic bonds should always be rendered, even when there is a valid Kekule structure. Delocalised bonds will either be rendered as a dashed bond to the side or as a circle/donut/life buoy inside small rings. This depiction is used by default when a bond does not have an order assigned (e.g. null/unset). Turning this option on means all delocalised bonds will be rendered this way. As recommended by IUPAC, their usage is discouraged and the Kekule representation is more clear."); - // Ring + // Ring - P("ShowAromaticity", "bool", "true", "whether rings should be drawn with a circle if they are aromatic"); - P("CDKStyleAromaticity", "bool", "false", "depicts aromaticity of rings in the original CDK style"); - P("MaxDrawableAromaticRing", "int", "8", "the maximum ring size for which an aromatic ring should be drawn"); - P("RingProportion", "double", "0.35", "the proportion of a ring bounds to use to draw the ring"); + P("ShowAromaticity", "bool", "true", "whether rings should be drawn with a circle if they are aromatic"); + P("CDKStyleAromaticity", "bool", "false", "depicts aromaticity of rings in the original CDK style"); + P("MaxDrawableAromaticRing", "int", "8", "the maximum ring size for which an aromatic ring should be drawn"); + P("RingProportion", "double", "0.35", "the proportion of a ring bounds to use to draw the ring"); - // - // Reaction - // + // + // Reaction + // - P("ShowReactionBoxes", "bool", "true", "indicates if boxes are drawn around the reaction"); + P("ShowReactionBoxes", "bool", "true", "indicates if boxes are drawn around the reaction"); - // - // Mapping - // + // + // Mapping + // - P("AtomAtomMappingLineColor", "WPF.Media.Color", "WPF.Media.Colors.Gray", "the color on screen of an atom-atom mapping line"); - P("MappingLineWidth", "double", "1", "the width on screen of an atom-atom mapping line"); - P("ShowAtomAtomMapping", "bool", "true", "whether atom-atom mapping depiction can be temporarily disabled"); + P("AtomAtomMappingLineColor", "WPF.Media.Color", "WPF.Media.Colors.Gray", "the color on screen of an atom-atom mapping line"); + P("MappingLineWidth", "double", "1", "the width on screen of an atom-atom mapping line"); + P("ShowAtomAtomMapping", "bool", "true", "whether atom-atom mapping depiction can be temporarily disabled"); - // - // Highlight - // + // + // Highlight + // - P("HighlightRadius", "double", "10", "the atom radius on screen used to provide the highlight colors"); - P("HighlightPalette", "NCDK.Renderers.Generators.HighlightGenerator.IPalette", "NCDK.Renderers.Generators.HighlightGenerator.DefaultPalette", "color palette used to provide the highlight colors"); + P("HighlightRadius", "double", "10", "the atom radius on screen used to provide the highlight colors"); + P("HighlightPalette", "NCDK.Renderers.Generators.IPalette", "NCDK.Renderers.Generators.HighlightGenerator.DefaultPalette", "color palette used to provide the highlight colors"); - // - // Bounds - // + // + // Bounds + // - P("BoundsColor", "WPF.Media.Color", "WPF.Media.Colors.LightGray", "the color of the box drawn at the bounds of a molecule, molecule set, or reaction"); + P("BoundsColor", "WPF.Media.Color", "WPF.Media.Colors.LightGray", "the color of the box drawn at the bounds of a molecule, molecule set, or reaction"); #> } } diff --git a/NCDKDisplay/Renderers/RendererModelTools.tt.cs b/NCDKDisplay/Renderers/RendererModelTools.tt.cs index fa2b5396..228d6ce2 100644 --- a/NCDKDisplay/Renderers/RendererModelTools.tt.cs +++ b/NCDKDisplay/Renderers/RendererModelTools.tt.cs @@ -9,7 +9,7 @@ namespace NCDK.Renderers public static partial class RendererModelTools { - public static readonly WPF.Media.Color DefaultSelectionColor = WPF.Media.Color.FromRgb(0x49, 0xdf, 0xff); + public static readonly WPF.Media.Color DefaultSelectionColor = WPF.Media.Color.FromRgb(0x49, 0xdf, 0xff); /// /// Get the color of a selection. Default value is WPF.Media.Color.FromRgb(0x49, 0xdf, 0xff). @@ -30,19 +30,19 @@ public static WPF.Media.Color GetSelectionColor(this RendererModel model) /// /// Set the color of a selection. /// - public static void SetSelectionColor(this RendererModel model, WPF.Media.Color value) + public static void SetSelectionColor(this RendererModel model, WPF.Media.Color value) { const string key = "SelectionColor"; model.Parameters[key] = value; } - public static bool HasSelectionColor(this RendererModel model) - { + public static bool HasSelectionColor(this RendererModel model) + { const string key = "SelectionColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultExternalHighlightColor = WPF.Media.Colors.Gray; + public static readonly WPF.Media.Color DefaultExternalHighlightColor = WPF.Media.Colors.Gray; /// /// Get the color used to highlight external selections. Default value is WPF.Media.Colors.Gray. @@ -63,19 +63,19 @@ public static WPF.Media.Color GetExternalHighlightColor(this RendererModel model /// /// Set the color used to highlight external selections. /// - public static void SetExternalHighlightColor(this RendererModel model, WPF.Media.Color value) + public static void SetExternalHighlightColor(this RendererModel model, WPF.Media.Color value) { const string key = "ExternalHighlightColor"; model.Parameters[key] = value; } - public static bool HasExternalHighlightColor(this RendererModel model) - { + public static bool HasExternalHighlightColor(this RendererModel model) + { const string key = "ExternalHighlightColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultPadding = 16; + public static readonly double DefaultPadding = 16; /// /// Get padding between molecules in a grid or row. Default value is 16. @@ -96,19 +96,19 @@ public static double GetPadding(this RendererModel model) /// /// Set padding between molecules in a grid or row. /// - public static void SetPadding(this RendererModel model, double value) + public static void SetPadding(this RendererModel model, double value) { const string key = "Padding"; model.Parameters[key] = value; } - public static bool HasPadding(this RendererModel model) - { + public static bool HasPadding(this RendererModel model) + { const string key = "Padding"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly System.Collections.Generic.IDictionary DefaultColorHash = new System.Collections.Generic.Dictionary(); + public static readonly System.Collections.Generic.IDictionary DefaultColorHash = new System.Collections.Generic.Dictionary(); /// /// Get the color hash is used to color substructures. Default value is new System.Collections.Generic.Dictionary{IChemObject, WPF.Media.Color}(). @@ -129,19 +129,19 @@ public static bool HasPadding(this RendererModel model) /// /// Set the color hash is used to color substructures. /// - public static void SetColorHash(this RendererModel model, System.Collections.Generic.IDictionary value) + public static void SetColorHash(this RendererModel model, System.Collections.Generic.IDictionary value) { const string key = "ColorHash"; model.Parameters[key] = value; } - public static bool HasColorHash(this RendererModel model) - { + public static bool HasColorHash(this RendererModel model) + { const string key = "ColorHash"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultTitleFontScale = 0.8; + public static readonly double DefaultTitleFontScale = 0.8; /// /// Get size of title font relative compared to atom symbols. Default value is 0.8. @@ -162,19 +162,19 @@ public static double GetTitleFontScale(this RendererModel model) /// /// Set size of title font relative compared to atom symbols. /// - public static void SetTitleFontScale(this RendererModel model, double value) + public static void SetTitleFontScale(this RendererModel model, double value) { const string key = "TitleFontScale"; model.Parameters[key] = value; } - public static bool HasTitleFontScale(this RendererModel model) - { + public static bool HasTitleFontScale(this RendererModel model) + { const string key = "TitleFontScale"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultTitleColor = WPF.Media.Colors.Red; + public static readonly WPF.Media.Color DefaultTitleColor = WPF.Media.Colors.Red; /// /// Get color of title text. Default value is WPF.Media.Colors.Red. @@ -195,19 +195,19 @@ public static WPF.Media.Color GetTitleColor(this RendererModel model) /// /// Set color of title text. /// - public static void SetTitleColor(this RendererModel model, WPF.Media.Color value) + public static void SetTitleColor(this RendererModel model, WPF.Media.Color value) { const string key = "TitleColor"; model.Parameters[key] = value; } - public static bool HasTitleColor(this RendererModel model) - { + public static bool HasTitleColor(this RendererModel model) + { const string key = "TitleColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultMarkedOutput = true; + public static readonly bool DefaultMarkedOutput = true; /// /// Get if format supports it (e.g. SVG) should marked up elements (id and classes) be output.. Default value is true. @@ -228,19 +228,19 @@ public static bool GetMarkedOutput(this RendererModel model) /// /// Set if format supports it (e.g. SVG) should marked up elements (id and classes) be output.. /// - public static void SetMarkedOutput(this RendererModel model, bool value) + public static void SetMarkedOutput(this RendererModel model, bool value) { const string key = "MarkedOutput"; model.Parameters[key] = value; } - public static bool HasMarkedOutput(this RendererModel model) - { + public static bool HasMarkedOutput(this RendererModel model) + { const string key = "MarkedOutput"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultAtomColor = WPF.Media.Colors.Black; + public static readonly WPF.Media.Color DefaultAtomColor = WPF.Media.Colors.Black; /// /// Get the color by which atom labels are drawn. Default value is WPF.Media.Colors.Black. @@ -261,19 +261,19 @@ public static WPF.Media.Color GetAtomColor(this RendererModel model) /// /// Set the color by which atom labels are drawn. /// - public static void SetAtomColor(this RendererModel model, WPF.Media.Color value) + public static void SetAtomColor(this RendererModel model, WPF.Media.Color value) { const string key = "AtomColor"; model.Parameters[key] = value; } - public static bool HasAtomColor(this RendererModel model) - { + public static bool HasAtomColor(this RendererModel model) + { const string key = "AtomColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly IAtomColorer DefaultAtomColorer = new UniColor(WPF.Media.Color.FromRgb(0x44, 0x44, 0x44)); + public static readonly IAtomColorer DefaultAtomColorer = new UniColor(WPF.Media.Color.FromRgb(0x44, 0x44, 0x44)); /// /// Get used to draw elements. Default value is new UniColor(WPF.Media.Color.FromRgb(0x44, 0x44, 0x44)). @@ -294,19 +294,19 @@ public static IAtomColorer GetAtomColorer(this RendererModel model) /// /// Set used to draw elements. /// - public static void SetAtomColorer(this RendererModel model, IAtomColorer value) + public static void SetAtomColorer(this RendererModel model, IAtomColorer value) { const string key = "AtomColorer"; model.Parameters[key] = value; } - public static bool HasAtomColorer(this RendererModel model) - { + public static bool HasAtomColorer(this RendererModel model) + { const string key = "AtomColorer"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly SymbolVisibility DefaultVisibility = NCDK.Renderers.Generators.Standards.SelectionVisibility.Disconnected(SymbolVisibility.IupacRecommendationsWithoutTerminalCarbon); + public static readonly SymbolVisibility DefaultVisibility = NCDK.Renderers.Generators.Standards.SelectionVisibility.Disconnected(SymbolVisibility.IupacRecommendationsWithoutTerminalCarbon); /// /// Get defines which atoms have their symbol displayed. Default value is NCDK.Renderers.Generators.Standards.SelectionVisibility.Disconnected(SymbolVisibility.IupacRecommendationsWithoutTerminalCarbon). @@ -327,19 +327,19 @@ public static SymbolVisibility GetVisibility(this RendererModel model) /// /// Set defines which atoms have their symbol displayed. /// - public static void SetVisibility(this RendererModel model, SymbolVisibility value) + public static void SetVisibility(this RendererModel model, SymbolVisibility value) { const string key = "Visibility"; model.Parameters[key] = value; } - public static bool HasVisibility(this RendererModel model) - { + public static bool HasVisibility(this RendererModel model) + { const string key = "Visibility"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultStrokeRatio = 1; + public static readonly double DefaultStrokeRatio = 1; /// /// Get defines the ratio of the stroke to the width of the stroke of the font used to depict atom symbols. Default value is 1. @@ -360,19 +360,19 @@ public static double GetStrokeRatio(this RendererModel model) /// /// Set defines the ratio of the stroke to the width of the stroke of the font used to depict atom symbols. /// - public static void SetStrokeRatio(this RendererModel model, double value) + public static void SetStrokeRatio(this RendererModel model, double value) { const string key = "StrokeRatio"; model.Parameters[key] = value; } - public static bool HasStrokeRatio(this RendererModel model) - { + public static bool HasStrokeRatio(this RendererModel model) + { const string key = "StrokeRatio"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultBondSeparation = 0.18; + public static readonly double DefaultBondSeparation = 0.18; /// /// Get defines the ratio of the separation between lines in double bonds as a percentage of length (). Default value is 0.18. @@ -393,19 +393,19 @@ public static double GetBondSeparation(this RendererModel model) /// /// Set defines the ratio of the separation between lines in double bonds as a percentage of length (). /// - public static void SetBondSeparation(this RendererModel model, double value) + public static void SetBondSeparation(this RendererModel model, double value) { const string key = "BondSeparation"; model.Parameters[key] = value; } - public static bool HasBondSeparation(this RendererModel model) - { + public static bool HasBondSeparation(this RendererModel model) + { const string key = "BondSeparation"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultSymbolMarginRatio = 2; + public static readonly double DefaultSymbolMarginRatio = 2; /// /// Get defines the margin between an atom symbol and a connected bond based on the stroke width. Default value is 2. @@ -426,19 +426,19 @@ public static double GetSymbolMarginRatio(this RendererModel model) /// /// Set defines the margin between an atom symbol and a connected bond based on the stroke width. /// - public static void SetSymbolMarginRatio(this RendererModel model, double value) + public static void SetSymbolMarginRatio(this RendererModel model, double value) { const string key = "SymbolMarginRatio"; model.Parameters[key] = value; } - public static bool HasSymbolMarginRatio(this RendererModel model) - { + public static bool HasSymbolMarginRatio(this RendererModel model) + { const string key = "SymbolMarginRatio"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultWedgeRatio = 6; + public static readonly double DefaultWedgeRatio = 6; /// /// Get ratio of the wide end of wedge compared to the narrow end (stroke width). Default value is 6. @@ -459,19 +459,19 @@ public static double GetWedgeRatio(this RendererModel model) /// /// Set ratio of the wide end of wedge compared to the narrow end (stroke width). /// - public static void SetWedgeRatio(this RendererModel model, double value) + public static void SetWedgeRatio(this RendererModel model, double value) { const string key = "WedgeRatio"; model.Parameters[key] = value; } - public static bool HasWedgeRatio(this RendererModel model) - { + public static bool HasWedgeRatio(this RendererModel model) + { const string key = "WedgeRatio"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultHashSpacing = 5; + public static readonly double DefaultHashSpacing = 5; /// /// Get the preferred spacing between lines in hashed bonds. Default value is 5. @@ -492,19 +492,19 @@ public static double GetHashSpacing(this RendererModel model) /// /// Set the preferred spacing between lines in hashed bonds. /// - public static void SetHashSpacing(this RendererModel model, double value) + public static void SetHashSpacing(this RendererModel model, double value) { const string key = "HashSpacing"; model.Parameters[key] = value; } - public static bool HasHashSpacing(this RendererModel model) - { + public static bool HasHashSpacing(this RendererModel model) + { const string key = "HashSpacing"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultWaveSpacing = 5; + public static readonly double DefaultWaveSpacing = 5; /// /// Get the spacing of waves (semi circles) drawn in wavy bonds with. Default value is 5. @@ -525,19 +525,19 @@ public static double GetWaveSpacing(this RendererModel model) /// /// Set the spacing of waves (semi circles) drawn in wavy bonds with. /// - public static void SetWaveSpacing(this RendererModel model, double value) + public static void SetWaveSpacing(this RendererModel model, double value) { const string key = "WaveSpacing"; model.Parameters[key] = value; } - public static bool HasWaveSpacing(this RendererModel model) - { + public static bool HasWaveSpacing(this RendererModel model) + { const string key = "WaveSpacing"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly int DefaultDashSection = 8; + public static readonly int DefaultDashSection = 8; /// /// Get the number of sections to render in a dashed 'unknown' bond. Default value is 8. @@ -558,19 +558,19 @@ public static int GetDashSection(this RendererModel model) /// /// Set the number of sections to render in a dashed 'unknown' bond. /// - public static void SetDashSection(this RendererModel model, int value) + public static void SetDashSection(this RendererModel model, int value) { const string key = "DashSection"; model.Parameters[key] = value; } - public static bool HasDashSection(this RendererModel model) - { + public static bool HasDashSection(this RendererModel model) + { const string key = "DashSection"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultFancyBoldWedges = true; + public static readonly bool DefaultFancyBoldWedges = true; /// /// Get modify bold wedges to be flush with adjacent bonds. Default value is true. @@ -591,19 +591,19 @@ public static bool GetFancyBoldWedges(this RendererModel model) /// /// Set modify bold wedges to be flush with adjacent bonds. /// - public static void SetFancyBoldWedges(this RendererModel model, bool value) + public static void SetFancyBoldWedges(this RendererModel model, bool value) { const string key = "FancyBoldWedges"; model.Parameters[key] = value; } - public static bool HasFancyBoldWedges(this RendererModel model) - { + public static bool HasFancyBoldWedges(this RendererModel model) + { const string key = "FancyBoldWedges"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultFancyHashedWedges = true; + public static readonly bool DefaultFancyHashedWedges = true; /// /// Get modify hashed wedges to be flush when there is a single adjacent bond. Default value is true. @@ -624,19 +624,19 @@ public static bool GetFancyHashedWedges(this RendererModel model) /// /// Set modify hashed wedges to be flush when there is a single adjacent bond. /// - public static void SetFancyHashedWedges(this RendererModel model, bool value) + public static void SetFancyHashedWedges(this RendererModel model, bool value) { const string key = "FancyHashedWedges"; model.Parameters[key] = value; } - public static bool HasFancyHashedWedges(this RendererModel model) - { + public static bool HasFancyHashedWedges(this RendererModel model) + { const string key = "FancyHashedWedges"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultOuterGlowWidth = 2; + public static readonly double DefaultOuterGlowWidth = 2; /// /// Get the width of outer glow as a percentage of stroke width. Default value is 2. @@ -657,19 +657,19 @@ public static double GetOuterGlowWidth(this RendererModel model) /// /// Set the width of outer glow as a percentage of stroke width. /// - public static void SetOuterGlowWidth(this RendererModel model, double value) + public static void SetOuterGlowWidth(this RendererModel model, double value) { const string key = "OuterGlowWidth"; model.Parameters[key] = value; } - public static bool HasOuterGlowWidth(this RendererModel model) - { + public static bool HasOuterGlowWidth(this RendererModel model) + { const string key = "OuterGlowWidth"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly HighlightStyle DefaultHighlighting = HighlightStyle.None; + public static readonly HighlightStyle DefaultHighlighting = HighlightStyle.None; /// /// Get the style of highlight used to emphasis atoms and bonds. Default value is HighlightStyle.None. @@ -690,19 +690,19 @@ public static HighlightStyle GetHighlighting(this RendererModel model) /// /// Set the style of highlight used to emphasis atoms and bonds. /// - public static void SetHighlighting(this RendererModel model, HighlightStyle value) + public static void SetHighlighting(this RendererModel model, HighlightStyle value) { const string key = "Highlighting"; model.Parameters[key] = value; } - public static bool HasHighlighting(this RendererModel model) - { + public static bool HasHighlighting(this RendererModel model) + { const string key = "Highlighting"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultAnnotationColor = WPF.Media.Colors.Red; + public static readonly WPF.Media.Color DefaultAnnotationColor = WPF.Media.Colors.Red; /// /// Get the color of the atom numbers. Default value is WPF.Media.Colors.Red. @@ -723,19 +723,19 @@ public static WPF.Media.Color GetAnnotationColor(this RendererModel model) /// /// Set the color of the atom numbers. /// - public static void SetAnnotationColor(this RendererModel model, WPF.Media.Color value) + public static void SetAnnotationColor(this RendererModel model, WPF.Media.Color value) { const string key = "AnnotationColor"; model.Parameters[key] = value; } - public static bool HasAnnotationColor(this RendererModel model) - { + public static bool HasAnnotationColor(this RendererModel model) + { const string key = "AnnotationColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultAnnotationDistance = 0.25; + public static readonly double DefaultAnnotationDistance = 0.25; /// /// Get the distance of atom numbers from their parent atom as a percentage of bond length. Default value is 0.25. @@ -756,19 +756,19 @@ public static double GetAnnotationDistance(this RendererModel model) /// /// Set the distance of atom numbers from their parent atom as a percentage of bond length. /// - public static void SetAnnotationDistance(this RendererModel model, double value) + public static void SetAnnotationDistance(this RendererModel model, double value) { const string key = "AnnotationDistance"; model.Parameters[key] = value; } - public static bool HasAnnotationDistance(this RendererModel model) - { + public static bool HasAnnotationDistance(this RendererModel model) + { const string key = "AnnotationDistance"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultAnnotationFontScale = 0.5; + public static readonly double DefaultAnnotationFontScale = 0.5; /// /// Get annotation font size relative to element symbols. Default value is 0.5. @@ -789,19 +789,19 @@ public static double GetAnnotationFontScale(this RendererModel model) /// /// Set annotation font size relative to element symbols. /// - public static void SetAnnotationFontScale(this RendererModel model, double value) + public static void SetAnnotationFontScale(this RendererModel model, double value) { const string key = "AnnotationFontScale"; model.Parameters[key] = value; } - public static bool HasAnnotationFontScale(this RendererModel model) - { + public static bool HasAnnotationFontScale(this RendererModel model) + { const string key = "AnnotationFontScale"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultSgroupBracketDepth = 0.18; + public static readonly double DefaultSgroupBracketDepth = 0.18; /// /// Get relative to bond length how deep are brackets drawn. Default value is 0.18. @@ -822,19 +822,19 @@ public static double GetSgroupBracketDepth(this RendererModel model) /// /// Set relative to bond length how deep are brackets drawn. /// - public static void SetSgroupBracketDepth(this RendererModel model, double value) + public static void SetSgroupBracketDepth(this RendererModel model, double value) { const string key = "SgroupBracketDepth"; model.Parameters[key] = value; } - public static bool HasSgroupBracketDepth(this RendererModel model) - { + public static bool HasSgroupBracketDepth(this RendererModel model) + { const string key = "SgroupBracketDepth"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultSgroupFontScale = 0.6; + public static readonly double DefaultSgroupFontScale = 0.6; /// /// Get scale Sgroup annotations relative to the normal font size (atom symbol). Default value is 0.6. @@ -855,19 +855,19 @@ public static double GetSgroupFontScale(this RendererModel model) /// /// Set scale Sgroup annotations relative to the normal font size (atom symbol). /// - public static void SetSgroupFontScale(this RendererModel model, double value) + public static void SetSgroupFontScale(this RendererModel model, double value) { const string key = "SgroupFontScale"; model.Parameters[key] = value; } - public static bool HasSgroupFontScale(this RendererModel model) - { + public static bool HasSgroupFontScale(this RendererModel model) + { const string key = "SgroupFontScale"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultOmitMajorIsotopes = false; + public static readonly bool DefaultOmitMajorIsotopes = false; /// /// Get whether Major Isotopes e.g. 12C, 16O should be omitted. Default value is false. @@ -888,19 +888,19 @@ public static bool GetOmitMajorIsotopes(this RendererModel model) /// /// Set whether Major Isotopes e.g. 12C, 16O should be omitted. /// - public static void SetOmitMajorIsotopes(this RendererModel model, bool value) + public static void SetOmitMajorIsotopes(this RendererModel model, bool value) { const string key = "OmitMajorIsotopes"; model.Parameters[key] = value; } - public static bool HasOmitMajorIsotopes(this RendererModel model) - { + public static bool HasOmitMajorIsotopes(this RendererModel model) + { const string key = "OmitMajorIsotopes"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultArrowHeadWidth = 10; + public static readonly double DefaultArrowHeadWidth = 10; /// /// Get the width of the head of arrows. Default value is 10. @@ -921,19 +921,19 @@ public static double GetArrowHeadWidth(this RendererModel model) /// /// Set the width of the head of arrows. /// - public static void SetArrowHeadWidth(this RendererModel model, double value) + public static void SetArrowHeadWidth(this RendererModel model, double value) { const string key = "ArrowHeadWidth"; model.Parameters[key] = value; } - public static bool HasArrowHeadWidth(this RendererModel model) - { + public static bool HasArrowHeadWidth(this RendererModel model) + { const string key = "ArrowHeadWidth"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowTooltip = false; + public static readonly bool DefaultShowTooltip = false; /// /// Get determines if tooltips are to be shown. Default value is false. @@ -954,19 +954,19 @@ public static bool GetShowTooltip(this RendererModel model) /// /// Set determines if tooltips are to be shown. /// - public static void SetShowTooltip(this RendererModel model, bool value) + public static void SetShowTooltip(this RendererModel model, bool value) { const string key = "ShowTooltip"; model.Parameters[key] = value; } - public static bool HasShowTooltip(this RendererModel model) - { + public static bool HasShowTooltip(this RendererModel model) + { const string key = "ShowTooltip"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowMoleculeTitle = false; + public static readonly bool DefaultShowMoleculeTitle = false; /// /// Get determines if the molecule's title is depicted. Default value is false. @@ -987,19 +987,19 @@ public static bool GetShowMoleculeTitle(this RendererModel model) /// /// Set determines if the molecule's title is depicted. /// - public static void SetShowMoleculeTitle(this RendererModel model, bool value) + public static void SetShowMoleculeTitle(this RendererModel model, bool value) { const string key = "ShowMoleculeTitle"; model.Parameters[key] = value; } - public static bool HasShowMoleculeTitle(this RendererModel model) - { + public static bool HasShowMoleculeTitle(this RendererModel model) + { const string key = "ShowMoleculeTitle"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowReactionTitle = false; + public static readonly bool DefaultShowReactionTitle = false; /// /// Get determines if the reaction's title is depicted. Default value is false. @@ -1020,19 +1020,19 @@ public static bool GetShowReactionTitle(this RendererModel model) /// /// Set determines if the reaction's title is depicted. /// - public static void SetShowReactionTitle(this RendererModel model, bool value) + public static void SetShowReactionTitle(this RendererModel model, bool value) { const string key = "ShowReactionTitle"; model.Parameters[key] = value; } - public static bool HasShowReactionTitle(this RendererModel model) - { + public static bool HasShowReactionTitle(this RendererModel model) + { const string key = "ShowReactionTitle"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultFitToScreen = false; + public static readonly bool DefaultFitToScreen = false; /// /// Get If , the scale is set such that the diagram fills the whole screen. Default value is false. @@ -1053,19 +1053,19 @@ public static bool GetFitToScreen(this RendererModel model) /// /// Set If , the scale is set such that the diagram fills the whole screen. /// - public static void SetFitToScreen(this RendererModel model, bool value) + public static void SetFitToScreen(this RendererModel model, bool value) { const string key = "FitToScreen"; model.Parameters[key] = value; } - public static bool HasFitToScreen(this RendererModel model) - { + public static bool HasFitToScreen(this RendererModel model) + { const string key = "FitToScreen"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultScale = 1; + public static readonly double DefaultScale = 1; /// /// Get the scale is the factor to multiply model coordinates by to convert the coordinates to screen space coordinate, such that the entire structure fits the visible screen dimension. Default value is 1. @@ -1086,19 +1086,19 @@ public static double GetScale(this RendererModel model) /// /// Set the scale is the factor to multiply model coordinates by to convert the coordinates to screen space coordinate, such that the entire structure fits the visible screen dimension. /// - public static void SetScale(this RendererModel model, double value) + public static void SetScale(this RendererModel model, double value) { const string key = "Scale"; model.Parameters[key] = value; } - public static bool HasScale(this RendererModel model) - { + public static bool HasScale(this RendererModel model) + { const string key = "Scale"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultBackgroundColor = WPF.Media.Colors.White; + public static readonly WPF.Media.Color DefaultBackgroundColor = WPF.Media.Colors.White; /// /// Get the background color of the drawn image. Default value is WPF.Media.Colors.White. @@ -1119,19 +1119,19 @@ public static WPF.Media.Color GetBackgroundColor(this RendererModel model) /// /// Set the background color of the drawn image. /// - public static void SetBackgroundColor(this RendererModel model, WPF.Media.Color value) + public static void SetBackgroundColor(this RendererModel model, WPF.Media.Color value) { const string key = "BackgroundColor"; model.Parameters[key] = value; } - public static bool HasBackgroundColor(this RendererModel model) - { + public static bool HasBackgroundColor(this RendererModel model) + { const string key = "BackgroundColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultBondLength = 40; + public static readonly double DefaultBondLength = 40; /// /// Get the length on the screen of a typical bond. Default value is 40. @@ -1152,19 +1152,19 @@ public static double GetBondLength(this RendererModel model) /// /// Set the length on the screen of a typical bond. /// - public static void SetBondLength(this RendererModel model, double value) + public static void SetBondLength(this RendererModel model, double value) { const string key = "BondLength"; model.Parameters[key] = value; } - public static bool HasBondLength(this RendererModel model) - { + public static bool HasBondLength(this RendererModel model) + { const string key = "BondLength"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultForegroundColor = WPF.Media.Colors.Black; + public static readonly WPF.Media.Color DefaultForegroundColor = WPF.Media.Colors.Black; /// /// Get the foreground color, with which objects are drawn. Default value is WPF.Media.Colors.Black. @@ -1185,19 +1185,19 @@ public static WPF.Media.Color GetForegroundColor(this RendererModel model) /// /// Set the foreground color, with which objects are drawn. /// - public static void SetForegroundColor(this RendererModel model, WPF.Media.Color value) + public static void SetForegroundColor(this RendererModel model, WPF.Media.Color value) { const string key = "ForegroundColor"; model.Parameters[key] = value; } - public static bool HasForegroundColor(this RendererModel model) - { + public static bool HasForegroundColor(this RendererModel model) + { const string key = "ForegroundColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultUseAntiAliasing = true; + public static readonly bool DefaultUseAntiAliasing = true; /// /// Get if set to true, uses anti-aliasing for drawing. Default value is true. @@ -1218,19 +1218,19 @@ public static bool GetUseAntiAliasing(this RendererModel model) /// /// Set if set to true, uses anti-aliasing for drawing. /// - public static void SetUseAntiAliasing(this RendererModel model, bool value) + public static void SetUseAntiAliasing(this RendererModel model, bool value) { const string key = "UseAntiAliasing"; model.Parameters[key] = value; } - public static bool HasUseAntiAliasing(this RendererModel model) - { + public static bool HasUseAntiAliasing(this RendererModel model) + { const string key = "UseAntiAliasing"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultMargin = 10; + public static readonly double DefaultMargin = 10; /// /// Get area on each of the four margins to keep empty. Default value is 10. @@ -1251,19 +1251,19 @@ public static double GetMargin(this RendererModel model) /// /// Set area on each of the four margins to keep empty. /// - public static void SetMargin(this RendererModel model, double value) + public static void SetMargin(this RendererModel model, double value) { const string key = "Margin"; model.Parameters[key] = value; } - public static bool HasMargin(this RendererModel model) - { + public static bool HasMargin(this RendererModel model) + { const string key = "Margin"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly Fonts.FontWeight DefaultUsedFontStyle = Fonts.FontWeight.Normal; + public static readonly Fonts.FontWeight DefaultUsedFontStyle = Fonts.FontWeight.Normal; /// /// Get the font style to use for text. Default value is Fonts.FontWeight.Normal. @@ -1284,19 +1284,19 @@ public static Fonts.FontWeight GetUsedFontStyle(this RendererModel model) /// /// Set the font style to use for text. /// - public static void SetUsedFontStyle(this RendererModel model, Fonts.FontWeight value) + public static void SetUsedFontStyle(this RendererModel model, Fonts.FontWeight value) { const string key = "UsedFontStyle"; model.Parameters[key] = value; } - public static bool HasUsedFontStyle(this RendererModel model) - { + public static bool HasUsedFontStyle(this RendererModel model) + { const string key = "UsedFontStyle"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly string DefaultFontName = "Arial"; + public static readonly string DefaultFontName = "Arial"; /// /// Get font name to use for text. Default value is "Arial". @@ -1317,19 +1317,19 @@ public static string GetFontName(this RendererModel model) /// /// Set font name to use for text. /// - public static void SetFontName(this RendererModel model, string value) + public static void SetFontName(this RendererModel model, string value) { const string key = "FontName"; model.Parameters[key] = value; } - public static bool HasFontName(this RendererModel model) - { + public static bool HasFontName(this RendererModel model) + { const string key = "FontName"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultZoomFactor = 1; + public static readonly double DefaultZoomFactor = 1; /// /// Get the zoom factor which is a user oriented parameter allowing the user to zoom in on parts of the molecule. Default value is 1. @@ -1350,19 +1350,19 @@ public static double GetZoomFactor(this RendererModel model) /// /// Set the zoom factor which is a user oriented parameter allowing the user to zoom in on parts of the molecule. /// - public static void SetZoomFactor(this RendererModel model, double value) + public static void SetZoomFactor(this RendererModel model, double value) { const string key = "ZoomFactor"; model.Parameters[key] = value; } - public static bool HasZoomFactor(this RendererModel model) - { + public static bool HasZoomFactor(this RendererModel model) + { const string key = "ZoomFactor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultAtomColorByType = false; + public static readonly bool DefaultAtomColorByType = false; /// /// Get triggers atoms to be colored by type when set to true. Default value is false. @@ -1383,19 +1383,19 @@ public static bool GetAtomColorByType(this RendererModel model) /// /// Set triggers atoms to be colored by type when set to true. /// - public static void SetAtomColorByType(this RendererModel model, bool value) + public static void SetAtomColorByType(this RendererModel model, bool value) { const string key = "AtomColorByType"; model.Parameters[key] = value; } - public static bool HasAtomColorByType(this RendererModel model) - { + public static bool HasAtomColorByType(this RendererModel model) + { const string key = "AtomColorByType"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowExplicitHydrogens = true; + public static readonly bool DefaultShowExplicitHydrogens = true; /// /// Get boolean property that triggers explicit hydrogens to be drawn if set to true. Default value is true. @@ -1416,19 +1416,19 @@ public static bool GetShowExplicitHydrogens(this RendererModel model) /// /// Set boolean property that triggers explicit hydrogens to be drawn if set to true. /// - public static void SetShowExplicitHydrogens(this RendererModel model, bool value) + public static void SetShowExplicitHydrogens(this RendererModel model, bool value) { const string key = "ShowExplicitHydrogens"; model.Parameters[key] = value; } - public static bool HasShowExplicitHydrogens(this RendererModel model) - { + public static bool HasShowExplicitHydrogens(this RendererModel model) + { const string key = "ShowExplicitHydrogens"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowImplicitHydrogens = false; + public static readonly bool DefaultShowImplicitHydrogens = false; /// /// Get indicates implicit hydrogens should be depicted. Default value is false. @@ -1449,19 +1449,19 @@ public static bool GetShowImplicitHydrogens(this RendererModel model) /// /// Set indicates implicit hydrogens should be depicted. /// - public static void SetShowImplicitHydrogens(this RendererModel model, bool value) + public static void SetShowImplicitHydrogens(this RendererModel model, bool value) { const string key = "ShowImplicitHydrogens"; model.Parameters[key] = value; } - public static bool HasShowImplicitHydrogens(this RendererModel model) - { + public static bool HasShowImplicitHydrogens(this RendererModel model) + { const string key = "ShowImplicitHydrogens"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultAtomRadius = 8; + public static readonly double DefaultAtomRadius = 8; /// /// Get magic number with unknown units that defines the radius around an atom, e.g. used for highlighting atoms. Default value is 8. @@ -1482,19 +1482,19 @@ public static double GetAtomRadius(this RendererModel model) /// /// Set magic number with unknown units that defines the radius around an atom, e.g. used for highlighting atoms. /// - public static void SetAtomRadius(this RendererModel model, double value) + public static void SetAtomRadius(this RendererModel model, double value) { const string key = "AtomRadius"; model.Parameters[key] = value; } - public static bool HasAtomRadius(this RendererModel model) - { + public static bool HasAtomRadius(this RendererModel model) + { const string key = "AtomRadius"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultCompactAtom = false; + public static readonly bool DefaultCompactAtom = false; /// /// Get atoms to be drawn as filled shapes. Default value is false. @@ -1515,19 +1515,19 @@ public static bool GetCompactAtom(this RendererModel model) /// /// Set atoms to be drawn as filled shapes. /// - public static void SetCompactAtom(this RendererModel model, bool value) + public static void SetCompactAtom(this RendererModel model, bool value) { const string key = "CompactAtom"; model.Parameters[key] = value; } - public static bool HasCompactAtom(this RendererModel model) - { + public static bool HasCompactAtom(this RendererModel model) + { const string key = "CompactAtom"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultKekuleStructure = false; + public static readonly bool DefaultKekuleStructure = false; /// /// Get whether structures should be drawn as Kekulé structures, thus giving each carbon element explicitly, instead of not displaying the element symbol. Example C-C-C instead of /". Default value is false. @@ -1548,19 +1548,19 @@ public static bool GetKekuleStructure(this RendererModel model) /// /// Set whether structures should be drawn as Kekulé structures, thus giving each carbon element explicitly, instead of not displaying the element symbol. Example C-C-C instead of /". /// - public static void SetKekuleStructure(this RendererModel model, bool value) + public static void SetKekuleStructure(this RendererModel model, bool value) { const string key = "KekuleStructure"; model.Parameters[key] = value; } - public static bool HasKekuleStructure(this RendererModel model) - { + public static bool HasKekuleStructure(this RendererModel model) + { const string key = "KekuleStructure"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly AtomShapeType DefaultCompactShape = AtomShapeType.Square; + public static readonly AtomShapeType DefaultCompactShape = AtomShapeType.Square; /// /// Get Shape to be used when drawing atoms in compact mode, as defined by the parameter. Default value is AtomShapeType.Square. @@ -1581,19 +1581,19 @@ public static AtomShapeType GetCompactShape(this RendererModel model) /// /// Set Shape to be used when drawing atoms in compact mode, as defined by the parameter. /// - public static void SetCompactShape(this RendererModel model, AtomShapeType value) + public static void SetCompactShape(this RendererModel model, AtomShapeType value) { const string key = "CompactShape"; model.Parameters[key] = value; } - public static bool HasCompactShape(this RendererModel model) - { + public static bool HasCompactShape(this RendererModel model) + { const string key = "CompactShape"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowEndCarbons = false; + public static readonly bool DefaultShowEndCarbons = false; /// /// Get show carbons with only one (non-hydrogen) neighbor to be drawn with an element symbol. Default value is false. @@ -1614,19 +1614,19 @@ public static bool GetShowEndCarbons(this RendererModel model) /// /// Set show carbons with only one (non-hydrogen) neighbor to be drawn with an element symbol. /// - public static void SetShowEndCarbons(this RendererModel model, bool value) + public static void SetShowEndCarbons(this RendererModel model, bool value) { const string key = "ShowEndCarbons"; model.Parameters[key] = value; } - public static bool HasShowEndCarbons(this RendererModel model) - { + public static bool HasShowEndCarbons(this RendererModel model) + { const string key = "ShowEndCarbons"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowAtomTypeNames = false; + public static readonly bool DefaultShowAtomTypeNames = false; /// /// Get indicates atom type names should be given instead of element symbols. Default value is false. @@ -1647,19 +1647,19 @@ public static bool GetShowAtomTypeNames(this RendererModel model) /// /// Set indicates atom type names should be given instead of element symbols. /// - public static void SetShowAtomTypeNames(this RendererModel model, bool value) + public static void SetShowAtomTypeNames(this RendererModel model, bool value) { const string key = "ShowAtomTypeNames"; model.Parameters[key] = value; } - public static bool HasShowAtomTypeNames(this RendererModel model) - { + public static bool HasShowAtomTypeNames(this RendererModel model) + { const string key = "ShowAtomTypeNames"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultAtomNumberTextColor = WPF.Media.Colors.Black; + public static readonly WPF.Media.Color DefaultAtomNumberTextColor = WPF.Media.Colors.Black; /// /// Get color to draw the atom numbers with. Default value is WPF.Media.Colors.Black. @@ -1680,19 +1680,19 @@ public static WPF.Media.Color GetAtomNumberTextColor(this RendererModel model) /// /// Set color to draw the atom numbers with. /// - public static void SetAtomNumberTextColor(this RendererModel model, WPF.Media.Color value) + public static void SetAtomNumberTextColor(this RendererModel model, WPF.Media.Color value) { const string key = "AtomNumberTextColor"; model.Parameters[key] = value; } - public static bool HasAtomNumberTextColor(this RendererModel model) - { + public static bool HasAtomNumberTextColor(this RendererModel model) + { const string key = "AtomNumberTextColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultWillDrawAtomNumbers = true; + public static readonly bool DefaultWillDrawAtomNumbers = true; /// /// Get indicating if atom numbers should be drawn, allowing this feature to be disabled temporarily. Default value is true. @@ -1713,19 +1713,19 @@ public static bool GetWillDrawAtomNumbers(this RendererModel model) /// /// Set indicating if atom numbers should be drawn, allowing this feature to be disabled temporarily. /// - public static void SetWillDrawAtomNumbers(this RendererModel model, bool value) + public static void SetWillDrawAtomNumbers(this RendererModel model, bool value) { const string key = "WillDrawAtomNumbers"; model.Parameters[key] = value; } - public static bool HasWillDrawAtomNumbers(this RendererModel model) - { + public static bool HasWillDrawAtomNumbers(this RendererModel model) + { const string key = "WillDrawAtomNumbers"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly IAtomColorer DefaultAtomNumberColorer = new CDK2DAtomColors(); + public static readonly IAtomColorer DefaultAtomNumberColorer = new CDK2DAtomColors(); /// /// Get the color scheme by which to color the atom numbers. Default value is new CDK2DAtomColors(). @@ -1746,19 +1746,19 @@ public static IAtomColorer GetAtomNumberColorer(this RendererModel model) /// /// Set the color scheme by which to color the atom numbers. /// - public static void SetAtomNumberColorer(this RendererModel model, IAtomColorer value) + public static void SetAtomNumberColorer(this RendererModel model, IAtomColorer value) { const string key = "AtomNumberColorer"; model.Parameters[key] = value; } - public static bool HasAtomNumberColorer(this RendererModel model) - { + public static bool HasAtomNumberColorer(this RendererModel model) + { const string key = "AtomNumberColorer"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultAtomNumberColorByType = false; + public static readonly bool DefaultAtomNumberColorByType = false; /// /// Get indicate of the scheme will be used. Default value is false. @@ -1779,19 +1779,19 @@ public static bool GetAtomNumberColorByType(this RendererModel model) /// /// Set indicate of the scheme will be used. /// - public static void SetAtomNumberColorByType(this RendererModel model, bool value) + public static void SetAtomNumberColorByType(this RendererModel model, bool value) { const string key = "AtomNumberColorByType"; model.Parameters[key] = value; } - public static bool HasAtomNumberColorByType(this RendererModel model) - { + public static bool HasAtomNumberColorByType(this RendererModel model) + { const string key = "AtomNumberColorByType"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly Vector2 DefaultAtomNumberOffset = Vector2.Zero; + public static readonly Vector2 DefaultAtomNumberOffset = Vector2.Zero; /// /// Get offset vector in screen space coordinates where the atom number label will be placed. Default value is Vector2.Zero. @@ -1812,19 +1812,19 @@ public static Vector2 GetAtomNumberOffset(this RendererModel model) /// /// Set offset vector in screen space coordinates where the atom number label will be placed. /// - public static void SetAtomNumberOffset(this RendererModel model, Vector2 value) + public static void SetAtomNumberOffset(this RendererModel model, Vector2 value) { const string key = "AtomNumberOffset"; model.Parameters[key] = value; } - public static bool HasAtomNumberOffset(this RendererModel model) - { + public static bool HasAtomNumberOffset(this RendererModel model) + { const string key = "AtomNumberOffset"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultBondWidth = 1; + public static readonly double DefaultBondWidth = 1; /// /// Get the width on screen of a bond. Default value is 1. @@ -1845,19 +1845,19 @@ public static double GetBondWidth(this RendererModel model) /// /// Set the width on screen of a bond. /// - public static void SetBondWidth(this RendererModel model, double value) + public static void SetBondWidth(this RendererModel model, double value) { const string key = "BondWidth"; model.Parameters[key] = value; } - public static bool HasBondWidth(this RendererModel model) - { + public static bool HasBondWidth(this RendererModel model) + { const string key = "BondWidth"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultBondDistance = 2; + public static readonly double DefaultBondDistance = 2; /// /// Get the gap between double and triple bond lines on the screen. Default value is 2. @@ -1878,19 +1878,19 @@ public static double GetBondDistance(this RendererModel model) /// /// Set the gap between double and triple bond lines on the screen. /// - public static void SetBondDistance(this RendererModel model, double value) + public static void SetBondDistance(this RendererModel model, double value) { const string key = "BondDistance"; model.Parameters[key] = value; } - public static bool HasBondDistance(this RendererModel model) - { + public static bool HasBondDistance(this RendererModel model) + { const string key = "BondDistance"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultDefaultBondColor = WPF.Media.Colors.Black; + public static readonly WPF.Media.Color DefaultDefaultBondColor = WPF.Media.Colors.Black; /// /// Get the color to draw bonds if not other color is given. Default value is WPF.Media.Colors.Black. @@ -1911,19 +1911,19 @@ public static WPF.Media.Color GetDefaultBondColor(this RendererModel model) /// /// Set the color to draw bonds if not other color is given. /// - public static void SetDefaultBondColor(this RendererModel model, WPF.Media.Color value) + public static void SetDefaultBondColor(this RendererModel model, WPF.Media.Color value) { const string key = "DefaultBondColor"; model.Parameters[key] = value; } - public static bool HasDefaultBondColor(this RendererModel model) - { + public static bool HasDefaultBondColor(this RendererModel model) + { const string key = "DefaultBondColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultWedgeWidth = 2; + public static readonly double DefaultWedgeWidth = 2; /// /// Get the width on screen of the fat end of a wedge bond. Default value is 2. @@ -1944,19 +1944,19 @@ public static double GetWedgeWidth(this RendererModel model) /// /// Set the width on screen of the fat end of a wedge bond. /// - public static void SetWedgeWidth(this RendererModel model, double value) + public static void SetWedgeWidth(this RendererModel model, double value) { const string key = "WedgeWidth"; model.Parameters[key] = value; } - public static bool HasWedgeWidth(this RendererModel model) - { + public static bool HasWedgeWidth(this RendererModel model) + { const string key = "WedgeWidth"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultTowardsRingCenterProportion = 0.15; + public static readonly double DefaultTowardsRingCenterProportion = 0.15; /// /// Get the proportion to move in towards the ring center. Default value is 0.15. @@ -1977,19 +1977,19 @@ public static double GetTowardsRingCenterProportion(this RendererModel model) /// /// Set the proportion to move in towards the ring center. /// - public static void SetTowardsRingCenterProportion(this RendererModel model, double value) + public static void SetTowardsRingCenterProportion(this RendererModel model, double value) { const string key = "TowardsRingCenterProportion"; model.Parameters[key] = value; } - public static bool HasTowardsRingCenterProportion(this RendererModel model) - { + public static bool HasTowardsRingCenterProportion(this RendererModel model) + { const string key = "TowardsRingCenterProportion"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultForceDelocalisedBondDisplay = false; + public static readonly bool DefaultForceDelocalisedBondDisplay = false; /// /// Get Indicate delocalised/aromatic bonds should always be rendered, even when there is a valid Kekule structure. Delocalised bonds will either be rendered as a dashed bond to the side or as a circle/donut/life buoy inside small rings. This depiction is used by default when a bond does not have an order assigned (e.g. null/unset). Turning this option on means all delocalised bonds will be rendered this way. As recommended by IUPAC, their usage is discouraged and the Kekule representation is more clear.. Default value is false. @@ -2010,19 +2010,19 @@ public static bool GetForceDelocalisedBondDisplay(this RendererModel model) /// /// Set Indicate delocalised/aromatic bonds should always be rendered, even when there is a valid Kekule structure. Delocalised bonds will either be rendered as a dashed bond to the side or as a circle/donut/life buoy inside small rings. This depiction is used by default when a bond does not have an order assigned (e.g. null/unset). Turning this option on means all delocalised bonds will be rendered this way. As recommended by IUPAC, their usage is discouraged and the Kekule representation is more clear.. /// - public static void SetForceDelocalisedBondDisplay(this RendererModel model, bool value) + public static void SetForceDelocalisedBondDisplay(this RendererModel model, bool value) { const string key = "ForceDelocalisedBondDisplay"; model.Parameters[key] = value; } - public static bool HasForceDelocalisedBondDisplay(this RendererModel model) - { + public static bool HasForceDelocalisedBondDisplay(this RendererModel model) + { const string key = "ForceDelocalisedBondDisplay"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowAromaticity = true; + public static readonly bool DefaultShowAromaticity = true; /// /// Get whether rings should be drawn with a circle if they are aromatic. Default value is true. @@ -2043,19 +2043,19 @@ public static bool GetShowAromaticity(this RendererModel model) /// /// Set whether rings should be drawn with a circle if they are aromatic. /// - public static void SetShowAromaticity(this RendererModel model, bool value) + public static void SetShowAromaticity(this RendererModel model, bool value) { const string key = "ShowAromaticity"; model.Parameters[key] = value; } - public static bool HasShowAromaticity(this RendererModel model) - { + public static bool HasShowAromaticity(this RendererModel model) + { const string key = "ShowAromaticity"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultCDKStyleAromaticity = false; + public static readonly bool DefaultCDKStyleAromaticity = false; /// /// Get depicts aromaticity of rings in the original CDK style. Default value is false. @@ -2076,19 +2076,19 @@ public static bool GetCDKStyleAromaticity(this RendererModel model) /// /// Set depicts aromaticity of rings in the original CDK style. /// - public static void SetCDKStyleAromaticity(this RendererModel model, bool value) + public static void SetCDKStyleAromaticity(this RendererModel model, bool value) { const string key = "CDKStyleAromaticity"; model.Parameters[key] = value; } - public static bool HasCDKStyleAromaticity(this RendererModel model) - { + public static bool HasCDKStyleAromaticity(this RendererModel model) + { const string key = "CDKStyleAromaticity"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly int DefaultMaxDrawableAromaticRing = 8; + public static readonly int DefaultMaxDrawableAromaticRing = 8; /// /// Get the maximum ring size for which an aromatic ring should be drawn. Default value is 8. @@ -2109,19 +2109,19 @@ public static int GetMaxDrawableAromaticRing(this RendererModel model) /// /// Set the maximum ring size for which an aromatic ring should be drawn. /// - public static void SetMaxDrawableAromaticRing(this RendererModel model, int value) + public static void SetMaxDrawableAromaticRing(this RendererModel model, int value) { const string key = "MaxDrawableAromaticRing"; model.Parameters[key] = value; } - public static bool HasMaxDrawableAromaticRing(this RendererModel model) - { + public static bool HasMaxDrawableAromaticRing(this RendererModel model) + { const string key = "MaxDrawableAromaticRing"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultRingProportion = 0.35; + public static readonly double DefaultRingProportion = 0.35; /// /// Get the proportion of a ring bounds to use to draw the ring. Default value is 0.35. @@ -2142,19 +2142,19 @@ public static double GetRingProportion(this RendererModel model) /// /// Set the proportion of a ring bounds to use to draw the ring. /// - public static void SetRingProportion(this RendererModel model, double value) + public static void SetRingProportion(this RendererModel model, double value) { const string key = "RingProportion"; model.Parameters[key] = value; } - public static bool HasRingProportion(this RendererModel model) - { + public static bool HasRingProportion(this RendererModel model) + { const string key = "RingProportion"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowReactionBoxes = true; + public static readonly bool DefaultShowReactionBoxes = true; /// /// Get indicates if boxes are drawn around the reaction. Default value is true. @@ -2175,19 +2175,19 @@ public static bool GetShowReactionBoxes(this RendererModel model) /// /// Set indicates if boxes are drawn around the reaction. /// - public static void SetShowReactionBoxes(this RendererModel model, bool value) + public static void SetShowReactionBoxes(this RendererModel model, bool value) { const string key = "ShowReactionBoxes"; model.Parameters[key] = value; } - public static bool HasShowReactionBoxes(this RendererModel model) - { + public static bool HasShowReactionBoxes(this RendererModel model) + { const string key = "ShowReactionBoxes"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultAtomAtomMappingLineColor = WPF.Media.Colors.Gray; + public static readonly WPF.Media.Color DefaultAtomAtomMappingLineColor = WPF.Media.Colors.Gray; /// /// Get the color on screen of an atom-atom mapping line. Default value is WPF.Media.Colors.Gray. @@ -2208,19 +2208,19 @@ public static WPF.Media.Color GetAtomAtomMappingLineColor(this RendererModel mod /// /// Set the color on screen of an atom-atom mapping line. /// - public static void SetAtomAtomMappingLineColor(this RendererModel model, WPF.Media.Color value) + public static void SetAtomAtomMappingLineColor(this RendererModel model, WPF.Media.Color value) { const string key = "AtomAtomMappingLineColor"; model.Parameters[key] = value; } - public static bool HasAtomAtomMappingLineColor(this RendererModel model) - { + public static bool HasAtomAtomMappingLineColor(this RendererModel model) + { const string key = "AtomAtomMappingLineColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultMappingLineWidth = 1; + public static readonly double DefaultMappingLineWidth = 1; /// /// Get the width on screen of an atom-atom mapping line. Default value is 1. @@ -2241,19 +2241,19 @@ public static double GetMappingLineWidth(this RendererModel model) /// /// Set the width on screen of an atom-atom mapping line. /// - public static void SetMappingLineWidth(this RendererModel model, double value) + public static void SetMappingLineWidth(this RendererModel model, double value) { const string key = "MappingLineWidth"; model.Parameters[key] = value; } - public static bool HasMappingLineWidth(this RendererModel model) - { + public static bool HasMappingLineWidth(this RendererModel model) + { const string key = "MappingLineWidth"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly bool DefaultShowAtomAtomMapping = true; + public static readonly bool DefaultShowAtomAtomMapping = true; /// /// Get whether atom-atom mapping depiction can be temporarily disabled. Default value is true. @@ -2274,19 +2274,19 @@ public static bool GetShowAtomAtomMapping(this RendererModel model) /// /// Set whether atom-atom mapping depiction can be temporarily disabled. /// - public static void SetShowAtomAtomMapping(this RendererModel model, bool value) + public static void SetShowAtomAtomMapping(this RendererModel model, bool value) { const string key = "ShowAtomAtomMapping"; model.Parameters[key] = value; } - public static bool HasShowAtomAtomMapping(this RendererModel model) - { + public static bool HasShowAtomAtomMapping(this RendererModel model) + { const string key = "ShowAtomAtomMapping"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly double DefaultHighlightRadius = 10; + public static readonly double DefaultHighlightRadius = 10; /// /// Get the atom radius on screen used to provide the highlight colors. Default value is 10. @@ -2307,30 +2307,30 @@ public static double GetHighlightRadius(this RendererModel model) /// /// Set the atom radius on screen used to provide the highlight colors. /// - public static void SetHighlightRadius(this RendererModel model, double value) + public static void SetHighlightRadius(this RendererModel model, double value) { const string key = "HighlightRadius"; model.Parameters[key] = value; } - public static bool HasHighlightRadius(this RendererModel model) - { + public static bool HasHighlightRadius(this RendererModel model) + { const string key = "HighlightRadius"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly NCDK.Renderers.Generators.HighlightGenerator.IPalette DefaultHighlightPalette = NCDK.Renderers.Generators.HighlightGenerator.DefaultPalette; + public static readonly NCDK.Renderers.Generators.IPalette DefaultHighlightPalette = NCDK.Renderers.Generators.HighlightGenerator.DefaultPalette; /// /// Get color palette used to provide the highlight colors. Default value is NCDK.Renderers.Generators.HighlightGenerator.DefaultPalette. /// /// color palette used to provide the highlight colors - public static NCDK.Renderers.Generators.HighlightGenerator.IPalette GetHighlightPalette(this RendererModel model) + public static NCDK.Renderers.Generators.IPalette GetHighlightPalette(this RendererModel model) { const string key = "HighlightPalette"; - NCDK.Renderers.Generators.HighlightGenerator.IPalette value; + NCDK.Renderers.Generators.IPalette value; if (model.Parameters.TryGetValue(key, out object v)) - value = (NCDK.Renderers.Generators.HighlightGenerator.IPalette)v; + value = (NCDK.Renderers.Generators.IPalette)v; else model.Parameters[key] = value = DefaultHighlightPalette; @@ -2340,19 +2340,19 @@ public static NCDK.Renderers.Generators.HighlightGenerator.IPalette GetHighlight /// /// Set color palette used to provide the highlight colors. /// - public static void SetHighlightPalette(this RendererModel model, NCDK.Renderers.Generators.HighlightGenerator.IPalette value) + public static void SetHighlightPalette(this RendererModel model, NCDK.Renderers.Generators.IPalette value) { const string key = "HighlightPalette"; model.Parameters[key] = value; } - public static bool HasHighlightPalette(this RendererModel model) - { + public static bool HasHighlightPalette(this RendererModel model) + { const string key = "HighlightPalette"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } - public static readonly WPF.Media.Color DefaultBoundsColor = WPF.Media.Colors.LightGray; + public static readonly WPF.Media.Color DefaultBoundsColor = WPF.Media.Colors.LightGray; /// /// Get the color of the box drawn at the bounds of a molecule, molecule set, or reaction. Default value is WPF.Media.Colors.LightGray. @@ -2373,17 +2373,17 @@ public static WPF.Media.Color GetBoundsColor(this RendererModel model) /// /// Set the color of the box drawn at the bounds of a molecule, molecule set, or reaction. /// - public static void SetBoundsColor(this RendererModel model, WPF.Media.Color value) + public static void SetBoundsColor(this RendererModel model, WPF.Media.Color value) { const string key = "BoundsColor"; model.Parameters[key] = value; } - public static bool HasBoundsColor(this RendererModel model) - { + public static bool HasBoundsColor(this RendererModel model) + { const string key = "BoundsColor"; - return model.Parameters.ContainsKey(key); - } + return model.Parameters.ContainsKey(key); + } } } diff --git a/NCDKDisplay/Renderers/Visitors/AbstractWPFDrawVisitor.cs b/NCDKDisplay/Renderers/Visitors/AbstractWPFDrawVisitor.cs index a77cd318..79704d33 100644 --- a/NCDKDisplay/Renderers/Visitors/AbstractWPFDrawVisitor.cs +++ b/NCDKDisplay/Renderers/Visitors/AbstractWPFDrawVisitor.cs @@ -40,7 +40,7 @@ public abstract class AbstractWPFDrawVisitor : IDrawVisitor /// the text string /// the world x-coordinate of where the text should be placed /// the screen coordinates - protected internal WPF.Rect GetTextBounds(string text, WPF::Point coord, Typeface typeface, double emSize) + internal static WPF.Rect GetTextBounds(string text, WPF::Point coord, Typeface typeface, double emSize) { var ft = new FormattedText(text, CultureInfo.CurrentCulture, WPF.FlowDirection.LeftToRight, typeface, emSize, Brushes.Black); var bounds = new WPF.Rect(0, 0, ft.Width, ft.Height); @@ -65,7 +65,7 @@ protected internal WPF.Rect GetTextBounds(string text, WPF::Point coord, Typefac /// the text string /// the world coordinate of where the text should be placed /// the screen coordinates - protected internal WPF.Point GetTextBasePoint(string text, WPF.Point coord, Typeface typeface, double emSize) + internal static WPF.Point GetTextBasePoint(string text, WPF.Point coord, Typeface typeface, double emSize) { var ft = new FormattedText(text, CultureInfo.CurrentCulture, WPF.FlowDirection.LeftToRight, typeface, emSize, Brushes.Black); var stringBounds = new WPF.Rect(0, 0, ft.Width, ft.Height); @@ -84,7 +84,7 @@ protected internal WPF.Point GetTextBasePoint(string text, WPF.Point coord, Type /// the text to obtain the bounds of /// bounds of the text /// - protected internal WPF.Rect GetTextBounds(string text, Typeface typeface, double emSize) + internal static WPF.Rect GetTextBounds(string text, Typeface typeface, double emSize) { var ft = new FormattedText(text, CultureInfo.CurrentCulture, WPF.FlowDirection.LeftToRight, typeface, emSize, Brushes.Black); return new WPF.Rect(0, 0, ft.Width, ft.Height); diff --git a/NCDKDisplay/Renderers/Visitors/WPFDrawVisitor.cs b/NCDKDisplay/Renderers/Visitors/WPFDrawVisitor.cs index c9e40427..c00b6c80 100644 --- a/NCDKDisplay/Renderers/Visitors/WPFDrawVisitor.cs +++ b/NCDKDisplay/Renderers/Visitors/WPFDrawVisitor.cs @@ -238,8 +238,8 @@ private Color BackgroundColor private void Visit(TextElement textElement) { - var point = this.GetTextBasePoint(textElement.Text, textElement.Coord, this.fontManager.Typeface, this.fontManager.Size); - var textBounds = this.GetTextBounds(textElement.Text, textElement.Coord, this.fontManager.Typeface, this.fontManager.Size); + var point = GetTextBasePoint(textElement.Text, textElement.Coord, this.fontManager.Typeface, this.fontManager.Size); + var textBounds = GetTextBounds(textElement.Text, textElement.Coord, this.fontManager.Typeface, this.fontManager.Size); var backColor = this.BackgroundColor; this.dc.DrawRectangle(GetBrush(backColor), null, textBounds); this.dc.DrawText(new FormattedText( diff --git a/NCDKDisplayTests/Depict/AbbreviationsTest.cs b/NCDKDisplayTests/Depict/AbbreviationsTest.cs index c50e0089..172c6bf3 100644 --- a/NCDKDisplayTests/Depict/AbbreviationsTest.cs +++ b/NCDKDisplayTests/Depict/AbbreviationsTest.cs @@ -162,7 +162,7 @@ public void DontOverwriteExistingSgroups() sgroup.Atoms.Add(mol.Atoms[8]); sgroup.Type = SgroupType.CtabAbbreviation; sgroup.Subscript = "n-Bu"; - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup }); + mol.SetCtabSgroups(new[] { sgroup }); var sgroups = factory.Generate(mol); Assert.AreEqual(0, sgroups.Count); } diff --git a/NCDKDisplayTests/NCDK.DisplayTests.csproj b/NCDKDisplayTests/NCDK.DisplayTests.csproj index e13bf117..05aad30b 100644 --- a/NCDKDisplayTests/NCDK.DisplayTests.csproj +++ b/NCDKDisplayTests/NCDK.DisplayTests.csproj @@ -75,16 +75,6 @@ - - - {60b8bebc-9968-44a7-ab0b-11c03116579d} - NCDK.Display - - - {b0b5eacf-5f39-42d0-bacd-1ff559ccc8b2} - NCDK - - @@ -158,6 +148,16 @@ + + + {60b8bebc-9968-44a7-ab0b-11c03116579d} + NCDK.Display + + + {b0b5eacf-5f39-42d0-bacd-1ff559ccc8b2} + NCDK + + diff --git a/NCDKDisplayTests/Renderers/BoundsCalculatorTest.cs b/NCDKDisplayTests/Renderers/BoundsCalculatorTest.cs index 8758e986..8802b908 100644 --- a/NCDKDisplayTests/Renderers/BoundsCalculatorTest.cs +++ b/NCDKDisplayTests/Renderers/BoundsCalculatorTest.cs @@ -21,7 +21,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Renderers diff --git a/NCDKDisplayTests/Renderers/Colors/CDK2DAtomColorsTest.cs b/NCDKDisplayTests/Renderers/Colors/CDK2DAtomColorsTest.cs index 8fcda0bc..b4588661 100644 --- a/NCDKDisplayTests/Renderers/Colors/CDK2DAtomColorsTest.cs +++ b/NCDKDisplayTests/Renderers/Colors/CDK2DAtomColorsTest.cs @@ -21,7 +21,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Windows.Media; using WPF = System.Windows; diff --git a/NCDKDisplayTests/Renderers/Colors/CDKAtomColorsTest.cs b/NCDKDisplayTests/Renderers/Colors/CDKAtomColorsTest.cs index 88827fb1..aafa6b24 100644 --- a/NCDKDisplayTests/Renderers/Colors/CDKAtomColorsTest.cs +++ b/NCDKDisplayTests/Renderers/Colors/CDKAtomColorsTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using WPF = System.Windows; namespace NCDK.Renderers.Colors diff --git a/NCDKDisplayTests/Renderers/Colors/CPKAtomColorsTest.cs b/NCDKDisplayTests/Renderers/Colors/CPKAtomColorsTest.cs index 3b755d10..e5dcf30f 100644 --- a/NCDKDisplayTests/Renderers/Colors/CPKAtomColorsTest.cs +++ b/NCDKDisplayTests/Renderers/Colors/CPKAtomColorsTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using WPF = System.Windows; namespace NCDK.Renderers.Colors diff --git a/NCDKDisplayTests/Renderers/Colors/PartialAtomicChargeColorsTest.cs b/NCDKDisplayTests/Renderers/Colors/PartialAtomicChargeColorsTest.cs index f4288a42..c43eb307 100644 --- a/NCDKDisplayTests/Renderers/Colors/PartialAtomicChargeColorsTest.cs +++ b/NCDKDisplayTests/Renderers/Colors/PartialAtomicChargeColorsTest.cs @@ -21,7 +21,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using WPF = System.Windows; namespace NCDK.Renderers.Colors diff --git a/NCDKDisplayTests/Renderers/Colors/RasmolColorsTest.cs b/NCDKDisplayTests/Renderers/Colors/RasmolColorsTest.cs index dcdb9c8e..ebca2b46 100644 --- a/NCDKDisplayTests/Renderers/Colors/RasmolColorsTest.cs +++ b/NCDKDisplayTests/Renderers/Colors/RasmolColorsTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using WPF = System.Windows; namespace NCDK.Renderers.Colors diff --git a/NCDKDisplayTests/Renderers/Generators/Standards/SelectionVisibilityTest.cs b/NCDKDisplayTests/Renderers/Generators/Standards/SelectionVisibilityTest.cs index 32effcae..b62ae859 100644 --- a/NCDKDisplayTests/Renderers/Generators/Standards/SelectionVisibilityTest.cs +++ b/NCDKDisplayTests/Renderers/Generators/Standards/SelectionVisibilityTest.cs @@ -1,8 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using NCDK.Default; using NCDK.Numerics; -using System.Windows.Media; +using NCDK.Silent; using WPF = System.Windows; namespace NCDK.Renderers.Generators.Standards diff --git a/NCDKDisplayTests/Renderers/RendererModelTest.cs b/NCDKDisplayTests/Renderers/RendererModelTest.cs index 1675809b..7fea12d1 100644 --- a/NCDKDisplayTests/Renderers/RendererModelTest.cs +++ b/NCDKDisplayTests/Renderers/RendererModelTest.cs @@ -21,11 +21,11 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Events; using NCDK.Renderers.Elements; using NCDK.Renderers.Generators; using NCDK.Renderers.Selection; +using NCDK.Silent; using System.Collections.Generic; namespace NCDK.Renderers diff --git a/NCDKDisplayTests/Renderers/SymbolVisibilityTest.cs b/NCDKDisplayTests/Renderers/SymbolVisibilityTest.cs index 9f9c5a45..5e8c79a7 100644 --- a/NCDKDisplayTests/Renderers/SymbolVisibilityTest.cs +++ b/NCDKDisplayTests/Renderers/SymbolVisibilityTest.cs @@ -23,8 +23,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Numerics; +using NCDK.Silent; using System; namespace NCDK.Renderers diff --git a/NCDKDisplayTests/Renderers/Visitor/AbstractWPFDrawVisitorTest.cs b/NCDKDisplayTests/Renderers/Visitor/AbstractWPFDrawVisitorTest.cs index 651aaadc..0fa9bf16 100644 --- a/NCDKDisplayTests/Renderers/Visitor/AbstractWPFDrawVisitorTest.cs +++ b/NCDKDisplayTests/Renderers/Visitor/AbstractWPFDrawVisitorTest.cs @@ -55,26 +55,24 @@ public void TestSetAffineTransformation() [TestMethod()] public void TestGetTextBounds() { - AbstractWPFDrawVisitor visitor = new NestedAWTDrawVisitor(); var typeface = new Typeface( new FontFamily("Arial"), WPF::FontStyles.Normal, WPF::FontWeights.Normal, WPF::FontStretches.Normal); - var rectangle = visitor.GetTextBounds("Foo", new WPF.Point(3, 5), typeface, 9); + var rectangle = AbstractWPFDrawVisitor.GetTextBounds("Foo", new WPF.Point(3, 5), typeface, 9); Assert.IsNotNull(rectangle); } [TestMethod()] public void TestGetTextBasePoint() { - AbstractWPFDrawVisitor visitor = new NestedAWTDrawVisitor(); var typeface = new Typeface( new FontFamily("Arial"), WPF::FontStyles.Normal, WPF::FontWeights.Normal, WPF::FontStretches.Normal); - var point = visitor.GetTextBasePoint("Foo", new WPF.Point(3, 5), typeface, 9); + var point = AbstractWPFDrawVisitor.GetTextBasePoint("Foo", new WPF.Point(3, 5), typeface, 9); Assert.IsNotNull(point); } } diff --git a/NCDKTests/AbstractAtomContainerTest.cs b/NCDKTests/AbstractAtomContainerTest.cs index 6929f5c3..6daaa94d 100644 --- a/NCDKTests/AbstractAtomContainerTest.cs +++ b/NCDKTests/AbstractAtomContainerTest.cs @@ -918,7 +918,7 @@ public virtual void TestRemoveAllElements_StereoElements() container.RemoveAllElements(); - foreach (IReadOnlyStereoElement element in container.StereoElements) + foreach (IStereoElement element in container.StereoElements) { count++; } @@ -968,7 +968,7 @@ public virtual void TestRemoveAtom_IAtom() } [TestMethod()] - [ExpectedException(typeof(IndexOutOfRangeException))] + [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestSetAtomOutOfRange() { IAtomContainer container = (IAtomContainer)NewChemObject(); @@ -988,7 +988,7 @@ public void TestSetAtom() } [TestMethod()] - [ExpectedException(typeof(ArgumentException), AllowDerivedTypes = true)] + [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = true)] public void TestSetAtomSameMolecule() { IAtomContainer container = (IAtomContainer)NewChemObject(); @@ -1082,7 +1082,7 @@ public void TestSetAtomUpdatesAtomStereo() container.AddBond(container.Atoms[0], container.Atoms[2], BondOrder.Single); container.AddBond(container.Atoms[0], container.Atoms[3], BondOrder.Single); container.AddBond(container.Atoms[0], container.Atoms[4], BondOrder.Single); - container.StereoElements.Add(new TetrahedralChirality(container.Atoms[0], container.Atoms.Skip(1).Take(4), TetrahedralStereo.Clockwise)); + container.StereoElements.Add(new TetrahedralChirality(container.Atoms[0], container.Atoms.Skip(1).Take(4).ToList(), TetrahedralStereo.Clockwise)); IAtom aNew = bldr.NewAtom(); container.Atoms[2] = aNew; @@ -3189,12 +3189,12 @@ public void CloneSgroups() sgroup.Atoms.Add(a2); sgroup.Bonds.Add(b1); sgroup.Bonds.Add(b2); - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup }); - IAtomContainer clone = (IAtomContainer)mol.Clone(); - ICollection sgroups = clone.GetProperty>(CDKPropertyName.CtabSgroups); + mol.SetCtabSgroups(new[] { sgroup }); + var clone = (IAtomContainer)mol.Clone(); + var sgroups = clone.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(1, sgroups.Count); - Sgroup clonedSgroup = sgroups.First(); + var clonedSgroup = sgroups.First(); Assert.AreEqual(SgroupType.CtabStructureRepeatUnit, clonedSgroup.Type); Assert.AreEqual("n", clonedSgroup.Subscript); Assert.IsFalse(clonedSgroup.Atoms.Contains(a2)); diff --git a/NCDKTests/AbstractAtomTest.cs b/NCDKTests/AbstractAtomTest.cs index b4049806..a8dac2e7 100644 --- a/NCDKTests/AbstractAtomTest.cs +++ b/NCDKTests/AbstractAtomTest.cs @@ -34,7 +34,7 @@ public abstract class AbstractAtomTest : AbstractAtomTypeTest /// Method to test the get/SetCharge() methods. /// [TestMethod()] - public virtual void TestSetCharge_Double() + public virtual void TestSetChargeDouble() { double charge = 0.15; @@ -46,14 +46,14 @@ public virtual void TestSetCharge_Double() [TestMethod()] public virtual void TestGetCharge() { - TestSetCharge_Double(); + TestSetChargeDouble(); } /// /// Method to test the get/SetHydrogenCount() methods. /// [TestMethod()] - public virtual void TestSetImplicitHydrogenCount_Integer() + public virtual void TestSetImplicitHydrogenCountInteger() { int count = 1; @@ -74,7 +74,7 @@ public virtual void TestGetImplicitHydrogenCount() /// Method to test the SetFractional3D() methods. /// [TestMethod()] - public virtual void TestSetFractionalPoint3d_Point3d() + public virtual void TestSetFractionalPoint3dPoint3d() { IAtom a = (IAtom)NewChemObject(); a.FractionalPoint3D = new Vector3(0.5, 0.5, 0.5); @@ -88,7 +88,7 @@ public virtual void TestSetFractionalPoint3d_Point3d() [TestMethod()] public virtual void TestGetFractionalPoint3d() { - TestSetFractionalPoint3d_Point3d(); + TestSetFractionalPoint3dPoint3d(); } [TestMethod()] @@ -103,7 +103,7 @@ public virtual void TestGetPoint3d() } [TestMethod()] - public virtual void TestSetPoint3d_Point3d() + public virtual void TestSetPoint3dPoint3d() { Vector3 point3d = new Vector3(1, 2, 3); @@ -125,7 +125,7 @@ public virtual void TestGetPoint2d() } [TestMethod()] - public virtual void TestSetPoint2d_Point2d() + public virtual void TestSetPoint2dPoint2d() { Vector2 point2d = new Vector2(1, 2); @@ -138,10 +138,10 @@ public virtual void TestSetPoint2d_Point2d() /// Method to test the get/SetHydrogenCount() methods. /// [TestMethod()] - public virtual void TestSetStereoParity_Integer() + public virtual void TestSetStereoParityInteger() { var parity = StereoAtomParities.Plus; - IAtom a = (IAtom)NewChemObject(); + var a = (IAtom)NewChemObject(); a.StereoParity = parity; Assert.AreEqual(parity, a.StereoParity); } @@ -149,7 +149,7 @@ public virtual void TestSetStereoParity_Integer() [TestMethod()] public virtual void TestGetStereoParity() { - TestSetStereoParity_Integer(); + TestSetStereoParityInteger(); } /// @@ -172,7 +172,7 @@ public override void TestClone() /// Method to test the Clone() method /// [TestMethod()] - public virtual void TestClone_Point2d() + public virtual void TestClonePoint2d() { IAtom atom = (IAtom)NewChemObject(); atom.Point2D = new Vector2(2, 3); @@ -181,10 +181,10 @@ public virtual void TestClone_Point2d() } /// - /// Method to test the Clone() method + /// Method to test the method /// [TestMethod()] - public virtual void TestClone_Point3d() + public virtual void TestClonePoint3d() { IAtom atom = (IAtom)NewChemObject(); atom.Point3D = new Vector3(2, 3, 4); @@ -193,10 +193,10 @@ public virtual void TestClone_Point3d() } /// - /// Method to test the Clone() method + /// Method to test the method /// [TestMethod()] - public virtual void TestClone_FractionalPoint3d() + public virtual void TestCloneFractionalPoint3d() { IAtom atom = (IAtom)NewChemObject(); atom.FractionalPoint3D = new Vector3(2, 3, 4); @@ -205,10 +205,10 @@ public virtual void TestClone_FractionalPoint3d() } /// - /// Method to test the Clone() method + /// Method to test the method /// [TestMethod()] - public virtual void TestClone_HydrogenCount() + public virtual void TestCloneHydrogenCount() { IAtom atom = (IAtom)NewChemObject(); atom.ImplicitHydrogenCount = 3; @@ -220,10 +220,10 @@ public virtual void TestClone_HydrogenCount() } /// - /// Method to test the Clone() method + /// Method to test the method /// [TestMethod()] - public virtual void TestClone_StereoParity() + public virtual void TestCloneStereoParity() { IAtom atom = (IAtom)NewChemObject(); atom.StereoParity = 3; @@ -235,10 +235,10 @@ public virtual void TestClone_StereoParity() } /// - /// Method to test the Clone() method + /// Method to test the method /// [TestMethod()] - public virtual void TestClone_Charge() + public virtual void TestCloneCharge() { IAtom atom = (IAtom)NewChemObject(); atom.Charge = 1.0; @@ -265,7 +265,7 @@ public override void TestToString() } [TestMethod()] - public virtual void TestToString_FractionalCoordinates() + public virtual void TestToStringFractionalCoordinates() { IAtom atom = (IAtom)NewChemObject(); atom.FractionalPoint3D = new Vector3(2, 3, 4); @@ -281,7 +281,6 @@ public virtual void TestDefaultChargeValue() { IAtom atom = (IAtom)NewChemObject(); Assert.AreEqual(null, atom.Charge); - // Assert.AreEqual(0.0, atom.Charge, 0.00000001); } } } \ No newline at end of file diff --git a/NCDKTests/AbstractMolecularFormulaSetTest.cs b/NCDKTests/AbstractMolecularFormulaSetTest.cs index b061b532..4431bc19 100644 --- a/NCDKTests/AbstractMolecularFormulaSetTest.cs +++ b/NCDKTests/AbstractMolecularFormulaSetTest.cs @@ -207,10 +207,10 @@ public virtual void TestClone_IMolecualrFormula() Assert.IsTrue(clone is IMolecularFormulaSet); Assert.AreNotSame(mfS, clone); Assert.AreEqual(mfS.Count(), ((IMolecularFormulaSet)clone).Count()); - Assert.AreEqual(mfS[0].Count, ((IMolecularFormulaSet)clone) - [0].Count); - Assert.AreEqual(mfS[1].Count, ((IMolecularFormulaSet)clone) - [1].Count); + Assert.AreEqual(mfS[0].IsotopesCount, ((IMolecularFormulaSet)clone) + [0].IsotopesCount); + Assert.AreEqual(mfS[1].IsotopesCount, ((IMolecularFormulaSet)clone) + [1].IsotopesCount); } [TestMethod()] diff --git a/NCDKTests/AbstractMolecularFormulaTest.cs b/NCDKTests/AbstractMolecularFormulaTest.cs index 40070bd1..f96eaba4 100644 --- a/NCDKTests/AbstractMolecularFormulaTest.cs +++ b/NCDKTests/AbstractMolecularFormulaTest.cs @@ -37,7 +37,7 @@ public virtual void TestGetIsotopeCount0() { IMolecularFormula mf = Builder.NewMolecularFormula(); - Assert.AreEqual(0, mf.Count); + Assert.AreEqual(0, mf.IsotopesCount); } [TestMethod()] @@ -50,7 +50,7 @@ public virtual void TestGetIsotopeCount() mf.Add(Builder.NewIsotope("H")); mf.Add(Builder.NewIsotope("H")); - Assert.AreEqual(2, mf.Count); + Assert.AreEqual(2, mf.IsotopesCount); } [TestMethod()] @@ -64,7 +64,7 @@ public virtual void TestAddIsotope_IIsotope() hy.NaturalAbundance = 2.00342342; mf.Add(hy); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); } [TestMethod()] @@ -83,7 +83,7 @@ public virtual void TestGetIsotopeCount_IIsotope() mf.Add(h2); mf.Add(h3); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); Assert.AreEqual(1, mf.GetCount(carb)); Assert.AreEqual(1, mf.GetCount(flu)); Assert.AreEqual(3, mf.GetCount(h1)); @@ -103,7 +103,7 @@ public virtual void TestGetIsotopeCount_IIsotope2() mf.Add(h1); mf.Add(h1); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); Assert.AreEqual(1, mf.GetCount(carb)); Assert.AreEqual(1, mf.GetCount(flu)); Assert.AreEqual(3, mf.GetCount(h1)); @@ -121,7 +121,7 @@ public virtual void TestAddIsotope_IIsotope_int() mf.Add(flu); mf.Add(h1, 3); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); Assert.AreEqual(1, mf.GetCount(carb)); Assert.AreEqual(1, mf.GetCount(flu)); Assert.AreEqual(3, mf.GetCount(h1)); @@ -169,7 +169,7 @@ public virtual void TestGetIsotopeCount_IIsotope_Occurr() mf.Add(flu); mf.Add(h1, 3); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); Assert.AreEqual(1, mf.GetCount(carb)); Assert.AreEqual(1, mf.GetCount(flu)); Assert.AreEqual(3, mf.GetCount(h1)); @@ -183,14 +183,14 @@ public virtual void TestAdd_IMolecularFormula() IIsotope oxig = Builder.NewIsotope("O"); acetone.Add(oxig); - Assert.AreEqual(2, acetone.Count); + Assert.AreEqual(2, acetone.IsotopesCount); IMolecularFormula water = Builder.NewMolecularFormula(); water.Add(Builder.NewIsotope("H"), 2); water.Add(oxig); acetone.Add(water); - Assert.AreEqual(3, acetone.Count); + Assert.AreEqual(3, acetone.IsotopesCount); } [TestMethod()] @@ -278,7 +278,7 @@ public virtual void TestGetCharge() mf.Add(Builder.NewAtom("F")); mf.Add(Builder.NewAtom("H"), 3); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); Assert.AreEqual(1.0, mf.Charge.Value, 0.001); } @@ -336,7 +336,7 @@ public virtual void TestRemoveIsotope_IIsotope() // remove the Fluorine mf.Remove(flu); - Assert.AreEqual(2, mf.Count); + Assert.AreEqual(2, mf.IsotopesCount); } [TestMethod()] @@ -353,7 +353,7 @@ public virtual void TestRemoveAllIsotopes() // remove the Fluorine mf.Clear(); - Assert.AreEqual(0, mf.Count); + Assert.AreEqual(0, mf.IsotopesCount); } /// @@ -366,7 +366,7 @@ public virtual void TestClone() mf.Charge = 1; object clone = mf.Clone(); Assert.IsTrue(clone is IMolecularFormula); - Assert.AreEqual(mf.Count, ((IMolecularFormula)clone).Count); + Assert.AreEqual(mf.IsotopesCount, ((IMolecularFormula)clone).IsotopesCount); Assert.AreEqual(mf.Charge, ((IMolecularFormula)clone).Charge); } @@ -384,16 +384,16 @@ public virtual void TestClone_Isotopes() mf.Add(flu); mf.Add(h1, 3); - Assert.AreEqual(3, mf.Count); + Assert.AreEqual(3, mf.IsotopesCount); Assert.AreEqual(1, mf.GetCount(carb)); Assert.AreEqual(1, mf.GetCount(flu)); Assert.AreEqual(3, mf.GetCount(h1)); object clone = mf.Clone(); Assert.IsTrue(clone is IMolecularFormula); - Assert.AreEqual(mf.Count, ((IMolecularFormula)clone).Count); + Assert.AreEqual(mf.IsotopesCount, ((IMolecularFormula)clone).IsotopesCount); - Assert.AreEqual(3, ((IMolecularFormula)clone).Count); + Assert.AreEqual(3, ((IMolecularFormula)clone).IsotopesCount); } [TestMethod()] diff --git a/NCDKTests/AbstractPDBAtomTest.cs b/NCDKTests/AbstractPDBAtomTest.cs index 42a836d7..0e7bdb82 100644 --- a/NCDKTests/AbstractPDBAtomTest.cs +++ b/NCDKTests/AbstractPDBAtomTest.cs @@ -33,7 +33,7 @@ public abstract class AbstractPDBAtomTest : AbstractAtomTest /// Method to test the SetFractional3D() methods. /// [TestMethod()] - public override void TestSetFractionalPoint3d_Point3d() + public override void TestSetFractionalPoint3dPoint3d() { IPDBAtom a = (IPDBAtom)NewChemObject(); a.Symbol = "C"; @@ -48,7 +48,7 @@ public override void TestSetFractionalPoint3d_Point3d() [TestMethod()] public override void TestGetFractionalPoint3d() { - TestSetFractionalPoint3d_Point3d(); + TestSetFractionalPoint3dPoint3d(); } [TestMethod()] @@ -63,7 +63,7 @@ public override void TestGetPoint3d() } [TestMethod()] - public override void TestSetPoint3d_Point3d() + public override void TestSetPoint3dPoint3d() { Vector3 point3d = new Vector3(1, 2, 3); @@ -89,7 +89,7 @@ public override void TestClone() /// Method to test the Clone() method /// [TestMethod()] - public override void TestClone_Point3d() + public override void TestClonePoint3d() { IPDBAtom atom = (IPDBAtom)NewChemObject(); atom.Symbol = "C"; @@ -102,7 +102,7 @@ public override void TestClone_Point3d() /// Method to test the Clone() method /// [TestMethod()] - public override void TestClone_FractionalPoint3d() + public override void TestCloneFractionalPoint3d() { IPDBAtom atom = (IPDBAtom)NewChemObject(); atom.Symbol = "C"; diff --git a/NCDKTests/AbstractPseudoAtomTest.cs b/NCDKTests/AbstractPseudoAtomTest.cs index 49ebe6e2..bc454290 100644 --- a/NCDKTests/AbstractPseudoAtomTest.cs +++ b/NCDKTests/AbstractPseudoAtomTest.cs @@ -73,7 +73,7 @@ public virtual void TestSetHydrogenCount_Integer() } [TestMethod()] - public override void TestSetCharge_Double() + public override void TestSetChargeDouble() { IPseudoAtom atom = (IPseudoAtom)NewChemObject(); atom.Charge = 0.78; @@ -89,7 +89,7 @@ public override void TestSetExactMass_Double() } [TestMethod()] - public override void TestSetStereoParity_Integer() + public override void TestSetStereoParityInteger() { IPseudoAtom atom = (IPseudoAtom)NewChemObject(); atom.StereoParity = -1; @@ -159,7 +159,7 @@ public virtual void TestBug1778479DefaultLabel() /// expect zero hydrogen counts. /// [TestMethod()] - public override void TestClone_HydrogenCount() + public override void TestCloneHydrogenCount() { IAtom atom = (IAtom)NewChemObject(); atom.ImplicitHydrogenCount = 3; @@ -191,7 +191,7 @@ public virtual void TestGetHydrogenCount() /// expect zero stereo parity. /// [TestMethod()] - public override void TestClone_StereoParity() + public override void TestCloneStereoParity() { IAtom atom = (IAtom)NewChemObject(); atom.StereoParity = 3; diff --git a/NCDKTests/AbstractRingTest.cs b/NCDKTests/AbstractRingTest.cs index ab7c9f49..5842937e 100644 --- a/NCDKTests/AbstractRingTest.cs +++ b/NCDKTests/AbstractRingTest.cs @@ -35,16 +35,16 @@ public virtual void TestGetBondOrderSum() { IChemObject obj = NewChemObject(); IRing r = obj.Builder.NewRing(5, "C"); - Assert.AreEqual(5, r.BondOrderSum); + Assert.AreEqual(5, r.GetBondOrderSum()); BondManipulator.IncreaseBondOrder(r.Bonds[0]); - Assert.AreEqual(6, r.BondOrderSum); + Assert.AreEqual(6, r.GetBondOrderSum()); BondManipulator.IncreaseBondOrder(r.Bonds[0]); - Assert.AreEqual(7, r.BondOrderSum); + Assert.AreEqual(7, r.GetBondOrderSum()); BondManipulator.IncreaseBondOrder(r.Bonds[4]); - Assert.AreEqual(8, r.BondOrderSum); + Assert.AreEqual(8, r.GetBondOrderSum()); } [TestMethod()] diff --git a/NCDKTests/Aromaticities/AromaticityTest.cs b/NCDKTests/Aromaticities/AromaticityTest.cs index 606c002b..ad4a5c4e 100644 --- a/NCDKTests/Aromaticities/AromaticityTest.cs +++ b/NCDKTests/Aromaticities/AromaticityTest.cs @@ -36,9 +36,9 @@ namespace NCDK.Aromaticities [TestClass()] public class AromaticityTest { - private readonly Aromaticity cdk = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllFinder); - private readonly Aromaticity cdkExo = new Aromaticity(ElectronDonation.CDKAllowingExocyclicModel, Cycles.AllFinder); - private readonly Aromaticity daylight = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + private readonly Aromaticity cdk = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); + private readonly Aromaticity cdkExo = new Aromaticity(ElectronDonation.CDKAllowingExocyclicModel, Cycles.AllSimpleFinder); + private readonly Aromaticity daylight = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); [TestMethod()] public void Benzene() @@ -156,7 +156,7 @@ public void EnsureConsistentRepresentation() { IAtomContainer a = CreateFromSmiles("C1=CC2=CC3=CC4=C(C=CC=C4)C=C3C=C2C=C1"); IAtomContainer b = CreateFromSmiles("c1cc2cc3cc4c(cccc4)cc3cc2cc1"); - Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); arom.Apply(a); arom.Apply(b); Assert.IsTrue(AtomContainerDiff.Diff(a, b).Count() == 0); diff --git a/NCDKTests/Aromaticities/KekulizationTest.cs b/NCDKTests/Aromaticities/KekulizationTest.cs index 7a8caa54..915a3c24 100644 --- a/NCDKTests/Aromaticities/KekulizationTest.cs +++ b/NCDKTests/Aromaticities/KekulizationTest.cs @@ -24,8 +24,9 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; +using System.Linq; namespace NCDK.Aromaticities { @@ -495,7 +496,7 @@ public void SulfurCation() void AssertBondOrders(IAtomContainer ac, params BondOrder[] expected) { Kekulization.Kekulize(ac); - IBond[] bonds = AtomContainerManipulator.GetBondArray(ac); + IBond[] bonds = ac.Bonds.ToArray(); ; BondOrder[] actual = new BondOrder[bonds.Length]; for (int i = 0; i < bonds.Length; i++) actual[i] = bonds[i].Order; diff --git a/NCDKTests/AssociationTest.cs b/NCDKTests/AssociationTest.cs index f1597e5c..3b80b047 100644 --- a/NCDKTests/AssociationTest.cs +++ b/NCDKTests/AssociationTest.cs @@ -18,7 +18,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; +using System.Linq; namespace NCDK { diff --git a/NCDKTests/AtomTypes/AbstractAtomTypeTest.cs b/NCDKTests/AtomTypes/AbstractAtomTypeTest.cs index 50d37d02..e7491a00 100644 --- a/NCDKTests/AtomTypes/AbstractAtomTypeTest.cs +++ b/NCDKTests/AtomTypes/AbstractAtomTypeTest.cs @@ -20,6 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; using NCDK.Tools.Manipulator; +using System; using System.Collections.Generic; using System.Linq; @@ -92,7 +93,7 @@ public void AssertAtomTypeNames(IDictionary testedAtomTypes, string private void AssertConsistentProperties(IAtomContainer mol, IAtom atom, IAtomType matched) { // X has no properties; nothing to match - if ("X".Equals(matched.AtomTypeName)) + if (string.Equals("X", matched.AtomTypeName, StringComparison.Ordinal)) { return; } diff --git a/NCDKTests/AtomTypes/AbstractSybylAtomTypeTest.cs b/NCDKTests/AtomTypes/AbstractSybylAtomTypeTest.cs index ffb96848..6ba6e177 100644 --- a/NCDKTests/AtomTypes/AbstractSybylAtomTypeTest.cs +++ b/NCDKTests/AtomTypes/AbstractSybylAtomTypeTest.cs @@ -51,8 +51,7 @@ public override IAtomTypeMatcher GetAtomTypeMatcher(IChemObjectBuilder builder) public override void AssertAtomTypes(IDictionary testedAtomTypes, string[] expectedTypes, IAtomContainer mol) { - Assert.AreEqual(expectedTypes.Length, mol.Atoms.Count, - "The number of expected atom types is unequal to the number of atoms"); + Assert.AreEqual(expectedTypes.Length, mol.Atoms.Count, "The number of expected atom types is unequal to the number of atoms"); IAtomTypeMatcher atm = GetAtomTypeMatcher(mol.Builder); for (int i = 0; i < expectedTypes.Length; i++) { diff --git a/NCDKTests/AtomTypes/CDKAtomTypeMatcherFilesTest.cs b/NCDKTests/AtomTypes/CDKAtomTypeMatcherFilesTest.cs index bad38e3a..8960bf86 100644 --- a/NCDKTests/AtomTypes/CDKAtomTypeMatcherFilesTest.cs +++ b/NCDKTests/AtomTypes/CDKAtomTypeMatcherFilesTest.cs @@ -18,10 +18,9 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Tools.Manipulator; - using System.Collections.Generic; using System.Linq; @@ -35,7 +34,7 @@ namespace NCDK.AtomTypes [TestClass()] public class CDKAtomTypeMatcherFilesTest : AbstractCDKAtomTypeTest { - private static IDictionary testedAtomTypes = new Dictionary(); + private static readonly Dictionary testedAtomTypes = new Dictionary(); [TestMethod()] public void TestFile3() @@ -113,8 +112,8 @@ public void TestSmilesFiles() Assert.IsNotNull(chemFile); IAtomContainer mol2 = ChemFileManipulator.GetAllAtomContainers(chemFile).First(); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); - IAtomType[] types2 = atomTypeMatcher.FindMatchingAtomTypes(mol2); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1).ToList(); + var types2 = atomTypeMatcher.FindMatchingAtomTypes(mol2).ToList(); for (int i = 0; i < mol1.Atoms.Count; i++) { Assert.IsNotNull(types1[i], "Atom typing in mol1 failed for atom " + (i + 1)); diff --git a/NCDKTests/AtomTypes/CDKAtomTypeMatcherSMILESTest.cs b/NCDKTests/AtomTypes/CDKAtomTypeMatcherSMILESTest.cs index c8896be4..96a2c84f 100644 --- a/NCDKTests/AtomTypes/CDKAtomTypeMatcherSMILESTest.cs +++ b/NCDKTests/AtomTypes/CDKAtomTypeMatcherSMILESTest.cs @@ -20,6 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Smiles; using NCDK.Tools.Manipulator; +using System.Linq; namespace NCDK.AtomTypes { @@ -40,17 +41,17 @@ public class CDKAtomTypeMatcherSMILESTest : AbstractCDKAtomTypeTest [TestMethod()] public void TestIdenticalTypes() { - string smiles1 = "CN(C)CCC1=CNC2=C1C=C(C=C2)CC1NC(=O)OC1"; - string smiles2 = "CN(C)CCC1=CNc2c1cc(cc2)CC1NC(=O)OC1"; + var smiles1 = "CN(C)CCC1=CNC2=C1C=C(C=C2)CC1NC(=O)OC1"; + var smiles2 = "CN(C)CCC1=CNc2c1cc(cc2)CC1NC(=O)OC1"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); - IAtomContainer mol2 = smilesParser.ParseSmiles(smiles2); + var mol1 = smilesParser.ParseSmiles(smiles1); + var mol2 = smilesParser.ParseSmiles(smiles2); Assert.AreEqual(mol1.Atoms.Count, mol2.Atoms.Count); Assert.AreEqual(mol1.Bonds.Count, mol2.Bonds.Count); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); - IAtomType[] types2 = atomTypeMatcher.FindMatchingAtomTypes(mol2); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1).ToList(); + var types2 = atomTypeMatcher.FindMatchingAtomTypes(mol2).ToList(); for (int i = 0; i < mol1.Atoms.Count; i++) { Assert.AreEqual(types1[i].AtomTypeName, types2[i].AtomTypeName); @@ -62,12 +63,12 @@ public void TestNitrogen() { string smiles1 = "c1c2cc[NH]cc2nc1"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); + var mol1 = smilesParser.ParseSmiles(smiles1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); Assert.AreEqual(9, mol1.Atoms.Count); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); foreach (var type in types1) { Assert.IsNotNull(type.AtomTypeName); @@ -78,12 +79,10 @@ public void TestNitrogen() public void TestNitrogen_SP2() { string smiles1 = "c1c2cc[nH]cc2nc1"; - - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); - + var mol1 = smilesParser.ParseSmiles(smiles1); Assert.AreEqual(9, mol1.Atoms.Count); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); foreach (var type in types1) { Assert.IsNotNull(type.AtomTypeName); @@ -94,11 +93,11 @@ public void TestNitrogen_SP2() [TestMethod()] public void TestAnotherNitrogen_SP2() { - string smiles1 = "c1cnc2s[cH][cH]n12"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); + var smiles1 = "c1cnc2s[cH][cH]n12"; + var mol1 = smilesParser.ParseSmiles(smiles1); Assert.AreEqual(8, mol1.Atoms.Count); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); foreach (var type in types1) { Assert.IsNotNull(type.AtomTypeName); @@ -112,14 +111,14 @@ public void TestBug1294() string smiles1 = "c2c1ccccc1c[nH]2"; string smiles2 = "C2=C1C=CC=CC1=CN2"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); - IAtomContainer mol2 = smilesParser.ParseSmiles(smiles2); + var mol1 = smilesParser.ParseSmiles(smiles1); + var mol2 = smilesParser.ParseSmiles(smiles2); Assert.AreEqual(mol1.Atoms.Count, mol2.Atoms.Count); Assert.AreEqual(mol1.Bonds.Count, mol2.Bonds.Count); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); - IAtomType[] types2 = atomTypeMatcher.FindMatchingAtomTypes(mol2); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1).ToList(); + var types2 = atomTypeMatcher.FindMatchingAtomTypes(mol2).ToList(); for (int i = 0; i < mol1.Atoms.Count; i++) { Assert.AreEqual(types1[i].AtomTypeName, types2[i].AtomTypeName); @@ -130,13 +129,13 @@ public void TestBug1294() [TestMethod()] public void TestBug3093644() { - string smiles1 = "[H]C5(CCC(N)=O)(C=1N=C(C=C4N=C(C(C)=C3[N-]C(C)(C2N=C(C=1(C))C(C)" + var smiles1 = "[H]C5(CCC(N)=O)(C=1N=C(C=C4N=C(C(C)=C3[N-]C(C)(C2N=C(C=1(C))C(C)" + "(CCC(=O)NCC(C)O)C2([H])(CC(N)=O))C(C)(CC(N)=O)C3([H])(CCC(N)=O))" + "C(C)(CC(N)=O)C4([H])(CCC(N)=O))C5(C)(C)).[H][C-]([H])C3([H])(OC([H])" + "(N2C=NC=1C(N)=NC=NC=12)C([H])(O)C3([H])(O)).[Co+3]"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); - IAtomType[] types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); + var mol1 = smilesParser.ParseSmiles(smiles1); + var types1 = atomTypeMatcher.FindMatchingAtomTypes(mol1); foreach (var type in types1) { Assert.IsNotNull(type.AtomTypeName); @@ -146,9 +145,9 @@ public void TestBug3093644() [TestMethod()] public void TestPlatinum4() { - string smiles1 = "Cl[Pt]1(Cl)(Cl)(Cl)NC2CCCCC2N1"; + var smiles1 = "Cl[Pt]1(Cl)(Cl)(Cl)NC2CCCCC2N1"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); + var mol1 = smilesParser.ParseSmiles(smiles1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); Assert.AreEqual(13, mol1.Atoms.Count); Assert.AreEqual("Pt.6", mol1.Atoms[1].AtomTypeName); @@ -157,9 +156,9 @@ public void TestPlatinum4() [TestMethod()] public void TestPlatinum6() { - string smiles1 = "[Pt](Cl)(Cl)(N)N"; + var smiles1 = "[Pt](Cl)(Cl)(N)N"; - IAtomContainer mol1 = smilesParser.ParseSmiles(smiles1); + var mol1 = smilesParser.ParseSmiles(smiles1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); Assert.AreEqual(5, mol1.Atoms.Count); Assert.AreEqual("Pt.4", mol1.Atoms[0].AtomTypeName); @@ -168,9 +167,9 @@ public void TestPlatinum6() [TestMethod()] public void TestAmineOxide() { - string smiles = "CN(C)(=O)CCC=C2c1ccccc1CCc3ccccc23"; + var smiles = "CN(C)(=O)CCC=C2c1ccccc1CCc3ccccc23"; - IAtomContainer mol = smilesParser.ParseSmiles(smiles); + var mol = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Assert.AreEqual("N.oxide", mol.Atoms[1].AtomTypeName); @@ -179,10 +178,10 @@ public void TestAmineOxide() [TestMethod()] public void TestYetAnotherNitrogen() { - string smiles = "CCCN1CC(CSC)CC2C1Cc3c[nH]c4cccc2c34"; + var smiles = "CCCN1CC(CSC)CC2C1Cc3c[nH]c4cccc2c34"; - IAtomContainer mol = smilesParser.ParseSmiles(smiles); - IAtomType[] types = atomTypeMatcher.FindMatchingAtomTypes(mol); + var mol = smilesParser.ParseSmiles(smiles); + var types = atomTypeMatcher.FindMatchingAtomTypes(mol); foreach (var type in types) { Assert.IsNotNull(type.AtomTypeName); @@ -192,10 +191,10 @@ public void TestYetAnotherNitrogen() [TestMethod()] public void Test4Sulphur() { - string smiles = "Br.Br.CS(CCC(N)C#N)C[C@H]1OC([C@H](O)[C@@H]1O)N2cnc3c(N)ncnc23"; + var smiles = "Br.Br.CS(CCC(N)C#N)C[C@H]1OC([C@H](O)[C@@H]1O)N2cnc3c(N)ncnc23"; - IAtomContainer mol = smilesParser.ParseSmiles(smiles); - IAtomType[] types = atomTypeMatcher.FindMatchingAtomTypes(mol); + var mol = smilesParser.ParseSmiles(smiles); + var types = atomTypeMatcher.FindMatchingAtomTypes(mol); foreach (var type in types) { Assert.IsNotNull(type.AtomTypeName); @@ -205,8 +204,8 @@ public void Test4Sulphur() [TestMethod()] public void TestTellaneLike() { - string smiles = "Clc1cccc(N2CCN(CCCCNC(=O)C3=Cc4ccccc4[Te]3)CC2)c1Cl"; - IAtomContainer mol = smilesParser.ParseSmiles(smiles); + var smiles = "Clc1cccc(N2CCN(CCCCNC(=O)C3=Cc4ccccc4[Te]3)CC2)c1Cl"; + var mol = smilesParser.ParseSmiles(smiles); foreach (var atom in mol.Atoms) Assert.AreNotSame("X", atom.AtomTypeName); } diff --git a/NCDKTests/AtomTypes/CDKAtomTypeMatcherTest.cs b/NCDKTests/AtomTypes/CDKAtomTypeMatcherTest.cs index ec8af5bc..09417b84 100644 --- a/NCDKTests/AtomTypes/CDKAtomTypeMatcherTest.cs +++ b/NCDKTests/AtomTypes/CDKAtomTypeMatcherTest.cs @@ -23,7 +23,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.Templates; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -42,19 +42,19 @@ namespace NCDK.AtomTypes [TestClass()] public class CDKAtomTypeMatcherTest : AbstractCDKAtomTypeTest { - private static IDictionary testedAtomTypes = new Dictionary(); + private static readonly Dictionary testedAtomTypes = new Dictionary(); [TestMethod()] public void TestGetInstance_IChemObjectBuilder() { - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance); + var matcher = CDKAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance); Assert.IsNotNull(matcher); } [TestMethod()] public void TestGetInstance_IChemObjectBuilder_int() { - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance, + var matcher = CDKAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance, CDKAtomTypeMatcher.Mode.RequireExplicitHydrogens); Assert.IsNotNull(matcher); } @@ -64,7 +64,7 @@ public void TestFindMatchingAtomType_IAtomContainer_IAtom() { IAtomContainer mol = new AtomContainer(); IAtom atom = new Atom("C"); - Hybridization thisHybridization = Hybridization.SP3; + var thisHybridization = Hybridization.SP3; atom.Hybridization = thisHybridization; mol.Atoms.Add(atom); @@ -77,16 +77,16 @@ public void TestFindMatchingAtomType_IAtomContainer() { IAtomContainer mol = new AtomContainer(); IAtom atom = new Atom("C"); - Hybridization thisHybridization = Hybridization.SP3; + var thisHybridization = Hybridization.SP3; atom.Hybridization = thisHybridization; mol.Atoms.Add(atom); // just check consistency; other methods do perception testing - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance); - IAtomType[] types = matcher.FindMatchingAtomTypes(mol); - for (int i = 0; i < types.Length; i++) + var matcher = CDKAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance); + var types = matcher.FindMatchingAtomTypes(mol).ToList(); + for (int i = 0; i < types.Count; i++) { - IAtomType type = matcher.FindMatchingAtomType(mol, mol.Atoms[i]); + var type = matcher.FindMatchingAtomType(mol, mol.Atoms[i]); Assert.AreEqual(type.AtomTypeName, types[i].AtomTypeName); } } @@ -109,8 +109,8 @@ public void TestNonExistingType() IAtomContainer mol = new AtomContainer(); IAtom atom = new Atom(); mol.Atoms.Add(atom); - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance); - IAtomType type = matcher.FindMatchingAtomType(mol, atom); + var matcher = CDKAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance); + var type = matcher.FindMatchingAtomType(mol, atom); Assert.IsNotNull(type); Assert.AreEqual("X", type.AtomTypeName); } @@ -509,13 +509,13 @@ public void TestTetrahydropyran() [TestMethod()] public void TestS3() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, o1, BondOrder.Double); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(s, o2, BondOrder.Double); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, o1, BondOrder.Double); + IBond b2 = ChemObjectBuilder.Instance.NewBond(s, o2, BondOrder.Double); mol.Atoms.Add(s); mol.Atoms.Add(o1); @@ -531,13 +531,13 @@ public void TestS3() [TestMethod()] public void TestH2S() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(s, h2, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); + IBond b2 = ChemObjectBuilder.Instance.NewBond(s, h2, BondOrder.Single); mol.Atoms.Add(s); mol.Atoms.Add(h1); @@ -554,13 +554,13 @@ public void TestH2S() [TestMethod()] public void TestH2Se() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom se = Default.ChemObjectBuilder.Instance.NewAtom("Se"); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom se = ChemObjectBuilder.Instance.NewAtom("Se"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(se, h1, BondOrder.Single); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(se, h2, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(se, h1, BondOrder.Single); + IBond b2 = ChemObjectBuilder.Instance.NewBond(se, h2, BondOrder.Single); mol.Atoms.Add(se); mol.Atoms.Add(h1); @@ -577,12 +577,12 @@ public void TestH2Se() [TestMethod()] public void TestH2Se_oneImplH() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom se = Default.ChemObjectBuilder.Instance.NewAtom("Se"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom se = ChemObjectBuilder.Instance.NewAtom("Se"); se.ImplicitHydrogenCount = 1; - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(se, h1, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(se, h1, BondOrder.Single); mol.Atoms.Add(se); mol.Atoms.Add(h1); @@ -596,8 +596,8 @@ public void TestH2Se_oneImplH() [TestMethod()] public void TestH2Se_twoImplH() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom se = Default.ChemObjectBuilder.Instance.NewAtom("Se"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom se = ChemObjectBuilder.Instance.NewAtom("Se"); se.ImplicitHydrogenCount = 2; mol.Atoms.Add(se); @@ -608,8 +608,8 @@ public void TestH2Se_twoImplH() [TestMethod()] public void TestSelenide() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom se = Default.ChemObjectBuilder.Instance.NewAtom("Se"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom se = ChemObjectBuilder.Instance.NewAtom("Se"); se.ImplicitHydrogenCount = 0; se.FormalCharge = -2; mol.Atoms.Add(se); @@ -621,8 +621,8 @@ public void TestSelenide() [TestMethod()] public void TestH2S_Hybridization() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); s.Hybridization = Hybridization.SP3; mol.Atoms.Add(s); string[] expectedTypes = { "S.3" }; @@ -632,12 +632,12 @@ public void TestH2S_Hybridization() [TestMethod()] public void TestHS() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); s.FormalCharge = -1; - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); mol.Atoms.Add(s); mol.Atoms.Add(h1); @@ -913,7 +913,7 @@ public void TestSulphuricAcid() [TestMethod()] public void TestThioSulphonate() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); mol.Atoms.Add(a1); @@ -1715,7 +1715,7 @@ public void TestMercuryComplex() [TestMethod()] public void Test_Hg_2plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Hg"); a1.FormalCharge = 2; @@ -1728,7 +1728,7 @@ public void Test_Hg_2plus() [TestMethod()] public void Test_Hg_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Hg"); a1.FormalCharge = 1; @@ -1746,7 +1746,7 @@ public void Test_Hg_plus() [TestMethod()] public void Test_Hg_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Hg"); a1.FormalCharge = 0; @@ -1759,7 +1759,7 @@ public void Test_Hg_metallic() [TestMethod()] public void Test_Hg_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Hg"); a1.FormalCharge = 0; @@ -1777,7 +1777,7 @@ public void Test_Hg_1() [TestMethod()] public void Test_Hg_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Hg"); a1.FormalCharge = 0; @@ -1925,7 +1925,7 @@ public void TestSalts() public void Fix_Ca_2() { //string molName = "Ca_2"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ca"); a1.FormalCharge = 0; @@ -1949,7 +1949,7 @@ public void Fix_Ca_2() public void Fix_Ca_1() { //string molName1 = "Ca_1"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ca"); a1.FormalCharge = 0; @@ -3143,7 +3143,7 @@ public void TestAssumeExplicitHydrogens() [TestMethod()] public void TestStructGenMatcher() { - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance); + CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance); Assert.IsNotNull(matcher); } @@ -3765,7 +3765,7 @@ public void TestFormalChargeRepresentation() mol.Atoms.Add(atom); string[] expectedTypes = { "O.minus" }; - // option one: int.Parse() + // option one: int.Parse(, NumberFormatInfo.InvariantInfo) atom.FormalCharge = -1; AssertAtomTypes(testedAtomTypes, expectedTypes, mol); @@ -3811,7 +3811,7 @@ public void TestPine() [TestMethod()] public void Test_S_sp3d1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); a1.FormalCharge = 0; @@ -3849,7 +3849,7 @@ public void Test_S_sp3d1() [TestMethod()] public void Test_S_inyl_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); a1.FormalCharge = 0; @@ -3872,7 +3872,7 @@ public void Test_S_inyl_2() [TestMethod()] public void Test_S_2minus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); a1.FormalCharge = -2; @@ -3885,7 +3885,7 @@ public void Test_S_2minus() [TestMethod()] public void Test_S_sp3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); a1.FormalCharge = 0; @@ -3908,7 +3908,7 @@ public void Test_S_sp3() [TestMethod()] public void Test_S_sp3_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); a1.FormalCharge = 0; @@ -3941,7 +3941,7 @@ public void Test_S_sp3_4() [TestMethod()] public void Test_Co_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 3; @@ -3954,7 +3954,7 @@ public void Test_Co_3plus() [TestMethod()] public void Test_Co_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 0; @@ -3967,7 +3967,7 @@ public void Test_Co_metallic() [TestMethod()] public void Test_Co_plus_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 1; @@ -4010,7 +4010,7 @@ public void Test_Co_plus_6() [TestMethod()] public void Test_Co_2plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 2; @@ -4023,7 +4023,7 @@ public void Test_Co_2plus() [TestMethod()] public void Test_Co_plus_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 1; @@ -4046,7 +4046,7 @@ public void Test_Co_plus_2() [TestMethod()] public void Test_Co_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -4069,7 +4069,7 @@ public void Test_Co_2() [TestMethod()] public void Test_Co_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 0; @@ -4112,7 +4112,7 @@ public void Test_Co_6() [TestMethod()] public void Test_Co_plus_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 1; @@ -4145,7 +4145,7 @@ public void Test_Co_plus_4() [TestMethod()] public void Test_Co_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 0; @@ -4178,7 +4178,7 @@ public void Test_Co_4() [TestMethod()] public void Test_Co_plus_5() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 1; @@ -4217,7 +4217,7 @@ public void Test_Co_plus_5() [TestMethod()] public void Test_Co_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a2 = builder.NewAtom("Co"); a2.FormalCharge = 1; @@ -4230,7 +4230,7 @@ public void Test_Co_plus() [TestMethod()] public void Test_Co_plus_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -4248,7 +4248,7 @@ public void Test_Co_plus_1() [TestMethod()] public void Test_Co_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Co"); a1.FormalCharge = 0; @@ -4270,7 +4270,7 @@ public void Test_Co_1() [TestMethod()] public void Test_Br_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Br"); a1.FormalCharge = 0; @@ -4298,7 +4298,7 @@ public void Test_Br_3() [TestMethod()] public void Test_Zn_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Zn"); a1.FormalCharge = 0; @@ -4311,7 +4311,7 @@ public void Test_Zn_metallic() [TestMethod()] public void Test_Zn_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Zn"); a1.FormalCharge = 0; @@ -4333,7 +4333,7 @@ public void Test_Zn_1() [TestMethod()] public void Test_V_3minus_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("V"); a1.FormalCharge = -3; @@ -4370,7 +4370,7 @@ public void Test_V_3minus_4() [TestMethod()] public void Test_Al_3minus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Al"); a1.FormalCharge = -3; @@ -4413,7 +4413,7 @@ public void Test_Al_3minus() [TestMethod()] public void TestSe_sp3d1_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.FormalCharge = 0; @@ -4446,7 +4446,7 @@ public void TestSe_sp3d1_4() [TestMethod()] public void TestSe_sp3_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.FormalCharge = 0; @@ -4479,7 +4479,7 @@ public void TestSe_sp3_4() [TestMethod()] public void TestSe_sp2_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.FormalCharge = 0; @@ -4502,7 +4502,7 @@ public void TestSe_sp2_2() [TestMethod()] public void TestSe_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -4520,7 +4520,7 @@ public void TestSe_1() [TestMethod()] public void TestSe_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.FormalCharge = 0; @@ -4543,7 +4543,7 @@ public void TestSe_3() [TestMethod()] public void TestSe_sp3_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -4571,7 +4571,7 @@ public void TestSe_sp3_3() [TestMethod()] public void TestSe_4plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.FormalCharge = 4; @@ -4584,7 +4584,7 @@ public void TestSe_4plus() [TestMethod()] public void TestSe_plus_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -4612,7 +4612,7 @@ public void TestSe_plus_3() [TestMethod()] public void TestSe_5() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.FormalCharge = 0; @@ -4650,7 +4650,7 @@ public void TestSe_5() [TestMethod()] public void Test_Se_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Se"); a1.ImplicitHydrogenCount = 0; @@ -4665,7 +4665,7 @@ public void Test_Se_2() [TestMethod()] public void TestTellane() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Te"); a1.FormalCharge = 0; @@ -4689,7 +4689,7 @@ public void TestTellane() [TestMethod()] public void TestPhosphanium() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("P"); a1.FormalCharge = 1; @@ -4718,7 +4718,7 @@ public void TestPhosphanium() [TestMethod()] public void TestPhosphide() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("P"); a1.FormalCharge = 0; @@ -4741,7 +4741,7 @@ public void TestPhosphide() [TestMethod()] public void TestPentaMethylPhosphane() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("P"); a1.FormalCharge = 0; @@ -4779,7 +4779,7 @@ public void TestPentaMethylPhosphane() [TestMethod()] public void Test_Sb_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -4812,7 +4812,7 @@ public void Test_Sb_4() [TestMethod()] public void Test_Sb_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Sb"); a1.FormalCharge = 0; @@ -4840,7 +4840,7 @@ public void Test_Sb_3() [TestMethod()] public void Test_B_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("B"); a1.FormalCharge = 3; @@ -4873,7 +4873,7 @@ public void Test_B_3plus() [TestMethod()] public void Test_Sr_2plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Sr"); a1.FormalCharge = 2; @@ -4886,7 +4886,7 @@ public void Test_Sr_2plus() [TestMethod()] public void Test_Te_4plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Te"); a1.FormalCharge = 4; @@ -4899,7 +4899,7 @@ public void Test_Te_4plus() [TestMethod()] public void Test_Be_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Be"); a1.FormalCharge = 0; @@ -4912,7 +4912,7 @@ public void Test_Be_neutral() [TestMethod()] public void Test_Cl_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cl"); a1.FormalCharge = 0; @@ -4935,7 +4935,7 @@ public void Test_Cl_2() [TestMethod()] public void Test_K_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("K"); a1.FormalCharge = 0; @@ -4953,7 +4953,7 @@ public void Test_K_neutral() [TestMethod()] public void Test_Li_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Li"); a1.FormalCharge = 0; @@ -4966,7 +4966,7 @@ public void Test_Li_neutral() [TestMethod()] public void Test_Li_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Li"); a1.FormalCharge = 1; @@ -4979,7 +4979,7 @@ public void Test_Li_plus() [TestMethod()] public void Test_I_sp3d2_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("I"); a1.FormalCharge = 0; @@ -5048,7 +5048,7 @@ public void TestAzoCompound() [TestMethod()] public void TestMethylphosphinicAcid() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("P"); a1.FormalCharge = 0; @@ -5101,7 +5101,7 @@ public void TestMethylphosphinicAcid() [TestMethod()] public void Test_Ti_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ti"); a1.FormalCharge = 0; @@ -5124,7 +5124,7 @@ public void Test_Ti_2() [TestMethod()] public void Test_Ni_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ni"); a1.FormalCharge = 0; @@ -5137,7 +5137,7 @@ public void Test_Ni_metallic() [TestMethod()] public void Test_Ni_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -5155,7 +5155,7 @@ public void Test_Ni_plus() [TestMethod()] public void Test_Pb_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Pb"); a1.FormalCharge = 0; @@ -5173,7 +5173,7 @@ public void Test_Pb_1() [TestMethod()] public void Test_Pb_2plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Pb"); a1.FormalCharge = 2; @@ -5186,7 +5186,7 @@ public void Test_Pb_2plus() [TestMethod()] public void Test_Pb_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Pb"); a1.FormalCharge = 0; @@ -5199,7 +5199,7 @@ public void Test_Pb_neutral() [TestMethod()] public void Test_Tl_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Tl"); a1.FormalCharge = 0; @@ -5212,7 +5212,7 @@ public void Test_Tl_neutral() [TestMethod()] public void Test_Tl_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -5230,7 +5230,7 @@ public void Test_Tl_1() [TestMethod()] public void Test_Tl_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Tl"); a1.FormalCharge = 1; @@ -5243,7 +5243,7 @@ public void Test_Tl_plus() [TestMethod()] public void Test_Mg_neutral_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -5266,7 +5266,7 @@ public void Test_Mg_neutral_2() [TestMethod()] public void Test_Mg_neutral_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -5299,7 +5299,7 @@ public void Test_Mg_neutral_4() [TestMethod()] public void Test_Mg_neutral_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Mg"); a1.FormalCharge = 0; @@ -5317,7 +5317,7 @@ public void Test_Mg_neutral_1() [TestMethod()] public void Test_Gd_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Gd"); a1.FormalCharge = 3; @@ -5330,7 +5330,7 @@ public void Test_Gd_3plus() [TestMethod()] public void Test_Mo_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Mo"); a1.FormalCharge = 0; @@ -5363,7 +5363,7 @@ public void Test_Mo_4() [TestMethod()] public void Test_Mo_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Mo"); a1.FormalCharge = 0; @@ -5376,7 +5376,7 @@ public void Test_Mo_metallic() [TestMethod()] public void Test_Pt_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Pt"); a1.FormalCharge = 0; @@ -5399,7 +5399,7 @@ public void Test_Pt_2() [TestMethod()] public void Test_Pt_2plus_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Pt"); a1.FormalCharge = 2; @@ -5432,7 +5432,7 @@ public void Test_Pt_2plus_4() [TestMethod()] public void Test_Cu_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cu"); a1.FormalCharge = 0; @@ -5445,7 +5445,7 @@ public void Test_Cu_metallic() [TestMethod()] public void Test_Cu_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cu"); a1.FormalCharge = 1; @@ -5458,7 +5458,7 @@ public void Test_Cu_plus() [TestMethod()] public void Test_Cu_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cu"); a1.FormalCharge = 0; @@ -5476,7 +5476,7 @@ public void Test_Cu_1() [TestMethod()] public void Test_Ra() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ra"); a1.FormalCharge = 0; @@ -5489,7 +5489,7 @@ public void Test_Ra() [TestMethod()] public void Test_Cr_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cr"); a1.FormalCharge = 0; @@ -5502,7 +5502,7 @@ public void Test_Cr_neutral() [TestMethod()] public void Test_Rb_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Rb"); a1.FormalCharge = 0; @@ -5515,7 +5515,7 @@ public void Test_Rb_neutral() [TestMethod()] public void Test_Rb_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Rb"); a1.FormalCharge = 1; @@ -5528,7 +5528,7 @@ public void Test_Rb_plus() [TestMethod()] public void Test_Cr_4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cr"); a1.FormalCharge = 0; @@ -5561,7 +5561,7 @@ public void Test_Cr_4() [TestMethod()] public void Test_Cr_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cr"); a1.FormalCharge = 3; @@ -5574,7 +5574,7 @@ public void Test_Cr_3plus() [TestMethod()] public void Test_Cr_6plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cr"); a1.FormalCharge = 6; @@ -5587,7 +5587,7 @@ public void Test_Cr_6plus() [TestMethod()] public void Test_Ba_2plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ba"); a1.FormalCharge = 2; @@ -5600,7 +5600,7 @@ public void Test_Ba_2plus() [TestMethod()] public void Test_Au_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -5618,7 +5618,7 @@ public void Test_Au_1() [TestMethod()] public void Test_Ag_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ag"); a1.FormalCharge = 0; @@ -5634,7 +5634,7 @@ public void Test_Ag_neutral() [TestMethod()] public void Test_Ag_plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ag"); a1.FormalCharge = 1; @@ -5650,7 +5650,7 @@ public void Test_Ag_plus() [TestMethod()] public void Test_Ag_covalent() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ag"); mol.Atoms.Add(a1); @@ -5665,7 +5665,7 @@ public void Test_Ag_covalent() [TestMethod()] public void Test_In_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("In"); a1.FormalCharge = 3; @@ -5678,7 +5678,7 @@ public void Test_In_3plus() [TestMethod()] public void Test_In_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("In"); a1.FormalCharge = 0; @@ -5706,7 +5706,7 @@ public void Test_In_3() [TestMethod()] public void Test_In_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("In"); a1.FormalCharge = 0; @@ -5724,7 +5724,7 @@ public void Test_In_1() [TestMethod()] public void Test_In() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("In"); a1.FormalCharge = 0; @@ -5737,7 +5737,7 @@ public void Test_In() [TestMethod()] public void Test_Cd_2plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cd"); a1.FormalCharge = 2; @@ -5750,7 +5750,7 @@ public void Test_Cd_2plus() [TestMethod()] public void Test_Cd_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cd"); a1.FormalCharge = 0; @@ -5773,7 +5773,7 @@ public void Test_Cd_2() [TestMethod()] public void Test_Cd_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Cd"); a1.FormalCharge = 0; @@ -5786,7 +5786,7 @@ public void Test_Cd_metallic() [TestMethod()] public void Test_Pu() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Pu"); a1.FormalCharge = 0; @@ -5799,7 +5799,7 @@ public void Test_Pu() [TestMethod()] public void Test_Th() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Th"); a1.FormalCharge = 0; @@ -5812,7 +5812,7 @@ public void Test_Th() [TestMethod()] public void Test_Ge_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -5840,7 +5840,7 @@ public void Test_Ge_3() [TestMethod()] public void Test_Na_neutral() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Na"); a1.FormalCharge = 0; @@ -5853,7 +5853,7 @@ public void Test_Na_neutral() [TestMethod()] public void Test_Mn_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Mn"); a1.FormalCharge = 3; @@ -5866,7 +5866,7 @@ public void Test_Mn_3plus() [TestMethod()] public void Test_Mn_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Mn"); a1.FormalCharge = 0; @@ -5889,7 +5889,7 @@ public void Test_Mn_2() [TestMethod()] public void Test_Mn_metallic() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Mn"); a1.FormalCharge = 0; @@ -5902,7 +5902,7 @@ public void Test_Mn_metallic() [TestMethod()] public void Test_Si_2minus_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Si"); a1.FormalCharge = -2; @@ -5945,7 +5945,7 @@ public void Test_Si_2minus_6() [TestMethod()] public void Test_Si_3() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Si"); a1.FormalCharge = 0; @@ -5973,7 +5973,7 @@ public void Test_Si_3() [TestMethod()] public void Test_Si_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Si"); a1.FormalCharge = 0; @@ -5996,7 +5996,7 @@ public void Test_Si_2() [TestMethod()] public void Test_As_minus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("As"); a1.FormalCharge = -1; @@ -6039,7 +6039,7 @@ public void Test_As_minus() [TestMethod()] public void Test_As_3plus() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("As"); a1.FormalCharge = 3; @@ -6052,7 +6052,7 @@ public void Test_As_3plus() [TestMethod()] public void Test_As_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -6075,7 +6075,7 @@ public void Test_As_2() [TestMethod()] public void Test_As_5() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("As"); a1.FormalCharge = 0; @@ -6109,7 +6109,7 @@ public void Test_As_5() public void Test_Fe_metallic() { //string molName = "Fe_metallic"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = 0; @@ -6122,7 +6122,7 @@ public void Test_Fe_metallic() public void Test_Fe_plus() { //string molName1 = "Fe_plus"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -6146,7 +6146,7 @@ public void Test_Fe_plus() public void Test_Fe_4() { //string molName2 = "Fe_4"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -6179,7 +6179,7 @@ public void Test_Fe_4() public void Test_Fe_3minus() { //string molName3 = "Fe_3minus"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = -3; @@ -6222,7 +6222,7 @@ public void Test_Fe_3minus() public void Test_Fe_2plus() { //string molName4 = "Fe_2plus"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = 2; @@ -6235,7 +6235,7 @@ public void Test_Fe_2plus() public void Test_Fe_4minus() { //string molName5 = "Fe_4minus"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = -4; @@ -6279,7 +6279,7 @@ public void Test_Fe_4minus() public void Test_Fe_5() { //string molNameFe5 = "Fe_5"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = 0; @@ -6317,7 +6317,7 @@ public void Test_Fe_5() public void Test_Fe_6() { //string molName7 = "Fe_6"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = 0; @@ -6360,7 +6360,7 @@ public void Test_Fe_6() public void Test_Fe_2minus() { //string molName8 = "Fe_2minus"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = -2; @@ -6403,7 +6403,7 @@ public void Test_Fe_2minus() public void Test_Fe_3plus() { //string molName9 = "Fe_3plus"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = 3; @@ -6416,7 +6416,7 @@ public void Test_Fe_3plus() public void Test_Fe_2() { //string molNameA = "Fe_2"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -6439,7 +6439,7 @@ public void Test_Fe_2() public void Test_Fe_3() { //string molNameB = "Fe_3"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Fe"); a1.FormalCharge = 0; @@ -6469,7 +6469,7 @@ public void Test_Fe_3() [TestMethod()] public void TestSulphur4() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("S"); mol.Atoms.Add(a1); @@ -6520,7 +6520,7 @@ public void TestSulphur4() [TestMethod()] public void Test_Ru_3minus_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ru"); a1.FormalCharge = -3; @@ -6566,7 +6566,7 @@ public void Test_Ru_3minus_6() [TestMethod()] public void Test_Ru_2minus_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ru"); a1.FormalCharge = -2; @@ -6609,7 +6609,7 @@ public void Test_Ru_2minus_6() [TestMethod()] public void Test_Ru_10plus_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ru"); a1.FormalCharge = 0; @@ -6652,7 +6652,7 @@ public void Test_Ru_10plus_6() [TestMethod()] public void Test_Ru_6() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("Ru"); a1.FormalCharge = 0; diff --git a/NCDKTests/AtomTypes/CDKAtomTypeMatcherTestFileReposTest.cs b/NCDKTests/AtomTypes/CDKAtomTypeMatcherTestFileReposTest.cs index 3c8e333c..4459b4e7 100644 --- a/NCDKTests/AtomTypes/CDKAtomTypeMatcherTestFileReposTest.cs +++ b/NCDKTests/AtomTypes/CDKAtomTypeMatcherTestFileReposTest.cs @@ -18,8 +18,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Diagnostics; @@ -139,7 +139,7 @@ public void TestMDLMolfiles() private TestResults TestFile(string dir, string filename, Type readerType) { - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance); + CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance); var ins = ResourceLoader.GetAsStream(dir + filename); var reader = (ISimpleChemObjectReader)readerType.GetConstructor(new Type[] { typeof(Stream) }).Invoke(new object[] { ins }); IAtomContainer mol = null; @@ -150,7 +150,7 @@ private TestResults TestFile(string dir, string filename, Type readerType) else if (reader.Accepts(typeof(IChemFile))) { IChemFile cf = reader.Read(new ChemFile()); - mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + mol = ChemObjectBuilder.Instance.NewAtomContainer(); var containers = ChemFileManipulator.GetAllAtomContainers(cf); foreach (var container in containers) mol.Add(container); diff --git a/NCDKTests/AtomTypes/EStateAtomTypeMatcherTest.cs b/NCDKTests/AtomTypes/EStateAtomTypeMatcherTest.cs index a9234447..df8d13b5 100644 --- a/NCDKTests/AtomTypes/EStateAtomTypeMatcherTest.cs +++ b/NCDKTests/AtomTypes/EStateAtomTypeMatcherTest.cs @@ -19,11 +19,12 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; using NCDK.RingSearches; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; using System; +using System.Linq; namespace NCDK.AtomTypes { @@ -74,8 +75,8 @@ public void TestFindMatchingAtomType_IAtomContainer() mol.Atoms.Add(atom); // just check consistency; other methods do perception testing - IAtomType[] types = matcher.FindMatchingAtomTypes(mol); - for (int i = 0; i < types.Length; i++) + var types = matcher.FindMatchingAtomTypes(mol).ToList(); + for (int i = 0; i < types.Count; i++) { IAtomType type = matcher.FindMatchingAtomType(mol, mol.Atoms[i]); Assert.AreEqual(type.AtomTypeName, types[i].AtomTypeName); @@ -350,7 +351,7 @@ public void TestAromaticAtoms() [TestMethod()] public void TestBenzeneFromSmiles() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); mol = sp.ParseSmiles("C1=CC=CC=C1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); diff --git a/NCDKTests/AtomTypes/ReactionStructuresTest.cs b/NCDKTests/AtomTypes/ReactionStructuresTest.cs index 1f515c63..8639b661 100644 --- a/NCDKTests/AtomTypes/ReactionStructuresTest.cs +++ b/NCDKTests/AtomTypes/ReactionStructuresTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -726,8 +726,7 @@ public void TestM26() expected1.AddBond(expected1.Atoms[6], expected1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(expected1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); string[] expectedTypes = { "F.plus.sp2", "C.sp2", "C.minus.planar", "C.sp2", "C.sp2", "C.sp2", "C.sp2", "H", "H", "H", "H", "H" }; Assert.AreEqual(expectedTypes.Length, expected1.Atoms.Count); diff --git a/NCDKTests/AtomTypes/RepeatedCDKAtomTypeMatcherSMILESTest.cs b/NCDKTests/AtomTypes/RepeatedCDKAtomTypeMatcherSMILESTest.cs index 679d617a..cc668b75 100644 --- a/NCDKTests/AtomTypes/RepeatedCDKAtomTypeMatcherSMILESTest.cs +++ b/NCDKTests/AtomTypes/RepeatedCDKAtomTypeMatcherSMILESTest.cs @@ -20,6 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Smiles; using NCDK.Tools.Manipulator; +using System.Linq; namespace NCDK.AtomTypes { @@ -100,27 +101,25 @@ public void TestSMILES11() TypeAndRetype("CCCN1CC(CSC)CC2C1Cc3c[nH]c4cccc2c34"); } - private void TypeAndRetype(string smiles) + private static void TypeAndRetype(string smiles) { - IAtomContainer mol = smilesParser.ParseSmiles(smiles); - IAtomType[] types = atomTypeMatcher.FindMatchingAtomTypes(mol); - for (int i = 0; i < types.Length; i++) + var mol = smilesParser.ParseSmiles(smiles); + var types = atomTypeMatcher.FindMatchingAtomTypes(mol).ToList(); + for (int i = 0; i < types.Count; i++) { AtomTypeManipulator.Configure(mol.Atoms[i], types[i]); } - IAtomType[] retyped = atomTypeMatcher.FindMatchingAtomTypes(mol); - for (int i = 0; i < types.Length; i++) + var retyped = atomTypeMatcher.FindMatchingAtomTypes(mol).ToList(); + for (int i = 0; i < types.Count; i++) { Assert.AreEqual(types[i], retyped[i], - "First perception resulted in " + types[i] + " but the second perception " + "gave " - + retyped[i]); + $"First perception resulted in {types[i]} but the second perception gave {retyped[i]}"); } - retyped = atomTypeMatcher.FindMatchingAtomTypes(mol); - for (int i = 0; i < types.Length; i++) + retyped = atomTypeMatcher.FindMatchingAtomTypes(mol).ToList(); + for (int i = 0; i < types.Count; i++) { Assert.AreEqual(types[i], retyped[i], - "First perception resulted in " + types[i] + " but the third perception " + "gave " - + retyped[i]); + $"First perception resulted in {types[i]} but the third perception gave {retyped[i]}"); } } } diff --git a/NCDKTests/AtomTypes/ResonanceStructuresTest.cs b/NCDKTests/AtomTypes/ResonanceStructuresTest.cs index acc5131c..2a90bf85 100644 --- a/NCDKTests/AtomTypes/ResonanceStructuresTest.cs +++ b/NCDKTests/AtomTypes/ResonanceStructuresTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.AtomTypes { diff --git a/NCDKTests/AtomTypes/StructGenAtomTypeGuesserTest.cs b/NCDKTests/AtomTypes/StructGenAtomTypeGuesserTest.cs index c10c4806..bcf3c213 100644 --- a/NCDKTests/AtomTypes/StructGenAtomTypeGuesserTest.cs +++ b/NCDKTests/AtomTypes/StructGenAtomTypeGuesserTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Linq; namespace NCDK.AtomTypes diff --git a/NCDKTests/AtomTypes/StructGenMatcherTest.cs b/NCDKTests/AtomTypes/StructGenMatcherTest.cs index 655f05c2..bad0dea1 100644 --- a/NCDKTests/AtomTypes/StructGenMatcherTest.cs +++ b/NCDKTests/AtomTypes/StructGenMatcherTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using System.Collections.Generic; namespace NCDK.AtomTypes @@ -56,8 +56,8 @@ public void TestStructGenMatcher() [TestMethod()] public void TestFindMatchingAtomType_IAtomContainer_IAtom() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom = ChemObjectBuilder.Instance.NewAtom("C"); atom.ImplicitHydrogenCount = 4; mol.Atoms.Add(atom); @@ -85,15 +85,15 @@ public void TestN3() [TestMethod()] public void TestFlourine() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.ImplicitHydrogenCount = 0; mol.Atoms.Add(atom1); for (int i = 0; i < 4; i++) { - IAtom floruineAtom = Default.ChemObjectBuilder.Instance.NewAtom("F"); + IAtom floruineAtom = ChemObjectBuilder.Instance.NewAtom("F"); mol.Atoms.Add(floruineAtom); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); + IBond bond = ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); mol.Bonds.Add(bond); } @@ -112,15 +112,15 @@ public void TestFlourine() [TestMethod()] public void TestChlorine() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.ImplicitHydrogenCount = 0; mol.Atoms.Add(atom1); for (int i = 0; i < 4; i++) { - IAtom floruineAtom = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom floruineAtom = ChemObjectBuilder.Instance.NewAtom("Cl"); mol.Atoms.Add(floruineAtom); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); + IBond bond = ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); mol.Bonds.Add(bond); } @@ -139,15 +139,15 @@ public void TestChlorine() [TestMethod()] public void TestBromine() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.ImplicitHydrogenCount = 0; mol.Atoms.Add(atom1); for (int i = 0; i < 4; i++) { - IAtom floruineAtom = Default.ChemObjectBuilder.Instance.NewAtom("Br"); + IAtom floruineAtom = ChemObjectBuilder.Instance.NewAtom("Br"); mol.Atoms.Add(floruineAtom); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); + IBond bond = ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); mol.Bonds.Add(bond); } @@ -166,15 +166,15 @@ public void TestBromine() [TestMethod()] public void TestIodine() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.ImplicitHydrogenCount = 0; mol.Atoms.Add(atom1); for (int i = 0; i < 4; i++) { - IAtom floruineAtom = Default.ChemObjectBuilder.Instance.NewAtom("I"); + IAtom floruineAtom = ChemObjectBuilder.Instance.NewAtom("I"); mol.Atoms.Add(floruineAtom); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); + IBond bond = ChemObjectBuilder.Instance.NewBond(floruineAtom, atom1); mol.Bonds.Add(bond); } @@ -193,10 +193,10 @@ public void TestIodine() [TestMethod()] public void TestLithium() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("Li"); - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("F"); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(atom1, atom2); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("Li"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("F"); + IBond bond = ChemObjectBuilder.Instance.NewBond(atom1, atom2); mol.Atoms.Add(atom1); mol.Atoms.Add(atom2); mol.Bonds.Add(bond); @@ -213,15 +213,15 @@ public void TestLithium() [TestMethod()] public void TestArsenic() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("As"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("As"); atom1.ImplicitHydrogenCount = 0; mol.Atoms.Add(atom1); for (int i = 0; i < 3; i++) { - IAtom atom = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom atom = ChemObjectBuilder.Instance.NewAtom("Cl"); mol.Atoms.Add(atom); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(atom, atom1, + IBond bond = ChemObjectBuilder.Instance.NewBond(atom, atom1, BondOrder.Single); mol.Bonds.Add(bond); } @@ -242,17 +242,17 @@ public void TestArsenic() [TestMethod()] public void TestOxygen1() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom carbon = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom carbon = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); carbon.ImplicitHydrogenCount = 1; o1.ImplicitHydrogenCount = 1; o2.ImplicitHydrogenCount = 0; - IBond bond1 = Default.ChemObjectBuilder.Instance.NewBond(carbon, o1, BondOrder.Single); - IBond bond2 = Default.ChemObjectBuilder.Instance.NewBond(carbon, o2, BondOrder.Double); + IBond bond1 = ChemObjectBuilder.Instance.NewBond(carbon, o1, BondOrder.Single); + IBond bond2 = ChemObjectBuilder.Instance.NewBond(carbon, o2, BondOrder.Double); mol.Atoms.Add(carbon); mol.Atoms.Add(o1); @@ -277,15 +277,15 @@ public void TestOxygen1() [TestMethod()] public void TestOxygen2() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond bond1 = Default.ChemObjectBuilder.Instance.NewBond(h1, o1, BondOrder.Single); - IBond bond2 = Default.ChemObjectBuilder.Instance.NewBond(o1, o2, BondOrder.Single); - IBond bond3 = Default.ChemObjectBuilder.Instance.NewBond(o2, h2, BondOrder.Single); + IBond bond1 = ChemObjectBuilder.Instance.NewBond(h1, o1, BondOrder.Single); + IBond bond2 = ChemObjectBuilder.Instance.NewBond(o1, o2, BondOrder.Single); + IBond bond3 = ChemObjectBuilder.Instance.NewBond(o2, h2, BondOrder.Single); mol.Atoms.Add(o1); mol.Atoms.Add(o2); @@ -316,17 +316,17 @@ public void TestOxygen2() [TestMethod()] public void TestP4() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom p = Default.ChemObjectBuilder.Instance.NewAtom("P"); - IAtom cl1 = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); - IAtom cl2 = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); - IAtom cl3 = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - - IBond bond1 = Default.ChemObjectBuilder.Instance.NewBond(p, cl1, BondOrder.Single); - IBond bond2 = Default.ChemObjectBuilder.Instance.NewBond(p, cl2, BondOrder.Single); - IBond bond3 = Default.ChemObjectBuilder.Instance.NewBond(p, cl3, BondOrder.Single); - IBond bond4 = Default.ChemObjectBuilder.Instance.NewBond(p, s, BondOrder.Double); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom p = ChemObjectBuilder.Instance.NewAtom("P"); + IAtom cl1 = ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom cl2 = ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom cl3 = ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); + + IBond bond1 = ChemObjectBuilder.Instance.NewBond(p, cl1, BondOrder.Single); + IBond bond2 = ChemObjectBuilder.Instance.NewBond(p, cl2, BondOrder.Single); + IBond bond3 = ChemObjectBuilder.Instance.NewBond(p, cl3, BondOrder.Single); + IBond bond4 = ChemObjectBuilder.Instance.NewBond(p, s, BondOrder.Double); mol.Atoms.Add(p); mol.Atoms.Add(cl1); @@ -359,25 +359,25 @@ public void TestP4() [TestMethod()] public void TestP3() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom p = Default.ChemObjectBuilder.Instance.NewAtom("P"); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o3 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom p = ChemObjectBuilder.Instance.NewAtom("P"); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o3 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c1.ImplicitHydrogenCount = 3; c2.ImplicitHydrogenCount = 3; c3.ImplicitHydrogenCount = 3; - IBond bond1 = Default.ChemObjectBuilder.Instance.NewBond(p, o1, BondOrder.Single); - IBond bond2 = Default.ChemObjectBuilder.Instance.NewBond(p, o2, BondOrder.Single); - IBond bond3 = Default.ChemObjectBuilder.Instance.NewBond(p, o3, BondOrder.Single); - IBond bond4 = Default.ChemObjectBuilder.Instance.NewBond(c1, o1, BondOrder.Single); - IBond bond5 = Default.ChemObjectBuilder.Instance.NewBond(c2, o2, BondOrder.Single); - IBond bond6 = Default.ChemObjectBuilder.Instance.NewBond(c3, o3, BondOrder.Single); + IBond bond1 = ChemObjectBuilder.Instance.NewBond(p, o1, BondOrder.Single); + IBond bond2 = ChemObjectBuilder.Instance.NewBond(p, o2, BondOrder.Single); + IBond bond3 = ChemObjectBuilder.Instance.NewBond(p, o3, BondOrder.Single); + IBond bond4 = ChemObjectBuilder.Instance.NewBond(c1, o1, BondOrder.Single); + IBond bond5 = ChemObjectBuilder.Instance.NewBond(c2, o2, BondOrder.Single); + IBond bond6 = ChemObjectBuilder.Instance.NewBond(c3, o3, BondOrder.Single); mol.Atoms.Add(p); mol.Atoms.Add(o1); @@ -409,10 +409,10 @@ public void TestP3() [TestMethod()] public void TestNa1() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom na = Default.ChemObjectBuilder.Instance.NewAtom("Na"); - IAtom cl = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(na, cl, BondOrder.Single); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom na = ChemObjectBuilder.Instance.NewAtom("Na"); + IAtom cl = ChemObjectBuilder.Instance.NewAtom("Cl"); + IBond bond = ChemObjectBuilder.Instance.NewBond(na, cl, BondOrder.Single); mol.Atoms.Add(na); mol.Atoms.Add(cl); mol.Bonds.Add(bond); @@ -431,19 +431,19 @@ public void TestNa1() [TestMethod()] public void TestSi4() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom si = Default.ChemObjectBuilder.Instance.NewAtom("Si"); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom cl1 = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); - IAtom cl2 = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); - IAtom cl3 = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom si = ChemObjectBuilder.Instance.NewAtom("Si"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom cl1 = ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom cl2 = ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtom cl3 = ChemObjectBuilder.Instance.NewAtom("Cl"); c1.ImplicitHydrogenCount = 3; - IBond bond1 = Default.ChemObjectBuilder.Instance.NewBond(si, c1, BondOrder.Single); - IBond bond2 = Default.ChemObjectBuilder.Instance.NewBond(si, cl1, BondOrder.Single); - IBond bond3 = Default.ChemObjectBuilder.Instance.NewBond(si, cl2, BondOrder.Single); - IBond bond4 = Default.ChemObjectBuilder.Instance.NewBond(si, cl3, BondOrder.Single); + IBond bond1 = ChemObjectBuilder.Instance.NewBond(si, c1, BondOrder.Single); + IBond bond2 = ChemObjectBuilder.Instance.NewBond(si, cl1, BondOrder.Single); + IBond bond3 = ChemObjectBuilder.Instance.NewBond(si, cl2, BondOrder.Single); + IBond bond4 = ChemObjectBuilder.Instance.NewBond(si, cl3, BondOrder.Single); mol.Atoms.Add(si); mol.Atoms.Add(c1); @@ -476,8 +476,8 @@ public void TestSi4() [TestMethod()] public void TestS2() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); s.ImplicitHydrogenCount = 2; mol.Atoms.Add(s); @@ -488,12 +488,12 @@ public void TestS2() matched = matcher.FindMatchingAtomType(mol, mol.Atoms[0]); AssertAtomType(testedAtomTypes, "S2", matched); - mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(s, h2, BondOrder.Single); + mol = ChemObjectBuilder.Instance.NewAtomContainer(); + s = ChemObjectBuilder.Instance.NewAtom("S"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); + IBond b2 = ChemObjectBuilder.Instance.NewBond(s, h2, BondOrder.Single); mol.Atoms.Add(s); mol.Atoms.Add(h1); @@ -516,13 +516,13 @@ public void TestS2() [TestMethod()] public void TestS3() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, o1, BondOrder.Double); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(s, o2, BondOrder.Double); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, o1, BondOrder.Double); + IBond b2 = ChemObjectBuilder.Instance.NewBond(s, o2, BondOrder.Double); mol.Atoms.Add(s); mol.Atoms.Add(o1); @@ -548,14 +548,14 @@ public void TestS3() [TestMethod()] public void TestS4() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); mol.Atoms.Add(s); for (int i = 0; i < 6; i++) { - IAtom f = Default.ChemObjectBuilder.Instance.NewAtom("F"); + IAtom f = ChemObjectBuilder.Instance.NewAtom("F"); mol.Atoms.Add(f); - IBond bond = Default.ChemObjectBuilder.Instance.NewBond(s, f, BondOrder.Single); + IBond bond = ChemObjectBuilder.Instance.NewBond(s, f, BondOrder.Single); mol.Bonds.Add(bond); } @@ -576,15 +576,15 @@ public void TestS4() [TestMethod()] public void TestS4oxide() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o3 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o3 = ChemObjectBuilder.Instance.NewAtom("O"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, o1, BondOrder.Double); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(s, o2, BondOrder.Double); - IBond b3 = Default.ChemObjectBuilder.Instance.NewBond(s, o3, BondOrder.Double); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, o1, BondOrder.Double); + IBond b2 = ChemObjectBuilder.Instance.NewBond(s, o2, BondOrder.Double); + IBond b3 = ChemObjectBuilder.Instance.NewBond(s, o3, BondOrder.Double); mol.Atoms.Add(s); mol.Atoms.Add(o1); @@ -615,13 +615,13 @@ public void TestS4oxide() [TestMethod()] public void TestN3acid() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom n = Default.ChemObjectBuilder.Instance.NewAtom("N"); - IAtom o = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom h = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom n = ChemObjectBuilder.Instance.NewAtom("N"); + IAtom o = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom h = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(n, o, BondOrder.Double); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(n, h, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(n, o, BondOrder.Double); + IBond b2 = ChemObjectBuilder.Instance.NewBond(n, h, BondOrder.Single); mol.Atoms.Add(n); mol.Atoms.Add(o); @@ -646,16 +646,16 @@ public void TestN3acid() [TestMethod()] public void TestN3cyanide() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom n = Default.ChemObjectBuilder.Instance.NewAtom("N"); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom n = ChemObjectBuilder.Instance.NewAtom("N"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c1.ImplicitHydrogenCount = 0; c2.ImplicitHydrogenCount = 3; - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(n, c1, BondOrder.Triple); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(c1, c2, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(n, c1, BondOrder.Triple); + IBond b2 = ChemObjectBuilder.Instance.NewBond(c1, c2, BondOrder.Single); mol.Atoms.Add(n); mol.Atoms.Add(c1); @@ -681,17 +681,17 @@ public void TestN3cyanide() [TestMethod()] public void TestN5() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom n = Default.ChemObjectBuilder.Instance.NewAtom("N"); - IAtom o1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom o2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom c = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom n = ChemObjectBuilder.Instance.NewAtom("N"); + IAtom o1 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom o2 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom c = ChemObjectBuilder.Instance.NewAtom("C"); c.ImplicitHydrogenCount = 3; - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(n, o1, BondOrder.Double); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(n, o2, BondOrder.Double); - IBond b3 = Default.ChemObjectBuilder.Instance.NewBond(n, c, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(n, o1, BondOrder.Double); + IBond b2 = ChemObjectBuilder.Instance.NewBond(n, o2, BondOrder.Double); + IBond b3 = ChemObjectBuilder.Instance.NewBond(n, c, BondOrder.Single); mol.Atoms.Add(n); mol.Atoms.Add(o1); @@ -722,15 +722,15 @@ public void TestN5() [TestMethod()] public void TestB3() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom b = Default.ChemObjectBuilder.Instance.NewAtom("B"); - IAtom f1 = Default.ChemObjectBuilder.Instance.NewAtom("F"); - IAtom f2 = Default.ChemObjectBuilder.Instance.NewAtom("F"); - IAtom f3 = Default.ChemObjectBuilder.Instance.NewAtom("F"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom b = ChemObjectBuilder.Instance.NewAtom("B"); + IAtom f1 = ChemObjectBuilder.Instance.NewAtom("F"); + IAtom f2 = ChemObjectBuilder.Instance.NewAtom("F"); + IAtom f3 = ChemObjectBuilder.Instance.NewAtom("F"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(b, f1, BondOrder.Single); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(b, f2, BondOrder.Single); - IBond b3 = Default.ChemObjectBuilder.Instance.NewBond(b, f3, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(b, f1, BondOrder.Single); + IBond b2 = ChemObjectBuilder.Instance.NewBond(b, f2, BondOrder.Single); + IBond b3 = ChemObjectBuilder.Instance.NewBond(b, f3, BondOrder.Single); mol.Atoms.Add(b); mol.Atoms.Add(f1); @@ -759,10 +759,10 @@ public void TestB3() [TestMethod()] public void TestSe2() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom se = Default.ChemObjectBuilder.Instance.NewAtom("Se"); - IAtom o = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(se, o, BondOrder.Double); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom se = ChemObjectBuilder.Instance.NewAtom("Se"); + IAtom o = ChemObjectBuilder.Instance.NewAtom("O"); + IBond b1 = ChemObjectBuilder.Instance.NewBond(se, o, BondOrder.Double); mol.Atoms.Add(se); mol.Atoms.Add(o); mol.Bonds.Add(b1); diff --git a/NCDKTests/AtomTypes/SybylAtomTypeMatcherTest.cs b/NCDKTests/AtomTypes/SybylAtomTypeMatcherTest.cs index 9f930129..9b5bd379 100644 --- a/NCDKTests/AtomTypes/SybylAtomTypeMatcherTest.cs +++ b/NCDKTests/AtomTypes/SybylAtomTypeMatcherTest.cs @@ -18,11 +18,12 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Templates; using NCDK.Tools.Manipulator; using System.Collections.Generic; +using System.Linq; namespace NCDK.AtomTypes { @@ -36,56 +37,54 @@ namespace NCDK.AtomTypes [TestClass()] public class SybylAtomTypeMatcherTest : AbstractSybylAtomTypeTest { - private static IDictionary testedAtomTypes = new Dictionary(); - - static SybylAtomTypeMatcherTest() + private static readonly IDictionary testedAtomTypes = new Dictionary { // do not complain about a few non-tested atom types // so, just mark them as tested - testedAtomTypes["LP"] = 1; - testedAtomTypes["Du"] = 1; - testedAtomTypes["Du.C"] = 1; - testedAtomTypes["Any"] = 1; - testedAtomTypes["Hal"] = 1; - testedAtomTypes["Het"] = 1; - testedAtomTypes["Hev"] = 1; - testedAtomTypes["X"] = 1; - testedAtomTypes["Het"] = 1; - testedAtomTypes["H.t3p"] = 1; - testedAtomTypes["H.spc"] = 1; - testedAtomTypes["O.t3p"] = 1; - testedAtomTypes["O.spc"] = 1; - } + ["LP"] = 1, + ["Du"] = 1, + ["Du.C"] = 1, + ["Any"] = 1, + ["Hal"] = 1, + ["Het"] = 1, + ["Hev"] = 1, + ["X"] = 1, + ["Het"] = 1, + ["H.t3p"] = 1, + ["H.spc"] = 1, + ["O.t3p"] = 1, + ["O.spc"] = 1, + }; [TestMethod()] public void TestGetInstance_IChemObjectBuilder() { - IAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(Silent.ChemObjectBuilder.Instance); + var matcher = SybylAtomTypeMatcher.GetInstance(Silent.ChemObjectBuilder.Instance); Assert.IsNotNull(matcher); } [TestMethod()] public void TestFindMatchingAtomType_IAtomContainer_IAtom() { - IAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(Silent.ChemObjectBuilder.Instance); + var matcher = SybylAtomTypeMatcher.GetInstance(Silent.ChemObjectBuilder.Instance); Assert.IsNotNull(matcher); - IAtomContainer ethane = TestMoleculeFactory.MakeAlkane(2); - string[] expectedTypes = { "C.3", "C.3" }; + var ethane = TestMoleculeFactory.MakeAlkane(2); + var expectedTypes = new[] { "C.3", "C.3" }; AssertAtomTypes(testedAtomTypes, expectedTypes, ethane); } [TestMethod()] public void TestFindMatchingAtomType_IAtomContainer() { - string filename = "NCDK.Data.Mol2.atomtyping.mol2"; + var filename = "NCDK.Data.Mol2.atomtyping.mol2"; var ins = ResourceLoader.GetAsStream(filename); - Mol2Reader reader = new Mol2Reader(ins); - IAtomContainer mol = (IAtomContainer)reader.Read(new AtomContainer()); + var reader = new Mol2Reader(ins); + var mol = reader.Read(new AtomContainer()); // just check consistency; other methods do perception testing - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(Default.ChemObjectBuilder.Instance); - IAtomType[] types = matcher.FindMatchingAtomTypes(mol); - for (int i = 0; i < types.Length; i++) + var matcher = SybylAtomTypeMatcher.GetInstance(ChemObjectBuilder.Instance); + var types = matcher.FindMatchingAtomTypes(mol).ToList(); + for (int i = 0; i < types.Count; i++) { IAtomType type = matcher.FindMatchingAtomType(mol, mol.Atoms[i]); Assert.AreEqual(type.AtomTypeName, types[i].AtomTypeName); @@ -97,15 +96,15 @@ public void TestAtomTyping() { string filename = "NCDK.Data.Mol2.atomtyping.mol2"; var ins = ResourceLoader.GetAsStream(filename); - Mol2Reader reader = new Mol2Reader(ins); - IAtomContainer molecule = (IAtomContainer)reader.Read(new AtomContainer()); + var reader = new Mol2Reader(ins); + var molecule = (IAtomContainer)reader.Read(new AtomContainer()); Assert.IsNotNull(molecule); - IAtomContainer reference = (IAtomContainer)molecule.Clone(); + var reference = (IAtomContainer)molecule.Clone(); // test if the perceived atom types match that PercieveAtomTypesAndConfigureAtoms(molecule); - IEnumerator refAtoms = reference.Atoms.GetEnumerator(); - IEnumerator atoms = molecule.Atoms.GetEnumerator(); + var refAtoms = reference.Atoms.GetEnumerator(); + var atoms = molecule.Atoms.GetEnumerator(); while (atoms.MoveNext() && refAtoms.MoveNext()) { // work around aromaticity, which we skipped for now @@ -120,11 +119,11 @@ public void TestAtomTyping() [TestMethod()] public void TestBenzene() { - IAtomContainer benzene = TestMoleculeFactory.MakeBenzene(); + var benzene = TestMoleculeFactory.MakeBenzene(); // test if the perceived atom types match that - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(benzene.Builder); - IAtomType[] types = matcher.FindMatchingAtomTypes(benzene); + var matcher = SybylAtomTypeMatcher.GetInstance(benzene.Builder); + var types = matcher.FindMatchingAtomTypes(benzene); foreach (var type in types) { Assert.AreEqual("C.ar", type.AtomTypeName); @@ -134,13 +133,13 @@ public void TestBenzene() [TestMethod()] public void TestAdenine() { - IAtomContainer mol = TestMoleculeFactory.MakeAdenine(); - string[] expectedTypes = { "C.ar", "C.ar", "C.ar", "N.ar", "N.ar", "N.ar", "N.ar", "N.3", "C.ar", "C.ar" }; - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(mol.Builder); - IAtomType[] types = matcher.FindMatchingAtomTypes(mol); + var mol = TestMoleculeFactory.MakeAdenine(); + var expectedTypes = new[] { "C.ar", "C.ar", "C.ar", "N.ar", "N.ar", "N.ar", "N.ar", "N.3", "C.ar", "C.ar" }; + var matcher = SybylAtomTypeMatcher.GetInstance(mol.Builder); + var types = matcher.FindMatchingAtomTypes(mol).ToList(); for (int i = 0; i < expectedTypes.Length; i++) { - AssertAtomType(testedAtomTypes, "Incorrect perception for atom " + i, expectedTypes[i], types[i]); + AssertAtomType(testedAtomTypes, $"Incorrect perception for atom {i}", expectedTypes[i], types[i]); } } @@ -150,11 +149,11 @@ public void TestAdenine() [TestMethod()] public void TestBenzene_AtomContainer() { - IAtomContainer benzene = TestMoleculeFactory.MakeBenzene(); + var benzene = TestMoleculeFactory.MakeBenzene(); // test if the perceived atom types match that - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(benzene.Builder); - IAtomType[] types = matcher.FindMatchingAtomTypes(benzene); + var matcher = SybylAtomTypeMatcher.GetInstance(benzene.Builder); + var types = matcher.FindMatchingAtomTypes(benzene); foreach (var type in types) { Assert.AreEqual("C.ar", type.AtomTypeName); @@ -164,17 +163,17 @@ public void TestBenzene_AtomContainer() [TestMethod()] public void TestAtomTyping4() { - string filename = "NCDK.Data.Mol2.atomtyping4.mol2"; + var filename = "NCDK.Data.Mol2.atomtyping4.mol2"; var ins = ResourceLoader.GetAsStream(filename); - Mol2Reader reader = new Mol2Reader(ins); - IAtomContainer molecule = (IAtomContainer)reader.Read(new AtomContainer()); + var reader = new Mol2Reader(ins); + var molecule = (IAtomContainer)reader.Read(new AtomContainer()); Assert.IsNotNull(molecule); - IAtomContainer reference = (IAtomContainer)molecule.Clone(); + var reference = (IAtomContainer)molecule.Clone(); // test if the perceived atom types match that PercieveAtomTypesAndConfigureAtoms(molecule); - IEnumerator refAtoms = reference.Atoms.GetEnumerator(); - IEnumerator atoms = molecule.Atoms.GetEnumerator(); + var refAtoms = reference.Atoms.GetEnumerator(); + var atoms = molecule.Atoms.GetEnumerator(); while (atoms.MoveNext() && refAtoms.MoveNext()) { // work around aromaticity, which we skipped for now @@ -191,11 +190,11 @@ public void TestAtomTyping4() [TestMethod()] public void TestNonExistingType() { - IAtomContainer mol = new AtomContainer(); - IAtom atom = new Atom(); + var mol = new AtomContainer(); + var atom = new Atom(); mol.Atoms.Add(atom); - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(mol.Builder); - IAtomType type = matcher.FindMatchingAtomType(mol, atom); + var matcher = SybylAtomTypeMatcher.GetInstance(mol.Builder); + var type = matcher.FindMatchingAtomType(mol, atom); Assert.IsNotNull(type); Assert.AreEqual("X", type.AtomTypeName); } @@ -203,17 +202,17 @@ public void TestNonExistingType() [TestMethod()] public void TestAtomTyping2() { - string filename = "NCDK.Data.Mol2.atomtyping2.mol2"; + var filename = "NCDK.Data.Mol2.atomtyping2.mol2"; var ins = ResourceLoader.GetAsStream(filename); - Mol2Reader reader = new Mol2Reader(ins); - IAtomContainer molecule = (IAtomContainer)reader.Read(new AtomContainer()); + var reader = new Mol2Reader(ins); + var molecule = reader.Read(new AtomContainer()); Assert.IsNotNull(molecule); - IAtomContainer reference = (IAtomContainer)molecule.Clone(); + var reference = (IAtomContainer)molecule.Clone(); // test if the perceived atom types match that PercieveAtomTypesAndConfigureAtoms(molecule); - IEnumerator refAtoms = reference.Atoms.GetEnumerator(); - IEnumerator atoms = molecule.Atoms.GetEnumerator(); + var refAtoms = reference.Atoms.GetEnumerator(); + var atoms = molecule.Atoms.GetEnumerator(); while (atoms.MoveNext() && refAtoms.MoveNext()) { // work around aromaticity, which we skipped for now @@ -227,17 +226,17 @@ public void TestAtomTyping2() [TestMethod()] public void TestAtomTyping3() { - string filename = "NCDK.Data.Mol2.atomtyping3.mol2"; + var filename = "NCDK.Data.Mol2.atomtyping3.mol2"; var ins = ResourceLoader.GetAsStream(filename); - Mol2Reader reader = new Mol2Reader(ins); - IAtomContainer molecule = (IAtomContainer)reader.Read(new AtomContainer()); + var reader = new Mol2Reader(ins); + var molecule = (IAtomContainer)reader.Read(new AtomContainer()); Assert.IsNotNull(molecule); - IAtomContainer reference = (IAtomContainer)molecule.Clone(); + var reference = (IAtomContainer)molecule.Clone(); // test if the perceived atom types match that PercieveAtomTypesAndConfigureAtoms(molecule); - IEnumerator refAtoms = reference.Atoms.GetEnumerator(); - IEnumerator atoms = molecule.Atoms.GetEnumerator(); + var refAtoms = reference.Atoms.GetEnumerator(); + var atoms = molecule.Atoms.GetEnumerator(); while (atoms.MoveNext() && refAtoms.MoveNext()) { // work around aromaticity, which we skipped for now @@ -248,16 +247,17 @@ public void TestAtomTyping3() } } - private void PercieveAtomTypesAndConfigureAtoms(IAtomContainer container) + private static void PercieveAtomTypesAndConfigureAtoms(IAtomContainer container) { - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(container.Builder); - IEnumerator atoms = container.Atoms.GetEnumerator(); + var matcher = SybylAtomTypeMatcher.GetInstance(container.Builder); + var atoms = container.Atoms.GetEnumerator(); while (atoms.MoveNext()) { - IAtom atom = atoms.Current; + var atom = atoms.Current; atom.AtomTypeName = null; - IAtomType matched = matcher.FindMatchingAtomType(container, atom); - if (matched != null) AtomTypeManipulator.Configure(atom, matched); + var matched = matcher.FindMatchingAtomType(container, atom); + if (matched != null) + AtomTypeManipulator.Configure(atom, matched); } } @@ -707,13 +707,13 @@ public void TestSalts() [TestMethod()] public void TestH2S() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom s = Default.ChemObjectBuilder.Instance.NewAtom("S"); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom s = ChemObjectBuilder.Instance.NewAtom("S"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(s, h2, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(s, h1, BondOrder.Single); + IBond b2 = ChemObjectBuilder.Instance.NewBond(s, h2, BondOrder.Single); mol.Atoms.Add(s); mol.Atoms.Add(h1); @@ -755,8 +755,7 @@ public void TestFerrocene() ferrocene.AddBond(ferrocene.Atoms[8], ferrocene.Atoms[9], BondOrder.Single); ferrocene.AddBond(ferrocene.Atoms[9], ferrocene.Atoms[5], BondOrder.Single); - string[] expectedTypes = new string[]{"C.2", "C.2", "C.2", "C.2", "Any", "C.2", "C.2", "C.2", "C.2", "Any", - "Fe"}; + var expectedTypes = new string[] {"C.2", "C.2", "C.2", "C.2", "Any", "C.2", "C.2", "C.2", "C.2", "Any", "Fe"}; AssertAtomTypes(testedAtomTypes, expectedTypes, ferrocene); } @@ -770,21 +769,21 @@ public void TestHCN() mol.Atoms.Add(atom2); mol.AddBond(mol.Atoms[0], mol.Atoms[1], BondOrder.Triple); - string[] expectedTypes = { "N.1", "C.1" }; + var expectedTypes = new[] { "N.1", "C.1" }; AssertAtomTypes(testedAtomTypes, expectedTypes, mol); } [TestMethod()] public void TestAniline() { - IAtomContainer benzene = TestMoleculeFactory.MakeBenzene(); - IAtom nitrogen = benzene.Builder.NewAtom("N"); + var benzene = TestMoleculeFactory.MakeBenzene(); + var nitrogen = benzene.Builder.NewAtom("N"); benzene.Atoms.Add(nitrogen); benzene.Bonds.Add(benzene.Builder.NewBond(benzene.Atoms[0], nitrogen, BondOrder.Single)); // test if the perceived atom types match that - SybylAtomTypeMatcher matcher = SybylAtomTypeMatcher.GetInstance(benzene.Builder); - IAtomType[] types = matcher.FindMatchingAtomTypes(benzene); + var matcher = SybylAtomTypeMatcher.GetInstance(benzene.Builder); + var types = matcher.FindMatchingAtomTypes(benzene).ToList(); for (int i = 0; i < 6; i++) { AssertAtomType(testedAtomTypes, "Incorrect perception for atom " + i, "C.ar", types[i]); @@ -852,13 +851,13 @@ public void TestZincChloride() [TestMethod()] public void TestH2Se() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom se = Default.ChemObjectBuilder.Instance.NewAtom("Se"); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom se = ChemObjectBuilder.Instance.NewAtom("Se"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); - IBond b1 = Default.ChemObjectBuilder.Instance.NewBond(se, h1, BondOrder.Single); - IBond b2 = Default.ChemObjectBuilder.Instance.NewBond(se, h2, BondOrder.Single); + IBond b1 = ChemObjectBuilder.Instance.NewBond(se, h1, BondOrder.Single); + IBond b2 = ChemObjectBuilder.Instance.NewBond(se, h2, BondOrder.Single); mol.Atoms.Add(se); mol.Atoms.Add(h1); diff --git a/NCDKTests/Beam/Core/DaylightDelocalisationTest.cs b/NCDKTests/Beam/Core/DaylightDelocalisationTest.cs index 11ae0fd1..ced2ab07 100644 --- a/NCDKTests/Beam/Core/DaylightDelocalisationTest.cs +++ b/NCDKTests/Beam/Core/DaylightDelocalisationTest.cs @@ -7,7 +7,7 @@ namespace NCDK.Beam [TestClass()] public class DaylightDelocalisationTest { - void Assert_AreEqual(object expected, object actual) + static void Assert_AreEqual(object expected, object actual) { Assert.IsTrue(Compares.AreDeepEqual(expected, actual)); } diff --git a/NCDKTests/Beam/Core/TopologyTest.cs b/NCDKTests/Beam/Core/TopologyTest.cs index 440f0724..456ca863 100644 --- a/NCDKTests/Beam/Core/TopologyTest.cs +++ b/NCDKTests/Beam/Core/TopologyTest.cs @@ -26,13 +26,13 @@ public void UnknownAtom() [TestMethod()] public void UnknownTransform() { - Assert.AreSame(Topology.Unknown, Topology.Unknown.Transform(new int[0])); + Assert.AreSame(Topology.Unknown, Topology.Unknown.Transform(Array.Empty())); } [TestMethod()] public void UnknownOrderBy() { - Assert.AreSame(Topology.Unknown, Topology.Unknown.OrderBy(new int[0])); + Assert.AreSame(Topology.Unknown, Topology.Unknown.OrderBy(Array.Empty())); } [TestMethod()] @@ -314,14 +314,14 @@ public void ImplicitToExplicit_ohs() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Create_AntiClockwise() { - Topology.Create(0, new int[0], new List(), Configuration.AntiClockwise); + Topology.Create(0, Array.Empty(), new List(), Configuration.AntiClockwise); } [TestMethod()] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Create_Clockwise() { - Topology.Create(0, new int[0], new List(), Configuration.Clockwise); + Topology.Create(0, Array.Empty(), new List(), Configuration.Clockwise); } [TestMethod()] @@ -379,7 +379,7 @@ public void Create_oh() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Create_al() { - Assert.AreEqual(Topology.Unknown, Topology.Create(0, new int[0], new List(), Configuration.AL1)); + Assert.AreEqual(Topology.Unknown, Topology.Create(0, Array.Empty(), new List(), Configuration.AL1)); } [TestMethod()] diff --git a/NCDKTests/CDKExceptionTest.cs b/NCDKTests/CDKExceptionTest.cs index 3539147e..0d0301c4 100644 --- a/NCDKTests/CDKExceptionTest.cs +++ b/NCDKTests/CDKExceptionTest.cs @@ -45,7 +45,7 @@ public void TestCDKException_String_Throwable() string EXPLANATION = "No, CDK cannot compute the multidollar ligand you search for target X."; try { - int[] array = new int[0]; + int[] array = Array.Empty(); int dummy = array[50]; dummy = dummy + 1; Assert.Fail("Should not have reached this place. The test *requires* the error to occur!"); diff --git a/NCDKTests/Charges/ElectronegativityTest.cs b/NCDKTests/Charges/ElectronegativityTest.cs index a92d50b1..edb60d37 100644 --- a/NCDKTests/Charges/ElectronegativityTest.cs +++ b/NCDKTests/Charges/ElectronegativityTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -29,7 +29,6 @@ namespace NCDK.Charges public class ElectronegativityTest : CDKTestCase { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); public ElectronegativityTest() : base() @@ -61,7 +60,7 @@ public void TestCalculateSigmaElectronegativity_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) Assert.AreEqual(testResult[i], pe.CalculateSigmaElectronegativity(molecule, molecule.Atoms[i]), 0.001); @@ -81,7 +80,7 @@ public void TestCalculateSigmaElectronegativity_IAtomContainer_IAtom_Int_Int() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs b/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs index d18c9596..d0979f44 100644 --- a/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs +++ b/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs @@ -19,8 +19,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System.IO; @@ -35,7 +35,6 @@ namespace NCDK.Charges public class GasteigerMarsiliPartialChargesTest : CDKTestCase { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); /// /// A unit test with methylenfluoride @@ -55,7 +54,7 @@ public void TestCalculateCharges_IAtomContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); peoe.CalculateCharges(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -79,7 +78,7 @@ public void TestAssignGasteigerMarsiliSigmaPartialCharges_IAtomContainer_Boolean AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); peoe.AssignGasteigerMarsiliSigmaPartialCharges(molecule, true); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -103,7 +102,7 @@ public void TestAssignGasteigerSigmaMarsiliFactors_IAtomContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); foreach (var atom in molecule.Atoms) atom.Charge = 0.0; @@ -193,7 +192,7 @@ public void TestUndefinedPartialCharge() AddExplicitHydrogens(ac); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); - lpcheck.Saturate(ac); + LonePairElectronChecker.Saturate(ac); GasteigerMarsiliPartialCharges peoe = new GasteigerMarsiliPartialCharges(); peoe.CalculateCharges(ac); diff --git a/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs b/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs index 92bb8b3f..4120bbb9 100644 --- a/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs +++ b/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -34,8 +34,7 @@ namespace NCDK.Charges public class GasteigerPEPEPartialChargesTest : CDKTestCase { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + /// /// A unit test for JUnit with methylenfluoride /// @@ -54,7 +53,7 @@ public void TestCalculateCharges_IAtomContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); peoe.CalculateCharges(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -71,13 +70,13 @@ public void TestAromaticBondOrders() GasteigerPEPEPartialCharges peoe = new GasteigerPEPEPartialCharges(); string smiles1 = "c1ccccc1"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles(smiles1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); Aromaticity.CDKLegacy.Apply(mol1); AddExplicitHydrogens(mol1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); - lpcheck.Saturate(mol1); + LonePairElectronChecker.Saturate(mol1); List oldBondOrders = new List(); for (int i = 0; i < mol1.Bonds.Count; i++) @@ -103,7 +102,7 @@ public void TestAromaticAndNonAromatic() string smiles1 = "c1ccccc1"; string smiles2 = "C1=CC=CC=C1"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles(smiles1); IAtomContainer mol2 = sp.ParseSmiles(smiles2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); @@ -113,11 +112,11 @@ public void TestAromaticAndNonAromatic() AddExplicitHydrogens(mol1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); - lpcheck.Saturate(mol1); + LonePairElectronChecker.Saturate(mol1); AddExplicitHydrogens(mol2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); - lpcheck.Saturate(mol2); + LonePairElectronChecker.Saturate(mol2); peoe.CalculateCharges(mol1); peoe.CalculateCharges(mol2); @@ -141,7 +140,7 @@ public void TestAssignGasteigerPiPartialCharges_IAtomContainer_Boolean() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); peoe.AssignGasteigerPiPartialCharges(molecule, true); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -213,7 +212,7 @@ public void TestAssignrPiMarsilliFactors_IAtomContainerSet() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); foreach (var atom in molecule.Atoms) atom.Charge = 0; @@ -223,7 +222,7 @@ public void TestAssignrPiMarsilliFactors_IAtomContainerSet() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.IsNotNull(peoe.AssignrPiMarsilliFactors(set)); } diff --git a/NCDKTests/Charges/InductivePartialChargesTest.cs b/NCDKTests/Charges/InductivePartialChargesTest.cs index ee857efd..15003af9 100644 --- a/NCDKTests/Charges/InductivePartialChargesTest.cs +++ b/NCDKTests/Charges/InductivePartialChargesTest.cs @@ -18,8 +18,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Numerics; +using NCDK.Silent; namespace NCDK.Charges { @@ -36,7 +36,7 @@ public class InductivePartialChargesTest : CDKTestCase static InductivePartialChargesTest() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; mol = builder.NewAtomContainer(); IAtom atom1 = builder.NewAtom("C"); IAtom atom2 = builder.NewAtom("Cl"); diff --git a/NCDKTests/Charges/MMFF94PartialChargesTest.cs b/NCDKTests/Charges/MMFF94PartialChargesTest.cs index cf759c78..8e203fc0 100644 --- a/NCDKTests/Charges/MMFF94PartialChargesTest.cs +++ b/NCDKTests/Charges/MMFF94PartialChargesTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.Charges @@ -38,7 +39,7 @@ public class MMFF94PartialChargesTest : CDKTestCase public void TestMMFF94PartialCharges() { double[] testResult = { -0.99, 0.314, 0.66, -0.57, -0.65, 0.36, 0.36, 0, 0, 0.5 }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer ac = sp.ParseSmiles("NCC(=O)O"); AddExplicitHydrogens(ac); MMFF94PartialCharges mmff = new MMFF94PartialCharges(); diff --git a/NCDKTests/Charges/PiElectronegativityTest.cs b/NCDKTests/Charges/PiElectronegativityTest.cs index 6b7ef18b..c4e51641 100644 --- a/NCDKTests/Charges/PiElectronegativityTest.cs +++ b/NCDKTests/Charges/PiElectronegativityTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -29,7 +29,6 @@ namespace NCDK.Charges public class PiElectronegativityTest : CDKTestCase { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); public PiElectronegativityTest() : base() @@ -61,7 +60,7 @@ public void TestCalculatePiElectronegativity_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -85,7 +84,7 @@ public void TestCalculatePiElectronegativity_IAtomContainer_IAtom_Int_Int() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/Charges/PolarizabilityTest.cs b/NCDKTests/Charges/PolarizabilityTest.cs index ffaa4314..c63b5c9f 100644 --- a/NCDKTests/Charges/PolarizabilityTest.cs +++ b/NCDKTests/Charges/PolarizabilityTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.Charges @@ -31,12 +32,11 @@ public class PolarizabilityTest : CDKTestCase [TestMethod()] public void TestGetPolarizabilitiyFactorForAtom_IAtomContainer_IAtom() { - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCN(C)(C)"); - double result = pol.GetPolarizabilitiyFactorForAtom(mol, mol.Atoms[0]); + double result = Polarizability.GetPolarizabilitiyFactorForAtom(mol, mol.Atoms[0]); Assert.IsNotNull(result); - result = pol.GetPolarizabilitiyFactorForAtom(mol, mol.Atoms[3]); + result = Polarizability.GetPolarizabilitiyFactorForAtom(mol, mol.Atoms[3]); Assert.IsNotNull(result); } @@ -47,12 +47,11 @@ public void TestGetPolarizabilitiyFactorForAtom_IAtomContainer_IAtom() public void TestCalculateGHEffectiveAtomPolarizability_IAtomContainer_IAtom_Int_Boolean() { double[] testResult = { 4.73, 6.92 }; - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCN(C)(C)"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[0], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[0], 100, true); Assert.AreEqual(testResult[0], result, 0.01); - result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); + result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); Assert.AreEqual(testResult[1], result, 0.01); } @@ -68,10 +67,9 @@ public void TestCalculateGHEffectiveAtomPolarizability_IAtomContainer_IAtom_Bool [TestMethod()] public void TestCalculateBondPolarizability_IAtomContainer_IBond() { - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCN(C)(C)"); - double result = pol.CalculateBondPolarizability((IAtomContainer)mol, mol.Bonds[0]); + double result = Polarizability.CalculateBondPolarizability((IAtomContainer)mol, mol.Bonds[0]); Assert.IsNotNull(result); } @@ -82,10 +80,9 @@ public void TestCalculateBondPolarizability_IAtomContainer_IBond() public void TestCalculateKJMeanMolecularPolarizability() { double testResult = 2.61; - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C"); - double result = pol.CalculateKJMeanMolecularPolarizability(mol); + double result = Polarizability.CalculateKJMeanMolecularPolarizability(mol); Assert.AreEqual(testResult, result, 0.01); } @@ -96,10 +93,9 @@ public void TestCalculateKJMeanMolecularPolarizability() public void TestCalculateGHEffectiveAtomPolarizability_Ethyl_chloride() { double testResult = 4.62; /* from thesis Wolfgang Hanebeck, TUM */ - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCl"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[2], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[2], 100, true); Assert.AreEqual(testResult, result, 0.01); } @@ -110,10 +106,9 @@ public void TestCalculateGHEffectiveAtomPolarizability_Ethyl_chloride() public void TestCalculateGHEffectiveAtomPolarizability_Allyl_bromide() { double testResult = 6.17; /* from thesis Wolfgang Hanebeck, TUM */ - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCBr"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); Assert.AreEqual(testResult, result, 0.01); } @@ -124,10 +119,9 @@ public void TestCalculateGHEffectiveAtomPolarizability_Allyl_bromide() public void TestCalculateGHEffectiveAtomPolarizability_Isopentyl_iodide() { double testResult = 8.69; /* from thesis Wolfgang Hanebeck, TUM */ - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[5], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[5], 100, true); Assert.AreEqual(testResult, result, 0.01); } @@ -138,10 +132,9 @@ public void TestCalculateGHEffectiveAtomPolarizability_Isopentyl_iodide() public void TestCalculateGHEffectiveAtomPolarizability_Ethoxy_ethane() { double testResult = 5.21; /* from thesis Wolfgang Hanebeck, TUM */ - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOCC"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[2], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[2], 100, true); Assert.AreEqual(testResult, result, 0.01); } @@ -152,12 +145,11 @@ public void TestCalculateGHEffectiveAtomPolarizability_Ethoxy_ethane() public void TestCalculateGHEffectiveAtomPolarizability_Ethanolamine() { double[] testResult = { 4.26, 3.60 }; // from thesis Wolfgang Hanebeck, TUM - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCO"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); Assert.AreEqual(testResult[1], result, 0.01); - result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[0], 100, true); + result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[0], 100, true); Assert.AreEqual(testResult[0], result, 0.01); } @@ -168,10 +160,9 @@ public void TestCalculateGHEffectiveAtomPolarizability_Ethanolamine() public void TestCalculateGHEffectiveAtomPolarizability_Allyl_mercaptan() { double testResult = 6.25; /* from thesis Wolfgang Hanebeck, TUM */ - Polarizability pol = new Polarizability(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCS"); - double result = pol.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); + double result = Polarizability.CalculateGHEffectiveAtomPolarizability(mol, mol.Atoms[3], 100, true); Assert.AreEqual(testResult, result, 0.01); } } diff --git a/NCDKTests/Charges/StabilizationChargesTest.cs b/NCDKTests/Charges/StabilizationChargesTest.cs index a299f353..9b335461 100644 --- a/NCDKTests/Charges/StabilizationChargesTest.cs +++ b/NCDKTests/Charges/StabilizationChargesTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -29,25 +29,16 @@ namespace NCDK.Charges public class StabilizationChargesTest : CDKTestCase { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); public StabilizationChargesTest() : base() { } - [TestMethod()] - public void TestStabilizationCharges() - { - Assert.IsNotNull(new StabilizationCharges()); - } - // @cdk.inchi InChI=1/C4H8/c1-3-4-2/h3H,1,4H2,2H3 [TestMethod()] [TestCategory("SlowTest")] public void TestCalculatePositive_IAtomContainer_IAtom() { - StabilizationCharges sc = new StabilizationCharges(); - IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(new Atom("C")); molecule.Atoms.Add(new Atom("C")); @@ -60,14 +51,14 @@ public void TestCalculatePositive_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { if (i == 1) - Assert.AreNotSame(0.0, sc.CalculatePositive(molecule, molecule.Atoms[i])); + Assert.AreNotSame(0.0, StabilizationCharges.CalculatePositive(molecule, molecule.Atoms[i])); else - Assert.AreEqual(0.0, sc.CalculatePositive(molecule, molecule.Atoms[i]), 0.001); + Assert.AreEqual(0.0, StabilizationCharges.CalculatePositive(molecule, molecule.Atoms[i]), 0.001); } } } diff --git a/NCDKTests/ChemObjectChangeEventTest.cs b/NCDKTests/ChemObjectChangeEventTest.cs index 9723e61e..a224f5bc 100644 --- a/NCDKTests/ChemObjectChangeEventTest.cs +++ b/NCDKTests/ChemObjectChangeEventTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK { diff --git a/NCDKTests/Config/AtomTypeFactoryTest.cs b/NCDKTests/Config/AtomTypeFactoryTest.cs index d4254eaa..e2ece77b 100644 --- a/NCDKTests/Config/AtomTypeFactoryTest.cs +++ b/NCDKTests/Config/AtomTypeFactoryTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Collections.Generic; using System.IO; @@ -322,7 +322,7 @@ public virtual void TestXMLValidityStructGen() AssertValidCML("NCDK.Config.Data.structgen_atomtypes.xml", "StructGen"); } - private void AssertValidCML(string atomTypeList, string shortcut) + private static void AssertValidCML(string atomTypeList, string shortcut) { using (var ins = ResourceLoader.GetAsStream(typeof(AtomTypeFactory).Assembly, atomTypeList)) { diff --git a/NCDKTests/Config/AtomType/AtomTypeReaderTest.cs b/NCDKTests/Config/AtomTypes/AtomTypeReaderTest.cs similarity index 99% rename from NCDKTests/Config/AtomType/AtomTypeReaderTest.cs rename to NCDKTests/Config/AtomTypes/AtomTypeReaderTest.cs index f8d5d6e4..70a1f8ad 100644 --- a/NCDKTests/Config/AtomType/AtomTypeReaderTest.cs +++ b/NCDKTests/Config/AtomTypes/AtomTypeReaderTest.cs @@ -18,11 +18,11 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.IO; using System.Linq; -namespace NCDK.Config.AtomType +namespace NCDK.Config.AtomTypes { // @cdk.module test-core [TestClass()] diff --git a/NCDKTests/Config/AtomType/OWLAtomTypeMappingHandlerTest.cs b/NCDKTests/Config/AtomTypes/OWLAtomTypeMappingHandlerTest.cs similarity index 98% rename from NCDKTests/Config/AtomType/OWLAtomTypeMappingHandlerTest.cs rename to NCDKTests/Config/AtomTypes/OWLAtomTypeMappingHandlerTest.cs index 2a826e51..8b33b0e2 100644 --- a/NCDKTests/Config/AtomType/OWLAtomTypeMappingHandlerTest.cs +++ b/NCDKTests/Config/AtomTypes/OWLAtomTypeMappingHandlerTest.cs @@ -20,7 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.Config.AtomType +namespace NCDK.Config.AtomTypes { /// /// Checks the functionality of the . diff --git a/NCDKTests/Config/AtomType/OWLAtomTypeMappingReaderTest.cs b/NCDKTests/Config/AtomTypes/OWLAtomTypeMappingReaderTest.cs similarity index 96% rename from NCDKTests/Config/AtomType/OWLAtomTypeMappingReaderTest.cs rename to NCDKTests/Config/AtomTypes/OWLAtomTypeMappingReaderTest.cs index 71cb95f1..e56baa0a 100644 --- a/NCDKTests/Config/AtomType/OWLAtomTypeMappingReaderTest.cs +++ b/NCDKTests/Config/AtomTypes/OWLAtomTypeMappingReaderTest.cs @@ -20,8 +20,9 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; +using System.Linq; -namespace NCDK.Config.AtomType +namespace NCDK.Config.AtomTypes { /// /// Checks the functionality of the . @@ -53,7 +54,7 @@ public class OWLAtomTypeMappingReaderTest : CDKTestCase + " " + ""; [TestMethod()] - public void TestOWLAtomTypeMappingReader_Reader() + public void TestOWLAtomTypeMappingReaderReader() { OWLAtomTypeMappingReader reader = new OWLAtomTypeMappingReader(new StringReader("")); Assert.IsNotNull(reader); @@ -70,7 +71,7 @@ public void TestReadAtomTypeMappings() } [TestMethod()] - public void TestReadAtomTypes_CDK2Sybyl() + public void TestReadAtomTypesCDK2Sybyl() { OWLAtomTypeMappingReader reader = new OWLAtomTypeMappingReader(new StringReader(OWL_CONTENT)); Assert.IsNotNull(reader); diff --git a/NCDKTests/Config/AtomType/OWLAtomTypeReaderTest.cs b/NCDKTests/Config/AtomTypes/OWLAtomTypeReaderTest.cs similarity index 98% rename from NCDKTests/Config/AtomType/OWLAtomTypeReaderTest.cs rename to NCDKTests/Config/AtomTypes/OWLAtomTypeReaderTest.cs index d3d83153..97198579 100644 --- a/NCDKTests/Config/AtomType/OWLAtomTypeReaderTest.cs +++ b/NCDKTests/Config/AtomTypes/OWLAtomTypeReaderTest.cs @@ -19,10 +19,10 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.IO; -namespace NCDK.Config.AtomType +namespace NCDK.Config.AtomTypes { // @cdk.module test-core [TestClass()] diff --git a/NCDKTests/Config/CDKBasedAtomTypeConfiguratorTest.cs b/NCDKTests/Config/CDKBasedAtomTypeConfiguratorTest.cs index d674744c..2bfed679 100644 --- a/NCDKTests/Config/CDKBasedAtomTypeConfiguratorTest.cs +++ b/NCDKTests/Config/CDKBasedAtomTypeConfiguratorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Linq; namespace NCDK.Config @@ -43,7 +43,7 @@ public virtual void TestReadAtomTypes_IChemObjectBuilder() var configFile = "NCDK.Config.Data.structgen_atomtypes.xml"; var ins = ResourceLoader.GetAsStream(typeof(CDKBasedAtomTypeConfigurator), configFile); var configurator = new CDKBasedAtomTypeConfigurator(); - configurator.Stream = ins; + configurator.SetStream(ins); var atomTypes = configurator.ReadAtomTypes(new ChemObject().Builder); Assert.AreNotSame(0, atomTypes.Count()); } diff --git a/NCDKTests/Config/Isotope/IsotopeHandlerTest.cs b/NCDKTests/Config/Isotope/IsotopeHandlerTest.cs index a48e8d5f..3dbe7f1e 100644 --- a/NCDKTests/Config/Isotope/IsotopeHandlerTest.cs +++ b/NCDKTests/Config/Isotope/IsotopeHandlerTest.cs @@ -18,7 +18,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Config.Isotopes; +using NCDK.Silent; namespace NCDK.Config.Isotope { diff --git a/NCDKTests/Config/Isotope/IsotopeReaderTest.cs b/NCDKTests/Config/Isotope/IsotopeReaderTest.cs index 69b9c278..a9593d8a 100644 --- a/NCDKTests/Config/Isotope/IsotopeReaderTest.cs +++ b/NCDKTests/Config/Isotope/IsotopeReaderTest.cs @@ -18,20 +18,21 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Config.Isotopes; +using NCDK.Silent; using System.IO; using System.Text; namespace NCDK.Config.Isotope { - // @cdk.module test-extra + // @cdk.module test-extra [TestClass()] public class IsotopeReaderTest : CDKTestCase { [TestMethod()] public void TestIsotopeReader_InputStream_IChemObjectBuilder() { - IsotopeReader reader = new IsotopeReader(new MemoryStream(new byte[0]), new ChemObject().Builder); + IsotopeReader reader = new IsotopeReader(new MemoryStream(System.Array.Empty()), new ChemObject().Builder); Assert.IsNotNull(reader); } diff --git a/NCDKTests/Config/IsotopesTest.cs b/NCDKTests/Config/IsotopesTest.cs index 4b574638..e5ec188f 100644 --- a/NCDKTests/Config/IsotopesTest.cs +++ b/NCDKTests/Config/IsotopesTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Linq; @@ -33,32 +33,32 @@ namespace NCDK.Config public class IsotopesTest : CDKTestCase { [TestMethod()] - public void TestGetInstance_IChemObjectBuilder() + public void TestGetInstanceIChemObjectBuilder() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Assert.IsNotNull(isofac); } [TestMethod()] public void TestGetSize() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Assert.IsTrue(isofac.Count > 0); } [TestMethod()] - public void TestConfigure_IAtom() + public void TestConfigureIAtom() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Atom atom = new Atom("H"); isofac.Configure(atom); Assert.AreEqual(1, atom.AtomicNumber.Value); } [TestMethod()] - public void TestConfigure_IAtom_IIsotope() + public void TestConfigureIAtomIIsotope() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Atom atom = new Atom("H"); IIsotope isotope = new Default.Isotope("H", 2); isofac.Configure(atom, isotope); @@ -66,49 +66,49 @@ public void TestConfigure_IAtom_IIsotope() } [TestMethod()] - public void TestGetMajorIsotope_String() + public void TestGetMajorIsotopeString() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IIsotope isotope = isofac.GetMajorIsotope("Te"); Assert.AreEqual(129.9062244, isotope.ExactMass.Value, 0.0001); } [TestMethod()] - public void TestGetMajorIsotope_int() + public void TestGetMajorIsotopeInt() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IIsotope isotope = isofac.GetMajorIsotope(17); Assert.AreEqual("Cl", isotope.Symbol); } [TestMethod()] - public void TestGetElement_String() + public void TestGetElementString() { - IsotopeFactory elfac = Isotopes.Instance; + IsotopeFactory elfac = BODRIsotopeFactory.Instance; IElement element = elfac.GetElement("Br"); Assert.AreEqual(35, element.AtomicNumber.Value); } [TestMethod()] - public void TestGetElement_int() + public void TestGetElementInt() { - IsotopeFactory elfac = Isotopes.Instance; + IsotopeFactory elfac = BODRIsotopeFactory.Instance; IElement element = elfac.GetElement(6); Assert.AreEqual("C", element.Symbol); } [TestMethod()] - public void TestGetElementSymbol_int() + public void TestGetElementSymbolInt() { - IsotopeFactory elfac = Isotopes.Instance; + IsotopeFactory elfac = BODRIsotopeFactory.Instance; string symbol = elfac.GetElementSymbol(8); Assert.AreEqual("O", symbol); } [TestMethod()] - public void TestGetIsotopes_String() + public void TestGetIsotopesString() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; var list = isofac.GetIsotopes("He"); Assert.AreEqual(8, list.Count()); } @@ -116,15 +116,15 @@ public void TestGetIsotopes_String() [TestMethod()] public void TestGetIsotopes() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; var list = isofac.GetIsotopes(); Assert.IsTrue(list.Count() > 200); } [TestMethod()] - public void TestGetIsotopes_Double_double() + public void TestGetIsotopesDoubleDouble() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; var list = isofac.GetIsotopes(87.90, 0.01).ToList(); // should return: // Isotope match: 88Sr has mass 87.9056121 @@ -135,14 +135,14 @@ public void TestGetIsotopes_Double_double() } [TestMethod()] - public void TestIsElement_String() + public void TestIsElementString() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Assert.IsTrue(isofac.IsElement("C")); } [TestMethod()] - public void TestConfigureAtoms_IAtomContainer() + public void TestConfigureAtomsIAtomContainer() { AtomContainer container = new AtomContainer(); container.Atoms.Add(new Atom("C")); @@ -151,7 +151,7 @@ public void TestConfigureAtoms_IAtomContainer() container.Atoms.Add(new Atom("O")); container.Atoms.Add(new Atom("F")); container.Atoms.Add(new Atom("Cl")); - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; isofac.ConfigureAtoms(container); for (int i = 0; i < container.Atoms.Count; i++) { @@ -160,16 +160,16 @@ public void TestConfigureAtoms_IAtomContainer() } [TestMethod()] - public void TestGetNaturalMass_IElement() + public void TestGetNaturalMassIElement() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Assert.AreEqual(1.0079760, isofac.GetNaturalMass(new Default.Element("H")), 0.1); } [TestMethod()] public void TestGetIsotope() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Assert.AreEqual(13.00335484, isofac.GetIsotope("C", 13).ExactMass.Value, 0.0000001); } @@ -179,21 +179,21 @@ public void TestGetIsotope() [TestMethod()] public void TestMajorUnstableIsotope() { - Isotopes isotopes = Isotopes.Instance; + var isotopes = BODRIsotopeFactory.Instance; Assert.IsNull(isotopes.GetMajorIsotope("Es")); } [TestMethod()] - public void TestGetIsotope_NonElement() + public void TestGetIsotopeNonElement() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; Assert.IsNull(isofac.GetIsotope("R", 13)); } [TestMethod()] public void TestGetIsotopeFromExactMass() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IIsotope carbon13 = isofac.GetIsotope("C", 13); IIsotope match = isofac.GetIsotope(carbon13.Symbol, carbon13.ExactMass.Value, 0.0001); Assert.IsNotNull(match); @@ -201,9 +201,9 @@ public void TestGetIsotopeFromExactMass() } [TestMethod()] - public void TestGetIsotopeFromExactMass_NonElement() + public void TestGetIsotopeFromExactMassNonElement() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IIsotope match = isofac.GetIsotope("R", 13.00001, 0.0001); Assert.IsNull(match); } @@ -211,15 +211,15 @@ public void TestGetIsotopeFromExactMass_NonElement() [TestMethod()] public void TestYeahSure() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IIsotope match = isofac.GetIsotope("H", 13.00001, 0.0001); Assert.IsNull(match); } [TestMethod()] - public void TestGetIsotopeFromExactMass_LargeTolerance() + public void TestGetIsotopeFromExactMassLargeTolerance() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IIsotope carbon13 = isofac.GetIsotope("C", 13); IIsotope match = isofac.GetIsotope(carbon13.Symbol, carbon13.ExactMass.Value, 2.0); Assert.IsNotNull(match); @@ -230,7 +230,7 @@ public void TestGetIsotopeFromExactMass_LargeTolerance() public void ConfigureDoesNotSetMajorIsotope() { IAtom atom = new Atom("CH4"); - Isotopes isotopes = Isotopes.Instance; + var isotopes = BODRIsotopeFactory.Instance; IIsotope major = isotopes.GetMajorIsotope(atom.Symbol); Assert.IsNotNull(major); Assert.AreEqual(12, major.MassNumber); @@ -243,32 +243,32 @@ public void ConfigureDoesNotSetMajorIsotope() [ExpectedException(typeof(ArgumentException))] public void TestNonexistingElement() { - Isotopes isofac = Isotopes.Instance; + var isofac = BODRIsotopeFactory.Instance; IAtom xxAtom = new Atom("Xx"); isofac.Configure(xxAtom); } [TestMethod()] - public void TestGetIsotopes_Nonelement() + public void TestGetIsotopesNonelement() { - IsotopeFactory isofac = Isotopes.Instance; + IsotopeFactory isofac = BODRIsotopeFactory.Instance; var list = isofac.GetIsotopes("E"); Assert.IsNotNull(list); Assert.AreEqual(0, list.Count()); } [TestMethod()] - public void TestGetElement_Nonelement() + public void TestGetElementNonelement() { - IsotopeFactory isofac = Isotopes.Instance; + IsotopeFactory isofac = BODRIsotopeFactory.Instance; IElement element = isofac.GetElement("E"); Assert.IsNull(element); } [TestMethod()] - public void TestGetMajorIsotope_Nonelement() + public void TestGetMajorIsotopeNonelement() { - IsotopeFactory isofac = Isotopes.Instance; + IsotopeFactory isofac = BODRIsotopeFactory.Instance; IIsotope isotope = isofac.GetMajorIsotope("E"); Assert.IsNull(isotope); } diff --git a/NCDKTests/Config/OWLBasedAtomTypeConfiguratorTest.cs b/NCDKTests/Config/OWLBasedAtomTypeConfiguratorTest.cs index bfbc68b1..123a544d 100644 --- a/NCDKTests/Config/OWLBasedAtomTypeConfiguratorTest.cs +++ b/NCDKTests/Config/OWLBasedAtomTypeConfiguratorTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Linq; namespace NCDK.Config @@ -44,7 +44,7 @@ public virtual void TestReadAtomTypes_IChemObjectBuilder() var configFile = "NCDK.Dict.Data.cdk-atom-types.owl"; var ins = ResourceLoader.GetAsStream(configFile); var configurator = new OWLBasedAtomTypeConfigurator(); - configurator.Stream = ins; + configurator.SetStream(ins); var atomTypes = configurator.ReadAtomTypes(new ChemObject().Builder); Assert.AreNotSame(0, atomTypes.Count()); } diff --git a/NCDKTests/Config/TXTBasedAtomTypeConfiguratorTest.cs b/NCDKTests/Config/TXTBasedAtomTypeConfiguratorTest.cs index 78a768d6..edf984d9 100644 --- a/NCDKTests/Config/TXTBasedAtomTypeConfiguratorTest.cs +++ b/NCDKTests/Config/TXTBasedAtomTypeConfiguratorTest.cs @@ -18,8 +18,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.Linq; -using NCDK.Default; namespace NCDK.Config { @@ -43,7 +43,7 @@ public virtual void TestReadAtomTypes_IChemObjectBuilder() var configFile = "NCDK.Config.Data.jmol_atomtypes.txt"; var ins = ResourceLoader.GetAsStream(typeof(TXTBasedAtomTypeConfigurator), configFile); var configurator = new TXTBasedAtomTypeConfigurator(); - configurator.Stream = ins; + configurator.SetStream(ins); var atomTypes = configurator.ReadAtomTypes(new ChemObject().Builder); Assert.AreNotSame(0, atomTypes.Count()); } diff --git a/NCDKTests/Config/XMLIsotopeFactoryTest.cs b/NCDKTests/Config/XMLIsotopeFactoryTest.cs index 2f4ae6bf..4fb97485 100644 --- a/NCDKTests/Config/XMLIsotopeFactoryTest.cs +++ b/NCDKTests/Config/XMLIsotopeFactoryTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Collections.Generic; using System.IO; @@ -37,7 +37,7 @@ namespace NCDK.Config public class XMLIsotopeFactoryTest : CDKTestCase { - bool standAlone = false; + readonly bool standAlone = false; readonly static AtomTypeFactory atf = AtomTypeFactory.GetInstance(new ChemObject().Builder); private const string JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; private const string W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; @@ -70,7 +70,7 @@ public static void Cleanup() } [TestMethod()] - public void TestGetInstance_IChemObjectBuilder() + public void TestGetInstanceIChemObjectBuilder() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); Assert.IsNotNull(isofac); @@ -84,7 +84,7 @@ public void TestGetSize() } [TestMethod()] - public void TestConfigure_IAtom() + public void TestConfigureIAtom() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); Atom atom = new Atom("H"); @@ -93,7 +93,7 @@ public void TestConfigure_IAtom() } [TestMethod()] - public void TestConfigure_IAtom_IIsotope() + public void TestConfigureIAtomIIsotope() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); Atom atom = new Atom("H"); @@ -103,7 +103,7 @@ public void TestConfigure_IAtom_IIsotope() } [TestMethod()] - public void TestGetMajorIsotope_String() + public void TestGetMajorIsotopeString() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope isotope = isofac.GetMajorIsotope("Te"); @@ -112,7 +112,7 @@ public void TestGetMajorIsotope_String() } [TestMethod()] - public void TestGetMajorIsotope_Nonelement() + public void TestGetMajorIsotopeNonelement() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope isotope = isofac.GetMajorIsotope("E"); @@ -120,7 +120,7 @@ public void TestGetMajorIsotope_Nonelement() } [TestMethod()] - public void TestGetMajorIsotope_int() + public void TestGetMajorIsotopeInt() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope isotope = isofac.GetMajorIsotope(17); @@ -128,7 +128,7 @@ public void TestGetMajorIsotope_int() } [TestMethod()] - public void TestGetElement_String() + public void TestGetElementString() { XMLIsotopeFactory elfac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IElement element = elfac.GetElement("Br"); @@ -136,7 +136,7 @@ public void TestGetElement_String() } [TestMethod()] - public void TestGetElement_Nonelement() + public void TestGetElementNonelement() { XMLIsotopeFactory elfac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IElement element = elfac.GetElement("E"); @@ -144,7 +144,7 @@ public void TestGetElement_Nonelement() } [TestMethod()] - public void TestGetElement_int() + public void TestGetElemenInt() { XMLIsotopeFactory elfac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IElement element = elfac.GetElement(6); @@ -152,7 +152,7 @@ public void TestGetElement_int() } [TestMethod()] - public void TestGetElementSymbol_int() + public void TestGetElementSymbolInt() { XMLIsotopeFactory elfac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); String symbol = elfac.GetElementSymbol(8); @@ -160,7 +160,7 @@ public void TestGetElementSymbol_int() } [TestMethod()] - public void TestGetIsotopes_String() + public void TestGetIsotopesString() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope[] list = isofac.GetIsotopes("He").ToArray(); @@ -168,7 +168,7 @@ public void TestGetIsotopes_String() } [TestMethod()] - public void TestGetIsotopes_Nonelement() + public void TestGetIsotopesNonelement() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope[] list = isofac.GetIsotopes("E").ToArray(); @@ -185,7 +185,7 @@ public void TestGetIsotopes() } [TestMethod()] - public void TestGetIsotopes_double_double() + public void TestGetIsotopesDoubleDouble() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope[] list = isofac.GetIsotopes(87.90, 0.01).ToArray(); @@ -198,14 +198,14 @@ public void TestGetIsotopes_double_double() } [TestMethod()] - public void TestIsElement_String() + public void TestIsElementString() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); Assert.IsTrue(isofac.IsElement("C")); } [TestMethod()] - public void TestConfigureAtoms_IAtomContainer() + public void TestConfigureAtomsIAtomContainer() { AtomContainer container = new AtomContainer(); container.Atoms.Add(new Atom("C")); @@ -229,7 +229,7 @@ public void TestXMLValidityHybrid() AssertValidCML("NCDK.Config.Data.isotopes.xml", "Isotopes"); } - private void AssertValidCML(string atomTypeList, string shortcut) + private static void AssertValidCML(string atomTypeList, string shortcut) { using (var ins = ResourceLoader.GetAsStream(atomTypeList)) { @@ -257,7 +257,7 @@ public void TestCanReadCMLSchema() } [TestMethod()] - public void TestGetNaturalMass_IElement() + public void TestGetNaturalMassIElement() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); Assert.AreEqual(1.0079760, isofac.GetNaturalMass(new Default.Element("H")), 0.1); @@ -289,7 +289,7 @@ public void TestYeahSure() } [TestMethod()] - public void TestGetIsotopeFromExactMass_LargeTolerance() + public void TestGetIsotopeFromExactMassLargeTolerance() { XMLIsotopeFactory isofac = XMLIsotopeFactory.GetInstance(new ChemObject().Builder); IIsotope carbon13 = isofac.GetIsotope("C", 13); diff --git a/NCDKTests/Dict/AbstractEntryTest.cs b/NCDKTests/Dict/AbstractEntryTest.cs index 86a068ee..a1f5dce7 100644 --- a/NCDKTests/Dict/AbstractEntryTest.cs +++ b/NCDKTests/Dict/AbstractEntryTest.cs @@ -86,7 +86,7 @@ public virtual void TestDescriptorMetadata() { Entry entry = GetTestClass(); Assert.IsNotNull(entry.DescriptorMetadata); - IList metadata = entry.DescriptorMetadata; + var metadata = entry.DescriptorMetadata; Assert.AreEqual(0, metadata.Count); entry.AddDescriptorMetadata("This entry was written by me."); metadata = entry.DescriptorMetadata; diff --git a/NCDKTests/FaulonSignatures/Simple/CanonicalLabellingTest.cs b/NCDKTests/FaulonSignatures/Simple/CanonicalLabellingTest.cs index 71f00d48..5f6dcee3 100644 --- a/NCDKTests/FaulonSignatures/Simple/CanonicalLabellingTest.cs +++ b/NCDKTests/FaulonSignatures/Simple/CanonicalLabellingTest.cs @@ -88,14 +88,14 @@ public void ThreeThreeFusedCycle() PermuteTest(new SimpleGraph("0:1,0:2,0:3,1:4,2:4,3:4")); } - [TestCategory("SlowTest")] + [TestCategory("VerySlowTest"), Ignore()] [TestMethod()] public void LargePermuteTestA() { PermuteTest(new SimpleGraph("5:7,6:7,0:6,1:6,2:5,3:5,0:4,1:4,2:4,3:4,0:3,2:3,0:1,1:2")); } - [TestCategory("SlowTest")] + [TestCategory("VerySlowTest"), Ignore()] [TestMethod()] public void LargePermuteTestB() { diff --git a/NCDKTests/Fingerprints/AbstractFixedLengthFingerprinterTest.cs b/NCDKTests/Fingerprints/AbstractFixedLengthFingerprinterTest.cs index d3491523..8f0ff68b 100644 --- a/NCDKTests/Fingerprints/AbstractFixedLengthFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/AbstractFixedLengthFingerprinterTest.cs @@ -25,6 +25,7 @@ using NCDK.Aromaticities; using NCDK.Common.Collections; using NCDK.IO; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System.Collections; @@ -62,7 +63,7 @@ public virtual void TestBug706786() BitArray superBS = fingerprinter.GetBitFingerprint(superStructure).AsBitSet(); BitArray subBS = fingerprinter.GetBitFingerprint(subStructure).AsBitSet(); - Assert.IsTrue(BitArrays.AreEqual(subBS, And(superBS, subBS))); + Assert.IsTrue(BitArrays.Equals(subBS, And(superBS, subBS))); } // @cdk.bug 853254 @@ -116,7 +117,7 @@ public virtual void TestBug934819() BitArray superBS = fingerprinter.GetBitFingerprint(superStructure).AsBitSet(); BitArray subBS = fingerprinter.GetBitFingerprint(subStructure).AsBitSet(); - Assert.IsTrue(BitArrays.AreEqual(subBS, And(superBS, subBS))); + Assert.IsTrue(BitArrays.Equals(subBS, And(superBS, subBS))); } /// @@ -205,7 +206,7 @@ public void TestBug931608() // @cdk.inchi InChI=1/C13H16O4/c1-7(14)8-4-5-10-9(6-8)11(15)12(16)13(2,3)17-10/h4-6,11-12,15-16H,1-3H3/t11-,12+/s2 public static IAtomContainer Bug706786_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); mol.Atoms.Add(a1); @@ -307,7 +308,7 @@ public static IAtomContainer Bug706786_1() // @cdk.inchi InChI=1/C9H10O/c1-2-6-9-8(4-1)5-3-7-10-9/h1-2,4,6H,3,5,7H2 public static IAtomContainer Bug706786_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); mol.Atoms.Add(a1); @@ -373,7 +374,7 @@ public static IAtomContainer Bug706786_2() // @cdk.inchi InChI=1/C4H3NO2S/c6-5(7)4-2-1-3-8-4/h1-3H public static IAtomContainer Bug934819_1() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("O"); a1.FormalCharge = -1; @@ -429,7 +430,7 @@ public static IAtomContainer Bug934819_1() // @cdk.inchi InChI=1/C14H13NO2S3/c1-2-3-10-18-14-9-7-12(20-14)5-4-11-6-8-13(19-11)15(16)17/h6-9H,2-3,10H2,1H3 public static IAtomContainer Bug934819_2() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); mol.Atoms.Add(a1); diff --git a/NCDKTests/Fingerprints/CircularFingerprintSmartsTest.cs b/NCDKTests/Fingerprints/CircularFingerprintSmartsTest.cs index 5ae95efd..f8e8a4de 100644 --- a/NCDKTests/Fingerprints/CircularFingerprintSmartsTest.cs +++ b/NCDKTests/Fingerprints/CircularFingerprintSmartsTest.cs @@ -25,7 +25,6 @@ using NCDK.SMARTS; using NCDK.Smiles; using System.Collections.Generic; -using static NCDK.Fingerprints.CircularFingerprinter; namespace NCDK.Fingerprints { @@ -33,13 +32,13 @@ namespace NCDK.Fingerprints [TestClass()] public class CircularFingerprintSmartsTest : CDKTestCase { - public static SmilesParser parser = new SmilesParser(Silent.ChemObjectBuilder.Instance); + private static SmilesParser parser = new SmilesParser(Silent.ChemObjectBuilder.Instance); [TestMethod()] public void TestMol1() { - string molSmiles = "CC"; - string[][] expectedFPSmarts = new[] { new[] { "C*" }, new[] { "CC" } }; + var molSmiles = "CC"; + var expectedFPSmarts = new[] { new[] { "C*" }, new[] { "CC" } }; CheckFPSmartsForMolecule(molSmiles, expectedFPSmarts); } @@ -47,8 +46,8 @@ public void TestMol1() [TestMethod()] public void TestMol2() { - string molSmiles = "CCC"; - string[][] expectedFPSmarts = new[] { new[] { "C*" }, new[] { "C(*)*" }, + var molSmiles = "CCC"; + var expectedFPSmarts = new[] { new[] { "C*" }, new[] { "C(*)*" }, new[] { "CC*", "C(*)C" }, new[] { "CCC" }, }; CheckFPSmartsForMolecule(molSmiles, expectedFPSmarts); @@ -57,8 +56,8 @@ public void TestMol2() [TestMethod()] public void TestMol3() { - string molSmiles = "CCN"; - string[][] expectedFPSmarts = new[] { new[] { "C*" }, new[] { "C(*)*" }, new[] { "N*" }, + var molSmiles = "CCN"; + var expectedFPSmarts = new[] { new[] { "C*" }, new[] { "C(*)*" }, new[] { "N*" }, new[] { "CC*", "C(*)C" }, new[] { "C(*)N", "NC*" }, new[] { "CCN", "NCC", "C(C)N", "C(N)C" }, }; @@ -68,8 +67,8 @@ public void TestMol3() [TestMethod()] public void TestMol4() { - string molSmiles = "C1CC1"; - string[][] expectedFPSmarts = new[] + var molSmiles = "C1CC1"; + var expectedFPSmarts = new[] { new[] { "C(*)*" }, new[] { "C1CC1", "C(C1)C1" } }; CheckFPSmartsForMolecule(molSmiles, expectedFPSmarts); @@ -78,8 +77,8 @@ public void TestMol4() [TestMethod()] public void TestMol5() { - string molSmiles = "C1CCC1"; - string[][] expectedFPSmarts = new[] { + var molSmiles = "C1CCC1"; + var expectedFPSmarts = new[] { new[] { "C(*)*" }, new[] { "C(C*)C*", "C(CC*)*", "C(*)CC*" }, new[] { "C1CCC1", "C(CC1)C1", "C(C1)CC1" } }; @@ -89,8 +88,8 @@ public void TestMol5() [TestMethod()] public void TestMol6() { - string molSmiles = "CC[C-]"; - string[][] expectedFPSmarts = new[] { + var molSmiles = "CC[C-]"; + var expectedFPSmarts = new[] { new[] { "C*" }, new[] { "C(*)*" }, new[] { "[C-]*" }, new[] { "CC*", "C(*)C" }, new[] { "[C-]C*", "C(*)[C-]" }, new[] { "CC[C-]", "C(C)[C-]", "[C-]CC", "C([C-])C" } }; @@ -101,8 +100,8 @@ public void TestMol6() [TestMethod()] public void TestMol7() { - string molSmiles = "c1ccccc1"; - string[][] expectedFPSmarts = new[] { + var molSmiles = "c1ccccc1"; + var expectedFPSmarts = new[] { new[] { "c(a)a" }, new[] { "c(a)cca", "c(ca)ca", "c(cca)a" }, new[] { "c(a)cccca", "c(ca)ccca", "c(cca)cca", "c(ccca)ca", "c(cccca)a" }, @@ -111,28 +110,28 @@ public void TestMol7() CheckFPSmartsForMolecule(molSmiles, expectedFPSmarts); } - private void CheckFPSmartsForMolecule(string moleculeSmiles, string[][] expectedFPSmarts) + private static void CheckFPSmartsForMolecule(string moleculeSmiles, string[][] expectedFPSmarts) { var expected = new HashSet(); - foreach (string[] strs in expectedFPSmarts) + foreach (var strs in expectedFPSmarts) foreach (var str in strs) expected.Add(str); // expectedFPSmarts[][] is a double array because for each smarts // several equivalent variants // of the smarts are given e.g. CCC C(C)C - IAtomContainer mol = parser.ParseSmiles(moleculeSmiles); + var mol = parser.ParseSmiles(moleculeSmiles); CircularFingerprinter circ = new CircularFingerprinter(); circ.Calculate(mol); - SmartsFragmentExtractor subsmarts = new SmartsFragmentExtractor(mol); - subsmarts.SetMode(SmartsFragmentExtractor.MODE_JCOMPOUNDMAPPER); - int numFP = circ.FPCount; + var subsmarts = new SmartsFragmentExtractor(mol); + subsmarts.SetMode(SubstructureSelectionMode.JCompoundMapper); + var numFP = circ.FPCount; var actual = new HashSet(); for (int i = 0; i < numFP; i++) { - FP fp = circ.GetFP(i); + var fp = circ.GetFP(i); actual.Add(subsmarts.Generate(fp.Atoms)); } diff --git a/NCDKTests/Fingerprints/CircularFingerprinterTest.cs b/NCDKTests/Fingerprints/CircularFingerprinterTest.cs index 20867427..61e12dee 100644 --- a/NCDKTests/Fingerprints/CircularFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/CircularFingerprinterTest.cs @@ -29,14 +29,15 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; using NCDK.Common.Collections; -using NCDK.Default; using NCDK.IO; using NCDK.Numerics; +using NCDK.Silent; using NCDK.Smiles; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.IO.Compression; @@ -46,19 +47,7 @@ namespace NCDK.Fingerprints [TestClass()] public class CircularFingerprinterTest : CDKTestCase { - private static readonly IAtomContainer trivialMol = null; - - static CircularFingerprinterTest() - { - SmilesParser parser = new SmilesParser(Silent.ChemObjectBuilder.Instance); - try - { - trivialMol = parser.ParseSmiles("CCC(=O)N"); - } - catch (InvalidSmilesException) - { - } - } + private static readonly IAtomContainer trivialMol = new SmilesParser(Silent.ChemObjectBuilder.Instance).ParseSmiles("CCC(=O)N"); [TestMethod()] [TestCategory("SlowTest")] @@ -66,7 +55,7 @@ public void TestFingerprints() { Trace.TraceInformation("CircularFingerprinter test: loading source materials"); - string fnzip = "NCDK.Data.CDD.circular_validation.zip"; + var fnzip = "NCDK.Data.CDD.circular_validation.zip"; Trace.TraceInformation("Loading source content: " + fnzip); using (Stream ins = ResourceLoader.GetAsStream(fnzip)) { @@ -103,9 +92,8 @@ public void TestUseStereoElements() IAtomContainer mol2 = smipar.ParseSmiles(smiles2); IAtomContainer mol3 = mdlr.Read(bldr.NewAtomContainer()); - CircularFingerprinter fpr = new CircularFingerprinter + var fpr = new CircularFingerprinter { - // when stereo-chemistry is perceived we don't have coordinates from the // SMILES and so get a different fingerprint PerceiveStereo = true @@ -122,22 +110,23 @@ public void TestUseStereoElements() public void TestGetBitFingerprint() { Assert.IsTrue(trivialMol != null); - CircularFingerprinter circ = new CircularFingerprinter(); - IBitFingerprint result = circ.GetBitFingerprint(trivialMol); + var circ = new CircularFingerprinter(); + var result = circ.GetBitFingerprint(trivialMol); BitArray wantBits = new BitArray(0), gotBits = result.AsBitSet(); int[] REQUIRE_BITS = { 19, 152, 293, 340, 439, 480, 507, 726, 762, 947, 993 }; foreach (var b in REQUIRE_BITS) BitArrays.SetValue(wantBits, b, true); - if (!BitArrays.AreEqual(wantBits, gotBits)) throw new CDKException("Got " + gotBits + ", wanted " + wantBits); + if (!BitArrays.Equals(wantBits, gotBits)) + throw new CDKException("Got " + gotBits + ", wanted " + wantBits); } [TestMethod()] public void TestGetCountFingerprint() { Assert.IsTrue(trivialMol != null); - CircularFingerprinter circ = new CircularFingerprinter(); - ICountFingerprint result = circ.GetCountFingerprint(trivialMol); + var circ = new CircularFingerprinter(); + var result = circ.GetCountFingerprint(trivialMol); int[] ANSWER_KEY = {-414937772, 1, -1027418143, 1, 1627608083, 1, -868007456, 1, -1006701866, 1, -1059145289, 1, -801752141, 1, 790592664, 1, -289109509, 1, -1650154758, 1, 1286833445, 1}; @@ -155,8 +144,7 @@ public void TestGetCountFingerprint() { found = true; if (gotCount != wantCount) - throw new CDKException("For hash " + gotHash + " got count " + gotCount + " but wanted " - + wantCount); + throw new CDKException("For hash " + gotHash + " got count " + gotCount + " but wanted " + wantCount); } } if (!found) @@ -165,7 +153,8 @@ public void TestGetCountFingerprint() break; } } - if (fail) throw new CDKException("Hash values do not match."); + if (fail) + throw new CDKException("Hash values do not match."); } [TestMethod()] @@ -174,16 +163,16 @@ public void TestGetRawFingerprint() // currently no-op } - private void Validate(Stream ins) + private static void Validate(Stream ins) { // stream the contents form the zipfile: these are all short - Dictionary content = new Dictionary(); + var content = new Dictionary(); using (var zip = new ZipArchive(ins)) { foreach (var ze in zip.Entries) { string fn = ze.Name; - MemoryStream buff = new MemoryStream(); + var buff = new MemoryStream(); using (var zs = ze.Open()) { int b; @@ -196,7 +185,7 @@ private void Validate(Stream ins) for (int idx = 1; ; idx++) { - string basefn = idx.ToString(); + string basefn = idx.ToString(NumberFormatInfo.InvariantInfo); while (basefn.Length < 6) basefn = "0" + basefn; if (!content.TryGetValue(basefn + ".mol", out byte[] molBytes)) @@ -208,58 +197,57 @@ private void Validate(Stream ins) mdl.Read(mol); } - CircularFingerprinter.FP[] validateECFP = ParseValidation(content[basefn + ".ecfp"]); - CircularFingerprinter.FP[] validateFCFP = ParseValidation(content[basefn + ".fcfp"]); + CircularFingerprint[] validateECFP = ParseValidation(content[basefn + ".ecfp"]); + CircularFingerprint[] validateFCFP = ParseValidation(content[basefn + ".fcfp"]); - Trace.TraceInformation("FN=" + basefn + " MOL=" + mol.Atoms.Count + "," + mol.Bonds.Count + " Requires ECFP=" - + validateECFP.Length + " FCFP=" + validateFCFP.Length); + Trace.TraceInformation("FN=" + basefn + " MOL=" + mol.Atoms.Count + "," + mol.Bonds.Count + " Requires ECFP=" + validateECFP.Length + " FCFP=" + validateFCFP.Length); - ValidateFingerprints("ECFP6", mol, CircularFingerprinter.CFPClass.ECFP6, validateECFP); - ValidateFingerprints("FCFP6", mol, CircularFingerprinter.CFPClass.FCFP6, validateFCFP); + ValidateFingerprints("ECFP6", mol, CircularFingerprinterClass.ECFP6, validateECFP); + ValidateFingerprints("FCFP6", mol, CircularFingerprinterClass.FCFP6, validateFCFP); } } - private CircularFingerprinter.FP[] ParseValidation(byte[] raw) + private static CircularFingerprint[] ParseValidation(byte[] raw) { - Stream ins = new MemoryStream(raw); - TextReader rdr = new StreamReader(ins); - List list = new List(); - - while (true) + using (var rdr = new StreamReader(new MemoryStream(raw))) { - string line = rdr.ReadLine(); - if (line == null || line.Length == 0) break; - string[] bits = line.Split(' '); - int hashCode = int.Parse(bits[0]); - int iteration = int.Parse(bits[1]); - int[] atoms = new int[bits.Length - 2]; - for (int n = 0; n < atoms.Length; n++) - atoms[n] = int.Parse(bits[n + 2]) - 1; // note: atom#'s are 1-based in reference file - list.Add(new CircularFingerprinter.FP(hashCode, iteration, atoms)); - } + var list = new List(); + + while (true) + { + var line = rdr.ReadLine(); + if (line == null || line.Length == 0) + break; + var bits = line.Split(' '); + var hashCode = int.Parse(bits[0], NumberFormatInfo.InvariantInfo); + var iteration = int.Parse(bits[1], NumberFormatInfo.InvariantInfo); + var atoms = new int[bits.Length - 2]; + for (int n = 0; n < atoms.Length; n++) + atoms[n] = int.Parse(bits[n + 2], NumberFormatInfo.InvariantInfo) - 1; // note: atom#'s are 1-based in reference file + list.Add(new CircularFingerprint(hashCode, iteration, atoms)); + } - rdr.Close(); - return list.ToArray(); + return list.ToArray(); + } } - private void ValidateFingerprints(string label, AtomContainer mol, CircularFingerprinter.CFPClass classType, - CircularFingerprinter.FP[] validate) + private static void ValidateFingerprints(string label, AtomContainer mol, CircularFingerprinterClass classType, CircularFingerprint[] validate) { CircularFingerprinter circ = new CircularFingerprinter(classType); try { circ.Calculate(mol); } - catch (Exception ex) + catch (Exception) { System.Console.Out.WriteLine("Fingerprint calculation failed for molecule:"); MDLV2000Writer molwr = new MDLV2000Writer(System.Console.Out); molwr.Write(mol); molwr.Close(); - throw ex; + throw; } - CircularFingerprinter.FP[] obtained = new CircularFingerprinter.FP[circ.FPCount]; + var obtained = new CircularFingerprint[circ.FPCount]; for (int n = 0; n < circ.FPCount; n++) obtained[n] = circ.GetFP(n); @@ -273,7 +261,8 @@ private void ValidateFingerprints(string label, AtomContainer mol, CircularFinge hit = true; break; } - if (!hit) same = false; + if (!hit) + same = false; } for (int i = 0; i < validate.Length && same; i++) { @@ -284,13 +273,15 @@ private void ValidateFingerprints(string label, AtomContainer mol, CircularFinge hit = true; break; } - if (!hit) same = false; + if (!hit) + same = false; } - if (same) return; + if (same) + return; { System.Console.Out.WriteLine("Fingerprint mismatch, validation failed.\nMolecular structure"); - MDLV2000Writer molwr = new MDLV2000Writer(System.Console.Out); + var molwr = new MDLV2000Writer(System.Console.Out); molwr.Write(mol); molwr.Close(); } @@ -305,19 +296,19 @@ private void ValidateFingerprints(string label, AtomContainer mol, CircularFinge throw new CDKException("Fingerprint comparison failed."); } - private bool EqualFingerprints(CircularFingerprinter.FP fp1, CircularFingerprinter.FP fp2) + private static bool EqualFingerprints(CircularFingerprint fp1, CircularFingerprint fp2) { - if (fp1.HashCode != fp2.HashCode || fp1.Iteration != fp2.Iteration || fp1.Atoms.Length != fp2.Atoms.Length) + if (fp1.Hash != fp2.Hash || fp1.Iteration != fp2.Iteration || fp1.Atoms.Count != fp2.Atoms.Count) return false; - for (int n = 0; n < fp1.Atoms.Length; n++) + for (int n = 0; n < fp1.Atoms.Count; n++) if (fp1.Atoms[n] != fp2.Atoms[n]) return false; return true; } - private string FormatFP(CircularFingerprinter.FP fp) + private static string FormatFP(CircularFingerprint fp) { - string str = "[" + fp.HashCode + "] iter=" + fp.Iteration + " atoms={"; - for (int n = 0; n < fp.Atoms.Length; n++) + string str = "[" + fp.Hash + "] iter=" + fp.Iteration + " atoms={"; + for (int n = 0; n < fp.Atoms.Count; n++) str += (n > 0 ? "," : "") + fp.Atoms[n]; return str + "}"; } @@ -327,7 +318,7 @@ public void ProtonsDontCauseNPE() { IAtomContainer proton = new AtomContainer(); proton.Atoms.Add(Atom("H", +1, 0)); - CircularFingerprinter circ = new CircularFingerprinter(CircularFingerprinter.CFPClass.FCFP2); + var circ = new CircularFingerprinter(CircularFingerprinterClass.FCFP2); Assert.AreEqual(circ.GetBitFingerprint(proton).Cardinality, 0); } @@ -347,7 +338,7 @@ public void IminesDetectionDoesntCauseNPE() pyrazole.AddBond(pyrazole.Atoms[3], pyrazole.Atoms[4], BondOrder.Single); pyrazole.AddBond(pyrazole.Atoms[4], pyrazole.Atoms[5], BondOrder.Double); pyrazole.AddBond(pyrazole.Atoms[1], pyrazole.Atoms[5], BondOrder.Single); - CircularFingerprinter circ = new CircularFingerprinter(CircularFingerprinter.CFPClass.FCFP2); + var circ = new CircularFingerprinter(CircularFingerprinterClass.FCFP2); Assert.IsNotNull(circ.GetBitFingerprint(pyrazole)); } @@ -367,7 +358,7 @@ public void PartialCoordinatesDontCauseNPE() m.AddBond(m.Atoms[1], m.Atoms[3], BondOrder.Single, BondStereo.Down); m.AddBond(m.Atoms[1], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[4], m.Atoms[5], BondOrder.Single); - CircularFingerprinter circ = new CircularFingerprinter(CircularFingerprinter.CFPClass.ECFP6); + var circ = new CircularFingerprinter(CircularFingerprinterClass.ECFP6); Assert.IsNotNull(circ.GetBitFingerprint(m)); } @@ -391,11 +382,8 @@ public void TestNonZZeroPlaner() mol.AddBond(mol.Atoms[0], mol.Atoms[3], BondOrder.Single); mol.Bonds[0].Stereo = BondStereo.Up; - CircularFingerprinter circ = new CircularFingerprinter(CircularFingerprinter.CFPClass.ECFP6) - { - PerceiveStereo = true - }; - IBitFingerprint fp0 = circ.GetBitFingerprint(mol); + var circ = new CircularFingerprinter(CircularFingerprinterClass.ECFP6) { PerceiveStereo = true }; + var fp0 = circ.GetBitFingerprint(mol); foreach (var atom in atoms) { @@ -404,7 +392,7 @@ public void TestNonZZeroPlaner() atom.Point3D = v; } - IBitFingerprint fp1 = circ.GetBitFingerprint(mol); + var fp1 = circ.GetBitFingerprint(mol); Assert.AreEqual(fp0, fp1); } @@ -432,9 +420,8 @@ static IAtom Atom(string symbol, int h, double x, double y) [TestMethod()] public void TestVersion() { - var fpr = new CircularFingerprinter(CircularFingerprinter.CFPClass.ECFP4); - string expected = "CDK-CircularFingerprinter/" + CDK.Version + - " classType=ECFP4 perceiveStereochemistry=false"; + var fpr = new CircularFingerprinter(CircularFingerprinterClass.ECFP4); + string expected = $"CDK-CircularFingerprinter/{CDK.Version} classType=ECFP4 perceiveStereochemistry=false"; Assert.AreEqual(expected, fpr.GetVersionDescription()); } } diff --git a/NCDKTests/Fingerprints/EStateFingerprinterTest.cs b/NCDKTests/Fingerprints/EStateFingerprinterTest.cs index 8236af6e..d76906be 100644 --- a/NCDKTests/Fingerprints/EStateFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/EStateFingerprinterTest.cs @@ -43,7 +43,7 @@ public override IFingerprinter GetBitFingerprinter() public void TestGetSize() { IFingerprinter printer = new EStateFingerprinter(); - Assert.AreEqual(79, printer.Count); + Assert.AreEqual(79, printer.Length); } [TestMethod()] @@ -55,7 +55,7 @@ public void TestFingerprint() IBitFingerprint bs1 = printer.GetBitFingerprint(parser.ParseSmiles("C=C-C#N")); IBitFingerprint bs2 = printer.GetBitFingerprint(parser.ParseSmiles("C=CCC(O)CC#N")); - Assert.AreEqual(79, printer.Count); + Assert.AreEqual(79, printer.Length); Assert.IsTrue(bs1[7]); Assert.IsTrue(bs1[10]); @@ -83,8 +83,8 @@ public override void TestBug706786() IBitFingerprint superBits = fpr.GetBitFingerprint(superStructure); IBitFingerprint subBits = fpr.GetBitFingerprint(subStructure); - Assert.IsTrue(BitArrays.AreEqual(AsBitSet(6, 11, 12, 15, 16, 18, 33, 34, 35), superBits.AsBitSet())); - Assert.IsTrue(BitArrays.AreEqual(AsBitSet(8, 11, 16, 35), subBits.AsBitSet())); + Assert.IsTrue(BitArrays.Equals(AsBitSet(6, 11, 12, 15, 16, 18, 33, 34, 35), superBits.AsBitSet())); + Assert.IsTrue(BitArrays.Equals(AsBitSet(8, 11, 16, 35), subBits.AsBitSet())); } } } diff --git a/NCDKTests/Fingerprints/ExtendedFingerprinterTest.cs b/NCDKTests/Fingerprints/ExtendedFingerprinterTest.cs index b7306745..6ff64079 100644 --- a/NCDKTests/Fingerprints/ExtendedFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/ExtendedFingerprinterTest.cs @@ -22,15 +22,14 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Graphs; using NCDK.IO; using NCDK.Numerics; using NCDK.RingSearches; +using NCDK.Silent; using NCDK.Templates; using NCDK.Tools.Diff; using System.Collections; -using System.Collections.Generic; namespace NCDK.Fingerprints { @@ -65,17 +64,17 @@ public void TestgetBitFingerprint_IAtomContainer() } [TestMethod()] - public void TestgetBitFingerprint_IAtomContainer_IRingSet_List() + public void TestgetBitFingerprintIAtomContainerIRingSetList() { - ExtendedFingerprinter fingerprinter = new ExtendedFingerprinter(); + var fingerprinter = new ExtendedFingerprinter(); Assert.IsNotNull(fingerprinter); - IAtomContainer mol = TestMoleculeFactory.MakeIndole(); - IRingSet rs = Cycles.FindSSSR(mol).ToRingSet(); - IList rslist = RingPartitioner.PartitionRings(rs); - BitArray bs = fingerprinter.GetBitFingerprint(mol, rs, rslist).AsBitSet(); - IAtomContainer frag1 = TestMoleculeFactory.MakePyrrole(); - BitArray bs1 = fingerprinter.GetBitFingerprint(frag1).AsBitSet(); + var mol = TestMoleculeFactory.MakeIndole(); + var rs = Cycles.FindSSSR(mol).ToRingSet(); + var rslist = RingPartitioner.PartitionRings(rs); + var bs = fingerprinter.GetBitFingerprint(mol, rs, rslist).AsBitSet(); + var frag1 = TestMoleculeFactory.MakePyrrole(); + var bs1 = fingerprinter.GetBitFingerprint(frag1).AsBitSet(); Assert.IsTrue(FingerprinterTool.IsSubset(bs, bs1)); Assert.IsFalse(FingerprinterTool.IsSubset(bs1, bs)); } @@ -85,7 +84,7 @@ public void TestGetSize() { IFingerprinter fingerprinter = new ExtendedFingerprinter(512); Assert.IsNotNull(fingerprinter); - Assert.AreEqual(512, fingerprinter.Count); + Assert.AreEqual(512, fingerprinter.Length); } [TestMethod()] @@ -433,7 +432,7 @@ public void TestMoleculeInvariance() Assert.IsNotNull(fp); string diff2 = AtomContainerDiff.Diff(mol, clone); - Assert.IsTrue(diff2.Equals(""), "There was a difference\n" + diff2); + Assert.IsTrue(diff2.Length == 0, "There was a difference\n" + diff2); } } } diff --git a/NCDKTests/Fingerprints/FingerprinterTest.cs b/NCDKTests/Fingerprints/FingerprinterTest.cs index 3e8dedd3..8efc7c99 100644 --- a/NCDKTests/Fingerprints/FingerprinterTest.cs +++ b/NCDKTests/Fingerprints/FingerprinterTest.cs @@ -23,9 +23,9 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Collections; -using NCDK.Default; using NCDK.Graphs; using NCDK.IO; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; using NCDK.Tools.Manipulator; @@ -66,7 +66,7 @@ public void TestGetSize() { IFingerprinter fingerprinter = new Fingerprinter(512); Assert.IsNotNull(fingerprinter); - Assert.AreEqual(512, fingerprinter.Count); + Assert.AreEqual(512, fingerprinter.Length); } [TestMethod()] @@ -85,7 +85,7 @@ public void TestgetBitFingerprint_IAtomContainer() IAtomContainer mol = TestMoleculeFactory.MakeIndole(); IBitFingerprint bs = fingerprinter.GetBitFingerprint(mol); Assert.IsNotNull(bs); - Assert.AreEqual(fingerprinter.Count, bs.Count); + Assert.AreEqual(fingerprinter.Length, bs.Length); } [TestMethod()] @@ -254,7 +254,7 @@ public void TestAtomPermutation2() public static IAtomContainer MakeFragment1() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -274,7 +274,7 @@ public static IAtomContainer MakeFragment1() public static IAtomContainer MakeFragment4() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 @@ -284,7 +284,7 @@ public static IAtomContainer MakeFragment4() public static IAtomContainer MakeFragment2() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -305,7 +305,7 @@ public static IAtomContainer MakeFragment2() public static IAtomContainer MakeFragment3() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -325,7 +325,7 @@ public static IAtomContainer MakeFragment3() public static IAtomContainer MakeButane() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -340,7 +340,7 @@ public static IAtomContainer MakeButane() public static IAtomContainer MakePropylAmine() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 diff --git a/NCDKTests/Fingerprints/FingerprinterToolTest.cs b/NCDKTests/Fingerprints/FingerprinterToolTest.cs index 4ef0899b..18fd0ec3 100644 --- a/NCDKTests/Fingerprints/FingerprinterToolTest.cs +++ b/NCDKTests/Fingerprints/FingerprinterToolTest.cs @@ -87,11 +87,13 @@ public void TestDifferences() [TestMethod()] public void MakeBitFingerprint() { - IDictionary features = new Dictionary(); - features.Add("CCO", 1); - features.Add("CC", 1); - features.Add("C", 1); - IBitFingerprint fp = FingerprinterTool.MakeBitFingerprint(features, 1024, 1); + var features = new Dictionary + { + { "CCO", 1 }, + { "CC", 1 }, + { "C", 1 } + }; + var fp = FingerprinterTool.MakeBitFingerprint(features, 1024, 1); Assert.IsTrue(3 >= fp.Cardinality); Assert.IsTrue(fp[(int)((uint)"CCO".GetHashCode() % 1024)]); Assert.IsTrue(fp[(int)((uint)"CC".GetHashCode() % 1024)]); @@ -101,11 +103,13 @@ public void MakeBitFingerprint() [TestMethod()] public void MakeCountFingerprint() { - IDictionary features = new Dictionary(); - features.Add("CCO", 1); - features.Add("CC", 2); - features.Add("C", 2); - ICountFingerprint fp = FingerprinterTool.MakeCountFingerprint(features); + var features = new Dictionary + { + { "CCO", 1 }, + { "CC", 2 }, + { "C", 2 } + }; + var fp = FingerprinterTool.MakeCountFingerprint(features); Assert.AreEqual(3, fp.GetNumberOfPopulatedBins()); Assert.AreEqual(1, fp.GetCountForHash("CCO".GetHashCode())); Assert.AreEqual(2, fp.GetCountForHash("CC".GetHashCode())); diff --git a/NCDKTests/Fingerprints/GraphOnlyFingerprinterTest.cs b/NCDKTests/Fingerprints/GraphOnlyFingerprinterTest.cs index 6d217a6b..e3dacd86 100644 --- a/NCDKTests/Fingerprints/GraphOnlyFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/GraphOnlyFingerprinterTest.cs @@ -22,9 +22,9 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; using NCDK.Isomorphisms; +using NCDK.Silent; using NCDK.Smiles; using System.Collections; using System.Diagnostics; @@ -94,7 +94,7 @@ private static IAtomContainer CreateMolecule(string molecule) Assert.IsNotNull(reader, "Could not create reader"); if (reader.Accepts(typeof(AtomContainer))) { - structure = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + structure = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); } } return structure; diff --git a/NCDKTests/Fingerprints/KlekotaRothFingerprinterTest.cs b/NCDKTests/Fingerprints/KlekotaRothFingerprinterTest.cs index 94d5b28c..842a9ca5 100644 --- a/NCDKTests/Fingerprints/KlekotaRothFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/KlekotaRothFingerprinterTest.cs @@ -41,7 +41,7 @@ public override IFingerprinter GetBitFingerprinter() public void TestGetSize() { IFingerprinter printer = GetBitFingerprinter(); - Assert.AreEqual(4860, printer.Count); + Assert.AreEqual(4860, printer.Length); } [TestMethod()] @@ -53,7 +53,7 @@ public void TestFingerprint() BitArray bs1 = printer.GetBitFingerprint(parser.ParseSmiles("C=C-C#N")).AsBitSet(); BitArray bs2 = printer.GetBitFingerprint(parser.ParseSmiles("C=CCC(O)CC#N")).AsBitSet(); - Assert.AreEqual(4860, printer.Count); + Assert.AreEqual(4860, printer.Length); Assert.IsTrue(FingerprinterTool.IsSubset(bs2, bs1)); } diff --git a/NCDKTests/Fingerprints/LingoFingerprinterTest.cs b/NCDKTests/Fingerprints/LingoFingerprinterTest.cs index 33adb809..635de5d9 100644 --- a/NCDKTests/Fingerprints/LingoFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/LingoFingerprinterTest.cs @@ -23,8 +23,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; -using System.Collections.Generic; namespace NCDK.Fingerprints { @@ -40,17 +40,17 @@ public override IFingerprinter GetBitFingerprinter() [TestMethod()] public void TestGetSize() { - IFingerprinter fingerprinter = new LingoFingerprinter(); + var fingerprinter = new LingoFingerprinter(); Assert.IsNotNull(fingerprinter); - Assert.AreEqual(-1, fingerprinter.Count); + Assert.AreEqual(-1, fingerprinter.Length); } [TestMethod()] public override void TestGetCountFingerprint() { - LingoFingerprinter fpr = new LingoFingerprinter(4); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - IAtomContainer mol = sp.ParseSmiles("Oc1ccccc1"); + var fpr = new LingoFingerprinter(4); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var mol = sp.ParseSmiles("Oc1ccccc1"); ICountFingerprint fp = fpr.GetCountFingerprint(mol); Assert.AreEqual(2, fp.GetCountForHash("cccc".GetHashCode())); Assert.AreEqual(1, fp.GetCountForHash("Oc0c".GetHashCode())); @@ -62,13 +62,13 @@ public override void TestGetCountFingerprint() [TestMethod()] public override void TestGetRawFingerprint() { - LingoFingerprinter lfp = new LingoFingerprinter(3); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - IAtomContainer mol = sp.ParseSmiles("SPONC"); - IDictionary map = lfp.GetRawFingerprint(mol); + var lfp = new LingoFingerprinter(3); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var mol = sp.ParseSmiles("SPONC"); + var map = lfp.GetRawFingerprint(mol); Assert.AreEqual(3, map.Count); // depend on canonical ordering of the SMILES since lingos uses Unique SMILES - string[] subs = { "PON", "ONC", "SPO" }; + var subs = new[] { "PON", "ONC", "SPO" }; foreach (var s in subs) Assert.IsTrue(map.ContainsKey(s)); } diff --git a/NCDKTests/Fingerprints/MACCSFingerprinterTest.cs b/NCDKTests/Fingerprints/MACCSFingerprinterTest.cs index cd584de4..96cd748a 100644 --- a/NCDKTests/Fingerprints/MACCSFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/MACCSFingerprinterTest.cs @@ -45,7 +45,7 @@ public override IFingerprinter GetBitFingerprinter() public void Getsize() { IFingerprinter printer = new MACCSFingerprinter(Silent.ChemObjectBuilder.Instance); - Assert.AreEqual(166, printer.Count); + Assert.AreEqual(166, printer.Length); } [TestMethod()] @@ -69,7 +69,7 @@ public void TestFingerprint() BitArray bs2 = printer.GetBitFingerprint(mol2).AsBitSet(); BitArray bs3 = printer.GetBitFingerprint(mol3).AsBitSet(); - Assert.AreEqual(166, printer.Count); + Assert.AreEqual(166, printer.Length); Assert.IsFalse(bs1[165]); Assert.IsTrue(bs1[124]); @@ -131,11 +131,11 @@ public override void TestBug706786() IBitFingerprint superBits = fpr.GetBitFingerprint(superStructure); IBitFingerprint subBits = fpr.GetBitFingerprint(subStructure); - Assert.IsTrue(BitArrays.AreEqual( + Assert.IsTrue(BitArrays.Equals( AsBitSet(53, 56, 65, 71, 73, 88, 97, 104, 111, 112, 126, 130, 136, 138, 139, 140, 142, 143, 144, 145, 148, 149, 151, 153, 156, 158, 159, 161, 162, 163, 164), superBits.AsBitSet())); - Assert.IsTrue(BitArrays.AreEqual( + Assert.IsTrue(BitArrays.Equals( AsBitSet(56, 97, 104, 108, 112, 117, 131, 136, 143, 144, 146, 151, 152, 156, 161, 162, 163, 164), subBits.AsBitSet())); } diff --git a/NCDKTests/Fingerprints/Model/BayesianTest.cs b/NCDKTests/Fingerprints/Model/BayesianTest.cs index 67097c5f..e4ca2d70 100644 --- a/NCDKTests/Fingerprints/Model/BayesianTest.cs +++ b/NCDKTests/Fingerprints/Model/BayesianTest.cs @@ -30,9 +30,11 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.IO.Iterator; +using NCDK.Silent; using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; @@ -45,7 +47,7 @@ namespace NCDK.Fingerprints.Model [TestClass()] public class BayesianTest { - private static readonly string REF_MOLECULE = "\n\n\n" + private const string REF_MOLECULE = "\n\n\n" + " 18 19 0 0 0 0 0 0 0 0999 V2000\n" + " -2.5317 -1.1272 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n" + " -1.5912 0.1672 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0\n" @@ -109,8 +111,8 @@ public void TestFingerprints() { Trace.TraceInformation("Bayesian/Fingerprints test: verifying circular fingerprints for a single molecule"); - CheckFP(REF_MOLECULE, CircularFingerprinter.CFPClass.ECFP6, 0, REF_ECFP6_0); - CheckFP(REF_MOLECULE, CircularFingerprinter.CFPClass.ECFP6, 1024, REF_ECFP6_1024); + CheckFP(REF_MOLECULE, CircularFingerprinterClass.ECFP6, 0, REF_ECFP6_0); + CheckFP(REF_MOLECULE, CircularFingerprinterClass.ECFP6, 1024, REF_ECFP6_1024); } [TestMethod()] @@ -135,10 +137,10 @@ public void TestFolding() { Trace.TraceInformation("Bayesian/Fingerprints test: comparing folded fingerprints to reference set"); - CompareFolding("FoldedProbes.sdf", "ECFP6/0", CircularFingerprinter.CFPClass.ECFP6, 0); - CompareFolding("FoldedProbes.sdf", "ECFP6/1024", CircularFingerprinter.CFPClass.ECFP6, 1024); - CompareFolding("FoldedProbes.sdf", "ECFP6/32768", CircularFingerprinter.CFPClass.ECFP6, 32768); - CompareFolding("FoldedProbes.sdf", "FCFP6/0", CircularFingerprinter.CFPClass.FCFP6, 0); + CompareFolding("FoldedProbes.sdf", "ECFP6/0", CircularFingerprinterClass.ECFP6, 0); + CompareFolding("FoldedProbes.sdf", "ECFP6/1024", CircularFingerprinterClass.ECFP6, 1024); + CompareFolding("FoldedProbes.sdf", "ECFP6/32768", CircularFingerprinterClass.ECFP6, 32768); + CompareFolding("FoldedProbes.sdf", "FCFP6/0", CircularFingerprinterClass.FCFP6, 0); } [TestMethod()] @@ -147,10 +149,9 @@ public void TestExample1() { Trace.TraceInformation("Bayesian/Fingerprints test: using dataset of binding data to compare to reference data"); - RunTest("Binders.sdf", "active", CircularFingerprinter.CFPClass.ECFP6, 1024, 0, "Binders-ECFP6-1024-loo.bayesian", true); - RunTest("Binders.sdf", "active", CircularFingerprinter.CFPClass.ECFP6, 32768, 5, - "Binders-ECFP6-32768-xv5.bayesian", true); - RunTest("Binders.sdf", "active", CircularFingerprinter.CFPClass.FCFP6, 0, 0, "Binders-FCFP6-0-loo.bayesian", true); + RunTest("Binders.sdf", "active", CircularFingerprinterClass.ECFP6, 1024, 0, "Binders-ECFP6-1024-loo.bayesian", true); + RunTest("Binders.sdf", "active", CircularFingerprinterClass.ECFP6, 32768, 5, "Binders-ECFP6-32768-xv5.bayesian", true); + RunTest("Binders.sdf", "active", CircularFingerprinterClass.FCFP6, 0, 0, "Binders-FCFP6-0-loo.bayesian", true); } [TestMethod()] @@ -159,25 +160,25 @@ public void TestExample2() { Trace.TraceInformation("Bayesian/Fingerprints test: using dataset of molecular probes to compare to reference data"); - RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinter.CFPClass.ECFP6, 1024, 0, + RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinterClass.ECFP6, 1024, 0, "MLProbes-ECFP6-1024-loo.bayesian"); - RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinter.CFPClass.ECFP6, 32768, 5, + RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinterClass.ECFP6, 32768, 5, "MLProbes-ECFP6-32768-xv5.bayesian"); - RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinter.CFPClass.FCFP6, 0, 0, + RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinterClass.FCFP6, 0, 0, "MLProbes-FCFP6-0-loo.bayesian"); - RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinter.CFPClass.FCFP6, 256, 3, + RunTest("MLProbes.sdf", "Lipinski score", CircularFingerprinterClass.FCFP6, 256, 3, "MLProbes-FCFP6-256-xv3.bayesian"); } // ----------------- private methods ----------------- // make sure that for a single molecule, the way that the hashes are created & folded is consistent with a reference - private void CheckFP(string molstr, CircularFingerprinter.CFPClass classType, int folding, int[] refHash) + private static void CheckFP(string molstr, CircularFingerprinterClass classType, int folding, int[] refHash) { - string strType = classType == CircularFingerprinter.CFPClass.ECFP6 ? "ECFP6" : "FCFP6"; + string strType = classType == CircularFingerprinterClass.ECFP6 ? "ECFP6" : "FCFP6"; WriteLine("Comparing hash codes for " + strType + "/folding=" + folding); - IAtomContainer mol = new EnumerableSDFReader(new StringReader(molstr), Default.ChemObjectBuilder.Instance).First(); + IAtomContainer mol = new EnumerableSDFReader(new StringReader(molstr), ChemObjectBuilder.Instance).First(); Bayesian model = new Bayesian(classType, folding); model.AddMolecule(mol, false); @@ -205,7 +206,7 @@ private void CheckTextFields() string dummyTitle = "some title", dummyOrigin = "some origin"; string[] dummyComments = new string[] { "comment1", "comment2" }; - Bayesian model1 = new Bayesian(CircularFingerprinter.CFPClass.ECFP6) + Bayesian model1 = new Bayesian(CircularFingerprinterClass.ECFP6) { NoteTitle = dummyTitle, NoteOrigin = dummyOrigin, @@ -222,44 +223,50 @@ private void CheckTextFields() throw new CDKException("Reserialisation failed", ex); } - if (!dummyTitle.Equals(model1.NoteTitle) || !dummyTitle.Equals(model2.NoteTitle) - || !dummyOrigin.Equals(model1.NoteOrigin) || !dummyOrigin.Equals(model2.NoteOrigin)) + if (!dummyTitle.Equals(model1.NoteTitle, StringComparison.Ordinal) + || !dummyTitle.Equals(model2.NoteTitle, StringComparison.Ordinal) + || !dummyOrigin.Equals(model1.NoteOrigin, StringComparison.Ordinal) + || !dummyOrigin.Equals(model2.NoteOrigin, StringComparison.Ordinal)) throw new CDKException("Note integrity failure for origin"); - string[] comments1 = model1.NoteComments, comments2 = model2.NoteComments; - if (comments1.Length != dummyComments.Length || comments2.Length != dummyComments.Length - || !comments1[0].Equals(dummyComments[0]) || !comments2[0].Equals(dummyComments[0]) - || !comments1[1].Equals(dummyComments[1]) || !comments2[1].Equals(dummyComments[1])) + var comments1 = model1.NoteComments; + var comments2 = model2.NoteComments; + if (comments1.Count != dummyComments.Length + || comments2.Count != dummyComments.Length + || !comments1[0].Equals(dummyComments[0], StringComparison.Ordinal) + || !comments2[0].Equals(dummyComments[0], StringComparison.Ordinal) + || !comments1[1].Equals(dummyComments[1], StringComparison.Ordinal) + || !comments2[1].Equals(dummyComments[1], StringComparison.Ordinal)) throw new CDKException("Note integrity failure for origin"); } // builds a model and uses the scaled predictions to rack up a confusion matrix, for comparison - private void ConfirmPredictions(string sdfile, int truePos, int trueNeg, int falsePos, int falseNeg) + private static void ConfirmPredictions(string sdfile, int truePos, int trueNeg, int falsePos, int falseNeg) { WriteLine("[" + sdfile + "] comparing confusion matrix"); List molecules = new List(); List activities = new List(); - Bayesian model = new Bayesian(CircularFingerprinter.CFPClass.ECFP6, 1024); + Bayesian model = new Bayesian(CircularFingerprinterClass.ECFP6, 1024); try { using (Stream ins = ResourceLoader.GetAsStream("NCDK.Data.CDD." + sdfile)) { - EnumerableSDFReader rdr = new EnumerableSDFReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSDFReader rdr = new EnumerableSDFReader(ins, ChemObjectBuilder.Instance); foreach (var mol in rdr) { - bool actv = "true".Equals((string)mol.GetProperties()["Active"]); + bool actv = "true" == (string)mol.GetProperties()["Active"]; molecules.Add(mol); activities.Add(actv); model.AddMolecule(mol, actv); } } } - catch (CDKException ex) + catch (CDKException) { - throw ex; + throw; } catch (Exception ex) { @@ -301,7 +308,7 @@ private void ConfirmPredictions(string sdfile, int truePos, int trueNeg, int fal } // compares a series of molecules for folding fingerprints being literally identical - private void CompareFolding(string sdfile, string fpField, CircularFingerprinter.CFPClass classType, int folding) + private static void CompareFolding(string sdfile, string fpField, CircularFingerprinterClass classType, int folding) { WriteLine("[" + sdfile + "] calculation of: " + fpField); @@ -310,7 +317,7 @@ private void CompareFolding(string sdfile, string fpField, CircularFingerprinter { using (Stream ins = ResourceLoader.GetAsStream("NCDK.Data.CDD." + sdfile)) { - EnumerableSDFReader rdr = new EnumerableSDFReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSDFReader rdr = new EnumerableSDFReader(ins, ChemObjectBuilder.Instance); int row = 0; foreach (var mol in rdr) @@ -324,20 +331,20 @@ private void CompareFolding(string sdfile, string fpField, CircularFingerprinter string gotHashes = ArrayStr(hashes); string reqHashes = (string)mol.GetProperties()[fpField]; - if (!gotHashes.Equals(reqHashes)) + if (gotHashes != reqHashes) { - WriteLine(" ///* mismatch at row " + row); - WriteLine(" ///* calc: " + gotHashes); - WriteLine(" ///* want: " + reqHashes); + WriteLine($" ///* mismatch at row {row}"); + WriteLine($" ///* calc: {gotHashes}"); + WriteLine($" ///* want: {reqHashes}"); failed = true; } } } } - catch (CDKException ex) + catch (CDKException) { - throw ex; + throw; } catch (Exception ex) { @@ -349,12 +356,12 @@ private void CompareFolding(string sdfile, string fpField, CircularFingerprinter // performs a bulk test: loads an SDfile, builds a model with the given parameters, and compares it to a reference model // that has been previously serialised - private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPClass classType, int folding, int xval, string modelFN) + private void RunTest(string sdfile, string actvField, CircularFingerprinterClass classType, int folding, int xval, string modelFN) { RunTest(sdfile, actvField, classType, folding, xval, modelFN, false); } - private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPClass classType, int folding, int xval, string modelFN, bool perceiveStereo) + private void RunTest(string sdfile, string actvField, CircularFingerprinterClass classType, int folding, int xval, string modelFN, bool perceiveStereo) { WriteLine("[" + modelFN + "]"); WriteLine(" Loading " + sdfile); @@ -369,15 +376,16 @@ private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPC int row = 0, numActives = 0; using ( EnumerableSDFReader rdr = new EnumerableSDFReader( - ResourceLoader.GetAsStream("NCDK.Data.CDD." + sdfile), Default.ChemObjectBuilder.Instance)) + ResourceLoader.GetAsStream("NCDK.Data.CDD." + sdfile), ChemObjectBuilder.Instance)) { foreach (var mol in rdr) { row++; string stractv = (string)mol.GetProperties()[actvField]; - int active = stractv.Equals("true") ? 1 : stractv.Equals("false") ? 0 : int.Parse(stractv); - if (active != 0 && active != 1) throw new CDKException("Activity field not found or invalid"); + int active = stractv.Equals("true", StringComparison.Ordinal) ? 1 : stractv.Equals("false", StringComparison.Ordinal) ? 0 : int.Parse(stractv, NumberFormatInfo.InvariantInfo); + if (active != 0 && active != 1) + throw new CDKException("Activity field not found or invalid"); model.AddMolecule(mol, active == 1); numActives += active; @@ -423,7 +431,7 @@ private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPC WriteLine(" ** reference training actives=" + reference.TrainingActives); failed = true; } - if (!model.RocType.Equals(reference.RocType)) + if (model.RocType != reference.RocType) { WriteLine(" ** reference ROC type=" + reference.RocType); failed = true; @@ -440,13 +448,13 @@ private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPC } if (Math.Abs(model.HighThreshold - reference.HighThreshold) > 0.00000000000001) { - WriteLine(" ** reference highThresh=" + reference.HighThreshold + " different to calculated " - + model.HighThreshold); + WriteLine(" ** reference highThresh=" + reference.HighThreshold + " different to calculated " + model.HighThreshold); failed = true; } // make sure individual hash bit contributions match - IDictionary mbits = model.Contributions, rbits = reference.Contributions; + var mbits = model.Contributions; + var rbits = reference.Contributions; if (mbits.Count != rbits.Count) { WriteLine(" ///* model has " + mbits.Count + " contribution bits, reference has " + rbits.Count); @@ -478,11 +486,12 @@ private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPC } } - if (failed) throw new CDKException("Comparison to reference failed"); + if (failed) + throw new CDKException("Comparison to reference failed"); } - catch (CDKException ex) + catch (CDKException) { - throw ex; + throw; } catch (Exception ex) { @@ -491,19 +500,18 @@ private void RunTest(string sdfile, string actvField, CircularFingerprinter.CFPC } // convenience functions - private void WriteLine(string str) + private static void WriteLine(string str) { - //Console.Out.WriteLine(str); Trace.TraceInformation(str); } - private bool DblEqual(double v1, double v2) + private static bool DblEqual(double v1, double v2) { return v1 == v2 || Math.Abs(v1 - v2) <= 1E-7 * Math.Max(Math.Abs(v1), Math.Abs(v2)); // 1E-14 to 1E-7 because of precision difference between double and float. } - private string ArrayStr(int[] A) + private static string ArrayStr(int[] A) { if (A == null) return "{null}"; string str = ""; diff --git a/NCDKTests/Fingerprints/PubchemFingerprinterTest.cs b/NCDKTests/Fingerprints/PubchemFingerprinterTest.cs index 230e8d62..98a1542f 100644 --- a/NCDKTests/Fingerprints/PubchemFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/PubchemFingerprinterTest.cs @@ -27,6 +27,7 @@ using NCDK.Aromaticities; using NCDK.Common.Base; using NCDK.Common.Collections; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -45,7 +46,7 @@ public class PubchemFingerprinterTest : AbstractFixedLengthFingerprinterTest public override IFingerprinter GetBitFingerprinter() { - return new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + return new PubchemFingerprinter(ChemObjectBuilder.Instance); } [TestInitialize()] @@ -57,15 +58,15 @@ public void Setup() [TestMethod()] public void TestGetSize() { - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); - Assert.AreEqual(881, printer.Count); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); + Assert.AreEqual(881, printer.Length); } [TestMethod()] public void TestFingerprint() { - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); - CDKHydrogenAdder adder = CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); + CDKHydrogenAdder adder = CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance); IAtomContainer mol1 = parser.ParseSmiles("c1ccccc1CCc1ccccc1"); IAtomContainer mol2 = parser.ParseSmiles("c1ccccc1CC"); @@ -85,7 +86,7 @@ public void TestFingerprint() BitArray bs1 = printer.GetBitFingerprint(mol1).AsBitSet(); BitArray bs2 = printer.GetBitFingerprint(mol2).AsBitSet(); - Assert.AreEqual(881, printer.Count); + Assert.AreEqual(881, printer.Length); Assert.IsFalse(FingerprinterTool.IsSubset(bs1, bs2), "c1ccccc1CC was detected as a subset of c1ccccc1CCc1ccccc1"); @@ -94,7 +95,7 @@ public void TestFingerprint() [TestMethod()] public void Testfp2() { - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); IAtomContainer mol1 = parser.ParseSmiles("CC(N)CCCN"); IAtomContainer mol2 = parser.ParseSmiles("CC(N)CCC"); @@ -131,12 +132,12 @@ public void TestCID2518130() AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(mol); Aromaticity.CDKLegacy.Apply(mol); - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); BitArray fp = printer.GetBitFingerprint(mol).AsBitSet(); BitArray ref_ = PubchemFingerprinter .Decode("AAADceBwPABAAAAAAAAAAAAAAAAAAAAAAAAkSAAAAAAAAAAAAAAAGgQACAAACBS0wAOCCAAABgQAAAAAAAAAAAAAAAAAAAAAAAAREAIAAAAiQAAFAAAHAAHAYAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="); - Assert.IsTrue(BitArrays.AreEqual(ref_, fp)); + Assert.IsTrue(BitArrays.Equals(ref_, fp)); } /// @@ -154,12 +155,12 @@ public void TestCID5934166() AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(mol); Aromaticity.CDKLegacy.Apply(mol); - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); BitArray fp = printer.GetBitFingerprint(mol).AsBitSet(); BitArray ref_ = PubchemFingerprinter .Decode("AAADceB+AAAAAAAAAAAAAAAAAAAAAAAAAAA8YMGCAAAAAAAB1AAAHAAAAAAADAjBHgQwgJMMEACgAyRiRACCgCAhAiAI2CA4ZJgIIOLAkZGEIAhggADIyAcQgMAOgAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="); - Assert.IsTrue(BitArrays.AreEqual(ref_, fp)); + Assert.IsTrue(BitArrays.Equals(ref_, fp)); } /// @@ -176,12 +177,12 @@ public void TestCID25181289() AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(mol); Aromaticity.CDKLegacy.Apply(mol); - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); BitArray fp = printer.GetBitFingerprint(mol).AsBitSet(); BitArray ref_ = PubchemFingerprinter .Decode("AAADccBzMAAGAAAAAAAAAAAAAAAAAAAAAAA8QAAAAAAAAAABwAAAHgIYCAAADA6BniAwzpJqEgCoAyTyTASChCAnJiIYumGmTtgKJnLD1/PEdQhkwBHY3Qe82AAOIAAAAAAAAABAAAAAAAAAAAAAAAAAAA=="); - Assert.IsTrue(BitArrays.AreEqual(ref_, fp)); + Assert.IsTrue(BitArrays.Equals(ref_, fp)); } [TestMethod()] @@ -250,12 +251,12 @@ public void TestBenzene() AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(mol); Aromaticity.CDKLegacy.Apply(mol); - IFingerprinter printer = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter printer = new PubchemFingerprinter(ChemObjectBuilder.Instance); BitArray fp = printer.GetBitFingerprint(mol).AsBitSet(); BitArray ref_ = PubchemFingerprinter .Decode("AAADcYBgAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAABAAAAGAAAAAAACACAEAAwAIAAAACAACBCAAACAAAgAAAIiAAAAIgIICKAERCAIAAggAAIiAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="); - Assert.IsTrue(BitArrays.AreEqual(ref_, fp)); + Assert.IsTrue(BitArrays.Equals(ref_, fp)); } class FpRunner @@ -272,7 +273,7 @@ public FpRunner(IAtomContainer mol) public void Call() { BitArray fp = null; - IFingerprinter fpr = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter fpr = new PubchemFingerprinter(ChemObjectBuilder.Instance); try { fp = fpr.GetBitFingerprint(mol).AsBitSet(); @@ -305,7 +306,7 @@ public void TestMultithReadedUsage() AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(mol2); Aromaticity.CDKLegacy.Apply(mol2); - IFingerprinter fp = new PubchemFingerprinter(Default.ChemObjectBuilder.Instance); + IFingerprinter fp = new PubchemFingerprinter(ChemObjectBuilder.Instance); BitArray bs1 = fp.GetBitFingerprint(mol1).AsBitSet(); BitArray bs2 = fp.GetBitFingerprint(mol2).AsBitSet(); @@ -323,8 +324,8 @@ public void TestMultithReadedUsage() BitArray fb2 = objs[1].Result; Assert.IsNotNull(fb2); - Assert.IsTrue(BitArrays.AreEqual(bs1, fb1)); - Assert.IsTrue(BitArrays.AreEqual(bs2, fb2)); + Assert.IsTrue(BitArrays.Equals(bs1, fb1)); + Assert.IsTrue(BitArrays.Equals(bs2, fb2)); } /// @@ -349,13 +350,13 @@ public override void TestBug934819() IBitFingerprint superBits = fpr.GetBitFingerprint(superStructure); IBitFingerprint subBits = fpr.GetBitFingerprint(subStructure); - Assert.IsTrue(BitArrays.AreEqual( + Assert.IsTrue(BitArrays.Equals( AsBitSet(9, 10, 14, 18, 19, 33, 143, 146, 255, 256, 283, 284, 285, 293, 301, 332, 344, 349, 351, 353, 355, 368, 370, 371, 376, 383, 384, 395, 401, 412, 416, 421, 423, 434, 441, 446, 449, 454, 455, 464, 470, 471, 480, 489, 490, 500, 502, 507, 513, 514, 516, 520, 524, 531, 532, 545, 546, 549, 552, 556, 558, 564, 570, 586, 592, 599, 600, 607, 633, 658, 665), subBits.AsBitSet())); - Assert.IsTrue(BitArrays.AreEqual( + Assert.IsTrue(BitArrays.Equals( AsBitSet(9, 10, 11, 14, 18, 19, 33, 34, 143, 146, 150, 153, 255, 256, 257, 258, 283, 284, 285, 293, 301, 332, 344, 349, 351, 353, 355, 368, 370, 371, 374, 376, 383, 384, 395, 401, 412, 416, 417, 421, 423, 427, 434, 441, 446, 449, 454, 455, 460, 464, 470, 471, 479, 480, 489, 490, 500, 502, diff --git a/NCDKTests/Fingerprints/ShortestPathFingerprinterTest.cs b/NCDKTests/Fingerprints/ShortestPathFingerprinterTest.cs index da7ae7db..cfe17677 100644 --- a/NCDKTests/Fingerprints/ShortestPathFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/ShortestPathFingerprinterTest.cs @@ -26,8 +26,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.Common.Collections; -using NCDK.Default; using NCDK.Graphs; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; using NCDK.Tools.Manipulator; @@ -66,7 +66,7 @@ public void TestGetSize() { IFingerprinter fingerprinter = new ShortestPathFingerprinter(512); Assert.IsNotNull(fingerprinter); - Assert.AreEqual(512, fingerprinter.Count); + Assert.AreEqual(512, fingerprinter.Length); } /// @@ -77,7 +77,7 @@ public void TestGetSize() public void TestGenerateFingerprint() { string smiles = "CCCCC1C(=O)N(N(C1=O)C1=CC=CC=C1)C1=CC=CC=C1"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); @@ -97,7 +97,7 @@ public void TestGenerateFingerprintIsSubset() { string smilesT = "NC(=O)C1=C2C=CC(Br)=CC2=C(Cl)C=C1"; string smilesQ = "CC1=C2C=CC(Br)=CC2=C(Cl)C=C1"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer moleculeQ = smilesParser.ParseSmiles(smilesQ); IAtomContainer moleculeT = smilesParser.ParseSmiles(smilesT); @@ -122,7 +122,7 @@ public void TestGenerateFingerprintIsNotASubSet1() { string smilesT = "O[C@H]1[C@H](O)[C@@H](O)[C@H](O)[C@H](O)[C@@H]1O"; string smilesQ = "OC[C@@H](O)[C@@H](O)[C@H](O)[C@@H](O)C(O)=O"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); smilesParser.Kekulise(false); IAtomContainer moleculeQ = smilesParser.ParseSmiles(smilesQ); IAtomContainer moleculeT = smilesParser.ParseSmiles(smilesT); @@ -142,7 +142,7 @@ public void TestGenerateFingerprintIsNotASubSet1() public void TestGenerateFingerprintAnthracene() { string smiles = "C1=CC2=CC3=CC=CC=C3C=C2C=C1"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); @@ -156,7 +156,7 @@ public void TestGenerateFingerprintAnthracene() public void TestGenerateFingerprintNaphthalene() { string smiles = "C1=CC2=CC=CC=C2C=C1"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); @@ -170,7 +170,7 @@ public void TestGenerateFingerprintNaphthalene() public void TestGenerateFingerprintMultiphtalene() { string smiles = "C1=CC2=CC=C3C4=CC5=CC6=CC=CC=C6C=C5C=C4C=CC3=C2C=C1"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); @@ -190,7 +190,7 @@ public void TestgetBitFingerprint_IAtomContainer() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); IBitFingerprint bs = fingerprinter.GetBitFingerprint(mol); Assert.IsNotNull(bs); - Assert.AreEqual(fingerprinter.Count, bs.Count); + Assert.AreEqual(fingerprinter.Length, bs.Length); } [TestMethod()] @@ -333,7 +333,7 @@ public void TestAtomPermutation2() public static IAtomContainer MakeFragment1() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -353,7 +353,7 @@ public static IAtomContainer MakeFragment1() public static IAtomContainer MakeFragment4() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 @@ -363,7 +363,7 @@ public static IAtomContainer MakeFragment4() public static IAtomContainer MakeFragment2() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -384,7 +384,7 @@ public static IAtomContainer MakeFragment2() public static IAtomContainer MakeFragment3() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 0 mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 @@ -404,7 +404,7 @@ public static IAtomContainer MakeFragment3() public static IAtomContainer MakeButane() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); Atom atom = new Atom("C") { Id = "0" }; mol.Atoms.Add(atom); // 0 @@ -426,7 +426,7 @@ public static IAtomContainer MakeButane() public static IAtomContainer MakePropylAmine() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); Atom atom = new Atom("C") { Id = "0" }; mol.Atoms.Add(atom); // 0 diff --git a/NCDKTests/Fingerprints/ShortestPathWalkerTest.cs b/NCDKTests/Fingerprints/ShortestPathWalkerTest.cs index 629c5fb3..4b55a539 100644 --- a/NCDKTests/Fingerprints/ShortestPathWalkerTest.cs +++ b/NCDKTests/Fingerprints/ShortestPathWalkerTest.cs @@ -13,11 +13,11 @@ public class ShortestPathWalkerTest [TestMethod()] public void TestPaths() { - IAtomContainer triazole = TestMoleculeFactory.Make123Triazole(); - ShortestPathWalker walker = new ShortestPathWalker(triazole); - ICollection expected = new SortedSet(new[] {"C", "N2N1N", "N", "N1N1C", "N1C2C", "C1N", "N2N1C", + var triazole = TestMoleculeFactory.Make123Triazole(); + var walker = new ShortestPathWalker(triazole); + var expected = new SortedSet(new[] {"C", "N2N1N", "N", "N1N1C", "N1C2C", "C1N", "N2N1C", "C1N2N", "C1N1N", "N1C", "C2C1N", "C2C", "N2N", "N1N2N", "N1N"}); - ICollection actual = walker.GetPaths(); + var actual = walker.GetPaths(); Assert.IsTrue(Compares.AreDeepEqual(expected, actual)); } diff --git a/NCDKTests/Fingerprints/SignatureFingerprinterTest.cs b/NCDKTests/Fingerprints/SignatureFingerprinterTest.cs index e3d69db3..9f262739 100644 --- a/NCDKTests/Fingerprints/SignatureFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/SignatureFingerprinterTest.cs @@ -22,8 +22,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; -using System.Collections.Generic; namespace NCDK.Fingerprints { @@ -39,20 +39,20 @@ public override IFingerprinter GetBitFingerprinter() [TestMethod()] public void TestGetSize() { - IFingerprinter fingerprinter = new SignatureFingerprinter(); + var fingerprinter = new SignatureFingerprinter(); Assert.IsNotNull(fingerprinter); - Assert.AreEqual(-1, fingerprinter.Count); + Assert.AreEqual(-1, fingerprinter.Length); } [TestMethod()] public override void TestGetRawFingerprint() { - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(0); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - IAtomContainer mol = sp.ParseSmiles("O(NC)CC"); - IDictionary map = fingerprinter.GetRawFingerprint(mol); + var fingerprinter = new SignatureFingerprinter(0); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var mol = sp.ParseSmiles("O(NC)CC"); + var map = fingerprinter.GetRawFingerprint(mol); Assert.AreEqual(3, map.Count); - string[] expectedPrints = { "[O]", "[C]", "[N]" }; + var expectedPrints = new[] { "[O]", "[C]", "[N]" }; foreach (var print in expectedPrints) { Assert.IsTrue(map.ContainsKey(print)); @@ -62,23 +62,23 @@ public override void TestGetRawFingerprint() [TestMethod()] public void TestBitFingerprint() { - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(0); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - IAtomContainer mol = sp.ParseSmiles("O(NC)CC"); - IBitFingerprint bitFP = fingerprinter.GetBitFingerprint(mol); + var fingerprinter = new SignatureFingerprinter(0); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var mol = sp.ParseSmiles("O(NC)CC"); + var bitFP = fingerprinter.GetBitFingerprint(mol); Assert.IsNotNull(bitFP); - Assert.AreNotSame(0, bitFP.Count); + Assert.AreNotSame(0, bitFP.Length); } [TestMethod()] public override void TestGetCountFingerprint() { - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(0); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - IAtomContainer mol = sp.ParseSmiles("O(NC)CC"); + var fingerprinter = new SignatureFingerprinter(0); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var mol = sp.ParseSmiles("O(NC)CC"); ICountFingerprint bitFP = fingerprinter.GetCountFingerprint(mol); Assert.IsNotNull(bitFP); - Assert.AreNotSame(0, bitFP.Count); + Assert.AreNotSame(0, bitFP.Length); } } } diff --git a/NCDKTests/Fingerprints/SimpleAtomCanonicalizerTest.cs b/NCDKTests/Fingerprints/SimpleAtomCanonicalizerTest.cs index 99617c03..bd5b206c 100644 --- a/NCDKTests/Fingerprints/SimpleAtomCanonicalizerTest.cs +++ b/NCDKTests/Fingerprints/SimpleAtomCanonicalizerTest.cs @@ -16,7 +16,7 @@ public void TestCanonicalizeAtoms() IAtomContainer container = TestMoleculeFactory.MakeAdenine(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - var atoms = new SimpleAtomCanonicalizer().CanonicalizeAtoms(container); + var atoms = SimpleAtomCanonicalizer.CanonicalizeAtoms(container.Atoms); List mutable = new List(atoms); foreach (var atom in mutable.GetRange(0, 5)) diff --git a/NCDKTests/Fingerprints/SimpleAtomComparatorTest.cs b/NCDKTests/Fingerprints/SimpleAtomComparatorTest.cs index 00ce2e72..9a504d12 100644 --- a/NCDKTests/Fingerprints/SimpleAtomComparatorTest.cs +++ b/NCDKTests/Fingerprints/SimpleAtomComparatorTest.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Fingerprints; +using NCDK.Silent; namespace NCDK.Fingerprints { @@ -8,7 +9,7 @@ namespace NCDK.Fingerprints [TestClass()] public class SimpleAtomComparatorTest { - private IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestCompare_NullHybridization() diff --git a/NCDKTests/Fingerprints/SubstructureFingerprinterTest.cs b/NCDKTests/Fingerprints/SubstructureFingerprinterTest.cs index 7ec7132a..7e03add6 100644 --- a/NCDKTests/Fingerprints/SubstructureFingerprinterTest.cs +++ b/NCDKTests/Fingerprints/SubstructureFingerprinterTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Collections; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.Fingerprints @@ -41,7 +42,7 @@ public override IFingerprinter GetBitFingerprinter() public void TestSize() { SubstructureFingerprinter fp = new SubstructureFingerprinter(); - Assert.AreEqual(307, fp.Count); + Assert.AreEqual(307, fp.Length); } [TestMethod()] @@ -57,10 +58,10 @@ public override void TestBug706786() IBitFingerprint superBits = fpr.GetBitFingerprint(superStructure); IBitFingerprint subBits = fpr.GetBitFingerprint(subStructure); - Assert.IsTrue(BitArrays.AreEqual( + Assert.IsTrue(BitArrays.Equals( AsBitSet(0, 11, 13, 17, 40, 48, 136, 273, 274, 278, 286, 294, 299, 301, 304, 306), superBits.AsBitSet())); - Assert.IsTrue(BitArrays.AreEqual( + Assert.IsTrue(BitArrays.Equals( AsBitSet(1, 17, 273, 274, 278, 294, 306), subBits.AsBitSet())); } @@ -70,9 +71,9 @@ public void TestUserFunctionalGroups() { string[] smarts = { "c1ccccc1", "[CX4H3][#6]", "[CX2]#[CX2]" }; IFingerprinter printer = new SubstructureFingerprinter(smarts); - Assert.AreEqual(3, printer.Count); + Assert.AreEqual(3, printer.Length); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles("c1ccccc1CCC"); IBitFingerprint fp = printer.GetBitFingerprint(mol1); Assert.IsNotNull(fp); @@ -93,9 +94,9 @@ public void TestUserFunctionalGroups() public void TestFingerprint() { IFingerprinter printer = new SubstructureFingerprinter(); - Assert.AreEqual(307, printer.Count); + Assert.AreEqual(307, printer.Length); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles("c1ccccc1CCC"); IBitFingerprint fp = printer.GetBitFingerprint(mol1); Assert.IsNotNull(fp); @@ -113,11 +114,11 @@ public void TestFingerprint() /// // @cdk.bug 2871303 //("the SMARTS pattern vinylogous ester is not strict enough - we can not fix this") - public void TestVinylogousEster() + public static void TestVinylogousEster() { string benzaldehyde = "c1ccccc1C=O"; IFingerprinter fprinter = new SubstructureFingerprinter(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IBitFingerprint fp = fprinter.GetBitFingerprint(sp.ParseSmiles(benzaldehyde)); Assert.IsFalse(fp[136], "Bit 136 (vinylogous ester) is set to true"); } diff --git a/NCDKTests/ForceField/MMFF/AbstractMmffAtomTypeValidationSuiteTest.cs b/NCDKTests/ForceFields/AbstractMmffAtomTypeValidationSuiteTest.cs similarity index 99% rename from NCDKTests/ForceField/MMFF/AbstractMmffAtomTypeValidationSuiteTest.cs rename to NCDKTests/ForceFields/AbstractMmffAtomTypeValidationSuiteTest.cs index d69b881e..62cf9b8c 100644 --- a/NCDKTests/ForceField/MMFF/AbstractMmffAtomTypeValidationSuiteTest.cs +++ b/NCDKTests/ForceFields/AbstractMmffAtomTypeValidationSuiteTest.cs @@ -2,7 +2,7 @@ using NCDK.Silent; using static NCDK.BondOrder; -namespace NCDK.ForceField.MMFF +namespace NCDK.ForceFields { /// /// This test class is generated from MMFF94hypervalent.mol2 and MMFF94opti.log available at diff --git a/NCDKTests/ForceField/MMFF/MmffAromaticTypeMappingTest.cs b/NCDKTests/ForceFields/MmffAromaticTypeMappingTest.cs similarity index 95% rename from NCDKTests/ForceField/MMFF/MmffAromaticTypeMappingTest.cs rename to NCDKTests/ForceFields/MmffAromaticTypeMappingTest.cs index 365e3a6c..cd6b4ca4 100644 --- a/NCDKTests/ForceField/MMFF/MmffAromaticTypeMappingTest.cs +++ b/NCDKTests/ForceFields/MmffAromaticTypeMappingTest.cs @@ -28,7 +28,7 @@ using NCDK.Common.Collections; using System.Collections.Generic; -namespace NCDK.ForceField.MMFF +namespace NCDK.ForceFields { [TestClass()] public class MmffAromaticTypeMappingTest @@ -265,28 +265,28 @@ public void UpdateCStarToCB() [TestMethod()] public void ImidazoleCarbonTypesAreNeitherAlphaOrBeta() { - IDictionary map = new Dictionary() { { "CB", "C5A" } }; + var map = new Dictionary() { { "CB", "C5A" } }; Assert.AreEqual("C5", MmffAromaticTypeMapping.GetAromaticType(map, 'A', "CB", true, false)); } [TestMethod()] public void ImidazoleNitrogenTypesAreNeitherAlphaOrBeta() { - IDictionary map = new Dictionary() { { "N=C", "N5A" } }; + var map = new Dictionary() { { "N=C", "N5A" } }; Assert.AreEqual("N5", MmffAromaticTypeMapping.GetAromaticType(map, 'A', "N=C", true, false)); } [TestMethod()] public void AnionCarbonTypesAreNeitherAlphaOrBeta() { - IDictionary map = new Dictionary() { { "CB", "C5A" } }; + var map = new Dictionary() { { "CB", "C5A" } }; Assert.AreEqual("C5", MmffAromaticTypeMapping.GetAromaticType(map, 'A', "CB", false, true)); } [TestMethod()] public void AnionNitrogensAreAlwaysN5M() { - IDictionary map = new Dictionary() { { "N=C", "N5A" } }; + var map = new Dictionary() { { "N=C", "N5A" } }; Assert.AreEqual("N5M", MmffAromaticTypeMapping.GetAromaticType(map, 'A', "N=C", false, true)); } @@ -294,7 +294,7 @@ public void AnionNitrogensAreAlwaysN5M() [TestMethod()] public void UseMappingWhenNeitherFlagIsRaised() { - IDictionary map = new Dictionary() { { "N=C", "N5A" } }; + var map = new Dictionary() { { "N=C", "N5A" } }; Assert.AreEqual("N5A", MmffAromaticTypeMapping.GetAromaticType(map, 'A', "N=C", false, false)); } diff --git a/NCDKTests/ForceField/MMFF/MmffAtomTypeMatcherTest.cs b/NCDKTests/ForceFields/MmffAtomTypeMatcherTest.cs similarity index 99% rename from NCDKTests/ForceField/MMFF/MmffAtomTypeMatcherTest.cs rename to NCDKTests/ForceFields/MmffAtomTypeMatcherTest.cs index 8e8f0156..f756ecd4 100644 --- a/NCDKTests/ForceField/MMFF/MmffAtomTypeMatcherTest.cs +++ b/NCDKTests/ForceFields/MmffAtomTypeMatcherTest.cs @@ -24,12 +24,12 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; using System.Text; -namespace NCDK.ForceField.MMFF +namespace NCDK.ForceFields { /// /// Unit tests for MMFF symbolic atom types. This class primarily tests preconditions and some diff --git a/NCDKTests/ForceField/MMFF/MmffAtomTypeValidationSuiteTest.cs b/NCDKTests/ForceFields/MmffAtomTypeValidationSuiteTest.cs similarity index 98% rename from NCDKTests/ForceField/MMFF/MmffAtomTypeValidationSuiteTest.cs rename to NCDKTests/ForceFields/MmffAtomTypeValidationSuiteTest.cs index da6dee70..8ccce8d7 100644 --- a/NCDKTests/ForceField/MMFF/MmffAtomTypeValidationSuiteTest.cs +++ b/NCDKTests/ForceFields/MmffAtomTypeValidationSuiteTest.cs @@ -28,7 +28,7 @@ using NCDK.Smiles; using System; -namespace NCDK.ForceField.MMFF +namespace NCDK.ForceFields { /// /// Ensure the atom types of the validation suite (http://server.ccl.net/cca/data/MMFF94/) are diff --git a/NCDKTests/ForceField/MMFF/MmffParamSetTest.cs b/NCDKTests/ForceFields/MmffParamSetTest.cs similarity index 98% rename from NCDKTests/ForceField/MMFF/MmffParamSetTest.cs rename to NCDKTests/ForceFields/MmffParamSetTest.cs index 5cc86d62..df196ce1 100644 --- a/NCDKTests/ForceField/MMFF/MmffParamSetTest.cs +++ b/NCDKTests/ForceFields/MmffParamSetTest.cs @@ -23,7 +23,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.ForceField.MMFF +namespace NCDK.ForceFields { // @author John May [TestClass()] diff --git a/NCDKTests/ForceField/MMFF/MmffTest.cs b/NCDKTests/ForceFields/MmffTest.cs similarity index 99% rename from NCDKTests/ForceField/MMFF/MmffTest.cs rename to NCDKTests/ForceFields/MmffTest.cs index 1be82992..310f3b05 100644 --- a/NCDKTests/ForceField/MMFF/MmffTest.cs +++ b/NCDKTests/ForceFields/MmffTest.cs @@ -26,7 +26,7 @@ using NCDK.Smiles; using NCDK.Tools.Manipulator; -namespace NCDK.ForceField.MMFF +namespace NCDK.ForceFields { // @author John May [TestClass()] diff --git a/NCDKTests/Formula/AdductFormulaTest.cs b/NCDKTests/Formula/AdductFormulaTest.cs index aec3e13b..11406972 100644 --- a/NCDKTests/Formula/AdductFormulaTest.cs +++ b/NCDKTests/Formula/AdductFormulaTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Formula { @@ -30,7 +30,7 @@ namespace NCDK.Formula [TestClass()] public class AdductFormulaTest : AbstractAdductFormulaTest { - protected override IChemObjectBuilder Builder => Default.ChemObjectBuilder.Instance; + protected override IChemObjectBuilder Builder => ChemObjectBuilder.Instance; [TestMethod()] public void TestAdductFormula() diff --git a/NCDKTests/Formula/IsotopePatternGeneratorTest.cs b/NCDKTests/Formula/IsotopePatternGeneratorTest.cs index 5e67bda5..9ee9dba6 100644 --- a/NCDKTests/Formula/IsotopePatternGeneratorTest.cs +++ b/NCDKTests/Formula/IsotopePatternGeneratorTest.cs @@ -45,14 +45,14 @@ public void TestIsotopePatternGenerator() } [TestMethod()] - public void TestIsotopePatternGenerator_Double() + public void TestIsotopePatternGeneratorDouble() { IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(); Assert.IsNotNull(isotopeGe); } [TestMethod()] - public void TestGetIsotopes_IMolecularFormula() + public void TestGetIsotopesIMolecularFormula() { IMolecularFormula molFor = MolecularFormulaManipulator.GetMajorIsotopeMolecularFormula("C41H79N8O3P1", builder); IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(.1); @@ -61,7 +61,7 @@ public void TestGetIsotopes_IMolecularFormula() } [TestMethod()] - public void TestGetIsotopes_IMolecularFormula_withoutONE() + public void TestGetIsotopesIMolecularFormulaWithoutONE() { IMolecularFormula molFor = MolecularFormulaManipulator.GetMajorIsotopeMolecularFormula("C41H79N8O3P", builder); IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(.01); @@ -75,15 +75,14 @@ public void TestGetIsotopes_IMolecularFormula_withoutONE() [TestMethod()] public void TestGetIsotopes1() { - IMolecularFormula molFor = new MolecularFormula(); + var molFor = new MolecularFormula(); molFor.Add(builder.NewIsotope("Br")); molFor.Add(builder.NewIsotope("Br")); - IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(.1); - IsotopePattern isoPattern = isotopeGe.GetIsotopes(molFor); + var isotopeGe = new IsotopePatternGenerator(0.1); + var isoPattern = isotopeGe.GetIsotopes(molFor); Assert.AreEqual(3, isoPattern.Isotopes.Count); - } /// @@ -121,17 +120,17 @@ public void TestCalculateIsotopesAllBromine() public void TestCalculateIsotopesIodemethylidyne() { // RESULTS ACCORDING PAGE: http://www2.sisweb.com/mstools/isotope.htm - double[] massResults = { 138.904480, 139.907839 }; - double[] abundResults = { 1.00, .011 }; + var massResults = new[] { 138.904480, 139.907839 }; + var abundResults = new[] { 1.00, .011 }; - IMolecularFormula molFor = new MolecularFormula(); + var molFor = new MolecularFormula(); molFor.Add(builder.NewIsotope("C")); molFor.Add(builder.NewIsotope("I")); - Assert.AreEqual(2, molFor.Count); + Assert.AreEqual(2, molFor.IsotopesCount); - IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(.01); - IsotopePattern isoPattern = isotopeGe.GetIsotopes(molFor); + var isotopeGe = new IsotopePatternGenerator(.01); + var isoPattern = isotopeGe.GetIsotopes(molFor); Assert.AreEqual(2, isoPattern.Isotopes.Count); @@ -258,7 +257,7 @@ public void TestGeneratorSavesState() } [TestMethod()] - public void TestGetIsotopes_IMolecularFormula_Charged() + public void TestGetIsotopesIMolecularFormulaCharged() { IsotopePatternGenerator isogen = new IsotopePatternGenerator(.1); @@ -277,7 +276,7 @@ public void TestGetIsotopes_IMolecularFormula_Charged() } [TestMethod()] - public void TestGetIsotopes_IMolecularFormula_deprotonate() + public void TestGetIsotopesIMolecularFormulaDeprotonate() { IsotopePatternGenerator isogen = new IsotopePatternGenerator(.1); diff --git a/NCDKTests/Formula/IsotopePatternManipulatorTest.cs b/NCDKTests/Formula/IsotopePatternManipulatorTest.cs index 12d8c656..ab564619 100644 --- a/NCDKTests/Formula/IsotopePatternManipulatorTest.cs +++ b/NCDKTests/Formula/IsotopePatternManipulatorTest.cs @@ -14,24 +14,27 @@ public IsotopePatternManipulatorTest() { } [TestMethod()] - public void TestNormalize_IsotopePattern() + public void TestNormalizeIsotopePattern() { - IsotopePattern spExp = new IsotopePattern(); - spExp.SetMonoIsotope(new IsotopeContainer(156.07770, 2)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.0006)); - spExp.Isotopes.Add(new IsotopeContainer(157.07503, 0.0002)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.004)); + var spExp = new IsotopePattern(new[] + { + new IsotopeContainer(156.07770, 2), + new IsotopeContainer(157.08059, 0.0006), + new IsotopeContainer(157.07503, 0.0002), + new IsotopeContainer(158.08135, 0.004), + }); + spExp.MonoIsotope = spExp.Isotopes[0]; spExp.Charge = 1; - IsotopePattern isoNorma = IsotopePatternManipulator.Normalize(spExp); + var isoNorma = IsotopePatternManipulator.Normalize(spExp); var listISO = isoNorma.Isotopes; - Assert.AreEqual(1, isoNorma.GetMonoIsotope().Intensity, 0.00001); + Assert.AreEqual(1, isoNorma.MonoIsotope.Intensity, 0.00001); Assert.AreEqual(1, listISO[0].Intensity, 0.00001); Assert.AreEqual(0.0003, listISO[1].Intensity, 0.00001); Assert.AreEqual(0.0001, listISO[2].Intensity, 0.00001); Assert.AreEqual(0.002, listISO[3].Intensity, 0.00001); - Assert.AreEqual(156.07770, isoNorma.GetMonoIsotope().Mass, 0.00001); + Assert.AreEqual(156.07770, isoNorma.MonoIsotope.Mass, 0.00001); Assert.AreEqual(156.07770, listISO[0].Mass, 0.00001); Assert.AreEqual(157.08059, listISO[1].Mass, 0.00001); Assert.AreEqual(157.07503, listISO[2].Mass, 0.00001); @@ -41,24 +44,27 @@ public void TestNormalize_IsotopePattern() } [TestMethod()] - public void TestSortByIntensity_IsotopePattern() + public void TestSortByIntensityIsotopePattern() { - IsotopePattern spExp = new IsotopePattern(); - spExp.SetMonoIsotope(new IsotopeContainer(157.07503, 0.0001)); - spExp.Isotopes.Add(new IsotopeContainer(156.07770, 1)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.0003)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.002)); + var spExp = new IsotopePattern(new[] + { + new IsotopeContainer(157.07503, 0.0001), + new IsotopeContainer(156.07770, 1), + new IsotopeContainer(157.08059, 0.0003), + new IsotopeContainer(158.08135, 0.002), + }); + spExp.MonoIsotope = spExp.Isotopes[0]; spExp.Charge = 1; - IsotopePattern isoNorma = IsotopePatternManipulator.SortByIntensity(spExp); + var isoNorma = IsotopePatternManipulator.SortByIntensity(spExp); var listISO = isoNorma.Isotopes; - Assert.AreEqual(156.07770, isoNorma.GetMonoIsotope().Mass, 0.00001); + Assert.AreEqual(156.07770, isoNorma.MonoIsotope.Mass, 0.00001); Assert.AreEqual(156.07770, listISO[0].Mass, 0.00001); Assert.AreEqual(158.08135, listISO[1].Mass, 0.00001); Assert.AreEqual(157.08059, listISO[2].Mass, 0.00001); Assert.AreEqual(157.07503, listISO[3].Mass, 0.00001); - Assert.AreEqual(1, isoNorma.GetMonoIsotope().Intensity, 0.00001); + Assert.AreEqual(1, isoNorma.MonoIsotope.Intensity, 0.00001); Assert.AreEqual(1, listISO[0].Intensity, 0.00001); Assert.AreEqual(0.002, listISO[1].Intensity, 0.00001); Assert.AreEqual(0.0003, listISO[2].Intensity, 0.001); @@ -68,24 +74,27 @@ public void TestSortByIntensity_IsotopePattern() } [TestMethod()] - public void TestSortAndNormalizedByIntensity_IsotopePattern() + public void TestSortAndNormalizedByIntensityIsotopePattern() { - IsotopePattern spExp = new IsotopePattern(); - spExp.Isotopes.Add(new IsotopeContainer(157.07503, 0.0002)); - spExp.SetMonoIsotope(new IsotopeContainer(156.07770, 2)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.004)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.0006)); + var spExp = new IsotopePattern(new[] + { + new IsotopeContainer(157.07503, 0.0002), + new IsotopeContainer(156.07770, 2), + new IsotopeContainer(158.08135, 0.004), + new IsotopeContainer(157.08059, 0.0006), + }); + spExp.MonoIsotope = spExp.Isotopes[1]; spExp.Charge = 1; - IsotopePattern isoNorma = IsotopePatternManipulator.SortAndNormalizedByIntensity(spExp); + var isoNorma = IsotopePatternManipulator.SortAndNormalizedByIntensity(spExp); var listISO = isoNorma.Isotopes; - Assert.AreEqual(156.07770, isoNorma.GetMonoIsotope().Mass, 0.00001); + Assert.AreEqual(156.07770, isoNorma.MonoIsotope.Mass, 0.00001); Assert.AreEqual(156.07770, listISO[0].Mass, 0.00001); Assert.AreEqual(158.08135, listISO[1].Mass, 0.00001); Assert.AreEqual(157.08059, listISO[2].Mass, 0.00001); Assert.AreEqual(157.07503, listISO[3].Mass, 0.00001); - Assert.AreEqual(1, isoNorma.GetMonoIsotope().Intensity, 0.00001); + Assert.AreEqual(1, isoNorma.MonoIsotope.Intensity, 0.00001); Assert.AreEqual(1, listISO[0].Intensity, 0.00001); Assert.AreEqual(0.002, listISO[1].Intensity, 0.00001); Assert.AreEqual(0.0003, listISO[2].Intensity, 0.00001); @@ -95,24 +104,27 @@ public void TestSortAndNormalizedByIntensity_IsotopePattern() } [TestMethod()] - public void TestSortByMass_IsotopePattern() + public void TestSortByMassIsotopePattern() { - IsotopePattern spExp = new IsotopePattern(); - spExp.Isotopes.Add(new IsotopeContainer(157.07503, 0.0002)); - spExp.SetMonoIsotope(new IsotopeContainer(156.07770, 2)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.004)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.0006)); + var spExp = new IsotopePattern(new[] + { + new IsotopeContainer(157.07503, 0.0002), + new IsotopeContainer(156.07770, 2), + new IsotopeContainer(158.08135, 0.004), + new IsotopeContainer(157.08059, 0.0006), + }); + spExp.MonoIsotope = spExp.Isotopes[1]; spExp.Charge = 1; - IsotopePattern isoNorma = IsotopePatternManipulator.SortByMass(spExp); + var isoNorma = IsotopePatternManipulator.SortByMass(spExp); var listISO = isoNorma.Isotopes; - Assert.AreEqual(156.07770, isoNorma.GetMonoIsotope().Mass, 0.001); + Assert.AreEqual(156.07770, isoNorma.MonoIsotope.Mass, 0.001); Assert.AreEqual(156.07770, listISO[0].Mass, 0.00001); Assert.AreEqual(157.07503, listISO[1].Mass, 0.00001); Assert.AreEqual(157.08059, listISO[2].Mass, 0.00001); Assert.AreEqual(158.08135, listISO[3].Mass, 0.00001); - Assert.AreEqual(2, isoNorma.GetMonoIsotope().Intensity, 0.001); + Assert.AreEqual(2, isoNorma.MonoIsotope.Intensity, 0.001); Assert.AreEqual(2, listISO[0].Intensity, 0.001); Assert.AreEqual(0.0002, listISO[1].Intensity, 0.00001); Assert.AreEqual(0.0006, listISO[2].Intensity, 0.00001); diff --git a/NCDKTests/Formula/IsotopePatternSimilarityTest.cs b/NCDKTests/Formula/IsotopePatternSimilarityTest.cs index e0c7b212..46da97a6 100644 --- a/NCDKTests/Formula/IsotopePatternSimilarityTest.cs +++ b/NCDKTests/Formula/IsotopePatternSimilarityTest.cs @@ -24,7 +24,7 @@ public void TestIsotopePatternSimilarity() } [TestMethod()] - public void TestSeTolerance_Double() + public void TestSeToleranceDouble() { IsotopePatternSimilarity is_ = new IsotopePatternSimilarity { Tolerance = 0.001 }; Assert.IsNotNull(is_); @@ -41,21 +41,24 @@ public void TestGetTolerance() /// Histidine example /// [TestMethod()] - public void TestCompare_IsotopePattern_IsotopePattern() + public void TestCompareIsotopePatternIsotopePattern() { var is_ = new IsotopePatternSimilarity(); - IsotopePattern spExp = new IsotopePattern(); - spExp.SetMonoIsotope(new IsotopeContainer(156.07770, 1)); - spExp.Isotopes.Add(new IsotopeContainer(157.07503, 0.0004)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.0003)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.002)); - - IMolecularFormula formula = MolecularFormulaManipulator.GetMajorIsotopeMolecularFormula("C6H10N3O2", builder); - IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(0.1); - IsotopePattern patternIsoPredicted = isotopeGe.GetIsotopes(formula); - IsotopePattern patternIsoNormalize = IsotopePatternManipulator.Normalize(patternIsoPredicted); - double score = is_.Compare(spExp, patternIsoNormalize); + IsotopePattern spExp = new IsotopePattern(new[] + { + new IsotopeContainer(156.07770, 1), + new IsotopeContainer(157.07503, 0.0004), + new IsotopeContainer(157.08059, 0.0003), + new IsotopeContainer(158.08135, 0.002), + }); + spExp.MonoIsotope = spExp.Isotopes[0]; + + var formula = MolecularFormulaManipulator.GetMajorIsotopeMolecularFormula("C6H10N3O2", builder); + var isotopeGe = new IsotopePatternGenerator(0.1); + var patternIsoPredicted = isotopeGe.GetIsotopes(formula); + var patternIsoNormalize = IsotopePatternManipulator.Normalize(patternIsoPredicted); + var score = is_.Compare(spExp, patternIsoNormalize); Assert.AreNotSame(0.0, score); } @@ -67,11 +70,15 @@ public void TestSelectingMF() { var is_ = new IsotopePatternSimilarity(); - IsotopePattern spExp = new IsotopePattern { Charge = 1 }; - spExp.SetMonoIsotope(new IsotopeContainer(156.07770, 1)); - spExp.Isotopes.Add(new IsotopeContainer(157.07503, 0.0101)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.074)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.0024)); + IsotopePattern spExp = new IsotopePattern(new[] + { + new IsotopeContainer(156.07770, 1), + new IsotopeContainer(157.07503, 0.0101), + new IsotopeContainer(157.08059, 0.074), + new IsotopeContainer(158.08135, 0.0024), + }); + spExp.MonoIsotope = spExp.Isotopes[0]; + spExp.Charge = 1; double score = 0; string mfString = ""; @@ -100,20 +107,20 @@ public void TestSelectingMF() [TestMethod()] public void TestExperiment() { - IsotopePattern spExp = new IsotopePattern(); - spExp.SetMonoIsotope(new IsotopeContainer(762.6006, 124118304)); - spExp.Isotopes.Add(new IsotopeContainer(763.6033, 57558840)); - spExp.Isotopes.Add(new IsotopeContainer(764.6064, 15432262)); + var spExp = new IsotopePattern(new[] + { + new IsotopeContainer(762.6006, 124118304), + new IsotopeContainer(763.6033, 57558840), + new IsotopeContainer(764.6064, 15432262), + }); + spExp.MonoIsotope = spExp.Isotopes[0]; spExp.Charge = 1.0; - IMolecularFormula formula = MolecularFormulaManipulator.GetMajorIsotopeMolecularFormula("C42H85NO8P", - Silent.ChemObjectBuilder.Instance); - - IsotopePatternGenerator isotopeGe = new IsotopePatternGenerator(0.01); - IsotopePattern patternIsoPredicted = isotopeGe.GetIsotopes(formula); - + var formula = MolecularFormulaManipulator.GetMajorIsotopeMolecularFormula("C42H85NO8P", Silent.ChemObjectBuilder.Instance); + var isotopeGe = new IsotopePatternGenerator(0.01); + var patternIsoPredicted = isotopeGe.GetIsotopes(formula); var is_ = new IsotopePatternSimilarity(); - double score = is_.Compare(spExp, patternIsoPredicted); + var score = is_.Compare(spExp, patternIsoPredicted); Assert.AreEqual(0.97, score, .01); } diff --git a/NCDKTests/Formula/IsotopePatternTest.cs b/NCDKTests/Formula/IsotopePatternTest.cs index 66968096..ad37f3b4 100644 --- a/NCDKTests/Formula/IsotopePatternTest.cs +++ b/NCDKTests/Formula/IsotopePatternTest.cs @@ -16,55 +16,39 @@ public IsotopePatternTest() [TestMethod()] public void TestIsotopePattern() { - IsotopePattern isoP = new IsotopePattern(); + var isoP = new IsotopePattern(); Assert.IsNotNull(isoP); } [TestMethod()] - public void TestSetMonoIsotope_IsotopeContainer() + public void TestSetMonoIsotopeIsotopeContainer() { - IsotopePattern isoP = new IsotopePattern(); - isoP.SetMonoIsotope(new IsotopeContainer()); + var isoP = new IsotopePattern { MonoIsotope = new IsotopeContainer() }; Assert.IsNotNull(isoP); } [TestMethod()] - public void TestAddIsotope_IsotopeContainer() + public void TestAddIsotopeIsotopeContainer() { - IsotopePattern isoP = new IsotopePattern(); - isoP.Isotopes.Add(new IsotopeContainer()); + var isoP = new IsotopePattern(new[] { new IsotopeContainer() }); Assert.IsNotNull(isoP); } [TestMethod()] public void TestGetMonoIsotope() { - IsotopePattern isoP = new IsotopePattern(); - IsotopeContainer isoC = new IsotopeContainer(); - isoP.SetMonoIsotope(isoC); - Assert.AreEqual(isoC, isoP.GetMonoIsotope()); + var isoP = new IsotopePattern(); + var isoC = new IsotopeContainer(); + isoP.MonoIsotope = isoC; + Assert.AreEqual(isoC, isoP.MonoIsotope); } [TestMethod()] public void TestGetIsotopes() { - IsotopePattern isoP = new IsotopePattern(); - IsotopeContainer iso1 = new IsotopeContainer(); - isoP.SetMonoIsotope(iso1); - IsotopeContainer iso2 = new IsotopeContainer(); - isoP.Isotopes.Add(iso2); - Assert.AreEqual(iso1, isoP.Isotopes[0]); - Assert.AreEqual(iso2, isoP.Isotopes[1]); - } - - [TestMethod()] - public void TestGetIsotope_int() - { - IsotopePattern isoP = new IsotopePattern(); - IsotopeContainer iso1 = new IsotopeContainer(); - isoP.SetMonoIsotope(iso1); - IsotopeContainer iso2 = new IsotopeContainer(); - isoP.Isotopes.Add(iso2); + var iso1 = new IsotopeContainer(); + var iso2 = new IsotopeContainer(); + var isoP = new IsotopePattern(new[] { iso1, iso2 }) { MonoIsotope = iso1 }; Assert.AreEqual(iso1, isoP.Isotopes[0]); Assert.AreEqual(iso2, isoP.Isotopes[1]); } @@ -72,46 +56,47 @@ public void TestGetIsotope_int() [TestMethod()] public void TestGetNumberOfIsotopes() { - IsotopePattern isoP = new IsotopePattern(); - IsotopeContainer iso1 = new IsotopeContainer(); - isoP.SetMonoIsotope(iso1); - IsotopeContainer iso2 = new IsotopeContainer(); - isoP.Isotopes.Add(iso2); + var iso1 = new IsotopeContainer(); + var iso2 = new IsotopeContainer(); + var isoP = new IsotopePattern(new[] { iso1, iso2 }) { MonoIsotope = iso1 }; Assert.AreEqual(2, isoP.Isotopes.Count); } [TestMethod()] - public void TestSetCharge_Double() + public void TestSetChargeDouble() { - IsotopePattern isoP = new IsotopePattern { Charge = 1.0 }; + var isoP = new IsotopePattern { Charge = 1.0 }; Assert.AreEqual(1.0, isoP.Charge, 0.000001); } [TestMethod()] public void TestGetCharge() { - IsotopePattern isoP = new IsotopePattern(); + var isoP = new IsotopePattern(); Assert.AreEqual(0, isoP.Charge, 0.000001); } [TestMethod()] public void TestClone() { - IsotopePattern spExp = new IsotopePattern(); - spExp.SetMonoIsotope(new IsotopeContainer(156.07770, 1)); - spExp.Isotopes.Add(new IsotopeContainer(157.07503, 0.0004)); - spExp.Isotopes.Add(new IsotopeContainer(157.08059, 0.0003)); - spExp.Isotopes.Add(new IsotopeContainer(158.08135, 0.002)); + var spExp = new IsotopePattern(new[] + { + new IsotopeContainer(156.07770, 1), + new IsotopeContainer(157.07503, 0.0004), + new IsotopeContainer(157.08059, 0.0003), + new IsotopeContainer(158.08135, 0.002), + }); + spExp.MonoIsotope = spExp.Isotopes[0]; spExp.Charge = 1; - IsotopePattern clone = (IsotopePattern)spExp.Clone(); - Assert.AreEqual(156.07770, clone.GetMonoIsotope().Mass, 0.001); + var clone = (IsotopePattern)spExp.Clone(); + Assert.AreEqual(156.07770, clone.MonoIsotope.Mass, 0.001); Assert.AreEqual(156.07770, clone.Isotopes[0].Mass, 0.001); Assert.AreEqual(157.07503, clone.Isotopes[1].Mass, 0.001); Assert.AreEqual(157.08059, clone.Isotopes[2].Mass, 0.001); Assert.AreEqual(158.08135, clone.Isotopes[3].Mass, 0.001); - Assert.AreEqual(1, clone.GetMonoIsotope().Intensity, 0.001); + Assert.AreEqual(1, clone.MonoIsotope.Intensity, 0.001); Assert.AreEqual(1, clone.Isotopes[0].Intensity, 0.001); Assert.AreEqual(0.0004, clone.Isotopes[1].Intensity, 0.001); Assert.AreEqual(0.0003, clone.Isotopes[2].Intensity, 0.001); diff --git a/NCDKTests/Formula/MolecularFormulaCheckerTest.cs b/NCDKTests/Formula/MolecularFormulaCheckerTest.cs index 4d080d2d..6a0afed4 100644 --- a/NCDKTests/Formula/MolecularFormulaCheckerTest.cs +++ b/NCDKTests/Formula/MolecularFormulaCheckerTest.cs @@ -41,7 +41,7 @@ public MolecularFormulaCheckerTest() { try { - ifac = Isotopes.Instance; + ifac = BODRIsotopeFactory.Instance; } catch (IOException e) { diff --git a/NCDKTests/Formula/MolecularFormulaGeneratorTest.cs b/NCDKTests/Formula/MolecularFormulaGeneratorTest.cs index c5710202..eaf047d8 100644 --- a/NCDKTests/Formula/MolecularFormulaGeneratorTest.cs +++ b/NCDKTests/Formula/MolecularFormulaGeneratorTest.cs @@ -41,7 +41,7 @@ public class MolecularFormulaGeneratorTest : CDKTestCase [TestMethod()] public void TestGetNextFormula() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -67,7 +67,7 @@ public void TestGetNextFormula() [TestMethod()] public void TestGetAllFormulas() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -95,7 +95,7 @@ public void TestGetAllFormulas() [TestMethod()] public void TestGetFinishedPercentage() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -140,7 +140,7 @@ public void TestGetFinishedPercentage() [Timeout(1000)] public void TestCancel() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -194,7 +194,7 @@ public void TestEmptyMFRange() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestNegativeMass() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); MolecularFormulaRange mfRange = new MolecularFormulaRange(); @@ -208,7 +208,7 @@ public void TestNegativeMass() [TestMethod()] public void TestMinCounts() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -244,7 +244,7 @@ public void TestMinCounts() [TestMethod()] public void TestMaxCounts() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -280,7 +280,7 @@ public void TestMaxCounts() [TestMethod()] public void TestSingleCarbon() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); MolecularFormulaRange mfRange = new MolecularFormulaRange(); @@ -303,7 +303,7 @@ public void TestSingleCarbon() [TestMethod()] public void TestCarbons() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); MolecularFormulaRange mfRange = new MolecularFormulaRange(); @@ -326,7 +326,7 @@ public void TestCarbons() [TestMethod()] public void TestWater() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -369,7 +369,7 @@ public void TestWater() [TestMethod()] public void TestUseFullEnumerationWhenNoHydrogen() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope n = ifac.GetMajorIsotope("N"); IIsotope o = ifac.GetMajorIsotope("O"); @@ -390,7 +390,7 @@ public void TestUseFullEnumerationWhenNoHydrogen() [TestMethod()] public void TestUseFullEnumerationWhenSuperLargeMassDeviation() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -413,7 +413,7 @@ public void TestUseFullEnumerationWhenSuperLargeMassDeviation() [TestMethod()] public void TestUseFullEnumerationWhenExceedIntegerSpace() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -435,7 +435,7 @@ public void TestUseFullEnumerationWhenExceedIntegerSpace() [TestMethod()] public void TestUseRoundRobinWheneverPossible() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -457,7 +457,7 @@ public void TestUseRoundRobinWheneverPossible() [TestMethod()] public void TestSmallMass() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -486,7 +486,7 @@ public void TestSmallMass() [TestMethod()] public void TestMiddleMass() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -515,7 +515,7 @@ public void TestMiddleMass() [TestMethod()] public void TestHighMass() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -547,7 +547,7 @@ public void TestHighMass() [TestMethod()] public void TestFormulaFoundInRange() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -585,7 +585,7 @@ public void TestFormulaFoundInRange() [TestMethod()] public void TestFormulaFoundInRange2() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -624,7 +624,7 @@ public void TestFormulaFoundInRange2() [TestMethod()] public void TestCompoundWith7Elements() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -659,7 +659,7 @@ public void TestCompoundWith7Elements() [TestMethod()] public void TestDifferentIsotopes() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); var carbons = ifac.GetIsotopes("C"); IIsotope c13 = carbons.ElementAt(5); // 13 @@ -684,7 +684,7 @@ public void TestDifferentIsotopes() trueFormula.Add(c13, 1); trueFormula.Add(h, 5); - Assert.AreEqual(trueFormula.Count, mfSet[0].Count); + Assert.AreEqual(trueFormula.IsotopesCount, mfSet[0].IsotopesCount); Assert.AreEqual(trueFormula.GetCount(c), mfSet[0].GetCount(c)); Assert.AreEqual(trueFormula.GetCount(c13), mfSet[0].GetCount(c13)); } @@ -696,7 +696,7 @@ public void TestDifferentIsotopes() [TestMethod()] public void TestFixedElementCounts() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -726,7 +726,7 @@ public void TestFixedElementCounts() [TestMethod()] public void TestMassRangeTooHigh() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); @@ -755,7 +755,7 @@ public void TestMassRangeTooHigh() [TestMethod()] public void TestMassRangeTooLow() { - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; IIsotope c = ifac.GetMajorIsotope("C"); IIsotope h = ifac.GetMajorIsotope("H"); IIsotope n = ifac.GetMajorIsotope("N"); diff --git a/NCDKTests/Formula/MolecularFormulaSetTest.cs b/NCDKTests/Formula/MolecularFormulaSetTest.cs index d4c5ef0e..9300d688 100644 --- a/NCDKTests/Formula/MolecularFormulaSetTest.cs +++ b/NCDKTests/Formula/MolecularFormulaSetTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; namespace NCDK.Formula { @@ -29,7 +30,7 @@ namespace NCDK.Formula [TestClass()] public class MolecularFormulaSetTest : AbstractMolecularFormulaSetTest { - protected override IChemObjectBuilder Builder => Default.ChemObjectBuilder.Instance; + protected override IChemObjectBuilder Builder => ChemObjectBuilder.Instance; [TestMethod()] public void TestMolecularFormulaSet() { diff --git a/NCDKTests/Formula/MolecularFormulaTest.cs b/NCDKTests/Formula/MolecularFormulaTest.cs index 655d6bb7..8dfa3396 100644 --- a/NCDKTests/Formula/MolecularFormulaTest.cs +++ b/NCDKTests/Formula/MolecularFormulaTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; namespace NCDK.Formula { @@ -30,18 +31,19 @@ namespace NCDK.Formula public class MolecularFormulaTest : AbstractMolecularFormulaTest { protected override IChemObjectBuilder Builder - => Default.ChemObjectBuilder.Instance; + => ChemObjectBuilder.Instance; [TestMethod()] - public void TestMolecularFormula() { + public void TestMolecularFormula() + { IMolecularFormula mf = Builder.NewMolecularFormula(); Assert.IsNotNull(mf); } [TestMethod()] - public void TestIsTheSame_IIsotope_IIsotope() { - MolecularFormula mf = new MolecularFormula(); + public void TestIsTheSame_IIsotope_IIsotope() + { IIsotope carb = Builder.NewIsotope("C"); IIsotope anotherCarb = Builder.NewIsotope("C"); IIsotope h = Builder.NewIsotope("H"); @@ -54,9 +56,9 @@ public void TestIsTheSame_IIsotope_IIsotope() { anotherCarb.NaturalAbundance = 34.0; h.NaturalAbundance = 99.0; - Assert.IsTrue(mf.IsTheSame(carb, carb)); - Assert.IsTrue(mf.IsTheSame(carb, anotherCarb)); - Assert.IsFalse(mf.IsTheSame(carb, h)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, carb)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, anotherCarb)); + Assert.IsFalse(MolecularFormula.IsTheSame(carb, h)); } } } diff --git a/NCDKTests/Formula/Rules/ChargeRuleTest.cs b/NCDKTests/Formula/Rules/ChargeRuleTest.cs index 5cc7ce4a..6dca5523 100644 --- a/NCDKTests/Formula/Rules/ChargeRuleTest.cs +++ b/NCDKTests/Formula/Rules/ChargeRuleTest.cs @@ -17,8 +17,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using System; using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; +using System; namespace NCDK.Formula.Rules { @@ -26,7 +27,7 @@ namespace NCDK.Formula.Rules [TestClass()] public class ChargeRuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; protected override Type RuleClass => typeof(ChargeRule); [TestMethod()] @@ -40,8 +41,8 @@ public void TestChargeRule() public void TestDefault() { IRule rule = new ChargeRule(); - object[] objects = rule.Parameters; - Assert.AreEqual(1, objects.Length); + var objects = rule.Parameters; + Assert.AreEqual(1, objects.Count); double charge = (double)objects[0]; Assert.AreEqual(0.0, charge, 0.00001); @@ -52,8 +53,8 @@ public void TestSetParameters() { IRule rule = new ChargeRule { Parameters = new object[] { -1.0 } }; - object[] objects = rule.Parameters; - Assert.AreEqual(1, objects.Length); + var objects = rule.Parameters; + Assert.AreEqual(1, objects.Count); double charge = (double)objects[0]; Assert.AreEqual(-1.0, charge, 0.00001); @@ -73,7 +74,7 @@ public void TestDefaultValidFalse() } [TestMethod()] - public void TestDefaultValidFalse_SetParam() + public void TestDefaultValidFalseSetParam() { IRule rule = new ChargeRule(); IMolecularFormula formula = new MolecularFormula(); diff --git a/NCDKTests/Formula/Rules/ElementRuleTest.cs b/NCDKTests/Formula/Rules/ElementRuleTest.cs index a1266f0c..1cd4843f 100644 --- a/NCDKTests/Formula/Rules/ElementRuleTest.cs +++ b/NCDKTests/Formula/Rules/ElementRuleTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Formula.Rules @@ -27,7 +27,7 @@ namespace NCDK.Formula.Rules [TestClass()] public class ElementRuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; protected override Type RuleClass => typeof(ElementRule); [TestMethod()] @@ -44,7 +44,7 @@ public void TestDefault() var objects = rule.Parameters; // MolecularFormulaRange needs a build to create isotopes - Assert.AreEqual(1, objects.Length); + Assert.AreEqual(1, objects.Count); Assert.IsNull(objects[0]); // when we do a validation... @@ -52,7 +52,7 @@ public void TestDefault() // a default option is created objects = rule.Parameters; - Assert.AreEqual(1, objects.Length); + Assert.AreEqual(1, objects.Count); Assert.IsNotNull(objects[0]); MolecularFormulaRange mfRange = (MolecularFormulaRange)objects[0]; @@ -73,7 +73,7 @@ public void TestSetParameters() rule.Parameters = new object[] { mfRange }; var objects = rule.Parameters; - Assert.AreEqual(1, objects.Length); + Assert.AreEqual(1, objects.Count); MolecularFormulaRange mfRange2 = (MolecularFormulaRange)objects[0]; Assert.AreEqual(mfRange.Count, mfRange2.Count); @@ -94,7 +94,7 @@ public void TestDefaultValidFalse() } [TestMethod()] - public void TestDefaultValidFalse_SetParam() + public void TestDefaultValidFalseSetParam() { IRule rule = new ElementRule(); diff --git a/NCDKTests/Formula/Rules/FormulaRuleTest.cs b/NCDKTests/Formula/Rules/FormulaRuleTest.cs index dd1746e7..b760ab71 100644 --- a/NCDKTests/Formula/Rules/FormulaRuleTest.cs +++ b/NCDKTests/Formula/Rules/FormulaRuleTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Formula.Rules @@ -34,7 +34,7 @@ public abstract class FormulaRuleTest : CDKTestCase protected virtual IRule GetRule() { - object rule = (object)RuleClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + object rule = (object)RuleClass.GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); if (!(rule is IRule)) { throw new CDKException("The passed rule class must be a IRule"); diff --git a/NCDKTests/Formula/Rules/IsotopePatternRuleTest.cs b/NCDKTests/Formula/Rules/IsotopePatternRuleTest.cs index 920f3bf3..610f1ab5 100644 --- a/NCDKTests/Formula/Rules/IsotopePatternRuleTest.cs +++ b/NCDKTests/Formula/Rules/IsotopePatternRuleTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; +using NCDK.Silent; using System; using System.Collections.Generic; @@ -28,8 +29,8 @@ namespace NCDK.Formula.Rules [TestClass()] public class IsotopePatternRuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; - private static readonly IsotopeFactory ifac = Isotopes.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; + private static readonly IsotopeFactory ifac = BODRIsotopeFactory.Instance; protected override Type RuleClass => typeof(IsotopePatternRule); protected override IRule GetRule() @@ -77,11 +78,11 @@ public void TestSetParameters() var objects = rule.Parameters; Assert.IsNotNull(objects[0]); - Assert.AreEqual(2, objects.Length); + Assert.AreEqual(2, objects.Count); } [TestMethod()] - public void TestValid_Bromine() + public void TestValidBromine() { List spectrum = new List { diff --git a/NCDKTests/Formula/Rules/MMElementRuleTest.cs b/NCDKTests/Formula/Rules/MMElementRuleTest.cs index 2d4e4cde..b5fac97c 100644 --- a/NCDKTests/Formula/Rules/MMElementRuleTest.cs +++ b/NCDKTests/Formula/Rules/MMElementRuleTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System; namespace NCDK.Formula.Rules @@ -26,7 +27,7 @@ namespace NCDK.Formula.Rules [TestClass()] public class MMElementRuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; protected override Type RuleClass => typeof(MMElementRule); [TestMethod()] @@ -40,7 +41,7 @@ public void TestMMElementRule() public void TestDefault() { IRule rule = new MMElementRule(); - object[] objects = rule.Parameters; + var objects = rule.Parameters; Assert.AreSame(MMElementRule.Database.Wiley, objects[0]); Assert.AreSame(MMElementRule.RangeMass.Minus500, objects[1]); @@ -57,7 +58,7 @@ public void TestSetParameters() params_[1] = MMElementRule.RangeMass.Minus1000; rule.Parameters = params_; - object[] objects = rule.Parameters; + var objects = rule.Parameters; Assert.AreSame(MMElementRule.Database.DictionaryNaturalProductsOnline, objects[0]); Assert.AreSame(MMElementRule.RangeMass.Minus1000, objects[1]); diff --git a/NCDKTests/Formula/Rules/NitrogenRuleTest.cs b/NCDKTests/Formula/Rules/NitrogenRuleTest.cs index defe945e..3ad67d7e 100644 --- a/NCDKTests/Formula/Rules/NitrogenRuleTest.cs +++ b/NCDKTests/Formula/Rules/NitrogenRuleTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; @@ -27,7 +28,7 @@ namespace NCDK.Formula.Rules [TestClass()] public class NitrogenRuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; protected override Type RuleClass => typeof(NitrogenRule); [TestMethod()] diff --git a/NCDKTests/Formula/Rules/RDBERuleTest.cs b/NCDKTests/Formula/Rules/RDBERuleTest.cs index 8dd19001..db9512f8 100644 --- a/NCDKTests/Formula/Rules/RDBERuleTest.cs +++ b/NCDKTests/Formula/Rules/RDBERuleTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; @@ -27,7 +28,7 @@ namespace NCDK.Formula.Rules [TestClass()] public class RDBERuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; protected override Type RuleClass => typeof(RDBERule); [TestMethod()] @@ -42,7 +43,7 @@ public void TestDefault() { IRule rule = new RDBERule(); var objects = rule.Parameters; - Assert.AreEqual(2, objects.Length); + Assert.AreEqual(2, objects.Count); double min = (double)objects[0]; double max = (double)objects[1]; @@ -61,7 +62,7 @@ public void TestSetParameters() rule.Parameters = parameters; var objects = rule.Parameters; - Assert.AreEqual(2, objects.Length); + Assert.AreEqual(2, objects.Count); double min = (double)objects[0]; double max = (double)objects[1]; diff --git a/NCDKTests/Formula/Rules/ToleranceRangeRuleTest.cs b/NCDKTests/Formula/Rules/ToleranceRangeRuleTest.cs index 03a5bb2f..eee93a1f 100644 --- a/NCDKTests/Formula/Rules/ToleranceRangeRuleTest.cs +++ b/NCDKTests/Formula/Rules/ToleranceRangeRuleTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System; namespace NCDK.Formula.Rules @@ -26,7 +27,7 @@ namespace NCDK.Formula.Rules [TestClass()] public class ToleranceRangeRuleTest : FormulaRuleTest { - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; protected override Type RuleClass => typeof(ToleranceRangeRule); [TestMethod()] @@ -41,7 +42,7 @@ public void TestDefault() { IRule rule = new ToleranceRangeRule(); var objects = rule.Parameters; - Assert.AreEqual(2, objects.Length); + Assert.AreEqual(2, objects.Count); double mass = (double)objects[0]; Assert.AreEqual(0.0, mass, 0.00001); @@ -61,7 +62,7 @@ public void TestSetParameters() var objects = rule.Parameters; - Assert.AreEqual(2, objects.Length); + Assert.AreEqual(2, objects.Count); double mass = (double)objects[0]; Assert.AreEqual(133.0, mass, 0.00001); diff --git a/NCDKTests/Fragments/FragmentUtilsTest.cs b/NCDKTests/Fragments/FragmentUtilsTest.cs index 218ce1be..eb7ef8f3 100644 --- a/NCDKTests/Fragments/FragmentUtilsTest.cs +++ b/NCDKTests/Fragments/FragmentUtilsTest.cs @@ -20,6 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Graphs; +using NCDK.Silent; using NCDK.Smiles; using System.Collections.Generic; using System.Linq; @@ -37,7 +38,7 @@ public class FragmentUtilsTest : CDKTestCase static FragmentUtilsTest() { - smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + smilesParser = new SmilesParser(ChemObjectBuilder.Instance); } [TestMethod()] diff --git a/NCDKTests/Fragments/MurckoFragmenterTest.cs b/NCDKTests/Fragments/MurckoFragmenterTest.cs index 5cec5670..7b94dfcf 100644 --- a/NCDKTests/Fragments/MurckoFragmenterTest.cs +++ b/NCDKTests/Fragments/MurckoFragmenterTest.cs @@ -35,19 +35,13 @@ namespace NCDK.Fragments [TestClass()] public class MurckoFragmenterTest : CDKTestCase { - static MurckoFragmenter fragmenter; - static SmilesParser smilesParser; - - static MurckoFragmenterTest() - { - fragmenter = new MurckoFragmenter(); - smilesParser = new SmilesParser(Silent.ChemObjectBuilder.Instance); - } + static MurckoFragmenter fragmenter = new MurckoFragmenter(); + static SmilesParser smilesParser = new SmilesParser(Silent.ChemObjectBuilder.Instance); [TestMethod()] public void TestNoFramework() { - IAtomContainer mol = smilesParser.ParseSmiles("CCO[C@@H](C)C(=O)C(O)O"); + var mol = smilesParser.ParseSmiles("CCO[C@@H](C)C(=O)C(O)O"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); Assert.AreEqual(0, frameworks.Count()); @@ -56,7 +50,7 @@ public void TestNoFramework() [TestMethod()] public void TestOnlyRingSystem() { - IAtomContainer mol = smilesParser.ParseSmiles("c1ccccc1CCCCC"); + var mol = smilesParser.ParseSmiles("c1ccccc1CCCCC"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); Assert.AreEqual(0, frameworks.Count()); @@ -67,7 +61,7 @@ public void TestOnlyRingSystem() [TestMethod()] public void TestMF3() { - IAtomContainer mol = smilesParser.ParseSmiles("C(CC1=C2C=CC=CC2=CC2=C1C=CC=C2)C1CCCCC1"); + var mol = smilesParser.ParseSmiles("C(CC1=C2C=CC=CC2=CC2=C1C=CC=C2)C1CCCCC1"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); Assert.AreEqual(1, frameworks.Count()); @@ -76,7 +70,7 @@ public void TestMF3() [TestMethod()] public void TestMF3_Container() { - IAtomContainer mol = smilesParser.ParseSmiles("C(CC1=C2C=CC=CC2=CC2=C1C=CC=C2)C1CCCCC1"); + var mol = smilesParser.ParseSmiles("C(CC1=C2C=CC=CC2=CC2=C1C=CC=C2)C1CCCCC1"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworksAsContainers(); Assert.AreEqual(1, frameworks.Count()); @@ -85,8 +79,8 @@ public void TestMF3_Container() [TestMethod()] public void TestMF1() { - IAtomContainer mol = smilesParser.ParseSmiles("c1ccccc1PP(B)c1cccc(N(N)N)c1SC1CCC1"); - MurckoFragmenter fragmenter = new MurckoFragmenter(false, 2); + var mol = smilesParser.ParseSmiles("c1ccccc1PP(B)c1cccc(N(N)N)c1SC1CCC1"); + var fragmenter = new MurckoFragmenter(false, 2); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); @@ -99,8 +93,8 @@ public void TestMF1() [TestMethod()] public void TestMF1_Container() { - IAtomContainer mol = smilesParser.ParseSmiles("c1ccccc1PP(B)c1cccc(N(N)N)c1SC1CCC1"); - MurckoFragmenter fragmenter = new MurckoFragmenter(false, 2); + var mol = smilesParser.ParseSmiles("c1ccccc1PP(B)c1cccc(N(N)N)c1SC1CCC1"); + var fragmenter = new MurckoFragmenter(false, 2); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworksAsContainers(); @@ -113,7 +107,7 @@ public void TestMF1_Container() [TestMethod()] public void TestMF2() { - IAtomContainer mol = smilesParser.ParseSmiles("C1(c2ccccc2)(CC(CC1)CCc1ccccc1)CC1C=CC=C1"); + var mol = smilesParser.ParseSmiles("C1(c2ccccc2)(CC(CC1)CCc1ccccc1)CC1C=CC=C1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); fragmenter.GenerateFragments(mol); @@ -134,19 +128,18 @@ public void TestMF2() [TestMethod()] public void TestSingleFramework() { - IAtomContainer mol = smilesParser.ParseSmiles("C1(c2ccccc2)(CC(CC1)CCc1ccccc1)CC1C=CC=C1"); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var mol = smilesParser.ParseSmiles("C1(c2ccccc2)(CC(CC1)CCc1ccccc1)CC1C=CC=C1"); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); Assert.AreEqual(1, frameworks.Count()); - } [TestMethod()] public void TestMF4() { - IAtomContainer mol = smilesParser.ParseSmiles("c1ccc(cc1)c2c(oc(n2)N(CCO)CCO)c3ccccc3"); + var mol = smilesParser.ParseSmiles("c1ccc(cc1)c2c(oc(n2)N(CCO)CCO)c3ccccc3"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); fragmenter.GenerateFragments(mol); @@ -160,7 +153,7 @@ public void TestMF4() [TestMethod()] public void TestMF5() { - IAtomContainer mol = smilesParser.ParseSmiles("c1cc(ccc1C(=O)Nc2ccc3c(c2)nc(o3)c4ccncc4)F"); + var mol = smilesParser.ParseSmiles("c1cc(ccc1C(=O)Nc2ccc3c(c2)nc(o3)c4ccncc4)F"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); Assert.AreEqual(3, frameworks.Count()); @@ -172,7 +165,7 @@ public void TestMF5() [TestMethod()] public void TestMF6() { - IAtomContainer mol = smilesParser.ParseSmiles("COc1ccc(cc1OCc2ccccc2)C(=S)N3CCOCC3"); + var mol = smilesParser.ParseSmiles("COc1ccc(cc1OCc2ccccc2)C(=S)N3CCOCC3"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); @@ -185,7 +178,7 @@ public void TestMF6() [TestMethod()] public void TestMF7() { - IAtomContainer mol = smilesParser.ParseSmiles("Cc1nnc(s1)N[C@H](C(=O)c2ccccc2)NC(=O)c3ccco3"); + var mol = smilesParser.ParseSmiles("Cc1nnc(s1)N[C@H](C(=O)c2ccccc2)NC(=O)c3ccco3"); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); @@ -199,8 +192,8 @@ public void TestMF7() [TestMethod()] public void TestBug1848591() { - IAtomContainer mol = smilesParser.ParseSmiles("c1(ccc(cc1C)CCC(C(CCC)C2C(C2)CC)C3C=C(C=C3)CC)C"); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var mol = smilesParser.ParseSmiles("c1(ccc(cc1C)CCC(C(CCC)C2C(C2)CC)C3C=C(C=C3)CC)C"); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(mol); var frameworks = fragmenter.GetFrameworks(); @@ -212,10 +205,10 @@ public void TestBug1848591() [TestMethod()] public void TestCarbinoxamine_Bug3088164() { - IAtomContainer mol = smilesParser.ParseSmiles("CN(C)CCOC(C1=CC=C(Cl)C=C1)C1=CC=CC=N1"); + var mol = smilesParser.ParseSmiles("CN(C)CCOC(C1=CC=C(Cl)C=C1)C1=CC=CC=N1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(mol); var f = fragmenter.GetFrameworks().ToList(); @@ -224,7 +217,7 @@ public void TestCarbinoxamine_Bug3088164() Assert.AreEqual(f.Count, fc.Count); Assert.AreEqual("n1ccccc1Cc2ccccc2", f[0]); - SmilesGenerator sg = SmilesGenerator.Unique().Aromatic(); + var sg = SmilesGenerator.Unique().Aromatic(); for (int i = 0; i < f.Count; i++) { Aromaticity.CDKLegacy.Apply(fc[i]); @@ -237,13 +230,13 @@ public void TestCarbinoxamine_Bug3088164() [TestMethod()] public void TestPirenperone_Bug3088164() { - SmilesGenerator sg = SmilesGenerator.Unique().Aromatic(); + var sg = SmilesGenerator.Unique().Aromatic(); - IAtomContainer mol = smilesParser.ParseSmiles("Fc1ccc(cc1)C(=O)C4CCN(CCC\\3=C(\\N=C2\\C=C/C=C\\N2C/3=O)C)CC4"); + var mol = smilesParser.ParseSmiles("Fc1ccc(cc1)C(=O)C4CCN(CCC\\3=C(\\N=C2\\C=C/C=C\\N2C/3=O)C)CC4"); AtomContainerManipulator.ClearAtomConfigurations(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(mol); var f = fragmenter.GetFrameworks().ToList(); @@ -270,12 +263,12 @@ public void TestPirenperone_Bug3088164() [TestMethod()] public void TestIsomoltane_Bug3088164() { - SmilesGenerator sg = SmilesGenerator.Unique().Aromatic(); + var sg = SmilesGenerator.Unique().Aromatic(); - IAtomContainer mol = smilesParser.ParseSmiles("CC(C)NCC(O)COC1=C(C=CC=C1)N1C=CC=C1"); + var mol = smilesParser.ParseSmiles("CC(C)NCC(O)COC1=C(C=CC=C1)N1C=CC=C1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(mol); var f = fragmenter.GetFrameworks().ToList(); @@ -295,11 +288,11 @@ public void TestIsomoltane_Bug3088164() [TestMethod()] public void TestGetFragmentsAsContainers() { - IAtomContainer biphenyl = TestMoleculeFactory.MakeBiphenyl(); + var biphenyl = TestMoleculeFactory.MakeBiphenyl(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(biphenyl); Aromaticity.CDKLegacy.Apply(biphenyl); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(biphenyl); var fragments = fragmenter.GetFragmentsAsContainers().ToList(); @@ -316,11 +309,10 @@ public void TestGetFragmentsAsContainers() [TestCategory("SlowTest")] public void TestMacrocycle() { - IAtomContainer mol = smilesParser - .ParseSmiles("C1=C(C=C(C(=C1O)O)O)C(=O)OC2=CC(=CC(=C2O)O)C(=O)OCC3C(C(C(C(O3)OC(=O)C4=CC(=C(C(=C4)OC(=O)C5=CC(=C(C(=C5)O)O)O)O)O)OC(=O)C6=CC(=C(C(=C6)OC(=O)C7=CC(=C(C(=C7)O)O)O)O)O)OC(=O)C8=CC(=C(C(=C8)OC(=O)C9=CC(=C(C(=C9)O)O)O)O)O)OC(=O)C1=CC(=C(C(=C1)OC(=O)C1=CC(=C(C(=C1)O)O)O)O)O"); + var mol = smilesParser.ParseSmiles("C1=C(C=C(C(=C1O)O)O)C(=O)OC2=CC(=CC(=C2O)O)C(=O)OCC3C(C(C(C(O3)OC(=O)C4=CC(=C(C(=C4)OC(=O)C5=CC(=C(C(=C5)O)O)O)O)O)OC(=O)C6=CC(=C(C(=C6)OC(=O)C7=CC(=C(C(=C7)O)O)O)O)O)OC(=O)C8=CC(=C(C(=C8)OC(=O)C9=CC(=C(C(=C9)O)O)O)O)O)OC(=O)C1=CC(=C(C(=C1)OC(=O)C1=CC(=C(C(=C1)O)O)O)O)O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 6); + var fragmenter = new MurckoFragmenter(true, 6); fragmenter.GenerateFragments(mol); var f = fragmenter.GetFrameworks(); diff --git a/NCDKTests/Geometries/Alignments/KabschAlignmentTest.cs b/NCDKTests/Geometries/Alignments/KabschAlignmentTest.cs index d9a96df6..4b97bb42 100644 --- a/NCDKTests/Geometries/Alignments/KabschAlignmentTest.cs +++ b/NCDKTests/Geometries/Alignments/KabschAlignmentTest.cs @@ -1,7 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; using NCDK.Numerics; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System.Linq; diff --git a/NCDKTests/Geometries/BondToolsTest.cs b/NCDKTests/Geometries/BondToolsTest.cs index 035fb5f1..f7bcd0a0 100644 --- a/NCDKTests/Geometries/BondToolsTest.cs +++ b/NCDKTests/Geometries/BondToolsTest.cs @@ -19,8 +19,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; namespace NCDK.Geometries { diff --git a/NCDKTests/Geometries/CIP/CIPSMILESTest.cs b/NCDKTests/Geometries/CIP/CIPSMILESTest.cs index d485db1a..dba08519 100644 --- a/NCDKTests/Geometries/CIP/CIPSMILESTest.cs +++ b/NCDKTests/Geometries/CIP/CIPSMILESTest.cs @@ -48,10 +48,10 @@ public void Test() /// /// Test case that tests sequence recursing of the atomic number rule. /// - /// + /// // @cdk.inchi InChI=1S/C5H12O/c1-3-5(2)4-6/h5-6H,3-4H2,1-2H3/t5-/m1/s1 [TestMethod()] - public void Test2methylbutanol_R() + public void Test2methylbutanolR() { IAtomContainer molecule = smiles.ParseSmiles("OCC([H])(C)CC"); LigancyFourChirality chirality = CIPTool.DefineLigancyFourChirality(molecule, 2, 3, 1, 4, 5, TetrahedralStereo.Clockwise); @@ -61,10 +61,10 @@ public void Test2methylbutanol_R() /// /// Test case that tests sequence recursing of the atomic number rule. /// - /// + /// // @cdk.inchi InChI=1S/C5H12O/c1-3-5(2)4-6/h5-6H,3-4H2,1-2H3/t5-/m0/s1 [TestMethod()] - public void Test2methylbutanol_S() + public void Test2methylbutanolS() { IAtomContainer molecule = smiles.ParseSmiles("OCC([H])(C)CC"); LigancyFourChirality chirality = CIPTool.DefineLigancyFourChirality(molecule, 2, 3, 1, 4, 5, @@ -73,7 +73,7 @@ public void Test2methylbutanol_S() } [TestMethod()] - public void TestTwoVersusDoubleBondedOxygen_R() + public void TestTwoVersusDoubleBondedOxygenR() { IAtomContainer molecule = smiles.ParseSmiles("OC(O)C([H])(C)C=O"); LigancyFourChirality chirality = CIPTool.DefineLigancyFourChirality(molecule, 3, 4, 5, 1, 6, TetrahedralStereo.Clockwise); @@ -81,7 +81,7 @@ public void TestTwoVersusDoubleBondedOxygen_R() } [TestMethod()] - public void TestTwoVersusDoubleBondedOxygen_S() + public void TestTwoVersusDoubleBondedOxygenS() { IAtomContainer molecule = smiles.ParseSmiles("OC(O)C([H])(C)C=O"); LigancyFourChirality chirality = CIPTool.DefineLigancyFourChirality(molecule, 3, 4, 5, 1, 6, @@ -138,7 +138,7 @@ public void TestTetraHalogenMethane() * @cdk.inchi InChI=1S/C20H20BrN3O3S/c1-23(2)9-10-24(20-22-14-8-7-13(21)11-18(14)28-20)19(25)17-12-26-15-5-3-4-6-16(15)27-17/h3-8,11,17H,9-10,12H2,1-2H3/p+1/t17-/m1/s1 */ [TestMethod()] - public void TestCID42475007_R() + public void TestCID42475007R() { IAtomContainer mol = smiles.ParseSmiles("C[NH+](C)CCN(C1=NC2=C(S1)C=C(C=C2)Br)C(=O)[C@H]3COC4=CC=CC=C4O3"); var stereoElements = mol.StereoElements; @@ -150,7 +150,7 @@ public void TestCID42475007_R() // @cdk.inchi InChI=1S/C20H20BrN3O3S/c1-23(2)9-10-24(20-22-14-8-7-13(21)11-18(14)28-20)19(25)17-12-26-15-5-3-4-6-16(15)27-17/h3-8,11,17H,9-10,12H2,1-2H3/p+1/t17+/m1/s1 [TestMethod()] - public void TestCID42475007_S() + public void TestCID42475007S() { IAtomContainer mol = smiles.ParseSmiles("C[NH+](C)CCN(C1=NC2=C(S1)C=C(C=C2)Br)C(=O)[C@@H]3COC4=CC=CC=C4O3"); var stereoElements = mol.StereoElements; @@ -162,7 +162,7 @@ public void TestCID42475007_S() // @cdk.inchi InChI=1/C4H10OS/c1-3-4-6(2)5/h3-4H2,1-2H3/t6+/s2 [TestMethod()] - public void R_sulfinyl() + public void RSulfinyl() { IAtomContainer mol = smiles.ParseSmiles("CCC[S@@](C)=O"); var stereoElements = mol.StereoElements; @@ -174,7 +174,7 @@ public void R_sulfinyl() // @cdk.inchi InChI=1/C4H10OS/c1-3-4-6(2)5/h3-4H2,1-2H3/t6-/s2 [TestMethod()] - public void S_sulfinyl() + public void SSulfinyl() { IAtomContainer mol = smiles.ParseSmiles("CCC[S@](C)=O"); var stereoElements = mol.StereoElements; @@ -185,7 +185,7 @@ public void S_sulfinyl() } [TestMethod()] - public void E_butene() + public void EButene() { Assert.AreEqual(CIPTool.CIPChirality.E, Label("C/C=C/C")); Assert.AreEqual(CIPTool.CIPChirality.E, Label("C/C=C/C")); @@ -193,7 +193,7 @@ public void E_butene() } [TestMethod()] - public void Z_butene() + public void ZButene() { Assert.AreEqual(CIPTool.CIPChirality.Z, Label("C/C=C\\C")); Assert.AreEqual(CIPTool.CIPChirality.Z, Label("C\\C=C/C")); @@ -207,27 +207,27 @@ public void None() } [TestMethod()] - public void E_depth2() + public void EDepth2() { Assert.AreEqual(CIPTool.CIPChirality.E, Label("CC/C(CO)=C(/CC)CO")); Assert.AreEqual(CIPTool.CIPChirality.E, Label("OC\\C(CC)=C(/CC)CO")); } [TestMethod()] - public void Z_depth2() + public void ZDepth2() { Assert.AreEqual(CIPTool.CIPChirality.Z, Label("CC\\C(CO)=C(/CC)CO")); Assert.AreEqual(CIPTool.CIPChirality.Z, Label("OC/C(CC)=C(/CC)CO")); } [TestMethod()] - public void One_size_depth2() + public void OneSizeDepth2() { Assert.AreEqual(CIPTool.CIPChirality.E, Label("CC\\C(CO)=C(/C)")); } [TestMethod()] - public void None_depth2() + public void NoneDepth2() { Assert.AreEqual(CIPTool.CIPChirality.None, Label("CC/C(CC)=C(/CC)CO")); } @@ -249,7 +249,7 @@ CIPTool.CIPChirality Label(string smi) /// the labelling CIPTool.CIPChirality Label(IAtomContainer container) { - var elements = new List>(); + var elements = new List>(); foreach (var element in container.StereoElements) { diff --git a/NCDKTests/Geometries/CIP/CIPToolTest.cs b/NCDKTests/Geometries/CIP/CIPToolTest.cs index 5bf4e74d..fcb87f24 100644 --- a/NCDKTests/Geometries/CIP/CIPToolTest.cs +++ b/NCDKTests/Geometries/CIP/CIPToolTest.cs @@ -22,9 +22,9 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; using NCDK.Numerics; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Stereo; using NCDK.Tools.Manipulator; @@ -39,17 +39,17 @@ public class CIPToolTest : CDKTestCase { static SmilesParser smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); static IAtomContainer molecule; - static ILigand[] ligands; + static IReadOnlyList ligands = MakeLigands(); - static CIPToolTest() + private static IReadOnlyList MakeLigands() { molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); - VisitedAtoms visitedAtoms = new VisitedAtoms(); - ILigand ligand1 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[4]); - ILigand ligand2 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[3]); - ILigand ligand3 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[2]); - ILigand ligand4 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[0]); - ligands = new ILigand[] { ligand1, ligand2, ligand3, ligand4 }; + var visitedAtoms = new VisitedAtoms(); + var ligand1 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[4]); + var ligand2 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[3]); + var ligand3 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[2]); + var ligand4 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[0]); + return new ILigand[] { ligand1, ligand2, ligand3, ligand4 }; } [TestMethod()] @@ -59,71 +59,68 @@ public void TestCheckIfAllLigandsAreDifferent() } [TestMethod()] - public void TestCheckIfAllLigandsAreDifferent_False() + public void TestCheckIfAllLigandsAreDifferentFalse() { - ILigand[] sameLigands = new ILigand[] { ligands[0], ligands[0], ligands[1], ligands[2] }; + var sameLigands = new ILigand[] { ligands[0], ligands[0], ligands[1], ligands[2] }; Assert.IsFalse(CIPTool.CheckIfAllLigandsAreDifferent(sameLigands)); } [TestMethod()] public void TestOrder() { - ILigand[] ligandCopy = CIPTool.Order(ligands); - Assert.AreEqual("H", ligandCopy[0].GetLigandAtom().Symbol); - Assert.AreEqual("Cl", ligandCopy[1].GetLigandAtom().Symbol); - Assert.AreEqual("Br", ligandCopy[2].GetLigandAtom().Symbol); - Assert.AreEqual("I", ligandCopy[3].GetLigandAtom().Symbol); + var ligandCopy = CIPTool.Order(ligands); + Assert.AreEqual("H", ligandCopy[0].LigandAtom.Symbol); + Assert.AreEqual("Cl", ligandCopy[1].LigandAtom.Symbol); + Assert.AreEqual("Br", ligandCopy[2].LigandAtom.Symbol); + Assert.AreEqual("I", ligandCopy[3].LigandAtom.Symbol); } [TestMethod()] public void TestGetCIPChirality() { - LigancyFourChirality chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); - CIPTool.CIPChirality rsChirality = CIPTool.GetCIPChirality(chirality); + var chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); + var rsChirality = CIPTool.GetCIPChirality(chirality); Assert.AreEqual(CIPTool.CIPChirality.S, rsChirality); } [TestMethod()] - public void TestGetCIPChirality_Anti() + public void TestGetCIPChiralityAnti() { - ILigand[] antiLigands = new ILigand[] { ligands[0], ligands[1], ligands[3], ligands[2] }; + var antiLigands = new ILigand[] { ligands[0], ligands[1], ligands[3], ligands[2] }; - LigancyFourChirality chirality = new LigancyFourChirality(molecule.Atoms[1], antiLigands, - TetrahedralStereo.AntiClockwise); - CIPTool.CIPChirality rsChirality = CIPTool.GetCIPChirality(chirality); + var chirality = new LigancyFourChirality(molecule.Atoms[1], antiLigands, TetrahedralStereo.AntiClockwise); + var rsChirality = CIPTool.GetCIPChirality(chirality); Assert.AreEqual(CIPTool.CIPChirality.S, rsChirality); } [TestMethod()] - public void TestGetCIPChirality_ILigancyFourChirality() + public void TestGetCIPChiralityILigancyFourChirality() { - List ligandAtoms = new List(); + var ligandAtoms = new List(); foreach (var ligand in ligands) - ligandAtoms.Add(ligand.GetLigandAtom()); - ITetrahedralChirality chirality = new TetrahedralChirality(molecule.Atoms[1], - ligandAtoms, TetrahedralStereo.Clockwise); - CIPTool.CIPChirality rsChirality = CIPTool.GetCIPChirality(molecule, chirality); + ligandAtoms.Add(ligand.LigandAtom); + var chirality = new TetrahedralChirality(molecule.Atoms[1], ligandAtoms, TetrahedralStereo.Clockwise); + var rsChirality = CIPTool.GetCIPChirality(molecule, chirality); Assert.AreEqual(CIPTool.CIPChirality.S, rsChirality); } [TestMethod()] - public void TestGetCIPChirality_Anti_ILigancyFourChirality() + public void TestGetCIPChiralityAntiILigancyFourChirality() { - ILigand[] antiLigands = new ILigand[] { ligands[0], ligands[1], ligands[3], ligands[2] }; - List ligandAtoms = new List(); + var antiLigands = new ILigand[] { ligands[0], ligands[1], ligands[3], ligands[2] }; + var ligandAtoms = new List(); foreach (var ligand in antiLigands) - ligandAtoms.Add(ligand.GetLigandAtom()); + ligandAtoms.Add(ligand.LigandAtom); - ITetrahedralChirality chirality = new TetrahedralChirality(molecule.Atoms[1], - ligandAtoms, TetrahedralStereo.AntiClockwise); + var chirality = new TetrahedralChirality(molecule.Atoms[1], ligandAtoms, TetrahedralStereo.AntiClockwise); CIPTool.CIPChirality rsChirality = CIPTool.GetCIPChirality(molecule, chirality); Assert.AreEqual(CIPTool.CIPChirality.S, rsChirality); } [TestMethod()] - public void TestGetCIPChirality_DoubleBond_Together() + public void TestGetCIPChiralityDoubleBondTogether() { - IAtomContainer container = new SmilesParser(Silent.ChemObjectBuilder.Instance).ParseSmiles("CCC(C)=C(C)CC"); + var container = new SmilesParser(Silent.ChemObjectBuilder.Instance).ParseSmiles("CCC(C)=C(C)CC"); CIPTool.CIPChirality label = CIPTool.GetCIPChirality( container, new DoubleBondStereochemistry(container.GetBond(container.Atoms[2], container.Atoms[4]), @@ -134,94 +131,92 @@ public void TestGetCIPChirality_DoubleBond_Together() } [TestMethod()] - public void TestGetCIPChirality_DoubleBond_Opposite() + public void TestGetCIPChiralityDoubleBondOpposite() { - IAtomContainer container = new SmilesParser(Silent.ChemObjectBuilder.Instance).ParseSmiles("CCC(C)=C(C)CC"); - CIPTool.CIPChirality label = CIPTool.GetCIPChirality( - container, - new DoubleBondStereochemistry(container.GetBond(container.Atoms[2], container.Atoms[4]), - new IBond[]{container.GetBond(container.Atoms[2], container.Atoms[3]), - container.GetBond(container.Atoms[4], container.Atoms[6])}, - DoubleBondConformation.Opposite)); + var container = new SmilesParser(Silent.ChemObjectBuilder.Instance).ParseSmiles("CCC(C)=C(C)CC"); + var label = CIPTool.GetCIPChirality( + container, + new DoubleBondStereochemistry( + container.GetBond(container.Atoms[2], container.Atoms[4]), + new[] { container.GetBond(container.Atoms[2], container.Atoms[3]), container.GetBond(container.Atoms[4], container.Atoms[6])}, + DoubleBondConformation.Opposite)); Assert.AreEqual(CIPTool.CIPChirality.Z, label); } [TestMethod()] public void Label() { - IAtomContainer container = new SmilesParser(Silent.ChemObjectBuilder.Instance) - .ParseSmiles("C/C=C/[C@@H](C)C(/C)=C(/C)C[C@H](C)O"); + var container = new SmilesParser(Silent.ChemObjectBuilder.Instance).ParseSmiles("C/C=C/[C@@H](C)C(/C)=C(/C)C[C@H](C)O"); CIPTool.Label(container); - Assert.AreEqual("R", container.Atoms[3].GetProperty(CDKPropertyName.CIP_Descriptor)); - Assert.AreEqual("S", container.Atoms[10].GetProperty(CDKPropertyName.CIP_Descriptor)); - Assert.AreEqual("E", container.GetBond(container.Atoms[1], container.Atoms[2]).GetProperty(CDKPropertyName.CIP_Descriptor)); - Assert.AreEqual("Z", container.GetBond(container.Atoms[5], container.Atoms[7]).GetProperty(CDKPropertyName.CIP_Descriptor)); + Assert.AreEqual("R", container.Atoms[3].GetCIPDescriptor()); + Assert.AreEqual("S", container.Atoms[10].GetCIPDescriptor()); + Assert.AreEqual("E", container.GetBond(container.Atoms[1], container.Atoms[2]).GetCIPDescriptor()); + Assert.AreEqual("Z", container.GetBond(container.Atoms[5], container.Atoms[7]).GetCIPDescriptor()); } [TestMethod()] public void TestDefineLigancyFourChirality() { - LigancyFourChirality chirality = CIPTool.DefineLigancyFourChirality(molecule, 1, 0, 2, 3, 4, - TetrahedralStereo.AntiClockwise); + var chirality = CIPTool.DefineLigancyFourChirality(molecule, 1, 0, 2, 3, 4, TetrahedralStereo.AntiClockwise); Assert.AreEqual(molecule.Atoms[1], chirality.ChiralAtom); Assert.AreEqual(TetrahedralStereo.AntiClockwise, chirality.Stereo); - ILigand[] ligands = chirality.Ligands; - Assert.AreEqual(molecule, ligands[0].GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[0], ligands[0].GetLigandAtom()); - Assert.AreEqual(molecule.Atoms[1], ligands[0].GetCentralAtom()); - Assert.AreEqual(molecule, ligands[1].GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[2], ligands[1].GetLigandAtom()); - Assert.AreEqual(molecule.Atoms[1], ligands[1].GetCentralAtom()); - Assert.AreEqual(molecule, ligands[2].GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[3], ligands[2].GetLigandAtom()); - Assert.AreEqual(molecule.Atoms[1], ligands[2].GetCentralAtom()); - Assert.AreEqual(molecule, ligands[3].GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[4], ligands[3].GetLigandAtom()); - Assert.AreEqual(molecule.Atoms[1], ligands[3].GetCentralAtom()); + var ligands = chirality.Ligands; + Assert.AreEqual(molecule, ligands[0].AtomContainer); + Assert.AreEqual(molecule.Atoms[0], ligands[0].LigandAtom); + Assert.AreEqual(molecule.Atoms[1], ligands[0].CentralAtom); + Assert.AreEqual(molecule, ligands[1].AtomContainer); + Assert.AreEqual(molecule.Atoms[2], ligands[1].LigandAtom); + Assert.AreEqual(molecule.Atoms[1], ligands[1].CentralAtom); + Assert.AreEqual(molecule, ligands[2].AtomContainer); + Assert.AreEqual(molecule.Atoms[3], ligands[2].LigandAtom); + Assert.AreEqual(molecule.Atoms[1], ligands[2].CentralAtom); + Assert.AreEqual(molecule, ligands[3].AtomContainer); + Assert.AreEqual(molecule.Atoms[4], ligands[3].LigandAtom); + Assert.AreEqual(molecule.Atoms[1], ligands[3].CentralAtom); } [TestMethod()] public void TestDefineLigand() { - ILigand ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 1, 2); - Assert.AreEqual(molecule, ligand.GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[1], ligand.GetCentralAtom()); - Assert.AreEqual(molecule.Atoms[2], ligand.GetLigandAtom()); + var ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 1, 2); + Assert.AreEqual(molecule, ligand.AtomContainer); + Assert.AreEqual(molecule.Atoms[1], ligand.CentralAtom); + Assert.AreEqual(molecule.Atoms[2], ligand.LigandAtom); } - /** - * Tests if it returns the right number of ligands, for single bonds only. - */ + /// + /// Tests if it returns the right number of ligands, for single bonds only. + /// [TestMethod()] public void TestGetLigandLigands() { - IAtomContainer molecule = smiles.ParseSmiles("CC(C)C(CC)(C(C)(C)C)[H]"); - ILigand ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); - ILigand[] sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(2, sideChains.Length); + var molecule = smiles.ParseSmiles("CC(C)C(CC)(C(C)(C)C)[H]"); + var ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); + var sideChains = CIPTool.GetLigandLigands(ligand); + Assert.AreEqual(2, sideChains.Count); ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 4); sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(1, sideChains.Length); + Assert.AreEqual(1, sideChains.Count); ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(3, sideChains.Length); + Assert.AreEqual(3, sideChains.Count); ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 10); sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(0, sideChains.Length); + Assert.AreEqual(0, sideChains.Count); } - /** - * Tests if it returns the right number of ligands, for single bonds only. - */ + /// + /// Tests if it returns the right number of ligands, for single bonds only. + /// [TestMethod()] - public void TestGetLigandLigands_VisitedTracking() + public void TestGetLigandLigandsVisitedTracking() { - IAtomContainer molecule = smiles.ParseSmiles("CC(C)C(CC)(C(C)(C)C)[H]"); - ILigand ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); - ILigand[] sideChains = CIPTool.GetLigandLigands(ligand); + var molecule = smiles.ParseSmiles("CC(C)C(CC)(C(C)(C)C)[H]"); + var ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); + var sideChains = CIPTool.GetLigandLigands(ligand); foreach (var ligand2 in sideChains) { - Assert.AreNotSame(ligand.GetVisitedAtoms(), ligand2.GetVisitedAtoms()); + Assert.AreNotSame(ligand.VisitedAtoms, ligand2.VisitedAtoms); } } @@ -229,37 +224,37 @@ public void TestGetLigandLigands_VisitedTracking() /// Tests if it returns the right number of ligands, for double bonds. /// [TestMethod()] - public void TestGetLigandLigands_DoubleTriple() + public void TestGetLigandLigandsDoubleTriple() { - IAtomContainer molecule = smiles.ParseSmiles("CC(C)C(C#N)(C(=C)C)[H]"); - ILigand ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); - ILigand[] sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(2, sideChains.Length); + var molecule = smiles.ParseSmiles("CC(C)C(C#N)(C(=C)C)[H]"); + var ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); + var sideChains = CIPTool.GetLigandLigands(ligand); + Assert.AreEqual(2, sideChains.Count); ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 4); sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(3, sideChains.Length); + Assert.AreEqual(3, sideChains.Count); ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(3, sideChains.Length); + Assert.AreEqual(3, sideChains.Count); ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 9); sideChains = CIPTool.GetLigandLigands(ligand); - Assert.AreEqual(0, sideChains.Length); + Assert.AreEqual(0, sideChains.Count); } [TestMethod()] - public void TestDefineLigand_ImplicitHydrogen() + public void TestDefineLigandImplicitHydrogen() { - IAtomContainer molecule = smiles.ParseSmiles("CC(C)C(C#N)(C(=C)C)"); - ILigand ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, CIPTool.Hydrogen); + var molecule = smiles.ParseSmiles("CC(C)C(C#N)(C(=C)C)"); + var ligand = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, CIPTool.Hydrogen); Assert.IsTrue(ligand is ImplicitHydrogenLigand); } [TestMethod()] - //(timeout=5000) + [Timeout(5000)] public void TestTermination() { int ringSize = 7; - IAtomContainer ring = new AtomContainer(); + var ring = new AtomContainer(); for (int i = 0; i < ringSize; i++) { ring.Atoms.Add(new Atom("C")); @@ -276,9 +271,8 @@ public void TestTermination() ring.AddBond(ring.Atoms[0], ring.Atoms[ringSize + 1], BondOrder.Single); ring.Atoms.Add(new Atom("O")); ring.AddBond(ring.Atoms[1], ring.Atoms[ringSize + 2], BondOrder.Single); - IAtom[] atoms = new IAtom[]{ring.Atoms[ringSize], ring.Atoms[ringSize + 1], ring.Atoms[ringSize - 1], - ring.Atoms[1]}; - ITetrahedralChirality stereoCenter = new TetrahedralChirality(ring.Atoms[0], atoms, TetrahedralStereo.AntiClockwise); + var atoms = new IAtom[]{ring.Atoms[ringSize], ring.Atoms[ringSize + 1], ring.Atoms[ringSize - 1], ring.Atoms[1]}; + var stereoCenter = new TetrahedralChirality(ring.Atoms[0], atoms, TetrahedralStereo.AntiClockwise); ring.StereoElements.Add(stereoCenter); SmilesGenerator generator = new SmilesGenerator(); CIPTool.GetCIPChirality(ring, stereoCenter); @@ -291,7 +285,7 @@ public void TestOla28() IChemFile file; IAtomContainer mol; - using (CMLReader reader = new CMLReader(ResourceLoader.GetAsStream(filename))) + using (var reader = new CMLReader(ResourceLoader.GetAsStream(filename))) { file = reader.Read(new ChemFile()); mol = ChemFileManipulator.GetAllAtomContainers(file).First(); @@ -313,448 +307,448 @@ public void TestOla28() [TestMethod()] public void TestSteroid() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; - IAtomContainer mol = builder.NewAtomContainer(); - IAtom a1 = builder.NewAtom("F"); + var builder = ChemObjectBuilder.Instance; + var mol = builder.NewAtomContainer(); + var a1 = builder.NewAtom("F"); a1.FormalCharge = 0; a1.Point3D = new Vector3(7.0124, 2.5853, -0.9016); mol.Atoms.Add(a1); - IAtom a2 = builder.NewAtom("O"); + var a2 = builder.NewAtom("O"); a2.FormalCharge = 0; a2.Point3D = new Vector3(-0.5682, -0.2861, 2.1733); mol.Atoms.Add(a2); - IAtom a3 = builder.NewAtom("O"); + var a3 = builder.NewAtom("O"); a3.FormalCharge = 0; a3.Point3D = new Vector3(2.2826, -2.9598, -0.5754); mol.Atoms.Add(a3); - IAtom a4 = builder.NewAtom("O"); + var a4 = builder.NewAtom("O"); a4.FormalCharge = 0; a4.Point3D = new Vector3(-6.6808, -1.9515, 0.4596); mol.Atoms.Add(a4); - IAtom a5 = builder.NewAtom("O"); + var a5 = builder.NewAtom("O"); a5.FormalCharge = 0; a5.Point3D = new Vector3(4.2201, -1.7701, -1.7827); mol.Atoms.Add(a5); - IAtom a6 = builder.NewAtom("O"); + var a6 = builder.NewAtom("O"); a6.FormalCharge = 0; a6.Point3D = new Vector3(-7.0886, 0.761, 0.0885); mol.Atoms.Add(a6); - IAtom a7 = builder.NewAtom("O"); + var a7 = builder.NewAtom("O"); a7.FormalCharge = 0; a7.Point3D = new Vector3(-3.3025, 3.5973, -0.657); mol.Atoms.Add(a7); - IAtom a8 = builder.NewAtom("C"); + var a8 = builder.NewAtom("C"); a8.FormalCharge = 0; a8.Point3D = new Vector3(0.4862, -0.9146, 0.0574); mol.Atoms.Add(a8); - IAtom a9 = builder.NewAtom("C"); + var a9 = builder.NewAtom("C"); a9.FormalCharge = 0; a9.Point3D = new Vector3(-0.1943, 0.2177, 0.8706); mol.Atoms.Add(a9); - IAtom a10 = builder.NewAtom("C"); + var a10 = builder.NewAtom("C"); a10.FormalCharge = 0; a10.Point3D = new Vector3(1.7596, -1.1559, 0.9089); mol.Atoms.Add(a10); - IAtom a11 = builder.NewAtom("C"); + var a11 = builder.NewAtom("C"); a11.FormalCharge = 0; a11.Point3D = new Vector3(-2.4826, -0.4593, -0.073); mol.Atoms.Add(a11); - IAtom a12 = builder.NewAtom("C"); + var a12 = builder.NewAtom("C"); a12.FormalCharge = 0; a12.Point3D = new Vector3(-3.7166, 0.0102, -0.941); mol.Atoms.Add(a12); - IAtom a13 = builder.NewAtom("C"); + var a13 = builder.NewAtom("C"); a13.FormalCharge = 0; a13.Point3D = new Vector3(-0.4659, -2.1213, 0.0044); mol.Atoms.Add(a13); - IAtom a14 = builder.NewAtom("C"); + var a14 = builder.NewAtom("C"); a14.FormalCharge = 0; a14.Point3D = new Vector3(-1.485, 0.6715, 0.2231); mol.Atoms.Add(a14); - IAtom a15 = builder.NewAtom("C"); + var a15 = builder.NewAtom("C"); a15.FormalCharge = 0; a15.Point3D = new Vector3(0.9729, 1.1842, 1.122); mol.Atoms.Add(a15); - IAtom a16 = builder.NewAtom("C"); + var a16 = builder.NewAtom("C"); a16.FormalCharge = 0; a16.Point3D = new Vector3(2.1976, 0.2666, 1.3272); mol.Atoms.Add(a16); - IAtom a17 = builder.NewAtom("C"); + var a17 = builder.NewAtom("C"); a17.FormalCharge = 0; a17.Point3D = new Vector3(-1.8034, -1.7401, -0.6501); mol.Atoms.Add(a17); - IAtom a18 = builder.NewAtom("C"); + var a18 = builder.NewAtom("C"); a18.FormalCharge = 0; a18.Point3D = new Vector3(-4.2265, 1.3894, -0.4395); mol.Atoms.Add(a18); - IAtom a19 = builder.NewAtom("C"); + var a19 = builder.NewAtom("C"); a19.FormalCharge = 0; a19.Point3D = new Vector3(2.8802, -1.9484, 0.2485); mol.Atoms.Add(a19); - IAtom a20 = builder.NewAtom("C"); + var a20 = builder.NewAtom("C"); a20.FormalCharge = 0; a20.Point3D = new Vector3(0.862, -0.4809, -1.3862); mol.Atoms.Add(a20); - IAtom a21 = builder.NewAtom("C"); + var a21 = builder.NewAtom("C"); a21.FormalCharge = 0; a21.Point3D = new Vector3(-4.8907, -1.0078, -0.8633); mol.Atoms.Add(a21); - IAtom a22 = builder.NewAtom("C"); + var a22 = builder.NewAtom("C"); a22.FormalCharge = 0; a22.Point3D = new Vector3(-1.7576, 1.9697, 0.0241); mol.Atoms.Add(a22); - IAtom a23 = builder.NewAtom("C"); + var a23 = builder.NewAtom("C"); a23.FormalCharge = 0; a23.Point3D = new Vector3(-4.9064, 1.3293, 0.9405); mol.Atoms.Add(a23); - IAtom a24 = builder.NewAtom("C"); + var a24 = builder.NewAtom("C"); a24.FormalCharge = 0; a24.Point3D = new Vector3(-3.339, 0.1527, -2.4408); mol.Atoms.Add(a24); - IAtom a25 = builder.NewAtom("C"); + var a25 = builder.NewAtom("C"); a25.FormalCharge = 0; a25.Point3D = new Vector3(-3.1038, 2.4096, -0.4054); mol.Atoms.Add(a25); - IAtom a26 = builder.NewAtom("C"); + var a26 = builder.NewAtom("C"); a26.FormalCharge = 0; a26.Point3D = new Vector3(-5.5668, -1.0627, 0.5104); mol.Atoms.Add(a26); - IAtom a27 = builder.NewAtom("C"); + var a27 = builder.NewAtom("C"); a27.FormalCharge = 0; a27.Point3D = new Vector3(3.7564, -1.0338, -0.652); mol.Atoms.Add(a27); - IAtom a28 = builder.NewAtom("C"); + var a28 = builder.NewAtom("C"); a28.FormalCharge = 0; a28.Point3D = new Vector3(-6.0498, 0.3154, 0.9627); mol.Atoms.Add(a28); - IAtom a29 = builder.NewAtom("C"); + var a29 = builder.NewAtom("C"); a29.FormalCharge = 0; a29.Point3D = new Vector3(3.6914, -2.6828, 1.3258); mol.Atoms.Add(a29); - IAtom a30 = builder.NewAtom("C"); + var a30 = builder.NewAtom("C"); a30.FormalCharge = 0; a30.Point3D = new Vector3(4.9535, -0.3812, 0.0661); mol.Atoms.Add(a30); - IAtom a31 = builder.NewAtom("C"); + var a31 = builder.NewAtom("C"); a31.FormalCharge = 0; a31.Point3D = new Vector3(5.4727, 0.8461, -0.696); mol.Atoms.Add(a31); - IAtom a32 = builder.NewAtom("C"); + var a32 = builder.NewAtom("C"); a32.FormalCharge = 0; a32.Point3D = new Vector3(6.7079, 1.5265, -0.0844); mol.Atoms.Add(a32); - IAtom a33 = builder.NewAtom("C"); + var a33 = builder.NewAtom("C"); a33.FormalCharge = 0; a33.Point3D = new Vector3(6.4387, 2.104, 1.3013); mol.Atoms.Add(a33); - IAtom a34 = builder.NewAtom("C"); + var a34 = builder.NewAtom("C"); a34.FormalCharge = 0; a34.Point3D = new Vector3(7.9342, 0.6197, -0.0661); mol.Atoms.Add(a34); - IAtom a35 = builder.NewAtom("H"); + var a35 = builder.NewAtom("H"); a35.FormalCharge = 0; a35.Point3D = new Vector3(1.4474, -1.6941, 1.8161); mol.Atoms.Add(a35); - IAtom a36 = builder.NewAtom("H"); + var a36 = builder.NewAtom("H"); a36.FormalCharge = 0; a36.Point3D = new Vector3(-2.8575, -0.7521, 0.9166); mol.Atoms.Add(a36); - IAtom a37 = builder.NewAtom("H"); + var a37 = builder.NewAtom("H"); a37.FormalCharge = 0; a37.Point3D = new Vector3(-0.0529, -2.952, -0.5733); mol.Atoms.Add(a37); - IAtom a38 = builder.NewAtom("H"); + var a38 = builder.NewAtom("H"); a38.FormalCharge = 0; a38.Point3D = new Vector3(-0.6583, -2.5149, 1.01); mol.Atoms.Add(a38); - IAtom a39 = builder.NewAtom("H"); + var a39 = builder.NewAtom("H"); a39.FormalCharge = 0; a39.Point3D = new Vector3(1.1462, 1.8516, 0.2703); mol.Atoms.Add(a39); - IAtom a40 = builder.NewAtom("H"); + var a40 = builder.NewAtom("H"); a40.FormalCharge = 0; a40.Point3D = new Vector3(0.8186, 1.8095, 2.0087); mol.Atoms.Add(a40); - IAtom a41 = builder.NewAtom("H"); + var a41 = builder.NewAtom("H"); a41.FormalCharge = 0; a41.Point3D = new Vector3(2.5044, 0.2648, 2.3797); mol.Atoms.Add(a41); - IAtom a42 = builder.NewAtom("H"); + var a42 = builder.NewAtom("H"); a42.FormalCharge = 0; a42.Point3D = new Vector3(2.9822, 0.7582, 0.7671); mol.Atoms.Add(a42); - IAtom a43 = builder.NewAtom("H"); + var a43 = builder.NewAtom("H"); a43.FormalCharge = 0; a43.Point3D = new Vector3(-2.4854, -2.5906, -0.5319); mol.Atoms.Add(a43); - IAtom a44 = builder.NewAtom("H"); + var a44 = builder.NewAtom("H"); a44.FormalCharge = 0; a44.Point3D = new Vector3(-1.6353, -1.6475, -1.7261); mol.Atoms.Add(a44); - IAtom a45 = builder.NewAtom("H"); + var a45 = builder.NewAtom("H"); a45.FormalCharge = 0; a45.Point3D = new Vector3(-4.9616, 1.7691, -1.1638); mol.Atoms.Add(a45); - IAtom a46 = builder.NewAtom("H"); + var a46 = builder.NewAtom("H"); a46.FormalCharge = 0; a46.Point3D = new Vector3(-0.0354, -0.2446, -1.9684); mol.Atoms.Add(a46); - IAtom a47 = builder.NewAtom("H"); + var a47 = builder.NewAtom("H"); a47.FormalCharge = 0; a47.Point3D = new Vector3(1.3691, -1.2574, -1.9625); mol.Atoms.Add(a47); - IAtom a48 = builder.NewAtom("H"); + var a48 = builder.NewAtom("H"); a48.FormalCharge = 0; a48.Point3D = new Vector3(1.4296, 0.4511, -1.4252); mol.Atoms.Add(a48); - IAtom a49 = builder.NewAtom("H"); + var a49 = builder.NewAtom("H"); a49.FormalCharge = 0; a49.Point3D = new Vector3(-4.5596, -2.0138, -1.147); mol.Atoms.Add(a49); - IAtom a50 = builder.NewAtom("H"); + var a50 = builder.NewAtom("H"); a50.FormalCharge = 0; a50.Point3D = new Vector3(-5.6512, -0.7511, -1.6149); mol.Atoms.Add(a50); - IAtom a51 = builder.NewAtom("H"); + var a51 = builder.NewAtom("H"); a51.FormalCharge = 0; a51.Point3D = new Vector3(-1.0464, 2.7559, 0.2488); mol.Atoms.Add(a51); - IAtom a52 = builder.NewAtom("H"); + var a52 = builder.NewAtom("H"); a52.FormalCharge = 0; a52.Point3D = new Vector3(-4.1786, 1.0807, 1.7222); mol.Atoms.Add(a52); - IAtom a53 = builder.NewAtom("H"); + var a53 = builder.NewAtom("H"); a53.FormalCharge = 0; a53.Point3D = new Vector3(-5.2947, 2.3265, 1.1848); mol.Atoms.Add(a53); - IAtom a54 = builder.NewAtom("H"); + var a54 = builder.NewAtom("H"); a54.FormalCharge = 0; a54.Point3D = new Vector3(-2.421, 0.7311, -2.5838); mol.Atoms.Add(a54); - IAtom a55 = builder.NewAtom("H"); + var a55 = builder.NewAtom("H"); a55.FormalCharge = 0; a55.Point3D = new Vector3(-3.2008, -0.8224, -2.9194); mol.Atoms.Add(a55); - IAtom a56 = builder.NewAtom("H"); + var a56 = builder.NewAtom("H"); a56.FormalCharge = 0; a56.Point3D = new Vector3(-4.1353, 0.658, -3.0004); mol.Atoms.Add(a56); - IAtom a57 = builder.NewAtom("H"); + var a57 = builder.NewAtom("H"); a57.FormalCharge = 0; a57.Point3D = new Vector3(-4.8758, -1.4669, 1.2574); mol.Atoms.Add(a57); - IAtom a58 = builder.NewAtom("H"); + var a58 = builder.NewAtom("H"); a58.FormalCharge = 0; a58.Point3D = new Vector3(-0.9312, 0.4562, 2.6867); mol.Atoms.Add(a58); - IAtom a59 = builder.NewAtom("H"); + var a59 = builder.NewAtom("H"); a59.FormalCharge = 0; a59.Point3D = new Vector3(3.1882, -0.2287, -1.0977); mol.Atoms.Add(a59); - IAtom a60 = builder.NewAtom("H"); + var a60 = builder.NewAtom("H"); a60.FormalCharge = 0; a60.Point3D = new Vector3(-6.4869, 0.2469, 1.965); mol.Atoms.Add(a60); - IAtom a61 = builder.NewAtom("H"); + var a61 = builder.NewAtom("H"); a61.FormalCharge = 0; a61.Point3D = new Vector3(4.102, -2.0082, 2.0826); mol.Atoms.Add(a61); - IAtom a62 = builder.NewAtom("H"); + var a62 = builder.NewAtom("H"); a62.FormalCharge = 0; a62.Point3D = new Vector3(4.5162, -3.2434, 0.8708); mol.Atoms.Add(a62); - IAtom a63 = builder.NewAtom("H"); + var a63 = builder.NewAtom("H"); a63.FormalCharge = 0; a63.Point3D = new Vector3(3.0747, -3.4251, 1.8469); mol.Atoms.Add(a63); - IAtom a64 = builder.NewAtom("H"); + var a64 = builder.NewAtom("H"); a64.FormalCharge = 0; a64.Point3D = new Vector3(1.8961, -3.6368, 0.0058); mol.Atoms.Add(a64); - IAtom a65 = builder.NewAtom("H"); + var a65 = builder.NewAtom("H"); a65.FormalCharge = 0; a65.Point3D = new Vector3(5.7631, -1.1204, 0.1084); mol.Atoms.Add(a65); - IAtom a66 = builder.NewAtom("H"); + var a66 = builder.NewAtom("H"); a66.FormalCharge = 0; a66.Point3D = new Vector3(4.743, -0.1036, 1.1001); mol.Atoms.Add(a66); - IAtom a67 = builder.NewAtom("H"); + var a67 = builder.NewAtom("H"); a67.FormalCharge = 0; a67.Point3D = new Vector3(-6.3482, -2.8223, 0.1828); mol.Atoms.Add(a67); - IAtom a68 = builder.NewAtom("H"); + var a68 = builder.NewAtom("H"); a68.FormalCharge = 0; a68.Point3D = new Vector3(4.6594, -1.153, -2.3908); mol.Atoms.Add(a68); - IAtom a69 = builder.NewAtom("H"); + var a69 = builder.NewAtom("H"); a69.FormalCharge = 0; a69.Point3D = new Vector3(-7.3836, 1.6319, 0.4047); mol.Atoms.Add(a69); - IAtom a70 = builder.NewAtom("H"); + var a70 = builder.NewAtom("H"); a70.FormalCharge = 0; a70.Point3D = new Vector3(5.716, 0.5715, -1.7297); mol.Atoms.Add(a70); - IAtom a71 = builder.NewAtom("H"); + var a71 = builder.NewAtom("H"); a71.FormalCharge = 0; a71.Point3D = new Vector3(4.6721, 1.5926, -0.7787); mol.Atoms.Add(a71); - IBond b1 = builder.NewBond(a1, a32, BondOrder.Single); + var b1 = builder.NewBond(a1, a32, BondOrder.Single); mol.Bonds.Add(b1); - IBond b2 = builder.NewBond(a2, a9, BondOrder.Single); + var b2 = builder.NewBond(a2, a9, BondOrder.Single); mol.Bonds.Add(b2); - IBond b3 = builder.NewBond(a2, a58, BondOrder.Single); + var b3 = builder.NewBond(a2, a58, BondOrder.Single); mol.Bonds.Add(b3); - IBond b4 = builder.NewBond(a3, a19, BondOrder.Single); + var b4 = builder.NewBond(a3, a19, BondOrder.Single); mol.Bonds.Add(b4); - IBond b5 = builder.NewBond(a3, a64, BondOrder.Single); + var b5 = builder.NewBond(a3, a64, BondOrder.Single); mol.Bonds.Add(b5); - IBond b6 = builder.NewBond(a4, a26, BondOrder.Single); + var b6 = builder.NewBond(a4, a26, BondOrder.Single); mol.Bonds.Add(b6); - IBond b7 = builder.NewBond(a4, a67, BondOrder.Single); + var b7 = builder.NewBond(a4, a67, BondOrder.Single); mol.Bonds.Add(b7); - IBond b8 = builder.NewBond(a5, a27, BondOrder.Single); + var b8 = builder.NewBond(a5, a27, BondOrder.Single); mol.Bonds.Add(b8); - IBond b9 = builder.NewBond(a5, a68, BondOrder.Single); + var b9 = builder.NewBond(a5, a68, BondOrder.Single); mol.Bonds.Add(b9); - IBond b10 = builder.NewBond(a6, a28, BondOrder.Single); + var b10 = builder.NewBond(a6, a28, BondOrder.Single); mol.Bonds.Add(b10); - IBond b11 = builder.NewBond(a6, a69, BondOrder.Single); + var b11 = builder.NewBond(a6, a69, BondOrder.Single); mol.Bonds.Add(b11); - IBond b12 = builder.NewBond(a7, a25, BondOrder.Double); + var b12 = builder.NewBond(a7, a25, BondOrder.Double); mol.Bonds.Add(b12); - IBond b13 = builder.NewBond(a8, a9, BondOrder.Single); + var b13 = builder.NewBond(a8, a9, BondOrder.Single); mol.Bonds.Add(b13); - IBond b14 = builder.NewBond(a8, a10, BondOrder.Single); + var b14 = builder.NewBond(a8, a10, BondOrder.Single); mol.Bonds.Add(b14); - IBond b15 = builder.NewBond(a8, a13, BondOrder.Single); + var b15 = builder.NewBond(a8, a13, BondOrder.Single); mol.Bonds.Add(b15); - IBond b16 = builder.NewBond(a8, a20, BondOrder.Single); + var b16 = builder.NewBond(a8, a20, BondOrder.Single); mol.Bonds.Add(b16); - IBond b17 = builder.NewBond(a9, a14, BondOrder.Single); + var b17 = builder.NewBond(a9, a14, BondOrder.Single); mol.Bonds.Add(b17); - IBond b18 = builder.NewBond(a9, a15, BondOrder.Single); + var b18 = builder.NewBond(a9, a15, BondOrder.Single); mol.Bonds.Add(b18); - IBond b19 = builder.NewBond(a10, a16, BondOrder.Single); + var b19 = builder.NewBond(a10, a16, BondOrder.Single); mol.Bonds.Add(b19); - IBond b20 = builder.NewBond(a10, a19, BondOrder.Single); + var b20 = builder.NewBond(a10, a19, BondOrder.Single); mol.Bonds.Add(b20); - IBond b21 = builder.NewBond(a10, a35, BondOrder.Single); + var b21 = builder.NewBond(a10, a35, BondOrder.Single); mol.Bonds.Add(b21); - IBond b22 = builder.NewBond(a11, a12, BondOrder.Single); + var b22 = builder.NewBond(a11, a12, BondOrder.Single); mol.Bonds.Add(b22); - IBond b23 = builder.NewBond(a11, a14, BondOrder.Single); + var b23 = builder.NewBond(a11, a14, BondOrder.Single); mol.Bonds.Add(b23); - IBond b24 = builder.NewBond(a11, a17, BondOrder.Single); + var b24 = builder.NewBond(a11, a17, BondOrder.Single); mol.Bonds.Add(b24); - IBond b25 = builder.NewBond(a11, a36, BondOrder.Single); + var b25 = builder.NewBond(a11, a36, BondOrder.Single); mol.Bonds.Add(b25); - IBond b26 = builder.NewBond(a12, a18, BondOrder.Single); + var b26 = builder.NewBond(a12, a18, BondOrder.Single); mol.Bonds.Add(b26); - IBond b27 = builder.NewBond(a12, a21, BondOrder.Single); + var b27 = builder.NewBond(a12, a21, BondOrder.Single); mol.Bonds.Add(b27); - IBond b28 = builder.NewBond(a12, a24, BondOrder.Single); + var b28 = builder.NewBond(a12, a24, BondOrder.Single); mol.Bonds.Add(b28); - IBond b29 = builder.NewBond(a13, a17, BondOrder.Single); + var b29 = builder.NewBond(a13, a17, BondOrder.Single); mol.Bonds.Add(b29); - IBond b30 = builder.NewBond(a13, a37, BondOrder.Single); + var b30 = builder.NewBond(a13, a37, BondOrder.Single); mol.Bonds.Add(b30); - IBond b31 = builder.NewBond(a13, a38, BondOrder.Single); + var b31 = builder.NewBond(a13, a38, BondOrder.Single); mol.Bonds.Add(b31); - IBond b32 = builder.NewBond(a14, a22, BondOrder.Double); + var b32 = builder.NewBond(a14, a22, BondOrder.Double); mol.Bonds.Add(b32); - IBond b33 = builder.NewBond(a15, a16, BondOrder.Single); + var b33 = builder.NewBond(a15, a16, BondOrder.Single); mol.Bonds.Add(b33); - IBond b34 = builder.NewBond(a15, a39, BondOrder.Single); + var b34 = builder.NewBond(a15, a39, BondOrder.Single); mol.Bonds.Add(b34); - IBond b35 = builder.NewBond(a15, a40, BondOrder.Single); + var b35 = builder.NewBond(a15, a40, BondOrder.Single); mol.Bonds.Add(b35); - IBond b36 = builder.NewBond(a16, a41, BondOrder.Single); + var b36 = builder.NewBond(a16, a41, BondOrder.Single); mol.Bonds.Add(b36); - IBond b37 = builder.NewBond(a16, a42, BondOrder.Single); + var b37 = builder.NewBond(a16, a42, BondOrder.Single); mol.Bonds.Add(b37); - IBond b38 = builder.NewBond(a17, a43, BondOrder.Single); + var b38 = builder.NewBond(a17, a43, BondOrder.Single); mol.Bonds.Add(b38); - IBond b39 = builder.NewBond(a17, a44, BondOrder.Single); + var b39 = builder.NewBond(a17, a44, BondOrder.Single); mol.Bonds.Add(b39); - IBond b40 = builder.NewBond(a18, a23, BondOrder.Single); + var b40 = builder.NewBond(a18, a23, BondOrder.Single); mol.Bonds.Add(b40); - IBond b41 = builder.NewBond(a18, a25, BondOrder.Single); + var b41 = builder.NewBond(a18, a25, BondOrder.Single); mol.Bonds.Add(b41); - IBond b42 = builder.NewBond(a18, a45, BondOrder.Single); + var b42 = builder.NewBond(a18, a45, BondOrder.Single); mol.Bonds.Add(b42); - IBond b43 = builder.NewBond(a19, a27, BondOrder.Single); + var b43 = builder.NewBond(a19, a27, BondOrder.Single); mol.Bonds.Add(b43); - IBond b44 = builder.NewBond(a19, a29, BondOrder.Single); + var b44 = builder.NewBond(a19, a29, BondOrder.Single); mol.Bonds.Add(b44); - IBond b45 = builder.NewBond(a20, a46, BondOrder.Single); + var b45 = builder.NewBond(a20, a46, BondOrder.Single); mol.Bonds.Add(b45); - IBond b46 = builder.NewBond(a20, a47, BondOrder.Single); + var b46 = builder.NewBond(a20, a47, BondOrder.Single); mol.Bonds.Add(b46); - IBond b47 = builder.NewBond(a20, a48, BondOrder.Single); + var b47 = builder.NewBond(a20, a48, BondOrder.Single); mol.Bonds.Add(b47); - IBond b48 = builder.NewBond(a21, a26, BondOrder.Single); + var b48 = builder.NewBond(a21, a26, BondOrder.Single); mol.Bonds.Add(b48); - IBond b49 = builder.NewBond(a21, a49, BondOrder.Single); + var b49 = builder.NewBond(a21, a49, BondOrder.Single); mol.Bonds.Add(b49); - IBond b50 = builder.NewBond(a21, a50, BondOrder.Single); + var b50 = builder.NewBond(a21, a50, BondOrder.Single); mol.Bonds.Add(b50); - IBond b51 = builder.NewBond(a22, a25, BondOrder.Single); + var b51 = builder.NewBond(a22, a25, BondOrder.Single); mol.Bonds.Add(b51); - IBond b52 = builder.NewBond(a22, a51, BondOrder.Single); + var b52 = builder.NewBond(a22, a51, BondOrder.Single); mol.Bonds.Add(b52); - IBond b53 = builder.NewBond(a23, a28, BondOrder.Single); + var b53 = builder.NewBond(a23, a28, BondOrder.Single); mol.Bonds.Add(b53); - IBond b54 = builder.NewBond(a23, a52, BondOrder.Single); + var b54 = builder.NewBond(a23, a52, BondOrder.Single); mol.Bonds.Add(b54); - IBond b55 = builder.NewBond(a23, a53, BondOrder.Single); + var b55 = builder.NewBond(a23, a53, BondOrder.Single); mol.Bonds.Add(b55); - IBond b56 = builder.NewBond(a24, a54, BondOrder.Single); + var b56 = builder.NewBond(a24, a54, BondOrder.Single); mol.Bonds.Add(b56); - IBond b57 = builder.NewBond(a24, a55, BondOrder.Single); + var b57 = builder.NewBond(a24, a55, BondOrder.Single); mol.Bonds.Add(b57); - IBond b58 = builder.NewBond(a24, a56, BondOrder.Single); + var b58 = builder.NewBond(a24, a56, BondOrder.Single); mol.Bonds.Add(b58); - IBond b59 = builder.NewBond(a26, a28, BondOrder.Single); + var b59 = builder.NewBond(a26, a28, BondOrder.Single); mol.Bonds.Add(b59); - IBond b60 = builder.NewBond(a26, a57, BondOrder.Single); + var b60 = builder.NewBond(a26, a57, BondOrder.Single); mol.Bonds.Add(b60); - IBond b61 = builder.NewBond(a27, a30, BondOrder.Single); + var b61 = builder.NewBond(a27, a30, BondOrder.Single); mol.Bonds.Add(b61); - IBond b62 = builder.NewBond(a27, a59, BondOrder.Single); + var b62 = builder.NewBond(a27, a59, BondOrder.Single); mol.Bonds.Add(b62); - IBond b63 = builder.NewBond(a28, a60, BondOrder.Single); + var b63 = builder.NewBond(a28, a60, BondOrder.Single); mol.Bonds.Add(b63); - IBond b64 = builder.NewBond(a29, a61, BondOrder.Single); + var b64 = builder.NewBond(a29, a61, BondOrder.Single); mol.Bonds.Add(b64); - IBond b65 = builder.NewBond(a29, a62, BondOrder.Single); + var b65 = builder.NewBond(a29, a62, BondOrder.Single); mol.Bonds.Add(b65); - IBond b66 = builder.NewBond(a29, a63, BondOrder.Single); + var b66 = builder.NewBond(a29, a63, BondOrder.Single); mol.Bonds.Add(b66); - IBond b67 = builder.NewBond(a30, a31, BondOrder.Single); + var b67 = builder.NewBond(a30, a31, BondOrder.Single); mol.Bonds.Add(b67); - IBond b68 = builder.NewBond(a30, a65, BondOrder.Single); + var b68 = builder.NewBond(a30, a65, BondOrder.Single); mol.Bonds.Add(b68); - IBond b69 = builder.NewBond(a30, a66, BondOrder.Single); + var b69 = builder.NewBond(a30, a66, BondOrder.Single); mol.Bonds.Add(b69); - IBond b70 = builder.NewBond(a31, a32, BondOrder.Single); + var b70 = builder.NewBond(a31, a32, BondOrder.Single); mol.Bonds.Add(b70); - IBond b71 = builder.NewBond(a31, a70, BondOrder.Single); + var b71 = builder.NewBond(a31, a70, BondOrder.Single); mol.Bonds.Add(b71); - IBond b72 = builder.NewBond(a31, a71, BondOrder.Single); + var b72 = builder.NewBond(a31, a71, BondOrder.Single); mol.Bonds.Add(b72); - IBond b73 = builder.NewBond(a32, a33, BondOrder.Single); + var b73 = builder.NewBond(a32, a33, BondOrder.Single); mol.Bonds.Add(b73); - IBond b74 = builder.NewBond(a32, a34, BondOrder.Single); + var b74 = builder.NewBond(a32, a34, BondOrder.Single); mol.Bonds.Add(b74); - IAtom[] ligandAtoms = new IAtom[4]; + var ligandAtoms = new IAtom[4]; ligandAtoms[0] = a1; // F ligandAtoms[1] = a33; // Me ligandAtoms[2] = a34; // Me ligandAtoms[3] = a31; // rest of molecule var stereo = StereoTool.GetStereo(ligandAtoms[0], ligandAtoms[1], ligandAtoms[2], ligandAtoms[3]); - ITetrahedralChirality tetraStereo = new TetrahedralChirality(a32, ligandAtoms, stereo); + var tetraStereo = new TetrahedralChirality(a32, ligandAtoms, stereo); Assert.AreEqual(CIPTool.CIPChirality.None, CIPTool.GetCIPChirality(mol, tetraStereo)); } diff --git a/NCDKTests/Geometries/CIP/ImplicitHydrogenLigandTest.cs b/NCDKTests/Geometries/CIP/ImplicitHydrogenLigandTest.cs index 7fb0e1c4..23fea247 100644 --- a/NCDKTests/Geometries/CIP/ImplicitHydrogenLigandTest.cs +++ b/NCDKTests/Geometries/CIP/ImplicitHydrogenLigandTest.cs @@ -38,9 +38,9 @@ public void TestConstructorAndGetMethods() ILigand ligand = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); Assert.IsNotNull(ligand); - Assert.AreEqual(molecule, ligand.GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[1], ligand.GetCentralAtom()); - Assert.IsTrue(ligand.GetLigandAtom() is ImmutableHydrogen); + Assert.AreEqual(molecule, ligand.AtomContainer); + Assert.AreEqual(molecule.Atoms[1], ligand.CentralAtom); + Assert.IsTrue(ligand.LigandAtom is ImmutableHydrogen); } } } diff --git a/NCDKTests/Geometries/CIP/LigancyFourChiralityTest.cs b/NCDKTests/Geometries/CIP/LigancyFourChiralityTest.cs index 21fd595c..963da625 100644 --- a/NCDKTests/Geometries/CIP/LigancyFourChiralityTest.cs +++ b/NCDKTests/Geometries/CIP/LigancyFourChiralityTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Stereo; using System.Collections.Generic; @@ -32,12 +32,12 @@ namespace NCDK.Geometries.CIP [TestClass()] public class LigancyFourChiralityTest : CDKTestCase { - private static IAtomContainer molecule; - private static ILigand[] ligands; + private static IAtomContainer molecule = MoleculeMaker(); + private static ILigand[] ligands = LigandsMaker(); - static LigancyFourChiralityTest() + private static IAtomContainer MoleculeMaker() { - molecule = new AtomContainer(); + var molecule = new AtomContainer(); molecule.Atoms.Add(new Atom("Cl")); molecule.Atoms.Add(new Atom("C")); molecule.Atoms.Add(new Atom("Br")); @@ -47,17 +47,23 @@ static LigancyFourChiralityTest() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); - ILigand ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); - ILigand ligand3 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); - ILigand ligand4 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + return molecule; + } + + private static ILigand[] LigandsMaker() + { + var ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); + var ligand3 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); + var ligand4 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); ligands = new ILigand[] { ligand1, ligand2, ligand3, ligand4 }; + return ligands; } [TestMethod()] public void TestConstructor() { - LigancyFourChirality chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); + var chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); Assert.IsNotNull(chirality); Assert.AreEqual(molecule.Atoms[1], chirality.ChiralAtom); for (int i = 0; i < ligands.Length; i++) @@ -68,50 +74,50 @@ public void TestConstructor() } [TestMethod()] - public void TestConstructor_ILigancyFourChirality() + public void TestConstructorILigancyFourChirality() { - List ligandAtoms = new List(); + var ligandAtoms = new List(); foreach (var ligand in ligands) - ligandAtoms.Add(ligand.GetLigandAtom()); - ITetrahedralChirality cdkChiral = new TetrahedralChirality(molecule.Atoms[1], + ligandAtoms.Add(ligand.LigandAtom); + var cdkChiral = new TetrahedralChirality(molecule.Atoms[1], ligandAtoms, TetrahedralStereo.Clockwise); - LigancyFourChirality chirality = new LigancyFourChirality(molecule, cdkChiral); + var chirality = new LigancyFourChirality(molecule, cdkChiral); Assert.IsNotNull(chirality); Assert.AreEqual(molecule.Atoms[1], chirality.ChiralAtom); for (int i = 0; i < ligands.Length; i++) { - Assert.AreEqual(ligands[i].GetLigandAtom(), chirality.Ligands[i].GetLigandAtom()); - Assert.AreEqual(ligands[i].GetCentralAtom(), chirality.Ligands[i].GetCentralAtom()); - Assert.AreEqual(ligands[i].GetAtomContainer(), chirality.Ligands[i].GetAtomContainer()); + Assert.AreEqual(ligands[i].LigandAtom, chirality.Ligands[i].LigandAtom); + Assert.AreEqual(ligands[i].CentralAtom, chirality.Ligands[i].CentralAtom); + Assert.AreEqual(ligands[i].AtomContainer, chirality.Ligands[i].AtomContainer); } Assert.AreEqual(TetrahedralStereo.Clockwise, chirality.Stereo); } - /** - * Checks if projecting onto itself does not change the stereochemistry. - */ + /// + /// Checks if projecting onto itself does not change the stereochemistry. + /// [TestMethod()] public void TestProject() { - LigancyFourChirality chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); + var chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); chirality.Project(ligands); Assert.AreEqual(TetrahedralStereo.Clockwise, chirality.Stereo); } [TestMethod()] - public void TestProject_OneChange() + public void TestProjectOneChange() { - LigancyFourChirality chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); - ILigand[] newLigands = new ILigand[] { ligands[0], ligands[1], ligands[3], ligands[2] }; + var chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); + var newLigands = new ILigand[] { ligands[0], ligands[1], ligands[3], ligands[2] }; chirality = chirality.Project(newLigands); Assert.AreEqual(TetrahedralStereo.AntiClockwise, chirality.Stereo); } [TestMethod()] - public void TestProject_TwoChanges() + public void TestProjectTwoChanges() { - LigancyFourChirality chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); - ILigand[] newLigands = new ILigand[] { ligands[1], ligands[0], ligands[3], ligands[2] }; + var chirality = new LigancyFourChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); + var newLigands = new ILigand[] { ligands[1], ligands[0], ligands[3], ligands[2] }; chirality = chirality.Project(newLigands); Assert.AreEqual(TetrahedralStereo.Clockwise, chirality.Stereo); } diff --git a/NCDKTests/Geometries/CIP/LigandTest.cs b/NCDKTests/Geometries/CIP/LigandTest.cs index cc25b983..f6d79d5e 100644 --- a/NCDKTests/Geometries/CIP/LigandTest.cs +++ b/NCDKTests/Geometries/CIP/LigandTest.cs @@ -33,26 +33,26 @@ public class LigandTest : CDKTestCase [TestMethod()] public void TestConstructorAndGetMethods() { - SmilesParser smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); - IAtomContainer molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); + var smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); + var molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); - ILigand ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); Assert.IsNotNull(ligand); - Assert.AreEqual(molecule, ligand.GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[1], ligand.GetCentralAtom()); - Assert.AreEqual(molecule.Atoms[0], ligand.GetLigandAtom()); + Assert.AreEqual(molecule, ligand.AtomContainer); + Assert.AreEqual(molecule.Atoms[1], ligand.CentralAtom); + Assert.AreEqual(molecule.Atoms[0], ligand.LigandAtom); } [TestMethod()] public void TestVisitedTracking() { - SmilesParser smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); - IAtomContainer molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); + var smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); + var molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); - ILigand ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - Assert.IsTrue(ligand.GetVisitedAtoms().IsVisited(molecule.Atoms[1])); + var ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + Assert.IsTrue(ligand.VisitedAtoms.IsVisited(molecule.Atoms[1])); Assert.IsTrue(ligand.IsVisited(molecule.Atoms[1])); - Assert.IsFalse(ligand.GetVisitedAtoms().IsVisited(molecule.Atoms[0])); + Assert.IsFalse(ligand.VisitedAtoms.IsVisited(molecule.Atoms[0])); Assert.IsFalse(ligand.IsVisited(molecule.Atoms[0])); } } diff --git a/NCDKTests/Geometries/CIP/Rules/AtomicNumberRuleTest.cs b/NCDKTests/Geometries/CIP/Rules/AtomicNumberRuleTest.cs index 1cef1925..15b72b99 100644 --- a/NCDKTests/Geometries/CIP/Rules/AtomicNumberRuleTest.cs +++ b/NCDKTests/Geometries/CIP/Rules/AtomicNumberRuleTest.cs @@ -69,10 +69,10 @@ public void TestOrder() }; ligands.Sort(new AtomicNumberRule()); - Assert.AreEqual("H", ligands[0].GetLigandAtom().Symbol); - Assert.AreEqual("Cl", ligands[1].GetLigandAtom().Symbol); - Assert.AreEqual("Br", ligands[2].GetLigandAtom().Symbol); - Assert.AreEqual("I", ligands[3].GetLigandAtom().Symbol); + Assert.AreEqual("H", ligands[0].LigandAtom.Symbol); + Assert.AreEqual("Cl", ligands[1].LigandAtom.Symbol); + Assert.AreEqual("Br", ligands[2].LigandAtom.Symbol); + Assert.AreEqual("I", ligands[3].LigandAtom.Symbol); } [TestMethod()] diff --git a/NCDKTests/Geometries/CIP/Rules/CIPLigandRuleTest.cs b/NCDKTests/Geometries/CIP/Rules/CIPLigandRuleTest.cs index 00cda141..5abe9eac 100644 --- a/NCDKTests/Geometries/CIP/Rules/CIPLigandRuleTest.cs +++ b/NCDKTests/Geometries/CIP/Rules/CIPLigandRuleTest.cs @@ -36,12 +36,12 @@ public class CIPLigandRuleTest : CDKTestCase [TestMethod()] public void TestCBrIFCl() { - IAtomContainer molecule = smiles.ParseSmiles("FC(Br)(Cl)I"); - ILigand ligandF = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ILigand ligandBr = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); - ILigand ligandCl = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); - ILigand ligandI = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("FC(Br)(Cl)I"); + var ligandF = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligandBr = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); + var ligandCl = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); + var ligandI = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); + var rule = new CIPLigandRule(); Assert.AreEqual(-1, rule.Compare(ligandF, ligandI)); Assert.AreEqual(-1, rule.Compare(ligandF, ligandBr)); Assert.AreEqual(-1, rule.Compare(ligandF, ligandCl)); @@ -49,35 +49,37 @@ public void TestCBrIFCl() Assert.AreEqual(-1, rule.Compare(ligandCl, ligandBr)); Assert.AreEqual(-1, rule.Compare(ligandBr, ligandI)); - List ligands = new List(); - ligands.Add(ligandI); - ligands.Add(ligandBr); - ligands.Add(ligandF); - ligands.Add(ligandCl); + var ligands = new List + { + ligandI, + ligandBr, + ligandF, + ligandCl + }; ligands.Sort(new CIPLigandRule()); - Assert.AreEqual("F", ligands[0].GetLigandAtom().Symbol); - Assert.AreEqual("Cl", ligands[1].GetLigandAtom().Symbol); - Assert.AreEqual("Br", ligands[2].GetLigandAtom().Symbol); - Assert.AreEqual("I", ligands[3].GetLigandAtom().Symbol); + Assert.AreEqual("F", ligands[0].LigandAtom.Symbol); + Assert.AreEqual("Cl", ligands[1].LigandAtom.Symbol); + Assert.AreEqual("Br", ligands[2].LigandAtom.Symbol); + Assert.AreEqual("I", ligands[3].LigandAtom.Symbol); } [TestMethod()] - public void TestCompare_Identity() + public void TestCompareIdentity() { - IAtomContainer molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); - ILigand ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); + var ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var rule = new CIPLigandRule(); Assert.AreEqual(0, rule.Compare(ligand, ligand)); } [TestMethod()] public void TestCompare() { - IAtomContainer molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); - ILigand ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); + var ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); + var rule = new CIPLigandRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } @@ -85,20 +87,20 @@ public void TestCompare() [TestMethod()] public void TestOrder() { - IAtomContainer molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); - List ligands = new List(); - VisitedAtoms visitedAtoms = new VisitedAtoms(); + var molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); + var ligands = new List(); + var visitedAtoms = new VisitedAtoms(); ligands.Add(CIPTool.DefineLigand(molecule, visitedAtoms, 1, 4)); ligands.Add(CIPTool.DefineLigand(molecule, visitedAtoms, 1, 3)); ligands.Add(CIPTool.DefineLigand(molecule, visitedAtoms, 1, 2)); ligands.Add(CIPTool.DefineLigand(molecule, visitedAtoms, 1, 0)); ligands.Sort(new CIPLigandRule()); - Assert.AreEqual("H", ligands[0].GetLigandAtom().Symbol); - Assert.AreEqual("C", ligands[1].GetLigandAtom().Symbol); - Assert.AreEqual("C", ligands[2].GetLigandAtom().Symbol); - Assert.AreEqual(13, ligands[2].GetLigandAtom().MassNumber.Value); - Assert.AreEqual("Br", ligands[3].GetLigandAtom().Symbol); + Assert.AreEqual("H", ligands[0].LigandAtom.Symbol); + Assert.AreEqual("C", ligands[1].LigandAtom.Symbol); + Assert.AreEqual("C", ligands[2].LigandAtom.Symbol); + Assert.AreEqual(13, ligands[2].LigandAtom.MassNumber.Value); + Assert.AreEqual("Br", ligands[3].LigandAtom.Symbol); } /// @@ -107,10 +109,10 @@ public void TestOrder() [TestMethod()] public void TestSideChains() { - IAtomContainer molecule = smiles.ParseSmiles("CC(C)C([H])(C)CC"); - ILigand ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); - ILigand ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CC(C)C([H])(C)CC"); + var ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); + var ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); + var rule = new CIPLigandRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } @@ -120,12 +122,12 @@ public void TestSideChains() /// but unlike , the tie only gets resolved after recursion. /// [TestMethod()] - public void TestSideChains_Recursive() + public void TestSideChainsRecursive() { - IAtomContainer molecule = smiles.ParseSmiles("CCCC([H])(C)CC"); - ILigand ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); - ILigand ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CCCC([H])(C)CC"); + var ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); + var ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); + var rule = new CIPLigandRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } @@ -138,10 +140,10 @@ public void TestSideChains_Recursive() [TestMethod()] public void TestTwoVersusDoubleBondedOxygen() { - IAtomContainer molecule = smiles.ParseSmiles("OC(O)C([H])(C)C=O"); - ILigand ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); - ILigand ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("OC(O)C([H])(C)C=O"); + var ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 1); + var ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 3, 6); + var rule = new CIPLigandRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } @@ -152,21 +154,21 @@ public void TestTwoVersusDoubleBondedOxygen() [TestMethod()] public void TestDeepRecursion() { - IAtomContainer molecule = smiles.ParseSmiles("CC([H])(CCCCCCCCCC)CCCCCCCCC"); - ILigand ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 1, 3); - ILigand ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 1, 13); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CC([H])(CCCCCCCCCC)CCCCCCCCC"); + var ligand1 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 1, 3); + var ligand2 = CIPTool.DefineLigand(molecule, new VisitedAtoms(), 1, 13); + var rule = new CIPLigandRule(); Assert.AreEqual(1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(-1, rule.Compare(ligand2, ligand1)); } [TestMethod()] - public void TestImplicitHydrogen_Same() + public void TestImplicitHydrogenSame() { - IAtomContainer molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); - ILigand ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); + var ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); + var rule = new CIPLigandRule(); Assert.AreEqual(0, rule.Compare(ligand1, ligand2)); Assert.AreEqual(0, rule.Compare(ligand2, ligand1)); } @@ -174,10 +176,10 @@ public void TestImplicitHydrogen_Same() [TestMethod()] public void TestImplicitHydrogen() { - IAtomContainer molecule = smiles.ParseSmiles("CC(Br)([2H])[H]"); - ILigand ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); - ISequenceSubRule rule = new CIPLigandRule(); + var molecule = smiles.ParseSmiles("CC(Br)([2H])[H]"); + var ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); + var rule = new CIPLigandRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); diff --git a/NCDKTests/Geometries/CIP/Rules/CombinedAtomicMassNumberRuleTest.cs b/NCDKTests/Geometries/CIP/Rules/CombinedAtomicMassNumberRuleTest.cs index af603f7e..51197bf0 100644 --- a/NCDKTests/Geometries/CIP/Rules/CombinedAtomicMassNumberRuleTest.cs +++ b/NCDKTests/Geometries/CIP/Rules/CombinedAtomicMassNumberRuleTest.cs @@ -35,19 +35,19 @@ public class CombinedAtomicMassNumberRuleTest : CDKTestCase static IAtomContainer molecule = smiles.ParseSmiles("CC(Br)([13C])[H]"); [TestMethod()] - public void TestCompare_Identity() + public void TestCompareIdentity() { - ILigand ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ISequenceSubRule rule = new CombinedAtomicMassNumberRule(); + var ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var rule = new CombinedAtomicMassNumberRule(); Assert.AreEqual(0, rule.Compare(ligand, ligand)); } [TestMethod()] public void TestCompare() { - ILigand ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); - ISequenceSubRule rule = new CombinedAtomicMassNumberRule(); + var ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); + var rule = new CombinedAtomicMassNumberRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } @@ -55,22 +55,24 @@ public void TestCompare() [TestMethod()] public void TestOrder() { - ILigand ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); - ILigand ligand3 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); - ILigand ligand4 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - List ligands = new List(); - ligands.Add(ligand1); - ligands.Add(ligand2); - ligands.Add(ligand3); - ligands.Add(ligand4); + var ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); + var ligand3 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); + var ligand4 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligands = new List + { + ligand1, + ligand2, + ligand3, + ligand4 + }; ligands.Sort(new CombinedAtomicMassNumberRule()); - Assert.AreEqual("H", ligands[0].GetLigandAtom().Symbol); - Assert.AreEqual("C", ligands[1].GetLigandAtom().Symbol); - Assert.AreEqual("C", ligands[2].GetLigandAtom().Symbol); - Assert.AreEqual(13, ligands[2].GetLigandAtom().MassNumber.Value); - Assert.AreEqual("Br", ligands[3].GetLigandAtom().Symbol); + Assert.AreEqual("H", ligands[0].LigandAtom.Symbol); + Assert.AreEqual("C", ligands[1].LigandAtom.Symbol); + Assert.AreEqual("C", ligands[2].LigandAtom.Symbol); + Assert.AreEqual(13, ligands[2].LigandAtom.MassNumber.Value); + Assert.AreEqual("Br", ligands[3].LigandAtom.Symbol); } } } diff --git a/NCDKTests/Geometries/CIP/Rules/MassNumberRuleTest.cs b/NCDKTests/Geometries/CIP/Rules/MassNumberRuleTest.cs index e38e54c8..0a0812f5 100644 --- a/NCDKTests/Geometries/CIP/Rules/MassNumberRuleTest.cs +++ b/NCDKTests/Geometries/CIP/Rules/MassNumberRuleTest.cs @@ -35,19 +35,19 @@ public class MassNumberRuleTest : CDKTestCase static IAtomContainer molecule = smiles.ParseSmiles("CC([13C])([2H])[H]"); [TestMethod()] - public void TestCompare_Identity() + public void TestCompareIdentity() { - ILigand ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ISequenceSubRule rule = new MassNumberRule(); + var ligand = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var rule = new MassNumberRule(); Assert.AreEqual(0, rule.Compare(ligand, ligand)); } [TestMethod()] public void TestCompare() { - ILigand ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); - ISequenceSubRule rule = new MassNumberRule(); + var ligand1 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[2]); + var rule = new MassNumberRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } @@ -55,33 +55,35 @@ public void TestCompare() [TestMethod()] public void TestOrder() { - VisitedAtoms visitedAtoms = new VisitedAtoms(); - ILigand ligand1 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[4]); - ILigand ligand2 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[3]); - ILigand ligand3 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[2]); - ILigand ligand4 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[0]); - List ligands = new List(); - ligands.Add(ligand1); - ligands.Add(ligand2); - ligands.Add(ligand3); - ligands.Add(ligand4); + var visitedAtoms = new VisitedAtoms(); + var ligand1 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[4]); + var ligand2 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[3]); + var ligand3 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[2]); + var ligand4 = new Ligand(molecule, visitedAtoms, molecule.Atoms[1], molecule.Atoms[0]); + var ligands = new List + { + ligand1, + ligand2, + ligand3, + ligand4 + }; ligands.Sort(new MassNumberRule()); Assert.IsNotNull(ligands[0]); - Assert.AreEqual("H", ligands[0].GetLigandAtom().Symbol); - Assert.AreEqual("H", ligands[1].GetLigandAtom().Symbol); - Assert.AreEqual(2, ligands[1].GetLigandAtom().MassNumber.Value); - Assert.AreEqual("C", ligands[2].GetLigandAtom().Symbol); - Assert.AreEqual("C", ligands[3].GetLigandAtom().Symbol); - Assert.AreEqual(13, ligands[3].GetLigandAtom().MassNumber.Value); + Assert.AreEqual("H", ligands[0].LigandAtom.Symbol); + Assert.AreEqual("H", ligands[1].LigandAtom.Symbol); + Assert.AreEqual(2, ligands[1].LigandAtom.MassNumber.Value); + Assert.AreEqual("C", ligands[2].LigandAtom.Symbol); + Assert.AreEqual("C", ligands[3].LigandAtom.Symbol); + Assert.AreEqual(13, ligands[3].LigandAtom.MassNumber.Value); } [TestMethod()] - public void TestImplicitHydrogen_Same() + public void TestImplicitHydrogenSame() { - ILigand ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); - ISequenceSubRule rule = new MassNumberRule(); + var ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[4]); + var rule = new MassNumberRule(); Assert.AreEqual(0, rule.Compare(ligand1, ligand2)); Assert.AreEqual(0, rule.Compare(ligand2, ligand1)); } @@ -89,9 +91,9 @@ public void TestImplicitHydrogen_Same() [TestMethod()] public void TestImplicitHydrogen() { - ILigand ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); - ILigand ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); - ISequenceSubRule rule = new MassNumberRule(); + var ligand1 = new ImplicitHydrogenLigand(molecule, new VisitedAtoms(), molecule.Atoms[1]); + var ligand2 = new Ligand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[3]); + var rule = new MassNumberRule(); Assert.AreEqual(-1, rule.Compare(ligand1, ligand2)); Assert.AreEqual(1, rule.Compare(ligand2, ligand1)); } diff --git a/NCDKTests/Geometries/CIP/TerminalLigandTest.cs b/NCDKTests/Geometries/CIP/TerminalLigandTest.cs index b28c02b4..6e40b9d1 100644 --- a/NCDKTests/Geometries/CIP/TerminalLigandTest.cs +++ b/NCDKTests/Geometries/CIP/TerminalLigandTest.cs @@ -33,14 +33,14 @@ public class TerminalLigandTest : CDKTestCase [TestMethod()] public void TestConstructorAndGetMethods() { - SmilesParser smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); - IAtomContainer molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); + var smiles = new SmilesParser(Silent.ChemObjectBuilder.Instance); + var molecule = smiles.ParseSmiles("ClC(Br)(I)[H]"); - ILigand ligand = new TerminalLigand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); + var ligand = new TerminalLigand(molecule, new VisitedAtoms(), molecule.Atoms[1], molecule.Atoms[0]); Assert.IsNotNull(ligand); - Assert.AreEqual(molecule, ligand.GetAtomContainer()); - Assert.AreEqual(molecule.Atoms[1], ligand.GetCentralAtom()); - Assert.AreEqual(molecule.Atoms[0], ligand.GetLigandAtom()); + Assert.AreEqual(molecule, ligand.AtomContainer); + Assert.AreEqual(molecule.Atoms[1], ligand.CentralAtom); + Assert.AreEqual(molecule.Atoms[0], ligand.LigandAtom); } } } diff --git a/NCDKTests/Geometries/CIP/VisitedAtomsTest.cs b/NCDKTests/Geometries/CIP/VisitedAtomsTest.cs index 8432b82c..19f853cb 100644 --- a/NCDKTests/Geometries/CIP/VisitedAtomsTest.cs +++ b/NCDKTests/Geometries/CIP/VisitedAtomsTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Geometries.CIP { diff --git a/NCDKTests/Geometries/CML/CML23FragmentsTest.cs b/NCDKTests/Geometries/CML/CML23FragmentsTest.cs index 5356cf5e..5f45b4ec 100644 --- a/NCDKTests/Geometries/CML/CML23FragmentsTest.cs +++ b/NCDKTests/Geometries/CML/CML23FragmentsTest.cs @@ -21,10 +21,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Dict; using NCDK.QSAR; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Stereo; using System.IO; using System.Linq; diff --git a/NCDKTests/Geometries/CML/CMLFragmentsTest.cs b/NCDKTests/Geometries/CML/CMLFragmentsTest.cs index 5b8650c6..e55c3f46 100644 --- a/NCDKTests/Geometries/CML/CMLFragmentsTest.cs +++ b/NCDKTests/Geometries/CML/CMLFragmentsTest.cs @@ -22,8 +22,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Numerics; +using NCDK.Silent; using System.IO; using System.Text; diff --git a/NCDKTests/Geometries/CML/JChemPaintTest.cs b/NCDKTests/Geometries/CML/JChemPaintTest.cs index 40c5195e..a64e975b 100644 --- a/NCDKTests/Geometries/CML/JChemPaintTest.cs +++ b/NCDKTests/Geometries/CML/JChemPaintTest.cs @@ -22,8 +22,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Geometries; +using NCDK.Silent; using System.Diagnostics; namespace NCDK.IO.CML @@ -53,11 +53,11 @@ public void TestSalt() // test the resulting ChemFile content Assert.IsNotNull(chemFile); Assert.AreEqual(1, chemFile.Count); - //Debug.WriteLine("NO sequences: " + chemFile.Count); + //Debug.WriteLine($"NO sequences: {chemFile.Count}"); IChemSequence seq = chemFile[0]; Assert.IsNotNull(seq); Assert.AreEqual(1, seq.Count); - //Debug.WriteLine("NO models: " + seq.Count); + //Debug.WriteLine($"NO models: {seq.Count}"); IChemModel model = seq[0]; Assert.IsNotNull(model); Assert.AreEqual(1, model.MoleculeSet.Count); diff --git a/NCDKTests/Geometries/CML/JmolTest.cs b/NCDKTests/Geometries/CML/JmolTest.cs index e91c35f8..88d3ec45 100644 --- a/NCDKTests/Geometries/CML/JmolTest.cs +++ b/NCDKTests/Geometries/CML/JmolTest.cs @@ -22,9 +22,9 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Geometries; using NCDK.Numerics; +using NCDK.Silent; using System.Diagnostics; namespace NCDK.IO.CML @@ -130,11 +130,11 @@ public void TestMethanolTwo() // test the resulting ChemFile content Assert.IsNotNull(chemFile); Assert.AreEqual(1, chemFile.Count); - //Debug.WriteLine("NO sequences: " + chemFile.Count); + //Debug.WriteLine($"NO sequences: {chemFile.Count}"); IChemSequence seq = chemFile[0]; Assert.IsNotNull(seq); Assert.AreEqual(1, seq.Count); - //Debug.WriteLine("NO models: " + seq.Count); + //Debug.WriteLine($"NO models: {seq.Count}"); IChemModel model = seq[0]; Assert.IsNotNull(model); Assert.AreEqual(1, model.MoleculeSet.Count); @@ -162,11 +162,11 @@ public void TestMethanolOne() // test the resulting ChemFile content Assert.IsNotNull(chemFile); Assert.AreEqual(1, chemFile.Count); - //Debug.WriteLine("NO sequences: " + chemFile.Count); + //Debug.WriteLine($"NO sequences: {chemFile.Count}"); IChemSequence seq = chemFile[0]; Assert.IsNotNull(seq); Assert.AreEqual(1, seq.Count); - //Debug.WriteLine("NO models: " + seq.Count); + //Debug.WriteLine($"NO models: {seq.Count}"); IChemModel model = seq[0]; Assert.IsNotNull(model); var som = model.MoleculeSet; diff --git a/NCDKTests/Geometries/CML/Jumbo46CMLFragmentsTest.cs b/NCDKTests/Geometries/CML/Jumbo46CMLFragmentsTest.cs index c47c3e3d..f7d11524 100644 --- a/NCDKTests/Geometries/CML/Jumbo46CMLFragmentsTest.cs +++ b/NCDKTests/Geometries/CML/Jumbo46CMLFragmentsTest.cs @@ -22,8 +22,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Numerics; +using NCDK.Silent; using System.IO; using System.Text; diff --git a/NCDKTests/Geometries/CML/JumboTest.cs b/NCDKTests/Geometries/CML/JumboTest.cs index ab882c69..d625edfb 100644 --- a/NCDKTests/Geometries/CML/JumboTest.cs +++ b/NCDKTests/Geometries/CML/JumboTest.cs @@ -22,8 +22,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Geometries; +using NCDK.Silent; using System.Diagnostics; namespace NCDK.IO.CML diff --git a/NCDKTests/Geometries/GeometryUtilTest.cs b/NCDKTests/Geometries/GeometryUtilTest.cs index 726d8753..5ea6fd1e 100644 --- a/NCDKTests/Geometries/GeometryUtilTest.cs +++ b/NCDKTests/Geometries/GeometryUtilTest.cs @@ -23,10 +23,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; using NCDK.IO; using NCDK.Isomorphisms; using NCDK.Numerics; +using NCDK.Silent; using NCDK.Tools.Diff; using System; using System.Collections.Generic; @@ -45,7 +45,7 @@ namespace NCDK.Geometries public class GeometryUtilTest : CDKTestCase { [TestMethod()] - public void TestHas2DCoordinates_IAtomContainer() + public void TestHas2DCoordinatesIAtomContainer() { Atom atom1 = new Atom("C") { Point2D = new Vector2(1, 1) }; Atom atom2 = new Atom("C") { Point2D = new Vector2(1, 0) }; @@ -63,7 +63,7 @@ public void TestHas2DCoordinates_IAtomContainer() } [TestMethod()] - public void TestHas2DCoordinates_EmptyAtomContainer() + public void TestHas2DCoordinatesEmptyAtomContainer() { IAtomContainer container = new AtomContainer(); Assert.IsFalse(GeometryUtil.Has2DCoordinates(container)); @@ -71,7 +71,7 @@ public void TestHas2DCoordinates_EmptyAtomContainer() } [TestMethod()] - public void TestHas2DCoordinates_Partial() + public void TestHas2DCoordinatesPartial() { IAtomContainer container = new AtomContainer(); Atom atom1 = new Atom("C"); @@ -85,7 +85,7 @@ public void TestHas2DCoordinates_Partial() // @cdk.bug 2936440 [TestMethod()] - public void TestHas2DCoordinates_With000() + public void TestHas2DCoordinatesWith000() { string filenameMol = "NCDK.Data.MDL.with000coordinate.mol"; var ins = ResourceLoader.GetAsStream(filenameMol); @@ -96,7 +96,7 @@ public void TestHas2DCoordinates_With000() } [TestMethod()] - public void Get2DCoordinateCoverage_EmptyAtomContainer() + public void Get2DCoordinateCoverageEmptyAtomContainer() { IAtomContainer container = new AtomContainer(); Assert.AreEqual(GeometryUtil.CoordinateCoverage.None, GeometryUtil.Get2DCoordinateCoverage(container)); @@ -105,7 +105,7 @@ public void Get2DCoordinateCoverage_EmptyAtomContainer() } [TestMethod()] - public void Get2DCoordinateCoverage_Partial() + public void Get2DCoordinateCoveragePartial() { IAtomContainer container = new AtomContainer(); @@ -124,7 +124,7 @@ public void Get2DCoordinateCoverage_Partial() } [TestMethod()] - public void Get2DCoordinateCoverage_Full() + public void Get2DCoordinateCoverageFull() { IAtomContainer container = new AtomContainer(); @@ -144,7 +144,7 @@ public void Get2DCoordinateCoverage_Full() } [TestMethod()] - public void Get2DCoordinateCoverage_None_3D() + public void Get2DCoordinateCoverageNone3D() { IAtomContainer container = new AtomContainer(); @@ -164,7 +164,7 @@ public void Get2DCoordinateCoverage_None_3D() } [TestMethod()] - public void TestTranslateAllPositive_IAtomContainer() + public void TestTranslateAllPositiveIAtomContainer() { IAtomContainer container = new AtomContainer(); IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()) @@ -176,7 +176,7 @@ public void TestTranslateAllPositive_IAtomContainer() } [TestMethod()] - public void TestGetLength2D_IBond() + public void TestGetLength2DIBond() { Atom o = new Atom("O", new Vector2(0.0, 0.0)); Atom c = new Atom("C", new Vector2(1.0, 0.0)); @@ -194,7 +194,7 @@ public void TestMapAtomsOfAlignedStructures() var ins = ResourceLoader.GetAsStream(filenameMolOne); IAtomContainer molOne; IAtomContainer molTwo; - IDictionary mappedAtoms = new Dictionary(); + var mappedAtoms = new Dictionary(); MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); molOne = reader.Read(new AtomContainer()); @@ -202,7 +202,7 @@ public void TestMapAtomsOfAlignedStructures() reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); molTwo = reader.Read(new AtomContainer()); - mappedAtoms = AtomMappingTools.MapAtomsOfAlignedStructures(molOne, molTwo, mappedAtoms); + AtomMappingTools.MapAtomsOfAlignedStructures(molOne, molTwo, mappedAtoms); //Debug.WriteLine("mappedAtoms:"+mappedAtoms.ToString()); //Debug.WriteLine("***** ANGLE VARIATIONS *****"); double AngleRMSD = GeometryUtil.GetAngleRMSD(molOne, molTwo, mappedAtoms); @@ -226,7 +226,7 @@ public void TestRotate_IAtomContainer_Point2d_Double() atom1.Point2D = new Vector2(1, 1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); GeometryUtil.Rotate(ac, Vector2.Zero, Math.PI / 2); @@ -241,13 +241,13 @@ public void TestRotate_IAtomContainer_Point2d_Double() } [TestMethod()] - public void TestGetMinMax_IAtomContainer() + public void TestGetMinMaxIAtomContainer() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); double[] minmax = GeometryUtil.GetMinMax(ac); @@ -265,7 +265,7 @@ public void TestGetMinMax2() atom1.Point2D = new Vector2(-2, -1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(-5, -1); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); double[] minmax = GeometryUtil.GetMinMax(ac); @@ -276,7 +276,7 @@ public void TestGetMinMax2() } [TestMethod()] - public void TestRotate_IAtom_Point3d_Point3d_Double() + public void TestRotateIAtomPoint3dPoint3dDouble() { Atom atom1 = new Atom("C"); atom1.Point3D = new Vector3(1, 1, 0); @@ -285,7 +285,7 @@ public void TestRotate_IAtom_Point3d_Point3d_Double() } [TestMethod()] - public void TestNormalize_Point3d() + public void TestNormalizePoint3d() { Vector3 p = new Vector3(1, 1, 0); p = Vector3.Normalize(p); @@ -295,13 +295,13 @@ public void TestNormalize_Point3d() } [TestMethod()] - public void TestGet2DCenter_IAtomContainer() + public void TestGet2DCenterIAtomContainer() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); Vector2 p = GeometryUtil.Get2DCenter(ac); @@ -310,7 +310,7 @@ public void TestGet2DCenter_IAtomContainer() } [TestMethod()] - public void TestGet2DCenterOfMass_IAtomContainer() + public void TestGet2DCenterOfMassIAtomContainer() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); @@ -318,7 +318,7 @@ public void TestGet2DCenterOfMass_IAtomContainer() Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); atom2.ExactMass = 12.0; - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); Vector2? p = GeometryUtil.Get2DCentreOfMass(ac); @@ -328,7 +328,7 @@ public void TestGet2DCenterOfMass_IAtomContainer() } [TestMethod()] - public void TestGet2DCenter_arrayIAtom() + public void TestGet2DCenterArrayIAtom() { IAtomContainer container = new AtomContainer(); Atom atom1 = new Atom("C"); @@ -343,16 +343,16 @@ public void TestGet2DCenter_arrayIAtom() } [TestMethod()] - public void TestGet2DCenter_IRingSet() + public void TestGet2DCenterIRingSet() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); - IRing ac = Default.ChemObjectBuilder.Instance.NewRing(); + IRing ac = ChemObjectBuilder.Instance.NewRing(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); - IRingSet ringset = Default.ChemObjectBuilder.Instance.NewRingSet(); + IRingSet ringset = ChemObjectBuilder.Instance.NewRingSet(); ringset.Add(ac); Vector2 p = GeometryUtil.Get2DCenter(ac); Assert.AreEqual(p.X, 1.0, .1); @@ -360,13 +360,13 @@ public void TestGet2DCenter_IRingSet() } [TestMethod()] - public void TestGet2DCenter_Iterator() + public void TestGet2DCenterIterator() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); Vector2 p = GeometryUtil.Get2DCenter(ac.Atoms); @@ -375,7 +375,7 @@ public void TestGet2DCenter_Iterator() } [TestMethod()] - public void TestHas2DCoordinates_IAtom() + public void TestHas2DCoordinatesIAtom() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); @@ -387,7 +387,7 @@ public void TestHas2DCoordinates_IAtom() } [TestMethod()] - public void TestHas2DCoordinates_IBond() + public void TestHas2DCoordinatesIBond() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); @@ -405,7 +405,7 @@ public void TestHas2DCoordinates_IBond() } [TestMethod()] - public void TestHas2DCoordinatesNew_IAtomContainer() + public void TestHas2DCoordinatesNewIAtomContainer() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); @@ -436,7 +436,7 @@ public void TestHas2DCoordinatesNew_IAtomContainer() } [TestMethod()] - public void TestHas3DCoordinates_IAtomContainer() + public void TestHas3DCoordinatesIAtomContainer() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 1); @@ -458,7 +458,7 @@ public void TestHas3DCoordinates_IAtomContainer() } [TestMethod()] - public void TestHas3DCoordinates_EmptyAtomContainer() + public void TestHas3DCoordinatesEmptyAtomContainer() { IAtomContainer container = new AtomContainer(); Assert.IsFalse(GeometryUtil.Has3DCoordinates(container)); @@ -466,7 +466,7 @@ public void TestHas3DCoordinates_EmptyAtomContainer() } [TestMethod()] - public void Get3DCoordinateCoverage_EmptyAtomContainer() + public void Get3DCoordinateCoverageEmptyAtomContainer() { IAtomContainer container = new AtomContainer(); Assert.AreEqual(GeometryUtil.CoordinateCoverage.None, GeometryUtil.Get3DCoordinateCoverage(container)); @@ -475,7 +475,7 @@ public void Get3DCoordinateCoverage_EmptyAtomContainer() } [TestMethod()] - public void Get3DCoordinateCoverage_Partial() + public void Get3DCoordinateCoveragePartial() { IAtomContainer container = new AtomContainer(); @@ -494,7 +494,7 @@ public void Get3DCoordinateCoverage_Partial() } [TestMethod()] - public void Get3DCoordinateCoverage_Full() + public void Get3DCoordinateCoverageFull() { IAtomContainer container = new AtomContainer(); @@ -514,7 +514,7 @@ public void Get3DCoordinateCoverage_Full() } [TestMethod()] - public void Get3DCoordinateCoverage_None_2D() + public void Get3DCoordinateCoverageNone2D() { IAtomContainer container = new AtomContainer(); @@ -534,13 +534,13 @@ public void Get3DCoordinateCoverage_None_2D() } [TestMethod()] - public void TestTranslateAllPositive_IAtomContainer_HashMap() + public void TestTranslateAllPositiveIAtomContainerHashMap() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(-1, -1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); GeometryUtil.TranslateAllPositive(ac); @@ -551,21 +551,21 @@ public void TestTranslateAllPositive_IAtomContainer_HashMap() } [TestMethod()] - public void TestGetLength2D_IBond_HashMap() + public void TestGetLength2DIBondHashMap() { Atom atom1 = new Atom("C"); atom1.Point2D = new Vector2(-1, -1); Atom atom2 = new Atom("C"); atom2.Point2D = new Vector2(1, 0); IBond bond = new Bond(atom1, atom2); - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(atom1); ac.Atoms.Add(atom2); Assert.AreEqual(GeometryUtil.GetLength2D(bond), 2.23, 0.01); } [TestMethod()] - public void TestGetClosestAtom_Multiatom() + public void TestGetClosestAtomMultiatom() { IAtom atom1 = new Atom("C"); atom1.Point2D = new Vector2(-1, -1); @@ -583,7 +583,7 @@ public void TestGetClosestAtom_Multiatom() } [TestMethod()] - public void TestGetClosestAtom_Double_Double_IAtomContainer_IAtom() + public void TestGetClosestAtomDoubleDoubleIAtomContainerIAtom() { IAtom atom1 = new Atom("C"); atom1.Point2D = new Vector2(1, 0); @@ -600,7 +600,7 @@ public void TestGetClosestAtom_Double_Double_IAtomContainer_IAtom() /// Tests if not the central atom is returned as closest atom. /// [TestMethod()] - public void TestGetClosestAtom_IAtomContainer_IAtom() + public void TestGetClosestAtomIAtomContainerIAtom() { IAtom atom1 = new Atom("C"); atom1.Point2D = new Vector2(-1, -1); @@ -614,7 +614,7 @@ public void TestGetClosestAtom_IAtomContainer_IAtom() } [TestMethod()] - public void TestShiftContainerHorizontal_IAtomContainer_Rectangle2D_Rectangle2D_Double() + public void TestShiftContainerHorizontalIAtomContainerRectangle2DRectangle2DDouble() { IAtom atom1 = new Atom("C"); atom1.Point2D = new Vector2(0, 1); @@ -646,7 +646,7 @@ public void TestShiftContainerHorizontal_IAtomContainer_Rectangle2D_Rectangle2D_ /// // @ Thrown when the cloning failed. [TestMethod()] - public void TestShiftContainerHorizontal_Two_vertical_molecules() + public void TestShiftContainerHorizontalTwoverticalmolecules() { IAtom atom1 = new Atom("C"); atom1.Point2D = Vector2.Zero; @@ -673,7 +673,7 @@ public void TestShiftContainerHorizontal_Two_vertical_molecules() } [TestMethod()] - public void TestGetBondLengthAverage_IReaction() + public void TestGetBondLengthAverageIReaction() { IAtom atom1 = new Atom("C"); atom1.Point2D = Vector2.Zero; @@ -693,7 +693,7 @@ public void TestGetBondLengthAverage_IReaction() /// s in the IReaction. /// [TestMethod()] - public void TestGetBondLengthAverage_MultiReaction() + public void TestGetBondLengthAverageMultiReaction() { IReaction reaction = new Reaction(); @@ -723,7 +723,7 @@ public void TestGetBondLengthAverage_MultiReaction() } [TestMethod()] - public void TestShiftReactionVertical_IAtomContainer_Rectangle2D_Rectangle2D_Double() + public void TestShiftReactionVerticalIAtomContainerRectangle2DRectangle2DDouble() { IAtom atom1 = new Atom("C"); atom1.Point2D = new Vector2(0, 1); @@ -760,7 +760,7 @@ public void TestShiftReactionVertical_IAtomContainer_Rectangle2D_Rectangle2D_Dou /// // @ Thrown when the cloning failed. [TestMethod()] - public void TestShiftReactionVertical_Two_horizontal_molecules() + public void TestShiftReactionVerticalTwohorizontalmolecules() { IAtom atom1 = new Atom("C"); atom1.Point2D = Vector2.Zero; @@ -772,8 +772,8 @@ public void TestShiftReactionVertical_Two_horizontal_molecules() react1.Atoms.Add(atom1); react1.Atoms.Add(atom2); react1.AddBond(react1.Atoms[0], react1.Atoms[1], BondOrder.Single); - IReaction reaction2 = (IReaction)reaction.Clone(); - IAtomContainer react2 = reaction2.Reactants[0]; + var reaction2 = (IReaction)reaction.Clone(); + var react2 = reaction2.Reactants[0]; // shift the second reaction up GeometryUtil.ShiftReactionVertical(reaction2, GeometryUtil.GetMinMax(react2), GeometryUtil.GetMinMax(react1), @@ -890,16 +890,16 @@ public void MedianBondLengthWithZeroLengthBonds() Assert.AreEqual(1d, GeometryUtil.GetBondLengthMedian(container)); } - private IAtom AtomAt(Vector2? p) + private static IAtom AtomAt(Vector2? p) { - IAtom atom = new Atom("C"); + var atom = new Atom("C"); atom.Point2D = p; return atom; } - private int AlignmentTestHelper(IAtom zero, params IAtom[] pos) + private static int AlignmentTestHelper(IAtom zero, params IAtom[] pos) { - IAtomContainer mol = new AtomContainer(); + var mol = new AtomContainer(); mol.Atoms.Add(zero); foreach (var atom in pos) { diff --git a/NCDKTests/Graphs/AllPairsShortestPathsTest.cs b/NCDKTests/Graphs/AllPairsShortestPathsTest.cs index 16e90984..2ae61e6e 100644 --- a/NCDKTests/Graphs/AllPairsShortestPathsTest.cs +++ b/NCDKTests/Graphs/AllPairsShortestPathsTest.cs @@ -23,7 +23,7 @@ */ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Templates; using System; @@ -52,9 +52,9 @@ public virtual void TestConstruction_Empty() for (int j = -10; j < 10; j++) { - Assert.IsTrue(Compares.AreEqual(new int[0][], asp.From(i).GetPathsTo(0))); - Assert.IsTrue(Compares.AreEqual(new int[0], asp.From(i).GetPathTo(0))); - Assert.IsTrue(Compares.AreEqual(new IAtom[0], asp.From(i).GetAtomsTo(0))); + Assert.IsTrue(Compares.AreEqual(Array.Empty(), asp.From(i).GetPathsTo(0))); + Assert.IsTrue(Compares.AreEqual(Array.Empty(), asp.From(i).GetPathTo(0))); + Assert.IsTrue(Compares.AreEqual(Array.Empty(), asp.From(i).GetAtomsTo(0))); Assert.AreEqual(0, asp.From(i).GetNPathsTo(j)); Assert.AreEqual(int.MaxValue, asp.From(i).GetDistanceTo(j)); diff --git a/NCDKTests/Graphs/AtomContainerAtomPermutorTest.cs b/NCDKTests/Graphs/AtomContainerAtomPermutorTest.cs index 941809ae..2816603e 100644 --- a/NCDKTests/Graphs/AtomContainerAtomPermutorTest.cs +++ b/NCDKTests/Graphs/AtomContainerAtomPermutorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Graphs { diff --git a/NCDKTests/Graphs/AtomContainerBondPermutorTest.cs b/NCDKTests/Graphs/AtomContainerBondPermutorTest.cs index 1ee9e3aa..ac5667d5 100644 --- a/NCDKTests/Graphs/AtomContainerBondPermutorTest.cs +++ b/NCDKTests/Graphs/AtomContainerBondPermutorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Graphs { diff --git a/NCDKTests/Graphs/AtomContainerPermutorTest.cs b/NCDKTests/Graphs/AtomContainerPermutorTest.cs index 92d92b9a..bb551ccf 100644 --- a/NCDKTests/Graphs/AtomContainerPermutorTest.cs +++ b/NCDKTests/Graphs/AtomContainerPermutorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Graphs { diff --git a/NCDKTests/Graphs/ConnectionMatrixTest.cs b/NCDKTests/Graphs/ConnectionMatrixTest.cs index dba0f128..d418c653 100644 --- a/NCDKTests/Graphs/ConnectionMatrixTest.cs +++ b/NCDKTests/Graphs/ConnectionMatrixTest.cs @@ -18,7 +18,7 @@ */ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs.Matrix; using NCDK.Smiles; diff --git a/NCDKTests/Graphs/ConnectivityCheckerTest.cs b/NCDKTests/Graphs/ConnectivityCheckerTest.cs index 31862667..677d6487 100644 --- a/NCDKTests/Graphs/ConnectivityCheckerTest.cs +++ b/NCDKTests/Graphs/ConnectivityCheckerTest.cs @@ -18,7 +18,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.Templates; @@ -161,7 +161,7 @@ public void TestIsConnected_IAtomContainer() [TestMethod()] public void TestIsConnectedArtemisinin1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer container = sp.ParseSmiles("C1CN2CCN(CCCN(CCN(C1)Cc1ccccn1)CC2)C"); Assert.IsTrue(ConnectivityChecker.IsConnected(container)); } diff --git a/NCDKTests/Graphs/CyclesTest.cs b/NCDKTests/Graphs/CyclesTest.cs index 230c1afe..0162e7ab 100644 --- a/NCDKTests/Graphs/CyclesTest.cs +++ b/NCDKTests/Graphs/CyclesTest.cs @@ -1,6 +1,6 @@ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Templates; using System.Collections.Generic; @@ -233,7 +233,7 @@ public virtual void MarkAtomsAndBonds() [TestMethod()] public virtual void Or() { - ICycleFinder cf = Cycles.Or(Cycles.AllFinder, Cycles.GetAllFinder(3)); + ICycleFinder cf = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(3)); IAtomContainer fullerene = GetFullerene(); CheckSize(cf.Find(fullerene, fullerene.Atoms.Count), 120); } @@ -242,7 +242,7 @@ public virtual void Or() public virtual void Unchorded() { IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); - CheckSize(Cycles.GetUnchorded(Cycles.AllFinder).Find(container), 3); + CheckSize(Cycles.GetUnchorded(Cycles.AllSimpleFinder).Find(container), 3); } // load a boron fullerene diff --git a/NCDKTests/Graphs/EssentialCyclesTest.cs b/NCDKTests/Graphs/EssentialCyclesTest.cs index 36b285fe..168f94f0 100644 --- a/NCDKTests/Graphs/EssentialCyclesTest.cs +++ b/NCDKTests/Graphs/EssentialCyclesTest.cs @@ -25,6 +25,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using static NCDK.Graphs.InitialCyclesTest; using NCDK.Common.Base; +using System; namespace NCDK.Graphs { @@ -39,7 +40,7 @@ public virtual void Paths_bicyclo() int[][] bicyclo = Bicyclo; EssentialCycles essential = new EssentialCycles(bicyclo); int[][] paths = essential.GetPaths(); - Assert.IsTrue(Compares.AreDeepEqual(new object[0][], paths)); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths)); } [TestMethod()] diff --git a/NCDKTests/Graphs/GraphUtilTest.cs b/NCDKTests/Graphs/GraphUtilTest.cs index 700ff4b0..af8b1cc5 100644 --- a/NCDKTests/Graphs/GraphUtilTest.cs +++ b/NCDKTests/Graphs/GraphUtilTest.cs @@ -23,7 +23,7 @@ */ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Graphs @@ -133,7 +133,7 @@ public virtual void TestToAdjList_withMap() { IAtomContainer container = Simple; - GraphUtil.EdgeToBondMap map = new GraphUtil.EdgeToBondMap(); + EdgeToBondMap map = new EdgeToBondMap(); int[][] adjacent = GraphUtil.ToAdjList(container, map); Assert.AreEqual(5, adjacent.Length, "adjacency list should have 5 vertices"); diff --git a/NCDKTests/Graphs/GreedyBasisTest.cs b/NCDKTests/Graphs/GreedyBasisTest.cs index 4f300bee..6df7dd76 100644 --- a/NCDKTests/Graphs/GreedyBasisTest.cs +++ b/NCDKTests/Graphs/GreedyBasisTest.cs @@ -25,8 +25,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NCDK.Common.Collections; -using System; using System.Collections; +using System.Linq; using static NCDK.Graphs.InitialCycles; namespace NCDK.Graphs @@ -43,7 +43,7 @@ public virtual void Add() var c2 = new Mock((InitialCycles)null, (ShortestPaths)null, (int[])null); c1.SetupGet(c => c.EdgeVector).Returns(new BitArray(0)); c2.SetupGet(c => c.EdgeVector).Returns(new BitArray(0)); - GreedyBasis basis = new GreedyBasis(2, 0); + var basis = new GreedyBasis(2, 0); Assert.IsTrue(basis.Members.Count == 0); basis.Add(c1.Object); Assert.IsTrue(basis.Members.Contains(c1.Object)); @@ -60,23 +60,13 @@ public virtual void AddAll() c1.SetupGet(c => c.EdgeVector).Returns(new BitArray(0)); c1.SetupGet(c => c.EdgeVector).Returns(new BitArray(0)); c2.SetupGet(c => c.EdgeVector).Returns(new BitArray(0)); - GreedyBasis basis = new GreedyBasis(2, 0); + var basis = new GreedyBasis(2, 0); Assert.IsTrue(basis.Members.Count == 0); basis.AddAll(new[] { c1.Object, c2.Object }); Assert.IsTrue(basis.Members.Contains(c1.Object)); Assert.IsTrue(basis.Members.Contains(c2.Object)); } - [TestMethod()] - [ExpectedException(typeof(NotSupportedException))] - public virtual void UnmodifiableMembers() - { - var c1 = new Mock((InitialCycles)null, (ShortestPaths)null, (int[])null); - c1.SetupGet(c => c.EdgeVector).Returns(new BitArray(0)); - GreedyBasis basis = new GreedyBasis(2, 0); - basis.Members.Add(c1.Object); - } - [TestMethod()] public virtual void SubSetOfBasis() { @@ -89,7 +79,7 @@ public virtual void SubSetOfBasis() c1.SetupGet(c => c.Length).Returns(3); c2.SetupGet(c => c.Length).Returns(3); c3.SetupGet(c => c.Length).Returns(4); - GreedyBasis basis = new GreedyBasis(3, 12); + var basis = new GreedyBasis(3, 12); Assert.IsFalse(basis.IsSubsetOfBasis(c3.Object)); basis.Add(c1.Object); Assert.IsFalse(basis.IsSubsetOfBasis(c3.Object)); @@ -110,7 +100,7 @@ public virtual void Independence() c1.SetupGet(c => c.Length).Returns(3); c2.SetupGet(c => c.Length).Returns(3); c3.SetupGet(c => c.Length).Returns(6); - GreedyBasis basis = new GreedyBasis(3, 12); + var basis = new GreedyBasis(3, 12); Assert.IsTrue(basis.IsIndependent(c1.Object)); Assert.IsTrue(basis.IsIndependent(c2.Object)); Assert.IsTrue(basis.IsIndependent(c3.Object)); @@ -124,7 +114,7 @@ public virtual void Independence() [TestMethod()] public virtual void Size() { - GreedyBasis basis = new GreedyBasis(3, 12); + var basis = new GreedyBasis(3, 12); Assert.AreEqual(0, basis.Count); var c1 = new Mock((InitialCycles)null, (ShortestPaths)null, (int[])null); var c2 = new Mock((InitialCycles)null, (ShortestPaths)null, (int[])null); diff --git a/NCDKTests/Graphs/InChi/InChIGeneratorFactoryTest.cs b/NCDKTests/Graphs/InChi/InChIGeneratorFactoryTest.cs index 7970e1a1..390481fd 100644 --- a/NCDKTests/Graphs/InChi/InChIGeneratorFactoryTest.cs +++ b/NCDKTests/Graphs/InChi/InChIGeneratorFactoryTest.cs @@ -21,7 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; using NCDK.Tools.Manipulator; @@ -120,8 +120,7 @@ public void TestGetInChIGenerator_IAtomContainer_NullList() [TestMethod()] public void TestGetInChIToStructure_String_IChemObjectBuilder() { - InChIToStructure parser = InChIGeneratorFactory.Instance.GetInChIToStructure("InChI=1/ClH/h1H", - Default.ChemObjectBuilder.Instance); + var parser = InChIToStructure.FromInChI("InChI=1/ClH/h1H", ChemObjectBuilder.Instance); Assert.IsNotNull(parser); } @@ -129,16 +128,14 @@ public void TestGetInChIToStructure_String_IChemObjectBuilder() [ExpectedException(typeof(ArgumentNullException))] public void TestGetInChIToStructure_String_IChemObjectBuilder_NullString() { - InChIGeneratorFactory.Instance.GetInChIToStructure("InChI=1/ClH/h1H", - Default.ChemObjectBuilder.Instance, (string)null); + InChIToStructure.FromInChI("InChI=1/ClH/h1H", ChemObjectBuilder.Instance, (string)null); } [TestMethod()] [ExpectedException(typeof(ArgumentNullException))] public void TestGetInChIToStructure_String_IChemObjectBuilder_NullList() { - InChIGeneratorFactory.Instance.GetInChIToStructure("InChI=1/ClH/h1H", - Default.ChemObjectBuilder.Instance, (List)null); + InChIToStructure.FromInChI("InChI=1/ClH/h1H", ChemObjectBuilder.Instance, (List)null); } /// @@ -147,8 +144,7 @@ public void TestGetInChIToStructure_String_IChemObjectBuilder_NullList() [TestMethod()] public void TestGetInChIToStructure_String_IChemObjectBuilder_List() { - InChIToStructure parser = InChIGeneratorFactory.Instance.GetInChIToStructure("InChI=1/ClH/h1H", - Default.ChemObjectBuilder.Instance, new List()); + var parser = InChIToStructure.FromInChI("InChI=1/ClH/h1H", ChemObjectBuilder.Instance, new List()); Assert.IsNotNull(parser); } @@ -156,7 +152,7 @@ public void TestGetInChIToStructure_String_IChemObjectBuilder_List() public void TestSMILESConversion_TopologicalCentre() { // (2R,3R,4S,5R,6S)-3,5-dimethylheptane-2,4,6-triol - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer container = parser.ParseSmiles("C[C@@H](O)[C@@H](C)[C@@H](O)[C@H](C)[C@H](C)O"); InChIGenerator generator = InChIGeneratorFactory.Instance.GetInChIGenerator(container); diff --git a/NCDKTests/Graphs/InChi/InChIGeneratorTest.cs b/NCDKTests/Graphs/InChi/InChIGeneratorTest.cs index c4ebe1ae..805fe51c 100644 --- a/NCDKTests/Graphs/InChi/InChIGeneratorTest.cs +++ b/NCDKTests/Graphs/InChi/InChIGeneratorTest.cs @@ -19,9 +19,9 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; using NCDK.Numerics; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Stereo; using System; diff --git a/NCDKTests/Graphs/InChi/InChIToStructureTest.cs b/NCDKTests/Graphs/InChi/InChIToStructureTest.cs index 7f488ae7..14feca0c 100644 --- a/NCDKTests/Graphs/InChi/InChIToStructureTest.cs +++ b/NCDKTests/Graphs/InChi/InChIToStructureTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; +using NCDK.Silent; using NCDK.Stereo; using System.Linq; @@ -34,14 +35,14 @@ public class InChIToStructureTest : CDKTestCase [TestMethod()] public void TestConstructor_String_IChemObjectBuilder() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH4/h1H4", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH4/h1H4", ChemObjectBuilder.Instance); Assert.IsNotNull(parser); } [TestMethod()] public void TestGetAtomContainer() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH4/h1H4", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH4/h1H4", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; Assert.IsNotNull(container); Assert.AreEqual(1, container.Atoms.Count); @@ -51,7 +52,7 @@ public void TestGetAtomContainer() [TestMethod()] public void NonNullAtomicNumbers() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH4/h1H4", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH4/h1H4", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; foreach (var atom in container.Atoms) { @@ -65,7 +66,7 @@ public void NonNullAtomicNumbers() public void TestFixedHydrogens() { InChIToStructure parser = new InChIToStructure("InChI=1/CH2O2/c2-1-3/h1H,(H,2,3)/f/h2H", - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; Assert.IsNotNull(container); Assert.AreEqual(3, container.Atoms.Count); @@ -76,7 +77,7 @@ public void TestFixedHydrogens() [TestMethod()] public void TestGetReturnStatus_EOF() { - InChIToStructure parser = new InChIToStructure("InChI=1S", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S", ChemObjectBuilder.Instance); var container = parser.AtomContainer; InChIReturnCode returnStatus = parser.ReturnStatus; Assert.IsNotNull(returnStatus); @@ -86,7 +87,7 @@ public void TestGetReturnStatus_EOF() [TestMethod()] public void TestGetMessage() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", ChemObjectBuilder.Instance); var container = parser.AtomContainer; string message = parser.Message; Assert.IsNotNull(message); @@ -95,7 +96,7 @@ public void TestGetMessage() [TestMethod()] public void TestGetMessageNull() { - InChIToStructure parser = new InChIToStructure("InChI=1S", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S", ChemObjectBuilder.Instance); var container = parser.AtomContainer; string message = parser.Message; Assert.IsNull(message); @@ -104,7 +105,7 @@ public void TestGetMessageNull() [TestMethod()] public void TestGetLog() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", ChemObjectBuilder.Instance); var container = parser.AtomContainer; string message = parser.Message; Assert.IsNotNull(message); @@ -113,31 +114,29 @@ public void TestGetLog() [TestMethod()] public void TestGetWarningFlags() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", Default.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", ChemObjectBuilder.Instance); var container = parser.AtomContainer; - ulong[,] flags = parser.WarningFlags; + var flags = parser.WarningFlags; Assert.IsNotNull(flags); - Assert.AreEqual(4, flags.Length); + Assert.AreEqual(4, flags.Count); } [TestMethod()] public void TestGetAtomContainer_IChemObjectBuilder() { - InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", Default.ChemObjectBuilder.Instance); - parser.GenerateAtomContainerFromInChI(Silent.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/CH5/h1H4", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; // test if the created IAtomContainer is done with the Silent module... // OK, this is not typical use, but maybe the above generate method should be private - Assert.IsInstanceOfType(container, Silent.ChemObjectBuilder.Instance.NewAtomContainer().GetType()); + Assert.IsInstanceOfType(container, ChemObjectBuilder.Instance.NewAtomContainer().GetType()); } [TestMethod()] public void AtomicOxygen() { - InChIToStructure parser = new InChIToStructure("InChI=1S/O", Default.ChemObjectBuilder.Instance); - parser.GenerateAtomContainerFromInChI(Silent.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/O", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; - Assert.IsInstanceOfType(container, Silent.ChemObjectBuilder.Instance.NewAtomContainer().GetType()); + Assert.IsInstanceOfType(container, ChemObjectBuilder.Instance.NewAtomContainer().GetType()); Assert.IsNotNull(container.Atoms[0].ImplicitHydrogenCount); Assert.AreEqual(0, container.Atoms[0].ImplicitHydrogenCount); } @@ -145,11 +144,10 @@ public void AtomicOxygen() [TestMethod()] public void HeavyOxygenWater() { - InChIToStructure parser = new InChIToStructure("InChI=1S/H2O/h1H2/i1+2", Default.ChemObjectBuilder.Instance); - parser.GenerateAtomContainerFromInChI(Silent.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1S/H2O/h1H2/i1+2", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; Assert.IsNotNull(container.Atoms[0].ImplicitHydrogenCount); - Assert.IsInstanceOfType(container, Silent.ChemObjectBuilder.Instance.NewAtomContainer().GetType()); + Assert.IsInstanceOfType(container, ChemObjectBuilder.Instance.NewAtomContainer().GetType()); Assert.IsNotNull(container.Atoms[0].ImplicitHydrogenCount); Assert.AreEqual(2, container.Atoms[0].ImplicitHydrogenCount); Assert.AreEqual(18, container.Atoms[0].MassNumber); @@ -158,12 +156,10 @@ public void HeavyOxygenWater() [TestMethod()] public void E_bute_2_ene() { - InChIToStructure parser = new InChIToStructure("InChI=1/C4H8/c1-3-4-2/h3-4H,1-2H3/b4-3+", - Default.ChemObjectBuilder.Instance); - parser.GenerateAtomContainerFromInChI(Silent.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1/C4H8/c1-3-4-2/h3-4H,1-2H3/b4-3+", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; var ses = container.StereoElements.GetEnumerator(); - Assert.IsInstanceOfType(container, Silent.ChemObjectBuilder.Instance.NewAtomContainer().GetType()); + Assert.IsInstanceOfType(container, ChemObjectBuilder.Instance.NewAtomContainer().GetType()); Assert.IsTrue(ses.MoveNext()); var se = ses.Current; Assert.IsInstanceOfType(se, typeof(IDoubleBondStereochemistry)); @@ -173,12 +169,10 @@ public void E_bute_2_ene() [TestMethod()] public void Z_bute_2_ene() { - InChIToStructure parser = new InChIToStructure("InChI=1/C4H8/c1-3-4-2/h3-4H,1-2H3/b4-3-", - Default.ChemObjectBuilder.Instance); - parser.GenerateAtomContainerFromInChI(Silent.ChemObjectBuilder.Instance); + InChIToStructure parser = new InChIToStructure("InChI=1/C4H8/c1-3-4-2/h3-4H,1-2H3/b4-3-", ChemObjectBuilder.Instance); IAtomContainer container = parser.AtomContainer; var ses = container.StereoElements.GetEnumerator(); - Assert.IsInstanceOfType(container, Silent.ChemObjectBuilder.Instance.NewAtomContainer().GetType()); + Assert.IsInstanceOfType(container, ChemObjectBuilder.Instance.NewAtomContainer().GetType()); Assert.IsTrue(ses.MoveNext()); var se = ses.Current; Assert.IsInstanceOfType(se, typeof(IDoubleBondStereochemistry)); diff --git a/NCDKTests/Graphs/InitialCyclesTest.cs b/NCDKTests/Graphs/InitialCyclesTest.cs index 718d0784..e03dd2be 100644 --- a/NCDKTests/Graphs/InitialCyclesTest.cs +++ b/NCDKTests/Graphs/InitialCyclesTest.cs @@ -27,6 +27,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System; namespace NCDK.Graphs { @@ -36,19 +37,19 @@ public class InitialCyclesTest [TestMethod()] public virtual void Lengths_empty() { - Assert.IsFalse(new InitialCycles(new int[0][]).Lengths.Count() > 0); + Assert.IsFalse(new InitialCycles(Array.Empty()).Lengths.Count() > 0); } [TestMethod()] public virtual void CyclesOfLength_empty() { - Assert.IsTrue(new InitialCycles(new int[0][]).GetCyclesOfLength(0).Count() == 0); + Assert.IsTrue(new InitialCycles(Array.Empty()).GetCyclesOfLength(0).Count() == 0); } [TestMethod()] public virtual void Graph() { - int[][] g = new int[0][]; + int[][] g = Array.Empty(); Assert.AreSame(g, new InitialCycles(g).Graph); } @@ -387,7 +388,7 @@ public virtual void EdgeToString() } internal static int[][] K1 - => new int[][] { new int[] { } }; + => new int[][] { Array.Empty() }; /// /// Simple undirected graph where every pair of of the four vertices is diff --git a/NCDKTests/Graphs/Invariant/CanonicalLabelerTest.cs b/NCDKTests/Graphs/Invariant/CanonicalLabelerTest.cs index 87c2c789..701e4a05 100644 --- a/NCDKTests/Graphs/Invariant/CanonicalLabelerTest.cs +++ b/NCDKTests/Graphs/Invariant/CanonicalLabelerTest.cs @@ -19,8 +19,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -37,7 +37,7 @@ namespace NCDK.Graphs.Invariant [TestClass()] public class CanonicalLabelerTest : CDKTestCase { - private SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + private SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); private CanonicalLabeler labeler = new CanonicalLabeler(); public CanonicalLabelerTest() @@ -61,14 +61,14 @@ public void TestCanonLabel_IAtomContainer() labeler.CanonLabel(molecule); foreach (var atom in molecule.Atoms) { - Assert.IsNotNull(atom.GetProperty(InvPair.CanonicalLabelKey)); + Assert.IsNotNull(atom.GetProperty(InvPair.CanonicalLabelPropertyKey)); } - Assert.AreEqual(3, molecule.Atoms[0].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(2, molecule.Atoms[1].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(1, molecule.Atoms[2].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(4, molecule.Atoms[3].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(5, molecule.Atoms[4].GetProperty(InvPair.CanonicalLabelKey)); + Assert.AreEqual(3, molecule.Atoms[0].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(2, molecule.Atoms[1].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(1, molecule.Atoms[2].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(4, molecule.Atoms[3].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(5, molecule.Atoms[4].GetProperty(InvPair.CanonicalLabelPropertyKey)); } /// @@ -83,13 +83,13 @@ public void TestSomeMoleculeWithDifferentStartingOrder() labeler.CanonLabel(molecule); foreach (var atom in molecule.Atoms) { - Assert.IsNotNull(atom.GetProperty(InvPair.CanonicalLabelKey)); + Assert.IsNotNull(atom.GetProperty(InvPair.CanonicalLabelPropertyKey)); } - Assert.AreEqual(1, molecule.Atoms[0].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(2, molecule.Atoms[1].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(3, molecule.Atoms[2].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(4, molecule.Atoms[3].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(5, molecule.Atoms[4].GetProperty(InvPair.CanonicalLabelKey)); + Assert.AreEqual(1, molecule.Atoms[0].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(2, molecule.Atoms[1].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(3, molecule.Atoms[2].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(4, molecule.Atoms[3].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(5, molecule.Atoms[4].GetProperty(InvPair.CanonicalLabelPropertyKey)); } // @cdk.bug 1014344 @@ -119,7 +119,7 @@ public void TestStabilityAfterRoundtrip() atoms2.MoveNext(); IAtom atom1 = atoms1.Current; IAtom atom2 = atoms2.Current; - Assert.AreEqual(atom1.GetProperty(InvPair.CanonicalLabelKey), atom2.GetProperty(InvPair.CanonicalLabelKey)); + Assert.AreEqual(atom1.GetProperty(InvPair.CanonicalLabelPropertyKey), atom2.GetProperty(InvPair.CanonicalLabelPropertyKey)); } } @@ -146,21 +146,21 @@ protected override void AddImplicitHydrogens(IAtomContainer container) [TestCategory("SlowTest")] public void TestBug2944519() { - IAtomContainer ac = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac = ChemObjectBuilder.Instance.NewAtomContainer(); ac.Atoms.Add(ac.Builder.NewAtom("C")); ac.Atoms.Add(ac.Builder.NewAtom("O")); ac.AddBond(ac.Atoms[0], ac.Atoms[1], BondOrder.Single); CanonicalLabeler canLabler = new CanonicalLabeler(); canLabler.CanonLabel(ac); - IAtomContainer ac2 = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer ac2 = ChemObjectBuilder.Instance.NewAtomContainer(); ac2.Atoms.Add(ac2.Builder.NewAtom("O")); ac2.Atoms.Add(ac2.Builder.NewAtom("C")); ac2.AddBond(ac2.Atoms[0], ac2.Atoms[1], BondOrder.Single); canLabler.CanonLabel(ac2); - Assert.AreEqual(ac.Atoms[0].GetProperty(InvPair.CanonicalLabelKey), - ac2.Atoms[1].GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(ac.Atoms[1].GetProperty(InvPair.CanonicalLabelKey), - ac2.Atoms[0].GetProperty(InvPair.CanonicalLabelKey)); + Assert.AreEqual(ac.Atoms[0].GetProperty(InvPair.CanonicalLabelPropertyKey), + ac2.Atoms[1].GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(ac.Atoms[1].GetProperty(InvPair.CanonicalLabelPropertyKey), + ac2.Atoms[0].GetProperty(InvPair.CanonicalLabelPropertyKey)); } } } diff --git a/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs b/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs index 04f758cf..f3dd96ac 100644 --- a/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs +++ b/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs @@ -15,16 +15,15 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; - using System.Diagnostics; namespace NCDK.Graphs.Invariant @@ -37,7 +36,6 @@ namespace NCDK.Graphs.Invariant public class ConjugatedPiSystemsDetectorTest : CDKTestCase { private static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private static LonePairElectronChecker lpcheck = new LonePairElectronChecker(); [TestMethod()] public void TestDetectButadiene() @@ -265,7 +263,7 @@ public void TestAceticAcid() mol = (new SmilesParser(builder)).ParseSmiles("CC(=O)O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -299,7 +297,7 @@ public void TestNN_dimethylaniline_cation() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -317,7 +315,7 @@ public void Test1_fluorobutadienene() IAtomContainer mol = (new SmilesParser(builder)).ParseSmiles("FC=CC=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -337,7 +335,7 @@ public void TestEthyne_difluoro() mol = (new SmilesParser(builder)).ParseSmiles("FC#CF"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -377,7 +375,7 @@ public void Test3Aminomethane_cation() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -392,7 +390,7 @@ public void Test3Aminomethane_cation() private IAtomContainer ReadCMLMolecule(string filename) { IAtomContainer mol = null; - Debug.WriteLine("Filename: " + filename); + Debug.WriteLine($"Filename: {filename}"); var ins = ResourceLoader.GetAsStream(filename); CMLReader reader = new CMLReader(ins); @@ -422,7 +420,7 @@ public void TestCyanoallene() mol = (new SmilesParser(builder)).ParseSmiles("C=C=CC#N"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -451,7 +449,7 @@ public void TestChargeWithProtonExplicit() SmilesParser sp = new SmilesParser(builder); IAtomContainer mol = sp.ParseSmiles("[H]C([H])=C([H])[C+]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -479,7 +477,7 @@ public void TestChargeWithProtonImplicit() SmilesParser sp = new SmilesParser(builder); IAtomContainer mol = sp.ParseSmiles("C=C[C+]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); diff --git a/NCDKTests/Graphs/Invariant/EquivalentClassPartitionerTest.cs b/NCDKTests/Graphs/Invariant/EquivalentClassPartitionerTest.cs index 23468646..4143db5d 100644 --- a/NCDKTests/Graphs/Invariant/EquivalentClassPartitionerTest.cs +++ b/NCDKTests/Graphs/Invariant/EquivalentClassPartitionerTest.cs @@ -16,17 +16,15 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Templates; using NCDK.Tools.Manipulator; -using System.Linq; - namespace NCDK.Graphs.Invariant { /// @@ -244,7 +242,7 @@ public void TestPseudoAtoms() var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol = reader.Read(mol); Assert.IsNotNull(mol); diff --git a/NCDKTests/Graphs/Invariant/InChINumbersToolsTest.cs b/NCDKTests/Graphs/Invariant/InChINumbersToolsTest.cs index 63bc4781..0296a6ef 100644 --- a/NCDKTests/Graphs/Invariant/InChINumbersToolsTest.cs +++ b/NCDKTests/Graphs/Invariant/InChINumbersToolsTest.cs @@ -20,7 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NCDK.Common.Base; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs.InChI; using NCDK.Smiles; @@ -68,7 +68,7 @@ public void TestHydrogens() [TestMethod()] public void TestGlycine() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = parser.ParseSmiles("C(C(=O)O)N"); long[] numbers = InChINumbersTools.GetNumbers(atomContainer); Assert.AreEqual(5, numbers.Length); @@ -82,7 +82,7 @@ public void TestGlycine() [TestMethod()] public void TestGlycine_uSmiles() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = parser.ParseSmiles("C(C(=O)O)N"); long[] numbers = InChINumbersTools.GetNumbers(atomContainer); Assert.AreEqual(5, numbers.Length); @@ -96,7 +96,7 @@ public void TestGlycine_uSmiles() [TestMethod()] public void FixedH() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = parser.ParseSmiles("N1C=NC2=CC=CC=C12"); string auxInfo = InChINumbersTools.AuxInfo(atomContainer, InChIOption.FixedH); string expected = "AuxInfo=1/1/" + "N:6,7,5,8,2,4,9,3,1/" + "E:(1,2)(3,4)(6,7)(8,9)/" + "F:7,6,8,5,2,9,4,1,3/" diff --git a/NCDKTests/Graphs/Invariant/MorganNumbersToolsTest.cs b/NCDKTests/Graphs/Invariant/MorganNumbersToolsTest.cs index c4563576..ff6d60ae 100644 --- a/NCDKTests/Graphs/Invariant/MorganNumbersToolsTest.cs +++ b/NCDKTests/Graphs/Invariant/MorganNumbersToolsTest.cs @@ -18,8 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; -using NCDK.Graphs.Canon; +using NCDK.Silent; using NCDK.IO; using NCDK.Templates; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/Graphs/JumboPathGraphTest.cs b/NCDKTests/Graphs/JumboPathGraphTest.cs index f4f072a1..99ee8f39 100644 --- a/NCDKTests/Graphs/JumboPathGraphTest.cs +++ b/NCDKTests/Graphs/JumboPathGraphTest.cs @@ -40,7 +40,7 @@ public virtual void NullMGraph() { try { - new JumboPathGraph(null, new int[0], 0); + new JumboPathGraph(null, Array.Empty(), 0); } catch (TargetInvocationException e) { @@ -54,7 +54,7 @@ public virtual void LimitTooLow() { try { - new JumboPathGraph(new int[4][], new int[0], -1); + new JumboPathGraph(new int[4][], Array.Empty(), -1); } catch (TargetInvocationException e) { @@ -68,7 +68,7 @@ public virtual void LimitTooHigh() { try { - new JumboPathGraph(new int[4][], new int[0], 5); + new JumboPathGraph(new int[4][], Array.Empty(), 5); } catch (TargetInvocationException e) { diff --git a/NCDKTests/Graphs/Matrix/TopologicalMatrixTest.cs b/NCDKTests/Graphs/Matrix/TopologicalMatrixTest.cs index 432bc9bd..4eb9c26a 100644 --- a/NCDKTests/Graphs/Matrix/TopologicalMatrixTest.cs +++ b/NCDKTests/Graphs/Matrix/TopologicalMatrixTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System; diff --git a/NCDKTests/Graphs/PathToolsTest.cs b/NCDKTests/Graphs/PathToolsTest.cs index 458bf5a6..031c3300 100644 --- a/NCDKTests/Graphs/PathToolsTest.cs +++ b/NCDKTests/Graphs/PathToolsTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Collections; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.Templates; @@ -85,25 +85,24 @@ public virtual void TestGetShortestPath_IAtomContainer_IAtom_IAtom() IAtomContainer atomContainer = null; IAtom start = null; IAtom end = null; - IList path = null; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); atomContainer = sp.ParseSmiles("CCCC"); start = atomContainer.Atoms[0]; end = atomContainer.Atoms[3]; - path = PathTools.GetShortestPath(atomContainer, start, end); - Assert.AreEqual(4, path.Count()); + var path = PathTools.GetShortestPath(atomContainer, start, end); + Assert.AreEqual(4, path.Count); atomContainer = sp.ParseSmiles("CC(N)CC"); start = atomContainer.Atoms[0]; end = atomContainer.Atoms[2]; path = PathTools.GetShortestPath(atomContainer, start, end); - Assert.AreEqual(3, path.Count()); + Assert.AreEqual(3, path.Count); atomContainer = sp.ParseSmiles("C1C(N)CC1"); start = atomContainer.Atoms[0]; end = atomContainer.Atoms[2]; path = PathTools.GetShortestPath(atomContainer, start, end); - Assert.AreEqual(3, path.Count()); + Assert.AreEqual(3, path.Count); } [TestMethod()] @@ -115,14 +114,14 @@ public virtual void TestGetShortestPath_Middle() IAtomContainer testMolecule = new AtomContainer(); reader.Read(testMolecule); - IList path = PathTools.GetShortestPath(testMolecule, testMolecule.Atoms[0], testMolecule.Atoms[9]); - Assert.AreEqual(10, path.Count()); + var path = PathTools.GetShortestPath(testMolecule, testMolecule.Atoms[0], testMolecule.Atoms[9]); + Assert.AreEqual(10, path.Count); path = PathTools.GetShortestPath(testMolecule, testMolecule.Atoms[1], testMolecule.Atoms[9]); - Assert.AreEqual(9, path.Count()); + Assert.AreEqual(9, path.Count); path = PathTools.GetShortestPath(testMolecule, testMolecule.Atoms[9], testMolecule.Atoms[0]); - Assert.AreEqual(10, path.Count()); + Assert.AreEqual(10, path.Count); } [TestMethod()] @@ -277,7 +276,7 @@ public virtual void TestDepthFirstTargetSearch_IAtomContainer_IAtom_IAtom_IAtomC foreach (var atom in molecule.Atoms) atom.IsVisited = false; - IAtomContainer paths = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer paths = ChemObjectBuilder.Instance.NewAtomContainer(); IAtom root = molecule.Atoms[0]; IAtom target = null; diff --git a/NCDKTests/Graphs/Rebond/BsptTest.cs b/NCDKTests/Graphs/Rebond/BsptTest.cs index 1be571d7..685b9262 100644 --- a/NCDKTests/Graphs/Rebond/BsptTest.cs +++ b/NCDKTests/Graphs/Rebond/BsptTest.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using static NCDK.Graphs.Rebond.RebondTool; diff --git a/NCDKTests/Graphs/Rebond/RebondToolTest.cs b/NCDKTests/Graphs/Rebond/RebondToolTest.cs index a1d38472..ff2b1a89 100644 --- a/NCDKTests/Graphs/Rebond/RebondToolTest.cs +++ b/NCDKTests/Graphs/Rebond/RebondToolTest.cs @@ -20,7 +20,7 @@ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Graphs.Rebond { diff --git a/NCDKTests/Graphs/RegularPathGraphTest.cs b/NCDKTests/Graphs/RegularPathGraphTest.cs index 7d3664b9..7085e2f3 100644 --- a/NCDKTests/Graphs/RegularPathGraphTest.cs +++ b/NCDKTests/Graphs/RegularPathGraphTest.cs @@ -40,7 +40,7 @@ public virtual void NullMGraph() { try { - new RegularPathGraph(null, new int[0], 0); + new RegularPathGraph(null, Array.Empty(), 0); } catch (TargetInvocationException e) { @@ -54,7 +54,7 @@ public virtual void LimitTooLow() { try { - new RegularPathGraph(new int[4][], new int[0], -1); + new RegularPathGraph(new int[4][], Array.Empty(), -1); } catch (TargetInvocationException e) { @@ -68,7 +68,7 @@ public virtual void LimitTooHigh() { try { - new RegularPathGraph(new int[4][], new int[0], 5); + new RegularPathGraph(new int[4][], Array.Empty(), 5); } catch (TargetInvocationException e) { diff --git a/NCDKTests/Graphs/ShortestPathsTest.cs b/NCDKTests/Graphs/ShortestPathsTest.cs index b916890f..21c1e680 100644 --- a/NCDKTests/Graphs/ShortestPathsTest.cs +++ b/NCDKTests/Graphs/ShortestPathsTest.cs @@ -24,7 +24,7 @@ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Templates; using System; @@ -37,8 +37,8 @@ public class ShortestPathsTest public virtual void TestConstructor_Container_Empty() { ShortestPaths sp = new ShortestPaths(new AtomContainer(), new Atom()); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], sp.GetPathTo(1))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], sp.GetPathsTo(1))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), sp.GetPathTo(1))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), sp.GetPathsTo(1))); Assert.AreEqual(0, sp.GetNPathsTo(1)); Assert.AreEqual(int.MaxValue, sp.GetDistanceTo(1)); } @@ -154,12 +154,12 @@ public virtual void TestIsPrecedingPathTo() } [TestMethod()] - [ExpectedException(typeof(IndexOutOfRangeException))] public virtual void TestIsPrecedingPathTo_OutOfBounds() { IAtomContainer benzene = TestMoleculeFactory.MakeBenzene(); ShortestPaths paths = new ShortestPaths(benzene, benzene.Atoms[0]); Assert.IsFalse(paths.IsPrecedingPathTo(-1)); + Assert.IsFalse(paths.IsPrecedingPathTo(10)); } /// @@ -271,7 +271,7 @@ public virtual void TestPathTo_Int_OutOfBoundsIndex() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(20))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(20))); } [TestMethod()] @@ -279,7 +279,7 @@ public virtual void TestPathTo_Int_NegativeIndex() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(-1))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(-1))); } [TestMethod()] @@ -287,7 +287,7 @@ public virtual void TestPathTo_Atom_MissingAtom() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(new Atom("C")))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(new Atom("C")))); } [TestMethod()] @@ -295,7 +295,7 @@ public virtual void TestPathTo_Atom_Null() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(null))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(null))); } [TestMethod()] @@ -312,11 +312,11 @@ public virtual void TestPathTo_Atom_Disconnected() Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 1, 4 }, paths.GetPathTo(simple.Atoms[4]))); // disconnect fragment should return 0 .Length path - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(simple.Atoms[5]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(simple.Atoms[6]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(simple.Atoms[7]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(simple.Atoms[8]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(simple.Atoms[9]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(simple.Atoms[5]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(simple.Atoms[6]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(simple.Atoms[7]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(simple.Atoms[8]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(simple.Atoms[9]))); } @@ -334,11 +334,11 @@ public virtual void TestPathTo_Int_Disconnected() Assert.IsTrue(Compares.AreDeepEqual(new int[] { 0, 1, 4 }, paths.GetPathTo(4))); // disconnect fragment should return 0 .Length path - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(5))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(6))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(7))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(8))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], paths.GetPathTo(9))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(5))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(6))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(7))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(8))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathTo(9))); } @@ -518,7 +518,7 @@ public virtual void TestPathsTo_Int_OutOfBoundsIndex() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(20))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(20))); } [TestMethod()] @@ -526,7 +526,7 @@ public virtual void TestPathsTo_Int_NegativeIndex() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(-1))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(-1))); } [TestMethod()] @@ -534,7 +534,7 @@ public virtual void TestPathsTo_Atom_MissingAtom() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(new Atom("C")))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(new Atom("C")))); } [TestMethod()] @@ -542,7 +542,7 @@ public virtual void TestPathsTo_Atom_Null() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(null))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(null))); } [TestMethod()] @@ -559,11 +559,11 @@ public virtual void TestPathsTo_Atom_Disconnected() Assert.IsTrue(Compares.AreDeepEqual(new int[][] { new int[] { 0, 1, 4 } }, paths.GetPathsTo(simple.Atoms[4]))); // disconnect fragment should return 0 .Length path - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(simple.Atoms[5]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(simple.Atoms[6]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(simple.Atoms[7]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(simple.Atoms[8]))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(simple.Atoms[9]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(simple.Atoms[5]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(simple.Atoms[6]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(simple.Atoms[7]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(simple.Atoms[8]))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(simple.Atoms[9]))); } @@ -581,11 +581,11 @@ public virtual void TestPathsTo_Int_Disconnected() Assert.IsTrue(Compares.AreDeepEqual(new int[][] { new int[] { 0, 1, 4 } }, paths.GetPathsTo(4))); // disconnect fragment should return 0 .Length path - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(5))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(6))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(7))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(8))); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths.GetPathsTo(9))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(5))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(6))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(7))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(8))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetPathsTo(9))); } @@ -698,11 +698,11 @@ public virtual void TestAtomsTo_Atom_Disconnected() Assert.IsTrue(Compares.AreDeepEqual(new IAtom[] { a, b, e }, paths.GetAtomsTo(e))); // disconnect fragment should return 0 .Length path - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(f))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(g))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(h))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(i))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(j))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(f))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(g))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(h))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(i))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(j))); } @@ -726,11 +726,11 @@ public virtual void TestAtomsTo_Int_Disconnected() Assert.IsTrue(Compares.AreDeepEqual(new IAtom[] { a, b, e }, paths.GetAtomsTo(4))); // disconnect fragment should return 0 .Length path - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(5))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(6))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(7))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(8))); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(9))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(5))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(6))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(7))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(8))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(9))); } @@ -739,7 +739,7 @@ public virtual void TestAtomsTo_Int_OutOfBoundsIndex() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(20))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(20))); } [TestMethod()] @@ -747,7 +747,7 @@ public virtual void TestAtomsTo_Int_NegativeIndex() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(-1))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(-1))); } [TestMethod()] @@ -755,7 +755,7 @@ public virtual void TestAtomsTo_Atom_MissingAtom() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(new Atom("C")))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(new Atom("C")))); } [TestMethod()] @@ -763,7 +763,7 @@ public virtual void TestAtomsTo_Atom_Null() { IAtomContainer simple = Simple(); ShortestPaths paths = new ShortestPaths(simple, simple.Atoms[0]); - Assert.IsTrue(Compares.AreDeepEqual(new IAtom[0], paths.GetAtomsTo(null))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths.GetAtomsTo(null))); } [TestMethod()] diff --git a/NCDKTests/Graphs/SpanningTreeTest.cs b/NCDKTests/Graphs/SpanningTreeTest.cs index 6598158a..bb47a954 100644 --- a/NCDKTests/Graphs/SpanningTreeTest.cs +++ b/NCDKTests/Graphs/SpanningTreeTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Templates; @@ -50,7 +50,7 @@ public SpanningTreeTest() if (ethane == null) { // create ethane - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer ethaneMolecule = builder.NewAtomContainer(); ethaneMolecule.Atoms.Add(builder.NewAtom("C")); ethaneMolecule.Atoms.Add(builder.NewAtom("C")); @@ -92,18 +92,17 @@ public virtual void TestGetBondsAcyclicCount() public virtual void TestGetPath_IAtomContainer_IAtom_IAtom() { IAtomContainer ethaneMol = ethane.GetSpanningTree(); - IAtomContainer path = ethane.GetPath(ethaneMol, ethaneMol.Atoms[0], ethaneMol.Atoms[1]); + IAtomContainer path = SpanningTree.GetPath(ethaneMol, ethaneMol.Atoms[0], ethaneMol.Atoms[1]); Assert.AreEqual(2, path.Atoms.Count); Assert.AreEqual(1, path.Bonds.Count); - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer disconnectedStructure = builder.NewAtomContainer(); disconnectedStructure.Atoms.Add(builder.NewAtom("Na")); disconnectedStructure.Atoms[0].FormalCharge = +1; disconnectedStructure.Atoms.Add(builder.NewAtom("Cl")); disconnectedStructure.Atoms[1].FormalCharge = -1; - path = ethane - .GetPath(disconnectedStructure, disconnectedStructure.Atoms[0], disconnectedStructure.Atoms[1]); + path = SpanningTree.GetPath(disconnectedStructure, disconnectedStructure.Atoms[0], disconnectedStructure.Atoms[1]); Assert.IsNotNull(path); Assert.AreEqual(0, path.Atoms.Count); Assert.AreEqual(0, path.Bonds.Count); diff --git a/NCDKTests/Graphs/TripletShortCyclesTest.cs b/NCDKTests/Graphs/TripletShortCyclesTest.cs index 46ddb20b..b7166782 100644 --- a/NCDKTests/Graphs/TripletShortCyclesTest.cs +++ b/NCDKTests/Graphs/TripletShortCyclesTest.cs @@ -24,6 +24,7 @@ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; using static NCDK.Graphs.InitialCyclesTest; +using System; namespace NCDK.Graphs { @@ -53,9 +54,9 @@ public virtual void Lexicographic() [TestMethod()] public virtual void IsEmpty() { - TripletShortCycles esssr = new TripletShortCycles(new MinimumCycleBasis(new int[0][]), false); + TripletShortCycles esssr = new TripletShortCycles(new MinimumCycleBasis(Array.Empty()), false); int[][] paths = esssr.GetPaths(); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], paths)); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), paths)); } [TestMethod()] diff --git a/NCDKTests/Groups/AtomGroupTests.cs b/NCDKTests/Groups/AtomGroupTests.cs index b4b20a00..3ce25498 100644 --- a/NCDKTests/Groups/AtomGroupTests.cs +++ b/NCDKTests/Groups/AtomGroupTests.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.Groups @@ -32,7 +33,7 @@ public class AtomGroupTests : CDKTestCase { public IAtomContainer GetMol(string smiles) { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); return parser.ParseSmiles(smiles); } diff --git a/NCDKTests/Groups/BondGroupTests.cs b/NCDKTests/Groups/BondGroupTests.cs index 07abe73f..85036df5 100644 --- a/NCDKTests/Groups/BondGroupTests.cs +++ b/NCDKTests/Groups/BondGroupTests.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.Groups @@ -32,14 +33,14 @@ public class BondGroupTests : CDKTestCase { private static readonly IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - public IAtomContainer GetMol(string smiles) + public static IAtomContainer GetMol(string smiles) { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + var parser = new SmilesParser(ChemObjectBuilder.Instance); parser.Kekulise(false); return parser.ParseSmiles(smiles); } - public void Test(IAtomContainer mol, int expected) + public static void Test(IAtomContainer mol, int expected) { BondDiscretePartitionRefiner refiner = new BondDiscretePartitionRefiner(); PermutationGroup group = refiner.GetAutomorphismGroup(mol); diff --git a/NCDKTests/Groups/PermutationGroupTest.cs b/NCDKTests/Groups/PermutationGroupTest.cs index 2e4bd3b8..f43e44b5 100644 --- a/NCDKTests/Groups/PermutationGroupTest.cs +++ b/NCDKTests/Groups/PermutationGroupTest.cs @@ -22,6 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; +using System.Linq; namespace NCDK.Groups { @@ -217,7 +218,7 @@ public void ApplyTest() } class NBacktracker - : PermutationGroup.IBacktracker + : IBacktracker { List all; @@ -249,10 +250,10 @@ public void Apply_FinishEarlyTest() } class FinishEarlyBacktracker - : PermutationGroup.IBacktracker + : IBacktracker { List all; - int max; + readonly int max; public FinishEarlyBacktracker(List all, int max) { diff --git a/NCDKTests/Groups/PermutationTest.cs b/NCDKTests/Groups/PermutationTest.cs index 6e50bc30..880609a4 100644 --- a/NCDKTests/Groups/PermutationTest.cs +++ b/NCDKTests/Groups/PermutationTest.cs @@ -20,9 +20,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Common.Base; + using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Common.Base; using System; +using System.Linq; namespace NCDK.Groups { @@ -35,7 +37,7 @@ public class PermutationTest : CDKTestCase public void SizeNConstructor() { int size = 4; - Permutation p = new Permutation(size); + var p = new Permutation(size); for (int index = 0; index < size; index++) { Assert.AreEqual(index, p[index]); @@ -46,7 +48,7 @@ public void SizeNConstructor() public void ValuesConstructor() { int[] values = new int[] { 1, 0, 3, 2 }; - Permutation p = new Permutation(values); + var p = new Permutation(values); for (int index = 0; index < p.Count; index++) { Assert.AreEqual(values[index], p[index]); @@ -57,31 +59,31 @@ public void ValuesConstructor() public void CloneConstructor() { int[] values = new int[] { 1, 0, 3, 2 }; - Permutation a = new Permutation(values); - Permutation b = new Permutation(a); + var a = new Permutation(values); + var b = new Permutation(a); Assert.AreEqual(a, b); } [TestMethod()] public void EqualsTest() { - Permutation a = new Permutation(1, 2, 0, 3); - Permutation b = new Permutation(1, 2, 0, 3); + var a = new Permutation(1, 2, 0, 3); + var b = new Permutation(1, 2, 0, 3); Assert.AreEqual(a, b); } [TestMethod()] public void EqualsTest_null() { - Permutation a = new Permutation(1, 2, 0, 3); + var a = new Permutation(1, 2, 0, 3); Assert.AreNotSame(a, null); } [TestMethod()] public void EqualsTest_difference() { - Permutation a = new Permutation(1, 2, 0, 3); - Permutation b = new Permutation(1, 0, 2, 3); + var a = new Permutation(1, 2, 0, 3); + var b = new Permutation(1, 0, 2, 3); Assert.AreNotSame(a, b); } @@ -89,7 +91,7 @@ public void EqualsTest_difference() public void IsIdentityTest() { int size = 4; - Permutation p = new Permutation(size); + var p = new Permutation(size); Assert.IsTrue(p.IsIdentity()); } @@ -97,14 +99,14 @@ public void IsIdentityTest() public void SizeTest() { int size = 4; - Permutation p = new Permutation(size); + var p = new Permutation(size); Assert.AreEqual(size, p.Count); } [TestMethod()] public void GetTest() { - Permutation p = new Permutation(1, 0); + var p = new Permutation(1, 0); Assert.AreEqual(1, p[0]); } @@ -112,7 +114,7 @@ public void GetTest() public void GetValuesTest() { int[] values = new int[] { 1, 0, 3, 2 }; - Permutation p = new Permutation(values); + var p = new Permutation(values); Assert.IsTrue(Compares.AreDeepEqual(values, p.Values)); } @@ -121,15 +123,15 @@ public void FirstIndexDiffTest() { int[] valuesA = new int[] { 1, 0, 3, 2 }; int[] valuesB = new int[] { 1, 0, 2, 3 }; - Permutation a = new Permutation(valuesA); - Permutation b = new Permutation(valuesB); + var a = new Permutation(valuesA); + var b = new Permutation(valuesB); Assert.AreEqual(2, a.FirstIndexOfDifference(b)); } [TestMethod()] public void GetOrbitTest() { - Permutation p = new Permutation(4, 6, 1, 3, 2, 5, 0); + var p = new Permutation(4, 6, 1, 3, 2, 5, 0); var orbit = p.GetOrbit(1); Assert.AreEqual(5, orbit.Count); Assert.IsTrue(orbit.Contains(1)); @@ -138,7 +140,7 @@ public void GetOrbitTest() [TestMethod()] public void SetTest() { - Permutation p = new Permutation(1, 0); + var p = new Permutation(1, 0); p[0] = 0; p[1] = 1; Assert.AreEqual(0, p[0]); @@ -149,8 +151,8 @@ public void SetTest() public void SetToTest() { int[] values = new int[] { 1, 0, 3, 2 }; - Permutation a = new Permutation(values); - Permutation b = new Permutation(values.Length); + var a = new Permutation(values); + var b = new Permutation(values.Length); a.SetTo(b); Assert.IsTrue(a.IsIdentity()); } @@ -159,8 +161,8 @@ public void SetToTest() [ExpectedException(typeof(ArgumentException))] public void SetToTest_differentLength() { - Permutation a = new Permutation(1, 0, 2); - Permutation b = new Permutation(0, 1); + var a = new Permutation(1, 0, 2); + var b = new Permutation(0, 1); a.SetTo(b); } @@ -170,9 +172,9 @@ public void MultiplyTest() int[] valuesA = new int[] { 1, 0, 2, 3 }; int[] valuesB = new int[] { 0, 1, 3, 2 }; int[] expectC = new int[] { 1, 0, 3, 2 }; - Permutation a = new Permutation(valuesA); - Permutation b = new Permutation(valuesB); - Permutation c = new Permutation(expectC); + var a = new Permutation(valuesA); + var b = new Permutation(valuesB); + var c = new Permutation(expectC); Assert.AreEqual(c, a.Multiply(b)); } @@ -181,8 +183,8 @@ public void InvertTest() { int[] values = new int[] { 3, 1, 0, 2 }; int[] invert = new int[] { 2, 1, 3, 0 }; - Permutation p = new Permutation(values); - Permutation invP = new Permutation(invert); + var p = new Permutation(values); + var invP = new Permutation(invert); Assert.AreEqual(invP, p.Invert()); } @@ -191,7 +193,7 @@ public void ToCycleStringTest() { int[] values = new int[] { 0, 2, 1, 4, 5, 3, 7, 8, 9, 6 }; string expected = "(0)(1, 2)(3, 4, 5)(6, 7, 8, 9)"; - Permutation p = new Permutation(values); + var p = new Permutation(values); Assert.AreEqual(expected, p.ToCycleString()); } } diff --git a/NCDKTests/Hash/AllEquivalentCyclicSetTest.cs b/NCDKTests/Hash/AllEquivalentCyclicSetTest.cs index 0563aed2..056512ff 100644 --- a/NCDKTests/Hash/AllEquivalentCyclicSetTest.cs +++ b/NCDKTests/Hash/AllEquivalentCyclicSetTest.cs @@ -24,7 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Hash { diff --git a/NCDKTests/Hash/HashCodeScenariosTest.cs b/NCDKTests/Hash/HashCodeScenariosTest.cs index 7a1306ec..476e69aa 100644 --- a/NCDKTests/Hash/HashCodeScenariosTest.cs +++ b/NCDKTests/Hash/HashCodeScenariosTest.cs @@ -23,7 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; using NCDK.IO.Iterator; using NCDK.Stereo; @@ -1087,7 +1087,7 @@ private List ExtractSDF(string path, int exp) Assert.IsNotNull(ins, path + " could not be found in classpath"); - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; EnumerableSDFReader sdf = new EnumerableSDFReader(ins, builder, false); List structures = new List(exp); foreach (var mol in sdf) diff --git a/NCDKTests/Hash/MinimumEquivalentCyclicSetUnionTest.cs b/NCDKTests/Hash/MinimumEquivalentCyclicSetUnionTest.cs index 78f4f571..61bc1ea7 100644 --- a/NCDKTests/Hash/MinimumEquivalentCyclicSetUnionTest.cs +++ b/NCDKTests/Hash/MinimumEquivalentCyclicSetUnionTest.cs @@ -24,7 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Hash { diff --git a/NCDKTests/Hash/PerturbedAtomHashGeneratorTest.cs b/NCDKTests/Hash/PerturbedAtomHashGeneratorTest.cs index 502f7ed6..266ed44c 100644 --- a/NCDKTests/Hash/PerturbedAtomHashGeneratorTest.cs +++ b/NCDKTests/Hash/PerturbedAtomHashGeneratorTest.cs @@ -23,7 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; -using NCDK.Default; +using NCDK.Silent; using NCDK.Hash.Stereo; namespace NCDK.Hash diff --git a/NCDKTests/Hash/Stereo/BasicPermutationParityTest.cs b/NCDKTests/Hash/Stereo/BasicPermutationParityTest.cs index 468daed9..b389f9b7 100644 --- a/NCDKTests/Hash/Stereo/BasicPermutationParityTest.cs +++ b/NCDKTests/Hash/Stereo/BasicPermutationParityTest.cs @@ -45,7 +45,7 @@ public void TestConstruction_Null() [ExpectedException(typeof(ArgumentException))] public void TestConstruction_Empty() { - new BasicPermutationParity(new int[0]); + new BasicPermutationParity(Array.Empty()); } [TestMethod()] diff --git a/NCDKTests/Hash/Stereo/GeometricCumulativeDoubleBondFactoryTest.cs b/NCDKTests/Hash/Stereo/GeometricCumulativeDoubleBondFactoryTest.cs index 47d2fa1c..df8a9667 100644 --- a/NCDKTests/Hash/Stereo/GeometricCumulativeDoubleBondFactoryTest.cs +++ b/NCDKTests/Hash/Stereo/GeometricCumulativeDoubleBondFactoryTest.cs @@ -23,7 +23,7 @@ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Hash.Stereo { diff --git a/NCDKTests/Hash/Stereo/GeometryEncoderTest.cs b/NCDKTests/Hash/Stereo/GeometryEncoderTest.cs index fc06d14f..8a474cff 100644 --- a/NCDKTests/Hash/Stereo/GeometryEncoderTest.cs +++ b/NCDKTests/Hash/Stereo/GeometryEncoderTest.cs @@ -39,7 +39,7 @@ public class GeometryEncoderTest [ExpectedException(typeof(ArgumentException))] public void TestConstruction_Empty() { - new GeometryEncoder(new int[0], new Mock().Object, new Mock().Object); + new GeometryEncoder(Array.Empty(), new Mock().Object, new Mock().Object); } [TestMethod()] diff --git a/NCDKTests/Hash/Stereo/Tetrahedral2DParityTest.cs b/NCDKTests/Hash/Stereo/Tetrahedral2DParityTest.cs index 3cb31d99..769911b0 100644 --- a/NCDKTests/Hash/Stereo/Tetrahedral2DParityTest.cs +++ b/NCDKTests/Hash/Stereo/Tetrahedral2DParityTest.cs @@ -42,14 +42,14 @@ public class Tetrahedral2DParityTest [ExpectedException(typeof(ArgumentException))] public void TestConstruction_InvalidCoords() { - new Tetrahedral2DParity(new Vector2[0], new int[4]); + new Tetrahedral2DParity(Array.Empty(), new int[4]); } [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void TestConstruction_InvalidElev() { - new Tetrahedral2DParity(new Vector2[4], new int[0]); + new Tetrahedral2DParity(new Vector2[4], Array.Empty()); } /// diff --git a/NCDKTests/Hash/Stereo/TetrahedralElementEncoderFactoryTest.cs b/NCDKTests/Hash/Stereo/TetrahedralElementEncoderFactoryTest.cs index 9013280a..18ac8075 100644 --- a/NCDKTests/Hash/Stereo/TetrahedralElementEncoderFactoryTest.cs +++ b/NCDKTests/Hash/Stereo/TetrahedralElementEncoderFactoryTest.cs @@ -66,7 +66,7 @@ public void CreateExplicitH() m_tc.SetupGet(n => n.Stereo).Returns(TetrahedralStereo.Clockwise); m_container.Setup(n => n.StereoElements).Returns(new[] { tc }); - IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, new int[0][]); // graph not used + IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, Array.Empty()); // graph not used Assert.AreEqual(-1, GetGeometricParity(encoder).Parity); // clockwise } @@ -95,7 +95,7 @@ public void CreateImplicitH_back() m_tc.SetupGet(n => n.Stereo).Returns(TetrahedralStereo.Clockwise); m_container.Setup(n => n.StereoElements).Returns(new[] { tc }); - IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, new int[0][]); // graph not used + IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, Array.Empty()); // graph not used Assert.AreEqual(-1, GetGeometricParity(encoder).Parity); // clockwise (we didn't have to move the implied H) } @@ -124,7 +124,7 @@ public void CreateImplicitH_front() m_tc.SetupGet(n => n.Stereo).Returns(TetrahedralStereo.Clockwise); m_container.Setup(n => n.StereoElements).Returns(new[] { tc }); - IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, new int[0][]); // graph not used + IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, Array.Empty()); // graph not used // anti-clockwise (inverted as we had to move the implicit H to the back // with an odd number of inversions) @@ -155,7 +155,7 @@ public void CreateImplicitH_middle() m_tc.SetupGet(n => n.Stereo).Returns(TetrahedralStereo.Clockwise); m_container.Setup(n => n.StereoElements).Returns(new[] { tc }); - IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, new int[0][]); // graph not used + IStereoEncoder encoder = new TetrahedralElementEncoderFactory().Create(container, Array.Empty()); // graph not used // clockwise - we had to move the implied H but we moved it an even // number of times @@ -195,7 +195,7 @@ private static IList ExtractEncoders(IStereoEncoder encoder) } return (IList)field.GetValue(encoder); } - return new IStereoEncoder[0]; + return Array.Empty(); } } } diff --git a/NCDKTests/IO/AbstractReaderFactoryTest.cs b/NCDKTests/IO/AbstractReaderFactoryTest.cs index cf08bccd..58aa3bd6 100644 --- a/NCDKTests/IO/AbstractReaderFactoryTest.cs +++ b/NCDKTests/IO/AbstractReaderFactoryTest.cs @@ -22,7 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Formats; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/IO/CIFReaderTest.cs b/NCDKTests/IO/CIFReaderTest.cs index c1caee6a..bb2f53b2 100644 --- a/NCDKTests/IO/CIFReaderTest.cs +++ b/NCDKTests/IO/CIFReaderTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using System; diff --git a/NCDKTests/IO/CML/CML2Test.cs b/NCDKTests/IO/CML/CML2Test.cs index 3e982c1e..66781917 100644 --- a/NCDKTests/IO/CML/CML2Test.cs +++ b/NCDKTests/IO/CML/CML2Test.cs @@ -22,7 +22,7 @@ * */ using NCDK.Common.Primitives; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using NCDK.Tools.Manipulator; using System.Collections.Generic; diff --git a/NCDKTests/IO/CML/CML2WriterTest.cs b/NCDKTests/IO/CML/CML2WriterTest.cs index c8c8db60..364c195c 100644 --- a/NCDKTests/IO/CML/CML2WriterTest.cs +++ b/NCDKTests/IO/CML/CML2WriterTest.cs @@ -25,7 +25,7 @@ using Moq; using NCDK.Aromaticities; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.Formula; using NCDK.Templates; using NCDK.Tools.Manipulator; @@ -200,7 +200,7 @@ public void TestReactionCustomization() public void TestReactionScheme1() { StringWriter writer = new StringWriter(); - IReactionScheme scheme1 = Default.ChemObjectBuilder.Instance.NewReactionScheme(); + IReactionScheme scheme1 = ChemObjectBuilder.Instance.NewReactionScheme(); scheme1.Id = "rs0"; IReactionScheme scheme2 = scheme1.Builder.NewReactionScheme(); scheme2.Id = "rs1"; @@ -249,7 +249,7 @@ public void TestReactionScheme2() ReactionScheme scheme1 = new ReactionScheme(); scheme1.Id = "rs0"; - IReaction reaction = Default.ChemObjectBuilder.Instance.NewReaction(); + IReaction reaction = ChemObjectBuilder.Instance.NewReaction(); reaction.Id = "r1"; IAtomContainer moleculeA = reaction.Builder.NewAtomContainer(); moleculeA.Id = "A"; @@ -291,7 +291,7 @@ public void TestReactionSchemeWithFormula() ReactionScheme scheme1 = new ReactionScheme(); scheme1.Id = "rs0"; - IReaction reaction = Default.ChemObjectBuilder.Instance.NewReaction(); + IReaction reaction = ChemObjectBuilder.Instance.NewReaction(); reaction.Id = "r1"; IAtomContainer moleculeA = reaction.Builder.NewAtomContainer(); moleculeA.Id = "A"; @@ -341,7 +341,7 @@ public void TestReactionSchemeWithFormula2() ReactionScheme scheme1 = new ReactionScheme(); scheme1.Id = "rs0"; - IReaction reaction = Default.ChemObjectBuilder.Instance.NewReaction(); + IReaction reaction = ChemObjectBuilder.Instance.NewReaction(); reaction.Id = "r1"; IAtomContainer moleculeA = reaction.Builder.NewAtomContainer(); moleculeA.Id = "A"; @@ -416,7 +416,7 @@ public void TestMoleculeSetID() public void TestReactionProperty() { StringWriter writer = new StringWriter(); - IReaction reaction = Default.ChemObjectBuilder.Instance.NewReaction(); + IReaction reaction = ChemObjectBuilder.Instance.NewReaction(); reaction.Id = "r1"; reaction.SetProperty("blabla", "blabla2"); CMLWriter cmlWriter = new CMLWriter(writer); @@ -438,7 +438,7 @@ public void TestReactionProperty() // chain.Id = "rsl1"; // // - // IReaction reaction = Default.ChemObjectBuilder.Instance.NewReaction(); + // IReaction reaction = ChemObjectBuilder.Instance.NewReaction(); // reaction.Id = "r1"; // IAtomContainer moleculeA = reaction.GetNewBuilder().NewAtomContainer(); // moleculeA.Id = "A"; @@ -481,7 +481,7 @@ public void TestReactionProperty() // scheme1.Add(scheme2); // // - // IReaction reaction1 = Default.ChemObjectBuilder.Instance.NewReaction(); + // IReaction reaction1 = ChemObjectBuilder.Instance.NewReaction(); // reaction1.Id = "r1.1"; // IAtomContainer moleculeA = reaction1.GetNewBuilder().NewAtomContainer(); // moleculeA.Id = "A"; diff --git a/NCDKTests/IO/CML/CMLRoundTripTest.cs b/NCDKTests/IO/CML/CMLRoundTripTest.cs index c9ef3c4f..a8f3c04f 100644 --- a/NCDKTests/IO/CML/CMLRoundTripTest.cs +++ b/NCDKTests/IO/CML/CMLRoundTripTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.LibIO.CML; using NCDK.Numerics; using NCDK.Templates; diff --git a/NCDKTests/IO/CML/CMLRoundTripTool.cs b/NCDKTests/IO/CML/CMLRoundTripTool.cs index dce822bf..5834e79f 100644 --- a/NCDKTests/IO/CML/CMLRoundTripTool.cs +++ b/NCDKTests/IO/CML/CMLRoundTripTool.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.LibIO.CML; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/CML/PDBAtomCustomizerTest.cs b/NCDKTests/IO/CML/PDBAtomCustomizerTest.cs index 94d6c25a..c332910e 100644 --- a/NCDKTests/IO/CML/PDBAtomCustomizerTest.cs +++ b/NCDKTests/IO/CML/PDBAtomCustomizerTest.cs @@ -22,7 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.LibIO.CML; using System; using System.IO; diff --git a/NCDKTests/IO/CMLReaderTest.cs b/NCDKTests/IO/CMLReaderTest.cs index 2146d7e2..08350297 100644 --- a/NCDKTests/IO/CMLReaderTest.cs +++ b/NCDKTests/IO/CMLReaderTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -67,7 +67,7 @@ public void TestBug1248() CMLReader reader = new CMLReader(ins); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.IsNotNull(cfile, "ChemFile was Null"); @@ -102,7 +102,7 @@ public void TestBug1245() CMLReader reader = new CMLReader(ins); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.IsNotNull(cfile, "ChemFile was Null"); @@ -159,7 +159,7 @@ public void TestBug1274() CMLReader reader = new CMLReader(ins); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.IsNotNull(cfile, "ChemFile was Null"); @@ -194,7 +194,7 @@ public void TestBug1275() CMLReader reader = new CMLReader(ins); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.IsNotNull(cfile, "ChemFile was Null"); @@ -224,7 +224,7 @@ public void TestWedgeBondParsing() CMLReader reader = new CMLReader(ins); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.IsNotNull(cfile, "ChemFile was Null"); var containers = ChemFileManipulator.GetAllAtomContainers(cfile); Assert.AreEqual(1, containers.Count(), "Expected a single atom container"); @@ -299,7 +299,7 @@ public void TestSFBug1085912_1() CMLReader reader = new CMLReader(new MemoryStream(Encoding.UTF8.GetBytes(cmlContent))); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.IsNotNull(cfile, "ChemFile was Null"); var containers = ChemFileManipulator.GetAllAtomContainers(cfile); Assert.AreEqual(1, containers.Count(), "Expected a single atom container"); @@ -322,7 +322,7 @@ public void TestMixedNamespaces() CMLReader reader = new CMLReader(ins); try { - IChemFile cfile = reader.Read(Default.ChemObjectBuilder.Instance.NewChemFile()); + IChemFile cfile = reader.Read(ChemObjectBuilder.Instance.NewChemFile()); Assert.AreEqual(34, ChemFileManipulator.GetAtomCount(cfile)); Assert.AreEqual(39, ChemFileManipulator.GetBondCount(cfile)); } diff --git a/NCDKTests/IO/CMLWriterFactoryTest.cs b/NCDKTests/IO/CMLWriterFactoryTest.cs index 6e464085..f3dd4662 100644 --- a/NCDKTests/IO/CMLWriterFactoryTest.cs +++ b/NCDKTests/IO/CMLWriterFactoryTest.cs @@ -34,13 +34,13 @@ namespace NCDK.IO [TestClass()] public class CMLWriterFactoryTest { - private WriterFactory factory = new WriterFactory(); + private readonly WriterFactory factory = new WriterFactory(); [TestMethod()] public void TestCMLWriter() { WriterFactory factory = new WriterFactory(); - factory.RegisterWriter(typeof(CMLWriter)); + WriterFactory.RegisterWriter(typeof(CMLWriter)); IChemObjectWriter writer = factory.CreateWriter((IChemFormat)CMLFormat.Instance, new StringWriter()); Assert.IsNotNull(writer); Assert.AreEqual(new CMLWriter(new StringWriter()).GetType().Name, writer.GetType().Name); diff --git a/NCDKTests/IO/CTXReaderTest.cs b/NCDKTests/IO/CTXReaderTest.cs index d95060ae..d56ff164 100644 --- a/NCDKTests/IO/CTXReaderTest.cs +++ b/NCDKTests/IO/CTXReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/ChemObjectIOInstantionTests.cs b/NCDKTests/IO/ChemObjectIOInstantionTests.cs index 6f0e58dc..0b644e3f 100644 --- a/NCDKTests/IO/ChemObjectIOInstantionTests.cs +++ b/NCDKTests/IO/ChemObjectIOInstantionTests.cs @@ -59,7 +59,7 @@ private void LoadFormats() var cls = typeof(IResourceFormat).Assembly.GetType(formatName); if (cls != null) { - IResourceFormat format = (IResourceFormat)cls.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + IResourceFormat format = (IResourceFormat)cls.GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); if (format is IChemFormat) { formats.Add((IChemFormat)format); @@ -127,7 +127,7 @@ private void TryToInstantiate(string className) } catch (ArgumentException) { - Debug.WriteLine("Could not find this class: " + className); + Debug.WriteLine($"Could not find this class: {className}"); // but that's not error, it can mean that it is a Jmol based IO class, and no Jmol is in the classpath } catch (IOException exception) diff --git a/NCDKTests/IO/ChemObjectIOTest.cs b/NCDKTests/IO/ChemObjectIOTest.cs index 0a20e95a..cc526fb9 100644 --- a/NCDKTests/IO/ChemObjectIOTest.cs +++ b/NCDKTests/IO/ChemObjectIOTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Formats; using NCDK.IO.Listener; using NCDK.IO.Setting; @@ -72,33 +72,37 @@ public virtual void TestGetFormat() Assert.IsNotNull(format, "The IChemObjectIO.Format method returned null."); } - private static IChemObject[] acceptableNNChemObjects = + private static IChemObject[] AcceptableNNChemObjects = { new ChemFile(), new ChemModel(), new Silent.AtomContainer(), new Reaction() }; [TestMethod()] public virtual void TestAcceptsAtLeastOneNonotifyObject() { bool oneAccepted = false; - foreach (var obj in acceptableNNChemObjects) + foreach (var obj in AcceptableNNChemObjects) { if (ChemObjectIOToTest.Accepts(obj.GetType())) { oneAccepted = true; } } - Assert.IsTrue(oneAccepted, - "At least one of the following IChemObect's should be accepted: IChemFile, IChemModel, IAtomContainer, IReaction"); + Assert.IsTrue(oneAccepted, "At least one of the following IChemObect's should be accepted: IChemFile, IChemModel, IAtomContainer, IReaction"); } /// static objects, shared between tests - difficult to locate bugs. [Obsolete] - protected static IChemObject[] acceptableChemObjects = {new ChemFile(), new ChemModel(), new Silent.AtomContainer(), - new Reaction(), new RGroupQuery(Default.ChemObjectBuilder.Instance)}; + protected static IChemObject[] acceptableChemObjects = + { + new ChemFile(), + new ChemModel(), + new Silent.AtomContainer(), + new Reaction(), + new RGroupQuery(ChemObjectBuilder.Instance) + }; protected static IChemObject[] AcceptableChemObjects() { - return new IChemObject[]{new ChemFile(), new ChemModel(), new Silent.AtomContainer(), new Reaction(), - new RGroupQuery(Default.ChemObjectBuilder.Instance)}; + return new IChemObject[]{new ChemFile(), new ChemModel(), new Silent.AtomContainer(), new Reaction(), new RGroupQuery(ChemObjectBuilder.Instance)}; } [TestMethod()] diff --git a/NCDKTests/IO/ChemObjectWriterTest.cs b/NCDKTests/IO/ChemObjectWriterTest.cs index 8d0cc432..b164e57d 100644 --- a/NCDKTests/IO/ChemObjectWriterTest.cs +++ b/NCDKTests/IO/ChemObjectWriterTest.cs @@ -21,7 +21,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/IO/CrystClustReaderTest.cs b/NCDKTests/IO/CrystClustReaderTest.cs index 648ddd13..eeb07ea5 100644 --- a/NCDKTests/IO/CrystClustReaderTest.cs +++ b/NCDKTests/IO/CrystClustReaderTest.cs @@ -22,7 +22,7 @@ * */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Diagnostics; using System; diff --git a/NCDKTests/IO/CustomFormat.cs b/NCDKTests/IO/CustomFormat.cs index f355bb86..bdfc4031 100644 --- a/NCDKTests/IO/CustomFormat.cs +++ b/NCDKTests/IO/CustomFormat.cs @@ -22,6 +22,7 @@ */ using NCDK.IO.Formats; using NCDK.Tools; +using System.Collections.Generic; namespace NCDK.IO { @@ -38,7 +39,7 @@ public class CustomFormat : IChemFormat public string WriterClassName => "NCDK.IO.CustomWriter"; public string FormatName => null; public string MIMEType => null; - public string[] NameExtensions => null; + public IReadOnlyList NameExtensions => null; public string PreferredNameExtension => null; public bool IsXmlBased => false; } diff --git a/NCDKTests/IO/FormatFactoryTest.cs b/NCDKTests/IO/FormatFactoryTest.cs index 688f7461..6bb2a2c7 100644 --- a/NCDKTests/IO/FormatFactoryTest.cs +++ b/NCDKTests/IO/FormatFactoryTest.cs @@ -27,6 +27,8 @@ using System.IO; using System.IO.Compression; using NCDK.Tools; +using System; +using System.Linq; namespace NCDK.IO { @@ -207,7 +209,7 @@ public void TestPubChemCompoundXML() ExpectFormat("NCDK.Data.ASN.PubChem.cid1145.xml", PubChemCompoundXMLFormat.Instance); } - private void ExpectFormat(string filename, IResourceFormat expectedFormat) + private static void ExpectFormat(string filename, IResourceFormat expectedFormat) { var ins = ResourceLoader.GetAsStream(filename); Assert.IsNotNull(ins, $"Cannot find file: {filename}"); @@ -298,15 +300,16 @@ class DummyFormat : IChemFormatMatcher public string MIMEType => null; public bool IsXmlBased => false; public string PreferredNameExtension => "dummy"; - public string[] NameExtensions { get; } = new string[] { "dummy", "dum" }; + public IReadOnlyList NameExtensions { get; } = new string[] { "dummy", "dum" }; - public MatchResult Matches(IList lines) + public MatchResult Matches(IEnumerable lines) { - if (lines.Count > 0 && lines[0].StartsWith("DummyFormat:")) + var first = lines.FirstOrDefault(); + if (first != null && first.StartsWith("DummyFormat:", StringComparison.Ordinal)) { return new MatchResult(true, this, 0); } - return MatchResult.NO_MATCH; + return MatchResult.NoMatch; } } diff --git a/NCDKTests/IO/Formats/Chem3D_Cartesian_1FormatTest.cs b/NCDKTests/IO/Formats/Chem3D_Cartesian_1FormatTest.cs index 3b4ba8f8..0721b4de 100644 --- a/NCDKTests/IO/Formats/Chem3D_Cartesian_1FormatTest.cs +++ b/NCDKTests/IO/Formats/Chem3D_Cartesian_1FormatTest.cs @@ -30,7 +30,7 @@ public class Chem3D_Cartesian_1FormatTest : ChemFormatTest { public Chem3D_Cartesian_1FormatTest() { - base.SetChemFormat((IChemFormat)Chem3D_Cartesian_1Format.Instance); + base.SetChemFormat((IChemFormat)Chem3DCartesian1Format.Instance); } } } diff --git a/NCDKTests/IO/Formats/Chem3D_Cartesian_2FormatTest.cs b/NCDKTests/IO/Formats/Chem3D_Cartesian_2FormatTest.cs index 9ea9cb0d..f42672dc 100644 --- a/NCDKTests/IO/Formats/Chem3D_Cartesian_2FormatTest.cs +++ b/NCDKTests/IO/Formats/Chem3D_Cartesian_2FormatTest.cs @@ -30,7 +30,7 @@ public class Chem3D_Cartesian_2FormatTest : ChemFormatTest { public Chem3D_Cartesian_2FormatTest() { - base.SetChemFormat((IChemFormat)Chem3D_Cartesian_2Format.Instance); + base.SetChemFormat((IChemFormat)Chem3DCartesian2Format.Instance); } } } diff --git a/NCDKTests/IO/Formats/FenskeHall_ZMatrixFormatTest.cs b/NCDKTests/IO/Formats/FenskeHall_ZMatrixFormatTest.cs index e3579e18..d979a4b6 100644 --- a/NCDKTests/IO/Formats/FenskeHall_ZMatrixFormatTest.cs +++ b/NCDKTests/IO/Formats/FenskeHall_ZMatrixFormatTest.cs @@ -30,7 +30,7 @@ public class FenskeHall_ZMatrixFormatTest : ChemFormatTest { public FenskeHall_ZMatrixFormatTest() { - base.SetChemFormat((IChemFormat)FenskeHall_ZMatrixFormat.Instance); + base.SetChemFormat((IChemFormat)FenskeHallZMatrixFormat.Instance); } } } diff --git a/NCDKTests/IO/Formats/ResourceFormatTest.cs b/NCDKTests/IO/Formats/ResourceFormatTest.cs index 80c14749..8cbe038c 100644 --- a/NCDKTests/IO/Formats/ResourceFormatTest.cs +++ b/NCDKTests/IO/Formats/ResourceFormatTest.cs @@ -67,7 +67,7 @@ public void TestGetPreferredNameExtension() { if (resourceFormat.PreferredNameExtension == null) { - if (resourceFormat.NameExtensions == null || resourceFormat.NameExtensions.Length == 0) + if (resourceFormat.NameExtensions == null || resourceFormat.NameExtensions.Count == 0) { // Seems to be current practice // FIXME: needs to be discussed @@ -84,11 +84,12 @@ public void TestGetPreferredNameExtension() Assert.IsNotNull( resourceFormat.NameExtensions, "This format defines a preferred file name extension (PreferredNameExtension), but does not provide a full list of extensions (NameExtensions)."); - string[] allExtensions = resourceFormat.NameExtensions; + var allExtensions = resourceFormat.NameExtensions; bool prefExtInAllExtList = false; - for (int i = 0; i < allExtensions.Length; i++) + foreach (var allExtension in allExtensions) { - if (allExtensions[i].Equals(prefExtension)) prefExtInAllExtList = true; + if (allExtension == prefExtension) + prefExtInAllExtList = true; } Assert.IsTrue(prefExtInAllExtList, "The preferred extension is not found in the list of all extensions"); } @@ -102,17 +103,15 @@ public void TestGetNameExtensions() // Seems to be current practice // FIXME: needs to be discussed } - else if (resourceFormat.NameExtensions.Length == 0) + else if (resourceFormat.NameExtensions.Count == 0) { // Seems to be current practice // FIXME: needs to be discussed } else { - string[] exts = resourceFormat.NameExtensions; - for (int i = 0; i < exts.Length; i++) + foreach (var extension in resourceFormat.NameExtensions) { - string extension = exts[i]; Assert.IsNotNull(extension); Assert.AreNotSame(0, extension.Length); Assert.IsFalse(extension.Contains(","), "File name extensions should not contain ',' characters"); @@ -124,23 +123,23 @@ public void TestGetNameExtensions() [TestMethod()] public void TestHashCode() { - IResourceFormat a = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(new object[0]); - IResourceFormat b = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + IResourceFormat a = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); + IResourceFormat b = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); Assert.AreEqual(b.GetHashCode(), a.GetHashCode()); } [TestMethod()] public void TestEquals() { - IResourceFormat a = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(new object[0]); - IResourceFormat b = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + IResourceFormat a = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); + IResourceFormat b = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); Assert.AreEqual(b, a); } [TestMethod()] public void TestEquals_null() { - IResourceFormat a = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + IResourceFormat a = (IResourceFormat)resourceFormat.GetType().GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); Assert.IsFalse(a.Equals(null)); } diff --git a/NCDKTests/IO/GamessReaderTest.cs b/NCDKTests/IO/GamessReaderTest.cs index 45382f35..c08300a6 100644 --- a/NCDKTests/IO/GamessReaderTest.cs +++ b/NCDKTests/IO/GamessReaderTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.IO; using System; diff --git a/NCDKTests/IO/Gaussian98ReaderTest.cs b/NCDKTests/IO/Gaussian98ReaderTest.cs index df3acdf1..1f8222ac 100644 --- a/NCDKTests/IO/Gaussian98ReaderTest.cs +++ b/NCDKTests/IO/Gaussian98ReaderTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.IO; diff --git a/NCDKTests/IO/GaussianInputWriterTest.cs b/NCDKTests/IO/GaussianInputWriterTest.cs index 075cf628..c5e1e54f 100644 --- a/NCDKTests/IO/GaussianInputWriterTest.cs +++ b/NCDKTests/IO/GaussianInputWriterTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Templates; using System; using System.IO; @@ -37,7 +38,7 @@ namespace NCDK.IO public class GaussianInputWriterTest : ChemObjectIOTest { protected override Type ChemObjectIOToTestType => typeof(GaussianInputWriter); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestAccepts() diff --git a/NCDKTests/IO/GhemicalReaderTest.cs b/NCDKTests/IO/GhemicalReaderTest.cs index f0a0bb00..29bf6aee 100644 --- a/NCDKTests/IO/GhemicalReaderTest.cs +++ b/NCDKTests/IO/GhemicalReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/IO/HINReaderTest.cs b/NCDKTests/IO/HINReaderTest.cs index b997665d..87e5e0bd 100644 --- a/NCDKTests/IO/HINReaderTest.cs +++ b/NCDKTests/IO/HINReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Diagnostics; diff --git a/NCDKTests/IO/InChIPlainTextReaderTest.cs b/NCDKTests/IO/InChIPlainTextReaderTest.cs index 6a3ab0b7..d8f64d87 100644 --- a/NCDKTests/IO/InChIPlainTextReaderTest.cs +++ b/NCDKTests/IO/InChIPlainTextReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/InChIReaderTest.cs b/NCDKTests/IO/InChIReaderTest.cs index ba9b0b31..7eb428e0 100644 --- a/NCDKTests/IO/InChIReaderTest.cs +++ b/NCDKTests/IO/InChIReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/Iterator/EnumerableMDLConformerReaderTest.cs b/NCDKTests/IO/Iterator/EnumerableMDLConformerReaderTest.cs index a53d7b90..4ea448ac 100644 --- a/NCDKTests/IO/Iterator/EnumerableMDLConformerReaderTest.cs +++ b/NCDKTests/IO/Iterator/EnumerableMDLConformerReaderTest.cs @@ -1,4 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; @@ -20,7 +21,7 @@ public void TestSDF() Trace.TraceInformation("Testing: " + filename); Stream ins = ResourceLoader.GetAsStream(filename); IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(ins, - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); int molCount = 0; int[] nconfs = new int[3]; @@ -46,7 +47,7 @@ public void TestRemove() string filename = "NCDK.Data.MDL.iterconftest.sdf"; Trace.TraceInformation("Testing: " + filename); Stream ins = ResourceLoader.GetAsStream(filename); - var reader = new IEnumerableMDLConformerReader(ins, Default.ChemObjectBuilder.Instance).GetEnumerator(); + var reader = new IEnumerableMDLConformerReader(ins, ChemObjectBuilder.Instance).GetEnumerator(); reader.MoveNext(); var dummy = reader.Current; diff --git a/NCDKTests/IO/Iterator/EnumerablePCCompoundASNReaderTest.cs b/NCDKTests/IO/Iterator/EnumerablePCCompoundASNReaderTest.cs index b9564e27..dd39f599 100644 --- a/NCDKTests/IO/Iterator/EnumerablePCCompoundASNReaderTest.cs +++ b/NCDKTests/IO/Iterator/EnumerablePCCompoundASNReaderTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.Diagnostics; namespace NCDK.IO.Iterator @@ -35,8 +36,7 @@ public void TestList() string filename = "NCDK.Data.ASN.PubChem.list.asn"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - EnumerablePCCompoundASNReader reader = new EnumerablePCCompoundASNReader(ins, - Default.ChemObjectBuilder.Instance); + EnumerablePCCompoundASNReader reader = new EnumerablePCCompoundASNReader(ins, ChemObjectBuilder.Instance); int molCount = 0; foreach (var obj in reader) diff --git a/NCDKTests/IO/Iterator/EnumerablePCCompoundXMLReaderTest.cs b/NCDKTests/IO/Iterator/EnumerablePCCompoundXMLReaderTest.cs index e984192b..ccab4c58 100644 --- a/NCDKTests/IO/Iterator/EnumerablePCCompoundXMLReaderTest.cs +++ b/NCDKTests/IO/Iterator/EnumerablePCCompoundXMLReaderTest.cs @@ -22,6 +22,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.Diagnostics; using System.IO; @@ -37,10 +38,10 @@ public void TestList() string filename = "NCDK.Data.ASN.PubChem.aceticAcids38.xml"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - var reader = new EnumerablePCCompoundXMLReader(new StreamReader(ins), Default.ChemObjectBuilder.Instance); + var reader = new EnumerablePCCompoundXMLReader(new StreamReader(ins), ChemObjectBuilder.Instance); int molCount = 0; - var set = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var set = ChemObjectBuilder.Instance.NewAtomContainerSet(); foreach (var obj in reader) { // Console.Out.WriteLine("next molecule found"); diff --git a/NCDKTests/IO/Iterator/EnumerablePCSubstancesXMLReaderTest.cs b/NCDKTests/IO/Iterator/EnumerablePCSubstancesXMLReaderTest.cs index f98d3747..e586c311 100644 --- a/NCDKTests/IO/Iterator/EnumerablePCSubstancesXMLReaderTest.cs +++ b/NCDKTests/IO/Iterator/EnumerablePCSubstancesXMLReaderTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System.Diagnostics; using System.IO; @@ -41,9 +42,9 @@ public void TestTaxols() IChemSequence set; using (var ins = ResourceLoader.GetAsStream(filename)) using (var sr = new StreamReader(ins)) - using (var reader = new EnumerablePCSubstancesXMLReader(sr, Default.ChemObjectBuilder.Instance)) + using (var reader = new EnumerablePCSubstancesXMLReader(sr, ChemObjectBuilder.Instance)) { - set = Default.ChemObjectBuilder.Instance.NewChemSequence(); + set = ChemObjectBuilder.Instance.NewChemSequence(); foreach (var obj in reader) { Assert.IsNotNull(obj); diff --git a/NCDKTests/IO/Iterator/EnumerableSDFReaderTest.cs b/NCDKTests/IO/Iterator/EnumerableSDFReaderTest.cs index b710f69d..7b35fa34 100644 --- a/NCDKTests/IO/Iterator/EnumerableSDFReaderTest.cs +++ b/NCDKTests/IO/Iterator/EnumerableSDFReaderTest.cs @@ -26,6 +26,7 @@ using NCDK.IO.Formats; using NCDK.IO.Listener; using NCDK.IO.Setting; +using System; using System.Collections.Specialized; using System.Diagnostics; using System.IO; @@ -280,7 +281,7 @@ class MyListener : IChemObjectIOListener { public void ProcessIOSettingQuestion(IOSetting setting) { - if ("ForceReadAs3DCoordinates".Equals(setting.Name)) + if (string.Equals("ForceReadAs3DCoordinates", setting.Name, StringComparison.Ordinal)) { try { diff --git a/NCDKTests/IO/Iterator/EnumerableSMILESReaderTest.cs b/NCDKTests/IO/Iterator/EnumerableSMILESReaderTest.cs index 2bdccb27..fce987fc 100644 --- a/NCDKTests/IO/Iterator/EnumerableSMILESReaderTest.cs +++ b/NCDKTests/IO/Iterator/EnumerableSMILESReaderTest.cs @@ -22,6 +22,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.IO.Formats; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; @@ -42,7 +43,7 @@ public void TestSMILESFileWithNames() string filename = "NCDK.Data.Smiles.test.smi"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, ChemObjectBuilder.Instance); int molCount = 0; foreach (var obj in reader) @@ -63,7 +64,7 @@ public void TestSMILESFileWithSpacesAndTabs() string filename = "NCDK.Data.Smiles.tabs.smi"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, ChemObjectBuilder.Instance); int molCount = 0; foreach (var obj in reader) @@ -84,7 +85,7 @@ public void TestSMILESTitles() string filename = "NCDK.Data.Smiles.tabs.smi"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, ChemObjectBuilder.Instance); foreach (var mol in reader) { string title = (string)mol.Title; @@ -99,7 +100,7 @@ public void TestSMILESFile() string filename = "NCDK.Data.Smiles.test2.smi"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, ChemObjectBuilder.Instance); int molCount = 0; foreach (var obj in reader) @@ -118,7 +119,7 @@ public void TestGetFormat() string filename = "NCDK.Data.Smiles.test2.smi"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, ChemObjectBuilder.Instance); IResourceFormat format = reader.Format; Assert.IsTrue(format is SMILESFormat); } @@ -128,7 +129,7 @@ public void TestSetReader1() { string filename = "NCDK.Data.Smiles.test2.smi"; var ins1 = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader1 = new EnumerableSMILESReader(ins1, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader1 = new EnumerableSMILESReader(ins1, ChemObjectBuilder.Instance); int molCount = 0; foreach (var mol in reader1) { @@ -136,7 +137,7 @@ public void TestSetReader1() } filename = "NCDK.Data.Smiles.tabs.smi"; var ins2 = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader2 = new EnumerableSMILESReader(ins2, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader2 = new EnumerableSMILESReader(ins2, ChemObjectBuilder.Instance); molCount = 0; foreach (var mol in reader2) { @@ -151,7 +152,7 @@ public void TestRemove() { string filename = "NCDK.Data.Smiles.test2.smi"; var ins1 = ResourceLoader.GetAsStream(filename); - EnumerableSMILESReader reader = new EnumerableSMILESReader(ins1, Default.ChemObjectBuilder.Instance); + EnumerableSMILESReader reader = new EnumerableSMILESReader(ins1, ChemObjectBuilder.Instance); int molCount = 0; foreach (var mol in reader) { diff --git a/NCDKTests/IO/MDLCMLRoundtripTest.cs b/NCDKTests/IO/MDLCMLRoundtripTest.cs index edd17f27..4ce5898e 100644 --- a/NCDKTests/IO/MDLCMLRoundtripTest.cs +++ b/NCDKTests/IO/MDLCMLRoundtripTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.IO; using System.Text; diff --git a/NCDKTests/IO/MDLRXNReaderTest.cs b/NCDKTests/IO/MDLRXNReaderTest.cs index 9bb93e2c..8ef49d34 100644 --- a/NCDKTests/IO/MDLRXNReaderTest.cs +++ b/NCDKTests/IO/MDLRXNReaderTest.cs @@ -22,7 +22,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/NCDKTests/IO/MDLRXNV2000ReaderTest.cs b/NCDKTests/IO/MDLRXNV2000ReaderTest.cs index cbc928b5..4604c387 100644 --- a/NCDKTests/IO/MDLRXNV2000ReaderTest.cs +++ b/NCDKTests/IO/MDLRXNV2000ReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/MDLRXNV3000ReaderTest.cs b/NCDKTests/IO/MDLRXNV3000ReaderTest.cs index c4edf78e..8f1ce531 100644 --- a/NCDKTests/IO/MDLRXNV3000ReaderTest.cs +++ b/NCDKTests/IO/MDLRXNV3000ReaderTest.cs @@ -22,7 +22,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/MDLRXNWriterTest.cs b/NCDKTests/IO/MDLRXNWriterTest.cs index f932ece4..401ca3e2 100644 --- a/NCDKTests/IO/MDLRXNWriterTest.cs +++ b/NCDKTests/IO/MDLRXNWriterTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; @@ -36,7 +36,7 @@ namespace NCDK.IO public class MDLRXNWriterTest : ChemObjectIOTest { protected override Type ChemObjectIOToTestType => typeof(MDLRXNWriter); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestAccepts() diff --git a/NCDKTests/IO/MDLReaderTest.cs b/NCDKTests/IO/MDLReaderTest.cs index 87ec0250..68535278 100644 --- a/NCDKTests/IO/MDLReaderTest.cs +++ b/NCDKTests/IO/MDLReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; @@ -221,7 +221,7 @@ public void TestMissingAtomProperties() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.bug3485634.mol"); MDLReader reader = new MDLReader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(9, molecule.Atoms.Count); @@ -233,7 +233,7 @@ public void Properties() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.bug1356.sdf"); MDLReader reader = new MDLReader(ins); - IChemFile chemfile = Default.ChemObjectBuilder.Instance.NewChemFile(); + IChemFile chemfile = ChemObjectBuilder.Instance.NewChemFile(); chemfile = reader.Read(chemfile); IAtomContainer container = ChemFileManipulator.GetAllAtomContainers(chemfile).First(); Assert.IsNotNull(container.GetProperty("first")); @@ -247,7 +247,7 @@ public void WrongFormat() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.bug1356.sdf"); MDLReader reader = new MDLReader(ins, ChemObjectReaderMode.Strict); - IChemFile chemfile = Default.ChemObjectBuilder.Instance.NewChemFile(); + IChemFile chemfile = ChemObjectBuilder.Instance.NewChemFile(); chemfile = reader.Read(chemfile); } } diff --git a/NCDKTests/IO/MDLV2000AtomBlockTest.cs b/NCDKTests/IO/MDLV2000AtomBlockTest.cs index dcbdecf8..05522194 100644 --- a/NCDKTests/IO/MDLV2000AtomBlockTest.cs +++ b/NCDKTests/IO/MDLV2000AtomBlockTest.cs @@ -309,8 +309,7 @@ public void ReadMDLCoordinate_offset() [TestMethod()] public void ReadOldJmolCoords() { - MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")); - reader.ReaderMode = ChemObjectReaderMode.Relaxed; + MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")) { ReaderMode = ChemObjectReaderMode.Relaxed }; Assert.IsTrue(Math.Abs(reader.ReadMDLCoordinate(" -2.00120 7.8089", 0) - (-2.00120)) < 0.1); } @@ -318,8 +317,7 @@ public void ReadOldJmolCoords() [ExpectedException(typeof(CDKException), AllowDerivedTypes = true)] public void ReadOldJmolCoordsFailOnStrictRead() { - MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")); - reader.ReaderMode = ChemObjectReaderMode.Strict; + MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")) { ReaderMode = ChemObjectReaderMode.Strict }; reader.ReadMDLCoordinate(" -2.00120 7.8089", 0); } @@ -327,32 +325,28 @@ public void ReadOldJmolCoordsFailOnStrictRead() [ExpectedException(typeof(CDKException), AllowDerivedTypes = true)] public void ReadMDLCoordinates_wrong_decimal_position_strict() { - MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")); - reader.ReaderMode = ChemObjectReaderMode.Strict; + MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")) { ReaderMode = ChemObjectReaderMode.Strict }; Assert.IsTrue(Math.Abs(reader.ReadMDLCoordinate(" -2.0012 7.8089 ", 10) - 7.8089) < 0.1); } [TestMethod()] public void ReadMDLCoordinates_wrong_decimal_position_relaxed() { - MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")); - reader.ReaderMode = ChemObjectReaderMode.Relaxed; + MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")) { ReaderMode = ChemObjectReaderMode.Relaxed }; Assert.IsTrue(Math.Abs(reader.ReadMDLCoordinate(" -2.0012 7.8089 ", 10) - 7.8089) < 0.1); } [TestMethod()] public void ReadMDLCoordinates_no_value_relaxed() { - MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")); - reader.ReaderMode = ChemObjectReaderMode.Relaxed; + MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")) { ReaderMode = ChemObjectReaderMode.Relaxed }; Assert.IsTrue(Math.Abs(reader.ReadMDLCoordinate(" -2.0012 ", 10) - 0) < 0.1); } [TestMethod()] public void ReadMDLCoordinates_no_decimal_relaxed() { - MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")); - reader.ReaderMode = ChemObjectReaderMode.Relaxed; + MDLV2000Reader reader = new MDLV2000Reader(new StringReader("")) { ReaderMode = ChemObjectReaderMode.Relaxed }; Assert.IsTrue(Math.Abs(reader.ReadMDLCoordinate(" -2.0012 708089 ", 10) - 708089) < 0.1); } } diff --git a/NCDKTests/IO/MDLV2000ReaderTest.cs b/NCDKTests/IO/MDLV2000ReaderTest.cs index 54bbefbb..01b11243 100644 --- a/NCDKTests/IO/MDLV2000ReaderTest.cs +++ b/NCDKTests/IO/MDLV2000ReaderTest.cs @@ -526,7 +526,7 @@ public void TestZeroZCoordinates() reader.Listeners.Add(listener); reader.CustomizeJob(); - IAtomContainer mol = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); reader.Close(); Assert.IsNotNull(mol); Assert.AreEqual(5, mol.Atoms.Count); @@ -543,7 +543,7 @@ public void TestZeroZCoordinates3DMarked() Trace.TraceInformation("Testing: " + filename); var ins = this.GetType().Assembly.GetManifestResourceStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer mol = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); reader.Close(); Assert.IsNotNull(mol); Assert.AreEqual(5, mol.Atoms.Count); @@ -786,7 +786,7 @@ public void TestRGroupHardcodedNumbering() Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer mol = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); reader.Close(); foreach (var bond in mol.Bonds) { @@ -887,7 +887,7 @@ public void TestAtomValueLines() var filename = "NCDK.Data.MDL.atomValueLines.mol"; var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer testMolecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer testMolecule = ChemObjectBuilder.Instance.NewAtomContainer(); IAtomContainer result = reader.Read(testMolecule); reader.Close(); IAtom oxygen = result.Atoms[0]; @@ -1028,7 +1028,7 @@ public void TestRGroupHighAtomNumber() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.brenda_molfile_rgroup.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); reader.Read(molecule); reader.Close(); Assert.AreEqual("R", molecule.Atoms[55].Symbol); @@ -1039,14 +1039,12 @@ public void TestAliasAtomNaming() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.mol_testAliasAtomNaming.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); reader.Read(molecule); reader.Close(); - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(molecule); - int r1Count = 0; - foreach (var atom in atoms) + foreach (var atom in molecule.Atoms) { if (atom is IPseudoAtom) { @@ -1062,7 +1060,7 @@ public void TestPseudoAtomLabels() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.pseudoatoms.sdf"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsTrue(molecule.Atoms[4] is IPseudoAtom); @@ -1077,7 +1075,7 @@ public void TestMissingAtomProperties() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.bug3485634.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(9, molecule.Atoms.Count); @@ -1088,7 +1086,7 @@ public void TestBondOrderFour() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.mdlWithBond4.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(9, molecule.Atoms.Count); @@ -1103,14 +1101,13 @@ public void TestAtomParity() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.mol_testAtomParity.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(6, molecule.Atoms.Count); bool chiralCentre = false; - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(molecule); - foreach (var atom in atoms) + foreach (var atom in molecule.Atoms) { var parity = atom.StereoParity; if (parity == 1) @@ -1129,7 +1126,7 @@ public void TestSingleSingletRadical() var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.singleSingletRadical.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -1142,7 +1139,7 @@ public void TestSingleDoubletRadical() var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.singleDoubletRadical.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -1155,7 +1152,7 @@ public void TestSingleTripletRadical() var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.singleTripletRadical.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(2, molecule.GetConnectedSingleElectrons(molecule.Atoms[1]).Count()); @@ -1167,7 +1164,7 @@ public void TestMultipleRadicals() var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.multipleRadicals.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -1187,7 +1184,7 @@ public void Fe_iii_valence() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.iron-iii.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(1, molecule.Atoms[0].ImplicitHydrogenCount); @@ -1200,7 +1197,7 @@ public void Bismuth_ion_valence() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.bismuth-ion.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.AreEqual(3, molecule.Atoms[0].ImplicitHydrogenCount); @@ -1211,7 +1208,7 @@ public void E_butene_2D() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.e_butene_2d.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsTrue(molecule.StereoElements.GetEnumerator().MoveNext()); @@ -1223,7 +1220,7 @@ public void E_butene_0D() { var ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.e_butene_0d.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsNotNull(molecule); @@ -1247,7 +1244,7 @@ public void E_butene_2D_force3D() reader.Listeners.Add(listener); reader.CustomizeJob(); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsNotNull(molecule); @@ -1268,7 +1265,7 @@ public void E_butene_3D() reader.Listeners.Add(listener); reader.CustomizeJob(); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsNotNull(molecule); @@ -1290,7 +1287,7 @@ public void E_butene_2D_optOff() reader.Listeners.Add(listener); reader.CustomizeJob(); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsNotNull(molecule); @@ -1619,7 +1616,7 @@ public void TestSgroupAbbreviation() using (MDLV2000Reader mdlr = new MDLV2000Reader(srm)) { IAtomContainer container = mdlr.Read(new AtomContainer()); - var sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = container.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(1, sgroups.Count); Sgroup sgroup = sgroups[0]; @@ -1636,7 +1633,7 @@ public void TestSgroupRepeatUnit() using (MDLV2000Reader mdlr = new MDLV2000Reader(srm)) { IAtomContainer container = mdlr.Read(new AtomContainer()); - IList sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + IList sgroups = container.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(1, sgroups.Count); Sgroup sgroup = sgroups[0]; @@ -1668,7 +1665,7 @@ public void TestSgroupUnorderedMixture() using (MDLV2000Reader mdlr = new MDLV2000Reader(srm)) { IAtomContainer container = mdlr.Read(new AtomContainer()); - IList sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + IList sgroups = container.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(3, sgroups.Count); // first sgroup @@ -1695,7 +1692,7 @@ public void TestSgroupExpandedAbbreviation() using (MDLV2000Reader mdlr = new MDLV2000Reader(srm)) { IAtomContainer container = mdlr.Read(new AtomContainer()); - IList sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + IList sgroups = container.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(3, sgroups.Count); // first sgroup @@ -1747,7 +1744,7 @@ public void TestSgroupBracketStyle() using (MDLV2000Reader mdlr = new MDLV2000Reader(srm)) { IAtomContainer container = mdlr.Read(new AtomContainer()); - IList sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + IList sgroups = container.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(2, sgroups.Count); Sgroup sgroup = sgroups[0]; diff --git a/NCDKTests/IO/MDLV2000WriterTest.cs b/NCDKTests/IO/MDLV2000WriterTest.cs index b4b8356e..99d13254 100644 --- a/NCDKTests/IO/MDLV2000WriterTest.cs +++ b/NCDKTests/IO/MDLV2000WriterTest.cs @@ -46,7 +46,7 @@ namespace NCDK.IO public class MDLV2000WriterTest : ChemObjectIOTest { protected override Type ChemObjectIOToTestType => typeof(MDLV2000Writer); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestAccepts() @@ -90,7 +90,7 @@ public void TestBug1212219() mdlWriter.Write(molecule); mdlWriter.Close(); string output = writer.ToString(); - //Debug.WriteLine("MDL output for testBug1212219: " + output); + //Debug.WriteLine($"MDL output for testBug1212219: {output}"); Assert.IsTrue(output.IndexOf("M ISO 1 1 14") != -1); } @@ -434,7 +434,7 @@ public void TestAtomParity() { Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.mol_testAtomParity.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -452,7 +452,7 @@ public void TestWritePseudoAtoms() { Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.pseudoatoms.sdf"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -470,7 +470,7 @@ public void TestWritePseudoAtoms() [TestMethod()] public void TestWritePseudoAtoms_LongLabel() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer container = builder.NewAtomContainer(); IAtom c1 = builder.NewAtom("C"); @@ -496,7 +496,7 @@ public void TestWritePseudoAtoms_LongLabel() [TestMethod()] public void TestWritePseudoAtoms_nullLabel() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer container = builder.NewAtomContainer(); IAtom c1 = builder.NewAtom("C"); @@ -521,7 +521,7 @@ public void TestWritePseudoAtoms_nullLabel() [TestMethod()] public void TestRGPLine_Multiline() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer container = builder.NewAtomContainer(); for (int i = 1; i < 20; i++) @@ -541,7 +541,7 @@ public void TestRGPLine_Multiline() [TestMethod()] public void TestAlias_TruncatedLabel() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer container = builder.NewAtomContainer(); string label = "This is a very long label - almost too long. it should be cut here -> and the rest is truncated"; @@ -577,7 +577,7 @@ public void TestSingleSingletRadical() { Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.singleSingletRadical.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -597,7 +597,7 @@ public void TestSingleDoubletRadical() { Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.singleDoubletRadical.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -619,7 +619,7 @@ public void TestSingleTripletRadical() { Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.singleTripletRadical.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -639,7 +639,7 @@ public void TestMultipleRadicals() { Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.multipleRadicals.mol"); MDLV2000Reader reader = new MDLV2000Reader(ins); - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); @@ -664,8 +664,7 @@ public void TestSgroupAtomListWrapping() Sgroup sgroup = new Sgroup(); foreach (var atom in mol.Atoms) sgroup.Atoms.Add(atom); - mol.SetProperty(CDKPropertyName.CtabSgroups, - new[] { sgroup }); + mol.SetCtabSgroups(new[] { sgroup }); StringWriter sw = new StringWriter(); using (MDLV2000Writer mdlw = new MDLV2000Writer(sw)) diff --git a/NCDKTests/IO/MDLV3000ReaderTest.cs b/NCDKTests/IO/MDLV3000ReaderTest.cs index 29dfd512..176811c0 100644 --- a/NCDKTests/IO/MDLV3000ReaderTest.cs +++ b/NCDKTests/IO/MDLV3000ReaderTest.cs @@ -23,6 +23,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Sgroups; +using NCDK.Silent; using System; using System.Collections.Generic; using System.Diagnostics; @@ -41,7 +42,7 @@ public class MDLV3000ReaderTest : SimpleChemObjectReaderTest { protected override string TestFile => "NCDK.Data.MDL.molV3000.mol"; protected override Type ChemObjectIOToTestType => typeof(MDLV3000Reader); - private static readonly IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static readonly IChemObjectBuilder builder = ChemObjectBuilder.Instance; private static readonly Type typeOfAtomContainer = builder.NewAtomContainer().GetType(); [TestMethod()] @@ -99,7 +100,7 @@ public void TestPseudoAtomLabels() using (Stream ins = ResourceLoader.GetAsStream("NCDK.Data.MDL.pseudoatomsv3000.mol")) using (MDLV3000Reader reader = new MDLV3000Reader(ins)) { - IAtomContainer molecule = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer molecule = ChemObjectBuilder.Instance.NewAtomContainer(); molecule = reader.Read(molecule); reader.Close(); Assert.IsTrue(molecule.Atoms[9] is IPseudoAtom); @@ -129,7 +130,7 @@ public void PositionalVariation() { IAtomContainer container = reader.Read(builder.NewAtomContainer()); Assert.AreEqual(8, container.Bonds.Count); - var sgroups = container.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = container.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(1, sgroups.Count); Assert.AreEqual(SgroupType.ExtMulticenter, sgroups[0].Type); diff --git a/NCDKTests/IO/MDLV3000WriterTest.cs b/NCDKTests/IO/MDLV3000WriterTest.cs index 2252e390..cfa9cf5e 100644 --- a/NCDKTests/IO/MDLV3000WriterTest.cs +++ b/NCDKTests/IO/MDLV3000WriterTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using NCDK.Sgroups; using NCDK.Stereo; @@ -326,7 +326,7 @@ public void WriteSRUs() sgroup.Subscript = "n"; sgroup.PutValue(SgroupKey.CtabConnectivity, "HH"); sgroups.Add(sgroup); - mol.SetProperty(CDKPropertyName.CtabSgroups, sgroups); + mol.SetCtabSgroups(sgroups); string res = WriteToStr(mol); Assert.IsTrue(res.Contains("M V30 1 SRU 0 ATOMS=(2 2 3) XBONDS=(2 1 3) LABEL=n CONNECT=HH\n")); } @@ -358,7 +358,7 @@ public void WriteMultipleGroup() sgroup.Type = SgroupType.CtabMultipleGroup; sgroup.Subscript = repeatAtoms.ToString(); sgroups.Add(sgroup); - mol.SetProperty(CDKPropertyName.CtabSgroups, sgroups); + mol.SetCtabSgroups(sgroups); string res = WriteToStr(mol); Assert.IsTrue(res.Contains("M V30 1 MUL 0 ATOMS=(50 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 2-\n" + "M V30 2 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 -\n" diff --git a/NCDKTests/IO/MDLValenceTest.cs b/NCDKTests/IO/MDLValenceTest.cs index ef2d42db..c3ae3763 100644 --- a/NCDKTests/IO/MDLValenceTest.cs +++ b/NCDKTests/IO/MDLValenceTest.cs @@ -23,7 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.IO { diff --git a/NCDKTests/IO/MoSSOutputReaderTest.cs b/NCDKTests/IO/MoSSOutputReaderTest.cs index bebebb9c..ce6b4167 100644 --- a/NCDKTests/IO/MoSSOutputReaderTest.cs +++ b/NCDKTests/IO/MoSSOutputReaderTest.cs @@ -20,7 +20,7 @@ * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/IO/Mol2ReaderTest.cs b/NCDKTests/IO/Mol2ReaderTest.cs index 13103dce..a8971b3b 100644 --- a/NCDKTests/IO/Mol2ReaderTest.cs +++ b/NCDKTests/IO/Mol2ReaderTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Diagnostics; @@ -370,7 +370,7 @@ public void TestBug1714794() } } - private void CheckMol(StringBuilder buf) + private static void CheckMol(StringBuilder buf) { StringReader sr = new StringReader(buf.ToString()); Mol2Reader reader = new Mol2Reader(sr); diff --git a/NCDKTests/IO/Mol2WriterTest.cs b/NCDKTests/IO/Mol2WriterTest.cs index 700c33a5..40c871b9 100644 --- a/NCDKTests/IO/Mol2WriterTest.cs +++ b/NCDKTests/IO/Mol2WriterTest.cs @@ -23,7 +23,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.IO; @@ -41,7 +41,7 @@ namespace NCDK.IO public class Mol2WriterTest : ChemObjectIOTest { protected override Type ChemObjectIOToTestType => typeof(Mol2Writer); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestAccepts() diff --git a/NCDKTests/IO/Mopac7ReaderTest.cs b/NCDKTests/IO/Mopac7ReaderTest.cs index f67a233e..f95f6623 100644 --- a/NCDKTests/IO/Mopac7ReaderTest.cs +++ b/NCDKTests/IO/Mopac7ReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/IO/Mopac7WriterTest.cs b/NCDKTests/IO/Mopac7WriterTest.cs index 452277ea..f6eae8fa 100644 --- a/NCDKTests/IO/Mopac7WriterTest.cs +++ b/NCDKTests/IO/Mopac7WriterTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Listener; using System; using System.Collections.Specialized; diff --git a/NCDKTests/IO/NCDKSourceCodeWriterTest.cs b/NCDKTests/IO/NCDKSourceCodeWriterTest.cs index ae3251a4..67b7ac44 100644 --- a/NCDKTests/IO/NCDKSourceCodeWriterTest.cs +++ b/NCDKTests/IO/NCDKSourceCodeWriterTest.cs @@ -22,7 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; @@ -49,8 +49,7 @@ public void TestOutput() { StringWriter writer = new StringWriter(); IAtomContainer molecule = new AtomContainer(); - Atom atom = new Atom("C"); - atom.MassNumber = 14; + Atom atom = new Atom("C") { MassNumber = 14 }; molecule.Atoms.Add(atom); var sourceWriter = new NCDKSourceCodeWriter(writer); @@ -59,7 +58,7 @@ public void TestOutput() string output = writer.ToString(); const string newline = "\n"; Assert.AreEqual("{" + newline + - " IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance;" + newline + + " IChemObjectBuilder builder = NCDK.Silent.ChemObjectBuilder.Instance;" + newline + " IAtomContainer mol = builder.NewAtomContainer();" + newline + " IAtom a1 = builder.NewAtom(\"C\");" + newline + " a1.FormalCharge = 0;" + newline + diff --git a/NCDKTests/IO/PCCompoundASNReaderTest.cs b/NCDKTests/IO/PCCompoundASNReaderTest.cs index fdef4a1a..4d30afe6 100644 --- a/NCDKTests/IO/PCCompoundASNReaderTest.cs +++ b/NCDKTests/IO/PCCompoundASNReaderTest.cs @@ -20,8 +20,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Diagnostics; diff --git a/NCDKTests/IO/PCCompoundXMLReaderTest.cs b/NCDKTests/IO/PCCompoundXMLReaderTest.cs index c95c020c..c7d541cd 100644 --- a/NCDKTests/IO/PCCompoundXMLReaderTest.cs +++ b/NCDKTests/IO/PCCompoundXMLReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/PCSubstanceXMLReaderTest.cs b/NCDKTests/IO/PCSubstanceXMLReaderTest.cs index ff851eb5..b58cd340 100644 --- a/NCDKTests/IO/PCSubstanceXMLReaderTest.cs +++ b/NCDKTests/IO/PCSubstanceXMLReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/PDBReaderTest.cs b/NCDKTests/IO/PDBReaderTest.cs index f48bd914..b6b9b8db 100644 --- a/NCDKTests/IO/PDBReaderTest.cs +++ b/NCDKTests/IO/PDBReaderTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.IO; diff --git a/NCDKTests/IO/PDBWriterTest.cs b/NCDKTests/IO/PDBWriterTest.cs index 364f47fd..b6c805b1 100644 --- a/NCDKTests/IO/PDBWriterTest.cs +++ b/NCDKTests/IO/PDBWriterTest.cs @@ -22,7 +22,7 @@ * */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Templates; using System.Collections.Generic; using System.IO; @@ -41,7 +41,7 @@ namespace NCDK.IO public class PDBWriterTest : ChemObjectIOTest { protected override Type ChemObjectIOToTestType => typeof(MDLRXNWriter); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestRoundTrip() diff --git a/NCDKTests/IO/PMPReaderTest.cs b/NCDKTests/IO/PMPReaderTest.cs index 465eef2d..7003f7bf 100644 --- a/NCDKTests/IO/PMPReaderTest.cs +++ b/NCDKTests/IO/PMPReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/IO/RDF/CDKOWLReaderTest.cs b/NCDKTests/IO/RDF/CDKOWLReaderTest.cs index ffaae451..e5286ab8 100644 --- a/NCDKTests/IO/RDF/CDKOWLReaderTest.cs +++ b/NCDKTests/IO/RDF/CDKOWLReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/RDF/CDKOWLWriterTest.cs b/NCDKTests/IO/RDF/CDKOWLWriterTest.cs index 30a98ff5..cf2663b5 100644 --- a/NCDKTests/IO/RDF/CDKOWLWriterTest.cs +++ b/NCDKTests/IO/RDF/CDKOWLWriterTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.IO; using System; @@ -35,7 +35,7 @@ namespace NCDK.IO.RDF public class CDKOWLWriterTest : ChemObjectWriterTest { protected override Type ChemObjectIOToTestType => typeof(CDKOWLWriter); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestWriteMolecule() @@ -43,7 +43,7 @@ public void TestWriteMolecule() StringWriter output = new StringWriter(); CDKOWLWriter writer = new CDKOWLWriter(output); - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); mol.Atoms.Add(new Atom("C")); mol.AddBond(mol.Atoms[0], mol.Atoms[1], BondOrder.Double); diff --git a/NCDKTests/IO/RGroupQueryReaderTest.cs b/NCDKTests/IO/RGroupQueryReaderTest.cs index 92869eb6..487ca892 100644 --- a/NCDKTests/IO/RGroupQueryReaderTest.cs +++ b/NCDKTests/IO/RGroupQueryReaderTest.cs @@ -23,7 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Formats; using NCDK.Isomorphisms.Matchers; using System; @@ -62,8 +62,6 @@ public override void TestAcceptsAtLeastOneChemObjectClass() Assert.IsTrue(reader.Accepts(typeof(RGroupQuery))); } - public void TestAcceptsAtLeastOneDebugObject() { } - public override void TestAcceptsAtLeastOneNonotifyObject() { } /// @@ -89,7 +87,7 @@ public void TestRgroupQueryFile1() Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 1); @@ -100,8 +98,8 @@ public void TestRgroupQueryFile1() if (at is PseudoAtom) { Assert.AreEqual(((PseudoAtom)at).Label, "R1"); - IDictionary> rootApo = rGroupQuery.RootAttachmentPoints; - IDictionary apoBonds = rootApo[at]; + var rootApo = rGroupQuery.RootAttachmentPoints; + var apoBonds = rootApo[at]; Assert.AreEqual(apoBonds.Count, 1); // Assert that the root attachment is the bond between R1 and P foreach (var bond in rGroupQuery.RootStructure.Bonds) @@ -133,7 +131,7 @@ public void TestRgroupQueryFile1() Assert.IsNull(rGroups[2].SecondAttachmentPoint); var configurations = rGroupQuery.GetAllConfigurations(); - Assert.AreEqual(configurations.Count, 4); + Assert.AreEqual(configurations.Count(), 4); //IsRestH is set to true for R1, so with zero substitutes, the phosphor should get the restH flag set to true. bool restH_Identified = false; @@ -162,11 +160,11 @@ public void TestRgroupQueryFile1() [TestMethod()] public void TestRgroupQueryFile2() { - string filename = "NCDK.Data.MDL.rgfile.2.mol"; + var filename = "NCDK.Data.MDL.rgfile.2.mol"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + var reader = new RGroupQueryReader(ins); + var rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 3); @@ -185,20 +183,20 @@ public void TestRgroupQueryFile2() { Assert.IsTrue(RGroupQuery.IsValidRgroupQueryLabel(((PseudoAtom)at).Label)); - int rgroupNum = int.Parse(((PseudoAtom)at).Label.Substring(1)); + var rgroupNum = int.Parse(((PseudoAtom)at).Label.Substring(1)); Assert.IsTrue(rgroupNum == 1 || rgroupNum == 2 || rgroupNum == 11); switch (rgroupNum) { case 1: { //Test: R1 has two attachment points, defined by AAL - IDictionary> rootApo = rGroupQuery.RootAttachmentPoints; - IDictionary apoBonds = rootApo[at]; + var rootApo = rGroupQuery.RootAttachmentPoints; + var apoBonds = rootApo[at]; Assert.AreEqual(apoBonds.Count, 2); Assert.AreEqual(apoBonds[1].GetOther(at).Symbol, "N"); Assert.IsTrue(apoBonds[2].GetOther(at).Symbol.Equals("C")); //Test: Oxygens are the 2nd APO's for R1 - RGroupList rList = rGroupQuery.RGroupDefinitions[1]; + var rList = rGroupQuery.RGroupDefinitions[1]; Assert.AreEqual(rList.RGroups.Count, 2); var rGroups = rList.RGroups; Assert.AreEqual(rGroups[0].SecondAttachmentPoint.Symbol, "O"); @@ -232,7 +230,7 @@ public void TestRgroupQueryFile2() } var configurations = rGroupQuery.GetAllConfigurations(); - Assert.AreEqual(12, configurations.Count); + Assert.AreEqual(12, configurations.Count()); //Test restH values int countRestHForSmallestConfigurations = 0; @@ -266,14 +264,14 @@ public void TestRgroupQueryFile3() Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 1); Assert.AreEqual(rGroupQuery.RootStructure.Atoms.Count, 10); Assert.AreEqual(rGroupQuery.RootAttachmentPoints.Count, 2); - Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count, 8); + Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count(), 8); //Test correctness AAL lines foreach (var at in rGroupQuery.GetRgroupQueryAtoms(1)) @@ -282,13 +280,13 @@ public void TestRgroupQueryFile3() { Assert.AreEqual(((PseudoAtom)at).Label, "R1"); - IDictionary apoBonds = rGroupQuery.RootAttachmentPoints[at]; + var apoBonds = rGroupQuery.RootAttachmentPoints[at]; Assert.AreEqual(apoBonds.Count, 2); - IAtom boundAtom1 = apoBonds[1].GetOther(at); + var boundAtom1 = apoBonds[1].GetOther(at); Assert.IsTrue(boundAtom1.Symbol.Equals("Te") || boundAtom1.Symbol.Equals("S")); - IAtom boundAtom2 = apoBonds[2].GetOther(at); + var boundAtom2 = apoBonds[2].GetOther(at); Assert.IsTrue(boundAtom2.Symbol.Equals("Po") || boundAtom2.Symbol.Equals("O")); } } @@ -307,11 +305,11 @@ public void TestRgroupQueryFile3() [TestMethod()] public void TestRgroupQueryFile4() { - string filename = "NCDK.Data.MDL.rgfile.4.mol"; + var filename = "NCDK.Data.MDL.rgfile.4.mol"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + var reader = new RGroupQueryReader(ins); + var rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 1); @@ -319,14 +317,14 @@ public void TestRgroupQueryFile4() var allrGroupQueryAtoms = rGroupQuery.GetAllRgroupQueryAtoms(); Assert.AreEqual(allrGroupQueryAtoms.Count, 1); - RGroupList rList = rGroupQuery.RGroupDefinitions[1]; + var rList = rGroupQuery.RGroupDefinitions[1]; Assert.AreEqual(rList.RGroups.Count, 2); Assert.AreEqual(rList.RequiredRGroupNumber, 0); Assert.IsFalse(rList.IsRestH); Assert.AreEqual(rGroupQuery.RootAttachmentPoints.Count, 0); Assert.IsTrue(rGroupQuery.AreSubstituentsDefined()); - Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count, 2); + Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count(), 2); // This query has a detached R-group, test for empty attachment points var rGroups = rList.RGroups; @@ -345,17 +343,17 @@ public void TestRgroupQueryFile4() [TestCategory("SlowTest")] public void TestRgroupQueryFile5() { - string filename = "NCDK.Data.MDL.rgfile.5.mol"; + var filename = "NCDK.Data.MDL.rgfile.5.mol"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + var reader = new RGroupQueryReader(ins); + var rGroupQuery = reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 4); //Test combinatorial explosion: R5 has many different configurations - Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count, 17820); + Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count(), 17820); } /// @@ -367,11 +365,11 @@ public void TestRgroupQueryFile5() [ExpectedException(typeof(CDKException))] public void TestRgroupQueryFile6() { - string filename = "NCDK.Data.MDL.rgfile.6.mol"; + var filename = "NCDK.Data.MDL.rgfile.6.mol"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + var reader = new RGroupQueryReader(ins); + var rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 3); @@ -383,7 +381,6 @@ public void TestRgroupQueryFile6() //Getting for all configurations won't happen, because not all groups were set rGroupQuery.GetAllConfigurations(); // Will raise exception - } /// @@ -397,16 +394,16 @@ public void TestRgroupQueryFile6() [TestMethod()] public void TestRgroupQueryFile7() { - string filename = "NCDK.Data.MDL.rgfile.7.mol"; + var filename = "NCDK.Data.MDL.rgfile.7.mol"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); - RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + var reader = new RGroupQueryReader(ins); + var rGroupQuery = reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); reader.Close(); Assert.IsNotNull(rGroupQuery); Assert.AreEqual(rGroupQuery.RGroupDefinitions.Count, 1); Assert.AreEqual(rGroupQuery.RootStructure.Atoms.Count, 9); - Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count, 20); + Assert.AreEqual(rGroupQuery.GetAllConfigurations().Count(), 20); } } } diff --git a/NCDKTests/IO/RGroupQueryWriterTest.cs b/NCDKTests/IO/RGroupQueryWriterTest.cs index ed92192f..a777149a 100644 --- a/NCDKTests/IO/RGroupQueryWriterTest.cs +++ b/NCDKTests/IO/RGroupQueryWriterTest.cs @@ -26,6 +26,7 @@ using System.IO; using System.Text.RegularExpressions; using System; +using NCDK.Silent; namespace NCDK.IO { @@ -41,7 +42,7 @@ namespace NCDK.IO public class RGroupQueryWriterTest : ChemObjectIOTest { protected override Type ChemObjectIOToTestType => typeof(RGroupQueryWriter); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public override void TestAcceptsAtLeastOneChemObjectClass() @@ -143,7 +144,7 @@ private string Recreate(string file) RGroupQueryWriter rgw = new RGroupQueryWriter(sw); var ins = ResourceLoader.GetAsStream(file); RGroupQueryReader reader = new RGroupQueryReader(ins); - RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(Default.ChemObjectBuilder.Instance)); + RGroupQuery rGroupQuery = (RGroupQuery)reader.Read(new RGroupQuery(ChemObjectBuilder.Instance)); rgw.Write(rGroupQuery); string output = sw.ToString(); return output; diff --git a/NCDKTests/IO/RandomAccess/RandomAccessTest.cs b/NCDKTests/IO/RandomAccess/RandomAccessTest.cs index 6a7d91de..aaf03933 100644 --- a/NCDKTests/IO/RandomAccess/RandomAccessTest.cs +++ b/NCDKTests/IO/RandomAccess/RandomAccessTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; @@ -55,7 +56,7 @@ public void Test() //System.Console.Out.WriteLine(System.GetProperty("user.dir")); - RandomAccessReader rf = new RandomAccessSDFReader(f, Default.ChemObjectBuilder.Instance); + RandomAccessReader rf = new RandomAccessSDFReader(f, ChemObjectBuilder.Instance); try { Assert.AreEqual(6, rf.Count); diff --git a/NCDKTests/IO/ReaderFactoryTest.cs b/NCDKTests/IO/ReaderFactoryTest.cs index 8b2e06da..361fea35 100644 --- a/NCDKTests/IO/ReaderFactoryTest.cs +++ b/NCDKTests/IO/ReaderFactoryTest.cs @@ -23,7 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Formats; using NCDK.Tools.Manipulator; using System.IO; diff --git a/NCDKTests/IO/SDFReaderTest.cs b/NCDKTests/IO/SDFReaderTest.cs index f9bf589a..bf895d54 100644 --- a/NCDKTests/IO/SDFReaderTest.cs +++ b/NCDKTests/IO/SDFReaderTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/IO/SDFWriterTest.cs b/NCDKTests/IO/SDFWriterTest.cs index 5e43b2b0..1e9a851c 100644 --- a/NCDKTests/IO/SDFWriterTest.cs +++ b/NCDKTests/IO/SDFWriterTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Listener; using NCDK.Smiles; using NCDK.Templates; @@ -40,7 +40,7 @@ namespace NCDK.IO public class SDFWriterTest : ChemObjectWriterTest { protected override Type ChemObjectIOToTestType => typeof(SDFWriter); - private static IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private static IChemObjectBuilder builder = ChemObjectBuilder.Instance; [TestMethod()] public void TestAccepts() @@ -112,13 +112,13 @@ public void TestWrite_IAtomContainerSet_CDKProperties() IChemObjectSet molSet = new ChemObjectSet(); IAtomContainer molecule = new AtomContainer(); molecule.Atoms.Add(new Atom("C")); - molecule.SetProperty(InvPair.CanonicalLabelKey, "bar"); + molecule.SetProperty(InvPair.CanonicalLabelPropertyKey, "bar"); molSet.Add(molecule); SDFWriter sdfWriter = new SDFWriter(writer); sdfWriter.Write(molSet); sdfWriter.Close(); - Assert.IsTrue(writer.ToString().IndexOf(InvPair.CanonicalLabelKey) == -1); + Assert.IsTrue(writer.ToString().IndexOf(InvPair.CanonicalLabelPropertyKey) == -1); } [TestMethod()] @@ -322,7 +322,7 @@ public void TestPropertyOutput_none() { IAtomContainer adenine = TestMoleculeFactory.MakeAdenine(); StringWriter sw = new StringWriter(); - SDFWriter sdf = new SDFWriter(sw, new string[0]); + SDFWriter sdf = new SDFWriter(sw, Array.Empty()); adenine.SetProperty("one", "a"); adenine.SetProperty("two", "b"); sdf.Write(adenine); diff --git a/NCDKTests/IO/SMILESReaderTest.cs b/NCDKTests/IO/SMILESReaderTest.cs index 31dccb60..e24be4dd 100644 --- a/NCDKTests/IO/SMILESReaderTest.cs +++ b/NCDKTests/IO/SMILESReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Iterator; using System; using System.Diagnostics; diff --git a/NCDKTests/IO/SMILESWriterTest.cs b/NCDKTests/IO/SMILESWriterTest.cs index 20c8e376..e623e236 100644 --- a/NCDKTests/IO/SMILESWriterTest.cs +++ b/NCDKTests/IO/SMILESWriterTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO.Listener; using NCDK.Templates; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/IO/ShelXReaderTest.cs b/NCDKTests/IO/ShelXReaderTest.cs index 90d5cb5c..fd2d8b5f 100644 --- a/NCDKTests/IO/ShelXReaderTest.cs +++ b/NCDKTests/IO/ShelXReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using System; using System.Diagnostics; diff --git a/NCDKTests/IO/ShelXWriterTest.cs b/NCDKTests/IO/ShelXWriterTest.cs index 58f0ecf8..21cbae27 100644 --- a/NCDKTests/IO/ShelXWriterTest.cs +++ b/NCDKTests/IO/ShelXWriterTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using System.IO; diff --git a/NCDKTests/IO/VASPReaderTest.cs b/NCDKTests/IO/VASPReaderTest.cs index 7186211f..3ad59d41 100644 --- a/NCDKTests/IO/VASPReaderTest.cs +++ b/NCDKTests/IO/VASPReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/WriterFactoryTest.cs b/NCDKTests/IO/WriterFactoryTest.cs index 5094b739..90d1f093 100644 --- a/NCDKTests/IO/WriterFactoryTest.cs +++ b/NCDKTests/IO/WriterFactoryTest.cs @@ -45,7 +45,7 @@ public void TestFormatCount() [TestMethod()] public void TestFindChemFormats() { - IChemFormat[] formats = factory.FindChemFormats(DataFeatures.HAS_3D_COORDINATES); + IChemFormat[] formats = factory.FindChemFormats(DataFeatures.Has3DCoordinates); Assert.IsNotNull(formats); Assert.IsTrue(formats.Length > 0); } @@ -63,7 +63,7 @@ public void TestCreateWriter_IChemFormat() public void TestCustomWriter() { WriterFactory factory = new WriterFactory(); - factory.RegisterWriter(typeof(CustomWriter)); + WriterFactory.RegisterWriter(typeof(CustomWriter)); IChemObjectWriter writer = factory.CreateWriter(new CustomFormat(), new StringWriter()); Assert.IsNotNull(writer); Assert.AreEqual(new CustomWriter(new StringWriter()).GetType().Name, writer.GetType().Name); diff --git a/NCDKTests/IO/XYZReaderTest.cs b/NCDKTests/IO/XYZReaderTest.cs index 0f851057..60354006 100644 --- a/NCDKTests/IO/XYZReaderTest.cs +++ b/NCDKTests/IO/XYZReaderTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/IO/XYZWriterTest.cs b/NCDKTests/IO/XYZWriterTest.cs index 996f3cde..bf3292aa 100644 --- a/NCDKTests/IO/XYZWriterTest.cs +++ b/NCDKTests/IO/XYZWriterTest.cs @@ -22,7 +22,7 @@ */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.IO; using System; diff --git a/NCDKTests/IO/ZMatrixReaderTest.cs b/NCDKTests/IO/ZMatrixReaderTest.cs index 3c5b7356..dee3f734 100644 --- a/NCDKTests/IO/ZMatrixReaderTest.cs +++ b/NCDKTests/IO/ZMatrixReaderTest.cs @@ -23,7 +23,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.IO; diff --git a/NCDKTests/Isomorphisms/ComponentGroupingTest.cs b/NCDKTests/Isomorphisms/ComponentGroupingTest.cs index 2e492282..e3469f1d 100644 --- a/NCDKTests/Isomorphisms/ComponentGroupingTest.cs +++ b/NCDKTests/Isomorphisms/ComponentGroupingTest.cs @@ -22,7 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; namespace NCDK.Isomorphisms diff --git a/NCDKTests/Isomorphisms/IsomorphismTesterTest.cs b/NCDKTests/Isomorphisms/IsomorphismTesterTest.cs index 8b3e0115..2914cca7 100644 --- a/NCDKTests/Isomorphisms/IsomorphismTesterTest.cs +++ b/NCDKTests/Isomorphisms/IsomorphismTesterTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/Isomorphisms/MappingsTest.cs b/NCDKTests/Isomorphisms/MappingsTest.cs index ee26228f..ea3623a8 100644 --- a/NCDKTests/Isomorphisms/MappingsTest.cs +++ b/NCDKTests/Isomorphisms/MappingsTest.cs @@ -52,14 +52,14 @@ public void Filter() Mappings ms = new Mappings(new Mock().Object, new Mock().Object, iterable); - System.Predicate f = n => - { - if (n == p1) return false; - if (n == p2) return true; - if (n == p3) return false; - if (n == p4) return true; - throw new InvalidOperationException(); - }; + bool f(int[] n) + { + if (n == p1) return false; + if (n == p2) return true; + if (n == p3) return false; + if (n == p4) return true; + throw new InvalidOperationException(); + } Assert.IsTrue(Compares.AreDeepEqual(new int[][] { p2, p4 }, ms.Filter(f).ToArray())); } @@ -116,7 +116,7 @@ public void Limit() var m_iterator = new Mock>(); var iterator = m_iterator.Object; m_iterable.Setup(n => n.GetEnumerator()).Returns(iterator); m_iterator.SetupSequence(n => n.MoveNext()).Returns(true).Returns(true).Returns(true).Returns(true).Returns(true).Returns(false); - m_iterator.SetupGet(n => n.Current).Returns(new int[0]); + m_iterator.SetupGet(n => n.Current).Returns(Array.Empty()); Mappings ms = new Mappings(new Mock().Object, new Mock().Object, iterable); Assert.AreEqual(2, ms.Limit(2).Count()); @@ -170,11 +170,11 @@ public void ToAtomMap() var iterator = iterable.GetEnumerator(); Assert.IsTrue(iterator.MoveNext()); - IDictionary m1 = iterator.Current; + var m1 = iterator.Current; Assert.AreEqual(m1[query.Atoms[0]], target.Atoms[0]); Assert.AreEqual(m1[query.Atoms[1]], target.Atoms[1]); Assert.IsTrue(iterator.MoveNext()); - IDictionary m2 = iterator.Current; + var m2 = iterator.Current; Assert.AreEqual(m2[query.Atoms[0]], target.Atoms[1]); Assert.AreEqual(m2[query.Atoms[1]], target.Atoms[0]); Assert.IsFalse(iterator.MoveNext()); @@ -190,11 +190,11 @@ public void ToBondMap() var iterator = iterable.GetEnumerator(); Assert.IsTrue(iterator.MoveNext()); - IDictionary m1 = iterator.Current; + var m1 = iterator.Current; Assert.AreEqual(m1[query.Bonds[0]], target.Bonds[0]); Assert.AreEqual(m1[query.Bonds[1]], target.Bonds[1]); Assert.IsTrue(iterator.MoveNext()); - IDictionary m2 = iterator.Current; + var m2 = iterator.Current; Assert.AreEqual(m2[query.Bonds[0]], target.Bonds[1]); Assert.AreEqual(m2[query.Bonds[1]], target.Bonds[0]); Assert.IsFalse(iterator.MoveNext()); @@ -210,14 +210,14 @@ public void ToAtomBondMap() var iterator = iterable.GetEnumerator(); Assert.IsTrue(iterator.MoveNext()); - IDictionary m1 = iterator.Current; + var m1 = iterator.Current; Assert.AreEqual(m1[query.Atoms[0]], (IChemObject)target.Atoms[0]); Assert.AreEqual(m1[query.Atoms[1]], (IChemObject)target.Atoms[1]); Assert.AreEqual(m1[query.Atoms[2]], (IChemObject)target.Atoms[2]); Assert.AreEqual(m1[query.Bonds[0]], (IChemObject)target.Bonds[0]); Assert.AreEqual(m1[query.Bonds[1]], (IChemObject)target.Bonds[1]); Assert.IsTrue(iterator.MoveNext()); - IDictionary m2 = iterator.Current; + var m2 = iterator.Current; Assert.AreEqual(m2[query.Atoms[0]], (IChemObject)target.Atoms[2]); Assert.AreEqual(m2[query.Atoms[1]], (IChemObject)target.Atoms[1]); Assert.AreEqual(m2[query.Atoms[2]], (IChemObject)target.Atoms[0]); @@ -258,7 +258,7 @@ public void AtLeast() var m_iterator = new Mock>(); var iterator = m_iterator.Object; m_iterable.Setup(n => n.GetEnumerator()).Returns(iterator); m_iterator.SetupSequence(n => n.MoveNext()).Returns(true).Returns(true).Returns(true).Returns(true).Returns(true).Returns(false); - m_iterator.SetupGet(n => n.Current).Returns(new int[0]); + m_iterator.SetupGet(n => n.Current).Returns(Array.Empty()); Mappings ms = new Mappings(new Mock().Object, new Mock().Object, iterable); @@ -274,8 +274,8 @@ public void First() m_iterable.Setup(n => n.GetEnumerator()).Returns(iterator); m_iterator.SetupSequence(n => n.MoveNext()).Returns(true).Returns(true).Returns(false); - int[] p1 = new int[0]; - int[] p2 = new int[0]; + int[] p1 = Array.Empty(); + int[] p2 = Array.Empty(); m_iterator.SetupSequence(n => n.Current).Returns(p1).Returns(p2); @@ -290,7 +290,7 @@ public void Count() var m_iterator = new Mock>(); var iterator = m_iterator.Object; m_iterable.Setup(n => n.GetEnumerator()).Returns(iterator); m_iterator.SetupSequence(n => n.MoveNext()).Returns(true).Returns(true).Returns(true).Returns(true).Returns(true).Returns(false); - m_iterator.SetupSequence(n => n.Current).Returns(new int[0]); + m_iterator.SetupSequence(n => n.Current).Returns(Array.Empty()); Mappings ms = new Mappings(new Mock().Object, new Mock().Object, iterable); Assert.AreEqual(5, ms.Count()); diff --git a/NCDKTests/Isomorphisms/Matchers/RGroupListTest.cs b/NCDKTests/Isomorphisms/Matchers/RGroupListTest.cs index 5a54a36a..a45b9d9a 100644 --- a/NCDKTests/Isomorphisms/Matchers/RGroupListTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/RGroupListTest.cs @@ -47,7 +47,7 @@ public void TestOccurrenceNull() { RGroupList rgrLst = new RGroupList(1); rgrLst.Occurrence = null; - Assert.AreEqual(rgrLst.Occurrence, RGroupList.DEFAULT_OCCURRENCE); + Assert.AreEqual(rgrLst.Occurrence, RGroupList.DefaultOccurence); } [TestMethod()] diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyAtomTest.cs index 3f72917d..040519c9 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyAtomTest.cs @@ -22,7 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Isomorphisms.Matchers.SMARTS { diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyOrderQueryBondTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyOrderQueryBondTest.cs index 466b3f62..15294e79 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyOrderQueryBondTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/AnyOrderQueryBondTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Isomorphisms.Matchers.SMARTS { diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/ExplicitConnectionAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/ExplicitConnectionAtomTest.cs index 45928766..7d1b32f7 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/ExplicitConnectionAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/ExplicitConnectionAtomTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using System; namespace NCDK.Isomorphisms.Matchers.SMARTS { @@ -40,7 +41,7 @@ public void Matches() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 0, 0, - new int[0], 0, 0, // <- degree not used due to old CDK bug + Array.Empty(), 0, 0, // <- degree not used due to old CDK bug 2, 0)); Assert.IsTrue(matcher.Matches(atom)); } diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/RingMembershipAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/RingMembershipAtomTest.cs index 0817349c..1264c987 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/RingMembershipAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/RingMembershipAtomTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using System; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace NCDK.Isomorphisms.Matchers.SMARTS @@ -42,7 +43,7 @@ public void Matches() mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants( new Mock().Object, 0, 2, - new int[0], 0, 0, 0, 0)); + Array.Empty(), 0, 0, 0, 0)); Assert.IsTrue(matcher.Matches(atom)); } @@ -55,7 +56,7 @@ public void Mismatches() mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants( new Mock().Object, 0, 1, - new int[0], 0, 0, 0, 0)); + Array.Empty(), 0, 0, 0, 0)); Assert.IsFalse(matcher.Matches(atom)); } @@ -67,7 +68,7 @@ public void None() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 0, 0, - new int[0], 0, 0, 0, 0)); + Array.Empty(), 0, 0, 0, 0)); Assert.IsTrue(matcher.Matches(atom)); } @@ -79,7 +80,7 @@ public void Any() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 0, 5, - new int[0], 2, 0, 0, 0)); + Array.Empty(), 2, 0, 0, 0)); Assert.IsTrue(matcher.Matches(atom)); } } diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalConnectionAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalConnectionAtomTest.cs index eeff4bbc..3a7d5256 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalConnectionAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalConnectionAtomTest.cs @@ -24,7 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; -using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; +using System; namespace NCDK.Isomorphisms.Matchers.SMARTS { @@ -41,8 +41,7 @@ public void Matches() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 0, 0, - new int[0], 0, - 0, 2, 0)); + Array.Empty(), 0, 0, 2, 0)); Assert.IsTrue(matcher.Matches(atom)); } } diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalHCountAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalHCountAtomTest.cs index 130b515b..ef078c1d 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalHCountAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalHCountAtomTest.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using System; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace NCDK.Isomorphisms.Matchers.SMARTS @@ -17,7 +18,7 @@ public void Matches() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 0, 0, - new int[0], 0, + Array.Empty(), 0, 0, 0, 4)); Assert.IsTrue(matcher.Matches(atom)); } diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalRingConnectionAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalRingConnectionAtomTest.cs index b8a97ce6..7002590e 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalRingConnectionAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalRingConnectionAtomTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using System; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace NCDK.Isomorphisms.Matchers.SMARTS @@ -41,7 +42,7 @@ public void Matches() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 0, 0, - new int[0], 2, + Array.Empty(), 2, 0, 0, 0)); Assert.IsTrue(matcher.Matches(atom)); } diff --git a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalValencyAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalValencyAtomTest.cs index c2cec64f..0d18122f 100644 --- a/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalValencyAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SMARTS/TotalValencyAtomTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using System; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace NCDK.Isomorphisms.Matchers.SMARTS @@ -41,7 +42,7 @@ public void Matches() IAtom atom = mock_atom.Object; mock_atom.Setup(n => n.GetProperty(SMARTSAtomInvariants.Key)).Returns( new SMARTSAtomInvariants(new Mock().Object, 4, 0, - new int[0], 0, + Array.Empty(), 0, 0, 0, 0)); Assert.IsTrue(matcher.Matches(atom)); } diff --git a/NCDKTests/Isomorphisms/Matchers/SymbolSetQueryAtomTest.cs b/NCDKTests/Isomorphisms/Matchers/SymbolSetQueryAtomTest.cs index 10d04f16..96b88e35 100644 --- a/NCDKTests/Isomorphisms/Matchers/SymbolSetQueryAtomTest.cs +++ b/NCDKTests/Isomorphisms/Matchers/SymbolSetQueryAtomTest.cs @@ -18,7 +18,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Isomorphisms.Matchers { @@ -33,7 +33,7 @@ public class SymbolSetQueryAtomTest : CDKTestCase static SymbolSetQueryAtomTest() { - symbolSet = new SymbolSetQueryAtom(Default.ChemObjectBuilder.Instance); + symbolSet = new SymbolSetQueryAtom(ChemObjectBuilder.Instance); symbolSet.Symbols.Add("C"); symbolSet.Symbols.Add("Fe"); } diff --git a/NCDKTests/Isomorphisms/SMARTSTest.cs b/NCDKTests/Isomorphisms/SMARTSTest.cs index 2fe53773..e32abac1 100644 --- a/NCDKTests/Isomorphisms/SMARTSTest.cs +++ b/NCDKTests/Isomorphisms/SMARTSTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms.Matchers; using NCDK.Smiles; using NCDK.Templates; @@ -37,7 +37,7 @@ public class SMARTSTest : CDKTestCase [TestMethod()] public void TestStrictSMARTS() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser sp = new SmilesParser(builder); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride @@ -56,7 +56,7 @@ public void TestStrictSMARTS() [TestMethod()] public void TestSMARTS() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser sp = new SmilesParser(builder); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride var query = new QueryAtomContainer(builder); @@ -88,7 +88,7 @@ public void TestImplicitHCountAtom() { IAtomContainer container = CreateEthane(); - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; QueryAtomContainer query1 = new QueryAtomContainer(builder); // SMARTS [h3][h3] var atom1 = new Matchers.SMARTS.ImplicitHCountAtom(3, builder); @@ -104,7 +104,7 @@ public void TestImplicitHCountAtom2() { IAtomContainer container = CreateEthane(); - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; QueryAtomContainer query1 = new QueryAtomContainer(builder); // SMARTS [h3][h2] var atom1 = new Matchers.SMARTS.ImplicitHCountAtom(3, builder); @@ -120,7 +120,7 @@ public void TestMatchInherited() { try { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SymbolQueryAtom c1 = new SymbolQueryAtom(new Atom("C")); SymbolAndChargeQueryAtom c2 = new SymbolAndChargeQueryAtom(new Atom("C")); diff --git a/NCDKTests/Isomorphisms/SmartsStereoMatchTest.cs b/NCDKTests/Isomorphisms/SmartsStereoMatchTest.cs index 1966ff44..b1b68544 100644 --- a/NCDKTests/Isomorphisms/SmartsStereoMatchTest.cs +++ b/NCDKTests/Isomorphisms/SmartsStereoMatchTest.cs @@ -23,7 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles.SMARTS.Parser; using NCDK.Stereo; using System.Collections.Generic; diff --git a/NCDKTests/Isomorphisms/StateStreamTest.cs b/NCDKTests/Isomorphisms/StateStreamTest.cs index 680a1e88..06f0d6e2 100644 --- a/NCDKTests/Isomorphisms/StateStreamTest.cs +++ b/NCDKTests/Isomorphisms/StateStreamTest.cs @@ -101,8 +101,8 @@ VFSubState CreateBenzeneToNaphthalene(AtomMatcher atomMatcher, BondMatcher bondM { IAtomContainer container1 = TestMoleculeFactory.MakeBenzene(); IAtomContainer container2 = TestMoleculeFactory.MakeNaphthalene(); - GraphUtil.EdgeToBondMap bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(container1); - GraphUtil.EdgeToBondMap bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(container2); + EdgeToBondMap bonds1 = EdgeToBondMap.WithSpaceFor(container1); + EdgeToBondMap bonds2 = EdgeToBondMap.WithSpaceFor(container2); int[][] g1 = GraphUtil.ToAdjList(container1, bonds1); int[][] g2 = GraphUtil.ToAdjList(container2, bonds2); return new VFSubState(container1, container2, g1, g2, bonds1, bonds2, atomMatcher, bondMatcher); @@ -119,8 +119,8 @@ VFSubState CreateNaphthaleneToBenzene(AtomMatcher atomMatcher, BondMatcher bondM { IAtomContainer container1 = TestMoleculeFactory.MakeNaphthalene(); IAtomContainer container2 = TestMoleculeFactory.MakeBenzene(); - GraphUtil.EdgeToBondMap bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(container1); - GraphUtil.EdgeToBondMap bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(container2); + EdgeToBondMap bonds1 = EdgeToBondMap.WithSpaceFor(container1); + EdgeToBondMap bonds2 = EdgeToBondMap.WithSpaceFor(container2); int[][] g1 = GraphUtil.ToAdjList(container1, bonds1); int[][] g2 = GraphUtil.ToAdjList(container2, bonds2); return new VFSubState(container1, container2, g1, g2, bonds1, bonds2, atomMatcher, bondMatcher); diff --git a/NCDKTests/Isomorphisms/UllmannStateTest.cs b/NCDKTests/Isomorphisms/UllmannStateTest.cs index 4445caf3..49656b62 100644 --- a/NCDKTests/Isomorphisms/UllmannStateTest.cs +++ b/NCDKTests/Isomorphisms/UllmannStateTest.cs @@ -249,8 +249,8 @@ UllmannState CreateBenzeneToNaphthalene(AtomMatcher atomMatcher, BondMatcher bon { IAtomContainer container1 = TestMoleculeFactory.MakeBenzene(); IAtomContainer container2 = TestMoleculeFactory.MakeNaphthalene(); - GraphUtil.EdgeToBondMap bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(container1); - GraphUtil.EdgeToBondMap bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(container2); + EdgeToBondMap bonds1 = EdgeToBondMap.WithSpaceFor(container1); + EdgeToBondMap bonds2 = EdgeToBondMap.WithSpaceFor(container2); int[][] g1 = GraphUtil.ToAdjList(container1, bonds1); int[][] g2 = GraphUtil.ToAdjList(container2, bonds2); return new UllmannState(container1, container2, g1, g2, bonds1, bonds2, atomMatcher, bondMatcher); diff --git a/NCDKTests/Isomorphisms/UllmannTest.cs b/NCDKTests/Isomorphisms/UllmannTest.cs index 46da5e28..0e027dcd 100644 --- a/NCDKTests/Isomorphisms/UllmannTest.cs +++ b/NCDKTests/Isomorphisms/UllmannTest.cs @@ -25,6 +25,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Templates; using System.Linq; +using System; namespace NCDK.Isomorphisms { @@ -55,7 +56,7 @@ public void NapthaleneSubsearch() int[] match = Ullmann.FindSubstructure( TestMoleculeFactory.MakeNaphthalene()).Match( TestMoleculeFactory.MakeBenzene()); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], match)); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), match)); int count = Ullmann.FindSubstructure( TestMoleculeFactory.MakeNaphthalene()).MatchAll( TestMoleculeFactory.MakeBenzene()).ToList().Count; diff --git a/NCDKTests/Isomorphisms/UniversalIsomorphismTesterTest.cs b/NCDKTests/Isomorphisms/UniversalIsomorphismTesterTest.cs index 70253f94..986dcda6 100644 --- a/NCDKTests/Isomorphisms/UniversalIsomorphismTesterTest.cs +++ b/NCDKTests/Isomorphisms/UniversalIsomorphismTesterTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.AtomTypes; +using NCDK.Common.Base; using NCDK.Graphs; using NCDK.IO; using NCDK.Isomorphisms.Matchers; @@ -42,14 +43,14 @@ namespace NCDK.Isomorphisms [TestClass()] public class UniversalIsomorphismTesterTest : CDKTestCase { - bool standAlone = false; + readonly bool standAlone = false; private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester(); [TestMethod()] - public void TestIsSubgraph_IAtomContainer_IAtomContainer() + public void TestIsSubgraphIAtomContainerIAtomContainer() { - IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); - IAtomContainer frag1 = TestMoleculeFactory.MakeCyclohexene(); //one double bond in ring + var mol = TestMoleculeFactory.MakeAlphaPinene(); + var frag1 = TestMoleculeFactory.MakeCyclohexene(); //one double bond in ring AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(frag1); Aromaticity.CDKLegacy.Apply(mol); @@ -57,7 +58,7 @@ public void TestIsSubgraph_IAtomContainer_IAtomContainer() if (standAlone) { - Console.Out.WriteLine("Cyclohexene is a subgraph of alpha-Pinen: " + uiTester.IsSubgraph(mol, frag1)); + Console.Out.WriteLine("Cyclohexene is a subgraph of alpha-Pinene: " + uiTester.IsSubgraph(mol, frag1)); } else { @@ -70,29 +71,20 @@ public void TestIsSubgraph_IAtomContainer_IAtomContainer() [TestMethod()] public void TestSFBug1708336() { - IChemObjectBuilder builder = ChemObjectBuilder.Instance; - IAtomContainer atomContainer = builder.NewAtomContainer(); + var builder = ChemObjectBuilder.Instance; + var atomContainer = builder.NewAtomContainer(); atomContainer.Atoms.Add(builder.NewAtom("C")); atomContainer.Atoms.Add(builder.NewAtom("C")); atomContainer.Atoms.Add(builder.NewAtom("N")); atomContainer.AddBond(atomContainer.Atoms[0], atomContainer.Atoms[1], BondOrder.Single); atomContainer.AddBond(atomContainer.Atoms[1], atomContainer.Atoms[2], BondOrder.Single); - IQueryAtomContainer query = new QueryAtomContainer(ChemObjectBuilder.Instance); - IQueryAtom a1 = new SymbolQueryAtom(ChemObjectBuilder.Instance) - { - Symbol = "C" - }; - + var a1 = new SymbolQueryAtom(ChemObjectBuilder.Instance) { Symbol = "C" }; var a2 = new Matchers.SMARTS.AnyAtom(ChemObjectBuilder.Instance); + var b1 = new OrderQueryBond(a1, a2, BondOrder.Single, ChemObjectBuilder.Instance); + var a3 = new SymbolQueryAtom(ChemObjectBuilder.Instance) { Symbol = "C" }; + var b2 = new OrderQueryBond(a2, a3, BondOrder.Single, ChemObjectBuilder.Instance); - IBond b1 = new OrderQueryBond(a1, a2, BondOrder.Single, ChemObjectBuilder.Instance); - - IQueryAtom a3 = new SymbolQueryAtom(ChemObjectBuilder.Instance) - { - Symbol = "C" - }; - - IBond b2 = new OrderQueryBond(a2, a3, BondOrder.Single, ChemObjectBuilder.Instance); + var query = new QueryAtomContainer(ChemObjectBuilder.Instance); query.Atoms.Add(a1); query.Atoms.Add(a2); query.Atoms.Add(a3); @@ -102,14 +94,14 @@ public void TestSFBug1708336() var list = uiTester.GetSubgraphMaps(atomContainer, query); - Assert.IsTrue(list.Count == 0); + Assert.IsTrue(list.Count() == 0); } [TestMethod()] public void Test2() { - IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); - IAtomContainer frag1 = TestMoleculeFactory.MakeCyclohexane(); // no double bond in ring + var mol = TestMoleculeFactory.MakeAlphaPinene(); + var frag1 = TestMoleculeFactory.MakeCyclohexane(); // no double bond in ring AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(frag1); Aromaticity.CDKLegacy.Apply(mol); @@ -117,7 +109,7 @@ public void Test2() if (standAlone) { - Console.Out.WriteLine("Cyclohexane is a subgraph of alpha-Pinen: " + uiTester.IsSubgraph(mol, frag1)); + Console.Out.WriteLine($"Cyclohexane is a subgraph of alpha-Pinene: {uiTester.IsSubgraph(mol, frag1)}"); } else { @@ -128,8 +120,8 @@ public void Test2() [TestMethod()] public void Test3() { - IAtomContainer mol = TestMoleculeFactory.MakeIndole(); - IAtomContainer frag1 = TestMoleculeFactory.MakePyrrole(); + var mol = TestMoleculeFactory.MakeIndole(); + var frag1 = TestMoleculeFactory.MakePyrrole(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(frag1); Aromaticity.CDKLegacy.Apply(mol); @@ -148,28 +140,28 @@ public void Test3() [TestMethod()] public void TestBasicQueryAtomContainer() { - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride - IAtomContainer SMILESquery = sp.ParseSmiles("CC"); // acetic acid anhydride + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride + var SMILESquery = sp.ParseSmiles("CC"); // acetic acid anhydride var query = QueryAtomContainerCreator.CreateBasicQueryContainer(SMILESquery); Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); } [TestMethod()] - public void TestGetSubgraphAtomsMaps_IAtomContainer() + public void TestGetSubgraphAtomsMapsIAtomContainer() { int[] result1 = { 6, 5, 7, 8, 0 }; int[] result2 = { 3, 4, 2, 1, 0 }; - IAtomContainer mol = TestMoleculeFactory.MakeIndole(); - IAtomContainer frag1 = TestMoleculeFactory.MakePyrrole(); + var mol = TestMoleculeFactory.MakeIndole(); + var frag1 = TestMoleculeFactory.MakePyrrole(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(frag1); Aromaticity.CDKLegacy.Apply(mol); Aromaticity.CDKLegacy.Apply(frag1); - var list = uiTester.GetSubgraphAtomsMaps(mol, frag1); + var list = uiTester.GetSubgraphAtomsMaps(mol, frag1).ToList(); var first = list[0]; for (int i = 0; i < first.Count; i++) { @@ -180,25 +172,25 @@ public void TestGetSubgraphAtomsMaps_IAtomContainer() } [TestMethod()] - public void TestGetSubgraphMap_IAtomContainer_IAtomContainer() + public void TestGetSubgraphMapIAtomContainerIAtomContainer() { - string molfile = "NCDK.Data.MDL.decalin.mol"; - string queryfile = "NCDK.Data.MDL.decalin.mol"; - IAtomContainer mol = new AtomContainer(); - IAtomContainer temp = new AtomContainer(); + var molfile = "NCDK.Data.MDL.decalin.mol"; + var queryfile = "NCDK.Data.MDL.decalin.mol"; + var mol = new AtomContainer(); + var temp = new AtomContainer(); QueryAtomContainer query1 = null; QueryAtomContainer query2 = null; var ins = ResourceLoader.GetAsStream(molfile); - MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); + var reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); reader.Read(mol); ins = ResourceLoader.GetAsStream(queryfile); reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); reader.Read(temp); query1 = QueryAtomContainerCreator.CreateBasicQueryContainer(temp); - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer atomContainer = sp.ParseSmiles("C1CCCCC1"); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var atomContainer = sp.ParseSmiles("C1CCCCC1"); query2 = QueryAtomContainerCreator.CreateBasicQueryContainer(atomContainer); var list = uiTester.GetSubgraphMap(mol, query1); @@ -206,17 +198,16 @@ public void TestGetSubgraphMap_IAtomContainer_IAtomContainer() list = uiTester.GetSubgraphMap(mol, query2); Assert.AreEqual(6, list.Count); - } // @cdk.bug 1110537 [TestMethod()] - public void TestGetOverlaps_IAtomContainer_IAtomContainer() + public void TestGetOverlapsIAtomContainerIAtomContainer() { - string file1 = "NCDK.Data.MDL.5SD.mol"; - string file2 = "NCDK.Data.MDL.ADN.mol"; - IAtomContainer mol1 = new AtomContainer(); - IAtomContainer mol2 = new AtomContainer(); + var file1 = "NCDK.Data.MDL.5SD.mol"; + var file2 = "NCDK.Data.MDL.ADN.mol"; + var mol1 = new AtomContainer(); + var mol2 = new AtomContainer(); var ins1 = ResourceLoader.GetAsStream(file1); new MDLV2000Reader(ins1, ChemObjectReaderMode.Strict).Read(mol1); @@ -236,9 +227,9 @@ public void TestGetOverlaps_IAtomContainer_IAtomContainer() [TestMethod()] public void TestBug2944080() { - SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); - IAtomContainer mol2 = smilesParser.ParseSmiles("CCC(=CC)C(=O)NC(N)=O"); + var smilesParser = new SmilesParser(ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); + var mol2 = smilesParser.ParseSmiles("CCC(=CC)C(=O)NC(N)=O"); var list = uiTester.GetOverlaps(mol1, mol2); Assert.AreEqual(1, list.Count); @@ -251,11 +242,11 @@ public void TestBug2944080() // @cdk.bug 2944080 [TestMethod()] - public void TestGetSubgraphAtomsMap_2944080() + public void TestGetSubgraphAtomsMap2944080() { - SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); - IAtomContainer mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); + var smilesParser = new SmilesParser(ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); + var mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); //Test for atom mapping between the mols var maplist = uiTester.GetSubgraphAtomsMap(mol1, mol2); @@ -265,11 +256,11 @@ public void TestGetSubgraphAtomsMap_2944080() // @cdk.bug 2944080 [TestMethod()] - public void TestGetSubgraphMap_2944080() + public void TestGetSubgraphMap2944080() { - SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); - IAtomContainer mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); + var smilesParser = new SmilesParser(ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); + var mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); //Test for atom mapping between the mols var maplist = uiTester.GetSubgraphMap(mol1, mol2); @@ -279,29 +270,28 @@ public void TestGetSubgraphMap_2944080() // @cdk.bug 2944080 [TestMethod()] - public void TestSearchNoConditions_2944080() + public void TestSearchNoConditions2944080() { - SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); - IAtomContainer mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); + var smilesParser = new SmilesParser(ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); + var mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); //Test for atom mapping between the mols - var maplist = uiTester.Search(mol1, mol2, new BitArray(mol1.Atoms.Count), - UniversalIsomorphismTester.GetBitSet(mol2), false, false); + var maplist = uiTester.Search(mol1, mol2, new BitArray(mol1.Atoms.Count), UniversalIsomorphismTester.GetBitSet(mol2), false, false); Assert.IsNotNull(maplist); - Assert.AreEqual(1, maplist.Count); + Assert.AreEqual(1, maplist.Count()); } // @cdk.bug 2944080 [TestMethod()] - public void TestSearch_2944080() + public void TestSearch2944080() { - SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); - IAtomContainer mol2 = smilesParser.ParseSmiles("CCC(=CC)C(=O)NC(N)=O"); + var smilesParser = new SmilesParser(ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); + var mol2 = smilesParser.ParseSmiles("CCC(=CC)C(=O)NC(N)=O"); //Test for atom mapping between the mols - var list = uiTester.Search(mol1, mol2, new BitArray(mol1.Atoms.Count), new BitArray(mol2.Atoms.Count), true, true); + var list = uiTester.Search(mol1, mol2, new BitArray(mol1.Atoms.Count), new BitArray(mol2.Atoms.Count), true, true).ToList(); Assert.AreEqual(3, list.Count); for (int i = 0; i < list.Count; i++) { @@ -309,7 +299,7 @@ public void TestSearch_2944080() Assert.AreNotSame(0, first.Count); } - list = uiTester.Search(mol1, mol2, new BitArray(mol1.Atoms.Count), new BitArray(mol2.Atoms.Count), false, false); + list = uiTester.Search(mol1, mol2, new BitArray(mol1.Atoms.Count), new BitArray(mol2.Atoms.Count), false, false).ToList(); Assert.AreEqual(1, list.Count); for (int i = 0; i < list.Count; i++) { @@ -320,13 +310,13 @@ public void TestSearch_2944080() // @cdk.bug 2944080 [TestMethod()] - public void TestGetSubgraphAtomsMaps_2944080() + public void TestGetSubgraphAtomsMaps2944080() { - SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); - IAtomContainer mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); + var smilesParser = new SmilesParser(ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("CCC(CC)(C(=O)NC(=O)NC(C)=O)Br"); + var mol2 = smilesParser.ParseSmiles("CCCC(=O)NC(N)=O"); - var list = uiTester.GetSubgraphAtomsMaps(mol1, mol2); + var list = uiTester.GetSubgraphAtomsMaps(mol1, mol2).ToList(); Assert.IsNotNull(list); Assert.AreNotSame(0, list.Count); for (int i = 0; i < list.Count; i++) @@ -338,10 +328,10 @@ public void TestGetSubgraphAtomsMaps_2944080() } [TestMethod()] - public void TestGetSubgraphAtomsMap_Butane() + public void TestGetSubgraphAtomsMapButane() { - IAtomContainer mol1 = TestMoleculeFactory.MakeAlkane(4); - IAtomContainer mol2 = TestMoleculeFactory.MakeAlkane(4); + var mol1 = TestMoleculeFactory.MakeAlkane(4); + var mol2 = TestMoleculeFactory.MakeAlkane(4); // Test for atom mapping between the mols var maplist = uiTester.GetSubgraphAtomsMap(mol2, mol1); @@ -354,12 +344,12 @@ public void TestGetSubgraphAtomsMap_Butane() } [TestMethod()] - public void TestGetSubgraphAtomsMaps_Butane() + public void TestGetSubgraphAtomsMapsButane() { - IAtomContainer mol1 = TestMoleculeFactory.MakeAlkane(4); - IAtomContainer mol2 = TestMoleculeFactory.MakeAlkane(4); + var mol1 = TestMoleculeFactory.MakeAlkane(4); + var mol2 = TestMoleculeFactory.MakeAlkane(4); - var list = uiTester.GetSubgraphAtomsMaps(mol1, mol2); + var list = uiTester.GetSubgraphAtomsMaps(mol1, mol2).ToList(); Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); for (int i = 0; i < list.Count; i++) @@ -374,16 +364,16 @@ public void TestGetSubgraphAtomsMaps_Butane() [TestMethod()] public void TestSFBug999330() { - string file1 = "NCDK.Data.MDL.5SD.mol"; - string file2 = "NCDK.Data.MDL.ADN.mol"; - IAtomContainer mol1 = new AtomContainer(); - IAtomContainer mol2 = new AtomContainer(); + var file1 = "NCDK.Data.MDL.5SD.mol"; + var file2 = "NCDK.Data.MDL.ADN.mol"; + var mol1 = new AtomContainer(); + var mol2 = new AtomContainer(); var ins1 = ResourceLoader.GetAsStream(file1); new MDLV2000Reader(ins1, ChemObjectReaderMode.Strict).Read(mol1); var ins2 = ResourceLoader.GetAsStream(file2); new MDLV2000Reader(ins2, ChemObjectReaderMode.Strict).Read(mol2); - AtomContainerAtomPermutor permutor = new AtomContainerAtomPermutor(mol2); + var permutor = new AtomContainerAtomPermutor(mol2); permutor.MoveNext(); mol2 = new AtomContainer((AtomContainer)permutor.Current); @@ -397,28 +387,28 @@ public void TestSFBug999330() [TestMethod()] public void TestItself() { - string smiles = "C1CCCCCCC1CC"; - var query = QueryAtomContainerCreator.CreateAnyAtomContainer(new SmilesParser( - ChemObjectBuilder.Instance).ParseSmiles(smiles), true); - IAtomContainer ac = new SmilesParser(ChemObjectBuilder.Instance).ParseSmiles(smiles); + var smiles = "C1CCCCCCC1CC"; + var query = QueryAtomContainerCreator.CreateAnyAtomContainer(new SmilesParser(ChemObjectBuilder.Instance).ParseSmiles(smiles), true); + var ac = new SmilesParser(ChemObjectBuilder.Instance).ParseSmiles(smiles); if (standAlone) { Console.Out.WriteLine("AtomCount of query: " + query.Atoms.Count); Console.Out.WriteLine("AtomCount of target: " + ac.Atoms.Count); - } bool matched = uiTester.IsSubgraph(ac, query); - if (standAlone) Console.Out.WriteLine("QueryAtomContainer matched: " + matched); - if (!standAlone) Assert.IsTrue(matched); + if (standAlone) + Console.Out.WriteLine("QueryAtomContainer matched: " + matched); + if (!standAlone) + Assert.IsTrue(matched); } [TestMethod()] - public void TestIsIsomorph_IAtomContainer_IAtomContainer() + public void TestIsIsomorphIAtomContainerIAtomContainer() { - AtomContainer ac1 = new AtomContainer(); + var ac1 = new AtomContainer(); ac1.Atoms.Add(new Atom("C")); - AtomContainer ac2 = new AtomContainer(); + var ac2 = new AtomContainer(); ac2.Atoms.Add(new Atom("C")); Assert.IsTrue(uiTester.IsIsomorph(ac1, ac2)); Assert.IsTrue(uiTester.IsSubgraph(ac1, ac2)); @@ -427,9 +417,9 @@ public void TestIsIsomorph_IAtomContainer_IAtomContainer() [TestMethod()] public void TestAnyAtomAnyBondCase() { - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer target = sp.ParseSmiles("O1C=CC=C1"); - IAtomContainer queryac = sp.ParseSmiles("C1CCCC1"); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("O1C=CC=C1"); + var queryac = sp.ParseSmiles("C1CCCC1"); var query = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(queryac, false); Assert.IsTrue(uiTester.IsSubgraph(target, query), "C1CCCC1 should be a subgraph of O1C=CC=C1"); @@ -440,9 +430,9 @@ public void TestAnyAtomAnyBondCase() [TestMethod()] public void TestFirstArgumentMustNotBeAnQueryAtomContainer() { - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer target = sp.ParseSmiles("O1C=CC=C1"); - IAtomContainer queryac = sp.ParseSmiles("C1CCCC1"); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("O1C=CC=C1"); + var queryac = sp.ParseSmiles("C1CCCC1"); var query = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(queryac, false); try @@ -459,13 +449,11 @@ public void TestFirstArgumentMustNotBeAnQueryAtomContainer() [TestMethod()] public void TestSingleAtomMatching() { + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("C"); + var query = sp.ParseSmiles("C"); - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - - IAtomContainer target = sp.ParseSmiles("C"); - IAtomContainer query = sp.ParseSmiles("C"); - - UniversalIsomorphismTester tester = new UniversalIsomorphismTester(); + var tester = new UniversalIsomorphismTester(); Assert.IsTrue(tester.IsIsomorph(target, query)); Assert.IsTrue(tester.IsIsomorph(query, target)); } @@ -473,13 +461,11 @@ public void TestSingleAtomMatching() [TestMethod()] public void TestSingleAtomMismatching() { + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("C"); + var query = sp.ParseSmiles("N"); - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - - IAtomContainer target = sp.ParseSmiles("C"); - IAtomContainer query = sp.ParseSmiles("N"); - - UniversalIsomorphismTester tester = new UniversalIsomorphismTester(); + var tester = new UniversalIsomorphismTester(); Assert.IsFalse(tester.IsIsomorph(target, query), "Single carbon and nitrogen should not match"); Assert.IsFalse(tester.IsIsomorph(query, target), "Single nitrogen and carbon should not match"); } @@ -488,31 +474,31 @@ public void TestSingleAtomMismatching() [TestMethod()] public void TestSingleAtomMatching1() { - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer target = sp.ParseSmiles("[H]"); - IAtomContainer queryac = sp.ParseSmiles("[H]"); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("[H]"); + var queryac = sp.ParseSmiles("[H]"); var query = QueryAtomContainerCreator.CreateSymbolAndBondOrderQueryContainer(queryac); - var matches = uiTester.GetIsomorphMaps(target, query); + var matches = uiTester.GetIsomorphMaps(target, query).ToList(); Assert.AreEqual(1, matches.Count); Assert.AreEqual(1, matches[0].Count); var mapping = matches[0][0]; Assert.AreEqual(0, mapping.Id1); Assert.AreEqual(0, mapping.Id2); var atomMappings = UniversalIsomorphismTester.MakeAtomsMapsOfBondsMaps(matches, target, query); - Assert.AreEqual(matches, atomMappings); + Assert.IsTrue(Compares.AreDeepEqual(matches, atomMappings)); } // @cdk.bug 2888845 [TestMethod()] public void TestSingleAtomMatching2() { - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer target = sp.ParseSmiles("CNC"); - IAtomContainer queryac = sp.ParseSmiles("C"); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("CNC"); + var queryac = sp.ParseSmiles("C"); var query = QueryAtomContainerCreator.CreateSymbolAndBondOrderQueryContainer(queryac); - var matches = uiTester.GetIsomorphMaps(target, query); + var matches = uiTester.GetIsomorphMaps(target, query).ToList(); Assert.AreEqual(2, matches.Count); Assert.AreEqual(1, matches[0].Count); Assert.AreEqual(1, matches[1].Count); @@ -526,18 +512,18 @@ public void TestSingleAtomMatching2() Assert.AreEqual(0, map2.Id2); var atomMappings = UniversalIsomorphismTester.MakeAtomsMapsOfBondsMaps(matches, target, query); - Assert.AreEqual(matches, atomMappings); + Assert.IsTrue(Compares.AreDeepEqual(matches, atomMappings)); } // @cdk.bug 2912627 [TestMethod()] public void TestSingleAtomMatching3() { - SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); - IAtomContainer target = sp.ParseSmiles("CNC"); - IAtomContainer queryac = sp.ParseSmiles("C"); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var target = sp.ParseSmiles("CNC"); + var queryac = sp.ParseSmiles("C"); - var matches = uiTester.GetIsomorphMaps(target, queryac); + var matches = uiTester.GetIsomorphMaps(target, queryac).ToList(); Assert.AreEqual(2, matches.Count); Assert.AreEqual(1, matches[0].Count); Assert.AreEqual(1, matches[1].Count); @@ -551,28 +537,28 @@ public void TestSingleAtomMatching3() Assert.AreEqual(0, map2.Id2); var atomMappings = UniversalIsomorphismTester.MakeAtomsMapsOfBondsMaps(matches, target, queryac); - Assert.AreEqual(matches, atomMappings); + Assert.IsTrue(Compares.AreDeepEqual(matches, atomMappings)); } [TestMethod()] public void TestUITTimeoutFix() { // Load molecules - string filename = "NCDK.Data.MDL.UITTimeout.sdf"; + var filename = "NCDK.Data.MDL.UITTimeout.sdf"; var ins = ResourceLoader.GetAsStream(filename); - ISimpleChemObjectReader reader = new MDLV2000Reader(ins); - ChemFile content = (ChemFile)reader.Read(new ChemFile()); + var reader = new MDLV2000Reader(ins); + var content = (ChemFile)reader.Read(new ChemFile()); var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); - IAtomContainer[] molecules = new IAtomContainer[2]; + var molecules = new IAtomContainer[2]; for (int j = 0; j < 2; j++) { - IAtomContainer aAtomContainer = (IAtomContainer)cList[j]; - CDKAtomTypeMatcher tmpMatcher = CDKAtomTypeMatcher.GetInstance(aAtomContainer.Builder); - CDKHydrogenAdder tmpAdder = CDKHydrogenAdder.GetInstance(aAtomContainer.Builder); + var aAtomContainer = (IAtomContainer)cList[j]; + var tmpMatcher = CDKAtomTypeMatcher.GetInstance(aAtomContainer.Builder); + var tmpAdder = CDKHydrogenAdder.GetInstance(aAtomContainer.Builder); for (int i = 0; i < aAtomContainer.Atoms.Count; i++) { - IAtom tmpAtom = aAtomContainer.Atoms[i]; - IAtomType tmpType = tmpMatcher.FindMatchingAtomType(aAtomContainer, tmpAtom); + var tmpAtom = aAtomContainer.Atoms[i]; + var tmpType = tmpMatcher.FindMatchingAtomType(aAtomContainer, tmpAtom); AtomTypeManipulator.Configure(tmpAtom, tmpType); tmpAdder.AddImplicitHydrogens(aAtomContainer, tmpAtom); } @@ -581,10 +567,10 @@ public void TestUITTimeoutFix() } var query = QueryAtomContainerCreator.CreateAnyAtomForPseudoAtomQueryContainer(molecules[1]); // test - long starttime = System.DateTime.Now.Ticks; + var starttime = System.DateTime.Now.Ticks; uiTester.Timeout = 200; uiTester.GetSubgraphAtomsMaps(molecules[0], query); - long duration = System.DateTime.Now.Ticks - starttime; + var duration = System.DateTime.Now.Ticks - starttime; // The search must last much longer then two seconds if the timeout not works Assert.IsTrue(duration < 2000 * 10000); // 1 msec = 10000 ticks } @@ -593,59 +579,56 @@ public void TestUITTimeoutFix() [TestMethod()] public void TestUITSymmetricMatch() { - QueryAtomContainer q = new QueryAtomContainer(ChemObjectBuilder.Instance); + var q = new QueryAtomContainer(ChemObjectBuilder.Instance); //setting atoms - IQueryAtom a0 = new Matchers.SMARTS.AliphaticSymbolAtom("C", ChemObjectBuilder.Instance); + var a0 = new Matchers.SMARTS.AliphaticSymbolAtom("C", ChemObjectBuilder.Instance); q.Atoms.Add(a0); - IQueryAtom a1 = new Matchers.SMARTS.AnyAtom(ChemObjectBuilder.Instance); + var a1 = new Matchers.SMARTS.AnyAtom(ChemObjectBuilder.Instance); q.Atoms.Add(a1); - IQueryAtom a2 = new Matchers.SMARTS.AnyAtom(ChemObjectBuilder.Instance); + var a2 = new Matchers.SMARTS.AnyAtom(ChemObjectBuilder.Instance); q.Atoms.Add(a2); - IQueryAtom a3 = new Matchers.SMARTS.AliphaticSymbolAtom("C", ChemObjectBuilder.Instance); + var a3 = new Matchers.SMARTS.AliphaticSymbolAtom("C", ChemObjectBuilder.Instance); q.Atoms.Add(a3); //setting bonds - var b0 = new Matchers.SMARTS.OrderQueryBond( - BondOrder.Single, ChemObjectBuilder.Instance); + var b0 = new Matchers.SMARTS.OrderQueryBond(BondOrder.Single, ChemObjectBuilder.Instance); b0.SetAtoms(new IAtom[] { a0, a1 }); q.Bonds.Add(b0); - var b1 = new Matchers.SMARTS.OrderQueryBond( - BondOrder.Single, ChemObjectBuilder.Instance); + var b1 = new Matchers.SMARTS.OrderQueryBond(BondOrder.Single, ChemObjectBuilder.Instance); b1.SetAtoms(new IAtom[] { a1, a2 }); q.Bonds.Add(b1); - var b2 = new Matchers.SMARTS.OrderQueryBond( - BondOrder.Single, ChemObjectBuilder.Instance); + var b2 = new Matchers.SMARTS.OrderQueryBond(BondOrder.Single, ChemObjectBuilder.Instance); b2.SetAtoms(new IAtom[] { a2, a3 }); q.Bonds.Add(b2); //Creating 'SCCS' target molecule - AtomContainer target = new AtomContainer(); + var target = new AtomContainer(); //atoms - IAtom ta0 = new Atom("S"); + var ta0 = new Atom("S"); target.Atoms.Add(ta0); - IAtom ta1 = new Atom("C"); + var ta1 = new Atom("C"); target.Atoms.Add(ta1); - IAtom ta2 = new Atom("C"); + var ta2 = new Atom("C"); target.Atoms.Add(ta2); - IAtom ta3 = new Atom("S"); + var ta3 = new Atom("S"); target.Atoms.Add(ta3); //bonds - IBond tb0 = new Bond(); + var tb0 = new Bond(); tb0.SetAtoms(new IAtom[] { ta0, ta1 }); tb0.Order = BondOrder.Single; target.Bonds.Add(tb0); - IBond tb1 = new Bond(); + var tb1 = new Bond(); tb1.SetAtoms(new IAtom[] { ta1, ta2 }); tb1.Order = BondOrder.Single; target.Bonds.Add(tb1); - IBond tb2 = new Bond(); + var tb2 = new Bond(); tb2.SetAtoms(new IAtom[] { ta2, ta3 }); tb2.Order = BondOrder.Single; target.Bonds.Add(tb2); //Isomorphism check - bool res = uiTester.IsSubgraph(target, q); + var res = uiTester.IsSubgraph(target, q); Assert.IsFalse(res, "C**C should not match SCCS"); } } diff --git a/NCDKTests/Isomorphisms/VFStateTest.cs b/NCDKTests/Isomorphisms/VFStateTest.cs index 3b372032..a3be1ecd 100644 --- a/NCDKTests/Isomorphisms/VFStateTest.cs +++ b/NCDKTests/Isomorphisms/VFStateTest.cs @@ -96,8 +96,8 @@ VFState CreateBenzeneToNaphthalene(AtomMatcher atomMatcher, BondMatcher bondMatc { IAtomContainer container1 = TestMoleculeFactory.MakeBenzene(); IAtomContainer container2 = TestMoleculeFactory.MakeNaphthalene(); - GraphUtil.EdgeToBondMap bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(container1); - GraphUtil.EdgeToBondMap bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(container2); + EdgeToBondMap bonds1 = EdgeToBondMap.WithSpaceFor(container1); + EdgeToBondMap bonds2 = EdgeToBondMap.WithSpaceFor(container2); int[][] g1 = GraphUtil.ToAdjList(container1, bonds1); int[][] g2 = GraphUtil.ToAdjList(container2, bonds2); return new VFState(container1, container2, g1, g2, bonds1, bonds2, atomMatcher, bondMatcher); diff --git a/NCDKTests/Isomorphisms/VFSubStateTest.cs b/NCDKTests/Isomorphisms/VFSubStateTest.cs index c7338032..7561b939 100644 --- a/NCDKTests/Isomorphisms/VFSubStateTest.cs +++ b/NCDKTests/Isomorphisms/VFSubStateTest.cs @@ -110,8 +110,8 @@ VFSubState CreateBenzeneToNaphthalene(AtomMatcher atomMatcher, BondMatcher bondM { IAtomContainer container1 = TestMoleculeFactory.MakeBenzene(); IAtomContainer container2 = TestMoleculeFactory.MakeNaphthalene(); - GraphUtil.EdgeToBondMap bonds1 = GraphUtil.EdgeToBondMap.WithSpaceFor(container1); - GraphUtil.EdgeToBondMap bonds2 = GraphUtil.EdgeToBondMap.WithSpaceFor(container2); + EdgeToBondMap bonds1 = EdgeToBondMap.WithSpaceFor(container1); + EdgeToBondMap bonds2 = EdgeToBondMap.WithSpaceFor(container2); int[][] g1 = GraphUtil.ToAdjList(container1, bonds1); int[][] g2 = GraphUtil.ToAdjList(container2, bonds2); return new VFSubState(container1, container2, g1, g2, bonds1, bonds2, atomMatcher, bondMatcher); diff --git a/NCDKTests/Isomorphisms/VentoFoggiaTest.cs b/NCDKTests/Isomorphisms/VentoFoggiaTest.cs index 638bebfd..d8366c6c 100644 --- a/NCDKTests/Isomorphisms/VentoFoggiaTest.cs +++ b/NCDKTests/Isomorphisms/VentoFoggiaTest.cs @@ -26,6 +26,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Templates; using System.Linq; +using System; namespace NCDK.Isomorphisms { @@ -51,7 +52,7 @@ public void BenzeneIdentical() public void BenzeneNonIdentical() { int[] match = VentoFoggia.FindIdentical(TestMoleculeFactory.MakeBenzene()).Match(TestMoleculeFactory.MakeNaphthalene()); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], match)); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), match)); int count = VentoFoggia.FindIdentical(TestMoleculeFactory.MakeBenzene()).MatchAll(TestMoleculeFactory.MakeNaphthalene()).ToList().Count; Assert.AreEqual(0, count); } @@ -72,7 +73,7 @@ public void NapthaleneSubsearch() { int[] match = VentoFoggia.FindSubstructure(TestMoleculeFactory.MakeNaphthalene()).Match( TestMoleculeFactory.MakeBenzene()); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], match)); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), match)); int count = VentoFoggia.FindSubstructure(TestMoleculeFactory.MakeNaphthalene()).MatchAll( TestMoleculeFactory.MakeBenzene()).ToList().Count; diff --git a/NCDKTests/Layout/AtomPlacerTest.cs b/NCDKTests/Layout/AtomPlacerTest.cs index 7c325f7a..bb9e2eb8 100644 --- a/NCDKTests/Layout/AtomPlacerTest.cs +++ b/NCDKTests/Layout/AtomPlacerTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System; using System.Collections.Generic; using NCDK.Numerics; @@ -42,7 +42,7 @@ public void EmptyAtomsListTest() bool npeThrown = false; try { - placer.PopulatePolygonCorners(atoms, Vector2.Zero, 0, 10, 10); + AtomPlacer.PopulatePolygonCorners(atoms, Vector2.Zero, 0, 10, 10); } catch (NullReferenceException) { @@ -54,12 +54,14 @@ public void EmptyAtomsListTest() [TestMethod()] public void TriangleTest() { - List atoms = new List(); - atoms.Add(new Atom("C")); - atoms.Add(new Atom("C")); - atoms.Add(new Atom("C")); + List atoms = new List + { + new Atom("C"), + new Atom("C"), + new Atom("C") + }; AtomPlacer placer = new AtomPlacer(); - placer.PopulatePolygonCorners(atoms, Vector2.Zero, 0, 10, 10); + AtomPlacer.PopulatePolygonCorners(atoms, Vector2.Zero, 0, 10, 10); foreach (var atom in atoms) { Assert.IsNotNull(atom.Point2D); @@ -82,8 +84,7 @@ public void Cumulated_x2() m.Atoms[0].Point2D = Vector2.Zero; m.Atoms[0].IsPlaced = true; - AtomPlacer atomPlacer = new AtomPlacer(); - atomPlacer.Molecule = m; + AtomPlacer atomPlacer = new AtomPlacer { Molecule = m }; atomPlacer.PlaceLinearChain(m, new Vector2(0, 1.5), 1.5); Vector2 p1 = m.Atoms[1].Point2D.Value; @@ -120,8 +121,7 @@ public void Cumulated_x3() m.Atoms[0].Point2D = Vector2.Zero; m.Atoms[0].IsPlaced = true; - AtomPlacer atomPlacer = new AtomPlacer(); - atomPlacer.Molecule = m; + AtomPlacer atomPlacer = new AtomPlacer { Molecule = m }; atomPlacer.PlaceLinearChain(m, new Vector2(0, 1.5), 1.5); Vector2 p1 = m.Atoms[1].Point2D.Value; @@ -147,8 +147,7 @@ public void Cumulated_x3() static IAtom Atom(string symbol, int hCount) { - IAtom a = new Atom(symbol); - a.ImplicitHydrogenCount = hCount; + IAtom a = new Atom(symbol) { ImplicitHydrogenCount = hCount }; return a; } } diff --git a/NCDKTests/Layout/CorrectGeometricConfigurationTest.cs b/NCDKTests/Layout/CorrectGeometricConfigurationTest.cs index d393500a..514cbd85 100644 --- a/NCDKTests/Layout/CorrectGeometricConfigurationTest.cs +++ b/NCDKTests/Layout/CorrectGeometricConfigurationTest.cs @@ -24,7 +24,7 @@ using NCDK.Common.Mathematics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Stereo; using NCDK.Numerics; diff --git a/NCDKTests/Layout/HydrogenPlacerTest.cs b/NCDKTests/Layout/HydrogenPlacerTest.cs index 0332e702..ace8770e 100644 --- a/NCDKTests/Layout/HydrogenPlacerTest.cs +++ b/NCDKTests/Layout/HydrogenPlacerTest.cs @@ -18,7 +18,7 @@ */ using NCDK.Common.Mathematics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using NCDK.IO; using System; diff --git a/NCDKTests/Layout/IdentityTemplateLibraryTest.cs b/NCDKTests/Layout/IdentityTemplateLibraryTest.cs index 842273d8..e57fa67f 100644 --- a/NCDKTests/Layout/IdentityTemplateLibraryTest.cs +++ b/NCDKTests/Layout/IdentityTemplateLibraryTest.cs @@ -23,7 +23,7 @@ */ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Collections.Generic; using System.IO; using NCDK.Numerics; diff --git a/NCDKTests/Layout/NonPlanarBondsTest.cs b/NCDKTests/Layout/NonPlanarBondsTest.cs index 19f25273..39373bb3 100644 --- a/NCDKTests/Layout/NonPlanarBondsTest.cs +++ b/NCDKTests/Layout/NonPlanarBondsTest.cs @@ -23,7 +23,7 @@ */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; using NCDK.Stereo; using NCDK.Smiles; diff --git a/NCDKTests/Layout/StructureDiagramGeneratorTest.cs b/NCDKTests/Layout/StructureDiagramGeneratorTest.cs index 3e3f9287..880f894a 100644 --- a/NCDKTests/Layout/StructureDiagramGeneratorTest.cs +++ b/NCDKTests/Layout/StructureDiagramGeneratorTest.cs @@ -21,7 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Mathematics; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using NCDK.IO; using NCDK.Numerics; @@ -76,7 +76,7 @@ public void VisualBugPMR() [Timeout(5000)] public void TestBugLecture2007() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); //IAtomContainer mol = sp.ParseSmiles("Oc1nc(Nc2c(nn(c12)C)CCC)c3cc(ccc3(OCC))S(=O)(=O)N4CCN(C)CC4"); IAtomContainer mol = sp.ParseSmiles("O=C(N1CCN(CC1)CCCN(C)C)C3(C=2C=CC(=CC=2)C)(CCCCC3)"); @@ -181,7 +181,7 @@ public void TestDiamantane() [Timeout(5000)] public void TestBug1670871() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(=O)OC1C=CC(SC23CC4CC(CC(C4)C2)C3)N(C1SC56CC7CC(CC(C7)C5)C6)C(C)=O"); IAtomContainer ac = Layout(mol); //MoleculeViewer2D.Display(new AtomContainer(ac), false); @@ -208,14 +208,14 @@ public void TestBicycloRings() public IAtomContainer MakeJhao3() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=C1C2=CC13(CC23)"); return mol; } public IAtomContainer MakeJhao4() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCC3C1CC23(CC12)"); return mol; } @@ -224,7 +224,7 @@ public IAtomContainer MakeJhao4() [Timeout(5000)] public void TestBenzene() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1ccccc1"); IAtomContainer ac = Layout(mol); Assert.IsTrue(GeometryUtil.Has2DCoordinates(ac)); @@ -264,7 +264,7 @@ public void TestBug1572062() ISimpleChemObjectReader molReader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); // read molecule - IAtomContainer molecule = molReader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer molecule = molReader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); // rebuild 2D coordinates for (int i = 0; i < 10; i++) @@ -276,7 +276,7 @@ public void TestBug1572062() // @cdk.bug 884993 public void TestBug884993() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[N+](=O)([O-])C1=C(O)C(=CC(=C1)[N+](=O)[O-])[N+](=O)[O-].C23N(CCCC2)CCCC3"); IAtomContainer ac = Layout(mol); Assert.IsTrue(GeometryUtil.Has2DCoordinates(ac)); @@ -293,7 +293,7 @@ public void TestBug1677912SDGHangs() { // Parse the SMILES string smiles = "[NH](-[CH]1-[CH]2-[CH2]-[CH]3-[CH2]-[CH]-1-[CH2]-[CH](-[CH2]-2)-[CH2]-3)-C(=O)-C(=O)-[CH2]-c1:n:c(:c(:[cH]:c:1-C(=O)-O-[CH3])-C(=O)-O-[CH3])-[CH2]-C(=O)-C(=O)-[NH]-[CH]1-[CH]2-[CH2]-[CH]3-[CH2]-[CH]-1-[CH2]-[CH](-[CH2]-2)-[CH2]-3"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); // Generate 2D coordinates @@ -500,7 +500,7 @@ public void TestBug1714794() IAtomContainer MakeTetraMethylCycloButane() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 mol.Atoms.Add(new Atom("C")); // 3 @@ -523,7 +523,7 @@ IAtomContainer MakeTetraMethylCycloButane() IAtomContainer MakeJhao1() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 mol.Atoms.Add(new Atom("C")); // 3 @@ -551,7 +551,7 @@ IAtomContainer MakeJhao1() IAtomContainer MakeJhao2() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); // 1 mol.Atoms.Add(new Atom("C")); // 2 mol.Atoms.Add(new Atom("C")); // 3 @@ -587,7 +587,7 @@ public IAtomContainer MakeBug1750968() ISimpleChemObjectReader molReader = new MDLReader(ins, ChemObjectReaderMode.Strict); // read molecule - return molReader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + return molReader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); } /// @@ -654,7 +654,7 @@ public void TestBug1784850InfiniteLoop() ISimpleChemObjectReader molReader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); // read molecule - IAtomContainer molecule = molReader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer molecule = molReader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); // rebuild 2D coordinates Layout(molecule); @@ -1072,7 +1072,7 @@ public void PlaceCrossingSgroupBrackets() sgroup.Atoms.Add(mol.Atoms[2]); sgroup.Bonds.Add(mol.Bonds[0]); sgroup.Bonds.Add(mol.Bonds[2]); - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup }); + mol.SetCtabSgroups(new[] { sgroup }); Layout(mol); var brackets = (IList)sgroup.GetValue(SgroupKey.CtabBracket); @@ -1102,7 +1102,7 @@ public void PlaceNonCrossingSgroupBrackets() sgroup.PutValue(SgroupKey.CtabConnectivity, "HT"); foreach (var atom in mol.Atoms) sgroup.Atoms.Add(atom); - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup }); + mol.SetCtabSgroups(new[] { sgroup }); Layout(mol); var brackets = (IList)sgroup.GetValue(SgroupKey.CtabBracket); @@ -1147,7 +1147,7 @@ public void PlaceOverlappingCrossingSgroupBrackets() sgroup2.Atoms.Add(mol.Atoms[3]); sgroup2.Bonds.Add(mol.Bonds[1]); sgroup2.Bonds.Add(mol.Bonds[3]); - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup1, sgroup2 }); + mol.SetCtabSgroups(new[] { sgroup1, sgroup2 }); Layout(mol); var brackets1 = (IList)sgroup1.GetValue(SgroupKey.CtabBracket); @@ -1197,7 +1197,7 @@ public void PositionalVariation() sgroup2.Atoms.Add(mol.Atoms[4]); sgroup2.Atoms.Add(mol.Atoms[5]); - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup1, sgroup2 }); + mol.SetCtabSgroups(new[] { sgroup1, sgroup2 }); Layout(mol); int numCrossing = 0; @@ -1229,7 +1229,7 @@ public void DisconnectedMultigroupPlacement() break; } sgroup.PutValue(SgroupKey.CtabParentAtomList, patoms); - mol.SetProperty(CDKPropertyName.CtabSgroups, new[] { sgroup }); + mol.SetCtabSgroups(new[] { sgroup }); Layout(mol); for (int i = 0; i < 6; i++) { diff --git a/NCDKTests/Layout/TemplateHandlerTest.cs b/NCDKTests/Layout/TemplateHandlerTest.cs index bb3228e5..3185d582 100644 --- a/NCDKTests/Layout/TemplateHandlerTest.cs +++ b/NCDKTests/Layout/TemplateHandlerTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.IO; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; using System.Diagnostics; @@ -39,13 +40,13 @@ public class TemplateHandlerTest : CDKTestCase static TemplateHandlerTest() { sdg = new StructureDiagramGenerator(); - sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + sp = new SmilesParser(ChemObjectBuilder.Instance); } [TestMethod()] public void TestInit() { - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); Assert.AreEqual(5, th.TemplateCount); } @@ -53,7 +54,7 @@ public void TestInit() [TestMethod()] public void TestDetection() { - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); string smiles = "CC12C3(C6CC6)C4(C)C1C5(C(CC)C)C(C(CC)C)2C(C)3C45CC(C)C"; IAtomContainer mol = sp.ParseSmiles(smiles); Assert.IsTrue(th.MapTemplates(mol)); @@ -66,7 +67,7 @@ public void TestDetection() public void TestOtherElements() { bool itIsInThere = false; - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); IAtomContainer mol = TestMoleculeFactory.MakeSteran(); itIsInThere = th.MapTemplates(mol); Assert.IsTrue(itIsInThere); @@ -82,7 +83,7 @@ public void TestOtherElements() public void TestOtherBondOrder() { bool itIsInThere = false; - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); IAtomContainer mol = TestMoleculeFactory.MakeSteran(); itIsInThere = th.MapTemplates(mol); Assert.IsTrue(itIsInThere); @@ -96,7 +97,7 @@ public void TestAddMolecule() { Debug.WriteLine("***TestAddMolecule***"); bool itIsInThere = false; - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); sdg.Molecule = mol; sdg.GenerateCoordinates(); @@ -105,12 +106,12 @@ public void TestAddMolecule() string smiles = "C1=C(C)C2CC(C1)C2(C)(C)"; IAtomContainer smilesMol = sp.ParseSmiles(smiles); itIsInThere = th.MapTemplates(smilesMol); - Debug.WriteLine("Alpha-Pinene found by templateMapper: " + itIsInThere); + Debug.WriteLine($"Alpha-Pinene found by templateMapper: {itIsInThere}"); Assert.IsFalse(itIsInThere); th.AddMolecule(mol); Debug.WriteLine("now adding template for alpha-Pinen and trying again."); itIsInThere = th.MapTemplates(smilesMol); - Debug.WriteLine("Alpha-Pinene found by templateMapper: " + itIsInThere); + Debug.WriteLine($"Alpha-Pinene found by templateMapper: {itIsInThere}"); Assert.IsTrue(itIsInThere); } @@ -119,7 +120,7 @@ public void TestRemoveMolecule() { Debug.WriteLine("***TestRemoveMolecule***"); bool itIsInThere = false; - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); IAtomContainer mol = TestMoleculeFactory.MakeAlphaPinene(); sdg.Molecule = mol; sdg.GenerateCoordinates(); @@ -128,17 +129,17 @@ public void TestRemoveMolecule() string smiles = "C1=C(C)C2CC(C1)C2(C)(C)"; IAtomContainer smilesMol = sp.ParseSmiles(smiles); itIsInThere = th.MapTemplates(smilesMol); - Debug.WriteLine("Alpha-Pinene found by templateMapper: " + itIsInThere); + Debug.WriteLine($"Alpha-Pinene found by templateMapper: {itIsInThere}"); Assert.IsFalse(itIsInThere); th.AddMolecule(mol); Debug.WriteLine("now adding template for alpha-Pinen and trying again."); itIsInThere = th.MapTemplates(smilesMol); - Debug.WriteLine("Alpha-Pinene found by templateMapper: " + itIsInThere); + Debug.WriteLine($"Alpha-Pinene found by templateMapper: {itIsInThere}"); Assert.IsTrue(itIsInThere); Debug.WriteLine("now removing template for alpha-Pinen again and trying again."); th.RemoveMolecule(mol); itIsInThere = th.MapTemplates(smilesMol); - Debug.WriteLine("Alpha-Pinene found by templateMapper: " + itIsInThere); + Debug.WriteLine($"Alpha-Pinene found by templateMapper: {itIsInThere}"); Assert.IsFalse(itIsInThere); } @@ -155,10 +156,10 @@ public void GetMappedSubstructures_IAtomContainer() ISimpleChemObjectReader molReader = new MDLReader(ins, ChemObjectReaderMode.Strict); // Read molecule - IAtomContainer molecule = (IAtomContainer)molReader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer molecule = (IAtomContainer)molReader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); // Map templates - TemplateHandler th = new TemplateHandler(Default.ChemObjectBuilder.Instance); + TemplateHandler th = new TemplateHandler(ChemObjectBuilder.Instance); var mappedStructures = th.GetMappedSubstructures(molecule); // Do the Assert.assertion diff --git a/NCDKTests/LibIO/CML/ConvertorTest.cs b/NCDKTests/LibIO/CML/ConvertorTest.cs index 15216aa2..f2f081c2 100644 --- a/NCDKTests/LibIO/CML/ConvertorTest.cs +++ b/NCDKTests/LibIO/CML/ConvertorTest.cs @@ -22,6 +22,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.IO; using System.Xml.Linq; @@ -34,7 +35,7 @@ public class ConvertorTest : CDKTestCase [TestMethod()] public void TestCdkBondToCMLBond_Wedge() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IBond bond = builder.NewBond(); bond.Order = BondOrder.Single; bond.Stereo = BondStereo.Up; @@ -55,7 +56,7 @@ public void TestCdkBondToCMLBond_Wedge() [TestMethod()] public void TestCdkBondToCMLBond_Hatch() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IBond bond = builder.NewBond(); bond.Order = BondOrder.Single; bond.Stereo = BondStereo.Down; diff --git a/NCDKTests/LibIO/CML/PDBAtomCustomizerTest.cs b/NCDKTests/LibIO/CML/PDBAtomCustomizerTest.cs index 1fa1f647..d6b112ca 100644 --- a/NCDKTests/LibIO/CML/PDBAtomCustomizerTest.cs +++ b/NCDKTests/LibIO/CML/PDBAtomCustomizerTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System.Diagnostics; using System.IO; diff --git a/NCDKTests/LibIO/MD/MDMoleculeTest.cs b/NCDKTests/LibIO/MD/MDMoleculeTest.cs index 47a997a9..28740ac5 100644 --- a/NCDKTests/LibIO/MD/MDMoleculeTest.cs +++ b/NCDKTests/LibIO/MD/MDMoleculeTest.cs @@ -22,7 +22,7 @@ * */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.IO.CML; using NCDK.LibIO.CML; diff --git a/NCDKTests/Maths/PrimesTest.cs b/NCDKTests/Maths/PrimesTest.cs index acf6d5d3..046003da 100644 --- a/NCDKTests/Maths/PrimesTest.cs +++ b/NCDKTests/Maths/PrimesTest.cs @@ -39,14 +39,14 @@ public void TestGetPrimeAt_int() Primes.GetPrimeAt(2229); Assert.Fail("Should fail her, because it contains only X primes."); } - catch (IndexOutOfRangeException) + catch (ArgumentOutOfRangeException) { // OK, that should happen } } [TestMethod()] - [ExpectedException(typeof(IndexOutOfRangeException))] + [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestArrayIndexOutOfBounds() { Primes.GetPrimeAt(-1); diff --git a/NCDKTests/MockMolecule.cs b/NCDKTests/MockMolecule.cs index 364c6200..1a819378 100644 --- a/NCDKTests/MockMolecule.cs +++ b/NCDKTests/MockMolecule.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; namespace NCDK diff --git a/NCDKTests/Modelings/Builder3D/AtomPlacer3DTest.cs b/NCDKTests/Modelings/Builder3D/AtomPlacer3DTest.cs index e195d150..b3ae570e 100644 --- a/NCDKTests/Modelings/Builder3D/AtomPlacer3DTest.cs +++ b/NCDKTests/Modelings/Builder3D/AtomPlacer3DTest.cs @@ -20,7 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Tools.Manipulator; using System.Diagnostics; @@ -81,7 +81,7 @@ private IAtomContainer MakeAlphaPinene() mol.AddBond(mol.Atoms[7], mol.Atoms[9], BondOrder.Single); try { - Isotopes.Instance.ConfigureAtoms(mol); + BODRIsotopeFactory.Instance.ConfigureAtoms(mol); } catch (IOException ex) { diff --git a/NCDKTests/Modelings/Builder3D/AtomTetrahedralLigandPlacer3DTest.cs b/NCDKTests/Modelings/Builder3D/AtomTetrahedralLigandPlacer3DTest.cs index 2f6169c8..4f441fb8 100644 --- a/NCDKTests/Modelings/Builder3D/AtomTetrahedralLigandPlacer3DTest.cs +++ b/NCDKTests/Modelings/Builder3D/AtomTetrahedralLigandPlacer3DTest.cs @@ -18,7 +18,7 @@ */ using NCDK.Common.Mathematics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; namespace NCDK.Modelings.Builder3D @@ -34,8 +34,10 @@ public class AtomTetrahedralLigandPlacer3DTest : CDKTestCase [TestMethod()] public void TestAdd3DCoordinatesForSinglyBondedLigands_IAtomContainer() { - IAtom atom1 = new Atom("C"); - atom1.Point3D = new Vector3(1, 1, 1); + IAtom atom1 = new Atom("C") + { + Point3D = new Vector3(1, 1, 1) + }; IAtom atom2 = new Atom("H"); IAtom atom3 = new Atom("H"); IAtom atom4 = new Atom("H"); @@ -66,12 +68,16 @@ public void TestAdd3DCoordinatesForSinglyBondedLigands_IAtomContainer() [TestMethod()] public void RescaleBondLength_IAtom_IAtom_Point3d() { - IAtom atom1 = new Atom("C"); - atom1.Point3D = new Vector3(1, 1, 1); - atom1.CovalentRadius = 0.2; - IAtom atom2 = new Atom("C"); - atom2.Point3D = new Vector3(2, 2, 2); - atom2.CovalentRadius = 0.2; + IAtom atom1 = new Atom("C") + { + Point3D = new Vector3(1, 1, 1), + CovalentRadius = 0.2 + }; + IAtom atom2 = new Atom("C") + { + Point3D = new Vector3(2, 2, 2), + CovalentRadius = 0.2 + }; Vector3 newpoint = new AtomTetrahedralLigandPlacer3D().RescaleBondLength(atom1, atom2, atom2.Point3D.Value); Assert.AreEqual(0.4, Vector3.Distance(newpoint, atom1.Point3D.Value), 0.001); } @@ -79,8 +85,10 @@ public void RescaleBondLength_IAtom_IAtom_Point3d() [TestMethod()] public void TestGet3DCoordinatesForLigands_IAtom_IAtomContainer_IAtomContainer_IAtom_int_Double_double() { - IAtom atom1 = new Atom("C"); - atom1.Point3D = new Vector3(1, 1, 1); + IAtom atom1 = new Atom("C") + { + Point3D = new Vector3(1, 1, 1) + }; IAtom atom2 = new Atom("H"); IAtom atom3 = new Atom("H"); IAtom atom4 = new Atom("H"); @@ -104,13 +112,14 @@ public void TestGet3DCoordinatesForLigands_IAtom_IAtomContainer_IAtomContainer_I ac.Bonds.Add(bond2); ac.Bonds.Add(bond3); ac.Bonds.Add(bond4); - IAtomContainer noCoords = new AtomTetrahedralLigandPlacer3D().GetUnsetAtomsInAtomContainer(atom1, ac); - IAtomContainer withCoords = new AtomTetrahedralLigandPlacer3D().GetPlacedAtomsInAtomContainer(atom1, ac); - Vector3[] newPoints = new AtomTetrahedralLigandPlacer3D().Get3DCoordinatesForLigands(atom1, noCoords, - withCoords, null, 4, AtomTetrahedralLigandPlacer3D.DEFAULT_BOND_LENGTH_H, -1); + IAtomContainer noCoords = AtomTetrahedralLigandPlacer3D.GetUnsetAtomsInAtomContainer(atom1, ac); + IAtomContainer withCoords = AtomTetrahedralLigandPlacer3D.GetPlacedAtomsInAtomContainer(atom1, ac); + var placer = new AtomTetrahedralLigandPlacer3D(); + Vector3[] newPoints = placer.Get3DCoordinatesForLigands(atom1, noCoords, withCoords, null, 4, placer.DefaultBondLengthH, -1); for (int j = 0; j < noCoords.Atoms.Count; j++) { - if (newPoints[j] == null) Assert.Fail("No coordinates generated for atom " + j); + if (newPoints[j] == null) + Assert.Fail("No coordinates generated for atom " + j); IAtom ligand = noCoords.Atoms[j]; ligand.Point3D = newPoints[j]; } diff --git a/NCDKTests/Modelings/Builder3D/ForceFieldConfiguratorTest.cs b/NCDKTests/Modelings/Builder3D/ForceFieldConfiguratorTest.cs index 1a757140..0c4879b1 100644 --- a/NCDKTests/Modelings/Builder3D/ForceFieldConfiguratorTest.cs +++ b/NCDKTests/Modelings/Builder3D/ForceFieldConfiguratorTest.cs @@ -22,6 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; @@ -53,7 +54,7 @@ public void TestCheckForceFieldType_String() public void TestSetForceFieldConfigurator_String() { string forceFieldName = "mmff94"; - forceFieldConfigurator.SetForceFieldConfigurator(forceFieldName, Default.ChemObjectBuilder.Instance); + forceFieldConfigurator.SetForceFieldConfigurator(forceFieldName, ChemObjectBuilder.Instance); var mmff94AtomTypes = forceFieldConfigurator.AtomTypes; Assert.IsNotNull(mmff94AtomTypes); IAtomType atomtype0 = mmff94AtomTypes[0]; @@ -62,7 +63,7 @@ public void TestSetForceFieldConfigurator_String() Assert.AreEqual("Csp2", atomtype1.AtomTypeName); forceFieldName = "mm2"; - forceFieldConfigurator.SetForceFieldConfigurator(forceFieldName, Default.ChemObjectBuilder.Instance); + forceFieldConfigurator.SetForceFieldConfigurator(forceFieldName, ChemObjectBuilder.Instance); var mm2AtomTypes = forceFieldConfigurator.AtomTypes; Assert.IsNotNull(mm2AtomTypes); IAtomType atomtype2 = mm2AtomTypes[2]; @@ -74,7 +75,7 @@ public void TestSetForceFieldConfigurator_String() [TestMethod()] public void TestSetMM2Parameters() { - forceFieldConfigurator.SetMM2Parameters(Default.ChemObjectBuilder.Instance); + forceFieldConfigurator.SetMM2Parameters(ChemObjectBuilder.Instance); Assert.IsNotNull(forceFieldConfigurator.GetParameterSet()); var atomtypeList = forceFieldConfigurator.AtomTypes; IAtomType atomtype1 = atomtypeList[1]; @@ -86,7 +87,7 @@ public void TestSetMM2Parameters() [TestMethod()] public void TestSetMMFF94Parameters() { - forceFieldConfigurator.SetMMFF94Parameters(Default.ChemObjectBuilder.Instance); + forceFieldConfigurator.SetMMFF94Parameters(ChemObjectBuilder.Instance); Assert.IsNotNull(forceFieldConfigurator.GetParameterSet()); var atomtypeList = forceFieldConfigurator.AtomTypes; IAtomType atomtype4 = atomtypeList[4]; @@ -100,10 +101,10 @@ public void TestSetMMFF94Parameters() public void TestRemoveAromaticityFlagsFromHoseCode_String() { string hosecode1 = "***HO*SE*CODE***"; - string cleanHoseCode = forceFieldConfigurator.RemoveAromaticityFlagsFromHoseCode(hosecode1); + string cleanHoseCode = ForceFieldConfigurator.RemoveAromaticityFlagsFromHoseCode(hosecode1); Assert.AreEqual("HOSECODE", cleanHoseCode); string hosecode2 = "HOSECODE"; - cleanHoseCode = forceFieldConfigurator.RemoveAromaticityFlagsFromHoseCode(hosecode2); + cleanHoseCode = ForceFieldConfigurator.RemoveAromaticityFlagsFromHoseCode(hosecode2); Assert.AreEqual("HOSECODE", cleanHoseCode); } @@ -112,7 +113,7 @@ public void TestRemoveAromaticityFlagsFromHoseCode_String() public void TestConfigureMMFF94BasedAtom_IAtom_String_boolean_hydroxyurea() { string husmi = "NC(=O)NO"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer hu = parser.ParseSmiles(husmi); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); @@ -129,7 +130,7 @@ public void TestConfigureMMFF94BasedAtom_IAtom_String_boolean_hydroxyurea() public void TestConfigureMMFF94BasedAtom_IAtom_String_boolean_propanamide() { string pasmi = "NC(=O)CC"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer pa = parser.ParseSmiles(pasmi); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); @@ -144,7 +145,7 @@ public void TestConfigureMMFF94BasedAtom_IAtom_String_boolean_propanamide() public void TestConfigureMMFF94BasedAtom_IAtom_String_boolean_urea() { string usmi = "NC(N)=O"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer urea = parser.ParseSmiles(usmi); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); @@ -165,7 +166,7 @@ public void TestAssignAtomTyps_test4_hydroxyurea() IAtomContainer molecule = null; string[] ffAtomTypes = null; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser smilesParser = new SmilesParser(builder); molecule = smilesParser.ParseSmiles(smiles); ffAtomTypes = new string[molecule.Atoms.Count]; @@ -192,7 +193,7 @@ public void TestAssignAtomTyps_test4_hydroxyurea() public void TestAssignAtomTyps_bug() { string smiles = "CC(C)C1CCC(CC1)C(=O)NC(Cc1ccccc1)C(=O)O"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer bugmol = parser.ParseSmiles(smiles); forceFieldConfigurator.SetForceFieldConfigurator("mmff94", builder); @@ -206,7 +207,7 @@ public void TestAssignAtomTyps_bug() public void TestAssignAtomTyps_bug_no2() { string smiles = "CC[N+](=O)[O-]"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer bugmol = parser.ParseSmiles(smiles); forceFieldConfigurator.SetForceFieldConfigurator("mmff94", builder); @@ -220,7 +221,7 @@ public void TestAssignAtomTyps_bug_no2() public void TestAssignAtomTyps_bug_so2() { string smiles = "CS(=O)(=O)NC(=O)NN1CC2CCCC2C1"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer bugmol = parser.ParseSmiles(smiles); forceFieldConfigurator.SetForceFieldConfigurator("mmff94", builder); @@ -235,7 +236,7 @@ public void TestAssignAtomTyps_bug_so2() public void TestAssignAtomTyps_bug_nitrogenatomType() { string smiles = "CNC(=O)N(C)N=O"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer bugmol = parser.ParseSmiles(smiles); forceFieldConfigurator.SetForceFieldConfigurator("mmff94", builder); @@ -255,7 +256,7 @@ public void TestAssignAtomTyps_bug_nitrogenatomType() public void TestAssignAtomTyps_bug_amideRingAtomType() { string smiles = "O=C1N(C(=O)C(C(=O)N1)(CC)CC)C"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser parser = new SmilesParser(builder); IAtomContainer bugmol = parser.ParseSmiles(smiles); forceFieldConfigurator.SetForceFieldConfigurator("mmff94", builder); diff --git a/NCDKTests/Modelings/Builder3D/FurtherAtomPlacer3DTest.cs b/NCDKTests/Modelings/Builder3D/FurtherAtomPlacer3DTest.cs index 6070d375..a8cd9326 100644 --- a/NCDKTests/Modelings/Builder3D/FurtherAtomPlacer3DTest.cs +++ b/NCDKTests/Modelings/Builder3D/FurtherAtomPlacer3DTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Smiles; using NCDK.Templates; +using NCDK.Silent; namespace NCDK.Modelings.Builder3D { @@ -307,14 +308,13 @@ public void TestGetNextUnplacedHeavyAtomWithAliphaticPlacedNeighbour_IAtomContai [TestMethod()] public void TestGetAngleValue_String_String_String() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "CCCCCC"; IAtomContainer molecule = parser.ParseSmiles(smiles); Assert.IsNotNull(molecule); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); - ffc.SetForceFieldConfigurator("mmff94", Default.ChemObjectBuilder.Instance); - AtomPlacer3D atomPlacer3d = new AtomPlacer3D(); - atomPlacer3d.Initilize(ffc.GetParameterSet()); + ffc.SetForceFieldConfigurator("mmff94", ChemObjectBuilder.Instance); + AtomPlacer3D atomPlacer3d = new AtomPlacer3D(ffc.GetParameterSet()); ffc.AssignAtomTyps(molecule); string id1 = molecule.Atoms[1].AtomTypeName; @@ -330,14 +330,13 @@ public void TestGetAngleValue_String_String_String() [TestMethod()] public void TestGetBondLengthValue_String_String() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "CCCCCC"; IAtomContainer molecule = parser.ParseSmiles(smiles); Assert.IsNotNull(molecule); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); - ffc.SetForceFieldConfigurator("mmff94", Default.ChemObjectBuilder.Instance); - AtomPlacer3D atomPlacer3d = new AtomPlacer3D(); - atomPlacer3d.Initilize(ffc.GetParameterSet()); + ffc.SetForceFieldConfigurator("mmff94", ChemObjectBuilder.Instance); + AtomPlacer3D atomPlacer3d = new AtomPlacer3D(ffc.GetParameterSet()); ffc.AssignAtomTyps(molecule); string id1 = molecule.Atoms[1].AtomTypeName; @@ -355,14 +354,13 @@ public void TestGetBondLengthValue_String_String() [TestMethod()] public void TestGetBondLengthValue_bug_CNBond() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "CCCN"; IAtomContainer molecule = parser.ParseSmiles(smiles); Assert.IsNotNull(molecule); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); - ffc.SetForceFieldConfigurator("mmff94", Default.ChemObjectBuilder.Instance); - AtomPlacer3D atomPlacer3d = new AtomPlacer3D(); - atomPlacer3d.Initilize(ffc.GetParameterSet()); + ffc.SetForceFieldConfigurator("mmff94", ChemObjectBuilder.Instance); + AtomPlacer3D atomPlacer3d = new AtomPlacer3D(ffc.GetParameterSet()); ffc.AssignAtomTyps(molecule); string id1 = molecule.Atoms[2].AtomTypeName; @@ -372,18 +370,6 @@ public void TestGetBondLengthValue_bug_CNBond() } - [TestMethod()] - public void TestMarkPlaced_IAtomContainer() - { - AtomPlacer3D atmplacer = new AtomPlacer3D(); - IAtomContainer molecule = TestMoleculeFactory.MakeAlkane(5); - IAtomContainer placedMolecule = atmplacer.MarkPlaced(molecule); - foreach (var atom in placedMolecule.Atoms) - { - Assert.IsTrue(atom.IsPlaced); - } - } - /// /// This class only places 'chains' - i.e. no branching. Check an exception is thrown. /// @@ -393,15 +379,14 @@ public void TestMarkPlaced_IAtomContainer() public void InvalidChain() { string input = "CCCCCC(CCCC)CCCC"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer m = sp.ParseSmiles(input); ForceFieldConfigurator ffc = new ForceFieldConfigurator(); - ffc.SetForceFieldConfigurator("mmff92", Default.ChemObjectBuilder.Instance); + ffc.SetForceFieldConfigurator("mmff92", ChemObjectBuilder.Instance); ffc.AssignAtomTyps(m); - AtomPlacer3D ap3d = new AtomPlacer3D(); - ap3d.Initilize(ffc.GetParameterSet()); + AtomPlacer3D ap3d = new AtomPlacer3D(ffc.GetParameterSet()); ap3d.PlaceAliphaticHeavyChain(m, m); } } diff --git a/NCDKTests/Modelings/Builder3D/FurtherTemplateHandler3DTest.cs b/NCDKTests/Modelings/Builder3D/FurtherTemplateHandler3DTest.cs index a9709e68..9d12fe53 100644 --- a/NCDKTests/Modelings/Builder3D/FurtherTemplateHandler3DTest.cs +++ b/NCDKTests/Modelings/Builder3D/FurtherTemplateHandler3DTest.cs @@ -23,6 +23,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.RingSearches; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; using System; @@ -57,12 +58,13 @@ public void TestLoadTemplates() Assert.AreEqual(10751, tmphandler3d.TemplateCount); } + [TestCategory("SlowTest")] [TestMethod()] - public void TestMapTemplates_cyclicMol1() + public void TestMapTemplatesCyclicMol1() { TemplateHandler3D tmphandler3d = TemplateHandler3D.Instance; string cyclicMolSmi = "O(CC(O)CN1CCN(CC1)CC(=O)Nc1c(cccc1C)C)c1c(cccc1)OC"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser smiparser = new SmilesParser(builder); IAtomContainer molecule = smiparser.ParseSmiles(cyclicMolSmi); ForceFieldConfigurator forcefconf = new ForceFieldConfigurator(); @@ -78,12 +80,13 @@ public void TestMapTemplates_cyclicMol1() } } + [TestCategory("SlowTest")] [TestMethod()] - public void TestMapTemplates_cyclicMol2() + public void TestMapTemplatesCyclicMol2() { TemplateHandler3D tmphandler3d = TemplateHandler3D.Instance; string cyclicMolSmi = "CC(C)(C)NC(=O)C1CN(CCN1CC(CC(Cc1ccccc1)C(=O)NC1c2ccccc2CC1O)O)Cc1cccnc1"; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser smiparser = new SmilesParser(builder); IAtomContainer molecule = smiparser.ParseSmiles(cyclicMolSmi); ForceFieldConfigurator forcefconf = new ForceFieldConfigurator(); diff --git a/NCDKTests/Modelings/Builder3D/MMFF94BasedParameterSetReaderTest.cs b/NCDKTests/Modelings/Builder3D/MMFF94BasedParameterSetReaderTest.cs index 9600467c..4309790f 100644 --- a/NCDKTests/Modelings/Builder3D/MMFF94BasedParameterSetReaderTest.cs +++ b/NCDKTests/Modelings/Builder3D/MMFF94BasedParameterSetReaderTest.cs @@ -23,6 +23,8 @@ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; +using System.Globalization; +using NCDK.Silent; namespace NCDK.Modelings.Builder3D { @@ -39,21 +41,20 @@ public class MMFF94BasedParameterSetReaderTest public void TestReadParameterSets() { MMFF94BasedParameterSetReader mmff94bpsr = new MMFF94BasedParameterSetReader(); - mmff94bpsr.ReadParameterSets(Default.ChemObjectBuilder.Instance); - IDictionary parameterSet = new Dictionary(); - parameterSet = mmff94bpsr.GetParamterSet(); + mmff94bpsr.ReadParameterSets(ChemObjectBuilder.Instance); + var parameterSet = mmff94bpsr.GetParamterSet(); //test atom type - List atomtypes = mmff94bpsr.AtomTypes; + var atomtypes = mmff94bpsr.AtomTypes; IAtomType atomtype = atomtypes[0]; string sid = "C"; Assert.AreEqual(sid, atomtype.AtomTypeName); string rootType = "C"; Assert.AreEqual(rootType, atomtype.Symbol); string smaxbond = "4"; - Assert.AreEqual(int.Parse(smaxbond), (int)atomtype.FormalNeighbourCount); + Assert.AreEqual(int.Parse(smaxbond, NumberFormatInfo.InvariantInfo), (int)atomtype.FormalNeighbourCount); string satomNr = "6"; - Assert.AreEqual(int.Parse(satomNr), (int)atomtype.AtomicNumber); + Assert.AreEqual(int.Parse(satomNr, NumberFormatInfo.InvariantInfo), (int)atomtype.AtomicNumber); //atom //TODO testing @@ -68,12 +69,14 @@ public void TestReadParameterSets() string sk4 = "715.009"; string sbci = "0.0000"; string bondkey = "bond" + sid1 + ";" + sid2; - var bonddata = new List(); - bonddata.Add((double)(double.Parse(slen))); - bonddata.Add((double)(double.Parse(sk2))); - bonddata.Add((double)(double.Parse(sk3))); - bonddata.Add((double)(double.Parse(sk4))); - bonddata.Add((double)(double.Parse(sbci))); + var bonddata = new List + { + (double)(double.Parse(slen, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(sk2, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(sk3, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(sk4, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(sbci, NumberFormatInfo.InvariantInfo)) + }; //strbnd // scode = "0"; @@ -83,9 +86,11 @@ public void TestReadParameterSets() string value1 = "14.82507"; string value2 = "14.82507"; string strbndkey = "strbnd" + sid1 + ";" + sid2 + ";" + sid3; - var strbnddata = new List(); - strbnddata.Add((double)(double.Parse(value1))); - strbnddata.Add((double)(double.Parse(value2))); + var strbnddata = new List + { + (double)(double.Parse(value1, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value2, NumberFormatInfo.InvariantInfo)) + }; //angle // scode = "0"; @@ -97,11 +102,13 @@ public void TestReadParameterSets() string value3 = "-34.5494"; string value4 = "0"; string anglekey = "angle" + sid1 + ";" + sid2 + ";" + sid3; - var angledata = new List(); - angledata.Add((double)(double.Parse(value1))); - angledata.Add((double)(double.Parse(value2))); - angledata.Add((double)(double.Parse(value3))); - angledata.Add((double)(double.Parse(value4))); + var angledata = new List + { + (double)(double.Parse(value1, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value2, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value3, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value4, NumberFormatInfo.InvariantInfo)) + }; //torsion // scode = "0"; @@ -115,12 +122,14 @@ public void TestReadParameterSets() value4 = "0.000"; string value5 = "0.000"; string torsionkey = "torsion" + ";" + sid1 + ";" + sid2 + ";" + sid3 + ";" + sid4; - var torsiondata = new List(); - torsiondata.Add((double)(double.Parse(value1))); - torsiondata.Add((double)(double.Parse(value2))); - torsiondata.Add((double)(double.Parse(value3))); - torsiondata.Add((double)(double.Parse(value4))); - torsiondata.Add((double)(double.Parse(value5))); + var torsiondata = new List + { + (double)(double.Parse(value1, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value2, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value3, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value4, NumberFormatInfo.InvariantInfo)), + (double)(double.Parse(value5, NumberFormatInfo.InvariantInfo)) + }; //opbend // scode = "0"; @@ -130,8 +139,10 @@ public void TestReadParameterSets() sid4 = "CR4R"; value1 = "10.86681780"; string opbendkey = "opbend" + ";" + sid1 + ";" + sid2 + ";" + sid3 + ";" + sid4; - var opbenddata = new List(); - opbenddata.Add((double)(double.Parse(value1))); + var opbenddata = new List + { + (double)(double.Parse(value1, NumberFormatInfo.InvariantInfo)) + }; //TODO data lines testing diff --git a/NCDKTests/Modelings/Builder3D/ModelBuilder3DTest.cs b/NCDKTests/Modelings/Builder3D/ModelBuilder3DTest.cs index 3fedb666..1b61f1d3 100644 --- a/NCDKTests/Modelings/Builder3D/ModelBuilder3DTest.cs +++ b/NCDKTests/Modelings/Builder3D/ModelBuilder3DTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using NCDK.IO; using NCDK.Layout; @@ -117,9 +117,9 @@ public void TestModelBuilder3D_c1ccccc1C0() [TestCategory("SlowTest")] public void TestModelBuilder3D_Konstanz() { - ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(Default.ChemObjectBuilder.Instance); + ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(ChemObjectBuilder.Instance); string smile = "C12(-[H])-C3(-C(-[H])(-[H])-C(-C4(-C5(-C(-Cl)(-Cl)-C(-C-3-4-[H])(-Cl)-C(-Cl)(-[H])-C-5(-Cl)-[H])-Cl)-[H])(-[H])-C-2(-O-1)-[H])-[H]"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles(smile); AddExplicitHydrogens(mol); mol = mb3d.Generate3DCoordinates(mol, false); @@ -360,7 +360,7 @@ public void TestModel3D_bug_1610997() [TestCategory("SlowTest")] public void TestModelBuilder3D_bug_1241421() { - ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(Default.ChemObjectBuilder.Instance); + ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(ChemObjectBuilder.Instance); string filename = "NCDK.Data.MDL.bug1241421.mol"; Stream ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); @@ -376,7 +376,7 @@ public void TestModelBuilder3D_bug_1241421() [TestCategory("SlowTest")] public void TestModelBuilder3D_reserpine() { - ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(Default.ChemObjectBuilder.Instance); + ModelBuilder3D mb3d = ModelBuilder3D.GetInstance(ChemObjectBuilder.Instance); string filename = "NCDK.Data.MDL.reserpine.mol"; Stream ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins); diff --git a/NCDKTests/Modelings/Builder3D/TemplateHandler3DTest.cs b/NCDKTests/Modelings/Builder3D/TemplateHandler3DTest.cs index 89c98ee9..967c7cfb 100644 --- a/NCDKTests/Modelings/Builder3D/TemplateHandler3DTest.cs +++ b/NCDKTests/Modelings/Builder3D/TemplateHandler3DTest.cs @@ -28,6 +28,7 @@ using System.Collections; using System.Collections.Generic; using System.IO; +using NCDK.Silent; namespace NCDK.Modelings.Builder3D { @@ -69,8 +70,8 @@ public void TestFingerprints() string filename = "NCDK.Data.MDL.fingerprints_from_modelbuilder3d.sdf"; Stream ins = ResourceLoader.GetAsStream(filename); - var data = new TemplateExtractor().MakeFingerprintsFromSdf(true, false, new Dictionary(), new StreamReader(ins), 10); - QueryChemObject obj = new QueryChemObject(Default.ChemObjectBuilder.Instance); + var data = TemplateExtractor.MakeFingerprintsFromSdf(true, false, new Dictionary(), new StreamReader(ins), 10); + QueryChemObject obj = new QueryChemObject(ChemObjectBuilder.Instance); var dummy = obj.Builder; for (int i = 0; i < data.Count; i++) { @@ -96,9 +97,9 @@ public void TestAnonFingerprints() string filename = "NCDK.Data.MDL.fingerprints_from_modelbuilder3d.sdf"; var ins = this.GetType().Assembly.GetManifestResourceStream(filename); - var data = new TemplateExtractor().MakeFingerprintsFromSdf(true, true, + var data = TemplateExtractor.MakeFingerprintsFromSdf(true, true, new Dictionary(), new StreamReader(ins), 10); - QueryChemObject obj = new QueryChemObject(Default.ChemObjectBuilder.Instance); + QueryChemObject obj = new QueryChemObject(ChemObjectBuilder.Instance); var dummy = obj.Builder; for (int i = 0; i < data.Count; i++) { diff --git a/NCDKTests/NCDKTests.csproj b/NCDKTests/NCDKTests.csproj index e26e80cb..29af09cc 100644 --- a/NCDKTests/NCDKTests.csproj +++ b/NCDKTests/NCDKTests.csproj @@ -1,6 +1,6 @@ - netcoreapp2.1 + net461 false Kazuya Ujihara NCDK @@ -1072,10 +1072,10 @@ - + - - + + diff --git a/NCDKTests/NInChI/TestNInchiOutputStructure.cs b/NCDKTests/NInChI/TestNInchiOutputStructure.cs index e2c6b3b3..b4eb7059 100644 --- a/NCDKTests/NInChI/TestNInchiOutputStructure.cs +++ b/NCDKTests/NInChI/TestNInchiOutputStructure.cs @@ -62,7 +62,7 @@ public void TestGetLog() public void TestGetWarningFlags() { NInchiOutputStructure output = new NInchiOutputStructure(InChIReturnCode.Ok); - ulong[,] flags = new ulong[,] { { 1, 2 }, { 3, 4 } }; + var flags = new ulong[] { 1, 2, 3, 4, }; output.WarningFlags = flags; Assert.AreEqual(flags, output.WarningFlags); } diff --git a/NCDKTests/Normalizers/NormalizerTest.cs b/NCDKTests/Normalizers/NormalizerTest.cs index 05279e5d..f8552b3d 100644 --- a/NCDKTests/Normalizers/NormalizerTest.cs +++ b/NCDKTests/Normalizers/NormalizerTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Xml.Linq; namespace NCDK.Normalizers diff --git a/NCDKTests/Normalizers/SMSDNormalizerTest.cs b/NCDKTests/Normalizers/SMSDNormalizerTest.cs index 4aba8c58..bf51ff04 100644 --- a/NCDKTests/Normalizers/SMSDNormalizerTest.cs +++ b/NCDKTests/Normalizers/SMSDNormalizerTest.cs @@ -20,6 +20,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; using System; @@ -39,7 +40,7 @@ public SMSDNormalizerTest() { } public void TestMakeDeepCopy() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer container = sp.ParseSmiles(rawMolSmiles); int counter = 0; @@ -63,7 +64,7 @@ public void TestMakeDeepCopy() public void TestAromatizeMolecule() { string rawMolSmiles = "C1=CC2=C(C=C1)C=CC=C2"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles(rawMolSmiles); SMSDNormalizer.AromatizeMolecule(mol); int count = 0; @@ -84,7 +85,7 @@ public void TestAromatizeMolecule() public void TestGetExplicitHydrogenCount() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom atom = null; foreach (var a in atomContainer.Atoms) @@ -108,7 +109,7 @@ public void TestGetExplicitHydrogenCount() public void TestGetImplicitHydrogenCount() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom atom = null; foreach (var a in atomContainer.Atoms) @@ -133,7 +134,7 @@ public void TestGetImplicitHydrogenCount() public void TestGetHydrogenCount() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom atom = null; foreach (var a in atomContainer.Atoms) @@ -156,7 +157,7 @@ public void TestGetHydrogenCount() public void TestRemoveHydrogensAndPreserveAtomID() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom beforeAtom = null; IAtom afterAtom = null; @@ -190,7 +191,7 @@ public void TestRemoveHydrogensAndPreserveAtomID() public void TestConvertExplicitToImplicitHydrogens() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); int expResult = 11; IAtomContainer result = SMSDNormalizer.ConvertExplicitToImplicitHydrogens(atomContainer); @@ -204,7 +205,7 @@ public void TestConvertExplicitToImplicitHydrogens() public void TestPercieveAtomTypesAndConfigureAtoms() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); SMSDNormalizer.PercieveAtomTypesAndConfigureAtoms(atomContainer); Assert.IsNotNull(atomContainer); diff --git a/NCDKTests/Pharmacophore/PharmacophoreUtilityTest.cs b/NCDKTests/Pharmacophore/PharmacophoreUtilityTest.cs index 806b8581..00885fa1 100644 --- a/NCDKTests/Pharmacophore/PharmacophoreUtilityTest.cs +++ b/NCDKTests/Pharmacophore/PharmacophoreUtilityTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.IO.Iterator; +using NCDK.Silent; using System.Collections.Generic; using System.IO; using System.Linq; @@ -34,7 +35,7 @@ static PharmacophoreUtilityTest() { string filename = "NCDK.Data.MDL.pcoretest1.sdf"; Stream ins = ResourceLoader.GetAsStream(filename); - IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(ins, Default.ChemObjectBuilder.Instance); + IEnumerableMDLConformerReader reader = new IEnumerableMDLConformerReader(ins, ChemObjectBuilder.Instance); conformers = reader.FirstOrDefault(); } @@ -107,17 +108,17 @@ public void TestReadPcoreAngleDef() foreach (var bond in def1.Bonds) { - if (bond is PharmacophoreQueryBond) + IAtom[] a; + switch (bond) { - PharmacophoreQueryBond cons = (PharmacophoreQueryBond)bond; - IAtom[] a = GetAtoms(cons); - Assert.AreEqual(2, a.Length); - } - else if (bond is PharmacophoreQueryAngleBond) - { - PharmacophoreQueryAngleBond cons = (PharmacophoreQueryAngleBond)bond; - IAtom[] a = GetAtoms(cons); - Assert.AreEqual(3, a.Length); + case PharmacophoreQueryBond cons: + a = GetAtoms(cons); + Assert.AreEqual(2, a.Length); + break; + case PharmacophoreQueryAngleBond cons: + a = GetAtoms(cons); + Assert.AreEqual(3, a.Length); + break; } } } @@ -168,7 +169,7 @@ public void TestPCoreWrite() Assert.AreEqual(0, nangle); } - private IAtom[] GetAtoms(IBond bond) + private static IAtom[] GetAtoms(IBond bond) { var alist = new List(); foreach (var iAtom in bond.Atoms) diff --git a/NCDKTests/QSAR/DescriptorEngineTest.cs b/NCDKTests/QSAR/DescriptorEngineTest.cs index 4ec54bfb..a2358538 100644 --- a/NCDKTests/QSAR/DescriptorEngineTest.cs +++ b/NCDKTests/QSAR/DescriptorEngineTest.cs @@ -17,6 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.Linq; namespace NCDK.QSAR @@ -33,47 +34,47 @@ public DescriptorEngineTest() { } [TestMethod()] public void TestConstructor() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); Assert.IsNotNull(engine); } [TestMethod()] public void TestLoadingOfMolecularDescriptors() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); Assert.IsNotNull(engine); - int loadedDescriptors = engine.GetDescriptorInstances().Count; + int loadedDescriptors = engine.GetDescriptorInstances().Count(); Assert.IsTrue(0 != loadedDescriptors, "Could not load any descriptors"); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count()); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count()); } [TestMethod()] public void TestLoadingOfAtomicDescriptors() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); Assert.IsNotNull(engine); - int loadedDescriptors = engine.GetDescriptorInstances().Count; + int loadedDescriptors = engine.GetDescriptorInstances().Count(); Assert.AreNotSame(0, loadedDescriptors); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count()); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count()); } [TestMethod()] public void TestLoadingOfBondDescriptors() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); Assert.IsNotNull(engine); - int loadedDescriptors = engine.GetDescriptorInstances().Count; + int loadedDescriptors = engine.GetDescriptorInstances().Count(); Assert.AreNotSame(0, loadedDescriptors); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count()); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count()); } [TestMethod()] public void TestDictionaryType() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); string className = "NCDK.QSAR.Descriptors.Moleculars.ZagrebIndexDescriptor"; DescriptorSpecification specRef = new DescriptorSpecification( @@ -88,7 +89,7 @@ public void TestDictionaryType() [TestMethod()] public void TestDictionaryClass() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); string className = "NCDK.QSAR.Descriptors.Moleculars.TPSADescriptor"; DescriptorSpecification specRef = new DescriptorSpecification( @@ -96,13 +97,13 @@ public void TestDictionaryClass() this.GetType().FullName, "The Chemistry Development Kit"); - string[] dictClass = engine.GetDictionaryClass(className); - Assert.AreEqual(2, dictClass.Length); + var dictClass = engine.GetDictionaryClass(className).ToList(); + Assert.AreEqual(2, dictClass.Count); Assert.AreEqual("topologicalDescriptor", dictClass[0]); Assert.AreEqual("electronicDescriptor", dictClass[1]); - dictClass = engine.GetDictionaryClass(specRef); - Assert.AreEqual(2, dictClass.Length); + dictClass = engine.GetDictionaryClass(specRef).ToList(); + Assert.AreEqual(2, dictClass.Count); Assert.AreEqual("topologicalDescriptor", dictClass[0]); Assert.AreEqual("electronicDescriptor", dictClass[1]); } @@ -110,7 +111,7 @@ public void TestDictionaryClass() [TestMethod()] public void TestAvailableClass() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); var availClasses = engine.GetAvailableDictionaryClasses(); Assert.AreEqual(5, availClasses.Count()); } @@ -118,12 +119,12 @@ public void TestAvailableClass() [TestMethod()] public void TestLoadingOfAtomPairDescriptors() { - DescriptorEngine engine = DescriptorEngine.Create(Default.ChemObjectBuilder.Instance); + DescriptorEngine engine = DescriptorEngine.Create(ChemObjectBuilder.Instance); Assert.IsNotNull(engine); - int loadedDescriptors = engine.GetDescriptorInstances().Count; + int loadedDescriptors = engine.GetDescriptorInstances().Count(); Assert.AreNotSame(0, loadedDescriptors); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count); - Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorClassNames().Count()); + Assert.AreEqual(loadedDescriptors, engine.GetDescriptorSpecifications().Count()); } } } diff --git a/NCDKTests/QSAR/DescriptorNamesTest.cs b/NCDKTests/QSAR/DescriptorNamesTest.cs index ab4b0bd9..6ae81440 100644 --- a/NCDKTests/QSAR/DescriptorNamesTest.cs +++ b/NCDKTests/QSAR/DescriptorNamesTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Tools.Manipulator; @@ -41,7 +41,7 @@ public DescriptorNamesTest() { } public void CheckUniqueMolecularDescriptorNames() { DescriptorEngine engine = new DescriptorEngine(new string[] { typeof(IMolecularDescriptor).FullName }, - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); var specs = engine.GetDescriptorSpecifications(); // we work with a simple molecule with 3D coordinates @@ -52,7 +52,7 @@ public void CheckUniqueMolecularDescriptorNames() var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); IAtomContainer ac = (IAtomContainer)cList[0]; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); - Isotopes.Instance.ConfigureAtoms(ac); + BODRIsotopeFactory.Instance.ConfigureAtoms(ac); engine.Process(ac); int ncalc = 0; @@ -72,7 +72,7 @@ public void CheckUniqueMolecularDescriptorNames() { if (!uniqueNames.Add(name)) dups.Add(name); } - Assert.AreEqual(specs.Count, ncalc); + Assert.AreEqual(specs.Count(), ncalc); Assert.AreEqual(descNames.Count, uniqueNames.Count); if (dups.Count != 0) { diff --git a/NCDKTests/QSAR/DescriptorValueTest.cs b/NCDKTests/QSAR/DescriptorValueTest.cs index b31dda5a..95960e03 100644 --- a/NCDKTests/QSAR/DescriptorValueTest.cs +++ b/NCDKTests/QSAR/DescriptorValueTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using System; namespace NCDK.QSAR { @@ -35,11 +36,11 @@ public DescriptorValueTest() private const string DESC_IMPL_ID = "bla4"; [TestMethod()] - public void TestDescriptorValue_DescriptorSpecification_arrayString_arrayObject_IDescriptorResult_arrayString() + public void TestDescriptorValueDescriptorSpecificationArrayStringArrayObjectIDescriptorResultArrayString() { DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); - var value = new DescriptorValue>(spec, new string[0], new object[0], new Result(0.7), + var value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), new Result(0.7), new string[] { "bla" }); Assert.IsNotNull(value); } @@ -50,7 +51,7 @@ public void TestGetValue() DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); Result doubleVal = new Result(0.7); - var value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { "bla" }); + var value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, new string[] { "bla" }); Assert.AreEqual(doubleVal, value.Value); } @@ -60,7 +61,7 @@ public void TestGetSpecification() DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); Result doubleVal = new Result(0.7); - var value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { "bla" }); + var value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, new string[] { "bla" }); Assert.AreEqual(spec, value.Specification); } @@ -70,8 +71,8 @@ public void TestGetParameters() DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); Result doubleVal = new Result(0.7); - var value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { "bla" }); - Assert.AreEqual(0, value.Parameters.Length); + var value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, new string[] { "bla" }); + Assert.AreEqual(0, value.Parameters.Count); } [TestMethod()] @@ -80,7 +81,7 @@ public void TestGetParameterNames() DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); Result doubleVal = new Result(0.7); - var value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { "bla" }); + var value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, new string[] { "bla" }); Assert.AreEqual(0, value.ParameterNames.Count); } @@ -90,17 +91,15 @@ public void TestGetNames() DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); Result doubleVal = new Result(0.7); - ArrayResult doubleVals = new ArrayResult(); - doubleVals.Add(0.1); - doubleVals.Add(0.2); + var doubleVals = new ArrayResult { 0.1, 0.2 }; IDescriptorValue value; - value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { "bla" }); + value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, new string[] { "bla" }); Assert.AreEqual(1, value.Names.Count); - value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { }); + value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, Array.Empty()); Assert.AreEqual(1, value.Names.Count); - value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, null); + value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, null); Assert.AreEqual(1, value.Names.Count); - value = new DescriptorValue>(spec, new string[0], new object[0], doubleVals, null); + value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVals, null); Assert.AreEqual(2, value.Names.Count); } @@ -110,7 +109,7 @@ public void TestGetException() DescriptorSpecification spec = new DescriptorSpecification(DESC_REF, DESC_IMPL_TITLE, DESC_IMPL_ID, DESC_IMPL_VENDOR); Result doubleVal = new Result(0.7); - var value = new DescriptorValue>(spec, new string[0], new object[0], doubleVal, new string[] { "bla" }, + var value = new DescriptorValue>(spec, Array.Empty(), Array.Empty(), doubleVal, new string[] { "bla" }, new CDKException("A test exception")); Assert.IsInstanceOfType(value.Exception, typeof(CDKException)); } diff --git a/NCDKTests/QSAR/Descriptors/Atomic/AtomDegreeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/AtomDegreeDescriptorTest.cs index b092fa79..90dcaad2 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/AtomDegreeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/AtomDegreeDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -38,7 +39,7 @@ public AtomDegreeDescriptorTest() public void TestAtomDegreeDescriptor() { IAtomicDescriptor descriptor = new AtomDegreeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(C)CCCC"); // Assert.AreEqual(3, ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationDescriptorTest.cs index 515cabbb..c03d4dc5 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -38,7 +39,7 @@ public AtomHybridizationDescriptorTest() [TestMethod()] public void TestAtomHybridizationDescriptorTest() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C#CC=CC"); // AddExplicitHydrogens(mol); var expectedStates = new Hybridization[] @@ -63,7 +64,7 @@ public void TestBug1701073() "C(#CN1CCCCC1)[Sn](C)(C)C", "c1([As+](c2ccccc2)(c2ccccc2)C)ccccc1.[I-]", "c1(noc(n1)CCC(=O)N(CC)CC)c1ccc(cc1)C", "c1c(c(ccc1)O)/C=N/CCCC", "c1(ccc(cc1)C#Cc1ccc(cc1)C#C)OC"}; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol; foreach (var smile in smiles) diff --git a/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs index cd6c4a58..27726b6d 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Smiles; using NCDK.Tools; @@ -233,15 +233,14 @@ public void TestAtomHybridizationVSEPRDescriptorTest_7() AtomHybridizationVSEPRDescriptor descriptor = new AtomHybridizationVSEPRDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("F-C=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); AssertAtomTypesPerceived(mol); for (int i = 0; i < 3; i++) @@ -266,15 +265,14 @@ public void TestAtomHybridizationVSEPRDescriptorTest_8() AtomHybridizationVSEPRDescriptor descriptor = new AtomHybridizationVSEPRDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[F+]=C-[C-]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AssertAtomTypesPerceived(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); AssertAtomTypesPerceived(mol); for (int i = 0; i < 3; i++) diff --git a/NCDKTests/QSAR/Descriptors/Atomic/AtomValenceDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/AtomValenceDescriptorTest.cs index 76accb8f..6216753f 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/AtomValenceDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/AtomValenceDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -38,7 +39,7 @@ public AtomValenceDescriptorTest() public void TestAtomValenceDescriptor() { IAtomicDescriptor descriptor = new AtomValenceDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCl"); // Assert.AreEqual(7, ((Result)descriptor.Calculate(mol.Atoms[2], mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Atomic/AtomicDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/AtomicDescriptorTest.cs index 37588e8d..f3748eea 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/AtomicDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/AtomicDescriptorTest.cs @@ -22,6 +22,7 @@ using NCDK.Tools.Diff; using System; using System.Diagnostics; +using NCDK.Silent; namespace NCDK.QSAR.Descriptors.Atomic { @@ -43,7 +44,7 @@ public override void SetDescriptor(Type descriptorClass) { if (descriptor == null) { - object descriptor = descriptorClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + object descriptor = descriptorClass.GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); if (!(descriptor is IAtomicDescriptor)) { throw new CDKException("The passed descriptor class must be a IAtomicDescriptor"); @@ -137,12 +138,12 @@ public void TestCalculate_NoModifications() private IAtomContainer SomeoneBringMeSomeWater() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("O"); c1.Point3D = new Vector3(0.0, 0.0, 0.0); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); h1.Point3D = new Vector3(1.0, 0.0, 0.0); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); h2.Point3D = new Vector3(-1.0, 0.0, 0.0); mol.Atoms.Add(c1); mol.Atoms.Add(h1); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/BondsToAtomDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/BondsToAtomDescriptorTest.cs index a3ba5cf4..2e82f01e 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/BondsToAtomDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/BondsToAtomDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -39,7 +40,7 @@ public void TestBondsToAtomDescriptor() { BondsToAtomDescriptor descriptor = new BondsToAtomDescriptor(); descriptor.Parameters = new object[] { 5 }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCCCC"); // Assert.AreEqual(5, ((Result)descriptor.Calculate(mol.Atoms[0], mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Atomic/CovalentRadiusDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/CovalentRadiusDescriptorTest.cs index 8253933a..b2f1a17c 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/CovalentRadiusDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/CovalentRadiusDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -36,7 +37,7 @@ public void TestVdWRadiusDescriptor() { double[] testResult = { 0.77 }; IAtomicDescriptor descriptor = new CovalentRadiusDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCN(C)(C)"); double retval = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value).Value; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/DistanceToAtomDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/DistanceToAtomDescriptorTest.cs index cef517b1..b3f966b7 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/DistanceToAtomDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/DistanceToAtomDescriptorTest.cs @@ -18,7 +18,7 @@ */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; namespace NCDK.QSAR.Descriptors.Atomic diff --git a/NCDKTests/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptorTest.cs index aec7328f..8a609769 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/EffectiveAtomPolarizabilityDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -43,7 +44,7 @@ public void TestEffectivePolarizabilityDescriptor() double[] testResult = { 4.7253, 6.1345, 6.763, 6.925, 5.41, 5.41 }; IAtomicDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCN(C)(C)"); AddExplicitHydrogens(mol); @@ -65,7 +66,7 @@ public void TestPolarizabilityDescriptor_Ethyl_chloride() EffectiveAtomPolarizabilityDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCl"); AddExplicitHydrogens(mol); for (int i = 0; i < 3; i++) @@ -84,7 +85,7 @@ public void TestPolarizabilityDescriptor_Allyl_bromide() double testResult = 6.1745; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml EffectiveAtomPolarizabilityDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCBr"); AddExplicitHydrogens(mol); @@ -101,7 +102,7 @@ public void TestPolarizabilityDescriptor_Isopentyl_iodide() double[] testResult = { 8.3585, 6.1118, 6.1118, 9.081, 10.526, 8.69 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml EffectiveAtomPolarizabilityDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); AddExplicitHydrogens(mol); @@ -121,7 +122,7 @@ public void TestPolarizabilityDescriptor_Ethoxy_ethane() double testResult = 5.207; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml EffectiveAtomPolarizabilityDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOCC"); AddExplicitHydrogens(mol); @@ -138,7 +139,7 @@ public void TestPolarizabilityDescriptor_Ethanolamine() double[] testResult = { 4.2552, 5.1945, 4.883, 3.595 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml EffectiveAtomPolarizabilityDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCO"); AddExplicitHydrogens(mol); for (int i = 0; i < 4; i++) @@ -157,7 +158,7 @@ public void TestPolarizabilityDescriptor_Allyl_mercaptan() double[] testResult = { 5.2995, 6.677, 7.677, 6.2545 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml EffectiveAtomPolarizabilityDescriptor descriptor = new EffectiveAtomPolarizabilityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCS"); AddExplicitHydrogens(mol); for (int i = 0; i < 4; i++) diff --git a/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs index 0937247f..814a9b53 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs @@ -16,8 +16,10 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -31,9 +33,8 @@ namespace NCDK.QSAR.Descriptors.Atomic [TestClass()] public class IPAtomicHOSEDescriptorTest : AtomicDescriptorTest { - private SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + private SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); + /// /// Constructor for the IPAtomicHOSEDescriptorTest object /// @@ -60,7 +61,7 @@ public void TestIPDescriptor1() IAtomContainer mol = sp.ParseSmiles("CCCCl"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[3], mol).Value).Value; double resultAccordingNIST = 10.8; @@ -78,7 +79,7 @@ public void TestIPDescriptor2() IAtomContainer mol = sp.ParseSmiles("CC(CC)Cl"); // not in db AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[4], mol).Value).Value; double resultAccordingNIST = 10.57; //value for CC(C)Cl @@ -96,7 +97,7 @@ public void TestNotDB() IAtomContainer mol = sp.ParseSmiles("C=CCCl"); // not in db AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[3], mol).Value).Value; double resultAccordingNIST = 10.8; //value for CCCCl aprox. @@ -114,7 +115,7 @@ public void TestIPDescriptor_1() IAtomContainer mol = sp.ParseSmiles("C-Cl"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value).Value; double resultAccordingNIST = 11.26; @@ -132,7 +133,7 @@ public void TestIPDescriptor_2() IAtomContainer mol = sp.ParseSmiles("C-C-Br"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[2], mol).Value).Value; double resultAccordingNIST = 11.29; @@ -149,7 +150,7 @@ public void TestIPDescriptor_3() IAtomContainer mol = sp.ParseSmiles("C-C-C-I"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[3], mol).Value).Value; double resultAccordingNIST = 9.27; @@ -168,8 +169,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2], mol).GetValue()).Value; // double resultAccordingNIST = 10.48; @@ -188,8 +188,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0], mol).GetValue()).Value; // double resultAccordingNIST = 7.77; @@ -208,8 +207,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[1],mol).GetValue()).Value; // double resultAccordingNIST = 8.24; @@ -228,8 +226,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2],mol).GetValue()).Value; // double resultAccordingNIST = 8.9; @@ -248,8 +245,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2], mol).GetValue()).Value; // double resultAccordingNIST = 8.5; @@ -269,8 +265,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0], mol).GetValue()).Value; // double resultAccordingNIST = 9.3; @@ -289,8 +284,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0],mol).GetValue()).Value; // double resultAccordingNIST = 9.01; @@ -310,8 +304,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2], mol).GetValue()).Value; //// Assert.IsNotNull(result); @@ -337,8 +330,7 @@ public void TestIPDescriptor_3() // AddExplicitHydrogens(mol); // AreEqual(10, mol.Atoms.Count); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // AreEqual("Unexpected number of lone pairs", 1, mol.GetLonePairCount()); // // AreEqual("N", mol.Atoms[2].Symbol); @@ -365,13 +357,12 @@ public void TestIPDescriptor_3() // [TestMethod()] // public void TestIPDescriptorReaction2() throws Exception{ // - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + // SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // IAtomContainer mol = sp.ParseSmiles("CCCCCC"); // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // descriptor.Calculate(mol.Atoms[0], mol); // IReactionSet reactionSet = descriptor.ReactionSet; @@ -391,13 +382,12 @@ public void TestIPDescriptor_3() // [TestMethod()] // public void TestIPPySystemWithHeteroatomDescriptor3() throws Exception{ // - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + // SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // IAtomContainer mol = sp.ParseSmiles("O(C=CC=C)C"); // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0],mol).GetValue()).Value; // double resultAccordingNIST = 8.03; @@ -419,13 +409,12 @@ public void TestIPDescriptor_3() // [TestMethod()] // public void TestIPPySystemWithHeteroatomDescriptor2() throws Exception{ // - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + // SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // IAtomContainer mol = sp.ParseSmiles("OC=CC"); // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0],mol).GetValue()).Value; // double resultAccordingNIST = 8.64; @@ -447,13 +436,12 @@ public void TestIPDescriptor_3() // [TestMethod()] // public void TestIPPySystemWithHeteroatomDescriptor1() throws Exception{ // - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + // SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // IAtomContainer mol = sp.ParseSmiles("C1=C(C)CCS1"); // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[5],mol).GetValue()).Value; // double resultAccordingNIST = 7.77; @@ -476,13 +464,12 @@ public void TestIPDescriptor_3() // [TestMethod()] // public void TestIDescriptor5() throws Exception{ // - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + // SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // IAtomContainer mol = sp.ParseSmiles("OC(C#CC)(C)C"); // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(mol); + // LonePairElectronChecker.Saturate(mol); // // descriptor.Calculate(mol.Atoms[0],mol); // diff --git a/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptorTest.cs index 2f32b0b3..51d662e9 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptorTest.cs @@ -18,7 +18,7 @@ */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; namespace NCDK.QSAR.Descriptors.Atomic diff --git a/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptorTest.cs index 9a4045dd..cb9c2558 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptorTest.cs @@ -18,7 +18,7 @@ */ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; namespace NCDK.QSAR.Descriptors.Atomic diff --git a/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptorTest.cs index 254b6ec5..0bf5148c 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInAromaticSystemDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -39,7 +40,7 @@ public void TestIsProtonInAromaticSystemDescriptor() { IAtomicDescriptor descriptor = new IsProtonInAromaticSystemDescriptor(); descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Oc1cc(OC)c(cc1Br)Br"); AddExplicitHydrogens(mol); Assert.AreEqual("H", mol.Atoms[11].Symbol); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptorTest.cs index 10dacf15..65e89081 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/IsProtonInConjugatedPiSystemDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -39,7 +40,7 @@ public void TestIsProtonInConjugatedPiSystemDescriptor() { IAtomicDescriptor descriptor = new IsProtonInConjugatedPiSystemDescriptor(); descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CNC=CC=C"); AddExplicitHydrogens(mol); Assert.IsTrue(((Result)descriptor.Calculate(mol.Atoms[13], mol).Value).Value); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs index 609bc0e7..a1b1ed3f 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Smiles; using NCDK.Tools; @@ -34,8 +34,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public class PartialPiChargeDescriptorTest : AtomicDescriptorTest { private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + public PartialPiChargeDescriptorTest() { SetDescriptor(typeof(PartialPiChargeDescriptor)); @@ -60,7 +59,7 @@ public void TestPartialPiChargeDescriptor_Methyl_Fluoride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -100,7 +99,7 @@ public void TestPartialPiChargeDescriptor_Fluoroethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -139,7 +138,7 @@ public void TestPartialPiChargeDescriptor_FormicAcid() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -186,7 +185,7 @@ public void TestPartialPiChargeDescriptor_Fluorobenzene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -228,7 +227,7 @@ public void TestPartialPiChargeDescriptor_Methoxyethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 4/* mol.Atoms.Count */; i++) { @@ -275,7 +274,7 @@ public void TestPartialPiChargeDescriptor_1_Methoxybutadiene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -317,11 +316,11 @@ public void TestPartialPiChargeDescriptoCharge_1() double[] testResult = { 0.0613, -0.0554, 0.0, -0.0059, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("F[C+]([H])[C-]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 6; i++) { @@ -368,7 +367,7 @@ public void TestPartialPiChargeDescriptoCharge_2() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -396,10 +395,10 @@ public void TestPartialPiChargeDescriptoCharge_3() double[] testResult = { -0.0379, -0.0032, 0.0, -0.0078, 0.0, 0.0488, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C([H])[C+]([H])[C-]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -429,12 +428,12 @@ public void TestPartialPiChargeDescripto4() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOCCCO"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -451,13 +450,13 @@ public void TestArticle1() IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); double[] testResult = { 0.0, 0.0216, -0.1644, 0.1428, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(=O)N"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); descriptor.Parameters = new object[] { 6, true }; - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -520,7 +519,7 @@ public void TestSousa() AddExplicitHydrogens(mol); descriptor.Parameters = new object[] { 6, true }; - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -550,12 +549,12 @@ public void TestBondNotConjugated() IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); double[] testResult = { 0.0, 0.0004, 0.0, -0.0004, 0.0, 0.0, 0.0, 0.0, 0.0277, 0.0, -0.0277 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]C([H])=C([H])C([H])([H])C([H])=O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); descriptor.Parameters = new object[] { 6, true }; - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -581,16 +580,16 @@ public void TestBondNotConjugated() [TestCategory("SlowTest")] public void TestDifferentStarts() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles("C=CCC=O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); AddExplicitHydrogens(mol1); - lpcheck.Saturate(mol1); + LonePairElectronChecker.Saturate(mol1); IAtomContainer mol2 = sp.ParseSmiles("O=CCC=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); AddExplicitHydrogens(mol2); - lpcheck.Saturate(mol2); + LonePairElectronChecker.Saturate(mol2); IAtomicDescriptor descriptor1 = new PartialPiChargeDescriptor(); IAtomicDescriptor descriptor2 = new PartialPiChargeDescriptor(); @@ -617,12 +616,12 @@ public void TestBondNotConjugated1() IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); double[] testResult = { 0.0, -0.0009, 0.0, 0.0009, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]C([H])=C([H])C([H])([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); descriptor.Parameters = new object[] { 6, true }; - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -649,12 +648,12 @@ public void TestBondNotConjugated2() IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); double[] testResult = { 0.0, 0.25, 0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]C([H])=C([H])[C+]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); descriptor.Parameters = new object[] { 6, true }; - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -681,11 +680,11 @@ public void TestBondNotConjugated2() public void TestLangCalculation() { IAtomicDescriptor descriptor = new PartialPiChargeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1ccc(cc1)N3c4ccccc4(c2ccccc23)"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); descriptor.Parameters = new object[] { 6, true }; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs index 76777080..0ea3d50c 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Smiles; using NCDK.Tools; @@ -34,8 +34,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public class PartialSigmaChargeDescriptorTest : AtomicDescriptorTest { private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + public PartialSigmaChargeDescriptorTest() { SetDescriptor(typeof(PartialSigmaChargeDescriptor)); @@ -66,7 +65,7 @@ public void TestPartialSigmaChargeDescriptor_Fluoroethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -91,7 +90,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_Floride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); AddExplicitHydrogens(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -118,7 +117,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_chloride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -144,7 +143,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_bromide() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -169,7 +168,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_iodide() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -198,7 +197,7 @@ public void TestPartialSigmaChargeDescriptor_Allyl_bromide() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); double result = ((Result)descriptor.Calculate(molecule.Atoms[3], molecule).Value).Value; Assert.AreEqual(testResult, result, 0.01); @@ -213,7 +212,7 @@ public void TestPartialSigmaChargeDescriptor_Isopentyl_iodide() { double[] testResult = { -0.0458, -0.0623, -0.0623, -0.0415, 0.0003, -0.0855 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -247,7 +246,7 @@ public void TestPartialSigmaChargeDescriptor_Ethoxy_ethane() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); double result = ((Result)descriptor.Calculate(molecule.Atoms[2], molecule).Value).Value; Assert.AreEqual(testResult, result, 0.01); @@ -273,7 +272,7 @@ public void TestPartialSigmaChargeDescriptor_Ethanolamine() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 4; i++) { @@ -302,7 +301,7 @@ public void TestPartialSigmaChargeDescriptor_Allyl_mercaptan() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 4; i++) { @@ -317,7 +316,7 @@ public void TestPartialSigmaChargeDescriptor1() { double[] testResult = { -0.2138, 0.079, 0.0942, -0.072, 0.0563, 0.0563 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[F+]=C([H])[C-]([H])[H]"); for (int i = 0; i < mol.Atoms.Count; i++) @@ -332,7 +331,7 @@ public void TestPartialSigmaChargeDescriptor2() { double[] testResult = { -0.3855, -0.0454, 0.0634, -0.0544, -0.0391, -0.0391 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C([H])[C-]([H])[H]"); descriptor.Parameters = new object[] { 6 }; for (int i = 0; i < mol.Atoms.Count; i++) @@ -347,7 +346,7 @@ public void TestPartialSigmaChargeDescriptor3() { double[] testResult = { -0.3855, -0.0454, 0.0634, -0.0544, -0.0391, -0.0391 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[O-]C([H])=C([H])[H]"); for (int i = 0; i < mol.Atoms.Count; i++) @@ -374,7 +373,7 @@ public void TestPartialSigmaChargeDescriptor4() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -405,7 +404,7 @@ public void TestPartialSigmaChargeDescriptor5() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); descriptor.Parameters = new object[] { 6 }; @@ -421,7 +420,7 @@ public void TestPartialSigmaChargeDescriptor6() { double[] testResult = { -0.4331, -0.1067, 0.0133, 0.0133, 0.0133 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[O-]C([H])([H])[H]"); descriptor.Parameters = new object[] { 6 }; for (int i = 0; i < mol.Atoms.Count; i++) @@ -440,7 +439,7 @@ public void TestPartialSigmaChargeDescriptor7() { // from Petra online: http://www2.chemi.uni.erlange.de/services/petra/smiles.pthml double[] testResult = { 0.0835, 0.0265, -0.2622, 0.0265, 0.0835, -0.0444, 0.064, -0.0596, 0.0626, -0.0444, 0.064 }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]c1[n-][c+]([H])c([H])c([H])c1([H])"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); @@ -449,7 +448,7 @@ public void TestPartialSigmaChargeDescriptor7() for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; - // logger.debug(mol.getAtom(i).getSymbol()+",result: "+result); + // logger.debug(mol.getAtom(i).getSymbol()+",result: "+result); Assert.AreEqual(testResult[i], result, 0.05); } } diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs index 380b094e..1d500e08 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -32,8 +33,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public class PartialTChargePEOEDescriptorTest : AtomicDescriptorTest { private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + public PartialTChargePEOEDescriptorTest() { SetDescriptor(typeof(PartialTChargePEOEDescriptor)); @@ -58,7 +58,7 @@ public void TestPartialTChargeDescriptor_Methyl_Fluoride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); AddExplicitHydrogens(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -80,12 +80,12 @@ public void TestPartialTChargeDescriptor_Fluoroethylene() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PartialTChargePEOEDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("F-C=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -116,7 +116,7 @@ public void TestPartialTChargeDescriptor_FormicAcid() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -156,7 +156,7 @@ public void TestPartialTChargeDescriptor_Fluorobenzene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 5; i++) { @@ -189,7 +189,7 @@ public void TestPartialTChargeDescriptor_Methoxyethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -227,7 +227,7 @@ public void TestPartialTChargeDescriptor_1_Methoxybutadiene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptorTest.cs index f73ec94c..4dbb1407 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PeriodicTablePositionDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -38,7 +39,7 @@ public PeriodicTablePositionDescriptorTest() public void TestPeriodicTablePositionDescriptor() { IAtomicDescriptor descriptor = new PeriodicTablePositionDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCl"); // Assert.AreEqual(3, ((Result)descriptor.Calculate(mol.Atoms[2], mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs index 3d621f7b..2dff5f42 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -32,7 +33,6 @@ namespace NCDK.QSAR.Descriptors.Atomic public class PiElectronegativityDescriptorTest : AtomicDescriptorTest { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); /// /// Constructor for the PiElectronegativityDescriptorTest object @@ -52,12 +52,11 @@ public void TestPiElectronegativityDescriptor_Methyl_Fluoride() double[] testResult = { 3.9608, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("FC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -84,12 +83,11 @@ public void TestPiElectronegativityDescriptor_Methyl_Chloride() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("ClC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -115,12 +113,11 @@ public void TestPiElectronegativityDescriptor_Methyl_Iodide() double[] testResult = { 4.1951, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("IC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -146,12 +143,11 @@ public void TestPiElectronegativityDescriptor_Methyl_Bromide() double[] testResult = { 3.8922, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("BrC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -177,12 +173,11 @@ public void TestPiElectronegativityDescriptor_Methyl_Alcohol() double[] testResult = { 3.1138, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("OC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 4; i++) { @@ -208,12 +203,11 @@ public void TestPiElectronegativityDescriptor_Formaldehyde() double[] testResult = { 6.3012, 8.0791, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -240,14 +234,13 @@ public void TestPiElectronegativityDescriptor_Ethylene() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 3; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -272,14 +265,13 @@ public void TestPiElectronegativityDescriptor_Fluoroethylene() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("F-C=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 3; i++) { @@ -305,14 +297,13 @@ public void TestPiElectronegativityDescriptor_FormicAcid() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(=O)O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -338,14 +329,13 @@ public void TestPiElectronegativityDescriptor_Methoxyethylene() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=C-O-C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -371,14 +361,13 @@ public void TestPiElectronegativity1() // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("F[C+][C-]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -407,14 +396,13 @@ public void TestPiElectronegativity2() /// IAtomicDescriptor descriptor = new PiElectronegativityDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOCCCO"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -449,7 +437,7 @@ public void TestCompareIonized() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molA); AddExplicitHydrogens(molA); - lpcheck.Saturate(molA); + LonePairElectronChecker.Saturate(molA); double resultA = ((Result)descriptor.Calculate(molA.Atoms[3], molA).Value).Value; @@ -468,7 +456,7 @@ public void TestCompareIonized() AddExplicitHydrogens(molB); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molB); - lpcheck.Saturate(molB); + LonePairElectronChecker.Saturate(molB); Assert.AreEqual(1, molB.Atoms[3].FormalCharge.Value, 0.00001); Assert.AreEqual(1, molB.SingleElectrons.Count, 0.00001); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs index 2c7c8eb9..2ca14f73 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs @@ -31,7 +31,6 @@ namespace NCDK.QSAR.Descriptors.Atomic [TestClass()] public class ProtonAffinityHOSEDescriptorTest : AtomicDescriptorTest { - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public ProtonAffinityHOSEDescriptorTest() @@ -70,7 +69,7 @@ public void TestAffinityDescriptor1() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[6], mol).Value).Value; double resultAccordingNIST = 753.1; @@ -91,7 +90,7 @@ public void TestAffinityDescriptor2() AddExplicitHydrogens(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[2], mol).Value).Value; double resultAccordingNIST = 693.4; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptorTest.cs index ca741800..ae357764 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/ProtonTotalPartialChargeDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -37,7 +38,7 @@ public void TestProtonTotalPartialChargeDescriptorTest() double[] testResult = { 0.07915, 0.05783, 0.05783, 0.05783 }; IAtomicDescriptor descriptor = new ProtonTotalPartialChargeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CF"); AddExplicitHydrogens(mol); ArrayResult retval = (ArrayResult)descriptor.Calculate(mol.Atoms[0], mol).Value; @@ -52,7 +53,7 @@ public void TestProtonTotalPartialChargeDescriptorTest() public void TestNaNs() { IAtomicDescriptor descriptor = new ProtonTotalPartialChargeDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(F)(F)"); AddExplicitHydrogens(mol); ArrayResult retval = (ArrayResult)descriptor.Calculate(mol.Atoms[0], mol).Value; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3RTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3RTest.cs index c4d91dfa..0f6d30f8 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3RTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_G3RTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; @@ -11,7 +11,7 @@ public class RDFProtonDescriptor_G3RTest : AtomicDescriptorTest { public RDFProtonDescriptor_G3RTest() { - SetDescriptor(typeof(RDFProtonDescriptor_G3R)); + SetDescriptor(typeof(RDFProtonDescriptorG3R)); } [TestMethod()] @@ -33,7 +33,7 @@ public void TestExample1() if (mol.Atoms[i].Symbol.Equals("H")) { //secondly perform calculation on it. - RDFProtonDescriptor_G3R descriptor = new RDFProtonDescriptor_G3R(); + RDFProtonDescriptorG3R descriptor = new RDFProtonDescriptorG3R(); var dv = descriptor.Calculate(mol.Atoms[i], mol); IDescriptorResult result = dv.Value; // Console.Out.WriteLine("array: " + result.ToString()); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDRTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDRTest.cs index 5d3aa3c6..95e496b5 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDRTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GDRTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; @@ -11,7 +11,7 @@ public class RDFProtonDescriptor_GDRTest : AtomicDescriptorTest { public RDFProtonDescriptor_GDRTest() { - SetDescriptor(typeof(RDFProtonDescriptor_GDR)); + SetDescriptor(typeof(RDFProtonDescriptorGDR)); } [TestMethod()] @@ -33,7 +33,7 @@ public void TestExample1() if (mol.Atoms[i].Symbol.Equals("H")) { //secondly perform calculation on it. - RDFProtonDescriptor_GDR descriptor = new RDFProtonDescriptor_GDR(); + RDFProtonDescriptorGDR descriptor = new RDFProtonDescriptorGDR(); var dv = descriptor.Calculate(mol.Atoms[i], mol); IDescriptorResult result = dv.Value; // Console.Out.WriteLine("array: " + result.ToString()); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHRTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHRTest.cs index 4a844eb3..781f4d19 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHRTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHRTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; @@ -11,7 +11,7 @@ public class RDFProtonDescriptor_GHRTest : AtomicDescriptorTest { public RDFProtonDescriptor_GHRTest() { - SetDescriptor(typeof(RDFProtonDescriptor_GHR)); + SetDescriptor(typeof(RDFProtonDescriptorGHR)); } // @cdk.bug 1632419 @@ -28,7 +28,7 @@ public void TestExample1() var som = model.MoleculeSet; IAtomContainer mol = som[0]; - RDFProtonDescriptor_GHR descriptor = new RDFProtonDescriptor_GHR(); + RDFProtonDescriptorGHR descriptor = new RDFProtonDescriptorGHR(); int hNumber = 0; for (int i = 0; i < mol.Atoms.Count; i++) { diff --git a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topolTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topolTest.cs index 354eaab9..efba341d 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topolTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GHR_topolTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; @@ -11,7 +11,7 @@ public class RDFProtonDescriptor_GHR_topolTest : AtomicDescriptorTest { public RDFProtonDescriptor_GHR_topolTest() { - SetDescriptor(typeof(RDFProtonDescriptor_GHR_topol)); + SetDescriptor(typeof(RDFProtonDescriptorGHRTopology)); } [TestMethod()] @@ -33,7 +33,7 @@ public void TestExample1() if (mol.Atoms[i].Symbol.Equals("H")) { //secondly perform calculation on it. - RDFProtonDescriptor_GHR_topol descriptor = new RDFProtonDescriptor_GHR_topol(); + RDFProtonDescriptorGHRTopology descriptor = new RDFProtonDescriptorGHRTopology(); var dv = descriptor.Calculate(mol.Atoms[i], mol); IDescriptorResult result = dv.Value; // Console.Out.WriteLine("array: " + result.ToString()); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSRTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSRTest.cs index e9ea8425..d9975f17 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSRTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/RDFProtonDescriptor_GSRTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; @@ -11,7 +11,7 @@ public class RDFProtonDescriptor_GSRTest : AtomicDescriptorTest { public RDFProtonDescriptor_GSRTest() { - SetDescriptor(typeof(RDFProtonDescriptor_GSR)); + SetDescriptor(typeof(RDFProtonDescriptorGSR)); } [TestMethod()] @@ -33,7 +33,7 @@ public void TestExample1() if (mol.Atoms[i].Symbol.Equals("H")) { //secondly perform calculation on it. - RDFProtonDescriptor_GSR descriptor = new RDFProtonDescriptor_GSR(); + RDFProtonDescriptorGSR descriptor = new RDFProtonDescriptorGSR(); var dv = descriptor.Calculate(mol.Atoms[i], mol); IDescriptorResult result = dv.Value; // Console.Out.WriteLine("array: " + result.ToString()); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs index 6e201e56..c2c52c0d 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs @@ -32,8 +32,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public class SigmaElectronegativityDescriptorTest : AtomicDescriptorTest { private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - private LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + public SigmaElectronegativityDescriptorTest() { SetDescriptor(typeof(SigmaElectronegativityDescriptor)); @@ -199,7 +198,7 @@ public void TestCompareIonized() AddExplicitHydrogens(molA); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molA); - lpcheck.Saturate(molA); + LonePairElectronChecker.Saturate(molA); double resultA = ((Result)descriptor.Calculate(molA.Atoms[3], molA).Value).Value; @@ -218,7 +217,7 @@ public void TestCompareIonized() AddExplicitHydrogens(molB); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molB); - lpcheck.Saturate(molB); + LonePairElectronChecker.Saturate(molB); Assert.AreEqual(1, molB.Atoms[3].FormalCharge.Value, 0.00001); Assert.AreEqual(1, molB.SingleElectrons.Count, 0.00001); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs index b23a5aa1..19cf0fcf 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs @@ -31,8 +31,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public class StabilizationPlusChargeDescriptorTest : AtomicDescriptorTest { private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - + public StabilizationPlusChargeDescriptorTest() { descriptor = new StabilizationPlusChargeDescriptor(); @@ -54,7 +53,7 @@ public void TestStabilizationPlusChargeDescriptor() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Result result = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value); @@ -75,7 +74,7 @@ public void TestNotCharged() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Result result = ((Result)descriptor.Calculate(mol.Atoms[0], mol).Value); @@ -97,7 +96,7 @@ public void TestStabilizationPlusChargeDescriptor2() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Result result = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value); @@ -119,7 +118,7 @@ public void TestStabilizationComparative() mol1.AddBond(mol1.Atoms[1], mol1.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); AddExplicitHydrogens(mol1); - lpcheck.Saturate(mol1); + LonePairElectronChecker.Saturate(mol1); Result result1 = ((Result)descriptor.Calculate(mol1.Atoms[1], mol1).Value); @@ -132,7 +131,7 @@ public void TestStabilizationComparative() mol2.AddBond(mol2.Atoms[1], mol2.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); AddExplicitHydrogens(mol2); - lpcheck.Saturate(mol2); + LonePairElectronChecker.Saturate(mol2); Result result2 = ((Result)descriptor.Calculate(mol2.Atoms[1], mol2).Value); @@ -145,7 +144,7 @@ public void TestStabilizationComparative() mol3.AddBond(mol3.Atoms[1], mol3.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol3); AddExplicitHydrogens(mol3); - lpcheck.Saturate(mol3); + LonePairElectronChecker.Saturate(mol3); Result result3 = ((Result)descriptor.Calculate(mol3.Atoms[1], mol3).Value); @@ -172,7 +171,7 @@ public void TestCompareIonized() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molA); AddExplicitHydrogens(molA); - lpcheck.Saturate(molA); + LonePairElectronChecker.Saturate(molA); double resultA = ((Result)descriptor.Calculate(molA.Atoms[3], molA).Value).Value; @@ -191,7 +190,7 @@ public void TestCompareIonized() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molB); AddExplicitHydrogens(molB); - lpcheck.Saturate(molB); + LonePairElectronChecker.Saturate(molB); Assert.AreEqual(1, molB.Atoms[3].FormalCharge.Value, 0.00001); Assert.AreEqual(1, molB.SingleElectrons.Count, 0.00001); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/VdWRadiusDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/VdWRadiusDescriptorTest.cs index 2d4f154f..dc22a02e 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/VdWRadiusDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/VdWRadiusDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Atomic @@ -36,7 +37,7 @@ public void TestVdWRadiusDescriptor() { double[] testResult = { 1.7 }; IAtomicDescriptor descriptor = new VdWRadiusDescriptor(); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCN(C)(C)"); double retval = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value).Value; diff --git a/NCDKTests/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptorTest.cs index d01441b0..8ad88203 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/AtomicNumberDifferenceDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Bonds @@ -34,7 +35,7 @@ public AtomicNumberDifferenceDescriptorTest() [TestMethod()] public void TestDescriptor1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles("CC"); double value = ((Result)descriptor.Calculate(mol1.Bonds[0], mol1).Value).Value; Assert.AreEqual(0, value, 0.0000); @@ -43,7 +44,7 @@ public void TestDescriptor1() [TestMethod()] public void TestDescriptor2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles("CO"); double value = ((Result)descriptor.Calculate(mol1.Bonds[0], mol1).Value).Value; Assert.AreEqual(2, value, 0.0000); diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondDescriptorTest.cs index 7201e720..b00ce5a5 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondDescriptorTest.cs @@ -21,6 +21,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Tools.Diff.Tree; using System; +using NCDK.Silent; namespace NCDK.QSAR.Descriptors.Bonds { @@ -129,12 +130,12 @@ public void TestCalculate_NoModifications() private IAtomContainer SomeoneBringMeSomeWater() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("O"); c1.Point3D = new Vector3(0.0, 0.0, 0.0); - IAtom h1 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h1 = ChemObjectBuilder.Instance.NewAtom("H"); h1.Point3D = new Vector3(1.0, 0.0, 0.0); - IAtom h2 = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h2 = ChemObjectBuilder.Instance.NewAtom("H"); h2.Point3D = new Vector3(-1.0, 0.0, 0.0); mol.Atoms.Add(c1); mol.Atoms.Add(h1); diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptorTest.cs index 1a14e048..e4ddce57 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptorTest.cs @@ -19,6 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Bonds @@ -42,7 +43,7 @@ public void TestBondPiElectronegativityDescriptor() double[] testResult = { 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CF"); AddExplicitHydrogens(mol); @@ -62,7 +63,7 @@ public void TestBondPiElectronegativityDescriptor_Allyl_bromide() descriptor = new BondPartialPiChargeDescriptor(); double[] testResult = { 0.0022, 0.0011, 0.0011, 0.0011, 0.0011, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCBr"); AddExplicitHydrogens(mol); @@ -82,7 +83,7 @@ public void TestBondPiElectronegativityDescriptor_Isopentyl_iodide() descriptor = new BondPartialPiChargeDescriptor(); double testResult = 0.0; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); AddExplicitHydrogens(mol); for (int i = 0; i < 6; i++) @@ -101,7 +102,7 @@ public void TestBondPiElectronegativityDescriptor_Allyl_mercaptan() descriptor = new BondPartialPiChargeDescriptor(); double[] testResult = { 0.0006, 0.0003, 0.0003, 0.0003, 0.0003, 0.0, 0.0, 0.0, 0.0 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCS"); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptorTest.cs index e324ac69..e75f4865 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialSigmaChargeDescriptorTest.cs @@ -19,6 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Bonds @@ -41,7 +42,7 @@ public void TestBondSigmaElectronegativityDescriptor() { double[] testResult = { 0.3323, 0.0218 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CF"); AddExplicitHydrogens(mol); @@ -60,7 +61,7 @@ public void TestBondSigmaElectronegativityDescriptor_Methyl_chloride() { double[] testResult = { 0.2137, 0.0075 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCl"); AddExplicitHydrogens(mol); for (int i = 0; i < 2; i++) @@ -78,7 +79,7 @@ public void TestBondSigmaElectronegativityDescriptor_Allyl_bromide() { double[] testResult = { 0.0265, 0.1268, 0.1872, 0.1564, 0.1564, 0.1347, 0.0013, 0.0013 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCBr"); AddExplicitHydrogens(mol); @@ -97,7 +98,7 @@ public void TestBondSigmaElectronegativityDescriptor_Isopentyl_iodide() { double testResult = 0.0165; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); AddExplicitHydrogens(mol); @@ -113,7 +114,7 @@ public void TestBondSigmaElectronegativityDescriptor_Ethoxy_ethane() { double[] testResult = { 0.0864, 0.4262, 0.4262, 0.0864, 0.0662, 0.0662, 0.0662, 0.0104, 0.0104 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOCC"); AddExplicitHydrogens(mol); @@ -132,7 +133,7 @@ public void TestBondSigmaElectronegativityDescriptor_Ethanolamine() { double[] testResult = { 0.3463, 0.0274, 0.448, 0.448, 0.448 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCO"); AddExplicitHydrogens(mol); @@ -151,7 +152,7 @@ public void TestBondSigmaElectronegativityDescriptor_Allyl_mercaptan() { double[] testResult = { 0.0203, 0.0921, 0.1835, 0.1569, 0.3593, 8.5917 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCS"); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs index 93bd2b97..fa90d4e0 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs @@ -19,6 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -43,14 +44,13 @@ public void TestBondTElectronegativityDescriptor() { double[] testResult = { 0.3323, 0.0218 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CF"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 2; i++) { @@ -67,12 +67,11 @@ public void TestBondTElectronegativityDescriptor_Allyl_bromide() { double[] testResult = { 0.0243, 0.1279, 0.1872, 0.1553, 0.1553, 0.1358, 0.0013, 0.0013 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCBr"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 8; i++) { @@ -89,7 +88,7 @@ public void TestBondTElectronegativityDescriptor_Isopentyl_iodide() { double testResult = 0.0165; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -105,7 +104,7 @@ public void TestBondTElectronegativityDescriptor_Allyl_mercaptan() { double[] testResult = { 0.0197, 0.0924, 0.1835, 0.1566, 0.1566, 0.1412, 0.0323, 0.0323, 0.2761 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCS"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs index 7de3f0f9..e3b0867e 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs @@ -19,6 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -43,12 +44,11 @@ public BondSigmaElectronegativityDescriptorTest() public void TestBondSigmaElectronegativityDescriptor() { double[] testResult = { 2.5882, 1.1894 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CF"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 2; i++) { @@ -66,7 +66,7 @@ public void TestBondSigmaElectronegativityDescriptor_Methyl_chloride() { double[] testResult = { 2.1612, 0.8751 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCl"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -85,7 +85,7 @@ public void TestBondSigmaElectronegativityDescriptor_Allyl_bromide() { double[] testResult = { 0.2396, 0.3635, 1.7086, 0.3635, 0.338, 0.574, 0.969, 0.969 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCBr"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -105,7 +105,7 @@ public void TestBondSigmaElectronegativityDescriptor_Isopentyl_iodide() { double testResult = 0.1482; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)CCI"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -122,7 +122,7 @@ public void TestBondSigmaElectronegativityDescriptor_Ethoxy_ethane() { double[] testResult = { 0.7939, 1.0715, 1.0715, 0.7939, 0.2749, 0.2749, 0.2749, 0.8796, 0.8796 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOCC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -142,7 +142,7 @@ public void TestBondSigmaElectronegativityDescriptor_Ethanolamine() { double[] testResult = { 0.0074, 0.3728, 0.8547, 0.2367, 0.2367 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NCCO"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -162,7 +162,7 @@ public void TestBondSigmaElectronegativityDescriptor_Allyl_mercaptan() { double[] testResult = { 0.1832, 0.0143, 0.5307, 0.3593, 0.3593, 8.5917 }; // from Petra online: http://www2.chemie.uni-erlangen.de/services/petra/smiles.phtml - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CCS"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/DescriptorTest.cs b/NCDKTests/QSAR/Descriptors/DescriptorTest.cs index 81d19a2e..70c961eb 100644 --- a/NCDKTests/QSAR/Descriptors/DescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/DescriptorTest.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using System; @@ -33,8 +34,6 @@ public abstract class DescriptorTest { protected virtual T Descriptor { get; set; } - public DescriptorTest() { } - public virtual void SetDescriptor(Type descriptorClass) { if (Descriptor == null) @@ -48,20 +47,19 @@ public virtual void SetDescriptor(Type descriptorClass) /// Makes sure that the extending class has set the . /// Each extending class should have this bit of code: /// - /// public void TestClassName() { + /// public void TestClassName() + /// { /// // Pass a Type, not an Object! /// SetDescriptor(typeof(SomeDescriptor)); /// } /// - /// /// The unit tests in the extending class may use this instance, but /// are not required. - /// /// [TestMethod()] public void TestHasSetSuperDotDescriptor() { - Assert.IsNotNull(Descriptor, "The extending class must set the super.descriptor in its SetUp() method."); + Assert.IsNotNull(Descriptor, $"The extending class must set the super.descriptor in its {nameof(SetDescriptor)}(Type) method."); } /// @@ -71,7 +69,7 @@ public void TestHasSetSuperDotDescriptor() public void TestGetParameterNames() { var paramNames = Descriptor.ParameterNames; - if (paramNames == null) paramNames = new string[0]; + if (paramNames == null) paramNames = Array.Empty(); foreach (var paramName in paramNames) { Assert.IsNotNull("A parameter name must not be null.", paramName); @@ -89,7 +87,7 @@ public void TestGetParameters() Assert.AreEqual(0, Descriptor.ParameterNames == null ? 0 : Descriptor.ParameterNames.Count, "For all parameters a default or actual value must be returned."); - parameters = new object[0]; + parameters = Array.Empty(); } foreach (var param in parameters) { @@ -99,23 +97,24 @@ public void TestGetParameters() // @cdk.bug 1862137 [TestMethod()] - public void TestGetParameterType_String() + public void TestGetParameterTypeString() { var paramNames = Descriptor.ParameterNames; - if (paramNames == null) paramNames = new string[0]; + if (paramNames == null) + paramNames = Array.Empty(); + var parameters = Descriptor.Parameters; - if (parameters == null) parameters = new object[0]; + if (parameters == null) + parameters = Array.Empty(); for (int i = 0; i < paramNames.Count; i++) { object type = Descriptor.GetParameterType(paramNames[i]); Assert.IsNotNull(type, - "The GetParameterType(string) return type is null for the " + "parameter: " - + paramNames[i]); + $"The GetParameterType(string) return type is null for the parameter: {paramNames[i]}"); Assert.AreEqual( type.GetType().FullName, parameters[i].GetType().FullName, - "The GetParameterType(string) return type is not consistent " - + "with the Parameters types for parameter " + i); + $"The GetParameterType(string) return type is not consistent with the Parameters types for parameter {i}"); } } @@ -124,13 +123,13 @@ public void TestParameterConsistency() { var paramNames = Descriptor.ParameterNames; // FIXME: see TestGetParameterNames() comment on the same line - if (paramNames == null) paramNames = new string[0]; + if (paramNames == null) paramNames = Array.Empty(); var parameters = Descriptor.Parameters; // FIXME: see TestGetParameters() comment on the same line - if (parameters == null) parameters = new object[0]; + if (parameters == null) parameters = Array.Empty(); Assert.AreEqual( - paramNames.Count, parameters.Length, + paramNames.Count, parameters.Count, "The number of returned parameter names must equate the number of returned parameters"); } @@ -159,16 +158,16 @@ public void TestGetSpecification() /// but one based on a repository blob or commit. /// [TestMethod()] - public void TestGetSpecification_IdentifierNonDefault() + public void TestGetSpecificationIdentifierNonDefault() { IImplementationSpecification spec = Descriptor.Specification; Assert.AreNotSame("$Id$", spec.ImplementationIdentifier); } [TestMethod()] - public void TestSetParameters_arrayObject() + public void TestSetParametersArrayObject() { - Object[] defaultParams = Descriptor.Parameters; + var defaultParams = Descriptor.Parameters; Descriptor.Parameters = defaultParams; } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs index 15d074f9..09bf890e 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -36,7 +36,7 @@ public class ALOGPDescriptorTest : MolecularDescriptorTest public ALOGPDescriptorTest() { SetDescriptor(typeof(ALOGPDescriptor)); - hydrogenAdder = CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance); + hydrogenAdder = CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance); } /// @@ -46,11 +46,11 @@ public ALOGPDescriptorTest() [TestMethod()] public void TestChloroButane() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom cl = Default.ChemObjectBuilder.Instance.NewAtom("Cl"); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom cl = ChemObjectBuilder.Instance.NewAtom("Cl"); mol.Atoms.Add(c1); mol.Atoms.Add(c2); mol.Atoms.Add(c3); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/APolDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/APolDescriptorTest.cs index 2367aa7e..2c0902a2 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/APolDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/APolDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -37,7 +38,7 @@ public APolDescriptorTest() [TestMethod()] public void TestAPolDescriptorTest() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)CC"); AddExplicitHydrogens(mol); Assert.AreEqual(10.88, ((Result)Descriptor.Calculate(mol).Value).Value, 0.01); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptorTest.cs index 23299afc..90721400 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; @@ -40,7 +41,7 @@ public void TestAromaticAtomsCountDescriptor() { object[] parameters = new object[] { true }; Descriptor.Parameters = parameters; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOc1ccccc1"); // ethanol Assert.AreEqual(6, ((Result)Descriptor.Calculate(mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptorTest.cs index ab6c3287..ad2d87cf 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; @@ -40,7 +41,7 @@ public void TestAromaticBondsCountDescriptor() { object[] parameters = new object[] { true }; Descriptor.Parameters = parameters; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCOc1ccccc1"); // ethanol Assert.AreEqual(6, ((Result)Descriptor.Calculate(mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/AtomCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/AtomCountDescriptorTest.cs index 49567395..70cdb46b 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/AtomCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/AtomCountDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -39,7 +40,7 @@ public void TestCarbonCount() { object[] parameters = new object[] { "C" }; Descriptor.Parameters = parameters; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCO"); // ethanol var value = Descriptor.Calculate(mol); Assert.AreEqual(2, ((Result)value.Value).Value); @@ -53,7 +54,7 @@ public void TestImplicitExplicitH() { object[] parameters = new object[] { "*" }; Descriptor.Parameters = parameters; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C"); // ethanol var value = Descriptor.Calculate(mol); Assert.AreEqual(5, ((Result)value.Value).Value); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorChargeTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorChargeTest.cs index c4a4d329..7f0ea472 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorChargeTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorChargeTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMassTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMassTest.cs index 26500fd7..9e046d8d 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMassTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorMassTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizabilityTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizabilityTest.cs index fb71b406..65644de7 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizabilityTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/AutocorrelationDescriptorPolarizabilityTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/BCUTDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/BCUTDescriptorTest.cs index 40cff3ec..9b36a5e1 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/BCUTDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/BCUTDescriptorTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -123,7 +123,7 @@ public void TestAromaticity() string smiles1 = "c1ccccc1"; string smiles2 = "C1=CC=CC=C1"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol1 = sp.ParseSmiles(smiles1); IAtomContainer mol2 = sp.ParseSmiles(smiles2); @@ -148,7 +148,7 @@ public void TestAromaticity() [TestMethod()] public void TestHAddition() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=1C=CC(=CC1)CNC2=CC=C(C=C2N(=O)=O)S(=O)(=O)C(Cl)(Cl)Br"); ArrayResult result1 = (ArrayResult)Descriptor.Calculate(mol).Value; for (int i = 0; i < result1.Length; i++) diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/BPolDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/BPolDescriptorTest.cs index d4d14a3e..29e04a92 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/BPolDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/BPolDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -37,7 +38,7 @@ public BPolDescriptorTest() [TestMethod()] public void TestBPolDescriptor() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)CC"); AddExplicitHydrogens(mol); Assert.AreEqual(7.517242, ((Result)Descriptor.Calculate(mol).Value).Value, 0.01); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptorTest.cs index 0b88da87..495f9022 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Smiles; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/CPSADescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/CPSADescriptorTest.cs index bf35d1b1..a032ed6b 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/CPSADescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/CPSADescriptorTest.cs @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/CarbonTypesDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/CarbonTypesDescriptorTest.cs index 4f7c98d3..2ab3b00a 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/CarbonTypesDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/CarbonTypesDescriptorTest.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -19,7 +20,7 @@ public CarbonTypesDescriptorTest() [TestMethod()] public void TestButane() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; @@ -38,7 +39,7 @@ public void TestButane() [TestMethod()] public void TestComplex1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(C)(C)C=C(C)C"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; @@ -57,7 +58,7 @@ public void TestComplex1() [TestMethod()] public void TestComplex2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C#CC(C)=C"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ChiChainDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ChiChainDescriptorTest.cs index c8241230..3f02383e 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ChiChainDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ChiChainDescriptorTest.cs @@ -1,7 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Numerics; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using System; @@ -12,13 +12,16 @@ namespace NCDK.QSAR.Descriptors.Moleculars /// // @cdk.module test-qsarmolecular [TestClass()] - public class ChiChainDescriptorTest : MolecularDescriptorTest { - public ChiChainDescriptorTest() { + public class ChiChainDescriptorTest : MolecularDescriptorTest + { + public ChiChainDescriptorTest() + { SetDescriptor(typeof(ChiChainDescriptor)); } [TestMethod()] - public void TestDan64() { + public void TestDan64() + { IAtomContainer mol = new AtomContainer(); IAtom a1 = mol.Builder.NewAtom("C"); a1.Point2D = new Vector2(0.7500000000000004, 2.799038105676658); @@ -54,7 +57,8 @@ public void TestDan64() { } [TestMethod()] - public void TestDan80() { + public void TestDan80() + { IAtomContainer mol = new AtomContainer(); IAtom a1 = mol.Builder.NewAtom("C"); a1.Point2D = new Vector2(0.0, 1.5); @@ -92,11 +96,11 @@ public void TestDan80() { Assert.AreEqual(0.0000, ret[6], 0.0001); Assert.AreEqual(0.04536, ret[7], 0.00001); Assert.AreEqual(0.0000, ret[8], 0.0001); - } [TestMethod()] - public void TestDan81() { + public void TestDan81() + { IAtomContainer mol = new AtomContainer(); IAtom a1 = mol.Builder.NewAtom("C"); a1.Point2D = new Vector2(0.0, 1.5); @@ -137,8 +141,8 @@ public void TestDan81() { } [TestMethod()] - public void TestDan82() { - + public void TestDan82() + { IAtomContainer mol = new AtomContainer(); IAtom a1 = mol.Builder.NewAtom("C"); a1.Point2D = new Vector2(0.0, 1.5); @@ -179,8 +183,8 @@ public void TestDan82() { } [TestMethod()] - public void TestDan154() { - + public void TestDan154() + { IAtomContainer mol = new AtomContainer(); IAtom a1 = mol.Builder.NewAtom("C"); a1.Point2D = new Vector2(0.0, 1.5); @@ -237,8 +241,9 @@ public void TestDan154() { // @cdk.bug 3023326 [TestMethod()] - public void TestCovalentMetal() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + public void TestCovalentMetal() + { + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC[Sn](CCCC)(CCCC)c1cc(Cl)c(Nc2nc(C)nc(N(CCC)CC3CC3)c2Cl)c(Cl)c1"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; Assert.IsNotNull(ret); @@ -246,29 +251,15 @@ public void TestCovalentMetal() { // @cdk.bug 3023326 [TestMethod()] - [ExpectedException(typeof(NullReferenceException))] public void TestCovalentPlatinum() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC1CN[Pt]2(N1)OC(=O)C(C)P(=O)(O)O2"); var dummy = Descriptor.Calculate(mol).Value; + if (dummy is ArrayResult result) + Assert.IsTrue(double.IsNaN(result[0])); + else + Assert.Fail(); } - - // [TestMethod()] public void TestDan277() { - // - // IAtomContainer mol = null; - // - // ChiChainDescriptor desc = new ChiChainDescriptor(); - // ArrayResult ret = (ArrayResult) desc.Calculate(mol).GetValue(); - // - // Assert.AreEqual(0.0000, ret[0], 0.0001); - // Assert.AreEqual(0.0000, ret[1], 0.0001); - // Assert.AreEqual(0.0000, ret[2], 0.0001); - // Assert.AreEqual(0.08333, ret[3], 0.00001); - // Assert.AreEqual(0.0000, ret[4], 0.0001); - // Assert.AreEqual(0.0000, ret[5], 0.0001); - // Assert.AreEqual(0.0000, ret[6], 0.0001); - // Assert.AreEqual(0.02778, ret[7], 0.00001); - // } } } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ChiClusterDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ChiClusterDescriptorTest.cs index 3ba643f6..de572fcb 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ChiClusterDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ChiClusterDescriptorTest.cs @@ -1,6 +1,6 @@ using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Smiles; using System; @@ -184,7 +184,7 @@ public void TestDan248() [TestMethod()] public void TestCovalentMetal() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC[Sn](CCCC)(CCCC)c1cc(Cl)c(Nc2nc(C)nc(N(CCC)CC3CC3)c2Cl)c(Cl)c1"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; Assert.IsNotNull(ret); @@ -192,12 +192,15 @@ public void TestCovalentMetal() // @cdk.bug 3023326 [TestMethod()] - [ExpectedException(typeof(NullReferenceException))] public void TestCovalentPlatinum() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC1CN[Pt]2(N1)OC(=O)C(C)P(=O)(O)O2"); var dummy = Descriptor.Calculate(mol).Value; + if (dummy is ArrayResult result) + Assert.IsTrue(double.IsNaN(result[0])); + else + Assert.Fail(); } // [TestMethod()] public void TestDan277() { diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ChiIndexUtilsTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ChiIndexUtilsTest.cs index 0555fd7e..0c99d990 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ChiIndexUtilsTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ChiIndexUtilsTest.cs @@ -16,7 +16,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -24,11 +26,11 @@ namespace NCDK.QSAR.Descriptors.Moleculars [TestClass()] public class ChiIndexUtilsTest : CDKTestCase { - Default.ChemObjectBuilder builder; + ChemObjectBuilder builder; public ChiIndexUtilsTest() { - builder = (Default.ChemObjectBuilder)Default.ChemObjectBuilder.Instance; + builder = (ChemObjectBuilder)ChemObjectBuilder.Instance; } [TestMethod()] diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptorTest.cs index 3d3770e6..95f062dd 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptorTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -179,7 +179,7 @@ public void TestDan248() [TestMethod()] public void TestCovalentMetal() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC[Sn](CCCC)(CCCC)c1cc(Cl)c(Nc2nc(C)nc(N(CCC)CC3CC3)c2Cl)c(Cl)c1"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; Assert.IsNotNull(ret); @@ -187,12 +187,15 @@ public void TestCovalentMetal() // @cdk.bug 3023326 [TestMethod()] - [ExpectedException(typeof(NullReferenceException))] public void TestCovalentPlatinum() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC1CN[Pt]2(N1)OC(=O)C(C)P(=O)(O)O2"); var dummy = Descriptor.Calculate(mol).Value; + if (dummy is ArrayResult result) + Assert.IsTrue(double.IsNaN(result[0])); + else + Assert.Fail(); } } } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathDescriptorTest.cs index 84e33a03..29b7ad59 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ChiPathDescriptorTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -250,7 +250,7 @@ public void TestDan154() [TestMethod()] public void TestCovalentMetal() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC[Sn](CCCC)(CCCC)c1cc(Cl)c(Nc2nc(C)nc(N(CCC)CC3CC3)c2Cl)c(Cl)c1"); ArrayResult ret = (ArrayResult)Descriptor.Calculate(mol).Value; Assert.IsNotNull(ret); @@ -258,12 +258,16 @@ public void TestCovalentMetal() // @cdk.bug 3023326 [TestMethod()] - [ExpectedException(typeof(NullReferenceException))] public void TestCovalentPlatinum() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC1CN[Pt]2(N1)OC(=O)C(C)P(=O)(O)O2"); var dummy = Descriptor.Calculate(mol).Value; + if (dummy is ArrayResult result) + Assert.IsTrue(double.IsNaN(result[0])); + else + Assert.Fail(); + } // [TestMethod()] public void TestDan277() { diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptorTest.cs index d4fb57db..60349586 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptorTest.cs @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/FMFDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/FMFDescriptorTest.cs index a7294b60..1bd975ed 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/FMFDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/FMFDescriptorTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -36,7 +37,7 @@ public FMFDescriptorTest() [TestMethod()] public void TestClenbuterol() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Clc1cc(cc(Cl)c1N)C(O)CNC(C)(C)C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); @@ -47,7 +48,7 @@ public void TestClenbuterol() [TestMethod()] public void TestCarbinoxamine() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CN(C)CCOC(C1=CC=C(Cl)C=C1)C1=CC=CC=N1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); @@ -58,7 +59,7 @@ public void TestCarbinoxamine() [TestMethod()] public void TestIsamoltane() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(C)NCC(O)COC1=C(C=CC=C1)N1C=CC=C1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); @@ -69,7 +70,7 @@ public void TestIsamoltane() [TestMethod()] public void TestPirenperone() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Fc1ccc(cc1)C(=O)C4CCN(CCC\\3=C(\\N=C2\\C=C/C=C\\N2C/3=O)C)CC4"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/FractionalPSADescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/FractionalPSADescriptorTest.cs index cc039790..db9454c3 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/FractionalPSADescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/FractionalPSADescriptorTest.cs @@ -27,7 +27,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptorTest.cs index c404ee18..1e3f242e 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptorTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Fragments; using NCDK.IO; using NCDK.QSAR.Results; @@ -48,7 +48,7 @@ public void Test2FragmentComplexityDescriptor() MurckoFragmenter gf = new MurckoFragmenter(); double Complexity = 0; MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); - IAtomContainer mol = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); gf.GenerateFragments(mol); var setOfFragments = gf.GetFrameworksAsContainers(); foreach (var setOfFragment in setOfFragments) diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptorTest.cs index 73888ba9..3645dac6 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptorTest.cs @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptorTest.cs index e19e1bd3..351c6270 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptorTest.cs @@ -20,6 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; using NCDK.Smiles; +using NCDK.Silent; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -39,7 +40,7 @@ public HBondAcceptorCountDescriptorTest() public void TestHBondAcceptorCountDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // original molecule O=N(=O)c1cccc2cn[nH]c12 - correct kekulisation will give // the same result. this test though should depend on kekulisation working IAtomContainer mol = sp.ParseSmiles("O=N(=O)C1=C2NN=CC2=CC=C1"); @@ -51,7 +52,7 @@ public void TestHBondAcceptorCountDescriptor() [TestMethod()] public void TestCID9257() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("N"); a1.FormalCharge = 0; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptorTest.cs index 80eb1ec7..334844b2 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptorTest.cs @@ -20,6 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; using NCDK.Smiles; +using NCDK.Silent; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -36,7 +37,7 @@ public HBondDonorCountDescriptorTest() public void TestHBondDonorCountDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Oc1ccccc1"); // Assert.AreEqual(1, ((Result)Descriptor.Calculate(mol).Value).Value); } @@ -46,7 +47,7 @@ public void TestHBondDonorCountDescriptor() [TestMethod()] public void TestCID9257() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("N"); a1.FormalCharge = 0; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptorTest.cs index f8463958..0918dcc5 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptorTest.cs @@ -19,6 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -38,7 +39,7 @@ public HybridizationRatioDescriptorTest() [TestMethod()] public void TestHybRatioDescriptor1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCC"); Assert.AreEqual(1.0, ((Result)Descriptor.Calculate(mol).Value).Value, 0.1); } @@ -46,7 +47,7 @@ public void TestHybRatioDescriptor1() [TestMethod()] public void TestHybRatioDescriptor2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1ccccc1"); Assert.AreEqual(0.0, ((Result)Descriptor.Calculate(mol).Value).Value, 0.1); } @@ -54,7 +55,7 @@ public void TestHybRatioDescriptor2() [TestMethod()] public void TestHybRatioDescriptor3() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]C#N"); Assert.AreEqual(double.NaN, ((Result)Descriptor.Calculate(mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptorTest.cs index 0993aab6..e58591f5 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptorTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -40,7 +41,7 @@ public KappaShapeIndicesDescriptorTest() public void TestKappaShapeIndicesDescriptor() { double[] testResult = { 5, 2.25, 4 }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)CC"); AtomContainerManipulator.RemoveHydrogens(mol); ArrayResult retval = (ArrayResult)Descriptor.Calculate(mol).Value; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptorTest.cs index 3cd78b2a..67075b28 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptorTest.cs @@ -16,9 +16,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; using System.Collections.Generic; @@ -52,7 +54,7 @@ private int GetIndex(string name) [TestMethod()] public void Test1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCO"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); @@ -68,7 +70,7 @@ public void Test1() [TestMethod()] public void Test2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1c(CN)cc(CCNC)cc1C(CO)CC(=O)CCOCCCO"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); @@ -88,7 +90,7 @@ public void Test2() [TestMethod()] public void Test3() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C#CC(C)(C)C(C)(C)C#C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/LargestChainDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/LargestChainDescriptorTest.cs index 1800f88b..75de79ba 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/LargestChainDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/LargestChainDescriptorTest.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -21,7 +22,7 @@ public LargestChainDescriptorTest() public void Test1LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1ccccc1"); // benzol //Debug.WriteLine("test1>:"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(0, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -31,7 +32,7 @@ public void Test1LargestChainDescriptor() public void Test2LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CC=Cc1ccccc1"); //Debug.WriteLine("test2>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(4, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -41,7 +42,7 @@ public void Test2LargestChainDescriptor() public void Test3LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CC=CCc2ccc(Cc1ccncc1C=C)cc2"); //Debug.WriteLine("test3>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(5, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -51,7 +52,7 @@ public void Test3LargestChainDescriptor() public void Test4LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC=CNCC"); //Debug.WriteLine("test4>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(6, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -61,7 +62,7 @@ public void Test4LargestChainDescriptor() public void Test5LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=C[NH2+]CC"); //Debug.WriteLine("test5>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(5, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -71,7 +72,7 @@ public void Test5LargestChainDescriptor() public void Test6LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCNOC"); //Debug.WriteLine("test6>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(5, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -81,7 +82,7 @@ public void Test6LargestChainDescriptor() public void Test7LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC=CC(C)=O"); //Debug.WriteLine("test7>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(5, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -91,7 +92,7 @@ public void Test7LargestChainDescriptor() public void TestSingleCAtom() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C"); //Debug.WriteLine("test7>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(0, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -101,7 +102,7 @@ public void TestSingleCAtom() public void TestSingleOAtom() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O"); //Debug.WriteLine("test7>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(0, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -111,7 +112,7 @@ public void TestSingleOAtom() public void Test8LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Cc1nn(c(c1)N)c1nc2c(s1)cccc2"); Assert.AreEqual(0, ((Result)Descriptor.Calculate(mol).Value).Value); } @@ -120,7 +121,7 @@ public void Test8LargestChainDescriptor() public void Test9LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Nc1c(cn[nH]1)C#N"); Assert.AreEqual(2, ((Result)Descriptor.Calculate(mol).Value).Value); } @@ -129,7 +130,7 @@ public void Test9LargestChainDescriptor() public void Test10LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("OCc1ccccc1CN"); Assert.AreEqual(2, ((Result)Descriptor.Calculate(mol).Value).Value); } @@ -138,7 +139,7 @@ public void Test10LargestChainDescriptor() public void Test11LargestChainDescriptor() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("COc1ccc(cc1)c1noc(c1)Cn1nc(C)c(c(c1=O)C#N)C"); Assert.AreEqual(2, ((Result)Descriptor.Calculate(mol).Value).Value); } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptorTest.cs index 08bc7046..dd032dd4 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptorTest.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using System; @@ -22,7 +23,7 @@ public LargestPiSystemDescriptorTest() public void Test1LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1ccccc1"); // benzol Assert.AreEqual(6, ((Result)Descriptor.Calculate(mol).Value).Value); } @@ -31,7 +32,7 @@ public void Test1LargestPiSystemDescriptor() public void Test2LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CC=Cc1ccccc1"); Assert.AreEqual(10, ((Result)Descriptor.Calculate(mol).Value).Value); //Debug.WriteLine("test2>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); @@ -41,7 +42,7 @@ public void Test2LargestPiSystemDescriptor() public void Test3LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CC=CCc2ccc(Cc1ccncc1C=C)cc2"); //Debug.WriteLine("test3>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(8, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -51,7 +52,7 @@ public void Test3LargestPiSystemDescriptor() public void Test4LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC=CNCC"); //Debug.WriteLine("test4>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(3, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -61,7 +62,7 @@ public void Test4LargestPiSystemDescriptor() public void Test5LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=C[NH2+]CC"); //Debug.WriteLine("test5>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(3, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -71,7 +72,7 @@ public void Test5LargestPiSystemDescriptor() public void Test6LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCNOC"); //Debug.WriteLine("test6>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(2, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -81,7 +82,7 @@ public void Test6LargestPiSystemDescriptor() public void Test7LargestPiSystemDescriptor() { Descriptor.Parameters = new object[] { false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC=CC(C)=O"); //Debug.WriteLine("test7>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(4, ((Result)Descriptor.Calculate(mol).Value).Value); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptorTest.cs index 22699d81..47d23f0c 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptorTest.cs @@ -1,6 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; @@ -29,7 +29,7 @@ public void TestLOBDescriptorCholesterol() ChemFile content = (ChemFile)reader.Read(new ChemFile()); var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); IAtomContainer ac = (IAtomContainer)cList[0]; - Isotopes.Instance.ConfigureAtoms(ac); + BODRIsotopeFactory.Instance.ConfigureAtoms(ac); ArrayResult result = (ArrayResult)Descriptor.Calculate(ac).Value; @@ -46,7 +46,7 @@ public void TestLOBDescriptorCyclohexane() ChemFile content = (ChemFile)reader.Read(new ChemFile()); var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); IAtomContainer ac = (IAtomContainer)cList[1]; - Isotopes.Instance.ConfigureAtoms(ac); + BODRIsotopeFactory.Instance.ConfigureAtoms(ac); ArrayResult result = (ArrayResult)Descriptor.Calculate(ac).Value; @@ -64,7 +64,7 @@ public void TestLOBDescriptorNaphthalene() var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); IAtomContainer ac = (IAtomContainer)cList[2]; - Isotopes.Instance.ConfigureAtoms(ac); + BODRIsotopeFactory.Instance.ConfigureAtoms(ac); ArrayResult result = (ArrayResult)Descriptor.Calculate(ac).Value; @@ -81,7 +81,7 @@ public void TestLOBDescriptorNButane() ChemFile content = (ChemFile)reader.Read(new ChemFile()); var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); IAtomContainer ac = (IAtomContainer)cList[3]; - Isotopes.Instance.ConfigureAtoms(ac); + BODRIsotopeFactory.Instance.ConfigureAtoms(ac); ArrayResult result = (ArrayResult)Descriptor.Calculate(ac).Value; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptorTest.cs index b6160197..f2bd919c 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptorTest.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -21,7 +22,7 @@ public LongestAliphaticChainDescriptorTest() public void Test1LongestAliphaticChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCCc1ccccc1"); // benzol //Debug.WriteLine("test1>:"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(4, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -31,7 +32,7 @@ public void Test1LongestAliphaticChainDescriptor() public void Test2LargestChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=CC=Cc1ccccc1"); //Debug.WriteLine("test2>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(4, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -41,7 +42,7 @@ public void Test2LargestChainDescriptor() public void Test3LargestChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C=C(CCC1CC1C(C)C(C)C)C(C)CC2CCCC2"); //Debug.WriteLine("test3>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(5, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -51,7 +52,7 @@ public void Test3LargestChainDescriptor() public void Test4LargestChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCCNCC"); //Debug.WriteLine("test4>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(4, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -61,7 +62,7 @@ public void Test4LargestChainDescriptor() public void Test5LargestChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(C)(C)c1ccccc1"); //Debug.WriteLine("test5>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(3, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -71,7 +72,7 @@ public void Test5LargestChainDescriptor() public void Test6LargestChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(C)(C)c2ccc(OCCCC(=O)Nc1nccs1)cc2"); //Debug.WriteLine("test6>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(4, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -81,7 +82,7 @@ public void Test6LargestChainDescriptor() public void Test7LargestChainDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(=O)N1CCN(CC1)c2ccc(NC(=O)COc3ccc(cc3)C(C)(C)C)cc2"); //Debug.WriteLine("test7>"+((Result)Descriptor.Calculate(mol).GetValue()).Value); Assert.AreEqual(3, ((Result)Descriptor.Calculate(mol).Value).Value); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/MDEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/MDEDescriptorTest.cs index 1dbfeebc..17db92bb 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/MDEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/MDEDescriptorTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/MolecularDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/MolecularDescriptorTest.cs index 01de2ea6..666f3e17 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/MolecularDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/MolecularDescriptorTest.cs @@ -19,10 +19,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; -using NCDK.Default; using NCDK.Dict; using NCDK.Numerics; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Templates; using NCDK.Tools.Diff; using NCDK.Tools.Manipulator; @@ -40,66 +40,88 @@ public abstract class MolecularDescriptorTest : DescriptorTest @@ -183,7 +205,7 @@ public void TestCalculate_NoModifications() [TestMethod()] public void TestLabels() { - IAtomContainer mol = SomeoneBringMeSomeWater(Default.ChemObjectBuilder.Instance); + var mol = SomeoneBringMeSomeWater(ChemObjectBuilder.Instance); var v = Descriptor.Calculate(mol); Assert.IsNotNull(v); @@ -197,7 +219,7 @@ public void TestLabels() // Console.Out.WriteLine("Label: " + names[i]); } Assert.IsNotNull(v.Value); - int valueCount = v.Value.Length; + var valueCount = v.Value.Length; Assert.AreEqual(names.Count, valueCount, "The number of labels must equals the number of values."); } @@ -210,7 +232,7 @@ public void TestLabels() [TestMethod()] public void TestNamesConsistency() { - IAtomContainer mol = SomeoneBringMeSomeWater(Default.ChemObjectBuilder.Instance); + var mol = SomeoneBringMeSomeWater(ChemObjectBuilder.Instance); var names1 = Descriptor.DescriptorNames; var v = Descriptor.Calculate(mol); @@ -219,17 +241,17 @@ public void TestNamesConsistency() Assert.AreEqual(names1.Count, names2.Count); Assert.IsTrue(Compares.AreDeepEqual(names1, names2)); - int valueCount = v.Value.Length; + var valueCount = v.Value.Length; Assert.AreEqual(valueCount, names1.Count); } [TestMethod()] public void TestGetDescriptorResultType() { - IDescriptorResult result = Descriptor.DescriptorResultType; + var result = Descriptor.DescriptorResultType; Assert.IsNotNull(result, "The DescriptorResultType must not be null."); - IAtomContainer mol = SomeoneBringMeSomeWater(Default.ChemObjectBuilder.Instance); + var mol = SomeoneBringMeSomeWater(ChemObjectBuilder.Instance); var v = Descriptor.Calculate(mol); Assert.IsTrue( @@ -242,22 +264,22 @@ public void TestGetDescriptorResultType() [TestMethod()] public void TestTakeIntoAccountImplicitHydrogens() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; - IAtomContainer methane1 = builder.NewAtomContainer(); - IAtom c1 = builder.NewAtom("C"); + var builder = ChemObjectBuilder.Instance; + var methane1 = builder.NewAtomContainer(); + var c1 = builder.NewAtom("C"); c1.ImplicitHydrogenCount = 4; methane1.Atoms.Add(c1); - IAtomContainer methane2 = builder.NewAtomContainer(); - IAtom c2 = builder.NewAtom("C"); + var methane2 = builder.NewAtomContainer(); + var c2 = builder.NewAtom("C"); methane2.Atoms.Add(c2); - IAtom h1 = builder.NewAtom("H"); + var h1 = builder.NewAtom("H"); methane2.Atoms.Add(h1); - IAtom h2 = builder.NewAtom("H"); + var h2 = builder.NewAtom("H"); methane2.Atoms.Add(h2); - IAtom h3 = builder.NewAtom("H"); + var h3 = builder.NewAtom("H"); methane2.Atoms.Add(h3); - IAtom h4 = builder.NewAtom("H"); + var h4 = builder.NewAtom("H"); methane2.Atoms.Add(h4); methane2.AddBond(methane2.Atoms[0], methane2.Atoms[1], BondOrder.Single); methane2.AddBond(methane2.Atoms[0], methane2.Atoms[2], BondOrder.Single); @@ -269,8 +291,8 @@ public void TestTakeIntoAccountImplicitHydrogens() AddImplicitHydrogens(methane1); AddImplicitHydrogens(methane2); - IDescriptorResult v1 = Descriptor.Calculate(methane1).Value; - IDescriptorResult v2 = Descriptor.Calculate(methane2).Value; + var v1 = Descriptor.Calculate(methane1).Value; + var v2 = Descriptor.Calculate(methane2).Value; string errorMessage = "(" + Descriptor.GetType().ToString() @@ -281,32 +303,32 @@ public void TestTakeIntoAccountImplicitHydrogens() [TestMethod()] public void TestTakeIntoAccountImplicitHydrogensInEthane() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; - IAtomContainer ethane1 = builder.NewAtomContainer(); - IAtom c1 = builder.NewAtom("C"); - IAtom c2 = builder.NewAtom("C"); + var builder = ChemObjectBuilder.Instance; + var ethane1 = builder.NewAtomContainer(); + var c1 = builder.NewAtom("C"); + var c2 = builder.NewAtom("C"); c1.ImplicitHydrogenCount = 3; c2.ImplicitHydrogenCount = 3; ethane1.Atoms.Add(c1); ethane1.Atoms.Add(c2); ethane1.AddBond(ethane1.Atoms[0], ethane1.Atoms[1], BondOrder.Single); - IAtomContainer ethane2 = builder.NewAtomContainer(); - IAtom c3 = builder.NewAtom("C"); - IAtom c4 = builder.NewAtom("C"); + var ethane2 = builder.NewAtomContainer(); + var c3 = builder.NewAtom("C"); + var c4 = builder.NewAtom("C"); ethane2.Atoms.Add(c3); ethane2.Atoms.Add(c4); - IAtom h1 = builder.NewAtom("H"); + var h1 = builder.NewAtom("H"); ethane2.Atoms.Add(h1); - IAtom h2 = builder.NewAtom("H"); + var h2 = builder.NewAtom("H"); ethane2.Atoms.Add(h2); - IAtom h3 = builder.NewAtom("H"); + var h3 = builder.NewAtom("H"); ethane2.Atoms.Add(h3); - IAtom h4 = builder.NewAtom("H"); - IAtom h5 = builder.NewAtom("H"); - IAtom h6 = builder.NewAtom("H"); + var h4 = builder.NewAtom("H"); + var h5 = builder.NewAtom("H"); + var h6 = builder.NewAtom("H"); ethane2.Atoms.Add(h4); ethane2.Atoms.Add(h5); ethane2.Atoms.Add(h6); @@ -325,22 +347,22 @@ public void TestTakeIntoAccountImplicitHydrogensInEthane() AddImplicitHydrogens(ethane1); AddImplicitHydrogens(ethane2); - IDescriptorResult v1 = Descriptor.Calculate(ethane1).Value; - IDescriptorResult v2 = Descriptor.Calculate(ethane2).Value; + var v1 = Descriptor.Calculate(ethane1).Value; + var v2 = Descriptor.Calculate(ethane2).Value; string errorMessage = "(" + Descriptor.GetType().ToString() + ") The descriptor does not give the same results depending on whether hydrogens are implicit or explicit."; AssertEqualOutput(v1, v2, errorMessage); } - + /// /// Checks that the results of the first and the second descriptor results are identical. /// /// first /// second /// error message to report when the results are not the same - private void AssertEqualOutput(IDescriptorResult v1, IDescriptorResult v2, string errorMessage) + private static void AssertEqualOutput(IDescriptorResult v1, IDescriptorResult v2, string errorMessage) { if (v1 is Result) { @@ -369,8 +391,8 @@ private void AssertEqualOutput(IDescriptorResult v1, IDescriptorResult v2, strin } else if (v1 is ArrayResult) { - ArrayResult da1 = (ArrayResult)v1; - ArrayResult da2 = (ArrayResult)v2; + var da1 = (ArrayResult)v1; + var da2 = (ArrayResult)v2; for (int i = 0; i < da1.Length; i++) { Assert.AreEqual(da1[i], da2[i], errorMessage); @@ -381,32 +403,28 @@ private void AssertEqualOutput(IDescriptorResult v1, IDescriptorResult v2, strin [TestMethod()] public void TestImplementationIndependence() { - IAtomContainer water1 = SomeoneBringMeSomeWater(Default.ChemObjectBuilder.Instance); - IAtomContainer water2 = SomeoneBringMeSomeWater(Silent.ChemObjectBuilder.Instance); + var water1 = SomeoneBringMeSomeWater(ChemObjectBuilder.Instance); + var water2 = SomeoneBringMeSomeWater(Silent.ChemObjectBuilder.Instance); - IDescriptorResult v1 = Descriptor.Calculate(water1).Value; - IDescriptorResult v2 = Descriptor.Calculate(water2).Value; + var v1 = Descriptor.Calculate(water1).Value; + var v2 = Descriptor.Calculate(water2).Value; - string errorMessage = "(" + Descriptor.GetType().ToString() - + ") The descriptor does not give the same results depending on " - + "the actual IChemObject implementation set (data, nonotify)."; + string errorMessage = $"({Descriptor.GetType().ToString()}) The descriptor does not give the same results depending on the actual IChemObject implementation set (data, nonotify)."; AssertEqualOutput(v1, v2, errorMessage); } [TestMethod()] public void TestAtomContainerHandling() { - IAtomContainer water1 = SomeoneBringMeSomeWater(Default.ChemObjectBuilder.Instance); + var water1 = SomeoneBringMeSomeWater(ChemObjectBuilder.Instance); // creates an AtomContainer with the atoms / bonds from water1 - IAtomContainer water2 = Silent.ChemObjectBuilder.Instance.NewAtomContainer(); + var water2 = Silent.ChemObjectBuilder.Instance.NewAtomContainer(); water2.Add(water1); - IDescriptorResult v1 = Descriptor.Calculate(water1).Value; - IDescriptorResult v2 = Descriptor.Calculate(water2).Value; + var v1 = Descriptor.Calculate(water1).Value; + var v2 = Descriptor.Calculate(water2).Value; - string errorMessage = "(" + Descriptor.GetType().ToString() - + ") The descriptor does not give the same results depending on " - + "it being passed an IAtomContainer or an IAtomContainer."; + string errorMessage = $"({Descriptor.GetType().ToString()}) The descriptor does not give the same results depending on it being passed an IAtomContainer or an IAtomContainer."; AssertEqualOutput(v1, v2, errorMessage); } @@ -416,22 +434,16 @@ public void TestAtomContainerHandling() [TestMethod()] public void TestDisconnectedStructureHandling() { - IAtomContainer disconnected = Silent.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom chloride = new Atom("Cl") - { - FormalCharge = -1 - }; + var disconnected = Silent.ChemObjectBuilder.Instance.NewAtomContainer(); + var chloride = new Atom("Cl") { FormalCharge = -1 }; disconnected.Atoms.Add(chloride); - IAtom sodium = new Atom("Na") - { - FormalCharge = +1 - }; + var sodium = new Atom("Na") { FormalCharge = +1 }; disconnected.Atoms.Add(sodium); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(disconnected); AddImplicitHydrogens(disconnected); - IDescriptorResult v1 = Descriptor.Calculate(disconnected).Value; + var v1 = Descriptor.Calculate(disconnected).Value; } [TestMethod(), Ignore()] @@ -443,25 +455,25 @@ private static int TestMethod() public void TestTakeIntoAccountBondHybridization() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; - IAtomContainer ethane1 = builder.NewAtomContainer(); - IAtom c1 = builder.NewAtom("C"); - IAtom c2 = builder.NewAtom("C"); + var builder = ChemObjectBuilder.Instance; + var ethane1 = builder.NewAtomContainer(); + var c1 = builder.NewAtom("C"); + var c2 = builder.NewAtom("C"); ethane1.Atoms.Add(c1); ethane1.Atoms.Add(c2); ethane1.AddBond(ethane1.Atoms[0], ethane1.Atoms[1], BondOrder.Double); - IAtomContainer ethane2 = builder.NewAtomContainer(); - IAtom c3 = builder.NewAtom("C"); + var ethane2 = builder.NewAtomContainer(); + var c3 = builder.NewAtom("C"); c3.Hybridization = Hybridization.SP2; - IAtom c4 = builder.NewAtom("C"); + var c4 = builder.NewAtom("C"); c4.Hybridization = Hybridization.SP2; ethane2.Atoms.Add(c3); ethane2.Atoms.Add(c4); ethane2.AddBond(ethane2.Atoms[0], ethane2.Atoms[1], BondOrder.Single); - IDescriptorResult v1 = Descriptor.Calculate(ethane1).Value; - IDescriptorResult v2 = Descriptor.Calculate(ethane2).Value; + var v1 = Descriptor.Calculate(ethane1).Value; + var v2 = Descriptor.Calculate(ethane2).Value; string errorMessage = "(" + Descriptor.GetType().ToString() @@ -471,12 +483,12 @@ public void TestTakeIntoAccountBondHybridization() private IAtomContainer SomeoneBringMeSomeWater(IChemObjectBuilder builder) { - IAtomContainer mol = builder.NewAtomContainer(); - IAtom c1 = builder.NewAtom("O"); + var mol = builder.NewAtomContainer(); + var c1 = builder.NewAtom("O"); c1.Point3D = new Vector3(0.0, 0.0, 0.0); - IAtom h1 = builder.NewAtom("H"); + var h1 = builder.NewAtom("H"); h1.Point3D = new Vector3(1.0, 0.0, 0.0); - IAtom h2 = builder.NewAtom("H"); + var h2 = builder.NewAtom("H"); h2.Point3D = new Vector3(-1.0, 0.0, 0.0); mol.Atoms.Add(c1); mol.Atoms.Add(h1); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptorTest.cs index ff7d0784..a4221af2 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptorTest.cs @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -44,7 +44,7 @@ public MomentOfInertiaDescriptorTest() [TestMethod()] public void TestMOIFromSmiles() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC"); var value = Descriptor.Calculate(mol); Assert.IsNotNull(value.Exception, "The Exception should be non-null since we don't have 3D coords"); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptorTest.cs index 9ab5bcf5..a1fdd20e 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -38,7 +39,7 @@ public PetitjeanNumberDescriptorTest() [TestMethod()] public void TestPetitjeanNumberDescriptor() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)CC"); AtomContainerManipulator.RemoveHydrogens(mol); Assert.AreEqual(0.33333334, ((Result)Descriptor.Calculate(mol).Value).Value, 0.01); @@ -47,7 +48,7 @@ public void TestPetitjeanNumberDescriptor() [TestMethod()] public void TestSingleAtomCase() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O"); Assert.AreEqual(0, ((Result)Descriptor.Calculate(mol).Value).Value, 0.01); } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptorTest.cs index a9b71282..ba2dd0ba 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -65,7 +65,7 @@ public void TestPetitjeanShapeIndexDescriptor() [TestMethod()] public void TestPetiteJeanShapeNo3D() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCCOCCC(O)=O"); var result = Descriptor.Calculate(atomContainer); ArrayResult dar = (ArrayResult)result.Value; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptorTest.cs index 4a23a799..6a75abb6 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Smiles; using NCDK.Tools; @@ -42,7 +42,7 @@ public RotatableBondsCountDescriptorTest() public void TestRotatableBondsCount() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC2CCC(C1CCCCC1)CC2"); // molecule with 2 bridged cicloexane and 1 methyl Assert.AreEqual(2, ((Result)Descriptor.Calculate(mol).Value).Value); } @@ -170,7 +170,7 @@ public void TestButaneExplicitH() public void TestAmideIncluded() { string amide = "CCNC(=O)CC(C)C"; // N-ethyl-3-methylbutanamide - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles(amide); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); @@ -184,7 +184,7 @@ public void TestAmideIncluded() public void TestAmideExcluded() { string amide = "CCNC(=O)CC(C)C"; // N-ethyl-3-methylbutanamide - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles(amide); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptorTest.cs index dadd12c3..2cd10347 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -38,7 +39,7 @@ public RuleOfFiveDescriptorTest() public void TestRuleOfFiveDescriptor() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC(OCC)OCC(c1cccc2ccccc12)C4CCC(CCCO)C(CC3CNCNC3)C4"); // AddExplicitHydrogens(mol); Assert.AreEqual(2, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -48,7 +49,7 @@ public void TestRuleOfFiveDescriptor() public void TestRuleOfFiveRotatableBonds() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCC1=CC(NC(=O)CC)=CC(CCC)=C1"); // nRot = 10 (excl. amide C-N bond) AddExplicitHydrogens(mol); Assert.AreEqual(0, ((Result)Descriptor.Calculate(mol).Value).Value); @@ -58,7 +59,7 @@ public void TestRuleOfFiveRotatableBonds() public void TestRuleOfFiveRotatableBondsViolated() { Descriptor.Parameters = new object[] { true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCCC1=CC(CCC)=CC(NC(=O)CC)=C1"); // nRot = 11 (excl. amide C-N bond) AddExplicitHydrogens(mol); Assert.AreEqual(1, ((Result)Descriptor.Calculate(mol).Value).Value); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/SmallRingDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/SmallRingDescriptorTest.cs index e0c03db4..609e8f64 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/SmallRingDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/SmallRingDescriptorTest.cs @@ -28,13 +28,14 @@ using NCDK.Common.Primitives; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; +using System.Globalization; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -69,7 +70,7 @@ public void TestDescriptors() public void Nop() { } // run through the cases - private void Validate(Stream ins) + private static void Validate(Stream ins) { var content = new Dictionary(); using (var zip = new ZipArchive(ins)) @@ -94,8 +95,7 @@ private void Validate(Stream ins) string basefn = idx.ToString(); while (basefn.Length < 6) basefn = "0" + basefn; - byte[] molBytes; - if (!content.TryGetValue(basefn + ".mol", out molBytes)) + if (!content.TryGetValue(basefn + ".mol", out byte[] molBytes)) break; AtomContainer mol = new AtomContainer(); @@ -110,10 +110,10 @@ private void Validate(Stream ins) { bits = Strings.Tokenize(rdr.ReadLine(), ' '); } - int wantSmallRings = int.Parse(bits[0]); - int wantRingBlocks = int.Parse(bits[1]); - int wantAromRings = int.Parse(bits[2]); - int wantAromBlocks = int.Parse(bits[3]); + int wantSmallRings = int.Parse(bits[0], NumberFormatInfo.InvariantInfo); + int wantRingBlocks = int.Parse(bits[1], NumberFormatInfo.InvariantInfo); + int wantAromRings = int.Parse(bits[2], NumberFormatInfo.InvariantInfo); + int wantAromBlocks = int.Parse(bits[3], NumberFormatInfo.InvariantInfo); Trace.TraceInformation("FN=" + basefn + " MOL=" + mol.Atoms.Count + "," + mol.Bonds.Count + " nSmallRings=" + wantSmallRings + " nRingBlocks=" + wantRingBlocks + " nAromRings=" + wantAromRings diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/TPSADescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/TPSADescriptorTest.cs index 377beff6..fca508d2 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/TPSADescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/TPSADescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -33,7 +34,7 @@ public class TPSADescriptorTest : MolecularDescriptorTest public TPSADescriptorTest() { - sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + sp = new SmilesParser(ChemObjectBuilder.Instance); SetDescriptor(typeof(TPSADescriptor)); Descriptor.Parameters = new object[] { true }; } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/VAdjMaDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/VAdjMaDescriptorTest.cs index af8f5399..33f38d98 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/VAdjMaDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/VAdjMaDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -42,7 +43,7 @@ public void IgnoreCalculate_IAtomContainer() [TestMethod()] public void TestCyclic() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C1CCC2CCCCC2C1"); Assert.AreEqual(4.459, ((Result)Descriptor.Calculate(mol).Value).Value, 0.001); } @@ -50,7 +51,7 @@ public void TestCyclic() [TestMethod()] public void TestLinear() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCCCCCCCC"); Assert.AreEqual(4.17, ((Result)Descriptor.Calculate(mol).Value).Value, 0.001); } @@ -58,7 +59,7 @@ public void TestLinear() [TestMethod()] public void TestCompound() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCCCC1CCCCC1"); Assert.AreEqual(4.322, ((Result)Descriptor.Calculate(mol).Value).Value, 0.001); } diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/WeightDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/WeightDescriptorTest.cs index 6e74d71c..b1b5754b 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/WeightDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/WeightDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -38,7 +39,7 @@ public WeightDescriptorTest() public void TestWeightDescriptor() { Descriptor.Parameters = new object[] { "*" }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCC"); Assert.AreEqual(44.06, ((Result)Descriptor.Calculate(mol).Value).Value, 0.1); } @@ -48,7 +49,7 @@ public void TestWeightDescriptor() public void TestNoHydrogens() { Descriptor.Parameters = new object[] { "*" }; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); mol.Atoms.Add(builder.NewAtom("C")); Assert.AreEqual(12.00, ((Result)Descriptor.Calculate(mol).Value).Value, 0.1); @@ -59,7 +60,7 @@ public void TestNoHydrogens() public void TestExplicitHydrogens() { Descriptor.Parameters = new object[] { "*" }; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); mol.Atoms.Add(builder.NewAtom("C")); mol.Atoms.Add(builder.NewAtom("H")); @@ -78,7 +79,7 @@ public void TestExplicitHydrogens() public void TestImplicitHydrogens() { Descriptor.Parameters = new object[] { "*" }; - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); mol.Atoms.Add(builder.NewAtom("C")); mol.Atoms[0].ImplicitHydrogenCount = 4; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/WeightedPathDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/WeightedPathDescriptorTest.cs index df34ccf3..e86d0601 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/WeightedPathDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/WeightedPathDescriptorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -41,7 +41,7 @@ public WeightedPathDescriptorTest() [TestMethod()] public void TestWeightedPathDescriptor() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = null; IDescriptorValue value = null; ArrayResult result = null; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/WienerNumbersDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/WienerNumbersDescriptorTest.cs index 17335ec4..20a4bda1 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/WienerNumbersDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/WienerNumbersDescriptorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -36,7 +37,7 @@ public WienerNumbersDescriptorTest() public void TestWienerNumbersDescriptor() { double[] testResult = { 18, 2 }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]C([H])([H])C([H])([H])C(=O)O"); AtomContainerManipulator.RemoveHydrogens(mol); ArrayResult retval = (ArrayResult)Descriptor.Calculate(mol).Value; @@ -51,7 +52,7 @@ public void TestWienerNumbersDescriptor() public void TestWithExplicitHydrogens() { double[] testResult = { 18, 2 }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[H]C([H])([H])C([H])([H])C(=O)O"); ArrayResult retval = (ArrayResult)Descriptor.Calculate(mol).Value; Assert.AreEqual(testResult[0], retval[0], 0.0001); @@ -64,7 +65,7 @@ public void TestWithExplicitHydrogens() [TestMethod()] public void TestOriginalWienerPaperCompounds() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); double[] testResult = { 10, 20, 35, 56, 84, 120, 165, 220, 286 }; string smiles = "CCC"; for (int i = 0; i < testResult.Length; i++) diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/XLogPDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/XLogPDescriptorTest.cs index 48997596..9bb23471 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/XLogPDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/XLogPDescriptorTest.cs @@ -21,6 +21,7 @@ using NCDK.Aromaticities; using NCDK.Graphs; using NCDK.QSAR.Results; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.QSAR.Descriptors.Moleculars @@ -41,7 +42,7 @@ public XLogPDescriptorTest() public void Testno688() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)c1[nH0]cccc1"); // xlogp training set molecule no688 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -54,7 +55,7 @@ public void Testno1596() { // the xlogp program value is 0.44 because of paralleled donor pair correction factor Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Nc2ccc(S(=O)(=O)c1ccc(N)cc1)cc2"); // xlogp training set molecule no1596 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -66,7 +67,7 @@ public void Testno1596() public void Testno367() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)C(N)CCCN"); // xlogp training set molecule no367 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -78,7 +79,7 @@ public void Testno367() public void Testno1837() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=P(N1CC1)(N2CC2)N3CC3"); // xlogp training set molecule no1837 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -90,7 +91,7 @@ public void Testno1837() public void Testno87() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("c1cc2ccc3ccc4ccc5cccc6c(c1)c2c3c4c56"); // xlogp training set molecule no87 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -102,7 +103,7 @@ public void Testno87() public void Testno1782() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("S1C2N(C(=O)C2NC(=O)C(c2ccccc2)C(=O)O)C(C(=O)O)C1(C)C"); // xlogp training set molecule no30 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -114,7 +115,7 @@ public void Testno1782() public void Testno30() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C(#Cc1ccccc1)c1ccccc1"); // xlogp training set molecule no30 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -126,7 +127,7 @@ public void Testno30() public void Testno937() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("ClCC(O)C[nH0]1c([nH0]cc1[N+](=O)[O-])C"); // xlogp training set molecule no937 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -138,7 +139,7 @@ public void Testno937() public void Testno990() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("FC(F)(F)c1ccc(cc1)C(=O)N"); // xlogp training set molecule no990 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -150,7 +151,7 @@ public void Testno990() public void Testno1000() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Clc1cccc(c1)/C=C/[N+](=O)[O-]"); // xlogp training set molecule no1000 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -162,7 +163,7 @@ public void Testno1000() public void TestApirinBug1296383() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CC(=O)OC1=CC=CC=C1C(=O)O"); // aspirin AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -174,7 +175,7 @@ public void TestApirinBug1296383() public void Testno1429() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(OC)CNC(=O)c1ccc(N)cc1"); // xlogp training set molecule no1429 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -186,7 +187,7 @@ public void Testno1429() public void Testno1274() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=[N+]([O-])c1ccc(cc1)CC(N)C(=O)O"); // xlogp training set molecule no1274 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -201,7 +202,7 @@ public void Testno454() //if one takes a 5 or 7 ring than the program assignes amid ... strange //sometimes amid is O=C-N-C=O sometimes not... Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C1NC(=O)C=CN1C1OC(CO)C(O)C1O"); // xlogp training set molecule no454 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -214,7 +215,7 @@ public void Testno498() { //even here the amid assignment is very strange Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C1N(C)C=CC(=O)N1C"); // xlogp training set molecule no498 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -227,7 +228,7 @@ public void TestAprindine() { //even here the amid assignment is very strange Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("CCN(CC)CCCN(C2Cc1ccccc1C2)c3ccccc3"); // xlogp training set molecule Aprindine AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -239,7 +240,7 @@ public void TestAprindine() public void Test1844() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // SMILES is in octet-rule version, PubChem has normalized one IAtomContainer mol = sp.ParseSmiles("Brc1cc(Cl)c(O[P+]([S-])(OC)OC)cc1Cl"); // xlogp training set molecule 1844 AssertAtomTypesPerceived(mol); @@ -252,7 +253,7 @@ public void Test1844() public void Test1810() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Clc1ccc2Sc3ccccc3N(CCCN3CCN(C)CC3)c2c1"); // xlogp training set molecule 1810 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -267,7 +268,7 @@ public void Test1810() public void Test1822() { Descriptor.Parameters = new object[] { true, false }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[S+]([O-])(CCC1C(=O)N(N(c2ccccc2)C1=O)c1ccccc1)c1ccccc1"); // xlogp training set molecule 1822 AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -279,9 +280,9 @@ public void Test1822() public void TestAromaticBenzene() { Descriptor.Parameters = new object[] { false, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C1=CC=CC=C1"); // benzene - Aromaticity aromaticity = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + Aromaticity aromaticity = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); aromaticity.Apply(mol); AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -292,7 +293,7 @@ public void TestAromaticBenzene() public void TestNonAromaticBenzene() { Descriptor.Parameters = new object[] { false, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C1=CC=CC=C1"); // benzene AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); @@ -304,7 +305,7 @@ public void TestNonAromaticBenzene() public void TestPerceivedAromaticBenzene() { Descriptor.Parameters = new object[] { true, true }; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C1=CC=CC=C1"); // benzene AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptorTest.cs index cd3fb9db..9c01a51e 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.QSAR.Results; using NCDK.Smiles; @@ -42,7 +42,7 @@ public ZagrebIndexDescriptorTest() [TestMethod()] public void TestZagrebIndexDescriptor() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C(O)CC"); Assert.AreEqual(16, ((Result)Descriptor.Calculate(mol).Value).Value, 0.0001); } @@ -50,7 +50,7 @@ public void TestZagrebIndexDescriptor() [TestMethod()] public void Test2Dvs3D() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O1C2C34C(C(C1O)CCCc1cc(cc(c1)C(F)(F)F)C(F)(F)F)CCC(C3CCC(O2)(OO4)C)C"); AddExplicitHydrogens(mol); diff --git a/NCDKTests/QSAR/Descriptors/Substances/OxygenAtomCountDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Substances/OxygenAtomCountDescriptorTest.cs index 2ad8c24a..5fdc73d3 100644 --- a/NCDKTests/QSAR/Descriptors/Substances/OxygenAtomCountDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Substances/OxygenAtomCountDescriptorTest.cs @@ -15,7 +15,7 @@ * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; @@ -35,7 +35,7 @@ public void TestCalculate_ZnO() ISubstance material = new Substance(); material.Add( MolecularFormulaManipulator.GetAtomContainer( - "ZnO", Default.ChemObjectBuilder.Instance + "ZnO", ChemObjectBuilder.Instance ) ); var value = descriptor.Calculate(material); @@ -51,7 +51,7 @@ public void TestCalculate_IronOxide() ISubstance material = new Substance(); material.Add( MolecularFormulaManipulator.GetAtomContainer( - "Fe3O4", Default.ChemObjectBuilder.Instance + "Fe3O4", ChemObjectBuilder.Instance ) ); var value = descriptor.Calculate(material); diff --git a/NCDKTests/QSAR/Descriptors/Substances/SubstanceDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Substances/SubstanceDescriptorTest.cs index 409cd979..5678bc79 100644 --- a/NCDKTests/QSAR/Descriptors/Substances/SubstanceDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Substances/SubstanceDescriptorTest.cs @@ -15,7 +15,7 @@ * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.QSAR.Results; using System; @@ -30,7 +30,7 @@ public void SetDescriptor(Type descriptorClass) { if (descriptor == null) { - var descriptor = descriptorClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + var descriptor = descriptorClass.GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); if (!(descriptor is ISubstanceDescriptor)) { throw new Exception( diff --git a/NCDKTests/Reactions/ReactionMechanismTest.cs b/NCDKTests/Reactions/ReactionMechanismTest.cs index 7df9af09..4d19a6ed 100644 --- a/NCDKTests/Reactions/ReactionMechanismTest.cs +++ b/NCDKTests/Reactions/ReactionMechanismTest.cs @@ -40,7 +40,7 @@ public void SetMechanism(Type descriptorClass) { if (reactionMechanism == null) { - var descriptor = descriptorClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + var descriptor = descriptorClass.GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); if (!(descriptor is IReactionMechanism)) { throw new CDKException("The passed reaction class must be a IReactionMechanism"); diff --git a/NCDKTests/Reactions/ReactionProcessTest.cs b/NCDKTests/Reactions/ReactionProcessTest.cs index e416f87b..44202e48 100644 --- a/NCDKTests/Reactions/ReactionProcessTest.cs +++ b/NCDKTests/Reactions/ReactionProcessTest.cs @@ -50,7 +50,7 @@ public void SetReaction(Type reactionClass) { if (dictionary == null) dictionary = OpeningDictionary(); - var obj = reactionClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); + var obj = reactionClass.GetConstructor(Type.EmptyTypes).Invoke(Array.Empty()); if (!(obj is IReactionProcess)) { diff --git a/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs b/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs index 62ea65e3..f44f4566 100644 --- a/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs +++ b/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs @@ -20,6 +20,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -35,7 +36,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class AdductionProtonLPReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester(); @@ -191,7 +191,7 @@ public void TestMapping() // @cdk.inchi InChI=1/C2H4O/c1-2-3/h2H,1H3 private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("O")); molecule.Atoms.Add(builder.NewAtom("C")); @@ -210,7 +210,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -247,7 +247,7 @@ private IChemObjectSet GetExpectedProducts() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs b/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs index 42fe9c5a..2d8619d9 100644 --- a/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs +++ b/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs @@ -20,6 +20,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -35,7 +36,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class AdductionProtonPBReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public AdductionProtonPBReactionTest() @@ -193,7 +193,7 @@ public void TestMapping() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); molecule.Atoms.Add(builder.NewAtom("C")); @@ -210,7 +210,7 @@ private IChemObjectSet GetExampleReactants() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -246,7 +246,7 @@ private IChemObjectSet GetExpectedProducts() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs b/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs index 665f7dc9..e481fef0 100644 --- a/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs +++ b/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs @@ -20,6 +20,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -35,7 +36,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class AdductionSodiumLPReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public AdductionSodiumLPReactionTest() @@ -198,7 +198,7 @@ public void TestMapping() // @cdk.inchi InChI=1/C2H4O/c1-2-3/h2H,1H3 private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("O")); molecule.Atoms.Add(builder.NewAtom("C")); @@ -217,7 +217,7 @@ private IChemObjectSet GetExampleReactants() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -254,7 +254,7 @@ private IChemObjectSet GetExpectedProducts() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs b/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs index 48eb7ded..e677bf7d 100644 --- a/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs +++ b/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Reactions.Types.Parameters; using NCDK.Tools; @@ -36,7 +36,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class CarbonylEliminationReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; /// @@ -183,7 +182,7 @@ private void MakeSureAtomTypesAreRecognized(IAtomContainer molecule) /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer();//CreateFromSmiles("C-C#[O+]") molecule.Atoms.Add(builder.NewAtom("C")); molecule.Atoms.Add(builder.NewAtom("H")); @@ -203,7 +202,7 @@ private IChemObjectSet GetExampleReactants() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } catch (CDKException e) diff --git a/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs b/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs index 14c34443..c8b052b1 100644 --- a/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs +++ b/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -36,7 +37,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class ElectronImpactNBEReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public ElectronImpactNBEReactionTest() @@ -75,7 +75,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() reactant.AddBond(reactant.Atoms[5], reactant.Atoms[6], BondOrder.Single); AddExplicitHydrogens(reactant); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactant); - lpcheck.Saturate(reactant); + LonePairElectronChecker.Saturate(reactant); foreach (var atom in reactant.Atoms) { @@ -85,7 +85,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() } } - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(reactant); /* initiate */ @@ -135,9 +135,9 @@ public void TestAutomatic_Set_Active_Atom() reactant.AddBond(reactant.Atoms[5], reactant.Atoms[6], BondOrder.Single); AddExplicitHydrogens(reactant); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactant); - lpcheck.Saturate(reactant); + LonePairElectronChecker.Saturate(reactant); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(reactant); /* initiate */ @@ -178,11 +178,11 @@ public void TestNsp3SingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[5], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new ElectronImpactNBEReaction(); @@ -217,7 +217,7 @@ public void TestNsp3SingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); @@ -245,11 +245,11 @@ public void TestNsp2SingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new ElectronImpactNBEReaction(); @@ -281,7 +281,7 @@ public void TestNsp2SingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); @@ -309,11 +309,11 @@ public void TestFspSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new ElectronImpactNBEReaction(); @@ -345,7 +345,7 @@ public void TestFspSingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); @@ -432,7 +432,7 @@ private void MakeSureAtomTypesAreRecognized(IAtomContainer molecule) /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer();//CreateFromSmiles("C=O") molecule.Atoms.Add(builder.NewAtom("C")); molecule.Atoms.Add(builder.NewAtom("O")); @@ -445,7 +445,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } catch (CDKException e) diff --git a/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs b/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs index 48bd8885..b0b1ce3e 100644 --- a/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs +++ b/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -34,7 +35,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class ElectronImpactPDBReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public ElectronImpactPDBReactionTest() @@ -85,7 +85,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() } } - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(reactant); /* initiate */ @@ -133,7 +133,7 @@ public void TestAutomatic_Set_Active_Bond() reactant.AddBond(reactant.Atoms[1], reactant.Atoms[2], BondOrder.Single); AddExplicitHydrogens(reactant); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(reactant); /* initiate */ @@ -179,7 +179,7 @@ public void TestAutomatic_Set_Active_Bond2() reactant.AddBond(reactant.Atoms[5], reactant.Atoms[6], BondOrder.Single); AddExplicitHydrogens(reactant); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(reactant); /* initiate */ @@ -300,7 +300,7 @@ private void MakeSureAtomTypesAreRecognized(IAtomContainer molecule) /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer();//Miles("C=CC") molecule.Atoms.Add(builder.NewAtom("C")); @@ -324,7 +324,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/ElectronImpactSDBReactionTest.cs b/NCDKTests/Reactions/Types/ElectronImpactSDBReactionTest.cs index d040d1a3..b833c3c5 100644 --- a/NCDKTests/Reactions/Types/ElectronImpactSDBReactionTest.cs +++ b/NCDKTests/Reactions/Types/ElectronImpactSDBReactionTest.cs @@ -16,9 +16,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using System; using System.Collections.Generic; using System.Linq; @@ -32,7 +34,7 @@ namespace NCDK.Reactions.Types [TestClass()] public class ElectronImpactSDBReactionTest : ReactionProcessTest { - private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; + private IChemObjectBuilder builder = ChemObjectBuilder.Instance; public ElectronImpactSDBReactionTest() { @@ -125,7 +127,7 @@ private void MakeSureAtomTypesAreRecognized(IAtomContainer molecule) /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer reactant = builder.NewAtomContainer();//CreateFromSmiles("C=CC") reactant.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs b/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs index 6911178d..955122b0 100644 --- a/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs +++ b/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -38,7 +38,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class HeterolyticCleavagePBReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester(); @@ -88,7 +87,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavagePBReaction(); @@ -127,7 +126,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -136,7 +135,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected1.Atoms[1].FormalCharge = -1; expected1.Atoms[2].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -184,7 +183,7 @@ public void TestCspDoubleB() molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavagePBReaction(); @@ -219,7 +218,7 @@ public void TestCspDoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -228,7 +227,7 @@ public void TestCspDoubleB() expected1.Atoms[1].FormalCharge = -1; expected1.Atoms[2].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, expected1)); @@ -264,7 +263,7 @@ public void TestCspTripleB() molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavagePBReaction(); @@ -307,7 +306,7 @@ public void TestCspTripleB() expected1.Atoms[1].FormalCharge = -1; expected1.Atoms[2].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -339,13 +338,13 @@ public void TestNsp2DoubleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavagePBReaction(); @@ -382,7 +381,7 @@ public void TestNsp2DoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -404,13 +403,13 @@ public void TestNspTripleB() molecule.Atoms.Add(builder.NewAtom("H")); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; molecule.Bonds[0].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavagePBReaction(); @@ -437,7 +436,7 @@ public void TestNspTripleB() expected1.Atoms.Add(builder.NewAtom("H")); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -461,13 +460,13 @@ public void TestOspDoubleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; molecule.Bonds[0].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavagePBReaction(); @@ -496,7 +495,7 @@ public void TestOspDoubleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -511,7 +510,7 @@ public void TestOspDoubleB() public void TestCDKConstants_REACTIVE_CENTER() { IReactionProcess type = new HeterolyticCleavagePBReaction(); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); /* C=O */ IAtomContainer molecule = builder.NewAtomContainer();//CreateFromSmiles("C=O") @@ -521,7 +520,7 @@ public void TestCDKConstants_REACTIVE_CENTER() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); setOfReactants.Add(molecule); /* manually put the reactive center */ @@ -640,7 +639,7 @@ public void TestBB_AutomaticSearchCentreActiveFormaldehyde() /// The IAtomContainerSet private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); @@ -650,7 +649,7 @@ private IChemObjectSet GetExampleReactants() { AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs b/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs index 3f31edc1..3bb5271b 100644 --- a/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs +++ b/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -37,7 +38,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class HeterolyticCleavageSBReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester(); @@ -91,7 +91,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -141,7 +141,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -204,7 +204,7 @@ public void TestCsp2SingleB() molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -249,7 +249,7 @@ public void TestCsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); @@ -258,7 +258,7 @@ public void TestCsp2SingleB() //CreateFromSmiles("C=[C-]") expected1.Atoms[1].FormalCharge = -1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -313,7 +313,7 @@ public void TestCspSingleB() molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -354,7 +354,7 @@ public void TestCspSingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[1].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -362,7 +362,7 @@ public void TestCspSingleB() //CreateFromSmiles("C#[C+]") expected1.Atoms[1].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[0].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -405,13 +405,13 @@ public void TestNsp3SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -443,7 +443,7 @@ public void TestNsp3SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -490,13 +490,13 @@ public void TestNsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -539,7 +539,7 @@ public void TestNsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -573,13 +573,13 @@ public void TestOsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -609,7 +609,7 @@ public void TestOsp2SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -650,13 +650,13 @@ public void TestFspSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; molecule.Bonds[0].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new HeterolyticCleavageSBReaction(); @@ -676,7 +676,7 @@ public void TestFspSingleB() expected1.Atoms.Add(builder.NewAtom("F")); expected1.Atoms[0].FormalCharge = -1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -791,7 +791,7 @@ private void MakeSureAtomTypesAreRecognized(IAtomContainer molecule) /// The IAtomContainerSet private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer();//CreateFromSmiles("CO") molecule.Atoms.Add(builder.NewAtom("C")); molecule.Atoms.Add(builder.NewAtom("O")); @@ -800,7 +800,7 @@ private IChemObjectSet GetExampleReactants() { AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } catch (Exception e) diff --git a/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs b/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs index 241bdeb2..05e6ed04 100644 --- a/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs +++ b/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -37,7 +37,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class HomolyticCleavageReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; private UniversalIsomorphismTester uiTester = new UniversalIsomorphismTester(); @@ -140,7 +139,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -224,7 +223,7 @@ public void TestCsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); @@ -301,7 +300,7 @@ public void TestCspSingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -380,7 +379,7 @@ public void TestCsp2DoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -450,7 +449,7 @@ public void TestCspDoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -557,7 +556,7 @@ public void TestNsp3SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -595,7 +594,7 @@ public void TestNsp3SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -649,7 +648,7 @@ public void TestNsp3ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[10], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -697,7 +696,7 @@ public void TestNsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -746,7 +745,7 @@ public void TestNsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - lpcheck.Saturate(expected2); + LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -781,7 +780,7 @@ public void TestNsp2ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -830,7 +829,7 @@ public void TestNsp2DoubleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -873,7 +872,7 @@ public void TestNsp2DoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -907,7 +906,7 @@ public void TestNsp2ChargeDoubleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -945,7 +944,7 @@ public void TestNspTripleB() molecule.Atoms.Add(builder.NewAtom("H")); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -978,7 +977,7 @@ public void TestNspTripleB() expected1.Atoms.Add(builder.NewAtom("H")); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1002,7 +1001,7 @@ public void TestNspChargeTripleB() molecule.AddBond(molecule.Atoms[0], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1053,7 +1052,7 @@ public void TestOsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -1089,7 +1088,7 @@ public void TestOsp2SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1141,7 +1140,7 @@ public void TestOsp2ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -1181,7 +1180,7 @@ public void TestOspDoubleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1216,7 +1215,7 @@ public void TestOspDoubleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1242,7 +1241,7 @@ public void TestOspChargeDoubleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1284,7 +1283,7 @@ public void TestFspSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1310,7 +1309,7 @@ public void TestFspSingleB() expected1.Atoms.Add(builder.NewAtom("F")); expected1.SingleElectrons.Add(builder.NewSingleElectron(expected1.Atoms[0])); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1432,8 +1431,7 @@ public void TestEthylbenzaldehydeManual() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1586,8 +1584,7 @@ public void TestEthylbenzaldehydeMapping() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1651,7 +1648,7 @@ private void MakeSureAtomTypesAreRecognized(IAtomContainer molecule) /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer();//CreateFromSmiles("C=O") molecule.Atoms.Add(builder.NewAtom("C")); @@ -1662,7 +1659,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } diff --git a/NCDKTests/Reactions/Types/HyperconjugationReactionTest.cs b/NCDKTests/Reactions/Types/HyperconjugationReactionTest.cs index ee90b646..cf7f1baa 100644 --- a/NCDKTests/Reactions/Types/HyperconjugationReactionTest.cs +++ b/NCDKTests/Reactions/Types/HyperconjugationReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; @@ -60,7 +61,7 @@ public void TestHyperconjugationReaction() public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() { IReactionProcess type = new HyperconjugationReaction(); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); /* [C+]CC */ IAtomContainer molecule = builder.NewAtomContainer(); @@ -283,7 +284,7 @@ public void TestMapping() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/PiBondingMovementReactionTest.cs b/NCDKTests/Reactions/Types/PiBondingMovementReactionTest.cs index 5122bad1..2ed308c4 100644 --- a/NCDKTests/Reactions/Types/PiBondingMovementReactionTest.cs +++ b/NCDKTests/Reactions/Types/PiBondingMovementReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; @@ -80,7 +81,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); MakeSureAtomTypesAreRecognized(molecule); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); /* initiate */ @@ -135,7 +136,7 @@ public void TestAutomaticSearchCentreActiveExample1() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); MakeSureAtomTypesAreRecognized(molecule); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); /* initiate */ @@ -302,7 +303,7 @@ public void TestDoubleRingConjugated2() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); // C{0}1=C{1}C{2}(=C{3}C{4}2=C{5}1C{6}=C{7}C{8}=C{9}2)C{10} // C1=CC(=CC2=C1C=CC=C2)C IAtomContainer molecule = builder.NewAtomContainer(); diff --git a/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationHReactionTest.cs b/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationHReactionTest.cs index 7cd6f2cc..c4cbafd3 100644 --- a/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationHReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationHReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -209,7 +209,7 @@ public void TestMapping() private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("O")); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationReactionTest.cs b/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationReactionTest.cs index 6f3b03e9..e93e9653 100644 --- a/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalChargeSiteInitiationReactionTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -164,7 +164,7 @@ public void TestMapping() private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("O")); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteHrAlphaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteHrAlphaReactionTest.cs index a6acd1ed..c38654bf 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteHrAlphaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteHrAlphaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -83,7 +83,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteHrBetaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteHrBetaReactionTest.cs index 60121525..656eeead 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteHrBetaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteHrBetaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -80,7 +80,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteHrDeltaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteHrDeltaReactionTest.cs index 55837f89..9e2d5962 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteHrDeltaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteHrDeltaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -119,7 +119,7 @@ public void TestManuallyCentreActive() // @cdk.inchi InChI=1/C6H12O/c1-3-5-6(7)4-2/h3-5H2,1-2H3 private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteHrGammaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteHrGammaReactionTest.cs index 92cda1f4..d00c121f 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteHrGammaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteHrGammaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -89,7 +89,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// The IAtomContainer private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteInitiationHReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteInitiationHReactionTest.cs index 5fcc3dbd..4b695137 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteInitiationHReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteInitiationHReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -216,7 +216,7 @@ public void TestMapping() private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteInitiationReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteInitiationReactionTest.cs index 65a62e7b..4895efac 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteInitiationReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteInitiationReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -165,7 +165,7 @@ public void TestMapping() private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteRrAlphaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteRrAlphaReactionTest.cs index 462d25b8..4b708fb5 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteRrAlphaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteRrAlphaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -91,7 +91,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// The IAtomContainer private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteRrBetaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteRrBetaReactionTest.cs index 5cf64833..16ad7e4f 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteRrBetaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteRrBetaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -91,7 +91,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// The IAtomContainer private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteRrDeltaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteRrDeltaReactionTest.cs index f0c7a1bb..7f577325 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteRrDeltaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteRrDeltaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -92,7 +92,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// The IAtomContainer private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RadicalSiteRrGammaReactionTest.cs b/NCDKTests/Reactions/Types/RadicalSiteRrGammaReactionTest.cs index b6afa49b..cd194971 100644 --- a/NCDKTests/Reactions/Types/RadicalSiteRrGammaReactionTest.cs +++ b/NCDKTests/Reactions/Types/RadicalSiteRrGammaReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -93,7 +93,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() /// The IAtomContainer private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs b/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs index 8f7273ca..b09f1d78 100644 --- a/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs +++ b/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -37,7 +37,7 @@ namespace NCDK.Reactions.Types /// displaced. /// /// - /// var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + /// var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); /// setOfReactants.Add(new AtomContainer()); /// IReactionProcess type = new RearrangementAnion1Reaction(); /// Dictionary params = new Dictionary(); @@ -65,7 +65,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class RearrangementAnionReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public RearrangementAnionReactionTest() @@ -264,9 +263,9 @@ public void TestAutomaticSearchCentreActiveExample3() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); /* initiate */ @@ -305,7 +304,7 @@ public void TestAutomaticSearchCentreActiveExample3() AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - lpcheck.Saturate(molecule2); + LonePairElectronChecker.Saturate(molecule2); MakeSureAtomTypesAreRecognized(molecule2); IQueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(product1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule2, queryAtom)); @@ -333,7 +332,7 @@ public void TestAutomaticSearchCentreActiveExample3() AddExplicitHydrogens(molecule3); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule3); - lpcheck.Saturate(molecule3); + LonePairElectronChecker.Saturate(molecule3); MakeSureAtomTypesAreRecognized(molecule3); queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(product2); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule3, queryAtom)); @@ -369,7 +368,7 @@ public void TestAtomTypesAtomContainer2() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RearrangementCationReactionTest.cs b/NCDKTests/Reactions/Types/RearrangementCationReactionTest.cs index 3e92f7cc..c9b8f982 100644 --- a/NCDKTests/Reactions/Types/RearrangementCationReactionTest.cs +++ b/NCDKTests/Reactions/Types/RearrangementCationReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; @@ -222,7 +223,7 @@ public void TestAtomTypesAtomContainer2() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs b/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs index 5b33026f..49b4162c 100644 --- a/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs +++ b/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -38,7 +38,7 @@ namespace NCDK.Reactions.Types /// /// /// - /// var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + /// var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); /// setOfReactants.Add(new AtomContainer()); /// IReactionProcess type = new RearrangementLonePairReaction(); /// Dictionary<string,object> params = new Dictionary<string,object>(); @@ -63,7 +63,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class RearrangementLonePairReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public RearrangementLonePairReactionTest() @@ -256,7 +255,7 @@ public void TestAtomTypesAtomContainer2() // @cdk.inchi InChI=1/C3H6O/c1-2-3-4/h2-4H,1H3 private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("O")); @@ -273,7 +272,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -309,7 +308,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) @@ -361,11 +360,11 @@ public void TestFluorobenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); IReactionProcess type = new RearrangementLonePairReaction(); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); /* automatic search of the center active */ List paramList = new List(); @@ -399,7 +398,7 @@ public void TestFluorobenzene() molecule1.AddBond(molecule1.Atoms[6], molecule1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - lpcheck.Saturate(molecule1); + LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, qAC)); diff --git a/NCDKTests/Reactions/Types/RearrangementRadicalReactionTest.cs b/NCDKTests/Reactions/Types/RearrangementRadicalReactionTest.cs index d5967517..2b14837f 100644 --- a/NCDKTests/Reactions/Types/RearrangementRadicalReactionTest.cs +++ b/NCDKTests/Reactions/Types/RearrangementRadicalReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -215,7 +215,7 @@ public void TestAtomTypesAtomContainer2() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); diff --git a/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs b/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs index 4c40bff0..1484007a 100644 --- a/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -37,7 +38,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class SharingAnionReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public SharingAnionReactionTest() @@ -140,9 +140,9 @@ public void TestCarbons() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); /* initiate */ @@ -165,7 +165,7 @@ public void TestCarbons() AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - lpcheck.Saturate(molecule2); + LonePairElectronChecker.Saturate(molecule2); IQueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(product); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule2, queryAtom)); @@ -259,7 +259,7 @@ public void TestAtomTypesAtomContainer2() /// The IAtomContainerSet private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); @@ -273,7 +273,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -302,7 +302,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs b/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs index 2fd847c8..9e589486 100644 --- a/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -37,7 +38,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class SharingChargeDBReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public SharingChargeDBReactionTest() @@ -213,7 +213,7 @@ public void TestAtomTypesAtomContainer2() /// private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); @@ -227,7 +227,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -258,7 +258,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs b/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs index 84a5d59e..a6d98e87 100644 --- a/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; @@ -38,7 +38,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class SharingChargeSBReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public SharingChargeSBReactionTest() @@ -222,7 +221,7 @@ public void TestAtomTypesAtomContainer2() /// The IAtomContainerSet private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); @@ -248,7 +247,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -282,7 +281,7 @@ private IChemObjectSet GetExpectedProducts() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); } catch (CDKException e) { @@ -358,13 +357,13 @@ public void TestNsp3ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[10], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new SharingChargeSBReaction(); @@ -397,7 +396,7 @@ public void TestNsp3ChargeSingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, queryAtom)); @@ -446,13 +445,13 @@ public void TestNsp2ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; molecule.Bonds[1].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new SharingChargeSBReaction(); @@ -481,7 +480,7 @@ public void TestNsp2ChargeSingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, queryAtom)); @@ -524,13 +523,13 @@ public void TestFspChargeSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; molecule.Bonds[0].IsReactiveCenter = true; - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); IReactionProcess type = new SharingChargeSBReaction(); @@ -551,7 +550,7 @@ public void TestFspChargeSingleB() expected1.Atoms.Add(builder.NewAtom("H")); expected1.AddBond(expected1.Atoms[0], expected1.Atoms[1], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - lpcheck.Saturate(expected1); + LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, queryAtom)); diff --git a/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs b/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs index 2be14aba..14b73ab0 100644 --- a/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs @@ -21,6 +21,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools; using NCDK.Tools.Manipulator; using System; @@ -36,7 +37,6 @@ namespace NCDK.Reactions.Types [TestClass()] public class SharingLonePairReactionTest : ReactionProcessTest { - private readonly LonePairElectronChecker lpcheck = new LonePairElectronChecker(); private IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; public SharingLonePairReactionTest() @@ -210,7 +210,7 @@ public void TestAtomTypesAtomContainer2() /// The IAtomContainerSet private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("C")); @@ -223,7 +223,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -252,7 +252,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/TautomerizationReactionTest.cs b/NCDKTests/Reactions/Types/TautomerizationReactionTest.cs index 2990681a..ca38ecbd 100644 --- a/NCDKTests/Reactions/Types/TautomerizationReactionTest.cs +++ b/NCDKTests/Reactions/Types/TautomerizationReactionTest.cs @@ -20,6 +20,7 @@ using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions.Types.Parameters; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System; using System.Collections.Generic; @@ -81,7 +82,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule2, queryAtom)); // reverse process - var setOfReactants2 = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants2 = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants2.Add(molecule2); IReactionSet setOfReactions2 = type.Initiate(setOfReactants2, null); @@ -145,7 +146,7 @@ public void TestManuallyCentreActive() molecule2.Bonds[0].IsReactiveCenter = true; molecule2.Bonds[1].IsReactiveCenter = true; molecule2.Bonds[5].IsReactiveCenter = true; - var setOfReactants2 = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants2 = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants2.Add(molecule2); var setOfReactions2 = type.Initiate(setOfReactants2, null); @@ -248,7 +249,7 @@ public void TestMapping() // @cdk.inchi InChI=1/C2H4O/c1-2-3/h2H,1H3 private IChemObjectSet GetExampleReactants() { - var setOfReactants = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); IAtomContainer molecule = builder.NewAtomContainer(); molecule.Atoms.Add(builder.NewAtom("O")); diff --git a/NCDKTests/RingSearches/AllRingsFinderTest.cs b/NCDKTests/RingSearches/AllRingsFinderTest.cs index 38e47ce9..fdec7262 100644 --- a/NCDKTests/RingSearches/AllRingsFinderTest.cs +++ b/NCDKTests/RingSearches/AllRingsFinderTest.cs @@ -16,12 +16,12 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; - using System; namespace NCDK.RingSearches @@ -54,7 +54,6 @@ public void TestFindAllRings_IAtomContainer() IRingSet ringSet = null; AllRingsFinder arf = new AllRingsFinder(); IAtomContainer molecule = TestMoleculeFactory.MakeEthylPropylPhenantren(); - //Display(molecule); ringSet = arf.FindAllRings(molecule); @@ -68,18 +67,14 @@ public void TestBondsWithinRing() IRingSet ringSet = null; AllRingsFinder arf = new AllRingsFinder(); IAtomContainer molecule = TestMoleculeFactory.MakeEthylPropylPhenantren(); - //Display(molecule); ringSet = arf.FindAllRings(molecule); - for (int i = 0; i < ringSet.Count; i++) + foreach (var ring in ringSet) { - Ring ring = (Ring)ringSet[i]; - for (int j = 0; j < ring.Bonds.Count; j++) + foreach (var ec in ring.Bonds) { - IBond ec = ring.Bonds[j]; - - IAtom atom1 = ec.Begin; - IAtom atom2 = ec.End; + var atom1 = ec.Begin; + var atom2 = ec.End; Assert.IsTrue(ring.Contains(atom1)); Assert.IsTrue(ring.Contains(atom2)); } @@ -94,31 +89,6 @@ public void TestFindAllRings_IAtomContainer_bool() arf.FindAllRings(molecule); } - [TestMethod(), Ignore()] // timeout not longer used - public void TestSetTimeout_long() - { - AllRingsFinder arf = new AllRingsFinder(); - arf.SetTimeout(1); - IAtomContainer molecule = TestMoleculeFactory.MakeEthylPropylPhenantren(); - arf.FindAllRings(molecule); - } - - [TestMethod(), Ignore()] // timeout not longer used - public void TestCheckTimeout() - { - AllRingsFinder arf = new AllRingsFinder(); - arf.SetTimeout(3); - arf.CheckTimeout(); - } - - [TestMethod(), Ignore()] // timeout not longer used - public void TestGetTimeout() - { - AllRingsFinder arf = new AllRingsFinder(); - arf.SetTimeout(3); - Assert.AreEqual(3, arf.TimeOut, 0.01); - } - [TestMethod()] public void TestPorphyrine() { @@ -143,7 +113,7 @@ public void TestPorphyrine() public void TestBigRingSystem() { IRingSet ringSet = null; - AllRingsFinder arf = AllRingsFinder.UsingThreshold(AllRingsFinder.Threshold.PubChem_994); + AllRingsFinder arf = AllRingsFinder.UsingThreshold(Threshold.PubChem994); string filename = "NCDK.Data.MDL.ring_03419.mol"; var ins = ResourceLoader.GetAsStream(filename); @@ -261,7 +231,7 @@ public void TestBug777488() [TestMethod()] public void TestRingFlags1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = sp.ParseSmiles("c1ccccc1"); foreach (var a in molecule.Atoms) a.IsInRing = false; @@ -279,7 +249,7 @@ public void TestRingFlags1() [TestMethod()] public void TestRingFlags2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = sp.ParseSmiles("C1CCCC1CC"); foreach (var a in molecule.Atoms) a.IsInRing = false; diff --git a/NCDKTests/RingSearches/JumboCyclicVertexSearchTest.cs b/NCDKTests/RingSearches/JumboCyclicVertexSearchTest.cs index d77f0452..b231c697 100644 --- a/NCDKTests/RingSearches/JumboCyclicVertexSearchTest.cs +++ b/NCDKTests/RingSearches/JumboCyclicVertexSearchTest.cs @@ -24,6 +24,7 @@ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections; +using System; namespace NCDK.RingSearches { @@ -35,7 +36,7 @@ public class JumboCyclicVertexSearchTest [TestMethod()] public virtual void TestEmpty() { - ICyclicVertexSearch search = new JumboCyclicVertexSearch(new int[0][]); + ICyclicVertexSearch search = new JumboCyclicVertexSearch(Array.Empty()); Assert.IsNotNull(search); } @@ -102,16 +103,16 @@ public virtual void TestIsolated_NonCyclic() { int[][] g = new int[][] { new[] { 1 }, new[] { 0, 2 }, new[] { 1, 3 }, new[] { 2, 4 }, new[] { 3 } }; ICyclicVertexSearch search = new JumboCyclicVertexSearch(g); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], search.Cyclic())); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), search.Cyclic())); } [TestMethod()] public virtual void TestIsolated_Empty() { - ICyclicVertexSearch search = new JumboCyclicVertexSearch(new int[0][]); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], search.Cyclic())); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], search.Isolated())); - Assert.IsTrue(Compares.AreDeepEqual(new int[0][], search.Fused())); + ICyclicVertexSearch search = new JumboCyclicVertexSearch(Array.Empty()); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), search.Cyclic())); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), search.Isolated())); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), search.Fused())); } /// @@ -350,7 +351,7 @@ public virtual void TestToArray() public virtual void TestToArray_Empty() { BitArray empty = new BitArray(0); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], JumboCyclicVertexSearch.ToArray(empty))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), JumboCyclicVertexSearch.ToArray(empty))); } [TestMethod()] diff --git a/NCDKTests/RingSearches/RegularCyclicVertexSearchTest.cs b/NCDKTests/RingSearches/RegularCyclicVertexSearchTest.cs index b52c0d38..689e8d5c 100644 --- a/NCDKTests/RingSearches/RegularCyclicVertexSearchTest.cs +++ b/NCDKTests/RingSearches/RegularCyclicVertexSearchTest.cs @@ -38,7 +38,7 @@ public class RegularCyclicVertexSearchTest [TestMethod()] public virtual void TestEmpty() { - ICyclicVertexSearch search = new RegularCyclicVertexSearch(new int[0][] { }); + ICyclicVertexSearch search = new RegularCyclicVertexSearch(Array.Empty()); Assert.IsNotNull(search); } @@ -105,14 +105,14 @@ public virtual void TestIsolated_NonCyclic() { int[][] g = new int[][] { new[] { 1 }, new[] { 0, 2 }, new[] { 1, 3 }, new[] { 2, 4 }, new[] { 3 } }; ICyclicVertexSearch search = new RegularCyclicVertexSearch(g); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], search.Cyclic())); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), search.Cyclic())); } [TestMethod()] public virtual void TestIsolated_Empty() { ICyclicVertexSearch search = new RegularCyclicVertexSearch(Arrays.CreateJagged(0, 0)); - Assert.IsTrue(Compares.AreDeepEqual(new int[0], search.Cyclic())); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), search.Cyclic())); Assert.IsTrue(Compares.AreDeepEqual(Arrays.CreateJagged(0, 0), search.Isolated())); Assert.IsTrue(Compares.AreDeepEqual(Arrays.CreateJagged(0, 0), search.Fused())); } @@ -343,7 +343,7 @@ public virtual void TestFused_Fullerene() [TestMethod()] public virtual void TestToArray_Empty() { - Assert.IsTrue(Compares.AreDeepEqual(new int[0], RegularCyclicVertexSearch.ToArray(0L))); + Assert.IsTrue(Compares.AreDeepEqual(Array.Empty(), RegularCyclicVertexSearch.ToArray(0L))); } [TestMethod()] diff --git a/NCDKTests/RingSearches/RingPartitionerTest.cs b/NCDKTests/RingSearches/RingPartitionerTest.cs index 2482c21b..966e40d0 100644 --- a/NCDKTests/RingSearches/RingPartitionerTest.cs +++ b/NCDKTests/RingSearches/RingPartitionerTest.cs @@ -16,10 +16,10 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Graphs; using NCDK.Templates; -using System.Collections.Generic; namespace NCDK.RingSearches { @@ -38,7 +38,7 @@ public RingPartitionerTest() } [TestMethod()] - public void TestConvertToAtomContainer_IRingSet() + public void TestConvertToAtomContainerIRingSet() { IAtomContainer molecule = TestMoleculeFactory.MakeAlphaPinene(); @@ -51,17 +51,17 @@ public void TestConvertToAtomContainer_IRingSet() [TestMethod()] public void TestPartitionIntoRings() { - IAtomContainer azulene = TestMoleculeFactory.MakeAzulene(); - IRingSet ringSet = Cycles.FindSSSR(azulene).ToRingSet(); - IList list = RingPartitioner.PartitionRings(ringSet); + var azulene = TestMoleculeFactory.MakeAzulene(); + var ringSet = Cycles.FindSSSR(azulene).ToRingSet(); + var list = RingPartitioner.PartitionRings(ringSet); Assert.AreEqual(1, list.Count); - IAtomContainer biphenyl = TestMoleculeFactory.MakeBiphenyl(); + var biphenyl = TestMoleculeFactory.MakeBiphenyl(); ringSet = Cycles.FindSSSR(biphenyl).ToRingSet(); list = RingPartitioner.PartitionRings(ringSet); Assert.AreEqual(2, list.Count); - IAtomContainer spiro = TestMoleculeFactory.MakeSpiroRings(); + var spiro = TestMoleculeFactory.MakeSpiroRings(); ringSet = Cycles.FindSSSR(spiro).ToRingSet(); list = RingPartitioner.PartitionRings(ringSet); Assert.AreEqual(1, list.Count); diff --git a/NCDKTests/RingSearches/RingSearchTest.cs b/NCDKTests/RingSearches/RingSearchTest.cs index e0607077..55e38781 100644 --- a/NCDKTests/RingSearches/RingSearchTest.cs +++ b/NCDKTests/RingSearches/RingSearchTest.cs @@ -24,6 +24,8 @@ using System; using Moq; using System.Collections.Generic; +using NCDK.Silent; +using System.Linq; namespace NCDK.RingSearches { @@ -226,7 +228,7 @@ public void TestRingFragments() mock_cyclicSearch.Setup(n => n.Cyclic()).Returns(new int[] { 0, 1, 2 }); mock_cyclicSearch.Setup(n => n.Isolated()).Returns(new int[][] { new[] { 0, 1, 2 } }); - mock_cyclicSearch.Setup(n => n.Fused()).Returns(new int[0][]); + mock_cyclicSearch.Setup(n => n.Fused()).Returns(Array.Empty()); mock_container.Setup(n => n.Atoms.Count).Returns(3); mock_builder.Setup(n => n.NewAtomContainer(It.IsAny>(), It.IsAny>())).Returns(new Mock().Object); mock_container.Setup(n => n.Builder).Returns(mock_builder.Object); @@ -261,7 +263,7 @@ public void TestIsolatedRingFragments() mock_container.Setup(n => n.Atoms[It.IsAny()]).Returns(new Mock().Object); mock_builder.Setup(n => n.NewAtomContainer(It.IsAny>(), It.IsAny>())).Returns(new Mock().Object); - ringSearch.IsolatedRingFragments(); + ringSearch.IsolatedRingFragments().ToList(); mock_cyclicSearch.Verify(n => n.Isolated(), Times.Once()); @@ -290,7 +292,7 @@ public void TestFusedRingFragments() mock_container.Setup(n => n.Bonds).Returns(new List()); mock_container.Setup(n => n.Atoms[It.IsAny()]).Returns(new Mock().Object); - ringSearch.FusedRingFragments(); + ringSearch.FusedRingFragments().ToList(); mock_cyclicSearch.Verify(n => n.Fused(), Times.Once()); @@ -329,8 +331,7 @@ public void ConnectingEdge2() // @cdk.inchi InChI=1/C10H16/c1-2-9(1,3-4-9)10(5-6-10)7-8-10/h1-8H2 public static IAtomContainer DiSpiroPentane() { - - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; @@ -398,7 +399,7 @@ public static IAtomContainer DiSpiroPentane() public static IAtomContainer TriSpiroPentane() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("C"); a1.FormalCharge = 0; diff --git a/NCDKTests/RingSearches/RingSearchTest_Benzene.cs b/NCDKTests/RingSearches/RingSearchTest_Benzene.cs index c1e44c9c..111b307a 100644 --- a/NCDKTests/RingSearches/RingSearchTest_Benzene.cs +++ b/NCDKTests/RingSearches/RingSearchTest_Benzene.cs @@ -20,9 +20,10 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Templates; -using System.Collections.Generic; +using System.Linq; namespace NCDK.RingSearches { @@ -45,8 +46,8 @@ public void TestCyclic() [TestMethod()] public void TestCyclic_Int() { - int n = benzene.Atoms.Count; - RingSearch ringSearch = new RingSearch(benzene); + var n = benzene.Atoms.Count; + var ringSearch = new RingSearch(benzene); for (int i = 0; i < n; i++) { Assert.IsTrue(ringSearch.Cyclic(i)); @@ -56,8 +57,8 @@ public void TestCyclic_Int() [TestMethod()] public void TestIsolated() { - RingSearch search = new RingSearch(benzene); - int[][] isolated = search.Isolated(); + var search = new RingSearch(benzene); + var isolated = search.Isolated(); Assert.AreEqual(1, isolated.Length); Assert.AreEqual(6, isolated[0].Length); } @@ -71,7 +72,7 @@ public void TestFused() [TestMethod()] public void TestRingFragments() { - IAtomContainer fragment = new RingSearch(benzene).RingFragments(); + var fragment = new RingSearch(benzene).RingFragments(); Assert.AreEqual(benzene.Atoms.Count, fragment.Atoms.Count); Assert.AreEqual(benzene.Bonds.Count, fragment.Bonds.Count); } @@ -79,8 +80,8 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - RingSearch search = new RingSearch(benzene); - IList isolated = search.IsolatedRingFragments(); + var search = new RingSearch(benzene); + var isolated = search.IsolatedRingFragments().ToList(); Assert.AreEqual(1, isolated.Count); Assert.AreEqual(6, isolated[0].Atoms.Count); Assert.AreEqual(6, isolated[0].Bonds.Count); @@ -89,9 +90,9 @@ public void TestIsolatedRingFragments() [TestMethod()] public void TestFusedRingFragments() { - RingSearch search = new RingSearch(benzene); - IList fused = search.FusedRingFragments(); - Assert.AreEqual(0, fused.Count); + var search = new RingSearch(benzene); + var fused = search.FusedRingFragments(); + Assert.AreEqual(0, fused.Count()); } } } diff --git a/NCDKTests/RingSearches/RingSearchTest_BenzylBenzene.cs b/NCDKTests/RingSearches/RingSearchTest_BenzylBenzene.cs index 55dfbc0c..dee1f568 100644 --- a/NCDKTests/RingSearches/RingSearchTest_BenzylBenzene.cs +++ b/NCDKTests/RingSearches/RingSearchTest_BenzylBenzene.cs @@ -20,9 +20,10 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; -using System.Collections.Generic; +using NCDK.Silent; +using System.Linq; namespace NCDK.RingSearches { @@ -45,8 +46,8 @@ public void TestCyclic() [TestMethod()] public void TestCyclic_Int() { - int n = benzylbenzene.Atoms.Count; - RingSearch ringSearch = new RingSearch(benzylbenzene); + var n = benzylbenzene.Atoms.Count; + var ringSearch = new RingSearch(benzylbenzene); int cyclic = 0, acyclic = 0; for (int i = 0; i < n; i++) @@ -65,8 +66,8 @@ public void TestCyclic_Int() [TestMethod()] public void TestIsolated() { - RingSearch search = new RingSearch(benzylbenzene); - int[][] isolated = search.Isolated(); + var search = new RingSearch(benzylbenzene); + var isolated = search.Isolated(); Assert.AreEqual(2, isolated.Length); Assert.AreEqual(6, isolated[0].Length); Assert.AreEqual(6, isolated[1].Length); @@ -81,7 +82,7 @@ public void TestFused() [TestMethod()] public void TestRingFragments() { - IAtomContainer fragment = new RingSearch(benzylbenzene).RingFragments(); + var fragment = new RingSearch(benzylbenzene).RingFragments(); Assert.AreEqual(benzylbenzene.Atoms.Count - 1, fragment.Atoms.Count); Assert.AreEqual(benzylbenzene.Bonds.Count - 2, fragment.Bonds.Count); } @@ -89,8 +90,8 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - RingSearch search = new RingSearch(benzylbenzene); - IList isolated = search.IsolatedRingFragments(); + var search = new RingSearch(benzylbenzene); + var isolated = search.IsolatedRingFragments().ToList(); Assert.AreEqual(2, isolated.Count); Assert.AreEqual(6, isolated[0].Atoms.Count); Assert.AreEqual(6, isolated[0].Bonds.Count); @@ -101,9 +102,9 @@ public void TestIsolatedRingFragments() [TestMethod()] public void TestFusedRingFragments() { - RingSearch search = new RingSearch(benzylbenzene); - IList fused = search.FusedRingFragments(); - Assert.AreEqual(0, fused.Count); + var search = new RingSearch(benzylbenzene); + var fused = search.FusedRingFragments(); + Assert.AreEqual(0, fused.Count()); } // @cdk.inchi InChI=1S/C13H12/c1-3-7-12(8-4-1)11-13-9-5-2-6-10-13/h1-10H,11H2 diff --git a/NCDKTests/RingSearches/RingSearchTest_Bicyclo.cs b/NCDKTests/RingSearches/RingSearchTest_Bicyclo.cs index 620781a2..cfdbffce 100644 --- a/NCDKTests/RingSearches/RingSearchTest_Bicyclo.cs +++ b/NCDKTests/RingSearches/RingSearchTest_Bicyclo.cs @@ -20,10 +20,10 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.Templates; -using System.Collections.Generic; +using System.Linq; namespace NCDK.RingSearches { @@ -41,16 +41,15 @@ public sealed class RingSearchTest_Bicyclo [TestMethod()] public void TestCyclic() { - int n = bicyclo.Atoms.Count; + var n = bicyclo.Atoms.Count; Assert.AreEqual(n, new RingSearch(bicyclo).Cyclic().Length, "cyclic vertices should be invariant for any ordering"); } [TestMethod()] public void TestCyclic_Int() { - int n = bicyclo.Atoms.Count; - - RingSearch ringSearch = new RingSearch(bicyclo); + var n = bicyclo.Atoms.Count; + var ringSearch = new RingSearch(bicyclo); for (int i = 0; i < n; i++) Assert.IsTrue(ringSearch.Cyclic(i), "all atoms should be cyclic"); } @@ -70,9 +69,8 @@ public void TestFused() [TestMethod()] public void TestRingFragments() { - int n = bicyclo.Atoms.Count; - - IAtomContainer fragment = new RingSearch(bicyclo).RingFragments(); + var n = bicyclo.Atoms.Count; + var fragment = new RingSearch(bicyclo).RingFragments(); Assert.AreEqual(bicyclo.Atoms.Count, fragment.Atoms.Count); Assert.AreEqual(bicyclo.Bonds.Count, fragment.Bonds.Count); } @@ -80,16 +78,15 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - int n = bicyclo.Atoms.Count; - - IList fragments = new RingSearch(bicyclo).IsolatedRingFragments(); - Assert.IsTrue(fragments.Count == 0); + var n = bicyclo.Atoms.Count; + var fragments = new RingSearch(bicyclo).IsolatedRingFragments(); + Assert.IsTrue(fragments.Count() == 0); } [TestMethod()] public void TestFusedRingFragments() { - IList fragments = new RingSearch(bicyclo).FusedRingFragments(); + var fragments = new RingSearch(bicyclo).FusedRingFragments().ToList(); Assert.AreEqual(1, fragments.Count); IAtomContainer fragment = fragments[0]; Assert.AreEqual(bicyclo.Atoms.Count, fragment.Atoms.Count); diff --git a/NCDKTests/RingSearches/RingSearchTest_Biphenyl.cs b/NCDKTests/RingSearches/RingSearchTest_Biphenyl.cs index d3b8d024..435d28b4 100644 --- a/NCDKTests/RingSearches/RingSearchTest_Biphenyl.cs +++ b/NCDKTests/RingSearches/RingSearchTest_Biphenyl.cs @@ -20,9 +20,10 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Templates; -using System.Collections.Generic; +using System.Linq; namespace NCDK.RingSearches { @@ -45,8 +46,8 @@ public void TestCyclic() [TestMethod()] public void TestCyclic_Int() { - int n = biphenyl.Atoms.Count; - RingSearch ringSearch = new RingSearch(biphenyl); + var n = biphenyl.Atoms.Count; + var ringSearch = new RingSearch(biphenyl); for (int i = 0; i < n; i++) { Assert.IsTrue(ringSearch.Cyclic(i)); @@ -56,8 +57,8 @@ public void TestCyclic_Int() [TestMethod()] public void TestIsolated() { - RingSearch search = new RingSearch(biphenyl); - int[][] isolated = search.Isolated(); + var search = new RingSearch(biphenyl); + var isolated = search.Isolated(); Assert.AreEqual(2, isolated.Length); Assert.AreEqual(6, isolated[0].Length); Assert.AreEqual(6, isolated[1].Length); @@ -72,7 +73,7 @@ public void TestFused() [TestMethod()] public void TestRingFragments() { - IAtomContainer fragment = new RingSearch(biphenyl).RingFragments(); + var fragment = new RingSearch(biphenyl).RingFragments(); Assert.AreEqual(biphenyl.Atoms.Count, fragment.Atoms.Count); Assert.AreEqual(biphenyl.Bonds.Count - 1, fragment.Bonds.Count); } @@ -80,8 +81,8 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - RingSearch search = new RingSearch(biphenyl); - IList isolated = search.IsolatedRingFragments(); + var search = new RingSearch(biphenyl); + var isolated = search.IsolatedRingFragments().ToList(); Assert.AreEqual(2, isolated.Count); Assert.AreEqual(6, isolated[0].Atoms.Count); Assert.AreEqual(6, isolated[0].Bonds.Count); @@ -92,9 +93,9 @@ public void TestIsolatedRingFragments() [TestMethod()] public void TestFusedRingFragments() { - RingSearch search = new RingSearch(biphenyl); - IList fused = search.FusedRingFragments(); - Assert.AreEqual(0, fused.Count); + var search = new RingSearch(biphenyl); + var fused = search.FusedRingFragments(); + Assert.AreEqual(0, fused.Count()); } } } diff --git a/NCDKTests/RingSearches/RingSearchTest_Empty.cs b/NCDKTests/RingSearches/RingSearchTest_Empty.cs index 44486127..ca12e5ec 100644 --- a/NCDKTests/RingSearches/RingSearchTest_Empty.cs +++ b/NCDKTests/RingSearches/RingSearchTest_Empty.cs @@ -21,7 +21,8 @@ * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; +using System.Linq; namespace NCDK.RingSearches { @@ -73,13 +74,13 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - Assert.IsTrue(new RingSearch(empty).IsolatedRingFragments().Count == 0); + Assert.IsTrue(new RingSearch(empty).IsolatedRingFragments().Count() == 0); } [TestMethod()] public void TestFusedRingFragments() { - Assert.IsTrue(new RingSearch(empty).FusedRingFragments().Count == 0); + Assert.IsTrue(new RingSearch(empty).FusedRingFragments().Count() == 0); } } } diff --git a/NCDKTests/RingSearches/RingSearchTest_Fused.cs b/NCDKTests/RingSearches/RingSearchTest_Fused.cs index 97df6e34..fc89a77c 100644 --- a/NCDKTests/RingSearches/RingSearchTest_Fused.cs +++ b/NCDKTests/RingSearches/RingSearchTest_Fused.cs @@ -20,9 +20,10 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Templates; -using System.Collections.Generic; +using System.Linq; namespace NCDK.RingSearches { @@ -39,7 +40,7 @@ public class RingSearchTest_Fused [TestMethod()] public void TestCyclic_Int() { - RingSearch ringSearch = new RingSearch(fusedRings); + var ringSearch = new RingSearch(fusedRings); for (int i = 0; i < fusedRings.Atoms.Count; i++) Assert.IsTrue(ringSearch.Cyclic(i)); } @@ -47,29 +48,29 @@ public void TestCyclic_Int() [TestMethod()] public void TestCyclic() { - RingSearch ringSearch = new RingSearch(fusedRings); + var ringSearch = new RingSearch(fusedRings); Assert.AreEqual(fusedRings.Atoms.Count, ringSearch.Cyclic().Length); } [TestMethod()] public void TestFused() { - RingSearch ringSearch = new RingSearch(fusedRings); + var ringSearch = new RingSearch(fusedRings); Assert.AreEqual(1, ringSearch.Fused().Length); } [TestMethod()] public void TestIsolated() { - RingSearch ringSearch = new RingSearch(fusedRings); + var ringSearch = new RingSearch(fusedRings); Assert.AreEqual(0, ringSearch.Isolated().Length); } [TestMethod()] public void TestRingFragments() { - RingSearch ringSearch = new RingSearch(fusedRings); - IAtomContainer fragment = ringSearch.RingFragments(); + var ringSearch = new RingSearch(fusedRings); + var fragment = ringSearch.RingFragments(); foreach (var atom in fusedRings.Atoms) { Assert.IsTrue(fragment.Contains(atom)); @@ -83,8 +84,8 @@ public void TestRingFragments() [TestMethod()] public void TestFusedRingFragments() { - RingSearch ringSearch = new RingSearch(fusedRings); - IList fragments = ringSearch.FusedRingFragments(); + var ringSearch = new RingSearch(fusedRings); + var fragments = ringSearch.FusedRingFragments().ToList(); Assert.AreEqual(1, fragments.Count); IAtomContainer fragment = fragments[0]; foreach (var atom in fusedRings.Atoms) @@ -100,9 +101,9 @@ public void TestFusedRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - RingSearch ringSearch = new RingSearch(fusedRings); - IList fragments = ringSearch.IsolatedRingFragments(); - Assert.AreEqual(0, fragments.Count); + var ringSearch = new RingSearch(fusedRings); + var fragments = ringSearch.IsolatedRingFragments(); + Assert.AreEqual(0, fragments.Count()); } } } diff --git a/NCDKTests/RingSearches/RingSearchTest_Hexaphenylene.cs b/NCDKTests/RingSearches/RingSearchTest_Hexaphenylene.cs index 2b904c9f..60424505 100644 --- a/NCDKTests/RingSearches/RingSearchTest_Hexaphenylene.cs +++ b/NCDKTests/RingSearches/RingSearchTest_Hexaphenylene.cs @@ -20,9 +20,10 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; -using System.Collections.Generic; +using NCDK.Silent; +using System.Linq; namespace NCDK.RingSearches { @@ -45,8 +46,8 @@ public void TestCyclic() [TestMethod()] public void TestCyclic_Int() { - int n = hexaphenylene.Atoms.Count; - RingSearch ringSearch = new RingSearch(hexaphenylene); + var n = hexaphenylene.Atoms.Count; + var ringSearch = new RingSearch(hexaphenylene); for (int i = 0; i < n; i++) { Assert.IsTrue(ringSearch.Cyclic(i)); @@ -56,15 +57,15 @@ public void TestCyclic_Int() [TestMethod()] public void TestIsolated() { - RingSearch search = new RingSearch(hexaphenylene); - int[][] isolated = search.Isolated(); + var search = new RingSearch(hexaphenylene); + var isolated = search.Isolated(); Assert.AreEqual(0, isolated.Length); } [TestMethod()] public void TestFused() { - int[][] fused = new RingSearch(hexaphenylene).Fused(); + var fused = new RingSearch(hexaphenylene).Fused(); Assert.AreEqual(1, fused.Length); Assert.AreEqual(hexaphenylene.Atoms.Count, fused[0].Length); } @@ -72,7 +73,7 @@ public void TestFused() [TestMethod()] public void TestRingFragments() { - IAtomContainer fragment = new RingSearch(hexaphenylene).RingFragments(); + var fragment = new RingSearch(hexaphenylene).RingFragments(); Assert.AreEqual(hexaphenylene.Atoms.Count, fragment.Atoms.Count); Assert.AreEqual(hexaphenylene.Bonds.Count, fragment.Bonds.Count); } @@ -80,16 +81,16 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - RingSearch search = new RingSearch(hexaphenylene); - IList isolated = search.IsolatedRingFragments(); - Assert.AreEqual(0, isolated.Count); + var search = new RingSearch(hexaphenylene); + var isolated = search.IsolatedRingFragments(); + Assert.AreEqual(0, isolated.Count()); } [TestMethod()] public void TestFusedRingFragments() { - RingSearch search = new RingSearch(hexaphenylene); - IList fused = search.FusedRingFragments(); + var search = new RingSearch(hexaphenylene); + var fused = search.FusedRingFragments().ToList(); Assert.AreEqual(1, fused.Count); Assert.AreEqual(hexaphenylene.Atoms.Count, fused[0].Atoms.Count); Assert.AreEqual(hexaphenylene.Bonds.Count, fused[0].Bonds.Count); diff --git a/NCDKTests/RingSearches/RingSearchTest_NonCyclic.cs b/NCDKTests/RingSearches/RingSearchTest_NonCyclic.cs index 2efad8a5..6747f531 100644 --- a/NCDKTests/RingSearches/RingSearchTest_NonCyclic.cs +++ b/NCDKTests/RingSearches/RingSearchTest_NonCyclic.cs @@ -22,6 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Templates; +using System.Linq; namespace NCDK.RingSearches { @@ -73,13 +74,13 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - Assert.IsTrue(new RingSearch(nonCyclic).IsolatedRingFragments().Count == 0); + Assert.IsTrue(new RingSearch(nonCyclic).IsolatedRingFragments().Count() == 0); } [TestMethod()] public void TestFusedRingFragments() { - Assert.IsTrue(new RingSearch(nonCyclic).FusedRingFragments().Count == 0); + Assert.IsTrue(new RingSearch(nonCyclic).FusedRingFragments().Count() == 0); } } } diff --git a/NCDKTests/RingSearches/RingSearchTest_SpiroRings.cs b/NCDKTests/RingSearches/RingSearchTest_SpiroRings.cs index e87fee3a..16609f39 100644 --- a/NCDKTests/RingSearches/RingSearchTest_SpiroRings.cs +++ b/NCDKTests/RingSearches/RingSearchTest_SpiroRings.cs @@ -20,10 +20,11 @@ * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Common.Base; + using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Common.Base; using NCDK.Templates; -using System.Collections.Generic; +using System.Linq; namespace NCDK.RingSearches { @@ -46,8 +47,8 @@ public void TestCyclic() [TestMethod()] public void TestCyclic_Int() { - int n = spiro.Atoms.Count; - RingSearch ringSearch = new RingSearch(spiro); + var n = spiro.Atoms.Count; + var ringSearch = new RingSearch(spiro); for (int i = 0; i < n; i++) { Assert.IsTrue(ringSearch.Cyclic(i)); @@ -57,8 +58,8 @@ public void TestCyclic_Int() [TestMethod()] public void TestIsolated() { - RingSearch search = new RingSearch(spiro); - int[][] isolated = search.Isolated(); + var search = new RingSearch(spiro); + var isolated = search.Isolated(); Assert.AreEqual(2, isolated.Length); Assert.IsTrue(Compares.AreOrderLessDeepEqual(new[] { 4, 7 }, new int[] { isolated[0].Length, isolated[1].Length })); } @@ -72,7 +73,7 @@ public void TestFused() [TestMethod()] public void TestRingFragments() { - IAtomContainer fragment = new RingSearch(spiro).RingFragments(); + var fragment = new RingSearch(spiro).RingFragments(); Assert.AreEqual(spiro.Atoms.Count, fragment.Atoms.Count); Assert.AreEqual(spiro.Bonds.Count, fragment.Bonds.Count); } @@ -80,8 +81,8 @@ public void TestRingFragments() [TestMethod()] public void TestIsolatedRingFragments() { - RingSearch search = new RingSearch(spiro); - IList isolated = search.IsolatedRingFragments(); + var search = new RingSearch(spiro); + var isolated = search.IsolatedRingFragments().ToList(); Assert.AreEqual(2, isolated.Count); Assert.IsTrue(Compares.AreOrderLessDeepEqual(new[] { 4, 7 }, new int[] { isolated[0].Atoms.Count, isolated[1].Atoms.Count })); } @@ -89,9 +90,9 @@ public void TestIsolatedRingFragments() [TestMethod()] public void TestFusedRingFragments() { - RingSearch search = new RingSearch(spiro); - IList fused = search.FusedRingFragments(); - Assert.AreEqual(0, fused.Count); + var search = new RingSearch(spiro); + var fused = search.FusedRingFragments(); + Assert.AreEqual(0, fused.Count()); } } } diff --git a/NCDKTests/SMARTS/SmartsFragmentExtractorTest.cs b/NCDKTests/SMARTS/SmartsFragmentExtractorTest.cs index d8dc9c1d..a6787c48 100644 --- a/NCDKTests/SMARTS/SmartsFragmentExtractorTest.cs +++ b/NCDKTests/SMARTS/SmartsFragmentExtractorTest.cs @@ -20,6 +20,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Smiles; @@ -28,18 +29,18 @@ namespace NCDK.SMARTS [TestClass()] public class SmartsFragmentExtractorTest { - private string Generate(string smi, int mode, int[] idxs) + private static string Generate(string smi, SubstructureSelectionMode mode, int[] idxs) { - SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); - IAtomContainer mol = smipar.ParseSmiles(smi); - SmartsFragmentExtractor subsmarts = new SmartsFragmentExtractor(mol); + var smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); + var mol = smipar.ParseSmiles(smi); + var subsmarts = new SmartsFragmentExtractor(mol); subsmarts.SetMode(mode); return subsmarts.Generate(idxs); } private static int[] MakeSeq(int beg, int to) { - int[] a = new int[to - beg]; + var a = new int[to - beg]; for (int i = 0; i < a.Length; i++) a[i] = beg++; return a; @@ -48,57 +49,43 @@ private static int[] MakeSeq(int beg, int to) [TestMethod()] public void MethylExact() { - string smarts = Generate("CC(C)CCC", - SmartsFragmentExtractor.MODE_EXACT, - MakeSeq(0, 1)); + var smarts = Generate("CC(C)CCC", SubstructureSelectionMode.ExactSmarts, MakeSeq(0, 1)); Assert.AreEqual("[CH3v4X4+0]", smarts); } [TestMethod()] public void MethylForJCompoundMap() { - string smarts = Generate("CC(C)CCC", - SmartsFragmentExtractor.MODE_JCOMPOUNDMAPPER, - MakeSeq(0, 1)); + var smarts = Generate("CC(C)CCC", SubstructureSelectionMode.JCompoundMapper, MakeSeq(0, 1)); Assert.AreEqual("C*", smarts); } [TestMethod()] public void Indole() { - string smarts = Generate("[nH]1ccc2c1cccc2", - SmartsFragmentExtractor.MODE_EXACT, - MakeSeq(0, 4)); + var smarts = Generate("[nH]1ccc2c1cccc2", SubstructureSelectionMode.ExactSmarts, MakeSeq(0, 4)); Assert.AreEqual("[nH1v3X3+0][cH1v4X3+0][cH1v4X3+0][cH0v4X3+0]", smarts); } [TestMethod()] public void IndoleForJCompoundMap() { - string smarts = Generate("[nH]1ccc2c1cccc2", - SmartsFragmentExtractor.MODE_JCOMPOUNDMAPPER, - MakeSeq(0, 4)); + var smarts = Generate("[nH]1ccc2c1cccc2", SubstructureSelectionMode.JCompoundMapper, MakeSeq(0, 4)); Assert.AreEqual("n(ccc(a)a)a", smarts); } [TestMethod()] public void BiphenylIncludesSingleBond() { - string smarts = Generate("c1ccccc1-c1ccccc1", - SmartsFragmentExtractor.MODE_EXACT, - MakeSeq(0, 12)); + var smarts = Generate("c1ccccc1-c1ccccc1", SubstructureSelectionMode.ExactSmarts, MakeSeq(0, 12)); Assert.IsTrue(smarts.Contains("-")); } [TestMethod()] public void FullereneC60() { - string smarts = Generate("c12c3c4c5c1c1c6c7c2c2c8c3c3c9c4c4c%10c5c5c1c1c6c6c%11c7c2c2c7c8c3c3c8c9c4c4c9c%10c5c5c1c1c6c6c%11c2c2c7c3c3c8c4c4c9c5c1c1c6c2c3c41", - SmartsFragmentExtractor.MODE_EXACT, - MakeSeq(0, 60)); - Assert.AreEqual( - "[cH0v4X3+0]12[cH0v4X3+0]3[cH0v4X3+0]4[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]7[cH0v4X3+0]2[cH0v4X3+0]2[cH0v4X3+0]8[cH0v4X3+0]3[cH0v4X3+0]3[cH0v4X3+0]9[cH0v4X3+0]4[cH0v4X3+0]4[cH0v4X3+0]%10[cH0v4X3+0]5[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]6[cH0v4X3+0]%11[cH0v4X3+0]7[cH0v4X3+0]2[cH0v4X3+0]2[cH0v4X3+0]7[cH0v4X3+0]8[cH0v4X3+0]3[cH0v4X3+0]3[cH0v4X3+0]8[cH0v4X3+0]9[cH0v4X3+0]4[cH0v4X3+0]4[cH0v4X3+0]9[cH0v4X3+0]%10[cH0v4X3+0]5[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]6[cH0v4X3+0]%11[cH0v4X3+0]2[cH0v4X3+0]2[cH0v4X3+0]7[cH0v4X3+0]3[cH0v4X3+0]3[cH0v4X3+0]8[cH0v4X3+0]4[cH0v4X3+0]4[cH0v4X3+0]9[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]2[cH0v4X3+0]3[cH0v4X3+0]41", - smarts); + var smarts = Generate("c12c3c4c5c1c1c6c7c2c2c8c3c3c9c4c4c%10c5c5c1c1c6c6c%11c7c2c2c7c8c3c3c8c9c4c4c9c%10c5c5c1c1c6c6c%11c2c2c7c3c3c8c4c4c9c5c1c1c6c2c3c41", SubstructureSelectionMode.ExactSmarts, MakeSeq(0, 60)); + Assert.AreEqual("[cH0v4X3+0]12[cH0v4X3+0]3[cH0v4X3+0]4[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]7[cH0v4X3+0]2[cH0v4X3+0]2[cH0v4X3+0]8[cH0v4X3+0]3[cH0v4X3+0]3[cH0v4X3+0]9[cH0v4X3+0]4[cH0v4X3+0]4[cH0v4X3+0]%10[cH0v4X3+0]5[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]6[cH0v4X3+0]%11[cH0v4X3+0]7[cH0v4X3+0]2[cH0v4X3+0]2[cH0v4X3+0]7[cH0v4X3+0]8[cH0v4X3+0]3[cH0v4X3+0]3[cH0v4X3+0]8[cH0v4X3+0]9[cH0v4X3+0]4[cH0v4X3+0]4[cH0v4X3+0]9[cH0v4X3+0]%10[cH0v4X3+0]5[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]6[cH0v4X3+0]%11[cH0v4X3+0]2[cH0v4X3+0]2[cH0v4X3+0]7[cH0v4X3+0]3[cH0v4X3+0]3[cH0v4X3+0]8[cH0v4X3+0]4[cH0v4X3+0]4[cH0v4X3+0]9[cH0v4X3+0]5[cH0v4X3+0]1[cH0v4X3+0]1[cH0v4X3+0]6[cH0v4X3+0]2[cH0v4X3+0]3[cH0v4X3+0]41", smarts); } } } diff --git a/NCDKTests/SMSD/AbstractMCSTest.cs b/NCDKTests/SMSD/AbstractMCSTest.cs index 4271297f..3dd0e21e 100644 --- a/NCDKTests/SMSD/AbstractMCSTest.cs +++ b/NCDKTests/SMSD/AbstractMCSTest.cs @@ -20,6 +20,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Isomorphisms.Matchers; using System.Collections.Generic; @@ -57,13 +58,13 @@ public override void SetChemFilters(bool stereoFilter, bool fragmentFilter, bool public override double GetEuclideanDistance() => 0.0; - public override IList> GetAllAtomMapping() => null; + public override IReadOnlyList> GetAllAtomMapping() => null; - public override IList> GetAllMapping() => null; + public override IReadOnlyList> GetAllMapping() => null; - public override IDictionary GetFirstAtomMapping() => null; + public override IReadOnlyDictionary GetFirstAtomMapping() => null; - public override IDictionary GetFirstMapping() => null; + public override IReadOnlyDictionary GetFirstMapping() => null; public override double BondSensitiveTimeOut { diff --git a/NCDKTests/SMSD/AbstractSubGraphTest.cs b/NCDKTests/SMSD/AbstractSubGraphTest.cs index a7beb5b0..af22859c 100644 --- a/NCDKTests/SMSD/AbstractSubGraphTest.cs +++ b/NCDKTests/SMSD/AbstractSubGraphTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; using NCDK.SMSD.Algorithms.VFLib; using NCDK.SMSD.Tools; @@ -42,7 +43,7 @@ public AbstractSubGraphTest() { } [TestMethod()] public virtual void TestIsSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); diff --git a/NCDKTests/SMSD/Algorithms/MCSPluses/ExactMappingTest.cs b/NCDKTests/SMSD/Algorithms/MCSPluses/ExactMappingTest.cs index 95c4d15c..6c61d4b1 100644 --- a/NCDKTests/SMSD/Algorithms/MCSPluses/ExactMappingTest.cs +++ b/NCDKTests/SMSD/Algorithms/MCSPluses/ExactMappingTest.cs @@ -20,6 +20,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; @@ -36,7 +37,7 @@ public ExactMappingTest() { } public void TestSomeMethod() { // TODO review the generated test code and remove the default call to fail. - Assert.IsNotNull(ExactMapping.ExtractMapping(new List>(), new List(), new List())); + Assert.IsNotNull(ExactMapping.ExtractMapping(new List>(), new List(), new List())); } } } diff --git a/NCDKTests/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraphTest.cs b/NCDKTests/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraphTest.cs index 0e8b9aef..d79bab74 100644 --- a/NCDKTests/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraphTest.cs +++ b/NCDKTests/SMSD/Algorithms/MCSPluses/GenerateCompatibilityGraphTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.SMSD.Algorithms.MCSPluses { diff --git a/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusHandlerTest.cs b/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusHandlerTest.cs index dfb4dd0f..d454fef0 100644 --- a/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusHandlerTest.cs +++ b/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusHandlerTest.cs @@ -20,7 +20,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.SMSD.Tools; @@ -49,7 +49,7 @@ public override void TestSearchMCS() { try { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = null; target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = null; @@ -73,7 +73,7 @@ public override void TestSearchMCS() [TestMethod()] public void TestSet_IAtomContainer_IAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -116,7 +116,7 @@ public void TestSet_String_String() [TestMethod()] public void TestSet_MolHandler_MolHandler() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target1 = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -134,7 +134,7 @@ public void TestSet_MolHandler_MolHandler() [TestMethod(), Ignore()] // Failing but not going to be fixed public void TestGetAllAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -157,7 +157,7 @@ public void TestGetAllAtomMapping() [TestMethod(), Ignore()] // Failing but not going to be fixed public void TestGetAllMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -181,7 +181,7 @@ public void TestGetAllMapping() [TestMethod()] public void TestGetFirstAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -201,7 +201,7 @@ public void TestGetFirstAtomMapping() [TestMethod()] public void TestGetFirstMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); diff --git a/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusTest.cs b/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusTest.cs index f2bf2e90..264303bf 100644 --- a/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusTest.cs +++ b/NCDKTests/SMSD/Algorithms/MCSPluses/MCSPlusTest.cs @@ -20,8 +20,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.SMSD.Algorithms.MCSPluses { @@ -36,7 +37,7 @@ public MCSPlusTest() { } public void TestSomeMethod() { // TODO review the generated test code and remove the default call to fail. - Assert.IsNotNull(new MCSPlus().GetOverlaps(new AtomContainer(), new AtomContainer(), true)); + Assert.IsNotNull(MCSPlus.GetOverlaps(new AtomContainer(), new AtomContainer(), true)); } } } diff --git a/NCDKTests/SMSD/Algorithms/RGraph/CDKMCSHandlerTest.cs b/NCDKTests/SMSD/Algorithms/RGraphs/CDKMCSHandlerTest.cs similarity index 92% rename from NCDKTests/SMSD/Algorithms/RGraph/CDKMCSHandlerTest.cs rename to NCDKTests/SMSD/Algorithms/RGraphs/CDKMCSHandlerTest.cs index e40950a5..f40fb941 100644 --- a/NCDKTests/SMSD/Algorithms/RGraph/CDKMCSHandlerTest.cs +++ b/NCDKTests/SMSD/Algorithms/RGraphs/CDKMCSHandlerTest.cs @@ -20,14 +20,14 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.SMSD.Tools; using System.Diagnostics; using System.IO; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { /// /// Unit testing for the class. @@ -48,7 +48,7 @@ public override void TestSearchMCS() { try { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = null; target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = null; @@ -72,7 +72,7 @@ public override void TestSearchMCS() [TestMethod()] public void TestSet_IAtomContainer_IAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -116,7 +116,7 @@ public void TestSet_String_String() [TestMethod()] public void TestSet_MolHandler_MolHandler() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target1 = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -134,7 +134,7 @@ public void TestSet_MolHandler_MolHandler() [TestMethod()] public void TestGetAllAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -153,7 +153,7 @@ public void TestGetAllAtomMapping() [TestMethod()] public void TestGetAllMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -173,7 +173,7 @@ public void TestGetAllMapping() [TestMethod()] public void TestGetFirstAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -194,7 +194,7 @@ public void TestGetFirstAtomMapping() [TestMethod()] public void TestGetFirstMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); diff --git a/NCDKTests/SMSD/Algorithms/RGraph/CDKMCSTest.cs b/NCDKTests/SMSD/Algorithms/RGraphs/CDKMCSTest.cs similarity index 92% rename from NCDKTests/SMSD/Algorithms/RGraph/CDKMCSTest.cs rename to NCDKTests/SMSD/Algorithms/RGraphs/CDKMCSTest.cs index 664f0ad9..6f2c4a90 100644 --- a/NCDKTests/SMSD/Algorithms/RGraph/CDKMCSTest.cs +++ b/NCDKTests/SMSD/Algorithms/RGraphs/CDKMCSTest.cs @@ -25,7 +25,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; using NCDK.IO; using NCDK.Isomorphisms.Matchers; @@ -37,7 +37,7 @@ using System; using System.IO; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { // @cdk.module test-smsd // @author Syed Asad Rahman @@ -74,25 +74,25 @@ public void TestIsSubgraph_IAtomContainer_IAtomContainer() [TestMethod()] public void TestSFBug1708336() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer atomContainer = builder.NewAtomContainer(); atomContainer.Atoms.Add(builder.NewAtom("C")); atomContainer.Atoms.Add(builder.NewAtom("C")); atomContainer.Atoms.Add(builder.NewAtom("N")); atomContainer.AddBond(atomContainer.Atoms[0], atomContainer.Atoms[1], BondOrder.Single); atomContainer.AddBond(atomContainer.Atoms[1], atomContainer.Atoms[2], BondOrder.Single); - IQueryAtomContainer query = new QueryAtomContainer(Default.ChemObjectBuilder.Instance); - IQueryAtom a1 = new SymbolQueryAtom(Default.ChemObjectBuilder.Instance); + IQueryAtomContainer query = new QueryAtomContainer(ChemObjectBuilder.Instance); + IQueryAtom a1 = new SymbolQueryAtom(ChemObjectBuilder.Instance); a1.Symbol = "C"; - var a2 = new Isomorphisms.Matchers.SMARTS.AnyAtom(Default.ChemObjectBuilder.Instance); + var a2 = new Isomorphisms.Matchers.SMARTS.AnyAtom(ChemObjectBuilder.Instance); - IBond b1 = new OrderQueryBond(a1, a2, BondOrder.Single, Default.ChemObjectBuilder.Instance); + IBond b1 = new OrderQueryBond(a1, a2, BondOrder.Single, ChemObjectBuilder.Instance); - IQueryAtom a3 = new SymbolQueryAtom(Default.ChemObjectBuilder.Instance); + IQueryAtom a3 = new SymbolQueryAtom(ChemObjectBuilder.Instance); a3.Symbol = "C"; - IBond b2 = new OrderQueryBond(a2, a3, BondOrder.Single, Default.ChemObjectBuilder.Instance); + IBond b2 = new OrderQueryBond(a2, a3, BondOrder.Single, ChemObjectBuilder.Instance); query.Atoms.Add(a1); query.Atoms.Add(a2); query.Atoms.Add(a3); @@ -152,7 +152,7 @@ public void Test3() [TestMethod()] public void TestBasicQueryAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); // acetic acid anhydride IAtomContainer SMILESquery = sp.ParseSmiles("CC"); // acetic acid anhydride var query = QueryAtomContainerCreator.CreateBasicQueryContainer(SMILESquery); @@ -205,7 +205,7 @@ public void TestGetSubgraphMap_IAtomContainer_IAtomContainer() reader.Read(temp); query1 = QueryAtomContainerCreator.CreateBasicQueryContainer(temp); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("C1CCCCC1"); query2 = QueryAtomContainerCreator.CreateBasicQueryContainer(atomContainer); @@ -292,8 +292,8 @@ public void TestItself() { string smiles = "C1CCCCCCC1CC"; var query = QueryAtomContainerCreator.CreateAnyAtomContainer(new SmilesParser( - Default.ChemObjectBuilder.Instance).ParseSmiles(smiles), true); - IAtomContainer ac = new SmilesParser(Default.ChemObjectBuilder.Instance).ParseSmiles(smiles); + ChemObjectBuilder.Instance).ParseSmiles(smiles), true); + IAtomContainer ac = new SmilesParser(ChemObjectBuilder.Instance).ParseSmiles(smiles); if (standAlone) { Console.Out.WriteLine("AtomCount of query: " + query.Atoms.Count); @@ -325,7 +325,7 @@ public void TestIsIsomorph_IAtomContainer_IAtomContainer() [TestMethod()] public void TestAnyAtomAnyBondCase() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("O1C=CC=C1"); IAtomContainer queryac = sp.ParseSmiles("C1CCCC1"); var query = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(queryac, false); @@ -338,7 +338,7 @@ public void TestAnyAtomAnyBondCase() [TestMethod()] public void TestFirstArgumentMustNotBeAnQueryAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("O1C=CC=C1"); IAtomContainer queryac = sp.ParseSmiles("C1CCCC1"); var query = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(queryac, false); @@ -358,7 +358,7 @@ public void TestFirstArgumentMustNotBeAnQueryAtomContainer() [TestMethod()] public void TestSingleAtomMatching1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("[H]"); IAtomContainer queryac = sp.ParseSmiles("[H]"); var query = QueryAtomContainerCreator.CreateSymbolAndBondOrderQueryContainer(queryac); @@ -377,7 +377,7 @@ public void TestSingleAtomMatching1() [TestMethod()] public void TestSingleAtomMatching2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("CNC"); IAtomContainer queryac = sp.ParseSmiles("C"); var query = QueryAtomContainerCreator.CreateSymbolAndBondOrderQueryContainer(queryac); diff --git a/NCDKTests/SMSD/Algorithms/RGraph/CDKRGraphTest.cs b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRGraphTest.cs similarity index 96% rename from NCDKTests/SMSD/Algorithms/RGraph/CDKRGraphTest.cs rename to NCDKTests/SMSD/Algorithms/RGraphs/CDKRGraphTest.cs index 4e9d791b..774708c4 100644 --- a/NCDKTests/SMSD/Algorithms/RGraph/CDKRGraphTest.cs +++ b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRGraphTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { // @cdk.module test-smsd // @author Syed Asad Rahman diff --git a/NCDKTests/SMSD/Algorithms/RGraph/CDKRMapHandlerTest.cs b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRMapHandlerTest.cs similarity index 86% rename from NCDKTests/SMSD/Algorithms/RGraph/CDKRMapHandlerTest.cs rename to NCDKTests/SMSD/Algorithms/RGraphs/CDKRMapHandlerTest.cs index b81312aa..e30a4b31 100644 --- a/NCDKTests/SMSD/Algorithms/RGraph/CDKRMapHandlerTest.cs +++ b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRMapHandlerTest.cs @@ -21,11 +21,12 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; using NCDK.SMSD.Helper; using System.Collections.Generic; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { // @cdk.module test-smsd // @author Syed Asad Rahman @@ -42,7 +43,7 @@ public CDKRMapHandlerTest() { } [TestMethod()] public void TestGetSource() { - IAtomContainer expResult = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer expResult = ChemObjectBuilder.Instance.NewAtomContainer(); handler.Source = expResult; IAtomContainer result = handler.Source; Assert.AreEqual(expResult, result); @@ -54,7 +55,7 @@ public void TestGetSource() [TestMethod()] public void TestSetSource() { - IAtomContainer expResult = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer expResult = ChemObjectBuilder.Instance.NewAtomContainer(); handler.Source = expResult; IAtomContainer result = handler.Source; Assert.AreEqual(expResult, result); @@ -66,7 +67,7 @@ public void TestSetSource() [TestMethod()] public void TestGetTarget() { - IAtomContainer expResult = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer expResult = ChemObjectBuilder.Instance.NewAtomContainer(); handler.Target = expResult; IAtomContainer result = handler.Target; Assert.AreEqual(expResult, result); @@ -78,7 +79,7 @@ public void TestGetTarget() [TestMethod()] public void TestSetTarget() { - IAtomContainer expResult = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer expResult = ChemObjectBuilder.Instance.NewAtomContainer(); handler.Target = expResult; IAtomContainer result = handler.Target; Assert.AreEqual(expResult, result); @@ -90,7 +91,7 @@ public void TestSetTarget() [TestMethod()] public void TestCalculateOverlapsAndReduce() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser sp = new SmilesParser(builder); IAtomContainer Molecule1 = sp.ParseSmiles("O1C=CC=C1"); IAtomContainer Molecule2 = sp.ParseSmiles("C1CCCC1"); @@ -105,7 +106,7 @@ public void TestCalculateOverlapsAndReduce() [TestMethod()] public void TestCalculateOverlapsAndReduceExactMatch() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser sp = new SmilesParser(builder); IAtomContainer Molecule1 = sp.ParseSmiles("O1C=CC=C1"); IAtomContainer Molecule2 = sp.ParseSmiles("O1C=CC=C1"); @@ -121,7 +122,7 @@ public void TestCalculateOverlapsAndReduceExactMatch() [TestMethod()] public void TestGetMappings() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; SmilesParser sp = new SmilesParser(builder); IAtomContainer Molecule1 = sp.ParseSmiles("O1C=CC=C1"); IAtomContainer Molecule2 = sp.ParseSmiles("O1C=CC=C1"); @@ -137,14 +138,17 @@ public void TestGetMappings() [TestMethod()] public void TestSetMappings() { - var map = new SortedDictionary(); - map[0] = 0; - map[1] = 1; + var map = new SortedDictionary + { + [0] = 0, + [1] = 1 + }; + var mappings = new List> { map }; - var mappings = new List>(); - mappings.Add(map); - CDKRMapHandler instance = new CDKRMapHandler(); - instance.Mappings = mappings; + CDKRMapHandler instance = new CDKRMapHandler + { + Mappings = mappings + }; Assert.IsNotNull(instance.Mappings); } diff --git a/NCDKTests/SMSD/Algorithms/RGraph/CDKRMapTest.cs b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRMapTest.cs similarity index 97% rename from NCDKTests/SMSD/Algorithms/RGraph/CDKRMapTest.cs rename to NCDKTests/SMSD/Algorithms/RGraphs/CDKRMapTest.cs index c36a0a32..0fbe37ef 100644 --- a/NCDKTests/SMSD/Algorithms/RGraph/CDKRMapTest.cs +++ b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRMapTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { // @cdk.module test-smsd // @author Syed Asad Rahman diff --git a/NCDKTests/SMSD/Algorithms/RGraph/CDKRNodeTest.cs b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRNodeTest.cs similarity index 97% rename from NCDKTests/SMSD/Algorithms/RGraph/CDKRNodeTest.cs rename to NCDKTests/SMSD/Algorithms/RGraphs/CDKRNodeTest.cs index f6b06a6b..ac210d7d 100644 --- a/NCDKTests/SMSD/Algorithms/RGraph/CDKRNodeTest.cs +++ b/NCDKTests/SMSD/Algorithms/RGraphs/CDKRNodeTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.SMSD.Algorithms.RGraph +namespace NCDK.SMSD.Algorithms.RGraphs { // @cdk.module test-smsd // @author Syed Asad Rahman diff --git a/NCDKTests/SMSD/Algorithms/Single/SingleMappingHandlerTest.cs b/NCDKTests/SMSD/Algorithms/Singles/SingleMappingHandlerTest.cs similarity index 99% rename from NCDKTests/SMSD/Algorithms/Single/SingleMappingHandlerTest.cs rename to NCDKTests/SMSD/Algorithms/Singles/SingleMappingHandlerTest.cs index b4094274..ab3a7868 100644 --- a/NCDKTests/SMSD/Algorithms/Single/SingleMappingHandlerTest.cs +++ b/NCDKTests/SMSD/Algorithms/Singles/SingleMappingHandlerTest.cs @@ -19,13 +19,14 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.SMSD.Tools; using System.IO; -namespace NCDK.SMSD.Algorithms.Single +namespace NCDK.SMSD.Algorithms.Singles { /// /// Unit testing for the class. diff --git a/NCDKTests/SMSD/Algorithms/Single/SingleMappingTest.cs b/NCDKTests/SMSD/Algorithms/Singles/SingleMappingTest.cs similarity index 97% rename from NCDKTests/SMSD/Algorithms/Single/SingleMappingTest.cs rename to NCDKTests/SMSD/Algorithms/Singles/SingleMappingTest.cs index b86e16ca..aa16eea2 100644 --- a/NCDKTests/SMSD/Algorithms/Single/SingleMappingTest.cs +++ b/NCDKTests/SMSD/Algorithms/Singles/SingleMappingTest.cs @@ -20,10 +20,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; -namespace NCDK.SMSD.Algorithms.Single +namespace NCDK.SMSD.Algorithms.Singles { // @author Syed Asad Rahman // @cdk.module test-smsd diff --git a/NCDKTests/SMSD/Algorithms/VFLib/Molecules.cs b/NCDKTests/SMSD/Algorithms/VFLib/Molecules.cs index c3efc4ff..7e4db042 100644 --- a/NCDKTests/SMSD/Algorithms/VFLib/Molecules.cs +++ b/NCDKTests/SMSD/Algorithms/VFLib/Molecules.cs @@ -45,7 +45,7 @@ * THE SOFTWARE. */ using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; using NCDK.Tools.Manipulator; @@ -63,20 +63,20 @@ public class Molecules { public static IAtomContainer Create4Toluene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("C"); c7.Id = "7"; result.Atoms.Add(c1); @@ -113,8 +113,8 @@ public static IAtomContainer Create4Toluene() public static IAtomContainer CreateMethane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); CDKHydrogenAdder adder = CDKHydrogenAdder.GetInstance(result.Builder); adder.AddImplicitHydrogens(result); @@ -124,7 +124,7 @@ public static IAtomContainer CreateMethane() public static IAtomContainer CreatePropane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); IAtom c1 = result.Builder.NewAtom("C"); IAtom c2 = result.Builder.NewAtom("C"); IAtom c3 = result.Builder.NewAtom("C"); @@ -149,19 +149,19 @@ public static IAtomContainer CreatePropane() public static IAtomContainer CreateHexane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -193,19 +193,19 @@ public static IAtomContainer CreateHexane() public static IAtomContainer CreateBenzene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -239,27 +239,27 @@ public static IAtomContainer CreateBenzene() public static IAtomContainer CreateNaphthalene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "7"; - IAtom c8 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c8 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "8"; - IAtom c9 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c9 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "9"; - IAtom c10 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c10 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "10"; result.Atoms.Add(c1); @@ -307,7 +307,7 @@ public static IAtomContainer CreateNaphthalene() public static IAtomContainer CreatePyridazine() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "C1=CN=NC=C1"; IAtomContainer result = sp.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(result); @@ -319,7 +319,7 @@ public static IAtomContainer CreatePyridazine() public static IAtomContainer CreateChloroIsoquinoline4() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "ClC1=CC=NC2=C1C=CC=C2"; IAtomContainer result = sp.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(result); @@ -331,7 +331,7 @@ public static IAtomContainer CreateChloroIsoquinoline4() public static IAtomContainer CreateChlorobenzene() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "Clc1ccccc1"; IAtomContainer result = sp.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(result); @@ -343,15 +343,15 @@ public static IAtomContainer CreateChlorobenzene() public static IAtomContainer CreateAcetone() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("O"); c4.Id = "4"; result.Atoms.Add(c1); @@ -394,22 +394,22 @@ public static IAtomContainer CreateAcetone() public static IAtomContainer CreateCubane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("C"); c7.Id = "7"; - IAtom c8 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c8 = ChemObjectBuilder.Instance.NewAtom("C"); c8.Id = "8"; result.Atoms.Add(c1); @@ -498,19 +498,19 @@ public static IAtomContainer CreateCubane() public static IAtomContainer CreatePyridine() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("N"); c6.Id = "6"; result.Atoms.Add(c1); @@ -543,21 +543,21 @@ public static IAtomContainer CreatePyridine() public static IAtomContainer CreateToluene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "7"; result.Atoms.Add(c1); @@ -595,21 +595,21 @@ public static IAtomContainer CreateToluene() public static IAtomContainer CreatePhenol() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("O"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("O"); c6.Id = "7"; result.Atoms.Add(c1); @@ -647,19 +647,19 @@ public static IAtomContainer CreatePhenol() public static IAtomContainer CreateCyclohexane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -693,11 +693,11 @@ public static IAtomContainer CreateCyclohexane() public static IAtomContainer CreateCyclopropane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); result.Atoms.Add(c2); @@ -721,12 +721,12 @@ public static IAtomContainer CreateCyclopropane() public static IAtomContainer CreateIsobutane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); result.Atoms.Add(c2); @@ -809,10 +809,10 @@ public static IAtomContainer CreateIsobutane() // } public static IAtomContainer CreateSimpleImine() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("N"); result.Atoms.Add(c1); result.Atoms.Add(c2); @@ -834,10 +834,10 @@ public static IAtomContainer CreateSimpleImine() public static IAtomContainer CreateSimpleAmine() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("N"); result.Atoms.Add(c1); result.Atoms.Add(c2); diff --git a/NCDKTests/SMSD/Algorithms/VFLib/VFLibTest.cs b/NCDKTests/SMSD/Algorithms/VFLib/VFLibTest.cs index f8f5855b..cb16fa9a 100644 --- a/NCDKTests/SMSD/Algorithms/VFLib/VFLibTest.cs +++ b/NCDKTests/SMSD/Algorithms/VFLib/VFLibTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.SMSD.Algorithms.VFLib.Builder; using NCDK.SMSD.Algorithms.VFLib.Map; using NCDK.SMSD.Algorithms.VFLib.Query; @@ -119,7 +119,7 @@ public void TestItShouldMapAllAtomsInTheSecondaryState() Match match1 = new Match(benzeneQuery.GetNode(1), benzene.Atoms[1]); IState state2 = state1.NextState(match1); - IDictionary map = state2.GetMap(); + var map = state2.GetMap(); Assert.AreEqual(2, map.Count); Assert.AreEqual(benzene.Atoms[0], map[benzeneQuery.GetNode(0)]); @@ -156,7 +156,7 @@ public void TestItShouldMapAllAtomsInTheTertiaryState() IState state2 = state1.NextState(match1); Match match2 = new Match(benzeneQuery.GetNode(2), benzene.Atoms[2]); IState state3 = state2.NextState(match2); - IDictionary map = state3.GetMap(); + var map = state3.GetMap(); Assert.AreEqual(3, map.Count); Assert.AreEqual(benzene.Atoms[0], map[benzeneQuery.GetNode(0)]); @@ -205,18 +205,18 @@ public void TestItShouldMatchHexaneToHexaneWhenUsingMolecule() public static IAtomContainer CreateHexane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -245,19 +245,19 @@ public static IAtomContainer CreateHexane() public static IAtomContainer CreateBenzene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); diff --git a/NCDKTests/SMSD/Algorithms/VFLib/VFlibMCSHandlerTest.cs b/NCDKTests/SMSD/Algorithms/VFLib/VFlibMCSHandlerTest.cs index 5b581bd0..99521d9c 100644 --- a/NCDKTests/SMSD/Algorithms/VFLib/VFlibMCSHandlerTest.cs +++ b/NCDKTests/SMSD/Algorithms/VFLib/VFlibMCSHandlerTest.cs @@ -20,7 +20,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.SMSD.Tools; @@ -47,7 +47,7 @@ public VFlibMCSHandlerTest() { } [TestMethod()] public override void TestSearchMCS() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = null; try { @@ -81,7 +81,7 @@ public override void TestSearchMCS() [TestMethod()] public void TestSet_IAtomContainer_IAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -126,7 +126,7 @@ public void TestSet_String_String() [TestMethod()] public void TestSet_MolHandler_MolHandler() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target1 = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -144,7 +144,7 @@ public void TestSet_MolHandler_MolHandler() [TestMethod()] public void TestGetAllAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -164,7 +164,7 @@ public void TestGetAllAtomMapping() [TestMethod()] public void TestGetAllMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -184,7 +184,7 @@ public void TestGetAllMapping() [TestMethod()] public void TestGetFirstAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -204,7 +204,7 @@ public void TestGetFirstAtomMapping() [TestMethod()] public void TestGetFirstMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); diff --git a/NCDKTests/SMSD/Algorithms/VFLib/VFlibTurboHandlerTest.cs b/NCDKTests/SMSD/Algorithms/VFLib/VFlibTurboHandlerTest.cs index ffe7b8dc..2c23f417 100644 --- a/NCDKTests/SMSD/Algorithms/VFLib/VFlibTurboHandlerTest.cs +++ b/NCDKTests/SMSD/Algorithms/VFLib/VFlibTurboHandlerTest.cs @@ -20,8 +20,9 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.SMSD.Tools; @@ -42,7 +43,7 @@ public VFlibTurboHandlerTest() { } [TestMethod()] public override void TestIsSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -59,7 +60,7 @@ public override void TestIsSubgraph() [TestMethod()] public void TestSet_IAtomContainer_IAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -101,7 +102,7 @@ public void TestSet_String_String() [TestMethod()] public void TestSet_MolHandler_MolHandler() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target1 = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -118,7 +119,7 @@ public void TestSet_MolHandler_MolHandler() [TestMethod()] public void TestGetAllAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -137,7 +138,7 @@ public void TestGetAllAtomMapping() [TestMethod()] public void TestGetAllMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -156,7 +157,7 @@ public void TestGetAllMapping() [TestMethod()] public void TestGetFirstAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -175,7 +176,7 @@ public void TestGetFirstAtomMapping() [TestMethod()] public void TestGetFirstMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); diff --git a/NCDKTests/SMSD/Factory/SubStructureSearchAlgorithmsTest.cs b/NCDKTests/SMSD/Factory/SubStructureSearchAlgorithmsTest.cs index 8b48a3e1..8844f03d 100644 --- a/NCDKTests/SMSD/Factory/SubStructureSearchAlgorithmsTest.cs +++ b/NCDKTests/SMSD/Factory/SubStructureSearchAlgorithmsTest.cs @@ -21,6 +21,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -51,7 +52,7 @@ public void TestSubStructureSearchAlgorithms() [TestMethod()] public void TestInit_3args_1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -68,7 +69,7 @@ public void TestInit_3args_1() [TestMethod()] public void TestInit_3args_2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -87,7 +88,7 @@ public void TestInit_3args_3() { // string sourceMolFileName = ""; // string targetMolFileName = ""; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -104,7 +105,7 @@ public void TestInit_3args_3() [TestMethod()] public void TestSetChemFilters() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -120,7 +121,7 @@ public void TestSetChemFilters() [TestMethod()] public void TestGetFragmentSize() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -137,7 +138,7 @@ public void TestGetFragmentSize() [TestMethod()] public void TestGetStereoScore() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -154,7 +155,7 @@ public void TestGetStereoScore() [TestMethod()] public void TestGetEnergyScore() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -171,7 +172,7 @@ public void TestGetEnergyScore() [TestMethod()] public void TestGetFirstMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -188,7 +189,7 @@ public void TestGetFirstMapping() [TestMethod()] public void TestGetAllMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -210,7 +211,7 @@ public void TestGetAllMapping() [TestMethod()] public void TestGetFirstAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -227,7 +228,7 @@ public void TestGetFirstAtomMapping() [TestMethod()] public void TestGetAllAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -249,7 +250,7 @@ public void TestGetAllAtomMapping() [TestMethod()] public void TestGetReactantMolecule() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -266,7 +267,7 @@ public void TestGetReactantMolecule() [TestMethod()] public void TestGetProductMolecule() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -283,7 +284,7 @@ public void TestGetProductMolecule() [TestMethod()] public void TestGetTanimotoSimilarity() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -301,7 +302,7 @@ public void TestGetTanimotoSimilarity() [TestMethod()] public void TestIsStereoMisMatch() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -317,7 +318,7 @@ public void TestIsStereoMisMatch() [TestMethod()] public void TestIsSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -333,7 +334,7 @@ public void TestIsSubgraph() [TestMethod()] public void TestGetEuclideanDistance() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); diff --git a/NCDKTests/SMSD/Filters/ChemicalFiltersTest.cs b/NCDKTests/SMSD/Filters/ChemicalFiltersTest.cs index 783dc4e4..5d95d11f 100644 --- a/NCDKTests/SMSD/Filters/ChemicalFiltersTest.cs +++ b/NCDKTests/SMSD/Filters/ChemicalFiltersTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; using System.Collections.Generic; using System.Linq; @@ -40,7 +41,7 @@ public ChemicalFiltersTest() { } [TestMethod()] public void TestSortResultsByStereoAndBondMatch() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -61,7 +62,7 @@ public void TestSortResultsByStereoAndBondMatch() [TestMethod()] public void TestSortResultsByFragments() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -82,7 +83,7 @@ public void TestSortResultsByFragments() [TestMethod()] public void TestSortResultsByEnergies() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -163,7 +164,7 @@ private static bool AreOrderedEqual(IEnumerable> expect [TestMethod()] public void TestGetSortedEnergy() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -180,7 +181,7 @@ public void TestGetSortedEnergy() [TestMethod()] public void TestGetSortedFragment() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -197,7 +198,7 @@ public void TestGetSortedFragment() [TestMethod()] public void TestGetStereoMatches() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); diff --git a/NCDKTests/SMSD/Filters/PostFilterTest.cs b/NCDKTests/SMSD/Filters/PostFilterTest.cs index 5b5aff58..9fb1d3d4 100644 --- a/NCDKTests/SMSD/Filters/PostFilterTest.cs +++ b/NCDKTests/SMSD/Filters/PostFilterTest.cs @@ -20,6 +20,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; @@ -38,34 +39,42 @@ public PostFilterTest() { } [TestMethod()] public void TestFilter() { - List l1 = new List(6); - l1.Add(1); - l1.Add(2); - l1.Add(3); - l1.Add(4); - l1.Add(5); - l1.Add(6); + List l1 = new List(6) + { + 1, + 2, + 3, + 4, + 5, + 6 + }; - List l2 = new List(6); - l2.Add(1); - l2.Add(2); - l2.Add(3); - l2.Add(4); - l2.Add(5); - l2.Add(6); + List l2 = new List(6) + { + 1, + 2, + 3, + 4, + 5, + 6 + }; - List l3 = new List(6); - l3.Add(1); - l3.Add(2); - l3.Add(5); - l3.Add(4); - l3.Add(3); - l3.Add(6); + List l3 = new List(6) + { + 1, + 2, + 5, + 4, + 3, + 6 + }; - var mappings = new List>(); - mappings.Add(l1); - mappings.Add(l2); - mappings.Add(l3); + var mappings = new List> + { + l1, + l2, + l3 + }; Assert.AreEqual(3, mappings.Count); var expResult = PostFilter.Filter(mappings); diff --git a/NCDKTests/SMSD/Global/TimeOutTest.cs b/NCDKTests/SMSD/Globals/TimeOutTest.cs similarity index 99% rename from NCDKTests/SMSD/Global/TimeOutTest.cs rename to NCDKTests/SMSD/Globals/TimeOutTest.cs index 559bdafe..e299251a 100644 --- a/NCDKTests/SMSD/Global/TimeOutTest.cs +++ b/NCDKTests/SMSD/Globals/TimeOutTest.cs @@ -21,7 +21,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.SMSD.Global +namespace NCDK.SMSD.Globals { /// /// Unit testing for the class. diff --git a/NCDKTests/SMSD/Helper/FinalMappingsTest.cs b/NCDKTests/SMSD/Helper/FinalMappingsTest.cs index b6bb37a8..5ebe8528 100644 --- a/NCDKTests/SMSD/Helper/FinalMappingsTest.cs +++ b/NCDKTests/SMSD/Helper/FinalMappingsTest.cs @@ -50,7 +50,7 @@ public void TestInstance() [TestMethod()] public void TestAdd() { - IDictionary mapping = new SortedDictionary(); + var mapping = new SortedDictionary(); mapping[1] = 1; mapping[2] = 2; mapping[3] = 3; @@ -66,16 +66,16 @@ public void TestAdd() [TestMethod()] public void TestSet() { - IDictionary mapping1 = new SortedDictionary(); + var mapping1 = new SortedDictionary(); mapping1[1] = 1; mapping1[2] = 2; mapping1[3] = 3; - IDictionary mapping2 = new SortedDictionary(); + var mapping2 = new SortedDictionary(); mapping2[1] = 2; mapping2[2] = 1; mapping2[3] = 3; - List> mappings = new List>(2); + var mappings = new List>(2); mappings.Add(mapping1); mappings.Add(mapping2); FinalMappings instance = new FinalMappings(); @@ -90,16 +90,16 @@ public void TestSet() [TestMethod()] public void TestGetIterator() { - IDictionary mapping1 = new SortedDictionary(); + var mapping1 = new SortedDictionary(); mapping1[1] = 1; mapping1[2] = 2; mapping1[3] = 3; - IDictionary mapping2 = new SortedDictionary(); + var mapping2 = new SortedDictionary(); mapping2[1] = 2; mapping2[2] = 1; mapping2[3] = 3; - List> mappings = new List>(2); + var mappings = new List>(2); mappings.Add(mapping1); mappings.Add(mapping2); FinalMappings instance = new FinalMappings(); @@ -114,16 +114,16 @@ public void TestGetIterator() [TestMethod()] public void TestClear() { - IDictionary mapping1 = new SortedDictionary(); + var mapping1 = new SortedDictionary(); mapping1[1] = 1; mapping1[2] = 2; mapping1[3] = 3; - IDictionary mapping2 = new SortedDictionary(); + var mapping2 = new SortedDictionary(); mapping2[1] = 2; mapping2[2] = 1; mapping2[3] = 3; - List> mappings = new List>(2); + var mappings = new List>(2); mappings.Add(mapping1); mappings.Add(mapping2); FinalMappings instance = new FinalMappings(); @@ -139,16 +139,16 @@ public void TestClear() [TestMethod()] public void TestGetFinalMapping() { - IDictionary mapping1 = new SortedDictionary(); + var mapping1 = new SortedDictionary(); mapping1[1] = 1; mapping1[2] = 2; mapping1[3] = 3; - IDictionary mapping2 = new SortedDictionary(); + var mapping2 = new SortedDictionary(); mapping2[1] = 2; mapping2[2] = 1; mapping2[3] = 3; - List> mappings = new List>(2); + var mappings = new List>(2); mappings.Add(mapping1); mappings.Add(mapping2); FinalMappings instance = new FinalMappings(); @@ -165,16 +165,20 @@ public void TestGetFinalMapping() [TestMethod()] public void TestGetSize() { - IDictionary mapping1 = new SortedDictionary(); - mapping1[1] = 1; - mapping1[2] = 2; - mapping1[3] = 3; - IDictionary mapping2 = new SortedDictionary(); - mapping2[1] = 2; - mapping2[2] = 1; - mapping2[3] = 3; - - List> mappings = new List>(2); + var mapping1 = new SortedDictionary + { + [1] = 1, + [2] = 2, + [3] = 3 + }; + var mapping2 = new SortedDictionary + { + [1] = 2, + [2] = 1, + [3] = 3 + }; + + var mappings = new List>(2); mappings.Add(mapping1); mappings.Add(mapping2); FinalMappings instance = new FinalMappings(); diff --git a/NCDKTests/SMSD/Helper/MolHandlerTest.cs b/NCDKTests/SMSD/Helper/MolHandlerTest.cs index 08261346..061051d7 100644 --- a/NCDKTests/SMSD/Helper/MolHandlerTest.cs +++ b/NCDKTests/SMSD/Helper/MolHandlerTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.SMSD.Tools; namespace NCDK.SMSD.Helper diff --git a/NCDKTests/SMSD/Ring/HanserRingFinderTest.cs b/NCDKTests/SMSD/Rings/HanserRingFinderTest.cs similarity index 99% rename from NCDKTests/SMSD/Ring/HanserRingFinderTest.cs rename to NCDKTests/SMSD/Rings/HanserRingFinderTest.cs index 2052a079..9ccd86d8 100644 --- a/NCDKTests/SMSD/Ring/HanserRingFinderTest.cs +++ b/NCDKTests/SMSD/Rings/HanserRingFinderTest.cs @@ -24,7 +24,7 @@ using NCDK.SMSD.Algorithms.VFLib; using System.Linq; -namespace NCDK.SMSD.Ring +namespace NCDK.SMSD.Rings { // @author Syed Asad Rahman // @cdk.module test-smsd diff --git a/NCDKTests/SMSD/SMSDBondInsensitiveTest.cs b/NCDKTests/SMSD/SMSDBondInsensitiveTest.cs index dd7ab278..9dd9a6d9 100644 --- a/NCDKTests/SMSD/SMSDBondInsensitiveTest.cs +++ b/NCDKTests/SMSD/SMSDBondInsensitiveTest.cs @@ -23,7 +23,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.SMSD.Tools; using NCDK.Tools.Manipulator; @@ -168,7 +168,7 @@ public void TestCyclopropaneNotASubgraphOfIsoButane() [TestMethod()] public void TestSingleMappingTesting() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("C"); IAtomContainer mol2 = Create4Toluene(); @@ -196,7 +196,7 @@ public void TestSingleMappingTesting() [TestMethod()] public void TestSMSDFragHetSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string file1 = "O=C1NC(=O)C2=C(N1)NC(=O)C=N2"; string file2 = "OC[C@@H](O)[C@@H](O)[C@@H](O)CN1C(O)C(CCC(O)O)NC2C(O)NC(O)NC12"; @@ -230,20 +230,20 @@ public void TestSMSDFragHetSubgraph() private IAtomContainer Create4Toluene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("C"); c7.Id = "7"; result.Atoms.Add(c1); @@ -277,8 +277,8 @@ private IAtomContainer Create4Toluene() public IAtomContainer CreateMethane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); return result; @@ -286,10 +286,10 @@ public IAtomContainer CreateMethane() public IAtomContainer CreatePropane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); result.Atoms.Add(c2); @@ -306,19 +306,19 @@ public IAtomContainer CreatePropane() public IAtomContainer CreateHexane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -347,19 +347,19 @@ public IAtomContainer CreateHexane() public static IAtomContainer CreateBenzene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -451,27 +451,27 @@ public static IAtomContainer CreateBenzene() public static IAtomContainer CreateNaphthalene() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; - IAtom c7 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c7 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "7"; - IAtom c8 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c8 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "8"; - IAtom c9 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c9 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "9"; - IAtom c10 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c10 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "10"; result.Atoms.Add(c1); @@ -614,19 +614,19 @@ public static IAtomContainer CreateNaphthalene() public static IAtomContainer CreateCyclohexane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); c1.Id = "1"; - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); c2.Id = "2"; - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); c3.Id = "3"; - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); c4.Id = "4"; - IAtom c5 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c5 = ChemObjectBuilder.Instance.NewAtom("C"); c5.Id = "5"; - IAtom c6 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c6 = ChemObjectBuilder.Instance.NewAtom("C"); c6.Id = "6"; result.Atoms.Add(c1); @@ -658,11 +658,11 @@ public static IAtomContainer CreateCyclohexane() public static IAtomContainer CreateCyclopropane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); result.Atoms.Add(c2); @@ -681,12 +681,12 @@ public static IAtomContainer CreateCyclopropane() public static IAtomContainer CreateIsobutane() { - IAtomContainer result = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer result = ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom c1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c2 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom c4 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c2 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c3 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom c4 = ChemObjectBuilder.Instance.NewAtom("C"); result.Atoms.Add(c1); result.Atoms.Add(c2); diff --git a/NCDKTests/SMSD/SMSDBondSensitiveTest.cs b/NCDKTests/SMSD/SMSDBondSensitiveTest.cs index bfc3b62f..a58d7e8e 100644 --- a/NCDKTests/SMSD/SMSDBondSensitiveTest.cs +++ b/NCDKTests/SMSD/SMSDBondSensitiveTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.Isomorphisms.Matchers; +using NCDK.Silent; using NCDK.Smiles; using NCDK.SMSD.Algorithms.VFLib; using NCDK.SMSD.Tools; @@ -56,7 +57,7 @@ public void TestSubgraph() public void TestMatchCount() { Isomorphism smsd = new Isomorphism(Algorithm.VFLibMCS, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -214,7 +215,7 @@ public void TestSMSDChemicalFilters() // [TestMethod()] // public void TestSingleMappingTesting() { // - // SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + // SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); // IAtomContainer atomContainer = sp.ParseSmiles("C"); // IQueryAtomContainer query = QueryAtomContainerCreator.CreateBasicQueryContainer(atomContainer); // @@ -245,7 +246,7 @@ public void TestSMSDChemicalFilters() [TestCategory("SlowTest")] public void TestSMSDAdpAtpSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string adp = "NC1=NC=NC2=C1N=CN2[C@@H]1O[C@H](COP(O)(=O)OP(O)(O)=O)[C@@H](O)[C@H]1O"; string atp = "NC1=NC=NC2=C1N=CN2[C@@H]1O[C@H](COP(O)(=O)OP(O)(=O)OP(O)(O)=O)[C@@H](O)[C@H]1O"; IAtomContainer mol1 = sp.ParseSmiles(adp); @@ -279,7 +280,7 @@ public void TestSMSDAdpAtpSubgraph() [TestCategory("SlowTest")] public void TestSMSDLargeSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string c03374 = "CC1=C(C=C)\\C(NC1=O)=C" + "\\C1=C(C)C(CCC(=O)O[C@@H]2O[C@@H]" + "([C@@H](O)[C@H](O)[C@H]2O)C(O)=O)" + "=C(CC2=C(CCC(O)=O)C(C)=C(N2)" + "\\C=C2NC(=O)C(C=C)=C/2C)N1"; diff --git a/NCDKTests/SMSD/SMSDTest.cs b/NCDKTests/SMSD/SMSDTest.cs index 71029312..2b429068 100644 --- a/NCDKTests/SMSD/SMSDTest.cs +++ b/NCDKTests/SMSD/SMSDTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Isomorphisms.Matchers; using NCDK.Smiles; @@ -46,7 +46,7 @@ public SMSDTest() { } [TestMethod()] public void TestInit_3args_1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -63,7 +63,7 @@ public void TestInit_3args_1() [TestMethod()] public void TestInit_3args_2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -82,7 +82,7 @@ public void TestSearchMCS() { try { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = null; target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); @@ -110,7 +110,7 @@ public void TestSearchMCS() [TestMethod()] public void TestSet_IAtomContainer_IAtomContainer() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -152,7 +152,7 @@ public void TestSet_String_String() [TestMethod()] public void TestSet_MolHandler_MolHandler() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target1 = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -170,7 +170,7 @@ public void TestSet_MolHandler_MolHandler() [TestMethod()] public void TestGetAllAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -200,7 +200,7 @@ public void TestGetAllAtomMapping() [TestMethod()] public void TestGetAllMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -223,7 +223,7 @@ public void TestGetAllMapping() [TestMethod()] public void TestGetFirstAtomMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -241,7 +241,7 @@ public void TestGetFirstAtomMapping() [TestMethod()] public void TestGetFirstMapping() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -259,7 +259,7 @@ public void TestGetFirstMapping() [TestMethod()] public void TestSetChemFilters() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -275,7 +275,7 @@ public void TestSetChemFilters() [TestMethod()] public void TestGetFragmentSize() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -292,7 +292,7 @@ public void TestGetFragmentSize() [TestMethod()] public void TestGetStereoScore() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/OCC=C"); IAtomContainer queryac = sp.ParseSmiles("CCCOCC(C)=C"); @@ -309,7 +309,7 @@ public void TestGetStereoScore() [TestMethod()] public void TestGetEnergyScore() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -326,7 +326,7 @@ public void TestGetEnergyScore() [TestMethod()] public void TestGetReactantMolecule() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -343,7 +343,7 @@ public void TestGetReactantMolecule() [TestMethod()] public void TestGetProductMolecule() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -360,7 +360,7 @@ public void TestGetProductMolecule() [TestMethod()] public void TestGetTanimotoSimilarity() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -378,7 +378,7 @@ public void TestGetTanimotoSimilarity() [TestMethod()] public void TestIsStereoMisMatch() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -394,7 +394,7 @@ public void TestIsStereoMisMatch() [TestMethod()] public void TestIsSubgraph() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -410,7 +410,7 @@ public void TestIsSubgraph() [TestMethod()] public void TestGetEuclideanDistance() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer target = sp.ParseSmiles("C\\C=C/Nc1cccc(c1)N(O)\\C=C\\C\\C=C\\C=C/C"); IAtomContainer queryac = sp.ParseSmiles("Nc1ccccc1"); @@ -432,7 +432,7 @@ public void TestGetEuclideanDistance() public void TestQueryAtomContainerDefault() { Isomorphism smsd = new Isomorphism(Algorithm.Default, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -450,7 +450,7 @@ public void TestQueryAtomContainerDefault() public void TestQueryAtomContainerMCSPLUS() { Isomorphism smsd = new Isomorphism(Algorithm.MCSPlus, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -467,7 +467,7 @@ public void TestQueryAtomContainerMCSPLUS() [TestMethod()] public void TestQueryAtomContainerSubstructure() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -496,7 +496,7 @@ public void TestQueryAtomContainerSubstructure() public void TestQueryAtomCount() { Isomorphism smsd = new Isomorphism(Algorithm.Default, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -515,7 +515,7 @@ public void TestQueryAtomCount() public void TestMatchCount() { Isomorphism smsd = new Isomorphism(Algorithm.Default, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -534,7 +534,7 @@ public void TestMatchCount() public void TestMatchCountCDKMCS() { Isomorphism smsd = new Isomorphism(Algorithm.CDKMCS, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C1CCC12CCCC2"); @@ -553,7 +553,7 @@ public void TestMatchCountCDKMCS() public void TestImpossibleQuery() { Isomorphism smsd = new Isomorphism(Algorithm.Default, true); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer query = sp.ParseSmiles("CC"); IAtomContainer target = sp.ParseSmiles("C"); diff --git a/NCDKTests/SMSD/Tools/BondEnergiesTest.cs b/NCDKTests/SMSD/Tools/BondEnergiesTest.cs index 0336fc5c..5439a07e 100644 --- a/NCDKTests/SMSD/Tools/BondEnergiesTest.cs +++ b/NCDKTests/SMSD/Tools/BondEnergiesTest.cs @@ -21,7 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.SMSD.Tools { diff --git a/NCDKTests/SMSD/Tools/ExtAtomContainerManipulatorTest.cs b/NCDKTests/SMSD/Tools/ExtAtomContainerManipulatorTest.cs index 54f25fa6..09adef05 100644 --- a/NCDKTests/SMSD/Tools/ExtAtomContainerManipulatorTest.cs +++ b/NCDKTests/SMSD/Tools/ExtAtomContainerManipulatorTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; using System; @@ -40,7 +41,7 @@ public ExtAtomContainerManipulatorTest() { } public void TestMakeDeepCopy() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer container = sp.ParseSmiles(rawMolSmiles); int counter = 0; @@ -64,7 +65,7 @@ public void TestMakeDeepCopy() public void TestAromatizeMolecule() { string rawMolSmiles = "C1=CC2=C(C=C1)C=CC=C2"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles(rawMolSmiles); ExtAtomContainerManipulator.AromatizeMolecule(mol); int count = 0; @@ -85,7 +86,7 @@ public void TestAromatizeMolecule() public void TestGetExplicitHydrogenCount() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom atom = null; foreach (var a in atomContainer.Atoms) @@ -109,7 +110,7 @@ public void TestGetExplicitHydrogenCount() public void TestGetImplicitHydrogenCount() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom atom = null; foreach (var a in atomContainer.Atoms) @@ -133,7 +134,7 @@ public void TestGetImplicitHydrogenCount() public void TestGetHydrogenCount() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom atom = null; foreach (var a in atomContainer.Atoms) @@ -156,7 +157,7 @@ public void TestGetHydrogenCount() public void TestRemoveHydrogensAndPreserveAtomID() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); IAtom beforeAtom = null; IAtom afterAtom = null; @@ -190,7 +191,7 @@ public void TestRemoveHydrogensAndPreserveAtomID() public void TestConvertExplicitToImplicitHydrogens() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); int expResult = 11; IAtomContainer result = ExtAtomContainerManipulator.ConvertExplicitToImplicitHydrogens(atomContainer); @@ -204,7 +205,7 @@ public void TestConvertExplicitToImplicitHydrogens() public void TestPercieveAtomTypesAndConfigureAtoms() { string rawMolSmiles = "[H]POOSC(Br)C(Cl)C(F)I"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(rawMolSmiles); ExtAtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(atomContainer); Assert.IsNotNull(atomContainer); diff --git a/NCDKTests/SMSD/Tools/MoleculeSanityCheckTest.cs b/NCDKTests/SMSD/Tools/MoleculeSanityCheckTest.cs index 78b2e5c5..c6249469 100644 --- a/NCDKTests/SMSD/Tools/MoleculeSanityCheckTest.cs +++ b/NCDKTests/SMSD/Tools/MoleculeSanityCheckTest.cs @@ -21,6 +21,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using NCDK.Smiles; namespace NCDK.SMSD.Tools @@ -39,7 +40,7 @@ public MoleculeSanityCheckTest() { } public void TestCheckAndCleanMolecule() { string fragmentMolSmiles = "C1=CC=CC=C1.C1=CC2=C(C=C1)C=CC=C2"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = sp.ParseSmiles(fragmentMolSmiles); IAtomContainer expResult = sp.ParseSmiles("C1=CC2=C(C=C1)C=CC=C2"); IAtomContainer result = MoleculeSanityCheck.CheckAndCleanMolecule(molecule); @@ -53,7 +54,7 @@ public void TestCheckAndCleanMolecule() public void TestFixAromaticity() { string rawMolSmiles = "C1=CC2=C(C=C1)C=CC=C2"; - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles(rawMolSmiles); MoleculeSanityCheck.CheckAndCleanMolecule(mol); int count = 0; diff --git a/NCDKTests/Signatures/MoleculeSignatureTest.cs b/NCDKTests/Signatures/MoleculeSignatureTest.cs index 382c62fa..7f668d66 100644 --- a/NCDKTests/Signatures/MoleculeSignatureTest.cs +++ b/NCDKTests/Signatures/MoleculeSignatureTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.FaulonSignatures; using NCDK.Graphs; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; using System.Collections.Generic; @@ -42,8 +43,8 @@ public class MoleculeSignatureTest : CDKTestCase public MoleculeSignatureTest() { - this.parser = new SmilesParser(Default.ChemObjectBuilder.Instance); - this.builder = Default.ChemObjectBuilder.Instance; + this.parser = new SmilesParser(ChemObjectBuilder.Instance); + this.builder = ChemObjectBuilder.Instance; mol = builder.NewAtomContainer(); mol.Atoms.Add(builder.NewAtom("C")); mol.Atoms.Add(builder.NewAtom("C")); @@ -148,7 +149,7 @@ public void AddHydrogens(IAtomContainer mol, IAtom atom, int n) [TestMethod()] public void TestEmpty() { - IAtomContainer mol = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol = ChemObjectBuilder.Instance.NewAtomContainer(); MoleculeSignature signature = new MoleculeSignature(mol); string signatureString = signature.ToCanonicalString(); string expected = ""; diff --git a/NCDKTests/Signatures/OrbitTest.cs b/NCDKTests/Signatures/OrbitTest.cs index 86bb5c08..23917698 100644 --- a/NCDKTests/Signatures/OrbitTest.cs +++ b/NCDKTests/Signatures/OrbitTest.cs @@ -31,7 +31,7 @@ namespace NCDK.Signatures [TestClass()] public class OrbitTest { - private string orbitLabel; + private readonly string orbitLabel; private Orbit orbit; private Orbit unsortedOrbit; @@ -63,7 +63,7 @@ public OrbitTest() public void IteratorTest() { int count = 0; - List indices = orbit.AtomIndices; + var indices = orbit.AtomIndices; foreach (var i in orbit) { Assert.AreEqual(i, indices[count]); @@ -76,8 +76,8 @@ public void IteratorTest() public void TestClone() { Orbit clonedOrbit = (Orbit)orbit.Clone(); - List indices = orbit.AtomIndices; - List clonedIndices = clonedOrbit.AtomIndices; + var indices = orbit.AtomIndices; + var clonedIndices = clonedOrbit.AtomIndices; Assert.IsTrue(Compares.AreDeepEqual(indices, clonedIndices)); Assert.AreEqual(orbit.Label, clonedOrbit.Label); } @@ -98,7 +98,7 @@ public void IsEmptyTest() Assert.IsTrue(orbit.IsEmpty(), "Orbit should now be empty"); } - private bool IsSorted(Orbit orbit) + private static bool IsSorted(Orbit orbit) { int prev = -1; foreach (var index in orbit) diff --git a/NCDKTests/Silent/ChemObjectTestHelper.cs b/NCDKTests/Silent/ChemObjectTestHelper.cs index 933f2fbd..f5537b8a 100644 --- a/NCDKTests/Silent/ChemObjectTestHelper.cs +++ b/NCDKTests/Silent/ChemObjectTestHelper.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; namespace NCDK.Silent { @@ -25,7 +26,7 @@ namespace NCDK.Silent /// Helper class to test the functionality of the s. /// // @cdk.module test-silent - public class ChemObjectTestHelper + public static class ChemObjectTestHelper { public static void TestNotifyChanged(IChemObject chemObject) { @@ -173,7 +174,7 @@ public static void TestSetAtoms_RemoveListener(IChemObject newChemObject) // if all is well, we should not get a change event this time listener.Reset(); Assert.IsFalse(listener.Changed); // make sure the reset worked - container.SetAtoms(new IAtom[0]); + container.SetAtoms(Array.Empty()); atoms[1].AtomTypeName = "C.sp2"; // make a change to an old atom Assert.IsFalse(listener.Changed); // but no change event should happen } diff --git a/NCDKTests/Similarity/DistanceMomentTest.cs b/NCDKTests/Similarity/DistanceMomentTest.cs index 24c6b7c4..8f5bb059 100644 --- a/NCDKTests/Similarity/DistanceMomentTest.cs +++ b/NCDKTests/Similarity/DistanceMomentTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Tools.Manipulator; using System.Collections.Generic; diff --git a/NCDKTests/Similarity/LingoSimilarityTest.cs b/NCDKTests/Similarity/LingoSimilarityTest.cs index 129a41ef..0bb8ea2f 100644 --- a/NCDKTests/Similarity/LingoSimilarityTest.cs +++ b/NCDKTests/Similarity/LingoSimilarityTest.cs @@ -22,11 +22,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Fingerprints; using NCDK.Templates; using NCDK.Tools.Manipulator; -using System.Collections.Generic; namespace NCDK.Similarity { @@ -37,15 +37,15 @@ public class LingoSimilarityTest : CDKTestCase [TestMethod()] public void TestLingoSim() { - IAtomContainer mol1 = TestMoleculeFactory.MakeIndole(); - IAtomContainer mol2 = TestMoleculeFactory.MakeIndole(); + var mol1 = TestMoleculeFactory.MakeIndole(); + var mol2 = TestMoleculeFactory.MakeIndole(); AddImplicitHydrogens(mol1); AddImplicitHydrogens(mol2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); - LingoFingerprinter fingerprinter = new LingoFingerprinter(); - IDictionary bs1 = fingerprinter.GetRawFingerprint(mol1); - IDictionary bs2 = fingerprinter.GetRawFingerprint(mol2); + var fingerprinter = new LingoFingerprinter(); + var bs1 = fingerprinter.GetRawFingerprint(mol1); + var bs2 = fingerprinter.GetRawFingerprint(mol2); var lingosim = LingoSimilarity.Calculate(bs1, bs2); Assert.AreEqual(1.0, lingosim, 0.01); } diff --git a/NCDKTests/Similarity/SignatureFingerprintTanimotoTest.cs b/NCDKTests/Similarity/SignatureFingerprintTanimotoTest.cs index 36d8cb8e..c909ca2f 100644 --- a/NCDKTests/Similarity/SignatureFingerprintTanimotoTest.cs +++ b/NCDKTests/Similarity/SignatureFingerprintTanimotoTest.cs @@ -38,13 +38,12 @@ public class SignatureFingerprintTanimotoTest : CDKTestCase [TestMethod()] public void TestRawTanimotoBetween0and1() { - SmilesParser smilesParser = new SmilesParser(Silent.ChemObjectBuilder.Instance); - IAtomContainer mol1 = smilesParser.ParseSmiles("Cc1nc(C(=O)NC23CC4CC(CC(C4)C2)C3)c(C)n1C5CCCCC5"); - IAtomContainer mol2 = smilesParser - .ParseSmiles("CS(=O)(=O)Nc1ccc(Cc2onc(n2)c3ccc(cc3)S(=O)(=O)Nc4ccc(CCNC[C@H](O)c5cccnc5)cc4)cc1"); - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(0); - IDictionary fp1 = fingerprinter.GetRawFingerprint(mol1); - IDictionary fp2 = fingerprinter.GetRawFingerprint(mol2); + var smilesParser = new SmilesParser(Silent.ChemObjectBuilder.Instance); + var mol1 = smilesParser.ParseSmiles("Cc1nc(C(=O)NC23CC4CC(CC(C4)C2)C3)c(C)n1C5CCCCC5"); + var mol2 = smilesParser.ParseSmiles("CS(=O)(=O)Nc1ccc(Cc2onc(n2)c3ccc(cc3)S(=O)(=O)Nc4ccc(CCNC[C@H](O)c5cccnc5)cc4)cc1"); + var fingerprinter = new SignatureFingerprinter(0); + var fp1 = fingerprinter.GetRawFingerprint(mol1); + var fp2 = fingerprinter.GetRawFingerprint(mol2); var tanimoto = Tanimoto.Calculate(fp1, fp2); Assert.IsTrue(tanimoto > 0 && tanimoto < 1, $"Tanimoto expected to be between 0 and 1, was:{tanimoto}"); } @@ -52,43 +51,41 @@ public void TestRawTanimotoBetween0and1() [TestMethod()] public void TestICountFingerprintComparison() { - IAtomContainer mol1 = TestMoleculeFactory.MakeIndole(); - IAtomContainer mol2 = TestMoleculeFactory.MakeIndole(); - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(); - ICountFingerprint fp1 = fingerprinter.GetCountFingerprint(mol1); - ICountFingerprint fp2 = fingerprinter.GetCountFingerprint(mol2); - double tanimoto = Tanimoto.Calculate(fp1, fp2); + var mol1 = TestMoleculeFactory.MakeIndole(); + var mol2 = TestMoleculeFactory.MakeIndole(); + var fingerprinter = new SignatureFingerprinter(); + var fp1 = fingerprinter.GetCountFingerprint(mol1); + var fp2 = fingerprinter.GetCountFingerprint(mol2); + var tanimoto = Tanimoto.Calculate(fp1, fp2); Assert.AreEqual(1.0, tanimoto, 0.001); } [TestMethod()] public void CompareCountFingerprintAndRawFingerprintTanimoto() { - IAtomContainer mol1 = TestMoleculeFactory.Make123Triazole(); - IAtomContainer mol2 = TestMoleculeFactory.MakeImidazole(); - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(1); - ICountFingerprint countFp1 = fingerprinter.GetCountFingerprint(mol1); - ICountFingerprint countFp2 = fingerprinter.GetCountFingerprint(mol2); - IDictionary feat1 = fingerprinter.GetRawFingerprint(mol1); - IDictionary feat2 = fingerprinter.GetRawFingerprint(mol2); + var mol1 = TestMoleculeFactory.Make123Triazole(); + var mol2 = TestMoleculeFactory.MakeImidazole(); + var fingerprinter = new SignatureFingerprinter(1); + var countFp1 = fingerprinter.GetCountFingerprint(mol1); + var countFp2 = fingerprinter.GetCountFingerprint(mol2); + var feat1 = fingerprinter.GetRawFingerprint(mol1); + var feat2 = fingerprinter.GetRawFingerprint(mol2); var rawTanimoto = Tanimoto.Calculate(feat1, feat2); - double countTanimoto = Tanimoto.Method1(countFp1, countFp2); + var countTanimoto = Tanimoto.Method1(countFp1, countFp2); Assert.AreEqual(rawTanimoto, countTanimoto, 0.001); } [TestMethod()] public void TestCountMethod1and2() { - ICountFingerprint fp1 = new IntArrayCountFingerprint(new Dictionary() - { { "A", 3 } }); - ICountFingerprint fp2 = new IntArrayCountFingerprint(new Dictionary() - { { "A", 4 } }); + ICountFingerprint fp1 = new IntArrayCountFingerprint(new Dictionary() { { "A", 3 } }); + ICountFingerprint fp2 = new IntArrayCountFingerprint(new Dictionary() { { "A", 4 } }); Assert.AreEqual(0.923, Tanimoto.Method1(fp1, fp2), 0.001); Assert.AreEqual(0.75, Tanimoto.Method2(fp1, fp2), 0.001); - IAtomContainer mol1 = TestMoleculeFactory.MakeIndole(); - IAtomContainer mol2 = TestMoleculeFactory.MakeIndole(); - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(); + var mol1 = TestMoleculeFactory.MakeIndole(); + var mol2 = TestMoleculeFactory.MakeIndole(); + var fingerprinter = new SignatureFingerprinter(); fp1 = fingerprinter.GetCountFingerprint(mol1); fp2 = fingerprinter.GetCountFingerprint(mol2); Assert.AreEqual(1.0, Tanimoto.Method1(fp1, fp2), 0.001); @@ -98,19 +95,19 @@ public void TestCountMethod1and2() [TestMethod()] public void TestCompaRingBitFingerprintAndCountBehavingAsBit() { - IAtomContainer mol1 = TestMoleculeFactory.Make123Triazole(); - IAtomContainer mol2 = TestMoleculeFactory.MakeImidazole(); + var mol1 = TestMoleculeFactory.Make123Triazole(); + var mol2 = TestMoleculeFactory.MakeImidazole(); - SignatureFingerprinter fingerprinter = new SignatureFingerprinter(1); + var fingerprinter = new SignatureFingerprinter(1); ICountFingerprint countFp1 = fingerprinter.GetCountFingerprint(mol1); ICountFingerprint countFp2 = fingerprinter.GetCountFingerprint(mol2); countFp1.SetBehaveAsBitFingerprint(true); countFp2.SetBehaveAsBitFingerprint(true); - IBitFingerprint bitFp1 = fingerprinter.GetBitFingerprint(mol1); - IBitFingerprint bitFp2 = fingerprinter.GetBitFingerprint(mol2); - double bitTanimoto = Tanimoto.Calculate(bitFp1, bitFp2); - double countTanimoto1 = Tanimoto.Method1(countFp1, countFp2); - double countTanimoto2 = Tanimoto.Method2(countFp1, countFp2); + var bitFp1 = fingerprinter.GetBitFingerprint(mol1); + var bitFp2 = fingerprinter.GetBitFingerprint(mol2); + var bitTanimoto = Tanimoto.Calculate(bitFp1, bitFp2); + var countTanimoto1 = Tanimoto.Method1(countFp1, countFp2); + var countTanimoto2 = Tanimoto.Method2(countFp1, countFp2); Assert.AreEqual(countTanimoto1, countTanimoto2, 0.001); Assert.AreEqual(bitTanimoto, countTanimoto1, 0.001); diff --git a/NCDKTests/Similarity/TanimotoTest.cs b/NCDKTests/Similarity/TanimotoTest.cs index 145c5650..b31ec6f0 100644 --- a/NCDKTests/Similarity/TanimotoTest.cs +++ b/NCDKTests/Similarity/TanimotoTest.cs @@ -23,6 +23,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Fingerprints; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Templates; using NCDK.Tools.Manipulator; @@ -35,7 +36,7 @@ namespace NCDK.Similarity [TestClass()] public class TanimotoTest : CDKTestCase { - bool standAlone = false; + readonly bool standAlone = false; [TestMethod()] public void TestTanimoto1() @@ -80,11 +81,11 @@ public void TestExactMatch() IAtomContainer mol2 = TestMoleculeFactory.MakeIndole(); AddImplicitHydrogens(mol1); AddImplicitHydrogens(mol2); - LingoFingerprinter fingerprinter = new LingoFingerprinter(); + var fingerprinter = new LingoFingerprinter(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); - IDictionary feat1 = fingerprinter.GetRawFingerprint(mol1); - IDictionary feat2 = fingerprinter.GetRawFingerprint(mol2); + var feat1 = fingerprinter.GetRawFingerprint(mol1); + var feat2 = fingerprinter.GetRawFingerprint(mol2); var tanimoto = Tanimoto.Calculate(feat1, feat2); Assert.AreEqual(1.0, tanimoto, 0.001); @@ -103,7 +104,7 @@ public void TestTanimoto3() [TestMethod()] public void KeggR00258() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string smiles1 = "O=C(O)CCC(=O)C(=O)O"; string smiles2 = "O=C(O)C(N)CCC(=O)O"; string smiles3 = "O=C(O)C(N)C"; diff --git a/NCDKTests/Smiles/CDKToBeamTest.cs b/NCDKTests/Smiles/CDKToBeamTest.cs index 316ddf76..94278892 100644 --- a/NCDKTests/Smiles/CDKToBeamTest.cs +++ b/NCDKTests/Smiles/CDKToBeamTest.cs @@ -46,7 +46,6 @@ namespace NCDK.Smiles public class CDKToBeamTest { [TestMethod()] - [ExpectedException(typeof(NullReferenceException))] public void NoImplicitHCount() { new CDKToBeam().ToBeamAtom(new Atom("C")); @@ -286,7 +285,7 @@ public void Benzene_kekule() public void Benzene() { IAtomContainer ac = TestMoleculeFactory.MakeBenzene(); - Beam.Graph g = Convert(ac, true, SmiFlavor.UseAromaticSymbols); + Beam.Graph g = Convert(ac, true, SmiFlavors.UseAromaticSymbols); Assert.AreEqual("c1ccccc1", g.ToSmiles()); } @@ -300,7 +299,7 @@ public void Imidazole_kekule() [TestMethod()] public void Imidazole() { - Beam.Graph g = Convert(TestMoleculeFactory.MakeImidazole(), true, SmiFlavor.UseAromaticSymbols); + Beam.Graph g = Convert(TestMoleculeFactory.MakeImidazole(), true, SmiFlavors.UseAromaticSymbols); Assert.AreEqual("c1[nH]cnc1", g.ToSmiles()); } @@ -318,7 +317,7 @@ public void C13_Isomeric() IAtom a = new Atom("C"); a.MassNumber = 13; ac.Atoms.Add(a); - Beam.Graph g = Convert(ac, SmiFlavor.AtomicMass); + Beam.Graph g = Convert(ac, SmiFlavors.AtomicMass); Assert.AreEqual(13, g.GetAtom(0).Isotope); Assert.AreEqual("[13CH4]", g.ToSmiles()); } @@ -389,7 +388,7 @@ public void E_1_2_difluoroethene() ac.StereoElements.Add(new DoubleBondStereochemistry(ac.Bonds[1], new IBond[] { ac.Bonds[0], ac.Bonds[2] }, DoubleBondConformation.Opposite)); - Beam.Graph g = Convert(ac, SmiFlavor.StereoCisTrans); + Beam.Graph g = Convert(ac, SmiFlavors.StereoCisTrans); Assert.AreEqual("F/C=C/F", g.ToSmiles()); } @@ -411,7 +410,7 @@ public void Z_1_2_difluoroethene() ac.StereoElements.Add(new DoubleBondStereochemistry(ac.Bonds[1], new IBond[] { ac.Bonds[0], ac.Bonds[2] }, DoubleBondConformation.Together)); - Beam.Graph g = Convert(ac, SmiFlavor.StereoCisTrans); + Beam.Graph g = Convert(ac, SmiFlavors.StereoCisTrans); Assert.AreEqual("F/C=C\\F", g.ToSmiles()); } @@ -441,7 +440,7 @@ public void Test_2R_butan_2_ol() ac.Atoms[5], // H }, TetrahedralStereo.Clockwise)); - Beam.Graph g = Convert(ac, SmiFlavor.StereoTetrahedral); + Beam.Graph g = Convert(ac, SmiFlavors.StereoTetrahedral); Assert.AreEqual("CC[C@@](C)(O)[H]", g.ToSmiles()); } @@ -471,7 +470,7 @@ public void Test_2S_butan_2_ol() ac.Atoms[5], // H }, TetrahedralStereo.AntiClockwise)); - Beam.Graph g = Convert(ac, SmiFlavor.StereoTetrahedral); + Beam.Graph g = Convert(ac, SmiFlavors.StereoTetrahedral); Assert.AreEqual("CC[C@](C)(O)[H]", g.ToSmiles()); } @@ -499,7 +498,7 @@ public void Z_1_2_difluoroethene_aromatic() ac.StereoElements.Add(new DoubleBondStereochemistry(ac.Bonds[1], new IBond[] { ac.Bonds[0], ac.Bonds[2] }, DoubleBondConformation.Together)); - Beam.Graph g = Convert(ac, SmiFlavor.UseAromaticSymbols); + Beam.Graph g = Convert(ac, SmiFlavors.UseAromaticSymbols); Assert.AreEqual("FccF", g.ToSmiles()); } @@ -520,7 +519,7 @@ public void WriteAtomClass() ac.Atoms[0].SetProperty(CDKPropertyName.AtomAtomMapping, 3); ac.Atoms[1].SetProperty(CDKPropertyName.AtomAtomMapping, 1); ac.Atoms[2].SetProperty(CDKPropertyName.AtomAtomMapping, 2); - Assert.AreEqual("[CH3:3][CH2:1][OH:2]", Convert(ac, SmiFlavor.AtomAtomMap).ToSmiles()); + Assert.AreEqual("[CH3:3][CH2:1][OH:2]", Convert(ac, SmiFlavors.AtomAtomMap).ToSmiles()); } [TestMethod()] @@ -541,7 +540,7 @@ public void R_penta_2_3_diene_impl_h() m.Atoms[3], m.Atoms[4]}, TetrahedralStereo.AntiClockwise); m.SetStereoElements(new[] { element }); - Assert.AreEqual("CC=[C@]=CC", Convert(m, SmiFlavor.Stereo).ToSmiles()); + Assert.AreEqual("CC=[C@]=CC", Convert(m, SmiFlavors.Stereo).ToSmiles()); } [TestMethod()] @@ -562,7 +561,7 @@ public void S_penta_2_3_diene_impl_h() m.Atoms[3], m.Atoms[4]}, TetrahedralStereo.Clockwise); m.SetStereoElements(new[] { element }); - Assert.AreEqual("CC=[C@@]=CC", Convert(m, SmiFlavor.Stereo).ToSmiles()); + Assert.AreEqual("CC=[C@@]=CC", Convert(m, SmiFlavors.Stereo).ToSmiles()); } [TestMethod()] @@ -593,7 +592,7 @@ public void R_penta_2_3_diene_expl_h() m.Atoms[atoms[i][1]], m.Atoms[atoms[i][2]], m.Atoms[atoms[i][3]]}, stereos[i]); m.SetStereoElements(new[] { element }); - Assert.AreEqual("CC(=[C@@]=C(C)[H])[H]", Convert(m, SmiFlavor.Stereo).ToSmiles()); + Assert.AreEqual("CC(=[C@@]=C(C)[H])[H]", Convert(m, SmiFlavors.Stereo).ToSmiles()); } } @@ -625,16 +624,16 @@ public void S_penta_2_3_diene_expl_h() m.Atoms[atoms[i][1]], m.Atoms[atoms[i][2]], m.Atoms[atoms[i][3]]}, stereos[i]); m.SetStereoElements(new[] { element }); - Assert.AreEqual("CC(=[C@]=C(C)[H])[H]", Convert(m, SmiFlavor.Stereo).ToSmiles()); + Assert.AreEqual("CC(=[C@]=C(C)[H])[H]", Convert(m, SmiFlavors.Stereo).ToSmiles()); } } - static Beam.Graph Convert(IAtomContainer ac, SmiFlavor options) + static Beam.Graph Convert(IAtomContainer ac, SmiFlavors options) { return Convert(ac, false, options); } - static Beam.Graph Convert(IAtomContainer ac, bool perceiveAromaticity, SmiFlavor options) + static Beam.Graph Convert(IAtomContainer ac, bool perceiveAromaticity, SmiFlavors options) { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); CDKHydrogenAdder.GetInstance(Silent.ChemObjectBuilder.Instance).AddImplicitHydrogens(ac); diff --git a/NCDKTests/Smiles/CxSmilesGeneratorTest.cs b/NCDKTests/Smiles/CxSmilesGeneratorTest.cs index 4b59f65a..8dd8dc82 100644 --- a/NCDKTests/Smiles/CxSmilesGeneratorTest.cs +++ b/NCDKTests/Smiles/CxSmilesGeneratorTest.cs @@ -22,8 +22,9 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; +using System; using System.Collections.Generic; namespace NCDK.Smiles @@ -34,51 +35,60 @@ public class CxSmilesGeneratorTest public void EmptyCXSMILES() { CxSmilesState state = new CxSmilesState(); - Assert.AreEqual("", CxSmilesGenerator.Generate(state, SmiFlavor.CxSmiles, new int[0], new int[0])); + Assert.AreEqual("", CxSmilesGenerator.Generate(state, SmiFlavors.CxSmiles, Array.Empty(), Array.Empty())); } [TestMethod()] public void Multicenter() { - CxSmilesState state = new CxSmilesState(); - state.positionVar = new Dictionary>(); + var state = new CxSmilesState { positionVar = new SortedDictionary>() }; state.positionVar[0] = new[] { 4, 5, 6, 7 }; state.positionVar[2] = new[] { 4, 6, 5, 7 }; - Assert.AreEqual(" |m:5:0.1.2.3,7:0.1.2.3|", CxSmilesGenerator.Generate(state, SmiFlavor.CxMulticenter, new int[0], new int[] { 7, 6, 5, 4, 3, 2, 1, 0 })); + Assert.AreEqual(" |m:5:0.1.2.3,7:0.1.2.3|", CxSmilesGenerator.Generate(state, SmiFlavors.CxMulticenter, Array.Empty(), new int[] { 7, 6, 5, 4, 3, 2, 1, 0 })); } [TestMethod()] public void Coords2d() { - CxSmilesState state = new CxSmilesState(); - state.AtomCoords = new[] + CxSmilesState state = new CxSmilesState { - new double[] { 0, 1.5, 0 }, - new double[] { 0, 3, 0 }, - new double[] { 1.5, 1.5, 0 }, + atomCoords = new List + { + new double[] { 0, 1.5, 0 }, + new double[] { 0, 3, 0 }, + new double[] { 1.5, 1.5, 0 }, + } }; - Assert.AreEqual(" |(1.5,1.5,;,1.5,;,3,)|", CxSmilesGenerator.Generate(state, SmiFlavor.CxCoordinates, new int[0], new int[] { 1, 2, 0 })); + Assert.AreEqual(" |(1.5,1.5,;,1.5,;,3,)|", CxSmilesGenerator.Generate(state, SmiFlavors.CxCoordinates, Array.Empty(), new int[] { 1, 2, 0 })); } [TestMethod()] public void Sgroups() { - CxSmilesState state = new CxSmilesState(); - state.sgroups = new List(1); - state.sgroups.Add(new CxSmilesState.PolymerSgroup("n", new[] { 2, 3 }, "n", "ht")); - state.sgroups.Add(new CxSmilesState.PolymerSgroup("n", new[] { 5 }, "m", "ht")); - Assert.AreEqual(" |Sg:n:2:m:ht,Sg:n:4,5:n:ht|", CxSmilesGenerator.Generate(state, SmiFlavor.CxPolymer, new int[0], new int[] { 7, 6, 5, 4, 3, 2, 1, 0 })); + CxSmilesState state = new CxSmilesState + { + sgroups = new List(1) + { + new CxSmilesState.PolymerSgroup("n", new[] { 2, 3 }, "n", "ht"), + new CxSmilesState.PolymerSgroup("n", new[] { 5 }, "m", "ht") + } + }; + Assert.AreEqual(" |Sg:n:2:m:ht,Sg:n:4,5:n:ht|", CxSmilesGenerator.Generate(state, SmiFlavors.CxPolymer, Array.Empty(), new int[] { 7, 6, 5, 4, 3, 2, 1, 0 })); } [TestMethod()] public void Radicals() { - CxSmilesState state = new CxSmilesState(); - state.atomRads = new Dictionary(); - state.atomRads[2] = CxSmilesState.Radical.Monovalent; - state.atomRads[6] = CxSmilesState.Radical.Monovalent; - state.atomRads[4] = CxSmilesState.Radical.Divalent; - Assert.AreEqual(" |^1:1,5,^2:3|", CxSmilesGenerator.Generate(state, SmiFlavor.CxSmiles, new int[0], new int[] { 7, 6, 5, 4, 3, 2, 1, 0 })); + CxSmilesState state = new CxSmilesState + { + atomRads = new SortedDictionary + { + [2] = CxSmilesState.Radical.Monovalent, + [6] = CxSmilesState.Radical.Monovalent, + [4] = CxSmilesState.Radical.Divalent + } + }; + Assert.AreEqual(" |^1:1,5,^2:3|", CxSmilesGenerator.Generate(state, SmiFlavors.CxSmiles, Array.Empty(), new int[] { 7, 6, 5, 4, 3, 2, 1, 0 })); } /// @@ -92,7 +102,7 @@ public void Chebi53695() using (var mdlr = new MDLV2000Reader(ins)) { IAtomContainer mol = mdlr.Read(Silent.ChemObjectBuilder.Instance.NewAtomContainer()); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxSmiles | SmiFlavor.AtomicMassStrict); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxSmiles | SmiFlavors.AtomicMassStrict); Assert.AreEqual("C(C(=O)OC)(C*)*C(C(C1=C(C(=C(C(=C1[2H])[2H])[2H])[2H])[2H])(*)[2H])([2H])[2H] |Sg:n:0,1,2,3,4,5:n:ht,Sg:n:8,9,10,11,12,13,14,15,16,17,18,19,20,22,23,24:m:ht|", smigen.Create(mol)); } } @@ -103,7 +113,7 @@ public void Chembl367774() using (MDLV2000Reader mdlr = new MDLV2000Reader(GetType().Assembly.GetManifestResourceStream(GetType(), "CHEMBL367774.mol"))) { IAtomContainer container = mdlr.Read(new AtomContainer()); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxSmiles); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxSmiles); Assert.AreEqual("OC(=O)C1=CC(F)=CC=2NC(=NC12)C3=CC=C(C=C3F)C4=CC=CC=C4", smigen.Create(container)); } } @@ -131,7 +141,7 @@ public void RadicalCanon() SmilesParser smipar = new SmilesParser(builder); IAtomContainer molb = smipar.ParseSmiles("CC(CCC[CH2])C |^1:5|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Canonical | SmiFlavor.CxRadical); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Canonical | SmiFlavors.CxRadical); Assert.AreEqual(smigen.Create(molb), smigen.Create(mola)); } } diff --git a/NCDKTests/Smiles/CxSmilesParserTest.cs b/NCDKTests/Smiles/CxSmilesParserTest.cs index 643b30c4..81c4f651 100644 --- a/NCDKTests/Smiles/CxSmilesParserTest.cs +++ b/NCDKTests/Smiles/CxSmilesParserTest.cs @@ -26,6 +26,7 @@ using NCDK.Sgroups; using System; using System.Collections.Generic; +using System.Linq; namespace NCDK.Smiles { @@ -150,11 +151,11 @@ public void Coords() { CxSmilesState state = new CxSmilesState(); Assert.AreNotEqual(-1, CxSmilesParser.ProcessCx("|(.0,-1.5,;-1.3,-.75,;-2.6,-1.5,;-3.9,-.75,;-3.9,.75,)|", state)); - Assert.IsTrue(new AprxDoubleArray(0, -1.5, 0).Matches(state.AtomCoords[0])); - Assert.IsTrue(new AprxDoubleArray(-1.3, -.75, 0).Matches(state.AtomCoords[1])); - Assert.IsTrue(new AprxDoubleArray(-2.6, -1.5, 0).Matches(state.AtomCoords[2])); - Assert.IsTrue(new AprxDoubleArray(-3.9, -.75, 0).Matches(state.AtomCoords[3])); - Assert.IsTrue(new AprxDoubleArray(-3.9, .75, 0).Matches(state.AtomCoords[4])); + Assert.IsTrue(new AprxDoubleArray(0, -1.5, 0).Matches(state.atomCoords[0])); + Assert.IsTrue(new AprxDoubleArray(-1.3, -.75, 0).Matches(state.atomCoords[1])); + Assert.IsTrue(new AprxDoubleArray(-2.6, -1.5, 0).Matches(state.atomCoords[2])); + Assert.IsTrue(new AprxDoubleArray(-3.9, -.75, 0).Matches(state.atomCoords[3])); + Assert.IsTrue(new AprxDoubleArray(-3.9, .75, 0).Matches(state.atomCoords[4])); } [TestMethod()] @@ -256,7 +257,7 @@ public void RelativeStereoReaction() private class AprxDoubleArray { double[] expected; - double epsilon = 0.01; + const double epsilon = 0.01; public AprxDoubleArray(params double[] expected) { diff --git a/NCDKTests/Smiles/CxSmilesTest.cs b/NCDKTests/Smiles/CxSmilesTest.cs index 514ed2ed..87118a75 100644 --- a/NCDKTests/Smiles/CxSmilesTest.cs +++ b/NCDKTests/Smiles/CxSmilesTest.cs @@ -125,8 +125,8 @@ public void AttachPoints() [TestMethod()] public void PositionalVariation() { - IAtomContainer mol = smipar.ParseSmiles("**.c1ccccc1CC |m:1:2.3.4.5.6.7|"); - IList sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var mol = smipar.ParseSmiles("**.c1ccccc1CC |m:1:2.3.4.5.6.7|"); + var sgroups = mol.GetCtabSgroups(); Assert.AreEqual(1, sgroups.Count); Assert.AreEqual(SgroupType.ExtMulticenter, sgroups[0].Type); Assert.AreEqual(7, sgroups[0].Atoms.Count); @@ -136,8 +136,8 @@ public void PositionalVariation() [TestMethod()] public void StructuralRepeatUnit() { - IAtomContainer mol = smipar.ParseSmiles("**.c1ccccc1CC |Sg:n:8:m:ht|"); - IList sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var mol = smipar.ParseSmiles("**.c1ccccc1CC |Sg:n:8:m:ht|"); + var sgroups = mol.GetCtabSgroups(); Assert.AreEqual(1, sgroups.Count); Assert.AreEqual(SgroupType.CtabStructureRepeatUnit, sgroups[0].Type); Assert.AreEqual("m", sgroups[0].Subscript); @@ -149,8 +149,8 @@ public void StructuralRepeatUnit() [TestMethod()] public void MarkushFragment() { - IAtomContainer mol = smipar.ParseSmiles("**.c1ccccc1CC |m:1:2.3.4.5.6.7,Sg:n:8:m:ht,$R';;;;;;;;;_AP1$|"); - IList sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var mol = smipar.ParseSmiles("**.c1ccccc1CC |m:1:2.3.4.5.6.7,Sg:n:8:m:ht,$R';;;;;;;;;_AP1$|"); + var sgroups = mol.GetCtabSgroups(); // P-var and F-var Assert.AreEqual(2, sgroups.Count); // atom-labels @@ -211,8 +211,8 @@ public void GenericReaction() [TestMethod()] public void TrailingAtomLabelSemiColonAndAtomValues() { - IAtomContainer mol = smipar.ParseSmiles("[H]C1=C([H])N2C(=O)C(=C([O-])[N+](CC3=CN=C(Cl)S3)=C2C(C)=C1[H])C1=CC(*)=CC=C1.** |$;;;;;;;;;;;;;;;;;;;;;;;;;;R;;;;RA;$,$_AV:;;;;;;;;;;;;;;;;;;;;;;;;2;;;4;5;6;;$,c:1,18,22,29,31,t:7,12,14,26,m:31:29.28.27.25.24.23|"); - var sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var mol = smipar.ParseSmiles("[H]C1=C([H])N2C(=O)C(=C([O-])[N+](CC3=CN=C(Cl)S3)=C2C(C)=C1[H])C1=CC(*)=CC=C1.** |$;;;;;;;;;;;;;;;;;;;;;;;;;;R;;;;RA;$,$_AV:;;;;;;;;;;;;;;;;;;;;;;;;2;;;4;5;6;;$,c:1,18,22,29,31,t:7,12,14,26,m:31:29.28.27.25.24.23|"); + var sgroups = mol.GetCtabSgroups(); Assert.IsInstanceOfType(mol.Atoms[26], typeof(IPseudoAtom)); Assert.IsInstanceOfType(mol.Atoms[30], typeof(IPseudoAtom)); Assert.AreEqual("R", ((IPseudoAtom)mol.Atoms[26]).Label); @@ -236,7 +236,7 @@ public void GenerateLabelledSmiles() mol.Atoms[2].ImplicitHydrogenCount = 0; mol.AddBond(mol.Atoms[0], mol.Atoms[1], BondOrder.Single); mol.AddBond(mol.Atoms[1], mol.Atoms[2], BondOrder.Single); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxAtomLabel); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxAtomLabel); string smi = smigen.Create(mol); Assert.AreEqual("CC* |$;;R1$|", smi); } @@ -253,8 +253,8 @@ public void GenerateCanonLabelledSmiles() mol.Atoms[2].ImplicitHydrogenCount = 0; mol.AddBond(mol.Atoms[0], mol.Atoms[1], BondOrder.Single); mol.AddBond(mol.Atoms[1], mol.Atoms[2], BondOrder.Single); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Canonical | - SmiFlavor.CxAtomLabel); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Canonical | + SmiFlavors.CxAtomLabel); string smi = smigen.Create(mol); Assert.AreEqual("*CC |$R1$|", smi); } @@ -265,8 +265,8 @@ public void RoundTripMulticenter() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("c1ccccc1.*Cl |m:6:0.1.2.3.4.5|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.UseAromaticSymbols | - SmiFlavor.CxMulticenter); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.UseAromaticSymbols | + SmiFlavors.CxMulticenter); string smi = smigen.Create(mol); Assert.AreEqual("c1ccccc1.*Cl |m:6:0.1.2.3.4.5|", smi); } @@ -277,9 +277,9 @@ public void CanonMulticenter() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("c1ccccc1.*Cl |m:6:0.1.2.3.4.5|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.UseAromaticSymbols | - SmiFlavor.CxMulticenter | - SmiFlavor.Canonical); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.UseAromaticSymbols | + SmiFlavors.CxMulticenter | + SmiFlavors.Canonical); string smi = smigen.Create(mol); Assert.AreEqual("*Cl.c1ccccc1 |m:0:2.3.4.5.6.7|", smi); } @@ -291,7 +291,7 @@ public void RoundTripPEGn() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("CCCOCCO |Sg:n:1,2,3::ht|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxPolymer); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxPolymer); string smi = smigen.Create(mol); Assert.AreEqual("CCCOCCO |Sg:n:1,2,3:n:ht|", smi); } @@ -302,8 +302,8 @@ public void CanonPEGn() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("CCCOCCO |Sg:n:1,2,3::ht|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Canonical | - SmiFlavor.CxPolymer); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Canonical | + SmiFlavors.CxPolymer); string smi = smigen.Create(mol); Assert.AreEqual("OCCOCCC |Sg:n:3,4,5:n:ht|", smi); } @@ -314,7 +314,7 @@ public void CoordsEtOH() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("CCO |(,,;1,1,;2,2,)|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxCoordinates); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxCoordinates); string smi = smigen.Create(mol); Assert.AreEqual("CCO |(,,;1,1,;2,2,)|", smi); } @@ -325,8 +325,8 @@ public void CanonCoordsEtOH() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("CCO |(,,;1,1,;2,2,)|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Canonical | - SmiFlavor.CxCoordinates); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Canonical | + SmiFlavors.CxCoordinates); string smi = smigen.Create(mol); Assert.AreEqual("OCC |(2,2,;1,1,;,,)|", smi); } @@ -348,7 +348,7 @@ public void NoCoordsInEtOH() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("CCO"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxCoordinates); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxCoordinates); string smi = smigen.Create(mol); Assert.AreEqual("CCO", smi); } @@ -359,7 +359,7 @@ public void RoundTripRadicals() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("[C]1C[CH][CH]OC1 |^1:2,3,^2:0|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxRadical); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxRadical); string smi = smigen.Create(mol); Assert.AreEqual("[C]1C[CH][CH]OC1 |^1:2,3,^2:0|", smi); } @@ -370,8 +370,8 @@ public void CanonRadicals() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("[C]1C[CH][CH]OC1 |^1:2,3,^2:0|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxRadical | - SmiFlavor.Canonical); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxRadical | + SmiFlavors.Canonical); string smi = smigen.Create(mol); Assert.AreEqual("[C]1CO[CH][CH]C1 |^1:3,4,^2:0|", smi); } @@ -382,8 +382,8 @@ public void RoundTripReactionAtomLabelsAndFragmentGroups() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IReaction rxn = smipar.ParseReactionSmiles("CC(C)c1ccccc1.ClC([*])=O>ClCCl.[Al+3].[Cl-].[Cl-].[Cl-]>CC(C)c1ccc(cc1)C([*])=O |$;;;;;;;;;;;R1;;;;;;;;;;;;;;;;;;;R1;$,f:3.4.5.6|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxAtomLabel | - SmiFlavor.CxFragmentGroup); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxAtomLabel | + SmiFlavors.CxFragmentGroup); Assert.AreEqual("CC(C)C1=CC=CC=C1.ClC(*)=O>ClCCl.[Al+3].[Cl-].[Cl-].[Cl-]>CC(C)C1=CC=C(C=C1)C(*)=O |f:3.4.5.6,$;;;;;;;;;;;R1;;;;;;;;;;;;;;;;;;;R1$|", smigen.Create(rxn)); } @@ -394,9 +394,9 @@ public void CanonicalReactionAtomLabelsAndFragmentGroups() SmilesParser smipar = new SmilesParser(bldr); IReaction rxn1 = smipar.ParseReactionSmiles("CC(C)c1ccccc1.ClC([*])=O>[Al+3].[Cl-].[Cl-].[Cl-].ClCCl>CC(C)c1ccc(cc1)C([*])=O |$;;;;;;;;;;;R1;;;;;;;;;;;;;;;;;;;R1;$,f:2.3.4.5|"); IReaction rxn2 = smipar.ParseReactionSmiles("ClC([*])=O.CC(C)c1ccccc1>[Al+3].[Cl-].[Cl-].[Cl-].ClCCl>CC(C)c1ccc(cc1)C([*])=O |$;;R1;;;;;;;;;;;;;;;;;;;;;;;;;;;;R1;$,f:2.3.5.4|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxAtomLabel | - SmiFlavor.CxFragmentGroup | - SmiFlavor.Canonical); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxAtomLabel | + SmiFlavors.CxFragmentGroup | + SmiFlavors.Canonical); Assert.AreEqual(smigen.Create(rxn2), smigen.Create(rxn1)); } @@ -406,7 +406,7 @@ public void CanonAtomLabels() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IAtomContainer mol = smipar.ParseSmiles("c1ccccc1O |$_AV:0;1;2;3;4;5;6$|"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Canonical | SmiFlavor.CxAtomValue); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Canonical | SmiFlavors.CxAtomValue); Assert.AreEqual("OC=1C=CC=CC1 |$_AV:6;5;0;1;2;3;4$|", smigen.Create(mol)); } } diff --git a/NCDKTests/Smiles/DeduceBondSystemToolTest.cs b/NCDKTests/Smiles/DeduceBondSystemToolTest.cs index 897c43f0..a06e7bae 100644 --- a/NCDKTests/Smiles/DeduceBondSystemToolTest.cs +++ b/NCDKTests/Smiles/DeduceBondSystemToolTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.RingSearches; using NCDK.Tools.Manipulator; @@ -56,7 +56,7 @@ public void TestInterruption() public void TestPyrrole() { string smiles = "c2ccc3n([H])c1ccccc1c3(c2)"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); smilesParser.Kekulise(false); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.SetSingleOrDoubleFlags(molecule); @@ -105,7 +105,7 @@ public void TestPyrrole_Silent() public void TestLargeRingSystem() { string smiles = "O=C1Oc6ccccc6(C(O)C1C5c2ccccc2CC(c3ccc(cc3)c4ccccc4)C5)"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); DeduceBondSystemTool dbst = new DeduceBondSystemTool(new AllRingsFinder()); @@ -130,7 +130,7 @@ public void TestLargeRingSystem() public void TestLargeBioclipseUseCase() { string smiles = "COc1ccc2[C@@H]3[C@H](COc2c1)C(C)(C)OC4=C3C(=O)C(=O)C5=C4OC(C)(C)[C@@H]6COc7cc(OC)ccc7[C@H]56"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); DeduceBondSystemTool dbst = new DeduceBondSystemTool(new AllRingsFinder()); @@ -155,7 +155,7 @@ public void TestLargeBioclipseUseCase() public void TestPyrrole_CustomRingFinder() { string smiles = "c2ccc3n([H])c1ccccc1c3(c2)"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); smilesParser.Kekulise(false); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.SetSingleOrDoubleFlags(molecule); diff --git a/NCDKTests/Smiles/FixBondOrdersToolTest.cs b/NCDKTests/Smiles/FixBondOrdersToolTest.cs index e154d232..32469696 100644 --- a/NCDKTests/Smiles/FixBondOrdersToolTest.cs +++ b/NCDKTests/Smiles/FixBondOrdersToolTest.cs @@ -20,7 +20,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Tools.Manipulator; -using NCDK.Default; +using NCDK.Silent; using NCDK.Config; namespace NCDK.Smiles @@ -31,37 +31,18 @@ namespace NCDK.Smiles [TestClass()] public class FixBondOrdersToolTest : CDKTestCase { - private static FixBondOrdersTool fbot = new FixBondOrdersTool(); - - [TestMethod()] - public void TestConstructors() - { - // basically: just test that no exception is thrown - Assert.IsNotNull(new FixBondOrdersTool()); - } - - [TestMethod()] - public void TestInterruption() - { - fbot.Interrupted = false; - Assert.IsFalse(fbot.Interrupted); - fbot.Interrupted = true; - Assert.IsTrue(fbot.Interrupted); - fbot.Interrupted = false; - } - [TestMethod()] [Timeout(1000)] public void TestPyrrole() { string smiles = "c2ccc3n([H])c1ccccc1c3(c2)"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); smilesParser.Kekulise(false); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); AtomContainerManipulator.SetSingleOrDoubleFlags(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - molecule = fbot.KekuliseAromaticRings(molecule); + molecule = FixBondOrdersTool.KekuliseAromaticRings(molecule); Assert.IsNotNull(molecule); molecule = (IAtomContainer)AtomContainerManipulator.RemoveHydrogens(molecule); @@ -86,7 +67,7 @@ public void TestPyrrole_Silent() AtomContainerManipulator.SetSingleOrDoubleFlags(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - molecule = fbot.KekuliseAromaticRings(molecule); + molecule = FixBondOrdersTool.KekuliseAromaticRings(molecule); Assert.IsNotNull(molecule); molecule = (IAtomContainer)AtomContainerManipulator.RemoveHydrogens(molecule); @@ -104,10 +85,10 @@ public void TestPyrrole_Silent() public void TestLargeRingSystem() { string smiles = "O=C1Oc6ccccc6(C(O)C1C5c2ccccc2CC(c3ccc(cc3)c4ccccc4)C5)"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); - molecule = fbot.KekuliseAromaticRings(molecule); + molecule = FixBondOrdersTool.KekuliseAromaticRings(molecule); Assert.IsNotNull(molecule); molecule = (IAtomContainer)AtomContainerManipulator.RemoveHydrogens(molecule); @@ -128,10 +109,10 @@ public void TestLargeRingSystem() public void TestLargeBioclipseUseCase() { string smiles = "COc1ccc2[C@@H]3[C@H](COc2c1)C(C)(C)OC4=C3C(=O)C(=O)C5=C4OC(C)(C)[C@@H]6COc7cc(OC)ccc7[C@H]56"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); - molecule = fbot.KekuliseAromaticRings(molecule); + molecule = FixBondOrdersTool.KekuliseAromaticRings(molecule); Assert.IsNotNull(molecule); molecule = (IAtomContainer)AtomContainerManipulator.RemoveHydrogens(molecule); @@ -188,9 +169,9 @@ public void XtestPyrrole() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(enol); // now have the algorithm have a go at it - enol = fbot.KekuliseAromaticRings(enol); + enol = FixBondOrdersTool.KekuliseAromaticRings(enol); Assert.IsNotNull(enol); - //Assert.IsTrue(fbot.IsOK(enol)); + //Assert.IsTrue(FixBondOrdersTool.IsOK(enol)); // now check whether it did the right thing Assert.AreEqual(BondOrder.Double, enol.Bonds[0].Order); ; @@ -244,7 +225,7 @@ public void XtestPyridine() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(enol); // now have the algorithm have a go at it - enol = fbot.KekuliseAromaticRings(enol); + enol = FixBondOrdersTool.KekuliseAromaticRings(enol); Assert.IsNotNull(enol); // Assert.IsTrue(dbst.IsOK(enol)); @@ -315,7 +296,7 @@ public void XtestBenzene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(enol); // now have the algorithm have a go at it - enol = fbot.KekuliseAromaticRings(enol); + enol = FixBondOrdersTool.KekuliseAromaticRings(enol); Assert.IsNotNull(enol); //Assert.IsTrue(dbst.IsOK(enol)); @@ -351,7 +332,7 @@ public void TestAcyclic() SmilesParser smilesParser = new SmilesParser(Silent.ChemObjectBuilder.Instance); IAtomContainer molecule = smilesParser.ParseSmiles(smiles); - molecule = fbot.KekuliseAromaticRings(molecule); + molecule = FixBondOrdersTool.KekuliseAromaticRings(molecule); Assert.IsNotNull(molecule); } } diff --git a/NCDKTests/Smiles/InvPairTest.cs b/NCDKTests/Smiles/InvPairTest.cs index ee91486e..48f312ba 100644 --- a/NCDKTests/Smiles/InvPairTest.cs +++ b/NCDKTests/Smiles/InvPairTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Smiles @@ -40,7 +40,7 @@ public void TestInvPair() } [TestMethod()] - public void TestInvPair_long_IAtom() + public void TestInvPairLongIAtom() { IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()); InvPair pair = new InvPair(5L, atom); @@ -50,7 +50,7 @@ public void TestInvPair_long_IAtom() } [TestMethod()] - public void TestEquals_Object() + public void TestEqualsObject() { IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()); InvPair pair = new InvPair(5L, atom); @@ -69,7 +69,7 @@ public void TestToString() } [TestMethod()] - public void TestSetAtom_IAtom() + public void TestSetAtomIAtom() { IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()); InvPair pair = new InvPair(); @@ -123,12 +123,12 @@ public void TestCommit() IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()); InvPair pair = new InvPair(5L, atom); pair.Commit(); - Assert.IsNotNull(atom.GetProperty(InvPair.CanonicalLabelKey)); - Assert.AreEqual(5, ((long)atom.GetProperty(InvPair.CanonicalLabelKey))); + Assert.IsNotNull(atom.GetProperty(InvPair.CanonicalLabelPropertyKey)); + Assert.AreEqual(5, ((long)atom.GetProperty(InvPair.CanonicalLabelPropertyKey))); } [TestMethod()] - public void TestSetCurr_long() + public void TestSetCurrLong() { IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()); InvPair pair = new InvPair(5L, atom); @@ -146,7 +146,7 @@ public void TestGetCurr() } [TestMethod()] - public void TestSetLast_long() + public void TestSetLastLong() { IAtom atom = new Atom(ChemicalElements.Carbon.ToIElement()); InvPair pair = new InvPair(5L, atom); diff --git a/NCDKTests/Smiles/SMARTS/Parser/ParserTest.cs b/NCDKTests/Smiles/SMARTS/Parser/ParserTest.cs index 25fe1d6b..cc264356 100644 --- a/NCDKTests/Smiles/SMARTS/Parser/ParserTest.cs +++ b/NCDKTests/Smiles/SMARTS/Parser/ParserTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Isomorphisms.Matchers.SMARTS; +using NCDK.Silent; using System.IO; namespace NCDK.Smiles.SMARTS.Parser @@ -38,7 +39,7 @@ private void Parse(string smarts) [TestMethod()] public void TestQueryAtomCreation() { - var container = SMARTSParser.Parse("*", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("*", ChemObjectBuilder.Instance); Assert.AreEqual(1, container.Atoms.Count); IAtom atom = container.Atoms[0]; Assert.IsTrue(atom is SMARTSAtom); @@ -47,7 +48,7 @@ public void TestQueryAtomCreation() [TestMethod()] public void TestAliphaticAtom() { - var container = SMARTSParser.Parse("A", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("A", ChemObjectBuilder.Instance); Assert.AreEqual(1, container.Atoms.Count); IAtom atom = container.Atoms[0]; Assert.IsTrue(atom is SMARTSAtom); @@ -56,7 +57,7 @@ public void TestAliphaticAtom() [TestMethod()] public void TestAromaticAtom() { - var container = SMARTSParser.Parse("a", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("a", ChemObjectBuilder.Instance); Assert.AreEqual(1, container.Atoms.Count); IAtom atom = container.Atoms[0]; Assert.IsTrue(atom is SMARTSAtom); @@ -65,7 +66,7 @@ public void TestAromaticAtom() [TestMethod()] public void TestDegree() { - var container = SMARTSParser.Parse("[D2]", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("[D2]", ChemObjectBuilder.Instance); Assert.AreEqual(1, container.Atoms.Count); IAtom atom = container.Atoms[0]; Assert.IsTrue(atom is SMARTSAtom); @@ -74,7 +75,7 @@ public void TestDegree() [TestMethod()] public void TestImplicitHCount() { - var container = SMARTSParser.Parse("[h3]", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("[h3]", ChemObjectBuilder.Instance); Assert.AreEqual(1, container.Atoms.Count); IAtom atom = container.Atoms[0]; Assert.IsTrue(atom is SMARTSAtom); @@ -83,7 +84,7 @@ public void TestImplicitHCount() [TestMethod()] public void TestTotalHCount() { - var container = SMARTSParser.Parse("[H2]", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("[H2]", ChemObjectBuilder.Instance); Assert.AreEqual(1, container.Atoms.Count); IAtom atom = container.Atoms[0]; Assert.IsTrue(atom is SMARTSAtom); @@ -95,7 +96,7 @@ public void TestTotalHCount() [TestMethod()] public void TestSingleBond() { - var container = SMARTSParser.Parse("C-C", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("C-C", ChemObjectBuilder.Instance); Assert.AreEqual(2, container.Atoms.Count); Assert.AreEqual(1, container.Bonds.Count); IBond bond = container.Bonds[0]; @@ -107,7 +108,7 @@ public void TestSingleBond() [TestMethod()] public void TestDoubleBond() { - var container = SMARTSParser.Parse("C=C", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("C=C", ChemObjectBuilder.Instance); Assert.AreEqual(2, container.Atoms.Count); Assert.AreEqual(1, container.Bonds.Count); IBond bond = container.Bonds[0]; @@ -119,7 +120,7 @@ public void TestDoubleBond() [TestMethod()] public void TestTripleBond() { - var container = SMARTSParser.Parse("C#C", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("C#C", ChemObjectBuilder.Instance); Assert.AreEqual(2, container.Atoms.Count); Assert.AreEqual(1, container.Bonds.Count); IBond bond = container.Bonds[0]; @@ -131,7 +132,7 @@ public void TestTripleBond() [TestMethod()] public void TestAromaticBond() { - var container = SMARTSParser.Parse("C:C", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("C:C", ChemObjectBuilder.Instance); Assert.AreEqual(2, container.Atoms.Count); Assert.AreEqual(1, container.Bonds.Count); IBond bond = container.Bonds[0]; @@ -141,7 +142,7 @@ public void TestAromaticBond() [TestMethod()] public void TestAnyOrderBond() { - var container = SMARTSParser.Parse("C~C", Default.ChemObjectBuilder.Instance); + var container = SMARTSParser.Parse("C~C", ChemObjectBuilder.Instance); Assert.AreEqual(2, container.Atoms.Count); Assert.AreEqual(1, container.Bonds.Count); IBond bond = container.Bonds[0]; @@ -154,7 +155,7 @@ public void TestAnyOrderBond() [TestMethod()] public void Test2LetterSMARTS() { - var query = SMARTSParser.Parse("Sc1ccccc1", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("Sc1ccccc1", ChemObjectBuilder.Instance); Assert.AreEqual(7, query.Atoms.Count); Assert.AreEqual("S", query.Atoms[0].Symbol); } diff --git a/NCDKTests/Smiles/SMARTS/Parser/RecursiveTest.cs b/NCDKTests/Smiles/SMARTS/Parser/RecursiveTest.cs index e69513b0..daa1e25d 100644 --- a/NCDKTests/Smiles/SMARTS/Parser/RecursiveTest.cs +++ b/NCDKTests/Smiles/SMARTS/Parser/RecursiveTest.cs @@ -22,8 +22,10 @@ using NCDK.Common.Base; using NCDK.Graphs; using NCDK.IO.Iterator; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System.IO; +using System.Linq; using static NCDK.Smiles.SMARTS.Parser.SMARTSSearchTest; namespace NCDK.Smiles.SMARTS.Parser @@ -42,8 +44,8 @@ public class RecursiveTest : CDKTestCase public void Match(string smarts, string smiles) { - SMARTSQueryTool sqt = new SMARTSQueryTool(smarts, Default.ChemObjectBuilder.Instance); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool(smarts, ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles(smiles); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(atomContainer); Aromaticity.CDKLegacy.Apply(atomContainer); @@ -51,7 +53,7 @@ public void Match(string smarts, string smiles) if (status) { nmatch = sqt.MatchesCount; - nqmatch = sqt.GetUniqueMatchingAtoms().Count; + nqmatch = sqt.GetUniqueMatchingAtoms().Count(); } else { @@ -443,9 +445,9 @@ public void TestBasicAmineOnDrugs_cdkAromaticModel() { string filename = "drugs.smi"; var ins = ResourceLoader.GetAsStream(GetType(), filename); - using (EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, Default.ChemObjectBuilder.Instance)) + using (EnumerableSMILESReader reader = new EnumerableSMILESReader(ins, ChemObjectBuilder.Instance)) { - SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;H2,H1;!$(NC=O)]", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;H2,H1;!$(NC=O)]", ChemObjectBuilder.Instance); sqt.SetAromaticity(new Aromaticity(ElectronDonation.CDKModel, Cycles.CDKAromaticSetFinder)); int nmatch = 0; int nmol = 0; @@ -483,11 +485,11 @@ public void TestBasicAmineOnDrugs() string filename = "drugs.smi"; var ins = ResourceLoader.GetAsStream(GetType(), filename); - SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;H2,H1;!$(NC=O)]", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;H2,H1;!$(NC=O)]", ChemObjectBuilder.Instance); // iterating SMILES reader doesn't allow us to turn off automatic aromaticity // perception - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); int nmatch = 0; int nmol = 0; diff --git a/NCDKTests/Smiles/SMARTS/Parser/SMARTSSearchTest.cs b/NCDKTests/Smiles/SMARTS/Parser/SMARTSSearchTest.cs index 7010e7af..a326604d 100644 --- a/NCDKTests/Smiles/SMARTS/Parser/SMARTSSearchTest.cs +++ b/NCDKTests/Smiles/SMARTS/Parser/SMARTSSearchTest.cs @@ -19,7 +19,7 @@ using NCDK.Common.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; using NCDK.IO; using NCDK.Isomorphisms; @@ -55,14 +55,14 @@ internal static IAtomContainer SmilesAtomTyped(string smiles) internal static IAtomContainer CreateFromSmiles(string smiles, bool perserveAromaticity) { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(!perserveAromaticity); return sp.ParseSmiles(smiles); } internal static SMARTSQueryTool CreateFromSmarts(string smarts) { - SMARTSQueryTool sqt = new SMARTSQueryTool(smarts, Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool(smarts, ChemObjectBuilder.Instance); return sqt; } @@ -71,7 +71,7 @@ internal static int[] Match(SMARTSQueryTool sqt, IAtomContainer m) bool status = sqt.Matches(m); if (status) { - return new int[] { sqt.MatchesCount, sqt.GetUniqueMatchingAtoms().Count }; + return new int[] { sqt.MatchesCount, sqt.GetUniqueMatchingAtoms().Count() }; } else { @@ -95,12 +95,12 @@ public void TestMoleculeFromSDF() var cList = ChemFileManipulator.GetAllAtomContainers(content).ToList(); IAtomContainer atomContainer = cList[0]; - SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;h1,h2,H1,H2;!$(NC=O)]", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("[NX3;h1,h2,H1,H2;!$(NC=O)]", ChemObjectBuilder.Instance); bool status = sqt.Matches(atomContainer); Assert.AreEqual(true, status); int nmatch = sqt.MatchesCount; - int nqmatch = sqt.GetUniqueMatchingAtoms().Count; + int nqmatch = sqt.GetUniqueMatchingAtoms().Count(); Assert.AreEqual(3, nmatch); Assert.AreEqual(3, nqmatch); @@ -113,9 +113,9 @@ public void TestMoleculeFromSDF() [TestMethod()] public void TestRGraphBond() { - var query = SMARTSParser.Parse("CC=O", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("CC=O", ChemObjectBuilder.Instance); Debug.WriteLine("Query c:c: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC=O"); // benzene, aromatic Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); @@ -124,9 +124,9 @@ public void TestRGraphBond() [TestMethod()] public void TestAromaticBond() { - var query = SMARTSParser.Parse("c:c", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("c:c", ChemObjectBuilder.Instance); Debug.WriteLine("Query c:c: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer atomContainer = sp.ParseSmiles("c1ccccc1"); // benzene, aromatic Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); @@ -138,9 +138,9 @@ public void TestAromaticBond() [TestMethod()] public void TestSingleBond() { - var query = SMARTSParser.Parse("C-C", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("C-C", ChemObjectBuilder.Instance); Debug.WriteLine("Query C-C: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); @@ -155,9 +155,9 @@ public void TestSingleBond() [TestMethod()] public void TestDoubleBond() { - var query = SMARTSParser.Parse("C=C", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("C=C", ChemObjectBuilder.Instance); Debug.WriteLine("Query C=C: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query)); @@ -172,9 +172,9 @@ public void TestDoubleBond() [TestMethod()] public void TestTripleBond() { - var query = SMARTSParser.Parse("C#C", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("C#C", ChemObjectBuilder.Instance); Debug.WriteLine("Query C#C: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsFalse(uiTester.IsSubgraph(atomContainer, query)); @@ -189,9 +189,9 @@ public void TestTripleBond() [TestMethod()] public void TestAnyOrderBond() { - var query = SMARTSParser.Parse("C~C", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("C~C", ChemObjectBuilder.Instance); Debug.WriteLine("Query C~C: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); @@ -206,9 +206,9 @@ public void TestAnyOrderBond() [TestMethod()] public void TestAnyAtom() { - var query = SMARTSParser.Parse("C*C", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("C*C", ChemObjectBuilder.Instance); Debug.WriteLine("Query C*C: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); @@ -223,9 +223,9 @@ public void TestAnyAtom() [TestMethod()] public void TestAliphaticAtom() { - var query = SMARTSParser.Parse("CAC", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("CAC", ChemObjectBuilder.Instance); Debug.WriteLine("Query CAC: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); @@ -240,9 +240,9 @@ public void TestAliphaticAtom() [TestMethod()] public void TestAromaticAtom() { - var query = SMARTSParser.Parse("aaa", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("aaa", ChemObjectBuilder.Instance); Debug.WriteLine("Query CaC: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); @@ -255,9 +255,9 @@ public void TestAromaticAtom() [TestMethod()] public void TestSymbolQueryAtom() { - var query = SMARTSParser.Parse("CCC", Default.ChemObjectBuilder.Instance); + var query = SMARTSParser.Parse("CCC", ChemObjectBuilder.Instance); Debug.WriteLine("Query CAC: " + query.ToString()); - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CCC"); Assert.IsTrue(uiTester.IsSubgraph(atomContainer, query)); diff --git a/NCDKTests/Smiles/SMARTS/Parser/SmartsQueryVisitorTest.cs b/NCDKTests/Smiles/SMARTS/Parser/SmartsQueryVisitorTest.cs index 8f0bf689..9ec843f6 100644 --- a/NCDKTests/Smiles/SMARTS/Parser/SmartsQueryVisitorTest.cs +++ b/NCDKTests/Smiles/SMARTS/Parser/SmartsQueryVisitorTest.cs @@ -17,6 +17,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.IO; namespace NCDK.Smiles.SMARTS.Parser @@ -35,7 +36,7 @@ public void Visit(string smarts) { SMARTSParser parser = new SMARTSParser(new StringReader(smarts)); ASTStart start = parser.Start(); - SmartsQueryVisitor visitor = new SmartsQueryVisitor(Default.ChemObjectBuilder.Instance); + SmartsQueryVisitor visitor = new SmartsQueryVisitor(ChemObjectBuilder.Instance); visitor.Visit(start, null); } diff --git a/NCDKTests/Smiles/SMARTS/Parser/SmartsStereoTest.cs b/NCDKTests/Smiles/SMARTS/Parser/SmartsStereoTest.cs index 8a1d81d9..41fa1602 100644 --- a/NCDKTests/Smiles/SMARTS/Parser/SmartsStereoTest.cs +++ b/NCDKTests/Smiles/SMARTS/Parser/SmartsStereoTest.cs @@ -22,6 +22,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 U */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.Linq; namespace NCDK.Smiles.SMARTS.Parser @@ -190,7 +191,7 @@ static IAtomContainer CreateFromSmiles(string smiles) static SMARTSQueryTool CreateFromSmarts(string smarts) { - return new SMARTSQueryTool(smarts, Default.ChemObjectBuilder.Instance); + return new SMARTSQueryTool(smarts, ChemObjectBuilder.Instance); } private static readonly SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); diff --git a/NCDKTests/Smiles/SMARTS/SMARTSQueryToolTest.cs b/NCDKTests/Smiles/SMARTS/SMARTSQueryToolTest.cs index 4d73025b..a277c850 100644 --- a/NCDKTests/Smiles/SMARTS/SMARTSQueryToolTest.cs +++ b/NCDKTests/Smiles/SMARTS/SMARTSQueryToolTest.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; using System.Linq; +using NCDK.Silent; namespace NCDK.Smiles.SMARTS { @@ -42,15 +43,15 @@ public class SMARTSQueryToolTest : CDKTestCase [ExpectedException(typeof(ArgumentException))] public void TestLexicalError() { - SMARTSQueryTool sqt = new SMARTSQueryTool("Epoxide", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("Epoxide", ChemObjectBuilder.Instance); } [TestMethod()] public void TestQueryTool() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("CC(=O)OC(=O)C"); - SMARTSQueryTool querytool = new SMARTSQueryTool("O=CO", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("O=CO", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); Assert.IsTrue(status); @@ -61,7 +62,7 @@ public void TestQueryTool() List map1 = new List { 1, 2, 3, }; List map2 = new List { 3, 4, 5, }; - var mappings = querytool.GetMatchingAtoms(); + var mappings = querytool.GetMatchingAtoms().ToList(); var ret1 = mappings[0].OrderBy(n => n).ToList(); for (int i = 0; i < 3; i++) { @@ -78,9 +79,9 @@ public void TestQueryTool() [TestMethod()] public void TestQueryToolSingleAtomCase() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("C1CCC12CCCC2"); - SMARTSQueryTool querytool = new SMARTSQueryTool("C", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("C", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); Assert.IsTrue(status); @@ -92,9 +93,9 @@ public void TestQueryToolSingleAtomCase() [TestMethod()] public void TestQueryToolReSetSmarts() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("C1CCC12CCCC2"); - SMARTSQueryTool querytool = new SMARTSQueryTool("C", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("C", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); Assert.IsTrue(status); @@ -110,17 +111,17 @@ public void TestQueryToolReSetSmarts() Assert.AreEqual(18, nmatch); var umatch = querytool.GetUniqueMatchingAtoms(); - Assert.AreEqual(9, umatch.Count); + Assert.AreEqual(9, umatch.Count()); } [TestMethod()] public void TestUniqueQueries() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("c1ccccc1CCCNCCCc1ccccc1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(atomContainer); Aromaticity.CDKLegacy.Apply(atomContainer); - SMARTSQueryTool querytool = new SMARTSQueryTool("c1ccccc1", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("c1ccccc1", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); Assert.IsTrue(status); @@ -129,17 +130,17 @@ public void TestUniqueQueries() Assert.AreEqual(24, nmatch); var umatch = querytool.GetUniqueMatchingAtoms(); - Assert.AreEqual(2, umatch.Count); + Assert.AreEqual(2, umatch.Count()); } [TestMethod()] public void TestQuery() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer atomContainer = sp.ParseSmiles("c12cc(CCN)ccc1c(COC)ccc2"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(atomContainer); Aromaticity.CDKLegacy.Apply(atomContainer); - SMARTSQueryTool querytool = new SMARTSQueryTool("c12ccccc1cccc2", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool("c12ccccc1cccc2", ChemObjectBuilder.Instance); bool status = querytool.Matches(atomContainer); Assert.IsTrue(status); @@ -148,7 +149,7 @@ public void TestQuery() Assert.AreEqual(4, nmatch); var umatch = querytool.GetUniqueMatchingAtoms(); - Assert.AreEqual(1, umatch.Count); + Assert.AreEqual(1, umatch.Count()); } /// @@ -167,10 +168,10 @@ public void TestIndoleAgainstItself() Aromaticity.CDKLegacy.Apply(indole); SmilesGenerator generator = new SmilesGenerator().Aromatic(); string indoleSmiles = generator.Create(indole); - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); indole = smilesParser.ParseSmiles(indoleSmiles); - SMARTSQueryTool querytool = new SMARTSQueryTool(indoleSmiles, Default.ChemObjectBuilder.Instance); + SMARTSQueryTool querytool = new SMARTSQueryTool(indoleSmiles, ChemObjectBuilder.Instance); Assert.IsTrue(querytool.Matches(indole)); } @@ -183,7 +184,7 @@ public void TestMethane() carbon.ImplicitHydrogenCount = 4; methane.Atoms.Add(carbon); - SMARTSQueryTool sqt = new SMARTSQueryTool("CC", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("CC", ChemObjectBuilder.Instance); bool matches = sqt.Matches(methane); Assert.IsFalse(matches); } @@ -192,14 +193,14 @@ public void TestMethane() [ExpectedException(typeof(ArgumentNullException))] public void NullAromaticity() { - SMARTSQueryTool sqt = new SMARTSQueryTool("CC", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("CC", ChemObjectBuilder.Instance); sqt.SetAromaticity(null); } [TestMethod()] public void SetAromaticity() { - SMARTSQueryTool sqt = new SMARTSQueryTool("[a]", Default.ChemObjectBuilder.Instance); + SMARTSQueryTool sqt = new SMARTSQueryTool("[a]", ChemObjectBuilder.Instance); IAtomContainer furan = CreateFromSmiles("O1C=CC=C1"); diff --git a/NCDKTests/Smiles/SmilesGeneratorTest.cs b/NCDKTests/Smiles/SmilesGeneratorTest.cs index 1058dd3c..e7d9944d 100644 --- a/NCDKTests/Smiles/SmilesGeneratorTest.cs +++ b/NCDKTests/Smiles/SmilesGeneratorTest.cs @@ -20,7 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; using NCDK.IO; using NCDK.Isomorphisms; @@ -122,7 +122,7 @@ public void TestAlanin() mol1.AddBond(mol1.Atoms[5], mol1.Atoms[12], BondOrder.Single); AddImplicitHydrogens(mol1); - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; ifac.ConfigureAtoms(mol1); Define(mol1, Anticlockwise(mol1, 1, 0, 2, 3, 4)); @@ -142,7 +142,7 @@ public void TestAlanin() [TestMethod()] public void TestCisResorcinol() { - IAtomContainer mol1 = Default.ChemObjectBuilder.Instance.NewAtomContainer(); + IAtomContainer mol1 = ChemObjectBuilder.Instance.NewAtomContainer(); SmilesGenerator sg = SmilesGenerator.Isomeric(); mol1.Atoms.Add(new Atom("O", new Vector2(3, 1))); // 1 @@ -208,7 +208,7 @@ public void TestCisResorcinol() mol1.AddBond(mol1.Atoms[8], mol1.Atoms[19], BondOrder.Single); AddImplicitHydrogens(mol1); - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; ifac.ConfigureAtoms(mol1); Define(mol1, Clockwise(mol1, 2, 0, 1, 3, 7), Clockwise(mol1, 7, 2, 6, 8, 9)); @@ -292,7 +292,7 @@ public void TestCisTransDecalin() mol1.Atoms.Add(new Atom("H", new Vector2(-0.84, -2.75))); mol1.AddBond(mol1.Atoms[11], mol1.Atoms[27], BondOrder.Single); AddImplicitHydrogens(mol1); - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; ifac.ConfigureAtoms(mol1); Define(mol1, Clockwise(mol1, 1, 0, 2, 4, 8), Clockwise(mol1, 2, 1, 3, 7, 1)); string smiles1 = sg.Create(mol1); @@ -334,7 +334,7 @@ public void TestDoubleBondConfiguration() mol1.AddBond(mol1.Atoms[3], mol1.Atoms[5], BondOrder.Single); // 4 AddImplicitHydrogens(mol1); - IsotopeFactory ifac = Isotopes.Instance; + IsotopeFactory ifac = BODRIsotopeFactory.Instance; ifac.ConfigureAtoms(mol1); mol1.StereoElements.Clear(); // clear existing @@ -385,16 +385,17 @@ public void TestPartitioning() string smiles = ""; IAtomContainer molecule = new AtomContainer(); SmilesGenerator sg = new SmilesGenerator(); - Atom sodium = new Atom("Na"); - sodium.FormalCharge = +1; - Atom hydroxyl = new Atom("O"); - hydroxyl.ImplicitHydrogenCount = 1; - hydroxyl.FormalCharge = -1; + Atom sodium = new Atom("Na") { FormalCharge = +1 }; + Atom hydroxyl = new Atom("O") + { + ImplicitHydrogenCount = 1, + FormalCharge = -1 + }; molecule.Atoms.Add(sodium); molecule.Atoms.Add(hydroxyl); AddImplicitHydrogens(molecule); smiles = sg.Create(molecule); - Assert.IsTrue(smiles.IndexOf(".") != -1); + Assert.IsTrue(smiles.IndexOf(".", StringComparison.Ordinal) != -1); } // @cdk.bug 791091 @@ -427,8 +428,7 @@ public void TestBug590236() IAtomContainer molecule = new AtomContainer(); SmilesGenerator sg = SmilesGenerator.Isomeric(); molecule.Atoms.Add(new Atom("C")); - Atom carbon2 = new Atom("C"); - carbon2.MassNumber = 13; + Atom carbon2 = new Atom("C") { MassNumber = 13 }; molecule.Atoms.Add(carbon2); molecule.AddBond(molecule.Atoms[0], molecule.Atoms[1], BondOrder.Single); FixCarbonHCount(molecule); @@ -446,9 +446,11 @@ public void TestSFBug956923_aromatic() string smiles = ""; IAtomContainer molecule = new AtomContainer(); SmilesGenerator sg = new SmilesGenerator().Aromatic(); - Atom sp2CarbonWithOneHydrogen = new Atom("C"); - sp2CarbonWithOneHydrogen.Hybridization = Hybridization.SP2; - sp2CarbonWithOneHydrogen.ImplicitHydrogenCount = 1; + Atom sp2CarbonWithOneHydrogen = new Atom("C") + { + Hybridization = Hybridization.SP2, + ImplicitHydrogenCount = 1 + }; molecule.Atoms.Add(sp2CarbonWithOneHydrogen); molecule.Atoms.Add((Atom)sp2CarbonWithOneHydrogen.Clone()); molecule.Atoms.Add((Atom)sp2CarbonWithOneHydrogen.Clone()); @@ -473,9 +475,11 @@ public void TestSFBug956923_nonAromatic() string smiles = ""; IAtomContainer molecule = new AtomContainer(); SmilesGenerator sg = new SmilesGenerator(); - Atom sp2CarbonWithOneHydrogen = new Atom("C"); - sp2CarbonWithOneHydrogen.Hybridization = Hybridization.SP2; - sp2CarbonWithOneHydrogen.ImplicitHydrogenCount = 1; + Atom sp2CarbonWithOneHydrogen = new Atom("C") + { + Hybridization = Hybridization.SP2, + ImplicitHydrogenCount = 1 + }; molecule.Atoms.Add(sp2CarbonWithOneHydrogen); molecule.Atoms.Add((Atom)sp2CarbonWithOneHydrogen.Clone()); molecule.Atoms.Add((Atom)sp2CarbonWithOneHydrogen.Clone()); @@ -548,7 +552,7 @@ public void TestBondPermutation() } } - private void FixCarbonHCount(IAtomContainer mol) + private static void FixCarbonHCount(IAtomContainer mol) { // the following line are just a quick fix for this particluar // carbon-only molecule until we have a proper hydrogen count @@ -560,13 +564,14 @@ private void FixCarbonHCount(IAtomContainer mol) atom = mol.Atoms[f]; bondCount = mol.GetBondOrderSum(atom); int correction = (int)(bondCount - (atom.Charge ?? 0)); - if (atom.Symbol.Equals("C")) - { - atom.ImplicitHydrogenCount = 4 - correction; - } - else if (atom.Symbol.Equals("N")) + switch (atom.Symbol) { - atom.ImplicitHydrogenCount = 3 - correction; + case "C": + atom.ImplicitHydrogenCount = 4 - correction; + break; + case "N": + atom.ImplicitHydrogenCount = 3 - correction; + break; } } } @@ -575,7 +580,7 @@ private void FixCarbonHCount(IAtomContainer mol) public void TestPseudoAtom() { IAtom atom = new PseudoAtom("Star"); - SmilesGenerator sg = new SmilesGenerator(SmiFlavor.Generic); + SmilesGenerator sg = new SmilesGenerator(SmiFlavors.Generic); string smiles = ""; IAtomContainer molecule = new AtomContainer(); molecule.Atoms.Add(atom); @@ -605,9 +610,9 @@ public void TestReactionSMILES() methane.Atoms[0].ImplicitHydrogenCount = 4; gold.Atoms[0].ImplicitHydrogenCount = 0; - SmilesGenerator sg = new SmilesGenerator(SmiFlavor.Generic); + SmilesGenerator sg = new SmilesGenerator(SmiFlavors.Generic); string smiles = sg.Create(reaction); - //Debug.WriteLine("Generated SMILES: " + smiles); + //Debug.WriteLine($"Generated SMILES: {smiles}"); Assert.AreEqual("C>*>[Au]", smiles); } @@ -620,11 +625,11 @@ public void TestAlaSMILES() string filename = "NCDK.Data.MDL.l-ala.mol"; var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); - IAtomContainer mol1 = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol1 = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); filename = "NCDK.Data.MDL.d-ala.mol"; ins = ResourceLoader.GetAsStream(filename); reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); - IAtomContainer mol2 = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol2 = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); SmilesGenerator sg = SmilesGenerator.Isomeric(); Define(mol1, Anticlockwise(mol1, 1, 0, 2, 3, 6)); @@ -697,7 +702,7 @@ public void TestCycloOctadien() string filename = "NCDK.Data.MDL.cyclooctadien.mol"; var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); - IAtomContainer mol1 = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol1 = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); SmilesGenerator sg = new SmilesGenerator(); string moleculeSmile = sg.Create(mol1); Assert.AreEqual("C=1\\CC/C=C\\CC/C1", moleculeSmile); @@ -865,7 +870,7 @@ public void TestIndole() SmilesGenerator smilesGenerator = new SmilesGenerator().Aromatic(); string smiles = smilesGenerator.Create(mol); - Assert.IsTrue(smiles.IndexOf("[nH]") >= 0); + Assert.IsTrue(smiles.Contains("[nH]")); } [TestMethod()] @@ -877,7 +882,7 @@ public void TestPyrrole() Aromaticity.CDKLegacy.Apply(mol); SmilesGenerator smilesGenerator = new SmilesGenerator().Aromatic(); string smiles = smilesGenerator.Create(mol); - Assert.IsTrue(smiles.IndexOf("[nH]") >= 0); + Assert.IsTrue(smiles.Contains("[nH]")); } // @cdk.bug 1300 @@ -932,17 +937,17 @@ public void TestSFBug2051597() { string smiles = "c1(c2ccc(c8ccccc8)cc2)" + "c(c3ccc(c9ccccc9)cc3)" + "c(c4ccc(c%10ccccc%10)cc4)" + "c(c5ccc(c%11ccccc%11)cc5)" + "c(c6ccc(c%12ccccc%12)cc6)" + "c1(c7ccc(c%13ccccc%13)cc7)"; - SmilesParser smilesParser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser smilesParser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer cdkMol = smilesParser.ParseSmiles(smiles); SmilesGenerator smilesGenerator = new SmilesGenerator(); string genSmiles = smilesGenerator.Create(cdkMol); // check that we have the appropriate ring closure symbols - Assert.IsTrue(genSmiles.IndexOf("%") >= 0, "There were'nt any % ring closures in the output"); - Assert.IsTrue(genSmiles.IndexOf("%10") >= 0); - Assert.IsTrue(genSmiles.IndexOf("%11") >= 0); - Assert.IsTrue(genSmiles.IndexOf("%12") >= 0); - Assert.IsTrue(genSmiles.IndexOf("%13") >= 0); + Assert.IsTrue(genSmiles.Contains("%"), "There were'nt any % ring closures in the output"); + Assert.IsTrue(genSmiles.Contains("%10")); + Assert.IsTrue(genSmiles.Contains("%11")); + Assert.IsTrue(genSmiles.Contains("%12")); + Assert.IsTrue(genSmiles.Contains("%13")); // check that we can read in the SMILES we got IAtomContainer cdkRoundTripMol = smilesParser.ParseSmiles(genSmiles); @@ -953,7 +958,7 @@ public void TestSFBug2051597() [TestMethod()] public void TestRoundTripPseudoAtom() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "[12*H2-]"; IAtomContainer mol = sp.ParseSmiles(smiles); SmilesGenerator smilesGenerator = SmilesGenerator.Isomeric(); @@ -965,19 +970,19 @@ public void TestRoundTripPseudoAtom() [TestMethod()] public void TestBug2781199() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string smiles = "n1ncn(c1)CC"; IAtomContainer mol = sp.ParseSmiles(smiles); SmilesGenerator smilesGenerator = new SmilesGenerator().Aromatic(); string genSmiles = smilesGenerator.Create(mol); - Assert.IsTrue(genSmiles.IndexOf("H") == -1, "Generated SMILES should not have explicit H: " + genSmiles); + Assert.IsFalse(genSmiles.Contains("H"), "Generated SMILES should not have explicit H: " + genSmiles); } // @cdk.bug 2898032 [TestMethod()] public void TestCanSmiWithoutConfiguredAtoms() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string s1 = "OC(=O)C(Br)(Cl)N"; string s2 = "ClC(Br)(N)C(=O)O"; @@ -988,21 +993,21 @@ public void TestCanSmiWithoutConfiguredAtoms() string o1 = sg.Create(m1); string o2 = sg.Create(m2); - Assert.IsTrue(o1.Equals(o2), "The two canonical SMILES should match"); + Assert.AreEqual(o1, o2, "The two canonical SMILES should match"); } // @cdk.bug 2898032 [TestMethod()] public void TestCanSmiWithConfiguredAtoms() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string s1 = "OC(=O)C(Br)(Cl)N"; string s2 = "ClC(Br)(N)C(=O)O"; IAtomContainer m1 = sp.ParseSmiles(s1); IAtomContainer m2 = sp.ParseSmiles(s2); - IsotopeFactory fact = Isotopes.Instance; + IsotopeFactory fact = BODRIsotopeFactory.Instance; fact.ConfigureAtoms(m1); fact.ConfigureAtoms(m2); @@ -1010,17 +1015,17 @@ public void TestCanSmiWithConfiguredAtoms() string o1 = sg.Create(m1); string o2 = sg.Create(m2); - Assert.IsTrue(o1.Equals(o2), "The two canonical SMILES should match"); + Assert.AreEqual(o1, o2, "The two canonical SMILES should match"); } // @cdk.bug 3040273 [TestMethod()] public void TestBug3040273() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); string testSmiles = "C1(C(C(C(C(C1Br)Br)Br)Br)Br)Br"; IAtomContainer mol = sp.ParseSmiles(testSmiles); - IsotopeFactory fact = Isotopes.Instance; + IsotopeFactory fact = BODRIsotopeFactory.Instance; fact.ConfigureAtoms(mol); SmilesGenerator sg = new SmilesGenerator(); string smiles = sg.Create((IAtomContainer)mol); @@ -1159,7 +1164,7 @@ public void CanonicalReactions() IReaction r1 = smipar.ParseReactionSmiles("CC(C)C1=CC=CC=C1.C(CC(=O)Cl)CCl>[Al+3].[Cl-].[Cl-].[Cl-].C(Cl)Cl>CC(C)C1=CC=C(C=C1)C(=O)CCCCl"); IReaction r2 = smipar.ParseReactionSmiles("C(CC(=O)Cl)CCl.CC(C)C1=CC=CC=C1>[Al+3].[Cl-].[Cl-].[Cl-].C(Cl)Cl>CC(C)C1=CC=C(C=C1)C(=O)CCCCl"); IReaction r3 = smipar.ParseReactionSmiles("CC(C)C1=CC=CC=C1.C(CC(=O)Cl)CCl>C(Cl)Cl.[Al+3].[Cl-].[Cl-].[Cl-]>CC(C)C1=CC=C(C=C1)C(=O)CCCCl"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Canonical); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Canonical); Assert.AreEqual(smigen.Create(r2), smigen.Create(r1)); Assert.AreEqual(smigen.Create(r3), smigen.Create(r2)); } @@ -1172,7 +1177,7 @@ public void InconsistentAromaticState() IAtomContainer mol = smipar.ParseSmiles("c1ccccc1"); foreach (IAtom atom in mol.Atoms) atom.IsAromatic = false; - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.UseAromaticSymbols); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.UseAromaticSymbols); smigen.Create(mol); } @@ -1181,7 +1186,7 @@ public void StrictIsotopes() { SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); IAtomContainer mol = smipar.ParseSmiles("[12CH3]C"); - Assert.AreEqual("[12CH3]C", new SmilesGenerator(SmiFlavor.AtomicMassStrict).Create(mol)); + Assert.AreEqual("[12CH3]C", new SmilesGenerator(SmiFlavors.AtomicMassStrict).Create(mol)); } [TestMethod()] @@ -1189,7 +1194,7 @@ public void TestIsotopes() { SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); IAtomContainer mol = smipar.ParseSmiles("[12CH3]C"); - Assert.AreEqual("[12CH3]C", new SmilesGenerator(SmiFlavor.AtomicMass).Create(mol)); + Assert.AreEqual("[12CH3]C", new SmilesGenerator(SmiFlavors.AtomicMass).Create(mol)); } static ITetrahedralChirality Anticlockwise(IAtomContainer container, int central, int a1, int a2, int a3, int a4) @@ -1206,9 +1211,9 @@ static ITetrahedralChirality Clockwise(IAtomContainer container, int central, in TetrahedralStereo.Clockwise); } - static void Define(IAtomContainer container, params IReadOnlyStereoElement[] elements) + static void Define(IAtomContainer container, params IStereoElement[] elements) { - container.SetStereoElements(new List>(elements)); + container.SetStereoElements(new List>(elements)); } static string Canon(string smi) @@ -1217,7 +1222,7 @@ static string Canon(string smi) SmilesParser smipar = new SmilesParser(bldr); IAtomContainer container = smipar.ParseSmiles(smi); AtomContainerManipulator.SuppressHydrogens(container); - Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllFinder); + Aromaticity arom = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); arom.Apply(container); return SmilesGenerator.Unique().Create(container); } diff --git a/NCDKTests/Smiles/SmilesParserTest.cs b/NCDKTests/Smiles/SmilesParserTest.cs index 3baba392..0a5a529f 100644 --- a/NCDKTests/Smiles/SmilesParserTest.cs +++ b/NCDKTests/Smiles/SmilesParserTest.cs @@ -30,6 +30,7 @@ using NCDK.Isomorphisms; using NCDK.Stereo; +using NCDK.Silent; namespace NCDK.Smiles { @@ -953,7 +954,7 @@ public void TestSFBug956921() [Timeout(1000)] public void TestSFBug1274464() { - IAtomContainer fromSmiles = new SmilesParser(Default.ChemObjectBuilder.Instance).ParseSmiles("C1=CC=CC=C1"); + IAtomContainer fromSmiles = new SmilesParser(ChemObjectBuilder.Instance).ParseSmiles("C1=CC=CC=C1"); IAtomContainer fromFactory = TestMoleculeFactory.MakeBenzene(); CDKHydrogenAdder hAdder = CDKHydrogenAdder.GetInstance(fromFactory.Builder); CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(fromFactory.Builder); @@ -1802,7 +1803,7 @@ public void TestIndole2() public void TestBug1963731() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = sp.ParseSmiles("C(C1C(C(C(C(O1)O)N)O)O)O"); int hcount = 0; for (int i = 0; i < molecule.Bonds.Count; i++) @@ -1815,7 +1816,7 @@ public void TestBug1963731() [TestMethod()] public void TestONSSolubility1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer molecule = sp.ParseSmiles("Oc1ccc(cc1OC)C=O"); Assert.AreEqual(11, molecule.Atoms.Count); Assert.AreEqual(11, molecule.Bonds.Count); @@ -1824,9 +1825,9 @@ public void TestONSSolubility1() [TestMethod()] public void Test1456139() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("Cc1nn(C)cc1[C@H]2[C@H](C(=O)N)C(=O)C[C@@](C)(O)[C@@H]2C(=O)N"); - IAtomContainer mol2 = Default.ChemObjectBuilder.Instance.NewAtomContainer(mol); + IAtomContainer mol2 = ChemObjectBuilder.Instance.NewAtomContainer(mol); Assert.IsNotNull(mol2); Assert.AreEqual(22, mol2.Atoms.Count); } @@ -1834,7 +1835,7 @@ public void Test1456139() [TestMethod()] public void TestExplicitH() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol; mol = p.ParseSmiles("CO[H]"); @@ -1851,7 +1852,7 @@ public void TestExplicitH() [TestMethod()] public void Testno937() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C[nH0]1c[nH0]cc1"); // xlogp training set molecule no937 Assert.IsNotNull(mol.Atoms[1].ImplicitHydrogenCount); Assert.AreEqual(0, mol.Atoms[1].ImplicitHydrogenCount.Value); @@ -1863,7 +1864,7 @@ public void Testno937() [TestMethod()] public void TestHardcodedH() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C[CH1]NC"); Assert.IsNotNull(mol.Atoms[1].ImplicitHydrogenCount); Assert.AreEqual(1, mol.Atoms[1].ImplicitHydrogenCount.Value); @@ -1882,7 +1883,7 @@ public void TestHardcodedH() [ExpectedException(typeof(InvalidSmilesException))] public void TestBadRingClosure1() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); p.ParseSmiles("c1ccccc1Cc1ccccc"); } @@ -1891,7 +1892,7 @@ public void TestBadRingClosure1() [ExpectedException(typeof(InvalidSmilesException))] public void TestBadRingClosure2() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); p.ParseSmiles("NC1=CC=C(N)C=C"); } @@ -1902,7 +1903,7 @@ public void TestBadRingClosure2() [TestMethod()] public void TestPyrrole_2() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("c1c[nH]cc1"); Assert.AreEqual(BondOrder.Double, mol.GetBond(mol.Atoms[0], mol.Atoms[1]).Order); @@ -1924,7 +1925,7 @@ public void TestPyrrole_2() [TestMethod()] public void TestAromaticSeParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); // The CDK aromaticity model does not recognise 'se' but we can still // parse it from the SMILES p.Kekulise(false); @@ -1939,7 +1940,7 @@ public void TestAromaticSeParsing() [TestMethod()] public void TestCeParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("Cl[Ce](Cl)Cl"); Assert.AreEqual("Ce", mol.Atoms[1].Symbol); } @@ -1948,7 +1949,7 @@ public void TestCeParsing() [TestMethod()] public void TestErParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("Cl[Er](Cl)Cl"); Assert.AreEqual("Er", mol.Atoms[1].Symbol); } @@ -1957,7 +1958,7 @@ public void TestErParsing() [TestMethod()] public void TestGdParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("Cl[Gd](Cl)Cl"); Assert.AreEqual("Gd", mol.Atoms[1].Symbol); } @@ -1966,7 +1967,7 @@ public void TestGdParsing() [TestMethod()] public void TestSmParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("Cl[Sm](Cl)Cl"); Assert.AreEqual("Sm", mol.Atoms[1].Symbol); } @@ -1975,7 +1976,7 @@ public void TestSmParsing() [TestMethod()] public void TestLaParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Cl-].[Cl-].[Cl-].[La+3]"); Assert.AreEqual("La", mol.Atoms[3].Symbol); } @@ -1984,7 +1985,7 @@ public void TestLaParsing() [TestMethod()] public void TestAcParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[255Ac]"); Assert.AreEqual("Ac", mol.Atoms[0].Symbol); } @@ -1993,7 +1994,7 @@ public void TestAcParsing() [TestMethod()] public void TestPuParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Pu]"); Assert.AreEqual("Pu", mol.Atoms[0].Symbol); } @@ -2002,7 +2003,7 @@ public void TestPuParsing() [TestMethod()] public void TestPrParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Pr]"); Assert.AreEqual("Pr", mol.Atoms[0].Symbol); } @@ -2011,7 +2012,7 @@ public void TestPrParsing() [TestMethod()] public void TestPaParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Pa]"); Assert.AreEqual("Pa", mol.Atoms[0].Symbol); } @@ -2020,7 +2021,7 @@ public void TestPaParsing() [TestMethod()] public void TestTbParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Tb]"); Assert.AreEqual("Tb", mol.Atoms[0].Symbol); } @@ -2029,7 +2030,7 @@ public void TestTbParsing() [TestMethod()] public void TestAmParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Am]"); Assert.AreEqual("Am", mol.Atoms[0].Symbol); } @@ -2038,7 +2039,7 @@ public void TestAmParsing() [TestMethod()] public void TestPmParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Pm]"); Assert.AreEqual("Pm", mol.Atoms[0].Symbol); } @@ -2047,7 +2048,7 @@ public void TestPmParsing() [TestMethod()] public void TestHoParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Ho]"); Assert.AreEqual("Ho", mol.Atoms[0].Symbol); } @@ -2056,7 +2057,7 @@ public void TestHoParsing() [TestMethod()] public void TestCfParsing() { - SmilesParser p = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser p = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = p.ParseSmiles("[Cf]"); Assert.AreEqual("Cf", mol.Atoms[0].Symbol); } @@ -2078,7 +2079,7 @@ public void TestAromaticity() [TestMethod()] public void TestAtAt() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Br[C@@H](Cl)I"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2107,7 +2108,7 @@ public void TestAtAt() [TestMethod()] public void TestAt() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Br[C@H](Cl)I"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2131,7 +2132,7 @@ public void TestAt() [TestMethod()] public void TestAtAt_ExplicitHydrogen() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Br[C@@]([H])(Cl)I"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2153,7 +2154,7 @@ public void TestAtAt_ExplicitHydrogen() [TestMethod()] public void TestAt_ExplicitHydrogen() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Br[C@]([H])(Cl)I"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2175,7 +2176,7 @@ public void TestAt_ExplicitHydrogen() [TestMethod()] public void TestRingClosure() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C12(OC1)CCC2"); Assert.AreEqual(6, mol.Atoms.Count); Assert.AreEqual("C", mol.Atoms[0].Symbol); @@ -2189,7 +2190,7 @@ public void TestRingClosure() [TestMethod()] public void TestRingClosure_At() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[C@]12(OC1)NCN2"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2213,9 +2214,9 @@ public void TestRingClosure_At() [TestMethod()] public void TestNeighboRingChirality() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("C[C@H](O)[C@H](O)C"); - var stereoElements = new List>(mol.StereoElements); + var stereoElements = new List>(mol.StereoElements); stereoElements.Sort((o1, o2) => Ints.Compare(mol.Atoms.IndexOf(((ITetrahedralChirality)o1).ChiralAtom), mol.Atoms.IndexOf(((ITetrahedralChirality)o2).ChiralAtom))); @@ -2254,7 +2255,7 @@ public void TestNeighboRingChirality() [TestMethod()] public void TestChiralityInBranch() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("NC([C@H](O)C)Cl"); var stereoElements = mol.StereoElements.GetEnumerator(); // first chiral center @@ -2277,7 +2278,7 @@ public void TestChiralityInBranch() [TestMethod()] public void TestChiralityWithTonsOfDots() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("I1.Cl2.Br3.[C@]123CCC"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2299,7 +2300,7 @@ public void TestChiralityWithTonsOfDots() [TestMethod()] public void TestChiralAtomWithDisconnectedLastAtom() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Br1.[C@]1(Cl)(OC)CCC"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2321,7 +2322,7 @@ public void TestChiralAtomWithDisconnectedLastAtom() [TestMethod()] public void TestFromBlog1() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[C@@H]231.C2.N1.F3"); var stereoElements = mol.StereoElements.GetEnumerator(); Assert.IsTrue(stereoElements.MoveNext()); @@ -2345,7 +2346,7 @@ public void TestFromBlog1() [TestMethod()] public void TestFromBlog2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("[C@@H](Cl)1[C@H](C)(F).Br1"); var stereoElements = mol.StereoElements.GetEnumerator(); for (int i = 0; i < 2; i++) @@ -2386,7 +2387,7 @@ public void TestFromBlog2() [TestMethod()] public void TestPreserveAromaticity() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer molecule = sp.ParseSmiles("Oc1ccc(Cl)c2C(=O)c3c(sc4nccn34)C(=O)c12"); Assert.AreEqual(14, CountAromaticAtoms(molecule)); @@ -2426,7 +2427,7 @@ public void CyclohexaneWithAromaticBonds() [TestMethod()] public void TestPreserveAromaticityAndPerceiveAtomTypes() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); sp.Kekulise(false); IAtomContainer molecule = sp.ParseSmiles("c1ccccc1"); MakeAtomType(molecule); @@ -2478,7 +2479,7 @@ public void TestBug1234() [TestMethod()] public void TestFormalNeighborBount() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("Oc1ccc(O)cc1"); MakeAtomType(mol); Assert.AreEqual("O.sp3", mol.Atoms[0].AtomTypeName); diff --git a/NCDKTests/Stereo/CyclicCarbohydrateRecognitionTest.cs b/NCDKTests/Stereo/CyclicCarbohydrateRecognitionTest.cs index 6f5a0d53..23333406 100644 --- a/NCDKTests/Stereo/CyclicCarbohydrateRecognitionTest.cs +++ b/NCDKTests/Stereo/CyclicCarbohydrateRecognitionTest.cs @@ -25,13 +25,14 @@ using NCDK.Common.Base; using NCDK.Common.Mathematics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Geometries; using NCDK.Graphs; using NCDK.Numerics; using static NCDK.Graphs.GraphUtil; using static NCDK.Stereo.CyclicCarbohydrateRecognition; using static NCDK.Stereo.CyclicCarbohydrateRecognition.Turn; +using System.Linq; namespace NCDK.Stereo { @@ -167,7 +168,7 @@ public void BetaDGlucose_Haworth() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Haworth }); + var elements = recon.Recognise(new[] { Projection.Haworth }).ToList(); AssertTetrahedralCenter(elements[0], m.Atoms[1], TetrahedralStereo.AntiClockwise, @@ -229,7 +230,7 @@ public void BetaDGlucose_Chair() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Chair }); + var elements = recon.Recognise(new[] { Projection.Chair }).ToList(); AssertTetrahedralCenter(elements[0], m.Atoms[1], TetrahedralStereo.Clockwise, @@ -302,7 +303,7 @@ public void BetaDGlucoseWithExplicitHydrogens_Haworth() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Haworth }); + var elements = recon.Recognise(new[] { Projection.Haworth }).ToList(); AssertTetrahedralCenter(elements[0], m.Atoms[1], TetrahedralStereo.AntiClockwise, @@ -378,7 +379,7 @@ public void Oxpene() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Haworth }); + var elements = recon.Recognise(new[] { Projection.Haworth }).ToList(); AssertTetrahedralCenter(elements[0], m.Atoms[2], TetrahedralStereo.AntiClockwise, @@ -481,7 +482,7 @@ public void Atp_Haworth() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Haworth }); + var elements = recon.Recognise(new[] { Projection.Haworth }).ToList(); AssertTetrahedralCenter(elements[0], m.Atoms[1], TetrahedralStereo.AntiClockwise, @@ -540,7 +541,7 @@ public void Hexopyranose() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - Assert.IsTrue(recon.Recognise(new[] { Projection.Haworth }).Count == 0); + Assert.IsTrue(recon.Recognise(new[] { Projection.Haworth }).Count() == 0); } /// @@ -593,7 +594,7 @@ public void BetaDGlucose_Chair_Rotated() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Chair }); + var elements = recon.Recognise(new[] { Projection.Chair }).ToList(); m.SetStereoElements(elements); AssertTetrahedralCenter(elements[0], @@ -655,7 +656,7 @@ public void HaworthFalsePositive() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Haworth }); + var elements = recon.Recognise(new[] { Projection.Haworth }).ToList(); Assert.IsTrue(elements.Count == 0); } @@ -690,11 +691,11 @@ public void RequireAtLeastTwoProjectedSubstituents() CyclicCarbohydrateRecognition recon = new CyclicCarbohydrateRecognition(m, graph, bondMap, stereocenters); - var elements = recon.Recognise(new[] { Projection.Haworth }); + var elements = recon.Recognise(new[] { Projection.Haworth }).ToList(); Assert.IsTrue(elements.Count == 0); } - static void AssertTetrahedralCenter(IReadOnlyStereoElement element, + static void AssertTetrahedralCenter(IStereoElement element, IAtom focus, TetrahedralStereo winding, params IAtom[] neighbors) @@ -708,9 +709,11 @@ static void AssertTetrahedralCenter(IReadOnlyStereoElement().Object; - IAtom[] peripherals = new IAtom[] { new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object }; - ExtendedTetrahedral element = new ExtendedTetrahedral(focus, peripherals, TetrahedralStereo.Clockwise); - - // modifying this array does not change the one in the structure - peripherals = element.Peripherals; - peripherals[0] = peripherals[1] = peripherals[2] = peripherals[3] = null; - Assert.IsNotNull(element.Peripherals[0]); - Assert.IsNotNull(element.Peripherals[1]); - Assert.IsNotNull(element.Peripherals[2]); - Assert.IsNotNull(element.Peripherals[3]); - } - [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void NonCumulatedAtomThrowsException() diff --git a/NCDKTests/Stereo/FischerRecognitionTest.cs b/NCDKTests/Stereo/FischerRecognitionTest.cs index 25fd7c2e..54dc6518 100644 --- a/NCDKTests/Stereo/FischerRecognitionTest.cs +++ b/NCDKTests/Stereo/FischerRecognitionTest.cs @@ -25,9 +25,10 @@ using NCDK.Common.Base; using NCDK.Numerics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Graphs; using static NCDK.Graphs.GraphUtil; +using System.Linq; namespace NCDK.Stereo { @@ -61,7 +62,7 @@ public void RecogniseRightHandedGlyceraldehyde() graph, bondMap, Stereocenters.Of(m)); - var elements = recogniser.Recognise(new[] { Projection.Fischer }); + var elements = recogniser.Recognise(new[] { Projection.Fischer }).ToList(); Assert.AreEqual(1, elements.Count); AssertTetrahedralCenter(elements[0], m.Atoms[1], @@ -96,7 +97,7 @@ public void RecogniseLeftHandedGlyceraldehyde() graph, bondMap, Stereocenters.Of(m)); - var elements = recogniser.Recognise(new[] { Projection.Fischer }); + var elements = recogniser.Recognise(new[] { Projection.Fischer }).ToList(); Assert.AreEqual(1, elements.Count); AssertTetrahedralCenter(elements[0], m.Atoms[1], @@ -129,7 +130,7 @@ public void RecogniseRightHandedGlyceraldehydeWithImplicitHydrogen() graph, bondMap, Stereocenters.Of(m)); - var elements = recogniser.Recognise(new[] { Projection.Fischer }); + var elements = recogniser.Recognise(new[] { Projection.Fischer }).ToList(); Assert.AreEqual(1, elements.Count); AssertTetrahedralCenter(elements[0], m.Atoms[1], @@ -172,7 +173,7 @@ public void Mannitol() graph, bondMap, Stereocenters.Of(m)); - var elements = recogniser.Recognise(new[] { Projection.Fischer }); + var elements = recogniser.Recognise(new[] { Projection.Fischer }).ToList(); Assert.AreEqual(4, elements.Count); AssertTetrahedralCenter(elements[0], @@ -562,7 +563,7 @@ public void IgnoreCyclicStereocenters() graph, bondMap, Stereocenters.Of(m)); - Assert.IsTrue(recogniser.Recognise(new[] { Projection.Fischer }).Count == 0); + Assert.IsTrue(recogniser.Recognise(new[] { Projection.Fischer }).Count() == 0); } /// @@ -604,10 +605,10 @@ public void HorizontalBondsMustBeTerminal() graph, bondMap, Stereocenters.Of(m)); - Assert.IsTrue(recogniser.Recognise(new[] { Projection.Fischer }).Count == 0); + Assert.IsTrue(recogniser.Recognise(new[] { Projection.Fischer }).Count() == 0); } - static void AssertTetrahedralCenter(IReadOnlyStereoElement element, + static void AssertTetrahedralCenter(IStereoElement element, IAtom focus, TetrahedralStereo winding, params IAtom[] neighbors) @@ -621,9 +622,11 @@ static void AssertTetrahedralCenter(IReadOnlyStereoElement=8 is okay for db stereo (ala inchi) @@ -81,7 +81,7 @@ public void Cyclooctatetraene() mol.AddBond(mol.Atoms[6], mol.Atoms[7], BondOrder.Double); mol.AddBond(mol.Atoms[0], mol.Atoms[7], BondOrder.Single); StereoElementFactory factory = StereoElementFactory.Using2DCoordinates(mol); - Assert.AreEqual(4, factory.CreateAll().Count); + Assert.AreEqual(4, factory.CreateAll().Count()); } // not okay... but technically the trans form exists @@ -104,7 +104,7 @@ public void DoubleBondInSevenMemberedRing() mol.AddBond(mol.Atoms[5], mol.Atoms[6], BondOrder.Single); mol.AddBond(mol.Atoms[6], mol.Atoms[0], BondOrder.Single); StereoElementFactory factory = StereoElementFactory.Using2DCoordinates(mol); - Assert.AreEqual(0, factory.CreateAll().Count); + Assert.AreEqual(0, factory.CreateAll().Count()); } [TestMethod()] @@ -120,7 +120,7 @@ public void HydrogenIsotope() mol.AddBond(mol.Atoms[1], mol.Atoms[2], BondOrder.Double); mol.AddBond(mol.Atoms[2], mol.Atoms[3], BondOrder.Single); StereoElementFactory factory = StereoElementFactory.Using2DCoordinates(mol); - Assert.AreEqual(1, factory.CreateAll().Count); + Assert.AreEqual(1, factory.CreateAll().Count()); } [TestMethod()] @@ -143,7 +143,7 @@ public void BridgeHeadNitrogen() mol.AddBond(mol.Atoms[5], mol.Atoms[6], BondOrder.Single, BondStereo.None); mol.AddBond(mol.Atoms[2], mol.Atoms[6], BondOrder.Single, BondStereo.None); StereoElementFactory factory = StereoElementFactory.Using2DCoordinates(mol); - Assert.AreEqual(2, factory.CreateAll().Count); + Assert.AreEqual(2, factory.CreateAll().Count()); } [TestMethod()] @@ -656,7 +656,7 @@ public void CreateExtendedTetrahedralFrom3DCoordinates_cw() m.AddBond(m.Atoms[1], m.Atoms[6], BondOrder.Single); m.AddBond(m.Atoms[3], m.Atoms[5], BondOrder.Single); - var stereos = StereoElementFactory.Using3DCoordinates(m).CreateAll(); + var stereos = StereoElementFactory.Using3DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(1, stereos.Count); Assert.IsInstanceOfType(stereos[0], typeof(ExtendedTetrahedral)); ExtendedTetrahedral et = (ExtendedTetrahedral)stereos[0]; @@ -683,7 +683,7 @@ public void CreateExtendedTetrahedralFrom3DCoordinates_ccw() m.AddBond(m.Atoms[1], m.Atoms[6], BondOrder.Single); m.AddBond(m.Atoms[3], m.Atoms[5], BondOrder.Single); - var stereos = StereoElementFactory.Using3DCoordinates(m).CreateAll(); + var stereos = StereoElementFactory.Using3DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(1, stereos.Count); Assert.IsInstanceOfType(stereos[0], typeof(ExtendedTetrahedral)); ExtendedTetrahedral et = (ExtendedTetrahedral)stereos[0]; @@ -783,7 +783,7 @@ public void Always2DTetrahedralElements() m.AddBond(m.Atoms[3], m.Atoms[7], BondOrder.Single); var elements = StereoElementFactory.Using2DCoordinates(m).CreateAll(); - Assert.AreEqual(3, elements.Count); + Assert.AreEqual(3, elements.Count()); } /// @@ -804,7 +804,7 @@ public void BadlyOptimizedAllene() m.AddBond(m.Atoms[0], m.Atoms[2], BondOrder.Single); m.AddBond(m.Atoms[1], m.Atoms[3], BondOrder.Double); m.AddBond(m.Atoms[3], m.Atoms[4], BondOrder.Single); - var elements = StereoElementFactory.Using3DCoordinates(m).CreateAll(); + var elements = StereoElementFactory.Using3DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(0, elements.Count); } @@ -828,7 +828,7 @@ public void OnlyCreateStereoForConsitionalDifferencesIn3D() m.AddBond(m.Atoms[2], m.Atoms[6], BondOrder.Single); m.AddBond(m.Atoms[3], m.Atoms[7], BondOrder.Single); - var elements = StereoElementFactory.Using3DCoordinates(m).CreateAll(); + var elements = StereoElementFactory.Using3DCoordinates(m).CreateAll().ToList(); // XXX: really 3 but we can't tell the middle centre is one ATM, see // 'dontCreateStereoForNonStereogenicIn3D' Assert.AreEqual(2, elements.Count); @@ -848,7 +848,7 @@ public void DontCreateStereoForNonStereogenicIn3D() m.AddBond(m.Atoms[0], m.Atoms[3], BondOrder.Single); m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); - var elements = StereoElementFactory.Using3DCoordinates(m).CreateAll(); + var elements = StereoElementFactory.Using3DCoordinates(m).CreateAll().ToList(); // methane carbon is of course non-stereogenic Assert.AreEqual(0, elements.Count); @@ -880,19 +880,19 @@ public void OnlyInterpretFischerProjectionsWhenAsked() Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Haworth) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Chair) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsFalse(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Fischer) .CreateAll() - .Count == 0); + .Count() == 0); } /// @@ -930,19 +930,19 @@ public void OnlyInterpretHaworthProjectionsWhenAsked() Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Fischer) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Chair) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsFalse(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Haworth) .CreateAll() - .Count == 0); + .Count() == 0); } /// @@ -980,19 +980,19 @@ public void OnlyInterpretChairProjectionsWhenAsked() Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Fischer) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsTrue(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Haworth) .CreateAll() - .Count == 0); + .Count() == 0); Assert.IsFalse(StereoElementFactory.Using2DCoordinates(m) .InterpretProjections(Projection.Chair) .CreateAll() - .Count == 0); + .Count() == 0); } /// @@ -1014,9 +1014,9 @@ public void KeepNonStereoConfiguration() m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[4], m.Atoms[5], BondOrder.Single); var elements = StereoElementFactory.Using2DCoordinates(m).CreateAll(); - Assert.AreEqual(1, elements.Count); + Assert.AreEqual(1, elements.Count()); m.SetStereoElements(elements); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo); Assert.AreEqual("[C@]([H])(C)(C)CC", smigen.Create(m)); } @@ -1036,9 +1036,9 @@ public void KeepNonStereoConfigurationPhosphorusTautomer() m.AddBond(m.Atoms[4], m.Atoms[5], BondOrder.Single); m.AddBond(m.Atoms[0], m.Atoms[1], BondOrder.Double); var elements = StereoElementFactory.Using2DCoordinates(m).CreateAll(); - Assert.AreEqual(1, elements.Count); + Assert.AreEqual(1, elements.Count()); m.SetStereoElements(elements); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo); Assert.AreEqual("[P@@](O)(C)(CC)=O", smigen.Create(m)); } @@ -1057,12 +1057,10 @@ public void DoNotkeepNonStereoConfigurationPhosphorusTautomer() m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[4], m.Atoms[5], BondOrder.Single); m.AddBond(m.Atoms[0], m.Atoms[1], BondOrder.Double); - var elements = StereoElementFactory.Using2DCoordinates(m) - .CheckSymmetry(true) - .CreateAll(); - Assert.AreEqual(0, elements.Count); + var elements = StereoElementFactory.Using2DCoordinates(m).CheckSymmetry(true).CreateAll(); + Assert.AreEqual(0, elements.Count()); m.SetStereoElements(elements); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo); Assert.AreEqual("P(O)(C)(CC)=O", smigen.Create(m)); } @@ -1084,12 +1082,10 @@ public void DoNotKeepNonStereoConfiguration() m.AddBond(m.Atoms[0], m.Atoms[3], BondOrder.Single); m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[4], m.Atoms[5], BondOrder.Single); - var elements = StereoElementFactory.Using2DCoordinates(m) - .CheckSymmetry(true) - .CreateAll(); - Assert.AreEqual(0, elements.Count); + var elements = StereoElementFactory.Using2DCoordinates(m).CheckSymmetry(true).CreateAll(); + Assert.AreEqual(0, elements.Count()); m.SetStereoElements(elements); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo); Assert.AreEqual("C([H])(C)(C)CC", smigen.Create(m)); } @@ -1112,9 +1108,9 @@ public void KeepNonStereoConfigurationH2() m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[4], m.Atoms[5], BondOrder.Single); var elements = StereoElementFactory.Using2DCoordinates(m).CreateAll(); - Assert.AreEqual(1, elements.Count); + Assert.AreEqual(1, elements.Count()); m.SetStereoElements(elements); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.Stereo); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.Stereo); Assert.AreEqual("[C@]([H])([H])(C)CC", smigen.Create(m)); AtomContainerManipulator.SuppressHydrogens(m); Assert.AreEqual("[C@H2](C)CC", smigen.Create(m)); @@ -1178,47 +1174,37 @@ public void Binol2D() m.AddBond(m.Atoms[18], m.Atoms[21], BondOrder.Double); m.AddBond(m.Atoms[4], m.Atoms[19], BondOrder.Single); m.AddBond(m.Atoms[18], m.Atoms[5], BondOrder.Single); - var stereo = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); + var stereo =StereoElementFactory.Using2DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(0, stereo.Count); m.Bonds[12].Stereo = BondStereo.Up; - var stereoUp = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); + var stereoUp = StereoElementFactory.Using2DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(1, stereoUp.Count); m.Bonds[12].Stereo = BondStereo.Down; - var stereoDown = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); + var stereoDown = StereoElementFactory.Using2DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(1, stereoDown.Count); var s1 = stereoUp[0]; var s2 = stereoDown[0]; Assert.AreEqual(s2.Focus, s1.Focus); - Assert.IsTrue(Compares.AreDeepEqual(s2.ReadOnlyCarriers, s1.ReadOnlyCarriers)); - Assert.AreEqual(StereoElement.Configuration.Right, s1.Configure); - Assert.AreEqual(StereoElement.Configuration.Left, s2.Configure); + Assert.IsTrue(Compares.AreDeepEqual(s2.Carriers, s1.Carriers)); + Assert.AreEqual(StereoConfigurations.Right, s1.Configure); + Assert.AreEqual(StereoConfigurations.Left, s2.Configure); // now test placement of wedges else where m.Bonds[12].Stereo = BondStereo.None; m.GetBond(m.Atoms[9], m.Atoms[12]).Stereo = BondStereo.Up; - var stereoUpOther = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); + var stereoUpOther = StereoElementFactory.Using2DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(1, stereoUpOther.Count); var s3 = stereoUpOther[0]; Assert.AreEqual(s2.Focus, s3.Focus); - Assert.IsTrue(Compares.AreDeepEqual(s2.ReadOnlyCarriers, s3.ReadOnlyCarriers)); + Assert.IsTrue(Compares.AreDeepEqual(s2.Carriers, s3.Carriers)); Assert.AreEqual(s2.Configure, s3.Configure); m.GetBond(m.Atoms[9], m.Atoms[12]).Stereo = BondStereo.Down; - var stereoDownOther = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); + var stereoDownOther = StereoElementFactory.Using2DCoordinates(m).CreateAll().ToList(); Assert.AreEqual(1, stereoDownOther.Count); var s4 = stereoDownOther[0]; Assert.AreEqual(s1.Focus, s4.Focus); - Assert.IsTrue(Compares.AreDeepEqual(s1.ReadOnlyCarriers, s4.ReadOnlyCarriers)); + Assert.IsTrue(Compares.AreDeepEqual(s1.Carriers, s4.Carriers)); Assert.AreEqual(s1.Configure, s4.Configure); } @@ -1258,10 +1244,8 @@ public void Atropisomer1() m.AddBond(m.Atoms[11], m.Atoms[12], BondOrder.Single); m.AddBond(m.Atoms[7], m.Atoms[13], BondOrder.Single); m.AddBond(m.Atoms[5], m.Atoms[14], BondOrder.Single); - var stereo = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); - Assert.AreEqual(1, stereo.Count); + var stereo = StereoElementFactory.Using2DCoordinates(m).CreateAll(); + Assert.AreEqual(1, stereo.Count()); } // @cdk.smiles CC1=C(C(O)=CC=C1)C1=CC=CC=C1 @@ -1298,10 +1282,8 @@ public void NonAtropisomer2() m.AddBond(m.Atoms[0], m.Atoms[6], BondOrder.Single); m.AddBond(m.Atoms[11], m.Atoms[12], BondOrder.Single); m.AddBond(m.Atoms[7], m.Atoms[13], BondOrder.Single); - var stereo = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); - Assert.AreEqual(0, stereo.Count); + var stereo = StereoElementFactory.Using2DCoordinates(m).CreateAll(); + Assert.AreEqual(0, stereo.Count()); } // @cdk.smiles CC1=C(C=CC=C1)C1=C(C)C=CC=C1 @@ -1338,10 +1320,8 @@ public void NonAtropisomer3() m.AddBond(m.Atoms[0], m.Atoms[6], BondOrder.Single); m.AddBond(m.Atoms[11], m.Atoms[12], BondOrder.Single); m.AddBond(m.Atoms[5], m.Atoms[13], BondOrder.Single); - var stereo = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); - Assert.AreEqual(0, stereo.Count); + var stereo = StereoElementFactory.Using2DCoordinates(m).CreateAll(); + Assert.AreEqual(0, stereo.Count()); } // @cdk.smiles [H]C1=CC=C2C=CC=CC2=C1C1=C([H])C=CC2=C1C=CC=C2 @@ -1396,10 +1376,8 @@ public void NonAtropisomerExplHydrogens() m.AddBond(m.Atoms[20], m.Atoms[21], BondOrder.Double); m.AddBond(m.Atoms[16], m.Atoms[21], BondOrder.Single); m.AddBond(m.Atoms[12], m.Atoms[13], BondOrder.Single); - var stereo = - StereoElementFactory.Using2DCoordinates(m) - .CreateAll(); - Assert.AreEqual(0, stereo.Count); + var stereo = StereoElementFactory.Using2DCoordinates(m).CreateAll(); + Assert.AreEqual(0, stereo.Count()); } // @cdk.smiles CC1=CC=CC(Cl)=C1C1=C(C)C=CC=C1 @@ -1438,25 +1416,27 @@ public void Atropisomer3D() m.AddBond(m.Atoms[8], m.Atoms[9], BondOrder.Single); m.AddBond(m.Atoms[8], m.Atoms[13], BondOrder.Double); m.AddBond(m.Atoms[13], m.Atoms[14], BondOrder.Single); - var stereo = - StereoElementFactory.Using3DCoordinates(m) - .CreateAll(); - Assert.AreEqual(1, stereo.Count); + var stereo = StereoElementFactory.Using3DCoordinates(m).CreateAll(); + Assert.AreEqual(1, stereo.Count()); } static IAtom Atom(string symbol, int h, double x, double y) { - IAtom a = new Atom(symbol); - a.ImplicitHydrogenCount = h; - a.Point2D = new Vector2(x, y); + IAtom a = new Atom(symbol) + { + ImplicitHydrogenCount = h, + Point2D = new Vector2(x, y) + }; return a; } static IAtom Atom(string symbol, int h, double x, double y, double z) { - IAtom a = new Atom(symbol); - a.ImplicitHydrogenCount = h; - a.Point3D = new Vector3(x, y, z); + IAtom a = new Atom(symbol) + { + ImplicitHydrogenCount = h, + Point3D = new Vector3(x, y, z) + }; return a; } } diff --git a/NCDKTests/Stereo/StereoToolTest.cs b/NCDKTests/Stereo/StereoToolTest.cs index 27fadf09..6d1b58fc 100644 --- a/NCDKTests/Stereo/StereoToolTest.cs +++ b/NCDKTests/Stereo/StereoToolTest.cs @@ -22,7 +22,7 @@ */ using NCDK.Common.Mathematics; using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using static NCDK.Stereo.StereoTool; diff --git a/NCDKTests/Stereo/StereocentersTest.cs b/NCDKTests/Stereo/StereocentersTest.cs index 456043d5..1cd69962 100644 --- a/NCDKTests/Stereo/StereocentersTest.cs +++ b/NCDKTests/Stereo/StereocentersTest.cs @@ -764,13 +764,13 @@ public void Germanium_neutral_geometric() [TestMethod()] public void Nitrogen_neutral_geometric() { - Test("N(=NC)C", Stereocenters.CoordinateType.Tricoordinate, true); - Test("N(=NC)", Stereocenters.CoordinateType.None, false); - Test("N(=N)C", Stereocenters.CoordinateType.None, false); - Test("N(=N)", Stereocenters.CoordinateType.None, false); - Test("N(=NC)[H]", Stereocenters.CoordinateType.Tricoordinate, false); - Test("N(=N[H])[H]", Stereocenters.CoordinateType.Tricoordinate, false); - Test("N(=N[H])[H]", Stereocenters.CoordinateType.Tricoordinate, false); + Test("N(=NC)C", CoordinateType.Tricoordinate, true); + Test("N(=NC)", CoordinateType.None, false); + Test("N(=N)C", CoordinateType.None, false); + Test("N(=N)", CoordinateType.None, false); + Test("N(=NC)[H]", CoordinateType.Tricoordinate, false); + Test("N(=N[H])[H]", CoordinateType.Tricoordinate, false); + Test("N(=N[H])[H]", CoordinateType.Tricoordinate, false); } [TestMethod()] @@ -782,35 +782,35 @@ public void Nitrogen_cation_geometric() } // assert the first atom of the SMILES is accepted as a tetrahedral center - void CreateTetrahedral(string smi) + static void CreateTetrahedral(string smi) { SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); - Test(sp.ParseSmiles(smi), Stereocenters.CoordinateType.Tetracoordinate, smi + " was not accepted", true); + Test(sp.ParseSmiles(smi), CoordinateType.Tetracoordinate, smi + " was not accepted", true); } // assert the first atom of the SMILES is accepted as a geometric center - void Geometric(string smi) + static void Geometric(string smi) { SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); - Test(sp.ParseSmiles(smi), Stereocenters.CoordinateType.Tricoordinate, smi + " was not accepted", true); + Test(sp.ParseSmiles(smi), CoordinateType.Tricoordinate, smi + " was not accepted", true); } // assert the first atom of the SMILES is accepted as a bicoordinate center - void Bicoordinate(string smi) + static void Bicoordinate(string smi) { SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); - Test(sp.ParseSmiles(smi), Stereocenters.CoordinateType.Bicoordinate, smi + " was not accepted", true); + Test(sp.ParseSmiles(smi), CoordinateType.Bicoordinate, smi + " was not accepted", true); } // assert the first atom of the SMILES is non stereogenic - void None(string smi) + static void None(string smi) { SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); - Test(sp.ParseSmiles(smi), Stereocenters.CoordinateType.None, smi + " was not rejected", true); + Test(sp.ParseSmiles(smi), CoordinateType.None, smi + " was not rejected", true); } // check if the first atom of the container is accepted - void Test(IAtomContainer container, Stereocenters.CoordinateType type, string mesg, bool hnorm) + static void Test(IAtomContainer container, CoordinateType type, string mesg, bool hnorm) { Assert.AreEqual(type, Stereocenters.Of(container).ElementType(0), mesg); if (hnorm) @@ -820,7 +820,7 @@ void Test(IAtomContainer container, Stereocenters.CoordinateType type, string me } } - void Test(string smi, Stereocenters.CoordinateType type, bool hnorm) + static void Test(string smi, CoordinateType type, bool hnorm) { SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); Test(sp.ParseSmiles(smi), type, smi + " was not accepted", hnorm); diff --git a/NCDKTests/Stereo/TetrahedralChiralityTest.cs b/NCDKTests/Stereo/TetrahedralChiralityTest.cs index 2f8c4ee5..5989343e 100644 --- a/NCDKTests/Stereo/TetrahedralChiralityTest.cs +++ b/NCDKTests/Stereo/TetrahedralChiralityTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Common.Base; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Stereo @@ -60,8 +60,8 @@ public void TestTetrahedralChirality_IAtom_arrayIAtom_ITetrahedralChirality_Ster public void TestBuilder() { TetrahedralChirality chirality = new TetrahedralChirality(molecule.Atoms[1], ligands, TetrahedralStereo.Clockwise); - chirality.Builder = Default.ChemObjectBuilder.Instance; - Assert.AreEqual(Default.ChemObjectBuilder.Instance, chirality.Builder); + chirality.Builder = ChemObjectBuilder.Instance; + Assert.AreEqual(ChemObjectBuilder.Instance, chirality.Builder); } [TestMethod()] @@ -99,7 +99,7 @@ public void TestGetLigands() [TestMethod()] public void TestMap_Map_Map() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtom c1 = builder.NewAtom("C"); IAtom o2 = builder.NewAtom("O"); @@ -148,7 +148,7 @@ public void TestMap_Map_Map() [ExpectedException(typeof(ArgumentNullException))] public void TestMap_Null_Map() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtom c1 = builder.NewAtom("C"); IAtom o2 = builder.NewAtom("O"); @@ -166,7 +166,7 @@ public void TestMap_Null_Map() [TestMethod()] public void TestMap_Map_Map_EmptyMapping() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtom c1 = builder.NewAtom("C"); IAtom o2 = builder.NewAtom("O"); @@ -187,7 +187,7 @@ public void TestMap_Map_Map_EmptyMapping() [TestMethod()] public void Contains() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtom c1 = builder.NewAtom("C"); IAtom o2 = builder.NewAtom("O"); diff --git a/NCDKTests/Stereo/TrigonalBipyramidalTest.cs b/NCDKTests/Stereo/TrigonalBipyramidalTest.cs index 169dec27..fe8023a6 100644 --- a/NCDKTests/Stereo/TrigonalBipyramidalTest.cs +++ b/NCDKTests/Stereo/TrigonalBipyramidalTest.cs @@ -66,12 +66,11 @@ public void TooManyCarriers() IAtom a4 = new Mock().Object; IAtom a5 = new Mock().Object; IAtom a6 = new Mock().Object; - new TrigonalBipyramidal(a0, new IAtom[] { a1, a2, a3, a4, a5, a6 }, 1); + var dummy = new TrigonalBipyramidal(a0, new IAtom[] { a1, a2, a3, a4, a5, a6 }, 1); } [TestMethod()] - [ExpectedException(typeof(ArgumentException), AllowDerivedTypes = true)] - + [ExpectedException(typeof(ArgumentOutOfRangeException), AllowDerivedTypes = true)] public void BadConfigurationOrder() { IAtom a0 = new Mock().Object; @@ -80,7 +79,7 @@ public void BadConfigurationOrder() IAtom a3 = new Mock().Object; IAtom a4 = new Mock().Object; IAtom a5 = new Mock().Object; - new TrigonalBipyramidal(a0, new IAtom[] { a1, a2, a3, a4, a5 }, 32); + var dummy = new TrigonalBipyramidal(a0, new IAtom[] { a1, a2, a3, a4, a5 }, 32); } } } diff --git a/NCDKTests/StructGen/SingleStructureRandomGeneratorTest.cs b/NCDKTests/StructGen/SingleStructureRandomGeneratorTest.cs index da09cc5e..202b195c 100644 --- a/NCDKTests/StructGen/SingleStructureRandomGeneratorTest.cs +++ b/NCDKTests/StructGen/SingleStructureRandomGeneratorTest.cs @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Default; +using NCDK.Silent; using NCDK.Layout; using NCDK.Numerics; using NCDK.Templates; diff --git a/NCDKTests/StructGen/Stochastic/Operator/ChemGraphTest.cs b/NCDKTests/StructGen/Stochastic/Operator/ChemGraphTest.cs index d05b5843..8c1659fd 100644 --- a/NCDKTests/StructGen/Stochastic/Operator/ChemGraphTest.cs +++ b/NCDKTests/StructGen/Stochastic/Operator/ChemGraphTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -namespace NCDK.StructGen.Stochastic.Operator +namespace NCDK.StructGen.Stochastic.Operators { // @cdk.module test-structgen [TestClass()] diff --git a/NCDKTests/StructGen/Stochastic/Operator/CrossoverMachineTest.cs b/NCDKTests/StructGen/Stochastic/Operator/CrossoverMachineTest.cs index 9b930af3..9df2df06 100644 --- a/NCDKTests/StructGen/Stochastic/Operator/CrossoverMachineTest.cs +++ b/NCDKTests/StructGen/Stochastic/Operator/CrossoverMachineTest.cs @@ -24,7 +24,7 @@ using NCDK.Tools.Manipulator; using System.IO; -namespace NCDK.StructGen.Stochastic.Operator +namespace NCDK.StructGen.Stochastic.Operators { // @cdk.module test-structgen [TestClass()] diff --git a/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs b/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs index c3ab570d..acd051ec 100644 --- a/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs +++ b/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs @@ -19,6 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Graphs; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools; @@ -31,12 +32,12 @@ public class PartialFilledStructureMergerTest : CDKTestCase [TestMethod()] public void TestGenerate_IAtomContainerSet() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - var acs = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var sp = new SmilesParser(ChemObjectBuilder.Instance); + var acs = ChemObjectBuilder.Instance.NewAtomContainerSet(); acs.Add(sp.ParseSmiles("[CH2]CCC[CH2]")); acs.Add(sp.ParseSmiles("[C]1=C(C1)C[CH2]")); - PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); - IAtomContainer result = pfsm.Generate(acs); + var pfsm = new PartialFilledStructureMerger(); + var result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); Assert.IsTrue(new SaturationChecker().AllSaturated(result)); } @@ -44,8 +45,8 @@ public void TestGenerate_IAtomContainerSet() [TestMethod()] public void TestPartialFilledStructureMerger2() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - var acs = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); + var acs = ChemObjectBuilder.Instance.NewAtomContainerSet(); acs.Add(sp.ParseSmiles("[C]=[C]CC[CH2]")); acs.Add(sp.ParseSmiles("[C]([CH2])=C1CC1")); PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); @@ -57,8 +58,8 @@ public void TestPartialFilledStructureMerger2() [TestMethod()] public void TestPartialFilledStructureMerger3() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - var acs = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); + var acs = ChemObjectBuilder.Instance.NewAtomContainerSet(); acs.Add(sp.ParseSmiles("[CH2]CCC[CH2]")); acs.Add(sp.ParseSmiles("[CH2]C[CH2]")); acs.Add(sp.ParseSmiles("[CH2][CH2]")); @@ -71,8 +72,8 @@ public void TestPartialFilledStructureMerger3() [TestMethod()] public void TestPartialFilledStructureMerger4() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - var acs = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); + var acs = ChemObjectBuilder.Instance.NewAtomContainerSet(); acs.Add(sp.ParseSmiles("[C]CCC[CH2]")); acs.Add(sp.ParseSmiles("[C]CC[CH2]")); acs.Add(sp.ParseSmiles("[CH2]")); @@ -85,8 +86,8 @@ public void TestPartialFilledStructureMerger4() [TestMethod()] public void TestPartialFilledStructureMerger5() { - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); - var acs = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); + var acs = ChemObjectBuilder.Instance.NewAtomContainerSet(); acs.Add(sp.ParseSmiles("[C]1CCC1")); acs.Add(sp.ParseSmiles("[C]([CH2])CC[CH2]")); acs.Add(sp.ParseSmiles("[CH2]")); diff --git a/NCDKTests/StructGen/VicinitySamplerTest.cs b/NCDKTests/StructGen/VicinitySamplerTest.cs index 40f9ac4a..1bfb4fc1 100644 --- a/NCDKTests/StructGen/VicinitySamplerTest.cs +++ b/NCDKTests/StructGen/VicinitySamplerTest.cs @@ -45,7 +45,7 @@ public void TestVicinitySampler_sample() { IAtomContainer mol = TestMoleculeFactory.MakeEthylPropylPhenantren(); - Isotopes.Instance.ConfigureAtoms(mol); + BODRIsotopeFactory.Instance.ConfigureAtoms(mol); AddImplicitHydrogens(mol); var structures = VicinitySampler.Sample(mol); @@ -65,7 +65,7 @@ public void TestCycloButene() { IAtomContainer mol = parser.ParseSmiles("C=CC=C"); - Isotopes.Instance.ConfigureAtoms(mol); + BODRIsotopeFactory.Instance.ConfigureAtoms(mol); AddImplicitHydrogens(mol); var structures = VicinitySampler.Sample(mol); diff --git a/NCDKTests/TT/AdductFormulaTest.tt.cs b/NCDKTests/TT/AdductFormulaTest.tt.cs index c13fa473..9d5c208b 100644 --- a/NCDKTests/TT/AdductFormulaTest.tt.cs +++ b/NCDKTests/TT/AdductFormulaTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net diff --git a/NCDKTests/TT/AminoAcidTest.tt b/NCDKTests/TT/AminoAcidTest.tt index e8d776a7..1e67b4df 100644 --- a/NCDKTests/TT/AminoAcidTest.tt +++ b/NCDKTests/TT/AminoAcidTest.tt @@ -43,8 +43,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/AminoAcidTest.tt.cs b/NCDKTests/TT/AminoAcidTest.tt.cs index c1bddb42..f2bf5628 100644 --- a/NCDKTests/TT/AminoAcidTest.tt.cs +++ b/NCDKTests/TT/AminoAcidTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -65,13 +66,13 @@ public void TestAminoAcid() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/AtomContainer2Test.tt b/NCDKTests/TT/AtomContainer2Test.tt index 1b863fbc..e51ef82d 100644 --- a/NCDKTests/TT/AtomContainer2Test.tt +++ b/NCDKTests/TT/AtomContainer2Test.tt @@ -104,8 +104,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/AtomContainer2Test.tt.cs b/NCDKTests/TT/AtomContainer2Test.tt.cs index c54d0911..074667fb 100644 --- a/NCDKTests/TT/AtomContainer2Test.tt.cs +++ b/NCDKTests/TT/AtomContainer2Test.tt.cs @@ -1,6 +1,7 @@  + /* * Copyright (c) 2017 John Mayfield * @@ -183,13 +184,13 @@ public void TestAtomGetBond() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/AtomContainerSetTest.tt b/NCDKTests/TT/AtomContainerSetTest.tt index 3579bf5d..aac8c849 100644 --- a/NCDKTests/TT/AtomContainerSetTest.tt +++ b/NCDKTests/TT/AtomContainerSetTest.tt @@ -50,7 +50,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/AtomContainerSetTest.tt.cs b/NCDKTests/TT/AtomContainerSetTest.tt.cs index 1037b149..4d21c71d 100644 --- a/NCDKTests/TT/AtomContainerSetTest.tt.cs +++ b/NCDKTests/TT/AtomContainerSetTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -79,7 +80,7 @@ public void TestAtomContainerSet() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/AtomContainerTest.tt b/NCDKTests/TT/AtomContainerTest.tt index b9aa82de..f1562410 100644 --- a/NCDKTests/TT/AtomContainerTest.tt +++ b/NCDKTests/TT/AtomContainerTest.tt @@ -44,8 +44,8 @@ namespace <#= ns.NS #> IAtomContainer ac = new AtomContainer(); Assert.AreEqual(0, ac.Atoms.Count); - Assert.AreEqual(0, ac.Bonds.Count); - Assert.AreEqual(0, ac.LonePairs.Count); + Assert.AreEqual(0, ac.Bonds.Count); + Assert.AreEqual(0, ac.LonePairs.Count); Assert.AreEqual(0, ac.SingleElectrons.Count); Assert.AreEqual(0, ac.GetElectronContainers().Count()); @@ -95,8 +95,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/AtomContainerTest.tt.cs b/NCDKTests/TT/AtomContainerTest.tt.cs index 1540752c..435208be 100644 --- a/NCDKTests/TT/AtomContainerTest.tt.cs +++ b/NCDKTests/TT/AtomContainerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -44,8 +45,8 @@ public void TestAtomContainer_int_int_int_int() IAtomContainer ac = new AtomContainer(); Assert.AreEqual(0, ac.Atoms.Count); - Assert.AreEqual(0, ac.Bonds.Count); - Assert.AreEqual(0, ac.LonePairs.Count); + Assert.AreEqual(0, ac.Bonds.Count); + Assert.AreEqual(0, ac.LonePairs.Count); Assert.AreEqual(0, ac.SingleElectrons.Count); Assert.AreEqual(0, ac.GetElectronContainers().Count()); @@ -117,8 +118,8 @@ public void TestAtomContainer_int_int_int_int() IAtomContainer ac = new AtomContainer(); Assert.AreEqual(0, ac.Atoms.Count); - Assert.AreEqual(0, ac.Bonds.Count); - Assert.AreEqual(0, ac.LonePairs.Count); + Assert.AreEqual(0, ac.Bonds.Count); + Assert.AreEqual(0, ac.LonePairs.Count); Assert.AreEqual(0, ac.SingleElectrons.Count); Assert.AreEqual(0, ac.GetElectronContainers().Count()); @@ -168,13 +169,13 @@ public void TestAtomContainer_IAtomContainer() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/AtomTest.tt b/NCDKTests/TT/AtomTest.tt index 233cb481..58b728f4 100644 --- a/NCDKTests/TT/AtomTest.tt +++ b/NCDKTests/TT/AtomTest.tt @@ -194,7 +194,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/AtomTest.tt.cs b/NCDKTests/TT/AtomTest.tt.cs index 8d357188..57c12f0e 100644 --- a/NCDKTests/TT/AtomTest.tt.cs +++ b/NCDKTests/TT/AtomTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -366,7 +367,7 @@ public override void TestCompare_Object() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/AtomTypeTest.tt b/NCDKTests/TT/AtomTypeTest.tt index 0b15d7ca..d9105deb 100644 --- a/NCDKTests/TT/AtomTypeTest.tt +++ b/NCDKTests/TT/AtomTypeTest.tt @@ -101,7 +101,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/AtomTypeTest.tt.cs b/NCDKTests/TT/AtomTypeTest.tt.cs index 762f1f70..f669eae3 100644 --- a/NCDKTests/TT/AtomTypeTest.tt.cs +++ b/NCDKTests/TT/AtomTypeTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -181,7 +182,7 @@ public void TestCompare_DiffBondOrderSum() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/BioPolymerTest.tt b/NCDKTests/TT/BioPolymerTest.tt index 000efb2f..b1971527 100644 --- a/NCDKTests/TT/BioPolymerTest.tt +++ b/NCDKTests/TT/BioPolymerTest.tt @@ -92,8 +92,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/BioPolymerTest.tt.cs b/NCDKTests/TT/BioPolymerTest.tt.cs index d3a2cf67..a7af5655 100644 --- a/NCDKTests/TT/BioPolymerTest.tt.cs +++ b/NCDKTests/TT/BioPolymerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -162,13 +163,13 @@ public void TestBioPolymer() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/BondTest.tt b/NCDKTests/TT/BondTest.tt index 7040420e..b9773e36 100644 --- a/NCDKTests/TT/BondTest.tt +++ b/NCDKTests/TT/BondTest.tt @@ -129,7 +129,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/BondTest.tt.cs b/NCDKTests/TT/BondTest.tt.cs index e7c64d82..f7fe833e 100644 --- a/NCDKTests/TT/BondTest.tt.cs +++ b/NCDKTests/TT/BondTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -233,7 +234,7 @@ public void TestBond_IAtom_IAtom_BondOrder_IBond_Stereo() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ChemFileTest.tt b/NCDKTests/TT/ChemFileTest.tt index de3137a0..21ea4bee 100644 --- a/NCDKTests/TT/ChemFileTest.tt +++ b/NCDKTests/TT/ChemFileTest.tt @@ -43,7 +43,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ChemFileTest.tt.cs b/NCDKTests/TT/ChemFileTest.tt.cs index 78a803b0..2567ec89 100644 --- a/NCDKTests/TT/ChemFileTest.tt.cs +++ b/NCDKTests/TT/ChemFileTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -65,7 +66,7 @@ public void TestChemFile() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ChemModelTest.tt b/NCDKTests/TT/ChemModelTest.tt index 9534ff69..0dabcef0 100644 --- a/NCDKTests/TT/ChemModelTest.tt +++ b/NCDKTests/TT/ChemModelTest.tt @@ -242,7 +242,7 @@ namespace <#= ns.NS #> Assert.IsFalse(listener.Changed); } - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ChemModelTest.tt.cs b/NCDKTests/TT/ChemModelTest.tt.cs index 2799d85b..e9a22f8b 100644 --- a/NCDKTests/TT/ChemModelTest.tt.cs +++ b/NCDKTests/TT/ChemModelTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -310,7 +311,7 @@ public override void TestStateChanged_ButNotAfterRemoval_RingSet() Assert.IsFalse(listener.Changed); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ChemObjectBuilderTest.tt.cs b/NCDKTests/TT/ChemObjectBuilderTest.tt.cs index 802add40..294adea3 100644 --- a/NCDKTests/TT/ChemObjectBuilderTest.tt.cs +++ b/NCDKTests/TT/ChemObjectBuilderTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2010 Egon Willighagen * * Contact: cdk-devel@lists.sourceforge.net diff --git a/NCDKTests/TT/ChemObjectTest.tt b/NCDKTests/TT/ChemObjectTest.tt index e0f9bfbc..a021fc4d 100644 --- a/NCDKTests/TT/ChemObjectTest.tt +++ b/NCDKTests/TT/ChemObjectTest.tt @@ -71,9 +71,9 @@ namespace <#= ns.NS #> co2.Id = "a2"; Assert.IsFalse(co1.Compare(co2)); } - + <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ChemObjectTest.tt.cs b/NCDKTests/TT/ChemObjectTest.tt.cs index 212f73c3..a579af2e 100644 --- a/NCDKTests/TT/ChemObjectTest.tt.cs +++ b/NCDKTests/TT/ChemObjectTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -71,7 +72,7 @@ public void CompareDifferent() co2.Id = "a2"; Assert.IsFalse(co1.Compare(co2)); } - + } } namespace NCDK.Silent @@ -123,9 +124,9 @@ public void CompareDifferent() co2.Id = "a2"; Assert.IsFalse(co1.Compare(co2)); } - + - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ChemSequenceTest.tt b/NCDKTests/TT/ChemSequenceTest.tt index 754ffdee..25691ca0 100644 --- a/NCDKTests/TT/ChemSequenceTest.tt +++ b/NCDKTests/TT/ChemSequenceTest.tt @@ -41,9 +41,9 @@ namespace <#= ns.NS #> IChemSequence cs = new ChemSequence(); Assert.IsNotNull(cs); } - + <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ChemSequenceTest.tt.cs b/NCDKTests/TT/ChemSequenceTest.tt.cs index 68102895..9421d772 100644 --- a/NCDKTests/TT/ChemSequenceTest.tt.cs +++ b/NCDKTests/TT/ChemSequenceTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -41,7 +42,7 @@ public void TestChemSequence() IChemSequence cs = new ChemSequence(); Assert.IsNotNull(cs); } - + } } namespace NCDK.Silent @@ -63,9 +64,9 @@ public void TestChemSequence() IChemSequence cs = new ChemSequence(); Assert.IsNotNull(cs); } - + - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ConformerContainerTest.tt.cs b/NCDKTests/TT/ConformerContainerTest.tt.cs index 329cc1b5..5871624e 100644 --- a/NCDKTests/TT/ConformerContainerTest.tt.cs +++ b/NCDKTests/TT/ConformerContainerTest.tt.cs @@ -1,6 +1,7 @@ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Numerics; using System; diff --git a/NCDKTests/TT/CrystalTest.tt b/NCDKTests/TT/CrystalTest.tt index a9c331ad..5c491250 100644 --- a/NCDKTests/TT/CrystalTest.tt +++ b/NCDKTests/TT/CrystalTest.tt @@ -70,8 +70,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/CrystalTest.tt.cs b/NCDKTests/TT/CrystalTest.tt.cs index c8f60fb5..e06a8e8d 100644 --- a/NCDKTests/TT/CrystalTest.tt.cs +++ b/NCDKTests/TT/CrystalTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -119,13 +120,13 @@ public void TestCrystal_IAtomContainer() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ElectronContainerTest.tt b/NCDKTests/TT/ElectronContainerTest.tt index fc3e7920..d7bf0e72 100644 --- a/NCDKTests/TT/ElectronContainerTest.tt +++ b/NCDKTests/TT/ElectronContainerTest.tt @@ -44,7 +44,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ElectronContainerTest.tt.cs b/NCDKTests/TT/ElectronContainerTest.tt.cs index 0596fb6d..73dc6324 100644 --- a/NCDKTests/TT/ElectronContainerTest.tt.cs +++ b/NCDKTests/TT/ElectronContainerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -67,7 +68,7 @@ public void TestElectronContainer() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ElementTest.tt b/NCDKTests/TT/ElementTest.tt index 2784fe62..2176f1fe 100644 --- a/NCDKTests/TT/ElementTest.tt +++ b/NCDKTests/TT/ElementTest.tt @@ -108,7 +108,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ElementTest.tt.cs b/NCDKTests/TT/ElementTest.tt.cs index 215d0795..554b325a 100644 --- a/NCDKTests/TT/ElementTest.tt.cs +++ b/NCDKTests/TT/ElementTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -195,7 +196,7 @@ public void CompareDiffAtomicNumber() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/FragmentAtomTest.tt b/NCDKTests/TT/FragmentAtomTest.tt index df121215..e75e2ec3 100644 --- a/NCDKTests/TT/FragmentAtomTest.tt +++ b/NCDKTests/TT/FragmentAtomTest.tt @@ -42,7 +42,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/FragmentAtomTest.tt.cs b/NCDKTests/TT/FragmentAtomTest.tt.cs index 064d2b4c..b2396b52 100644 --- a/NCDKTests/TT/FragmentAtomTest.tt.cs +++ b/NCDKTests/TT/FragmentAtomTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -63,7 +64,7 @@ public void TestFragmentAtom() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/IsotopeTest.tt b/NCDKTests/TT/IsotopeTest.tt index 1c252a39..393ea75b 100644 --- a/NCDKTests/TT/IsotopeTest.tt +++ b/NCDKTests/TT/IsotopeTest.tt @@ -105,7 +105,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/IsotopeTest.tt.cs b/NCDKTests/TT/IsotopeTest.tt.cs index 39a90bb0..c9cbbb8a 100644 --- a/NCDKTests/TT/IsotopeTest.tt.cs +++ b/NCDKTests/TT/IsotopeTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * 2012 Egon Willighagen * @@ -188,7 +189,7 @@ public void TestCompare_NaturalAbundance() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/LonePairTest.tt b/NCDKTests/TT/LonePairTest.tt index 6565a657..0af46054 100644 --- a/NCDKTests/TT/LonePairTest.tt +++ b/NCDKTests/TT/LonePairTest.tt @@ -54,7 +54,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/LonePairTest.tt.cs b/NCDKTests/TT/LonePairTest.tt.cs index bd7a73c4..bf464296 100644 --- a/NCDKTests/TT/LonePairTest.tt.cs +++ b/NCDKTests/TT/LonePairTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -87,7 +88,7 @@ public void TestLonePair_IAtom() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/MappingTest.tt b/NCDKTests/TT/MappingTest.tt index ebfd2ada..dbc3e847 100644 --- a/NCDKTests/TT/MappingTest.tt +++ b/NCDKTests/TT/MappingTest.tt @@ -44,7 +44,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/MappingTest.tt.cs b/NCDKTests/TT/MappingTest.tt.cs index b7d13d99..c688b1ae 100644 --- a/NCDKTests/TT/MappingTest.tt.cs +++ b/NCDKTests/TT/MappingTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -67,7 +68,7 @@ public void TestMapping_IChemObject_IChemObject() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/MolecularFormulaSetTest.tt.cs b/NCDKTests/TT/MolecularFormulaSetTest.tt.cs index 0d8af006..f7a9342e 100644 --- a/NCDKTests/TT/MolecularFormulaSetTest.tt.cs +++ b/NCDKTests/TT/MolecularFormulaSetTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net diff --git a/NCDKTests/TT/MolecularFormulaTest.tt b/NCDKTests/TT/MolecularFormulaTest.tt index 24fd6319..9a1a820b 100644 --- a/NCDKTests/TT/MolecularFormulaTest.tt +++ b/NCDKTests/TT/MolecularFormulaTest.tt @@ -56,9 +56,9 @@ namespace <#= ns.NS #> anotherCarb.NaturalAbundance = 34.0; h.NaturalAbundance = 99.0; - Assert.IsTrue(mf.IsTheSame(carb, carb)); - Assert.IsTrue(mf.IsTheSame(carb, anotherCarb)); - Assert.IsFalse(mf.IsTheSame(carb, h)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, carb)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, anotherCarb)); + Assert.IsFalse(MolecularFormula.IsTheSame(carb, h)); } } } diff --git a/NCDKTests/TT/MolecularFormulaTest.tt.cs b/NCDKTests/TT/MolecularFormulaTest.tt.cs index 7da3acaa..00345e9c 100644 --- a/NCDKTests/TT/MolecularFormulaTest.tt.cs +++ b/NCDKTests/TT/MolecularFormulaTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2008 Egon Willighagen * * Contact: cdk-devel@lists.sourceforge.net @@ -56,9 +57,9 @@ public void TestIsTheSame_IIsotope_IIsotope() anotherCarb.NaturalAbundance = 34.0; h.NaturalAbundance = 99.0; - Assert.IsTrue(mf.IsTheSame(carb, carb)); - Assert.IsTrue(mf.IsTheSame(carb, anotherCarb)); - Assert.IsFalse(mf.IsTheSame(carb, h)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, carb)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, anotherCarb)); + Assert.IsFalse(MolecularFormula.IsTheSame(carb, h)); } } } @@ -96,9 +97,9 @@ public void TestIsTheSame_IIsotope_IIsotope() anotherCarb.NaturalAbundance = 34.0; h.NaturalAbundance = 99.0; - Assert.IsTrue(mf.IsTheSame(carb, carb)); - Assert.IsTrue(mf.IsTheSame(carb, anotherCarb)); - Assert.IsFalse(mf.IsTheSame(carb, h)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, carb)); + Assert.IsTrue(MolecularFormula.IsTheSame(carb, anotherCarb)); + Assert.IsFalse(MolecularFormula.IsTheSame(carb, h)); } } } diff --git a/NCDKTests/TT/MonomerTest.tt b/NCDKTests/TT/MonomerTest.tt index e6c1f69a..a6f800f6 100644 --- a/NCDKTests/TT/MonomerTest.tt +++ b/NCDKTests/TT/MonomerTest.tt @@ -43,8 +43,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/MonomerTest.tt.cs b/NCDKTests/TT/MonomerTest.tt.cs index 90043daa..bf3659fd 100644 --- a/NCDKTests/TT/MonomerTest.tt.cs +++ b/NCDKTests/TT/MonomerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -65,13 +66,13 @@ public void TestMonomer() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/PDBAtomTest.tt b/NCDKTests/TT/PDBAtomTest.tt index 110a99f1..554be23a 100644 --- a/NCDKTests/TT/PDBAtomTest.tt +++ b/NCDKTests/TT/PDBAtomTest.tt @@ -67,7 +67,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/PDBAtomTest.tt.cs b/NCDKTests/TT/PDBAtomTest.tt.cs index 807ada7b..39f883bd 100644 --- a/NCDKTests/TT/PDBAtomTest.tt.cs +++ b/NCDKTests/TT/PDBAtomTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2004-2007 Miguel Rojas * * Contact: cdk-devel@lists.sourceforge.net @@ -112,7 +113,7 @@ public void TestPDBAtom_String_Point3d() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/PDBMonomerTest.tt b/NCDKTests/TT/PDBMonomerTest.tt index 23b926fa..6463c0e9 100644 --- a/NCDKTests/TT/PDBMonomerTest.tt +++ b/NCDKTests/TT/PDBMonomerTest.tt @@ -44,8 +44,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/PDBMonomerTest.tt.cs b/NCDKTests/TT/PDBMonomerTest.tt.cs index ef7c513f..1810952b 100644 --- a/NCDKTests/TT/PDBMonomerTest.tt.cs +++ b/NCDKTests/TT/PDBMonomerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2004-2007 Miguel Rojas * * Contact: cdk-devel@lists.sourceforge.net @@ -67,13 +68,13 @@ public void TestPDBMonomer() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/PDBPolymerTest.tt b/NCDKTests/TT/PDBPolymerTest.tt index b74f225f..1bb396f2 100644 --- a/NCDKTests/TT/PDBPolymerTest.tt +++ b/NCDKTests/TT/PDBPolymerTest.tt @@ -28,7 +28,7 @@ namespace <#= ns.NS #> /// /// Checks the functionality of the . /// - [TestClass()] + [TestClass()] public class PDBPolymerTest : AbstractPDBPolymerTest { public override IChemObject NewChemObject() @@ -118,10 +118,10 @@ namespace <#= ns.NS #> monomers.MoveNext(); Assert.AreEqual("CYS280", monomers.Current); } - + <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/PDBPolymerTest.tt.cs b/NCDKTests/TT/PDBPolymerTest.tt.cs index dd2699eb..7247a342 100644 --- a/NCDKTests/TT/PDBPolymerTest.tt.cs +++ b/NCDKTests/TT/PDBPolymerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2004-2007 Miguel Rojas * * Contact: cdk-devel@lists.sourceforge.net @@ -28,7 +29,7 @@ namespace NCDK.Default /// /// Checks the functionality of the . /// - [TestClass()] + [TestClass()] public class PDBPolymerTest : AbstractPDBPolymerTest { public override IChemObject NewChemObject() @@ -118,7 +119,7 @@ public void TestGetMonomerNamesInSequentialOrder() monomers.MoveNext(); Assert.AreEqual("CYS280", monomers.Current); } - + } } namespace NCDK.Silent @@ -126,7 +127,7 @@ namespace NCDK.Silent /// /// Checks the functionality of the . /// - [TestClass()] + [TestClass()] public class PDBPolymerTest : AbstractPDBPolymerTest { public override IChemObject NewChemObject() @@ -216,15 +217,15 @@ public void TestGetMonomerNamesInSequentialOrder() monomers.MoveNext(); Assert.AreEqual("CYS280", monomers.Current); } - + - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/PDBStructureTest.tt.cs b/NCDKTests/TT/PDBStructureTest.tt.cs index b3177988..d489e0d1 100644 --- a/NCDKTests/TT/PDBStructureTest.tt.cs +++ b/NCDKTests/TT/PDBStructureTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2004-2007 Miguel Rojas * * Contact: cdk-devel@lists.sourceforge.net diff --git a/NCDKTests/TT/PolymerTest.tt b/NCDKTests/TT/PolymerTest.tt index d3a60cab..319a8f1f 100644 --- a/NCDKTests/TT/PolymerTest.tt +++ b/NCDKTests/TT/PolymerTest.tt @@ -41,10 +41,10 @@ namespace <#= ns.NS #> Assert.IsNotNull(polymer); Assert.IsTrue(polymer is Polymer); } - + <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/PolymerTest.tt.cs b/NCDKTests/TT/PolymerTest.tt.cs index 91ac1026..e3101e73 100644 --- a/NCDKTests/TT/PolymerTest.tt.cs +++ b/NCDKTests/TT/PolymerTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -41,7 +42,7 @@ public void TestPolymer() Assert.IsNotNull(polymer); Assert.IsTrue(polymer is Polymer); } - + } } namespace NCDK.Silent @@ -63,15 +64,15 @@ public void TestPolymer() Assert.IsNotNull(polymer); Assert.IsTrue(polymer is Polymer); } - + - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/PseudoAtomTest.tt b/NCDKTests/TT/PseudoAtomTest.tt index 3ee26783..1885e184 100644 --- a/NCDKTests/TT/PseudoAtomTest.tt +++ b/NCDKTests/TT/PseudoAtomTest.tt @@ -108,7 +108,7 @@ namespace <#= ns.NS #> <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/PseudoAtomTest.tt.cs b/NCDKTests/TT/PseudoAtomTest.tt.cs index 98a7e82a..5d193259 100644 --- a/NCDKTests/TT/PseudoAtomTest.tt.cs +++ b/NCDKTests/TT/PseudoAtomTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -194,7 +195,7 @@ public void TestPseudoAtom_String_Point3d() - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ReactionChainTest.tt.cs b/NCDKTests/TT/ReactionChainTest.tt.cs index 4bc98e98..4be50696 100644 --- a/NCDKTests/TT/ReactionChainTest.tt.cs +++ b/NCDKTests/TT/ReactionChainTest.tt.cs @@ -1,6 +1,7 @@  + /* Copyright (C) 2008 Miguel Rojas * * Contact: cdk-devel@lists.sourceforge.net diff --git a/NCDKTests/TT/ReactionSchemeTest.tt b/NCDKTests/TT/ReactionSchemeTest.tt index 1d2c6bd9..03536a4d 100644 --- a/NCDKTests/TT/ReactionSchemeTest.tt +++ b/NCDKTests/TT/ReactionSchemeTest.tt @@ -43,7 +43,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ReactionSchemeTest.tt.cs b/NCDKTests/TT/ReactionSchemeTest.tt.cs index 3f9537ff..9168c1d6 100644 --- a/NCDKTests/TT/ReactionSchemeTest.tt.cs +++ b/NCDKTests/TT/ReactionSchemeTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2008 Egon Willighagen * * Contact: cdk-devel@lists.sourceforge.net @@ -65,7 +66,7 @@ public void TestReactionScheme() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ReactionSetTest.tt b/NCDKTests/TT/ReactionSetTest.tt index 2985af5e..b95e18ef 100644 --- a/NCDKTests/TT/ReactionSetTest.tt +++ b/NCDKTests/TT/ReactionSetTest.tt @@ -43,7 +43,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ReactionSetTest.tt.cs b/NCDKTests/TT/ReactionSetTest.tt.cs index 01b4f6c0..b4adfb64 100644 --- a/NCDKTests/TT/ReactionSetTest.tt.cs +++ b/NCDKTests/TT/ReactionSetTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -65,7 +66,7 @@ public void TestReactionSet() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/ReactionTest.tt b/NCDKTests/TT/ReactionTest.tt index ae896828..303368cb 100644 --- a/NCDKTests/TT/ReactionTest.tt +++ b/NCDKTests/TT/ReactionTest.tt @@ -43,7 +43,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/ReactionTest.tt.cs b/NCDKTests/TT/ReactionTest.tt.cs index 893bf304..5a4f0186 100644 --- a/NCDKTests/TT/ReactionTest.tt.cs +++ b/NCDKTests/TT/ReactionTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -65,7 +66,7 @@ public void TestReaction() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/RingSetTest.tt b/NCDKTests/TT/RingSetTest.tt index 04adcd99..81275226 100644 --- a/NCDKTests/TT/RingSetTest.tt +++ b/NCDKTests/TT/RingSetTest.tt @@ -48,7 +48,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/RingSetTest.tt.cs b/NCDKTests/TT/RingSetTest.tt.cs index 6fd0b419..7ff814e0 100644 --- a/NCDKTests/TT/RingSetTest.tt.cs +++ b/NCDKTests/TT/RingSetTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -75,7 +76,7 @@ public void TestRingSet() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/RingTest.tt b/NCDKTests/TT/RingTest.tt index 013b5369..610bd8ec 100644 --- a/NCDKTests/TT/RingTest.tt +++ b/NCDKTests/TT/RingTest.tt @@ -74,8 +74,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/RingTest.tt.cs b/NCDKTests/TT/RingTest.tt.cs index d7b8f119..e4cec56e 100644 --- a/NCDKTests/TT/RingTest.tt.cs +++ b/NCDKTests/TT/RingTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -127,13 +128,13 @@ public void TestRing_IAtomContainer() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/SingleElectronTest.tt b/NCDKTests/TT/SingleElectronTest.tt index e33b54db..cd18c973 100644 --- a/NCDKTests/TT/SingleElectronTest.tt +++ b/NCDKTests/TT/SingleElectronTest.tt @@ -54,7 +54,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/SingleElectronTest.tt.cs b/NCDKTests/TT/SingleElectronTest.tt.cs index 493ca488..d8d053a6 100644 --- a/NCDKTests/TT/SingleElectronTest.tt.cs +++ b/NCDKTests/TT/SingleElectronTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -87,7 +88,7 @@ public void TestSingleElectron_IAtom() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/StrandTest.tt b/NCDKTests/TT/StrandTest.tt index 4d3fa7bc..449c377a 100644 --- a/NCDKTests/TT/StrandTest.tt +++ b/NCDKTests/TT/StrandTest.tt @@ -85,8 +85,8 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractAtomContainer.ttinclude" #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractAtomContainer.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/StrandTest.tt.cs b/NCDKTests/TT/StrandTest.tt.cs index b4cb1043..d3d15b38 100644 --- a/NCDKTests/TT/StrandTest.tt.cs +++ b/NCDKTests/TT/StrandTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 1997-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net @@ -148,13 +149,13 @@ public void TestStrand() } - [TestMethod()] + [TestMethod()] public override void TestSetAtoms_RemoveListener() { ChemObjectTestHelper.TestSetAtoms_RemoveListener(NewChemObject()); } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/TT/SubstanceTest.tt b/NCDKTests/TT/SubstanceTest.tt index a07980f7..b0fd8bfc 100644 --- a/NCDKTests/TT/SubstanceTest.tt +++ b/NCDKTests/TT/SubstanceTest.tt @@ -41,7 +41,7 @@ namespace <#= ns.NS #> } <# if (ns.IsSilent) { #> - <#@ include file="TestAbstractChemObjectTest.ttinclude" #> + <#@ include file="TestAbstractChemObjectTest.ttinclude" #> <# } #> } } diff --git a/NCDKTests/TT/SubstanceTest.tt.cs b/NCDKTests/TT/SubstanceTest.tt.cs index 0e390f99..6d4e79de 100644 --- a/NCDKTests/TT/SubstanceTest.tt.cs +++ b/NCDKTests/TT/SubstanceTest.tt.cs @@ -1,6 +1,7 @@ + /* Copyright (C) 2014 Egon Willighagen * * Contact: cdk-devel@lists.sourceforge.net @@ -61,7 +62,7 @@ public override IAtomContainer NewContainerObject() } - // Overwrite default methods: no notifications are expected! + // Overwrite default methods: no notifications are expected! [TestMethod()] public override void TestNotifyChanged() diff --git a/NCDKTests/Tautomers/InChITautomerGeneratorTest.cs b/NCDKTests/Tautomers/InChITautomerGeneratorTest.cs index c92f3066..30234ae0 100644 --- a/NCDKTests/Tautomers/InChITautomerGeneratorTest.cs +++ b/NCDKTests/Tautomers/InChITautomerGeneratorTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using NCDK.Tools; @@ -188,7 +188,7 @@ public void Test_WithNInChI() [TestMethod()] public void TestAdenine() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); IAtom a1 = builder.NewAtom("N"); mol.Atoms.Add(a1); diff --git a/NCDKTests/Templates/TestMoleculeFactory.cs b/NCDKTests/Templates/TestMoleculeFactory.cs index cdacdd70..d89677a2 100644 --- a/NCDKTests/Templates/TestMoleculeFactory.cs +++ b/NCDKTests/Templates/TestMoleculeFactory.cs @@ -23,7 +23,7 @@ */ using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using System; using System.Diagnostics; @@ -35,11 +35,11 @@ namespace NCDK.Templates /// copy of for use in tests. /// // @cdk.module test-data - public class TestMoleculeFactory + public static class TestMoleculeFactory { private static IAtomContainer NewAtomContainer() { - return Default.ChemObjectBuilder.Instance.NewAtomContainer(); + return ChemObjectBuilder.Instance.NewAtomContainer(); } private static void MolAddBond(IAtomContainer mol, int a, int b, BondOrder order) @@ -1908,7 +1908,7 @@ private static void ConfigureAtoms(IAtomContainer mol) { foreach (IAtom atom in mol.Atoms) atom.ImplicitHydrogenCount = null; - Isotopes.Instance.ConfigureAtoms(mol); + BODRIsotopeFactory.Instance.ConfigureAtoms(mol); } catch (Exception exc) { diff --git a/NCDKTests/Tools/ATASaturationCheckerTest.cs b/NCDKTests/Tools/ATASaturationCheckerTest.cs index 6a7c7b77..0d615b0d 100644 --- a/NCDKTests/Tools/ATASaturationCheckerTest.cs +++ b/NCDKTests/Tools/ATASaturationCheckerTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; @@ -28,7 +28,7 @@ namespace NCDK.Tools /// /// A test class for the AtomTypeAwereSaturationChecker-class /// - // @author Klas Jönsson + // @author Klas Jönsson // @cdk.created 2012-04-18 // @cdk.module test-valencycheck [TestClass()] @@ -46,40 +46,40 @@ public class ATASaturationCheckerTest : CDKTestCase public void TestASimpleCarbonRing() { // First we create a simple carbon ring to play with... - IAtomContainer mol = new AtomContainer(); - IAtomType carbon = new AtomType(ChemicalElements.Carbon.ToIElement()); + var mol = new AtomContainer(); + var carbon = new AtomType(ChemicalElements.Carbon.ToIElement()); - IAtom a0 = new Atom("C") + var a0 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a0, carbon); - IAtom a1 = new Atom("C") + var a1 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a1, carbon); - IAtom a2 = new Atom("C") + var a2 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a2, carbon); - IAtom a3 = new Atom("C") + var a3 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a3, carbon); - IAtom a4 = new Atom("C") + var a4 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a4, carbon); - IAtom a5 = new Atom("C") + var a5 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 @@ -93,40 +93,20 @@ public void TestASimpleCarbonRing() mol.Atoms.Add(a4); mol.Atoms.Add(a5); - IBond b0 = new Bond(a0, a1) - { - IsSingleOrDouble = true - }; + var b0 = new Bond(a0, a1) { IsSingleOrDouble = true }; mol.Bonds.Add(b0); - IBond b1 = new Bond(a1, a2) - { - IsSingleOrDouble = true - }; + var b1 = new Bond(a1, a2) { IsSingleOrDouble = true }; mol.Bonds.Add(b1); - IBond b2 = new Bond(a2, a3) - { - IsSingleOrDouble = true - }; + var b2 = new Bond(a2, a3) { IsSingleOrDouble = true }; mol.Bonds.Add(b2); - IBond b3 = new Bond(a3, a4) - { - IsSingleOrDouble = true - }; + var b3 = new Bond(a3, a4) { IsSingleOrDouble = true }; mol.Bonds.Add(b3); - IBond b4 = new Bond(a4, a5) - { - IsSingleOrDouble = true - }; + var b4 = new Bond(a4, a5) { IsSingleOrDouble = true }; mol.Bonds.Add(b4); - IBond b5 = new Bond(a5, a0) - { - IsSingleOrDouble = true - }; + var b5 = new Bond(a5, a0) { IsSingleOrDouble = true }; mol.Bonds.Add(b5); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - AtomTypeTools att = new AtomTypeTools(); - att.AssignAtomTypePropertiesToAtom(mol, false); // ...then we send it to the method we want to test... atasc.DecideBondOrder(mol, false); @@ -148,7 +128,7 @@ public void TestASimpleCarbonRing() [TestMethod()] public void TestQuinone() { - IAtomContainer mol = sp.ParseSmiles("O=c1ccc(=O)cc1"); + var mol = sp.ParseSmiles("O=c1ccc(=O)cc1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); atasc.DecideBondOrder(mol, true); @@ -197,7 +177,7 @@ public void TestQuinone() [TestMethod()] public void TestASimpleCarbonRing2() { - IAtomContainer mol = sp.ParseSmiles("c1ccccc1"); + var mol = sp.ParseSmiles("c1ccccc1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); atasc.DecideBondOrder(mol, true); @@ -219,8 +199,8 @@ public void TestASimpleCarbonRing2() public void TestALargeRingSystem() { // Should have 13 double bonds. - string smiles = "O=C1Oc6ccccc6(C(O)C1C5c2ccccc2CC(c3ccc(cc3)c4ccccc4)C5)"; - IAtomContainer mol = sp.ParseSmiles(smiles); + var smiles = "O=C1Oc6ccccc6(C(O)C1C5c2ccccc2CC(c3ccc(cc3)c4ccccc4)C5)"; + var mol = sp.ParseSmiles(smiles); atasc.DecideBondOrder(mol, true); @@ -240,14 +220,15 @@ public void TestALargeRingSystem() public void TestLargeRingSystem1() { // Should have 6 double bonds - string smiles = "c1ccc2c(c1)CC4NCCc3cccc2c34"; - IAtomContainer mol = sp.ParseSmiles(smiles); + var smiles = "c1ccc2c(c1)CC4NCCc3cccc2c34"; + var mol = sp.ParseSmiles(smiles); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; foreach (var bond in mol.Bonds) { - if (bond.Order.Equals(BondOrder.Double)) doubleBondCount++; + if (bond.Order.Equals(BondOrder.Double)) + doubleBondCount++; } Assert.AreEqual(6, doubleBondCount); } @@ -256,8 +237,8 @@ public void TestLargeRingSystem1() public void TestLargeRingSystem2() { // Should have 8 double bonds - string smiles = "Oc1ccc(cc1)c1coc2c(c1=O)c(O)cc(c2)O"; - IAtomContainer mol = sp.ParseSmiles(smiles); + var smiles = "Oc1ccc(cc1)c1coc2c(c1=O)c(O)cc(c2)O"; + var mol = sp.ParseSmiles(smiles); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -410,7 +391,7 @@ public void TestFurane() [TestMethod()] public void TestAnOtherDoubleRing() { - IAtomContainer mol = sp.ParseSmiles("c1cccc2cccc2c1"); + var mol = sp.ParseSmiles("c1cccc2cccc2c1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); atasc.DecideBondOrder(mol, true); @@ -426,17 +407,16 @@ public void TestAnOtherDoubleRing() [TestMethod()] public void TestAnOtherRingSystem() { - // Should have 7 double bonds - // IAtomContainer mol = sp.ParseSmiles("O=c2c1ccccc1c3ccccc23"); // Should have 6 double bonds - IAtomContainer mol = sp.ParseSmiles("o2c1ccccc1c3c2cccc3"); + var mol = sp.ParseSmiles("o2c1ccccc1c3c2cccc3"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); atasc.DecideBondOrder(mol, true); Assert.AreEqual(mol.Atoms[1].Hybridization, Hybridization.SP2); int doubleBondCount = 0; foreach (var bond in mol.Bonds) { - if (bond.Order == BondOrder.Double) doubleBondCount++; + if (bond.Order == BondOrder.Double) + doubleBondCount++; } Assert.AreEqual(6, doubleBondCount); } @@ -445,14 +425,15 @@ public void TestAnOtherRingSystem() public void TestAnOtherRingSystem2() { // Should have 7 double bonds - IAtomContainer mol = sp.ParseSmiles("O=c2c1ccccc1c3ccccc23"); + var mol = sp.ParseSmiles("O=c2c1ccccc1c3ccccc23"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); atasc.DecideBondOrder(mol, true); Assert.AreEqual(mol.Atoms[1].Hybridization, Hybridization.SP2); int doubleBondCount = 0; foreach (var bond in mol.Bonds) { - if (bond.Order == BondOrder.Double) doubleBondCount++; + if (bond.Order == BondOrder.Double) + doubleBondCount++; } Assert.AreEqual(7, doubleBondCount); } @@ -460,7 +441,7 @@ public void TestAnOtherRingSystem2() [TestMethod()] public void TestAzulene() { - IAtomContainer mol = sp.ParseSmiles("c12c(ccccc2)ccc1"); + var mol = sp.ParseSmiles("c12c(ccccc2)ccc1"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -476,7 +457,7 @@ public void TestAzulene() [TestMethod()] public void MailCase1a() { - IAtomContainer mol = sp.ParseSmiles("o1cccc1"); + var mol = sp.ParseSmiles("o1cccc1"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -490,7 +471,7 @@ public void MailCase1a() [TestMethod()] public void MailCase1b() { - IAtomContainer mol = sp.ParseSmiles("O1cccc1"); + var mol = sp.ParseSmiles("O1cccc1"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -504,7 +485,7 @@ public void MailCase1b() [TestMethod()] public void MailCase3b() { - IAtomContainer mol = sp.ParseSmiles("c1ccccc1Oc1cOcc1"); + var mol = sp.ParseSmiles("c1ccccc1Oc1cOcc1"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -518,7 +499,7 @@ public void MailCase3b() [TestMethod()] public void MailCase4() { - IAtomContainer mol = sp.ParseSmiles("o2c1ccccc1c3c2cccc3"); + var mol = sp.ParseSmiles("o2c1ccccc1c3c2cccc3"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -532,7 +513,7 @@ public void MailCase4() [TestMethod()] public void MailCase5a() { - IAtomContainer mol = sp.ParseSmiles("c5cc2ccc1ccccc1c2c6c4c3ccccc3ccc4ccc56"); + var mol = sp.ParseSmiles("c5cc2ccc1ccccc1c2c6c4c3ccccc3ccc4ccc56"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -546,7 +527,7 @@ public void MailCase5a() [TestMethod()] public void MailCase5b() { - IAtomContainer mol = sp.ParseSmiles("c1cc2ccc3ccc4ccc5ccc6ccc1c7c2c3c4c5c67"); + var mol = sp.ParseSmiles("c1cc2ccc3ccc4ccc5ccc6ccc1c7c2c3c4c5c67"); atasc.DecideBondOrder(mol, true); @@ -562,7 +543,7 @@ public void MailCase5b() [TestMethod()] public void MailCase6() { - IAtomContainer mol = sp.ParseSmiles("c1ccc2c(c1)cc-3c4c2cccc4-c5c3cccc5"); + var mol = sp.ParseSmiles("c1ccc2c(c1)cc-3c4c2cccc4-c5c3cccc5"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -576,7 +557,7 @@ public void MailCase6() [TestMethod()] public void TestNPolycyclicCompounds() { - IAtomContainer mol = sp.ParseSmiles("n12cncc1cccc2"); + var mol = sp.ParseSmiles("n12cncc1cccc2"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -590,8 +571,7 @@ public void TestNPolycyclicCompounds() [TestMethod()] public void TestIndoles2() { - IAtomContainer mol = sp - .ParseSmiles("Cl.Cl.Oc1ccc2CC3[C@](Cc4c(-c5ccccc5)c(C)[nH0](Cc5ccccc5)c4[C@@H]([C@](CCN3CC3CC3)(c2c1O1)2)1)2(O)"); + var mol = sp.ParseSmiles("Cl.Cl.Oc1ccc2CC3[C@](Cc4c(-c5ccccc5)c(C)[nH0](Cc5ccccc5)c4[C@@H]([C@](CCN3CC3CC3)(c2c1O1)2)1)2(O)"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -605,7 +585,7 @@ public void TestIndoles2() [TestMethod()] public void SomeOtherWieredDoubleRing() { - IAtomContainer mol = sp.ParseSmiles("CCc2c3ccccc3[nH]c2"); + var mol = sp.ParseSmiles("CCc2c3ccccc3[nH]c2"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; @@ -618,7 +598,7 @@ public void SomeOtherWieredDoubleRing() [TestMethod()] public void TestButadieneSmile() { - IAtomContainer mol = sp.ParseSmiles("cccc"); + var mol = sp.ParseSmiles("cccc"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); // The SMILES-parser does not seams raise the SingleOrDouble-flag if a // molecule don't have any rings @@ -638,28 +618,28 @@ public void TestButadieneSmile() [TestMethod()] public void TestButadiene() { - IAtomContainer mol = new AtomContainer(); - IAtomType carbon = new AtomType(ChemicalElements.Carbon.ToIElement()); + var mol = new AtomContainer(); + var carbon = new AtomType(ChemicalElements.Carbon.ToIElement()); - IAtom a0 = new Atom("C") + var a0 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 2 }; AtomTypeManipulator.ConfigureUnsetProperties(a0, carbon); - IAtom a1 = new Atom("C") + var a1 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a1, carbon); - IAtom a2 = new Atom("C") + var a2 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 1 }; AtomTypeManipulator.ConfigureUnsetProperties(a2, carbon); - IAtom a3 = new Atom("C") + var a3 = new Atom("C") { Hybridization = Hybridization.SP2, ImplicitHydrogenCount = 2 @@ -671,25 +651,14 @@ public void TestButadiene() mol.Atoms.Add(a2); mol.Atoms.Add(a3); - IBond b0 = new Bond(a0, a1) - { - IsSingleOrDouble = true - }; + var b0 = new Bond(a0, a1) { IsSingleOrDouble = true }; mol.Bonds.Add(b0); - IBond b1 = new Bond(a1, a2) - { - IsSingleOrDouble = true - }; + var b1 = new Bond(a1, a2) { IsSingleOrDouble = true }; mol.Bonds.Add(b1); - IBond b2 = new Bond(a2, a3) - { - IsSingleOrDouble = true - }; + IBond b2 = new Bond(a2, a3) { IsSingleOrDouble = true }; mol.Bonds.Add(b2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - AtomTypeTools att = new AtomTypeTools(); - att.AssignAtomTypePropertiesToAtom(mol, true); atasc.DecideBondOrder(mol, true); @@ -701,13 +670,14 @@ public void TestButadiene() [TestMethod()] public void TestMolFromSdf() { - IAtomContainer mol = sp.ParseSmiles("OC(COc1ccccc1CC=C)CNC(C)C"); + var mol = sp.ParseSmiles("OC(COc1ccccc1CC=C)CNC(C)C"); atasc.DecideBondOrder(mol, true); int doubleBondCount = 0; foreach (var bond in mol.Bonds) { - if (bond.Order == BondOrder.Double) doubleBondCount++; + if (bond.Order == BondOrder.Double) + doubleBondCount++; } Assert.AreEqual(4, doubleBondCount); } @@ -716,7 +686,7 @@ public void TestMolFromSdf() public void TestOnlyOneAtom() { // If all bonds in the molecule are implicit, then it was noticed that the SatChecker failed - IAtomContainer mol = sp.ParseSmiles("C"); + var mol = sp.ParseSmiles("C"); int preBondCount = mol.Bonds.Count; atasc.DecideBondOrder(mol); diff --git a/NCDKTests/Tools/BremserPredictorTest.cs b/NCDKTests/Tools/BremserPredictorTest.cs index 0804e90a..0f87651a 100644 --- a/NCDKTests/Tools/BremserPredictorTest.cs +++ b/NCDKTests/Tools/BremserPredictorTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System; @@ -84,7 +84,7 @@ public void TestGetConfidenceLimit() for (int f = 0; f < molecule.Atoms.Count; f++) { s = hcg.GetHOSECode(molecule, molecule.Atoms[f], 1); - prediction = bp.GetConfidenceLimit(hcg.MakeBremserCompliant(s)); + prediction = bp.GetConfidenceLimit(HOSECodeGenerator.MakeBremserCompliant(s)); //logger.debug("\"" + prediction + "\","); Assert.AreEqual(result[f], prediction, 0.001); } @@ -148,7 +148,7 @@ public void TestFailure3() Assert.IsTrue(correct); } - private void RemoveHydrogens(IAtomContainer ac) + private static void RemoveHydrogens(IAtomContainer ac) { IAtom atom = null; int f = ac.Atoms.Count - 1; @@ -156,9 +156,11 @@ private void RemoveHydrogens(IAtomContainer ac) do { atom = ac.Atoms[f]; - if (atom.Symbol.Equals("H")) + switch (atom.Symbol) { - ac.RemoveAtom(atom); + case "H": + ac.RemoveAtom(atom); + break; } f--; } while (f >= 0); diff --git a/NCDKTests/Tools/CDKHydrogenAdderTest.cs b/NCDKTests/Tools/CDKHydrogenAdderTest.cs index 55cc2f60..cf0fee00 100644 --- a/NCDKTests/Tools/CDKHydrogenAdderTest.cs +++ b/NCDKTests/Tools/CDKHydrogenAdderTest.cs @@ -20,7 +20,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Numerics; using NCDK.Tools.Manipulator; diff --git a/NCDKTests/Tools/CDKValencyCheckerTest.cs b/NCDKTests/Tools/CDKValencyCheckerTest.cs index 2a4d9873..8141da8f 100644 --- a/NCDKTests/Tools/CDKValencyCheckerTest.cs +++ b/NCDKTests/Tools/CDKValencyCheckerTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.AtomTypes; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; namespace NCDK.Tools @@ -36,7 +36,7 @@ public class CDKValencyCheckerTest : CDKTestCase [TestMethod()] public void TestInstance() { - CDKValencyChecker checker = CDKValencyChecker.GetInstance(Default.ChemObjectBuilder.Instance); + CDKValencyChecker checker = CDKValencyChecker.GetInstance(ChemObjectBuilder.Instance); Assert.IsNotNull(checker); } diff --git a/NCDKTests/Tools/DataFeaturesTest.cs b/NCDKTests/Tools/DataFeaturesTest.cs index a93e2ea4..c74c5975 100644 --- a/NCDKTests/Tools/DataFeaturesTest.cs +++ b/NCDKTests/Tools/DataFeaturesTest.cs @@ -33,7 +33,7 @@ public class DataFeaturesTest : CDKTestCase [TestMethod()] public void TestDataFeatures() { - Assert.IsFalse(DataFeatures.HAS_2D_COORDINATES == (DataFeatures)(-1)); + Assert.IsFalse(DataFeatures.Has2DCoordinates == (DataFeatures)(-1)); } // FIXME: should add a test here that used introspection and test whether there diff --git a/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs b/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs index 3d8c6c8e..825d1db7 100644 --- a/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs +++ b/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Tools { diff --git a/NCDKTests/Tools/HOSECodeAnalyserTest.cs b/NCDKTests/Tools/HOSECodeAnalyserTest.cs index 0390c35b..c55b6ba3 100644 --- a/NCDKTests/Tools/HOSECodeAnalyserTest.cs +++ b/NCDKTests/Tools/HOSECodeAnalyserTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Linq; namespace NCDK.Tools { @@ -26,7 +27,7 @@ namespace NCDK.Tools public class HOSECodeAnalyserTest : CDKTestCase { [TestMethod()] - public void TestGetElements_String() + public void TestGetElementsString() { var elements = HOSECodeAnalyser.GetElements("CCY(CF,C,/C,,&/&)//"); Assert.AreEqual(3, elements.Count); diff --git a/NCDKTests/Tools/HOSECodeGeneratorTest.cs b/NCDKTests/Tools/HOSECodeGeneratorTest.cs index fc4a0dea..4124c4ff 100644 --- a/NCDKTests/Tools/HOSECodeGeneratorTest.cs +++ b/NCDKTests/Tools/HOSECodeGeneratorTest.cs @@ -23,13 +23,14 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Numerics; using NCDK.Smiles; using NCDK.Tools.Manipulator; using System; using System.IO; +using System.Linq; namespace NCDK.Tools { @@ -42,7 +43,7 @@ namespace NCDK.Tools [TestClass()] public class HOSECodeGeneratorTest : CDKTestCase { - static bool standAlone = false; + static readonly bool standAlone = false; // @cdk.bug 968852 [TestMethod()] @@ -51,7 +52,7 @@ public void Test968852() string filename = "NCDK.Data.MDL.2,5-dimethyl-furan.mol"; var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); - IAtomContainer mol1 = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol1 = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); Aromaticity.CDKLegacy.Apply(mol1); Assert.AreEqual(new HOSECodeGenerator().GetHOSECode(mol1, mol1.Atoms[2], 6), @@ -64,12 +65,12 @@ public void TestSecondSphere() string filename = "NCDK.Data.MDL.isopropylacetate.mol"; var ins = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader = new MDLV2000Reader(ins, ChemObjectReaderMode.Strict); - IAtomContainer mol1 = reader.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol1 = reader.Read(ChemObjectBuilder.Instance.NewAtomContainer()); string code1 = new HOSECodeGenerator().GetHOSECode(mol1, mol1.Atoms[0], 6); filename = "NCDK.Data.MDL.testisopropylacetate.mol"; Stream ins2 = ResourceLoader.GetAsStream(filename); MDLV2000Reader reader2 = new MDLV2000Reader(ins2, ChemObjectReaderMode.Strict); - IAtomContainer mol2 = reader2.Read(Default.ChemObjectBuilder.Instance.NewAtomContainer()); + IAtomContainer mol2 = reader2.Read(ChemObjectBuilder.Instance.NewAtomContainer()); string code2 = new HOSECodeGenerator().GetHOSECode(mol2, mol2.Atoms[2], 6); Assert.AreNotSame(code2, code1); } @@ -217,9 +218,11 @@ public void Test1Sphere() for (int f = 0; f < 23; f++) { s = hcg.GetHOSECode(mol, mol.Atoms[f], 1); - if (standAlone) Console.Out.Write("|" + s + "| -> " + result[f]); + if (standAlone) + Console.Out.Write("|" + s + "| -> " + result[f]); Assert.AreEqual(result[f], s); - if (standAlone) Console.Out.WriteLine(" OK"); + if (standAlone) + Console.Out.WriteLine(" OK"); } } @@ -236,13 +239,14 @@ public void TestMakeBremserCompliant() "O(//)", "CC(//)", "CCC(//)", "CCC(//)", "CCC(//)"}; string s = null; - HOSECodeGenerator hcg = new HOSECodeGenerator(); for (int f = 0; f < startData.Length; f++) { - s = hcg.MakeBremserCompliant(startData[f]); - if (standAlone) Console.Out.Write("|" + s + "| -> " + result[f]); + s = HOSECodeGenerator.MakeBremserCompliant(startData[f]); + if (standAlone) + Console.Out.Write("|" + s + "| -> " + result[f]); Assert.AreEqual(result[f], s); - if (standAlone) Console.Out.WriteLine(" OK"); + if (standAlone) + Console.Out.WriteLine(" OK"); } } @@ -402,9 +406,11 @@ public void Test4Sphere() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); s = hcg.GetHOSECode(mol, mol.Atoms[f], 4); - if (standAlone) Console.Out.WriteLine(f + "|" + s + "| -> " + result[f]); + if (standAlone) + Console.Out.WriteLine(f + "|" + s + "| -> " + result[f]); Assert.AreEqual(result[f], s); - if (standAlone) Console.Out.WriteLine(" OK"); + if (standAlone) + Console.Out.WriteLine(" OK"); } } @@ -417,7 +423,7 @@ public void Test4() "C-3;*C*C(*C,*C/*C*N,*&/*&*C,*C)", "C-3;*C*C(*C,*C/*C*C,*&/*&*N,*C)", "C-3;*C*C(*C*C,*C/*C*N,*C,*&/*&,*&,*&)"}; - IAtomContainer molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)) + IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)) .ParseSmiles("C1(C=CN2)=C2C=CC=C1"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); @@ -427,9 +433,11 @@ public void Test4() for (int f = 0; f < molecule.Atoms.Count; f++) { s = hcg.GetHOSECode(molecule, molecule.Atoms[f], 4); - if (standAlone) Console.Out.WriteLine(f + "|" + s + "| -> " + result[f]); + if (standAlone) + Console.Out.WriteLine(f + "|" + s + "| -> " + result[f]); Assert.AreEqual(result[f], s); - if (standAlone) Console.Out.WriteLine(" OK"); + if (standAlone) + Console.Out.WriteLine(" OK"); } } @@ -441,7 +449,7 @@ public void TestBug655169() HOSECodeGenerator hcg = null; string[] result = { "C-4;C(=C/Y/)", "C-3;=CC(Y,//)", "C-3;=CY(C,//)", "Br-1;C(=C/C/)" }; - molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CC=CBr"); + molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC=CBr"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); hcg = new HOSECodeGenerator(); @@ -449,9 +457,11 @@ public void TestBug655169() for (int f = 0; f < molecule.Atoms.Count; f++) { s = hcg.GetHOSECode(molecule, molecule.Atoms[f], 4); - if (standAlone) Console.Out.Write("|" + s + "| -> " + result[f]); + if (standAlone) + Console.Out.Write("|" + s + "| -> " + result[f]); Assert.AreEqual(result[f], s); - if (standAlone) Console.Out.WriteLine(" OK"); + if (standAlone) + Console.Out.WriteLine(" OK"); } } @@ -463,7 +473,7 @@ public void TestBug795480() HOSECodeGenerator hcg = null; string[] result = { "C-4-;C(=C/Y'+4'/)", "C-3;=CC-(Y'+4',//)", "C-3;=CY'+4'(C-,//)", "Br-1'+4';C(=C/C-/)" }; - molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CC=CBr"); + molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC=CBr"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); bool isAromatic = Aromaticity.CDKLegacy.Apply(molecule); Assert.IsFalse(isAromatic); @@ -474,22 +484,24 @@ public void TestBug795480() for (int f = 0; f < molecule.Atoms.Count; f++) { s = hcg.GetHOSECode(molecule, molecule.Atoms[f], 4); - if (standAlone) Console.Out.Write("|" + s + "| -> " + result[f]); + if (standAlone) + Console.Out.Write("|" + s + "| -> " + result[f]); Assert.AreEqual(result[f], s); - if (standAlone) Console.Out.WriteLine(" OK"); + if (standAlone) + Console.Out.WriteLine(" OK"); } } [TestMethod()] public void TestGetAtomsOfSphere() { - IAtomContainer molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CC=CBr"); + IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC=CBr"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); HOSECodeGenerator hcg = new HOSECodeGenerator(); hcg.GetSpheres(molecule, molecule.Atoms[0], 4, true); - var atoms = hcg.GetNodesInSphere(3); + var atoms = hcg.GetNodesInSphere(3).ToList(); Assert.AreEqual(1, atoms.Count); Assert.AreEqual("Br", atoms[0].Symbol); @@ -498,14 +510,14 @@ public void TestGetAtomsOfSphere() [TestMethod()] public void TestGetAtomsOfSphereWithHydr() { - IAtomContainer molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)) + IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)) .ParseSmiles("C([H])([H])([H])C([H])=C([H])Br"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); Aromaticity.CDKLegacy.Apply(molecule); HOSECodeGenerator hcg = new HOSECodeGenerator(); hcg.GetSpheres(molecule, molecule.Atoms[0], 3, true); - var atoms = hcg.GetNodesInSphere(3); + var atoms = hcg.GetNodesInSphere(3).ToList(); Assert.AreEqual(2, atoms.Count); diff --git a/NCDKTests/Tools/IDCreatorTest.cs b/NCDKTests/Tools/IDCreatorTest.cs index 4b071f96..77ebcbac 100644 --- a/NCDKTests/Tools/IDCreatorTest.cs +++ b/NCDKTests/Tools/IDCreatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Tools.Manipulator; using System.Linq; diff --git a/NCDKTests/Tools/LonePairElectronCheckerTest.cs b/NCDKTests/Tools/LonePairElectronCheckerTest.cs index 4d1a0dc5..38d0c572 100644 --- a/NCDKTests/Tools/LonePairElectronCheckerTest.cs +++ b/NCDKTests/Tools/LonePairElectronCheckerTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Tools.Manipulator; using System.Linq; @@ -36,8 +36,6 @@ namespace NCDK.Tools [TestClass()] public class LonePairElectronCheckerTest : CDKTestCase { - private static LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - [TestMethod()] public void TestAllSaturated_Formaldehyde() { @@ -61,7 +59,7 @@ public void TestAllSaturated_Formaldehyde() m.Bonds.Add(new Bond(c, O, BondOrder.Double)); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - Assert.IsTrue(lpcheck.AllSaturated(m)); + Assert.IsTrue(LonePairElectronChecker.AllSaturated(m)); } [TestMethod()] @@ -84,7 +82,7 @@ public void TestAllSaturated_Methanethiol() } AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - Assert.IsFalse(lpcheck.AllSaturated(m)); + Assert.IsFalse(LonePairElectronChecker.AllSaturated(m)); } [TestMethod()] @@ -101,7 +99,7 @@ public void TestNewSaturate_Methyl_chloride() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(3, m.GetConnectedLonePairs(cl).Count()); Assert.AreEqual(0, m.GetConnectedLonePairs(c1).Count()); } @@ -120,7 +118,7 @@ public void TestNewSaturate_Methyl_alcohol() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(2, m.GetConnectedLonePairs(o).Count()); Assert.AreEqual(0, m.GetConnectedLonePairs(c1).Count()); } @@ -141,7 +139,7 @@ public void TestNewSaturate_Methyl_alcohol_AddH() m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[1], m.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(2, m.GetConnectedLonePairs(m.Atoms[1]).Count()); Assert.AreEqual(0, m.GetConnectedLonePairs(m.Atoms[0]).Count()); @@ -165,7 +163,7 @@ public void TestNewSaturate_Methyl_alcohol_protonated() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(1, m.GetConnectedLonePairs(o).Count()); } @@ -184,7 +182,7 @@ public void TestNewSaturate_methoxide_anion() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(3, m.GetConnectedLonePairs(o).Count()); } @@ -199,7 +197,7 @@ public void TestNewSaturate_Ammonia() m.Atoms.Add(n); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(1, m.GetConnectedLonePairs(n).Count()); } @@ -222,7 +220,7 @@ public void TestNewSaturate_methylamine_radical_cation() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - lpcheck.Saturate(m); + LonePairElectronChecker.Saturate(m); Assert.AreEqual(0, m.GetConnectedLonePairs(n).Count()); } @@ -234,10 +232,10 @@ public void TestNewSaturate_methylamine_radical_cation() public void TestNewSaturate_withHAdded() { // O=C([H])[C+]([H])[C-]([H])[H] - SmilesParser sp = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C([H])[C+]([H])[C-]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - lpcheck.Saturate(mol); + LonePairElectronChecker.Saturate(mol); Assert.AreEqual(2, mol.GetConnectedLonePairs(mol.Atoms[0]).Count()); Assert.AreEqual(0, mol.GetConnectedLonePairs(mol.Atoms[3]).Count()); diff --git a/NCDKTests/Tools/Manipulator/AtomContainerComparatorBy2DCenterTest.cs b/NCDKTests/Tools/Manipulator/AtomContainerComparatorBy2DCenterTest.cs index daa0175c..006b542a 100644 --- a/NCDKTests/Tools/Manipulator/AtomContainerComparatorBy2DCenterTest.cs +++ b/NCDKTests/Tools/Manipulator/AtomContainerComparatorBy2DCenterTest.cs @@ -19,7 +19,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.Numerics; using System.Collections.Generic; diff --git a/NCDKTests/Tools/Manipulator/AtomContainerComparatorTest.cs b/NCDKTests/Tools/Manipulator/AtomContainerComparatorTest.cs index c2562073..4cf52f2d 100644 --- a/NCDKTests/Tools/Manipulator/AtomContainerComparatorTest.cs +++ b/NCDKTests/Tools/Manipulator/AtomContainerComparatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Collections.Generic; namespace NCDK.Tools.Manipulator @@ -34,7 +34,7 @@ public AtomContainerComparatorTest() [TestMethod()] public void TestCompare_Null_IAtomContainer() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloPentane = builder.NewRing(5, "C"); // Instantiate the comparator @@ -76,7 +76,7 @@ public void TestCompare_Atom_PseudoAtom() [TestMethod()] public void TestCompare_IAtomContainer_Null() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloPentane = builder.NewRing(5, "C"); // Instantiate the comparator @@ -90,7 +90,7 @@ public void TestCompare_IAtomContainer_Null() public void TestCompare_RingSize() { // Create some IAtomContainers - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloPentane = builder.NewRing(5, "C"); IRing cycloHexane = builder.NewRing(6, "C"); @@ -106,7 +106,7 @@ public void TestCompare_RingSize() public void TestCompare_Ring_NonRing() { // Create some IAtomContainers - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloHexane = builder.NewRing(6, "C"); IAtomContainer hexaneNitrogen = builder.NewRing(6, "N"); hexaneNitrogen.Bonds.RemoveAt(0); @@ -123,7 +123,7 @@ public void TestCompare_Ring_NonRing() public void TestCompare_Ring_NonRing2() { // Create some IAtomContainers - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer hexaneNitrogen = builder.NewRing(6, "N"); hexaneNitrogen.Bonds.RemoveAt(0); IRing cycloHexaneNitrogen = builder.NewRing(6, "N"); @@ -140,7 +140,7 @@ public void TestCompare_Ring_NonRing2() public void TestCompare_BondOrder() { // Create some IAtomContainers - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloHexaneNitrogen = builder.NewRing(6, "N"); IRing cycloHexeneNitrogen = builder.NewRing(6, "N"); cycloHexeneNitrogen.Bonds[0].Order = BondOrder.Double; diff --git a/NCDKTests/Tools/Manipulator/AtomContainerManipulatorTest.cs b/NCDKTests/Tools/Manipulator/AtomContainerManipulatorTest.cs index a7b80c4f..babb8bde 100644 --- a/NCDKTests/Tools/Manipulator/AtomContainerManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/AtomContainerManipulatorTest.cs @@ -19,10 +19,10 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; using NCDK.IO; using NCDK.Isomorphisms; using NCDK.Sgroups; +using NCDK.Silent; using NCDK.Smiles; using NCDK.Stereo; using NCDK.Templates; @@ -36,7 +36,7 @@ namespace NCDK.Tools.Manipulator [TestClass()] public class AtomContainerManipulatorTest : CDKTestCase { - IAtomContainer ac = TestMoleculeFactory.MakeAlphaPinene(); + readonly IAtomContainer ac = TestMoleculeFactory.MakeAlphaPinene(); [TestMethod()] public void TestExtractSubstructure() @@ -224,7 +224,7 @@ public void SuppressHydrogensKeepsRadicals() Assert.AreEqual(1, ac.SingleElectrons.Count); } - private IAtomContainer GetChiralMolTemplate() + private static IAtomContainer GetChiralMolTemplate() { IAtomContainer molecule = new AtomContainer(); molecule.Atoms.Add(new Atom("Cl")); @@ -380,7 +380,7 @@ public void TestGetAtomArray_IAtomContainer() mol.Atoms.Add(new Atom("H")); mol.Atoms.Add(new Atom("H")); - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(mol); + IAtom[] atoms = mol.Atoms.ToArray(); Assert.AreEqual(6, atoms.Length); Assert.AreEqual(mol.Atoms[0], atoms[0]); Assert.AreEqual(mol.Atoms[1], atoms[1]); @@ -407,7 +407,7 @@ public void TestGetAtomArray_List() mol.AddBond(mol.Atoms[1], mol.Atoms[5], BondOrder.Double); mol.IsAromatic = true; - IAtom[] atoms = AtomContainerManipulator.GetAtomArray(mol.GetConnectedAtoms(mol.Atoms[0])); + IAtom[] atoms = mol.GetConnectedAtoms(mol.Atoms[0]).ToArray(); Assert.AreEqual(3, atoms.Length); Assert.AreEqual(mol.Atoms[1], atoms[0]); Assert.AreEqual(mol.Atoms[2], atoms[1]); @@ -431,7 +431,7 @@ public void TestGetBondArray_List() mol.AddBond(mol.Atoms[1], mol.Atoms[5], BondOrder.Double); mol.IsAromatic = true; - IBond[] bonds = AtomContainerManipulator.GetBondArray(mol.GetConnectedBonds(mol.Atoms[0])); + IBond[] bonds = mol.GetConnectedBonds(mol.Atoms[0]).ToArray(); Assert.AreEqual(3, bonds.Length); Assert.AreEqual(mol.Bonds[0], bonds[0]); Assert.AreEqual(mol.Bonds[1], bonds[1]); @@ -455,7 +455,7 @@ public void TestGetBondArray_IAtomContainer() mol.AddBond(mol.Atoms[1], mol.Atoms[5], BondOrder.Double); mol.IsAromatic = true; - IBond[] bonds = AtomContainerManipulator.GetBondArray(mol); + IBond[] bonds = mol.Bonds.ToArray(); Assert.AreEqual(5, bonds.Length); Assert.AreEqual(mol.Bonds[0], bonds[0]); Assert.AreEqual(mol.Bonds[1], bonds[1]); @@ -540,7 +540,7 @@ public void TestRemoveHydrogensBorane() [TestMethod()] public void TestGetTotalFormalCharge_IAtomContainer() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = parser.ParseSmiles("[O-]C([N+])C([N+])C"); int totalCharge = AtomContainerManipulator.GetTotalFormalCharge(mol); @@ -553,7 +553,7 @@ public void TestGetTotalFormalCharge_IAtomContainer() [TestMethod()] public void TestGetTotalExactMass_IAtomContainer() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = parser.ParseSmiles("CCl"); mol.Atoms[0].ExactMass = 12.00; mol.Atoms[1].ExactMass = 34.96885268; @@ -585,7 +585,7 @@ public void GetNaturalExactMassNeedsAtomicNumber() [TestMethod()] public void TestGetNaturalExactMass_IAtomContainer() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer mol = builder.NewAtomContainer(); mol.Atoms.Add(new Atom("C")); mol.Atoms.Add(new Atom("Cl")); @@ -594,9 +594,9 @@ public void TestGetNaturalExactMass_IAtomContainer() mol.Atoms[1].ImplicitHydrogenCount = 1; double expectedMass = 0.0; - expectedMass += Isotopes.Instance.GetNaturalMass(builder.NewElement("C")); - expectedMass += Isotopes.Instance.GetNaturalMass(builder.NewElement("Cl")); - expectedMass += 5 * Isotopes.Instance.GetNaturalMass(builder.NewElement("H")); + expectedMass += BODRIsotopeFactory.Instance.GetNaturalMass(builder.NewElement("C")); + expectedMass += BODRIsotopeFactory.Instance.GetNaturalMass(builder.NewElement("Cl")); + expectedMass += 5 * BODRIsotopeFactory.Instance.GetNaturalMass(builder.NewElement("H")); double totalExactMass = AtomContainerManipulator.GetNaturalExactMass(mol); @@ -609,7 +609,7 @@ public void TestGetNaturalExactMass_IAtomContainer() [TestMethod()] public void TestGetTotalNaturalAbundance_IAtomContainer() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = parser.ParseSmiles("CCl"); mol.Atoms[0].NaturalAbundance = 98.93; mol.Atoms[1].NaturalAbundance = 75.78; @@ -624,7 +624,7 @@ public void TestGetTotalNaturalAbundance_IAtomContainer() [TestMethod()] public void TestGetTotalPositiveFormalCharge_IAtomContainer() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = parser.ParseSmiles("[O-]C([N+])C([N+])C"); int totalCharge = AtomContainerManipulator.GetTotalPositiveFormalCharge(mol); @@ -637,7 +637,7 @@ public void TestGetTotalPositiveFormalCharge_IAtomContainer() [TestMethod()] public void TestGetTotalNegativeFormalCharge_IAtomContainer() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = parser.ParseSmiles("[O-]C([N+])C([N+])C"); int totalCharge = AtomContainerManipulator.GetTotalNegativeFormalCharge(mol); @@ -647,7 +647,7 @@ public void TestGetTotalNegativeFormalCharge_IAtomContainer() [TestMethod()] public void TestGetIntersection_IAtomContainer_IAtomContainer() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtom c1 = builder.NewAtom("C"); IAtom o = builder.NewAtom("O"); IAtom c2 = builder.NewAtom("C"); @@ -717,10 +717,10 @@ public void TestPerceiveAtomTypesAndConfigureUnSetProperties() [TestMethod()] public void TestClearConfig() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom atom3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom atom3 = ChemObjectBuilder.Instance.NewAtom("C"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); container.Atoms.Add(atom3); @@ -745,10 +745,10 @@ public void TestClearConfig() [TestMethod()] public void AtomicNumberIsNotCleared() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("O"); - IAtom atom3 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("O"); + IAtom atom3 = ChemObjectBuilder.Instance.NewAtom("C"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); container.Atoms.Add(atom3); @@ -777,10 +777,10 @@ public void TestGetSBE() [TestMethod()] public void TestGetTotalCharge() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.Charge = 1.0; - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("N"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); @@ -797,7 +797,7 @@ public void TestGetTotalCharge() public void TestCountExplicitH_Null_IAtom() { AtomContainerManipulator.CountExplicitHydrogens(null, - Default.ChemObjectBuilder.Instance.NewAtom()); + ChemObjectBuilder.Instance.NewAtom()); } // @cdk.bug 1254 @@ -806,16 +806,16 @@ public void TestCountExplicitH_Null_IAtom() public void TestCountExplicitH_IAtomContainer_Null() { AtomContainerManipulator.CountExplicitHydrogens( - Default.ChemObjectBuilder.Instance.NewAtomContainer(), null); + ChemObjectBuilder.Instance.NewAtomContainer(), null); } [TestMethod()] public void TestCountExplicitH() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.Charge = 1.0; - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("N"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); @@ -826,7 +826,7 @@ public void TestCountExplicitH() for (int i = 0; i < 3; i++) { - IAtom h = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h = ChemObjectBuilder.Instance.NewAtom("H"); container.Atoms.Add(h); container.Bonds.Add(new Bond(atom1, h, BondOrder.Single)); } @@ -836,10 +836,10 @@ public void TestCountExplicitH() [TestMethod()] public void TestCountH() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.Charge = 1.0; - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("N"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); @@ -850,7 +850,7 @@ public void TestCountH() Assert.AreEqual(0, AtomContainerManipulator.CountHydrogens(container, atom2)); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - CDKHydrogenAdder ha = CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance); + CDKHydrogenAdder ha = CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance); ha.AddImplicitHydrogens(container); Assert.AreEqual(3, AtomContainerManipulator.CountHydrogens(container, atom1)); @@ -858,7 +858,7 @@ public void TestCountH() for (int i = 0; i < 3; i++) { - IAtom h = Default.ChemObjectBuilder.Instance.NewAtom("H"); + IAtom h = ChemObjectBuilder.Instance.NewAtom("H"); container.Atoms.Add(h); container.Bonds.Add(new Bond(atom1, h, BondOrder.Single)); } @@ -890,7 +890,7 @@ public void TestGetImplicitHydrogenCount_adenine() { IAtomContainer container = TestMoleculeFactory.MakeAdenine(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance).AddImplicitHydrogens(container); + CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance).AddImplicitHydrogens(container); Assert.AreEqual(5, AtomContainerManipulator.GetImplicitHydrogenCount(container), "Adenine should have 5 implicit hydrogens"); @@ -899,16 +899,16 @@ public void TestGetImplicitHydrogenCount_adenine() [TestMethod()] public void TestReplaceAtom() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.Charge = 1.0; - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("N"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); container.Bonds.Add(new Bond(atom1, atom2, BondOrder.Single)); - IAtom atom3 = Default.ChemObjectBuilder.Instance.NewAtom("Br"); + IAtom atom3 = ChemObjectBuilder.Instance.NewAtom("Br"); AtomContainerManipulator.ReplaceAtomByAtom(container, atom2, atom3); Assert.AreEqual(atom3, container.Atoms[1]); @@ -917,17 +917,17 @@ public void TestReplaceAtom() [TestMethod()] public void TestReplaceAtom_lonePair() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.Charge = 1.0; - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("N"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); container.Bonds.Add(new Bond(atom1, atom2, BondOrder.Single)); container.AddLonePairTo(container.Atoms[1]); - IAtom atom3 = Default.ChemObjectBuilder.Instance.NewAtom("Br"); + IAtom atom3 = ChemObjectBuilder.Instance.NewAtom("Br"); AtomContainerManipulator.ReplaceAtomByAtom(container, atom2, atom3); Assert.AreEqual(atom3, container.LonePairs[0].Atom); @@ -936,17 +936,17 @@ public void TestReplaceAtom_lonePair() [TestMethod()] public void TestReplaceAtom_singleElectron() { - IAtomContainer container = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - IAtom atom1 = Default.ChemObjectBuilder.Instance.NewAtom("C"); + IAtomContainer container = ChemObjectBuilder.Instance.NewAtomContainer(); + IAtom atom1 = ChemObjectBuilder.Instance.NewAtom("C"); atom1.Charge = 1.0; - IAtom atom2 = Default.ChemObjectBuilder.Instance.NewAtom("N"); + IAtom atom2 = ChemObjectBuilder.Instance.NewAtom("N"); container.Atoms.Add(atom1); container.Atoms.Add(atom2); container.Bonds.Add(new Bond(atom1, atom2, BondOrder.Single)); container.AddSingleElectronTo(container.Atoms[1]); - IAtom atom3 = Default.ChemObjectBuilder.Instance.NewAtom("Br"); + IAtom atom3 = ChemObjectBuilder.Instance.NewAtom("Br"); AtomContainerManipulator.ReplaceAtomByAtom(container, atom2, atom3); Assert.AreEqual(atom3, container.SingleElectrons[0].Atom); @@ -967,7 +967,7 @@ public void TestReplaceAtom_stereochemistry() [TestMethod()] public void TestGetHeavyAtoms_IAtomContainer() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer container = builder.NewAtomContainer(); container.Atoms.Add(builder.NewAtom("C")); for (int i = 0; i < 4; i++) @@ -1013,19 +1013,20 @@ public void TestRemoveHydrogensPreserveMultiplyBonded() { IAtom atom = ac.Atoms[i]; string sym = atom.Symbol; - if (sym.Equals("B")) + switch (sym) { - // Each B has two explicit and two implicit H. - b++; - Assert.AreEqual(2, atom.ImplicitHydrogenCount.Value, "incorrect hydrogen count"); - var nbs = ac.GetConnectedAtoms(atom).ToList(); - Assert.AreEqual(2, nbs.Count, "incorrect connected count"); - Assert.AreEqual("H", ((IAtom)nbs[0]).Symbol, "incorrect bond"); - Assert.AreEqual("H", ((IAtom)nbs[1]).Symbol, "incorrect bond"); - } - else if (sym.Equals("H")) - { - h++; + case "B": + // Each B has two explicit and two implicit H. + b++; + Assert.AreEqual(2, atom.ImplicitHydrogenCount.Value, "incorrect hydrogen count"); + var nbs = ac.GetConnectedAtoms(atom).ToList(); + Assert.AreEqual(2, nbs.Count, "incorrect connected count"); + Assert.AreEqual("H", ((IAtom)nbs[0]).Symbol, "incorrect bond"); + Assert.AreEqual("H", ((IAtom)nbs[1]).Symbol, "incorrect bond"); + break; + case "H": + h++; + break; } } Assert.AreEqual(2, b, "incorrect no. Bs"); @@ -1033,7 +1034,7 @@ public void TestRemoveHydrogensPreserveMultiplyBonded() } [TestMethod()] - public void TestCreateAnyAtomAnyBondAtomContainer_IAtomContainer() + public void TestCreateAnyAtomAnyBondAtomContainerIAtomContainer() { string smiles = "c1ccccc1"; SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); @@ -1104,7 +1105,7 @@ public void TestOverWriteConfig() var exactMass = new Dictionary(); - Isotopes.Instance.ConfigureAtoms(ac); + BODRIsotopeFactory.Instance.ConfigureAtoms(ac); foreach (var atom in ac.Atoms) { @@ -1175,7 +1176,7 @@ public void TestRemoveHydrogensFromMolecularHydrogen() [TestMethod()] public void TestBondOrderSum() { - SmilesParser parser = new SmilesParser(Default.ChemObjectBuilder.Instance); + SmilesParser parser = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = parser.ParseSmiles("C=CC"); double bosum = AtomContainerManipulator.GetBondOrderSum(mol, mol.Atoms[0]); Assert.AreEqual(2.0, bosum, 0.001); @@ -1183,109 +1184,104 @@ public void TestBondOrderSum() Assert.AreEqual(3.0, bosum, 0.001); bosum = AtomContainerManipulator.GetBondOrderSum(mol, mol.Atoms[2]); Assert.AreEqual(1.0, bosum, 0.001); - } [TestMethod()] - public void ConvertExplicitHydrogen_chiralCarbon() + public void ConvertExplicitHydrogenChiralCarbon() { SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); IAtomContainer m = smipar.ParseSmiles("C[C@H](CC)O"); - AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(m); - Assert.AreEqual("C([C@](C(C([H])([H])[H])([H])[H])(O[H])[H])([H])([H])[H]", SmilesGenerator.Isomeric().Create(m)); } [TestMethod()] - public void ConvertExplicitHydrogen_sulfoxide() + public void ConvertExplicitHydrogenSulfoxide() { SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); IAtomContainer m = smipar.ParseSmiles("[S@](=O)(C)CC"); - AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(m); - Assert.AreEqual("[S@](=O)(C([H])([H])[H])C(C([H])([H])[H])([H])[H]", SmilesGenerator.Isomeric().Create(m)); } [TestMethod()] - public void RemoveHydrogens_chiralCarbon1() + public void RemoveHydrogensChiralCarbon1() { AssertRemoveH("C[C@@](CC)([H])O", "C[C@H](CC)O"); } [TestMethod()] - public void RemoveHydrogens_chiralCarbon2() + public void RemoveHydrogensChiralCarbon2() { AssertRemoveH("C[C@@]([H])(CC)O", "C[C@@H](CC)O"); } [TestMethod()] - public void RemoveHydrogens_chiralCarbon3() + public void RemoveHydrogensChiralCarbon3() { AssertRemoveH("C[C@@](CC)(O)[H]", "C[C@@H](CC)O"); } [TestMethod()] - public void RemoveHydrogens_chiralCarbon4() + public void RemoveHydrogensChiralCarbon4() { AssertRemoveH("[H][C@@](C)(CC)O", "[C@@H](C)(CC)O"); } [TestMethod()] - public void RemoveHydrogens_db_trans1() + public void RemoveHydrogensDbTrans1() { AssertRemoveH("C/C([H])=C([H])/C", "C/C=C/C"); AssertRemoveH("C\\C([H])=C([H])\\C", "C/C=C/C"); } [TestMethod()] - public void RemoveHydrogens_db_cis1() + public void RemoveHydrogensDbCis1() { AssertRemoveH("C/C([H])=C([H])\\C", "C/C=C\\C"); AssertRemoveH("C\\C([H])=C([H])/C", "C/C=C\\C"); } [TestMethod()] - public void RemoveHydrogens_db_trans2() + public void RemoveHydrogensDbTrans2() { AssertRemoveH("CC(/[H])=C([H])/C", "C/C=C/C"); } [TestMethod()] - public void RemoveHydrogens_db_cis2() + public void RemoveHydrogensDbCis2() { AssertRemoveH("CC(\\[H])=C([H])/C", "C/C=C\\C"); } [TestMethod()] - public void RemoveHydrogens_db_trans3() + public void RemoveHydrogensDbTrans3() { AssertRemoveH("CC(/[H])=C(\\[H])C", "C/C=C/C"); } [TestMethod()] - public void RemoveHydrogens_db_cis3() + public void RemoveHydrogensDbCis3() { AssertRemoveH("CC(\\[H])=C(\\[H])C", "C/C=C\\C"); } // hydrogen isotopes should not be removed [TestMethod()] - public void RemoveHydrogens_Isotopes() + public void RemoveHydrogensIsotopes() { AssertRemoveH("C([H])([2H])([3H])[H]", "C([2H])[3H]"); } // hydrogens with charge should not be removed [TestMethod()] - public void RemoveHydrogens_ions() + public void RemoveHydrogensIons() { AssertRemoveH("C([H])([H+])([H-])[H]", "C([H+])[H-]"); } [TestMethod()] - public void RemoveHydrogens_molecularH() + public void RemoveHydrogensMolecularH() { AssertRemoveH("[H][H]", "[H][H]"); AssertRemoveH("[HH]", "[H][H]"); @@ -1300,10 +1296,10 @@ public void TestSgroupSuppressionSRU() [TestMethod()] public void TestSgroupSuppressionSRUUpdated() { - SmilesParser smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); - IAtomContainer mol = smipar.ParseSmiles("CCC([H])CC |Sg:n:1,2,3,4:n:ht|"); + var smipar = new SmilesParser(Silent.ChemObjectBuilder.Instance); + var mol = smipar.ParseSmiles("CCC([H])CC |Sg:n:1,2,3,4:n:ht|"); AtomContainerManipulator.SuppressHydrogens(mol); - ICollection sgroups = mol.GetProperty>(CDKPropertyName.CtabSgroups); + var sgroups = mol.GetCtabSgroups(); Assert.IsNotNull(sgroups); Assert.AreEqual(1, sgroups.Count); Sgroup sgroup = sgroups.First(); @@ -1329,12 +1325,11 @@ public void MolecularWeight() IAtomContainer mol = smipar.ParseSmiles("[13CH4]CO"); double molecularWeight = AtomContainerManipulator.GetMolecularWeight(mol); double naturalExactMass = AtomContainerManipulator.GetNaturalExactMass(mol); - Isotopes isotopes = Isotopes.Instance; + BODRIsotopeFactory isotopes = BODRIsotopeFactory.Instance; foreach (IAtom atom in mol.Atoms) { if (atom.MassNumber == null) - atom.ExactMass = isotopes.GetMajorIsotope(atom.AtomicNumber.Value) - .ExactMass; + atom.ExactMass = isotopes.GetMajorIsotope(atom.AtomicNumber.Value).ExactMass; else isotopes.Configure(atom); } diff --git a/NCDKTests/Tools/Manipulator/AtomContainerSetManipulatorTest.cs b/NCDKTests/Tools/Manipulator/AtomContainerSetManipulatorTest.cs index 200b6a84..2660f58f 100644 --- a/NCDKTests/Tools/Manipulator/AtomContainerSetManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/AtomContainerSetManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Linq; namespace NCDK.Tools.Manipulator @@ -190,7 +190,7 @@ public void TestGetAllChemObjects_IAtomContainerSet() public void TestSort_IAtomContainerSet() { // Create some IAtomContainers - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloPentane = builder.NewRing(5, "C"); IRing cycloHexane = builder.NewRing(6, "C"); IAtomContainer hexaneNitrogen = builder.NewRing(6, "N"); @@ -221,9 +221,8 @@ public void TestSort_IAtomContainerSet() [TestMethod()] public void TestContainsByID_IAtomContainerSet_IAtomContainer() { - IAtomContainer relevantAtomContainer = Default.ChemObjectBuilder.Instance.NewAtomContainer(); - var atomContainerSet = Default.ChemObjectBuilder.Instance - .NewAtomContainerSet(); + IAtomContainer relevantAtomContainer = ChemObjectBuilder.Instance.NewAtomContainer(); + var atomContainerSet = ChemObjectBuilder.Instance.NewAtomContainerSet(); atomContainerSet.Add(relevantAtomContainer); Assert.IsFalse(AtomContainerSetManipulator.ContainsByID(atomContainerSet, relevantAtomContainer.Id)); relevantAtomContainer.Id = "1"; diff --git a/NCDKTests/Tools/Manipulator/AtomTypeManipulatorTest.cs b/NCDKTests/Tools/Manipulator/AtomTypeManipulatorTest.cs index d9432cd7..a7ab9c1f 100644 --- a/NCDKTests/Tools/Manipulator/AtomTypeManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/AtomTypeManipulatorTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using System; namespace NCDK.Tools.Manipulator diff --git a/NCDKTests/Tools/Manipulator/BondManipulatorTest.cs b/NCDKTests/Tools/Manipulator/BondManipulatorTest.cs index 82074318..104fc55a 100644 --- a/NCDKTests/Tools/Manipulator/BondManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/BondManipulatorTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using System; using System.Collections.Generic; diff --git a/NCDKTests/Tools/Manipulator/ChemFileManipulatorTest.cs b/NCDKTests/Tools/Manipulator/ChemFileManipulatorTest.cs index 7c8b4555..3f188cd5 100644 --- a/NCDKTests/Tools/Manipulator/ChemFileManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/ChemFileManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System.Collections.Generic; using System.Diagnostics; diff --git a/NCDKTests/Tools/Manipulator/ChemModelManipulatorTest.cs b/NCDKTests/Tools/Manipulator/ChemModelManipulatorTest.cs index 467753b1..ff92a282 100644 --- a/NCDKTests/Tools/Manipulator/ChemModelManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/ChemModelManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System; using System.Collections.Generic; @@ -61,7 +61,7 @@ public void SetUp() atomInMol2 = new Atom("O"); atomInMol2.ImplicitHydrogenCount = 2; molecule2.Atoms.Add(atomInMol2); - moleculeSet = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + moleculeSet = ChemObjectBuilder.Instance.NewAtomContainerSet(); moleculeSet.Add(molecule1); moleculeSet.Add(molecule2); reaction = new Reaction(); @@ -141,7 +141,7 @@ public void TestRemoveElectronContainer_IChemModel_IElectronContainer() mol2.Atoms.Add(new Atom("I")); IBond bond2 = new Bond(mol2.Atoms[0], mol2.Atoms[1]); mol2.Bonds.Add(bond2); - var molSet = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var molSet = ChemObjectBuilder.Instance.NewAtomContainerSet(); molSet.Add(mol1); IReaction r = new Reaction(); r.Products.Add(mol2); @@ -175,7 +175,7 @@ public void TestRemoveAtomAndConnectedElectronContainers_IChemModel_IAtom() mol2.Atoms.Add(new Atom("I")); IBond bond2 = new Bond(mol2.Atoms[0], mol2.Atoms[1]); mol2.Bonds.Add(bond2); - var molSet = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + var molSet = ChemObjectBuilder.Instance.NewAtomContainerSet(); molSet.Add(mol1); IReaction r = new Reaction(); r.Products.Add(mol2); diff --git a/NCDKTests/Tools/Manipulator/ChemSequenceManipulatorTest.cs b/NCDKTests/Tools/Manipulator/ChemSequenceManipulatorTest.cs index 4a106110..b978cbc5 100644 --- a/NCDKTests/Tools/Manipulator/ChemSequenceManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/ChemSequenceManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Collections.Generic; namespace NCDK.Tools.Manipulator @@ -56,7 +56,7 @@ public void SetUp() atomInMol2 = new Atom("O"); atomInMol2.ImplicitHydrogenCount = 2; molecule2.Atoms.Add(atomInMol2); - moleculeSet = Default.ChemObjectBuilder.Instance.NewAtomContainerSet(); + moleculeSet = ChemObjectBuilder.Instance.NewAtomContainerSet(); moleculeSet.Add(molecule1); moleculeSet.Add(molecule2); reaction = new Reaction(); diff --git a/NCDKTests/Tools/Manipulator/MolecularFormulaManipulatorTest.cs b/NCDKTests/Tools/Manipulator/MolecularFormulaManipulatorTest.cs index 76eb07fd..cfab501e 100644 --- a/NCDKTests/Tools/Manipulator/MolecularFormulaManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/MolecularFormulaManipulatorTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Config; -using NCDK.Default; +using NCDK.Silent; using NCDK.Formula; using NCDK.IO; using NCDK.Templates; @@ -47,7 +47,7 @@ public MolecularFormulaManipulatorTest() { try { - ifac = Isotopes.Instance; + ifac = BODRIsotopeFactory.Instance; } catch (IOException e) { @@ -290,8 +290,8 @@ public void TestGetMajorIsotopeMolecularFormula_String_IChemObjectBuilder() Assert.AreEqual(28, MolecularFormulaManipulator.GetAtomCount(mf2)); Assert.AreEqual(2, mf2.Isotopes.Count()); - IIsotope carbon = Isotopes.Instance.GetMajorIsotope("C"); - IIsotope hydrogen = Isotopes.Instance.GetMajorIsotope("H"); + IIsotope carbon = BODRIsotopeFactory.Instance.GetMajorIsotope("C"); + IIsotope hydrogen = BODRIsotopeFactory.Instance.GetMajorIsotope("H"); double totalMass = carbon.ExactMass.Value * 11; totalMass += hydrogen.ExactMass.Value * 17; Assert.AreEqual(totalMass, MolecularFormulaManipulator.GetTotalExactMass(mf2), 0.0000001); @@ -380,8 +380,8 @@ public void TestGetNaturalExactMass_IMolecularFormula() formula.Add(builder.NewIsotope("Cl")); double expectedMass = 0.0; - expectedMass += Isotopes.Instance.GetNaturalMass(builder.NewElement("C")); - expectedMass += Isotopes.Instance.GetNaturalMass(builder.NewElement("Cl")); + expectedMass += BODRIsotopeFactory.Instance.GetNaturalMass(builder.NewElement("C")); + expectedMass += BODRIsotopeFactory.Instance.GetNaturalMass(builder.NewElement("Cl")); double totalExactMass = MolecularFormulaManipulator.GetNaturalExactMass(formula); Assert.AreEqual(expectedMass, totalExactMass, 0.000001); @@ -406,8 +406,8 @@ public void TestGetMajorIsotopeMass_IMolecularFormula() formula.Add(builder.NewIsotope("H"), 4); double expectedMass = 0.0; - expectedMass += Isotopes.Instance.GetMajorIsotope("C").ExactMass.Value; - expectedMass += 4.0 * Isotopes.Instance.GetMajorIsotope("H").ExactMass.Value; + expectedMass += BODRIsotopeFactory.Instance.GetMajorIsotope("C").ExactMass.Value; + expectedMass += 4.0 * BODRIsotopeFactory.Instance.GetMajorIsotope("H").ExactMass.Value; double totalExactMass = MolecularFormulaManipulator.GetMajorIsotopeMass(formula); Assert.AreEqual(expectedMass, totalExactMass, 0.000001); @@ -780,7 +780,7 @@ public void TestGetAtomContainer_String_IChemObjectBuilder() { string mf = "C2H4"; IAtomContainer atomContainer = MolecularFormulaManipulator.GetAtomContainer(mf, - Default.ChemObjectBuilder.Instance); + ChemObjectBuilder.Instance); Assert.AreEqual(6, atomContainer.Atoms.Count); } @@ -797,9 +797,9 @@ public void TestGetAtomContainer_AddsAtomicNumbers() Assert.IsNotNull(ac.Atoms[0].AtomicNumber); foreach (var atom in ac.Atoms) { - if ("C".Equals(atom.Symbol)) + if (string.Equals("C", atom.Symbol, StringComparison.Ordinal)) Assert.AreEqual(6, atom.AtomicNumber.Value); - else if ("H".Equals(atom.Symbol)) + else if (string.Equals("H", atom.Symbol, StringComparison.Ordinal)) Assert.AreEqual(1, atom.AtomicNumber.Value); else Assert.Fail("Unexcepted element: " + atom.Symbol); @@ -950,7 +950,7 @@ public void TestGenerateOrderEle() // The "odd one out": an unspecified R-group "R"}; - string[] arrayGenerated = MolecularFormulaManipulator.OrderEle; + var arrayGenerated = MolecularFormulaManipulator.OrderEle; var listGenerated = arrayGenerated.ToList(); Assert.AreEqual(113, listGenerated.Count()); @@ -998,7 +998,7 @@ public void TestSingleAtomFromSmiles() // previously performed inside SmilesParser AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance).AddImplicitHydrogens(mol); + CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance).AddImplicitHydrogens(mol); IMolecularFormula mf = MolecularFormulaManipulator.GetMolecularFormula(mol); double exactMass = MolecularFormulaManipulator.GetTotalExactMass(mf); @@ -1164,7 +1164,7 @@ public void TestFromMol() IAtomContainer mol = mols[0]; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - CDKHydrogenAdder ha = CDKHydrogenAdder.GetInstance(Default.ChemObjectBuilder.Instance); + CDKHydrogenAdder ha = CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance); ha.AddImplicitHydrogens(mol); AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(mol); @@ -1249,7 +1249,7 @@ public void NoNullPointerExceptionForMajorMassOfRGroups() [TestMethod()] public void NoNullPointerForStaticIsotopes() { - Isotopes isotopes = Isotopes.Instance; + BODRIsotopeFactory isotopes = BODRIsotopeFactory.Instance; IIsotope carbon = isotopes.GetMajorIsotope("C"); MolecularFormula mf = new MolecularFormula(); mf.Add(carbon, 10); @@ -1333,12 +1333,12 @@ public void ProtonateDeuteratedPhenolate() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; IMolecularFormula mf = bldr.NewMolecularFormula(); // [C6DH4O]- (parser not good enough ATM so need to create like this) - IIsotope deuterium = Isotopes.Instance.GetIsotope("H", 2); - IIsotope hydrogen = Isotopes.Instance.GetMajorIsotope(1); + IIsotope deuterium = BODRIsotopeFactory.Instance.GetIsotope("H", 2); + IIsotope hydrogen = BODRIsotopeFactory.Instance.GetMajorIsotope(1); mf.Add(deuterium, 1); mf.Add(hydrogen, 4); - mf.Add(Isotopes.Instance.GetMajorIsotope(6), 6); - mf.Add(Isotopes.Instance.GetMajorIsotope(8), 1); + mf.Add(BODRIsotopeFactory.Instance.GetMajorIsotope(6), 6); + mf.Add(BODRIsotopeFactory.Instance.GetMajorIsotope(8), 1); mf.Charge = -1; Assert.IsTrue(MolecularFormulaManipulator.AdjustProtonation(mf, +1)); Assert.AreEqual("C6H6O", MolecularFormulaManipulator.GetString(mf)); diff --git a/NCDKTests/Tools/Manipulator/MoleculeSetManipulatorTest.cs b/NCDKTests/Tools/Manipulator/MoleculeSetManipulatorTest.cs index 8704fb7f..65ee3bc1 100644 --- a/NCDKTests/Tools/Manipulator/MoleculeSetManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/MoleculeSetManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using System.Linq; namespace NCDK.Tools.Manipulator diff --git a/NCDKTests/Tools/Manipulator/ReactionManipulatorTest.cs b/NCDKTests/Tools/Manipulator/ReactionManipulatorTest.cs index dcda3ed6..9b5ed2c3 100644 --- a/NCDKTests/Tools/Manipulator/ReactionManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/ReactionManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using NCDK.Smiles; using System.Linq; @@ -32,7 +32,7 @@ namespace NCDK.Tools.Manipulator public class ReactionManipulatorTest : CDKTestCase { private IReaction reaction; - private IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + private IChemObjectBuilder builder = ChemObjectBuilder.Instance; public ReactionManipulatorTest() : base() @@ -293,7 +293,7 @@ public void InliningReactionsWithRadicals() IChemObjectBuilder bldr = Silent.ChemObjectBuilder.Instance; SmilesParser smipar = new SmilesParser(bldr); IReaction reaction = smipar.ParseReactionSmiles("[CH2]CO.CC(=O)O>[H+]>CCOC(=O)C.O |^1:0| ethyl esterification"); - SmilesGenerator smigen = new SmilesGenerator(SmiFlavor.CxSmiles); + SmilesGenerator smigen = new SmilesGenerator(SmiFlavors.CxSmiles); // convert to molecule IAtomContainer mol = ReactionManipulator.ToMolecule(reaction); Assert.AreEqual("[CH2]CO.CC(=O)O.[H+].CCOC(=O)C.O |^1:0|", smigen.Create(mol)); diff --git a/NCDKTests/Tools/Manipulator/ReactionSchemeManipulatorTest.cs b/NCDKTests/Tools/Manipulator/ReactionSchemeManipulatorTest.cs index cf8b3d0d..976feac1 100644 --- a/NCDKTests/Tools/Manipulator/ReactionSchemeManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/ReactionSchemeManipulatorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; using System.Linq; namespace NCDK.Tools.Manipulator @@ -35,7 +36,7 @@ public ReactionSchemeManipulatorTest() [TestInitialize()] public void SetUp() { - builder = Default.ChemObjectBuilder.Instance; + builder = ChemObjectBuilder.Instance; } [TestMethod()] diff --git a/NCDKTests/Tools/Manipulator/ReactionSetManipulatorTest.cs b/NCDKTests/Tools/Manipulator/ReactionSetManipulatorTest.cs index 9547a2fc..a7205221 100644 --- a/NCDKTests/Tools/Manipulator/ReactionSetManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/ReactionSetManipulatorTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; using NCDK.IO; using System.Linq; @@ -38,7 +38,7 @@ public ReactionSetManipulatorTest() [TestInitialize()] public void SetUp() { - builder = Default.ChemObjectBuilder.Instance; + builder = ChemObjectBuilder.Instance; string filename1 = "NCDK.Data.MDL.reaction-1.rxn"; var ins1 = ResourceLoader.GetAsStream(filename1); MDLRXNReader reader1 = new MDLRXNReader(ins1); diff --git a/NCDKTests/Tools/Manipulator/RingManipulatorTest.cs b/NCDKTests/Tools/Manipulator/RingManipulatorTest.cs index 7d141f1a..ce2ba28f 100644 --- a/NCDKTests/Tools/Manipulator/RingManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/RingManipulatorTest.cs @@ -22,7 +22,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Tools.Manipulator { diff --git a/NCDKTests/Tools/Manipulator/RingSetManipulatorTest.cs b/NCDKTests/Tools/Manipulator/RingSetManipulatorTest.cs index e6ee6929..4ba9d341 100644 --- a/NCDKTests/Tools/Manipulator/RingSetManipulatorTest.cs +++ b/NCDKTests/Tools/Manipulator/RingSetManipulatorTest.cs @@ -24,6 +24,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; using NCDK.RingSearches; +using NCDK.Silent; using NCDK.Templates; using System.Collections.Generic; using System.Linq; @@ -47,7 +48,7 @@ public class RingSetManipulatorTest : CDKTestCase [TestInitialize()] public void SetUp() { - builder = Default.ChemObjectBuilder.Instance; + builder = ChemObjectBuilder.Instance; ringset = builder.NewRingSet(); ring1Atom1 = builder.NewAtom("C"); // rather artificial molecule IAtom ring1Atom2 = builder.NewAtom("C"); @@ -237,13 +238,13 @@ public void TestGetAllInOneContainer_IRingSet() } [TestMethod()] - public void TestGetLargestRingSet_List_IRingSet() + public void TestGetLargestRingSetListIRingSet() { - IList list = new List { ringset }; - IAtomContainer mol = TestMoleculeFactory.MakeBiphenyl(); + var list = new List { ringset }; + var mol = TestMoleculeFactory.MakeBiphenyl(); - AllRingsFinder arf = new AllRingsFinder(); - IRingSet ringSet = arf.FindAllRings(mol); + var arf = new AllRingsFinder(); + var ringSet = arf.FindAllRings(mol); list.Add(ringSet); Assert.AreEqual(2, RingSetManipulator.GetLargestRingSet(list).Count); } diff --git a/NCDKTests/Tools/Manipulator/RingSizeComparatorTest.cs b/NCDKTests/Tools/Manipulator/RingSizeComparatorTest.cs index 1d1a35e7..38d9ceef 100644 --- a/NCDKTests/Tools/Manipulator/RingSizeComparatorTest.cs +++ b/NCDKTests/Tools/Manipulator/RingSizeComparatorTest.cs @@ -18,6 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; +using NCDK.Silent; namespace NCDK.Tools.Manipulator { @@ -32,24 +33,24 @@ public RingSizeComparatorTest() [TestMethod()] public void TestRingSizeComparator_int() { - RingSizeComparator comp = new RingSizeComparator(RingSizeComparator.LARGE_FIRST); + RingSizeComparator comp = new RingSizeComparator(SortMode.LargeFirst); Assert.IsNotNull(comp); } [TestMethod()] public void TestCompare() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IRing cycloPentane = builder.NewRing(5, "C"); IRing cycloHexane = builder.NewRing(6, "C"); IRing cycloHexane2 = builder.NewRing(6, "C"); - RingSizeComparator ringSizeComparator = new RingSizeComparator(RingSizeComparator.LARGE_FIRST); + RingSizeComparator ringSizeComparator = new RingSizeComparator(SortMode.LargeFirst); Assert.IsTrue(ringSizeComparator.Compare(cycloHexane, cycloPentane) == -1); Assert.IsTrue(ringSizeComparator.Compare(cycloPentane, cycloHexane) == 1); Assert.IsTrue(ringSizeComparator.Compare(cycloHexane, cycloHexane2) == 0); - ringSizeComparator = new RingSizeComparator(RingSizeComparator.SMALL_FIRST); + ringSizeComparator = new RingSizeComparator(SortMode.SmallFirst); Assert.IsTrue(ringSizeComparator.Compare(cycloHexane, cycloPentane) == 1); Assert.IsTrue(ringSizeComparator.Compare(cycloPentane, cycloHexane) == -1); Assert.IsTrue(ringSizeComparator.Compare(cycloHexane, cycloHexane2) == 0); diff --git a/NCDKTests/Tools/SaturationCheckerTest.cs b/NCDKTests/Tools/SaturationCheckerTest.cs index 629c21fd..7bd5d5ff 100644 --- a/NCDKTests/Tools/SaturationCheckerTest.cs +++ b/NCDKTests/Tools/SaturationCheckerTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Tools { @@ -384,7 +384,7 @@ public void TestBug777529() [TestMethod()] public void TestCalculateNumberOfImplicitHydrogens() { - IChemObjectBuilder builder = Default.ChemObjectBuilder.Instance; + IChemObjectBuilder builder = ChemObjectBuilder.Instance; IAtomContainer proton = builder.NewAtomContainer(); IAtom hplus = builder.NewAtom("H"); diff --git a/NCDKTests/Tools/StructureResonanceGeneratorTest.cs b/NCDKTests/Tools/StructureResonanceGeneratorTest.cs index fc6a431c..03f8f186 100644 --- a/NCDKTests/Tools/StructureResonanceGeneratorTest.cs +++ b/NCDKTests/Tools/StructureResonanceGeneratorTest.cs @@ -19,7 +19,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Aromaticities; -using NCDK.Default; +using NCDK.Silent; using NCDK.Isomorphisms; using NCDK.Isomorphisms.Matchers; using NCDK.Reactions; @@ -28,6 +28,7 @@ using NCDK.Templates; using NCDK.Tools.Manipulator; using System.Collections.Generic; +using System.Linq; namespace NCDK.Tools { @@ -36,7 +37,6 @@ namespace NCDK.Tools public class StructureResonanceGeneratorTest : CDKTestCase { private readonly static IChemObjectBuilder builder = Silent.ChemObjectBuilder.Instance; - LonePairElectronChecker lpcheck = new LonePairElectronChecker(); /// /// Constructor of the StructureResonanceGeneratorTest. @@ -152,11 +152,10 @@ public void TestSetReactions_List() // /// The test suite // /// // [TestMethod()] public void TestGetAllStructures_IAtomContainer() { - // IAtomContainer molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); + // IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); // AddExplicitHydrogens(molecule); // AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(molecule); + // LonePairElectronChecker.Saturate(molecule); // // IAtom atom = molecule.Atoms[2]; // molecule.SingleElectrons.Add(new SingleElectron(atom)); @@ -181,14 +180,14 @@ public void TestSetReactions_List() // Assert.AreEqual(8,setOfMolecules.Count); // // /*1*/ - // IAtomContainer molecule1 = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("C[C+](O)C=O"); + // IAtomContainer molecule1 = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("C[C+](O)C=O"); // For(int i = 0; i < 4; i++) // molecule1.Atoms.Add(new Atom("H")); // molecule1.AddBond(molecule1.Atoms[0], molecule1.Atoms[5], BondOrder.Single); // molecule1.AddBond(molecule1.Atoms[0], molecule1.Atoms[6], BondOrder.Single); // molecule1.AddBond(molecule1.Atoms[0], molecule1.Atoms[7], BondOrder.Single); // molecule1.AddBond(molecule1.Atoms[3], molecule1.Atoms[8], BondOrder.Single); - // lpcheck.Saturate(molecule1); + // LonePairElectronChecker.Saturate(molecule1); // IAtom atom1 = molecule1.Atoms[2]; // molecule1.SingleElectrons.Add(new SingleElectron(atom1)); // QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); @@ -202,7 +201,7 @@ public void TestSetReactions_List() //// molecule2.AddBond(molecule2.Atoms[0], molecule2.Atoms[6], BondOrder.Single); //// molecule2.AddBond(molecule2.Atoms[0], molecule2.Atoms[7], BondOrder.Single); //// molecule2.AddBond(molecule2.Atoms[3], molecule2.Atoms[8], BondOrder.Single); - //// lpcheck.NewSaturate(molecule2); + //// LonePairElectronChecker.NewSaturate(molecule2); //// IAtom atom2a = molecule2.Atoms[2]; //// molecule2.AddElectronContainer(new SingleElectron(atom2a)); //// @@ -232,11 +231,10 @@ public void TestSetReactions_List() // /// The test suite // /// // [TestMethod()] public void TestGetStructures_IAtomContainer() { - // IAtomContainer molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); + // IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); // AddExplicitHydrogens(molecule); // AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(molecule); + // LonePairElectronChecker.Saturate(molecule); // // IAtom atom = molecule.Atoms[2]; // molecule.SingleElectrons.Add(new SingleElectron(atom)); @@ -250,9 +248,9 @@ public void TestSetReactions_List() // // Assert.AreEqual(2,setOfMolecules.Count); // - // IAtomContainer molecule1 = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); + // IAtomContainer molecule1 = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); // AddExplicitHydrogens(molecule1); - // lpcheck.Saturate(molecule1); + // LonePairElectronChecker.Saturate(molecule1); // IAtom atom1 = molecule1.Atoms[4]; // molecule1.SingleElectrons.Add(new SingleElectron(atom1)); // selectron = molecule1.GetConnectedLonePairsList(atom1); @@ -270,11 +268,10 @@ public void TestSetReactions_List() // /// The test suite // /// // [TestMethod()] public void TestGetStructures2() { - // IAtomContainer molecule = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CCC(=O)C(C)=O"); + // IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CCC(=O)C(C)=O"); // AddExplicitHydrogens(molecule); // AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - // LonePairElectronChecker lpcheck = new LonePairElectronChecker(); - // lpcheck.Saturate(molecule); + // LonePairElectronChecker.Saturate(molecule); // // IAtom atom = molecule.Atoms[3]; // molecule.SingleElectrons.Add(new SingleElectron(atom)); @@ -288,9 +285,9 @@ public void TestSetReactions_List() // // Assert.AreEqual(2,setOfMolecules.Count); // - // IAtomContainer molecule1 = (new SmilesParser(Default.ChemObjectBuilder.Instance)).ParseSmiles("CCC(=O)C(C)=O"); + // IAtomContainer molecule1 = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CCC(=O)C(C)=O"); // AddExplicitHydrogens(molecule1); - // lpcheck.Saturate(molecule1); + // LonePairElectronChecker.Saturate(molecule1); // // IAtom atom1 = molecule1.Atoms[6]; // molecule1.SingleElectrons.Add(new SingleElectron(atom1)); @@ -462,10 +459,10 @@ public void TestFormicAcid() molecule.AddBond(molecule.Atoms[0], molecule.Atoms[2], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gR = new StructureResonanceGenerator(); - var reactionList = gR.Reactions; + var reactionList = gR.Reactions.ToList(); reactionList.Add(new HeterolyticCleavagePBReaction()); gR.Reactions = reactionList; var setOfMolecules = gR.GetStructures(molecule); @@ -482,7 +479,7 @@ public void TestFormicAcid() molecule2.AddBond(molecule2.Atoms[0], molecule2.Atoms[2], BondOrder.Double); AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - lpcheck.Saturate(molecule2); + LonePairElectronChecker.Saturate(molecule2); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule2); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[1], qAC)); @@ -503,7 +500,7 @@ public void TestFluoroethene() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Double); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gR = new StructureResonanceGenerator(); var setOfMolecules = gR.GetStructures(molecule); @@ -520,7 +517,7 @@ public void TestFluoroethene() molecule1.Atoms[2].FormalCharge = -1; AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - lpcheck.Saturate(molecule1); + LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[1], qAC)); @@ -552,7 +549,7 @@ public void TestFluorobenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -578,7 +575,7 @@ public void TestFluorobenzene() molecule1.AddBond(molecule1.Atoms[6], molecule1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - lpcheck.Saturate(molecule1); + LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[2], qAC)); @@ -602,7 +599,7 @@ public void TestFluorobenzene() molecule2.AddBond(molecule2.Atoms[6], molecule2.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - lpcheck.Saturate(molecule2); + LonePairElectronChecker.Saturate(molecule2); IAtomContainer product2 = setOfMolecules[4]; qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule2); @@ -635,7 +632,7 @@ public void TestFluorobenzeneContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); IAtomContainer container = gRI.GetContainer(molecule, molecule.Atoms[0]); @@ -669,7 +666,7 @@ public void TestFluorobenzene_symm() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(true); var setOfMolecules = gRI.GetStructures(molecule); @@ -695,7 +692,7 @@ public void TestFluorobenzene_symm() molecule1.AddBond(molecule1.Atoms[6], molecule1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - lpcheck.Saturate(molecule1); + LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[1], qAC)); @@ -719,7 +716,7 @@ public void TestFluorobenzene_symm() molecule2.AddBond(molecule2.Atoms[6], molecule2.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - lpcheck.Saturate(molecule2); + LonePairElectronChecker.Saturate(molecule2); IAtomContainer product2 = setOfMolecules[2]; qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule2); @@ -752,7 +749,7 @@ public void TestAniline() molecule.AddBond(molecule.Atoms[6], molecule.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -784,7 +781,7 @@ public void TestAniline_Symm() molecule.AddBond(molecule.Atoms[6], molecule.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(true); var setOfMolecules = gRI.GetStructures(molecule); @@ -812,7 +809,7 @@ public void TestAllyl() AddExplicitHydrogens(molecule); Assert.AreEqual(8, molecule.Atoms.Count); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var resonanceStructures = gRI.GetStructures(molecule); @@ -861,7 +858,7 @@ public void TestEthenolate() molecule.Atoms[0].FormalCharge = -1; AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(6, molecule.Atoms.Count); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); @@ -899,7 +896,7 @@ public void Test2Methylaniline() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[7], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(17, molecule.Atoms.Count); @@ -933,8 +930,7 @@ public void Test12DimethylBenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker lpChecker = new LonePairElectronChecker(); - lpChecker.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(18, molecule.Atoms.Count); @@ -976,7 +972,7 @@ public void TestPreservingAromaticity() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); bool isAromatic = Aromaticity.CDKLegacy.Apply(molecule); Assert.IsTrue(isAromatic, "Molecule is expected to be marked aromatic!"); @@ -1023,7 +1019,7 @@ public void TestCyclobutadiene() IAtomContainer molecule = TestMoleculeFactory.MakeCyclobutadiene(); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -1039,7 +1035,7 @@ public void TestBenzene() IAtomContainer molecule = TestMoleculeFactory.MakeBenzene(); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -1064,7 +1060,7 @@ public void TestGetContainers_IAtomContainer() molecule.Atoms[0].FormalCharge = -1; AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(6, molecule.Atoms.Count); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); @@ -1108,7 +1104,7 @@ public void TestGetContainers2Groups() molecule.Atoms[7].FormalCharge = +1; AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); var setOfContainers = sRG.GetContainers(molecule); @@ -1158,7 +1154,7 @@ public void TestGetContainer_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); IAtomContainer container = sRG.GetContainer(molecule, atom4); @@ -1205,7 +1201,7 @@ public void TestGetContainer_IAtomContainer_IBond() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); IAtomContainer container = sRG.GetContainer(molecule, molecule.Bonds[1]); @@ -1259,7 +1255,7 @@ public void TestGetID() molecule.AddBond(molecule.Atoms[6], molecule.Atoms[7], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); IAtomContainer container = sRG.GetContainer(molecule, atom4); @@ -1301,7 +1297,7 @@ public void TestGetContainersFluoromethylbenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1343,7 +1339,7 @@ public void TestGetContainersFluorobenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1377,7 +1373,7 @@ public void Test1Propene2chloro() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1414,7 +1410,7 @@ public void TestBenzene1bromo4methoxy() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1452,7 +1448,7 @@ public void TestBenzene1bromo4methoxy_with() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1506,7 +1502,7 @@ public void TestBenzylamine() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1543,7 +1539,7 @@ public void TestBenzylamine_Aromatic() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.IsTrue(Aromaticity.CDKLegacy.Apply(molecule)); @@ -1582,7 +1578,7 @@ public void TestBenzylamine_Aromatic_lookingSymmetry() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - lpcheck.Saturate(molecule); + LonePairElectronChecker.Saturate(molecule); Assert.IsTrue(Aromaticity.CDKLegacy.Apply(molecule)); diff --git a/NCDKTests/Validate/Geometry3DValidatorTest.cs b/NCDKTests/Validate/Geometry3DValidatorTest.cs index 157f502c..db0bd545 100644 --- a/NCDKTests/Validate/Geometry3DValidatorTest.cs +++ b/NCDKTests/Validate/Geometry3DValidatorTest.cs @@ -18,8 +18,8 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; using NCDK.IO; +using NCDK.Silent; namespace NCDK.Validate { diff --git a/NCDKTests/Validate/ProblemMarkerTest.cs b/NCDKTests/Validate/ProblemMarkerTest.cs index 62175c9e..fd5410a9 100644 --- a/NCDKTests/Validate/ProblemMarkerTest.cs +++ b/NCDKTests/Validate/ProblemMarkerTest.cs @@ -18,7 +18,7 @@ */ using Microsoft.VisualStudio.TestTools.UnitTesting; -using NCDK.Default; +using NCDK.Silent; namespace NCDK.Validate { @@ -37,7 +37,7 @@ public void TestUnMarkWithError_IChemObject() Assert.IsNull(obj.GetProperty(ProblemMarker.ErrorMarker)); ProblemMarker.MarkWithError(obj); Assert.IsNotNull(obj.GetProperty(ProblemMarker.ErrorMarker)); - ProblemMarker.UnMarkWithError(obj); + ProblemMarker.UnmarkWithError(obj); Assert.IsNull(obj.GetProperty(ProblemMarker.ErrorMarker)); } @@ -48,7 +48,7 @@ public void TestUnMarkWithWarning_IChemObject() Assert.IsNull(obj.GetProperty(ProblemMarker.WarningMarker)); ProblemMarker.MarkWithWarning(obj); Assert.IsNotNull(obj.GetProperty(ProblemMarker.WarningMarker)); - ProblemMarker.UnMarkWithWarning(obj); + ProblemMarker.UnmarkWithWarning(obj); Assert.IsNull(obj.GetProperty(ProblemMarker.WarningMarker)); } diff --git a/README.md b/README.md index 3c9fd56b..d5ccd0ca 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -NCDK: The Chemistry Development Kit ported to C +NCDK: The Chemistry Development Kit ported to C# =============================================== NCDK is .NET port of [the Chemistry Development Project (CDK)](https://github.com/cdk/cdk). Functionality is provided for many areas in cheminformatics. @@ -23,12 +23,14 @@ Build ----- Windows: Open Developer Command Prompt for VS 2017, and launch "BuildAll.bat". Of course, you can build with Visual Studio 2017. Open NCDKDisplay.sln and build it. + Linux (.NET Core): To build NCDK.dll, launch "dotnet build --framework netstandard2.0" in NCDK directory. Test ---- Windows: Launch "vstest.console.exe NCDKTests\bin\Release\netcoreapp2.1\NCDKTests.dll" and "vstest.console.exe NCDKDisplayTests\bin\Release\NCDKDisplayTests.dll". + Linux: Copy libinchi.so.#.## to output directory of NCDKTests, and make a libinchi.so link to it and launch "dotnet test" in NCDKTests directory. NuGet Packages From c5a118a6c0390e8a09a8516b8de6e25aa5a84ae1 Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Mon, 27 Aug 2018 12:56:41 +0900 Subject: [PATCH 2/8] Update versions --- BuildAll.bat | 1 + NCDK/NCDK.csproj | 7 +-- NCDK/NCDK.nuspec | 2 +- NCDK/NCDK.ruleset | 78 --------------------------------- NCDKDisplay/NCDK.Display.nuspec | 10 +++-- 5 files changed, 9 insertions(+), 89 deletions(-) delete mode 100644 NCDK/NCDK.ruleset diff --git a/BuildAll.bat b/BuildAll.bat index 0ea72a51..c4e12bc7 100644 --- a/BuildAll.bat +++ b/BuildAll.bat @@ -1,6 +1,7 @@ pushd NCDK dotnet add package MathNet.Numerics.Signed dotnet add package dotNetRDF +dotnet restore call :BuildProject NCDK popd diff --git a/NCDK/NCDK.csproj b/NCDK/NCDK.csproj index fdd515e5..f427b4ea 100644 --- a/NCDK/NCDK.csproj +++ b/NCDK/NCDK.csproj @@ -1,7 +1,7 @@ - net461 + net461;netstandard2.0 NCDK true ncdk.snk @@ -36,17 +36,12 @@ bin\Release\net461\NCDK.xml - NCDK.ruleset bin\Release\netstandard2.0\NCDK.xml - - NCDK.ruleset - - diff --git a/NCDK/NCDK.nuspec b/NCDK/NCDK.nuspec index f3a7dd0d..b6f413a0 100644 --- a/NCDK/NCDK.nuspec +++ b/NCDK/NCDK.nuspec @@ -2,7 +2,7 @@ NCDK - 1.3.1-alpha + 1.4.0-alpha NCDK: library of algorithms for structural cheminformatics Kazuya Ujihara kazuya diff --git a/NCDK/NCDK.ruleset b/NCDK/NCDK.ruleset deleted file mode 100644 index 78a4fced..00000000 --- a/NCDK/NCDK.ruleset +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/NCDKDisplay/NCDK.Display.nuspec b/NCDKDisplay/NCDK.Display.nuspec index c08bfad3..b5770058 100644 --- a/NCDKDisplay/NCDK.Display.nuspec +++ b/NCDKDisplay/NCDK.Display.nuspec @@ -1,8 +1,10 @@ - + NCDK.Display - 1.3.1-alpha + 1.4.0-alpha NCDK.Display: Depiction module of NCDK Kazuya Ujihara kazuya @@ -13,14 +15,14 @@ This release is based on https://github.com/cdk/cdk/tree/6fade7b5470669955835046d9fb09c48f658efde snapshot. Copyright © 2016-2018 Kazuya Ujihara cdk cheminformatics chemistry toolkit - + - + From 46662f90fc24a0a843f8a71d13ab449a1d60a624 Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Tue, 28 Aug 2018 00:14:31 +0900 Subject: [PATCH 3/8] Fix target of NCDKTests --- NCDKTests/NCDKTests.csproj | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NCDKTests/NCDKTests.csproj b/NCDKTests/NCDKTests.csproj index 29af09cc..8738c24c 100644 --- a/NCDKTests/NCDKTests.csproj +++ b/NCDKTests/NCDKTests.csproj @@ -1,6 +1,6 @@ - net461 + netcoreapp2.1 false Kazuya Ujihara NCDK diff --git a/README.md b/README.md index d5ccd0ca..3cfca698 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Test Windows: Launch "vstest.console.exe NCDKTests\bin\Release\netcoreapp2.1\NCDKTests.dll" and "vstest.console.exe NCDKDisplayTests\bin\Release\NCDKDisplayTests.dll". -Linux: Copy libinchi.so.#.## to output directory of NCDKTests, and make a libinchi.so link to it and launch "dotnet test" in NCDKTests directory. +Linux: Launch "dotnet build" and copy libinchi.so.#.## to output directory of NCDKTests, and make a libinchi.so link to it and launch "dotnet test" in NCDKTests directory. NuGet Packages -------------- From 023b813cdd93cddc452805d1ed1dca8a82b3333c Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Mon, 17 Sep 2018 22:37:42 +0900 Subject: [PATCH 4/8] Correct API call. --- NCDK/Isomorphisms/Pattern.cs | 2 +- NCDK/NCDK.csproj | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/NCDK/Isomorphisms/Pattern.cs b/NCDK/Isomorphisms/Pattern.cs index 2a177493..c5ff32ae 100644 --- a/NCDK/Isomorphisms/Pattern.cs +++ b/NCDK/Isomorphisms/Pattern.cs @@ -150,7 +150,7 @@ public static Pattern FindSubstructure(IAtomContainer query) /// public static Pattern FindIdentical(IAtomContainer query) { - return VentoFoggia.FindSubstructure(query); + return VentoFoggia.FindIdentical(query); } } } \ No newline at end of file diff --git a/NCDK/NCDK.csproj b/NCDK/NCDK.csproj index f427b4ea..1ca176b3 100644 --- a/NCDK/NCDK.csproj +++ b/NCDK/NCDK.csproj @@ -18,8 +18,7 @@ https://github.com/kazuyaujihara/NCDK git cdk cheminformatics chemistry toolkit - This release is based on https://github.com/cdk/cdk/tree/6fade7b5470669955835046d9fb09c48f658efde snapshot. - + This release is based on https://github.com/cdk/cdk/tree/6fade7b5470669955835046d9fb09c48f658efde snapshot. false NCDK From 3fe8d5b591537a63d16da5d43446e5846a665b2b Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Sat, 22 Sep 2018 17:39:41 +0900 Subject: [PATCH 5/8] Refactor --- NCDK/IO/InChIPlainTextReader.cs | 6 +- NCDK/IO/InChIReader.cs | 3 +- NCDK/QSAR/DescriptorValue.cs | 2 +- .../Descriptors/Moleculars/ALOGPDescriptor.cs | 71 +++++++-------- .../Descriptors/Moleculars/APolDescriptor.cs | 13 +-- .../Moleculars/AcidicGroupCountDescriptor.cs | 10 +-- .../Moleculars/AminoAcidCountDescriptor.cs | 24 ++--- .../AromaticAtomsCountDescriptor.cs | 23 ++--- .../AromaticBondsCountDescriptor.cs | 4 +- .../Moleculars/AtomCountDescriptor.cs | 17 +--- .../Descriptors/Moleculars/BCUTDescriptor.cs | 36 ++++---- .../Descriptors/Moleculars/BPolDescriptor.cs | 29 ++---- .../Moleculars/BasicGroupCountDescriptor.cs | 7 +- .../Moleculars/BondCountDescriptor.cs | 16 +--- .../Descriptors/Moleculars/CPSADescriptor.cs | 21 ++--- .../Moleculars/CarbonTypesDescriptor.cs | 12 --- .../Moleculars/ChiChainDescriptor.cs | 25 +++--- .../Moleculars/ChiClusterDescriptor.cs | 21 +++-- .../Descriptors/Moleculars/ChiIndexUtils.cs | 59 ++++++------ .../Moleculars/ChiPathClusterDescriptor.cs | 21 +++-- .../Moleculars/ChiPathDescriptor.cs | 34 +++---- .../EccentricConnectivityIndexDescriptor.cs | 38 +++----- .../Descriptors/Moleculars/FMFDescriptor.cs | 13 +-- .../Moleculars/FractionalPSADescriptor.cs | 8 +- .../FragmentComplexityDescriptor.cs | 24 ++--- .../GravitationalIndexDescriptor.cs | 90 ++++++++----------- .../HBondAcceptorCountDescriptor.cs | 20 +---- .../Moleculars/HBondDonorCountDescriptor.cs | 15 +--- .../HybridizationRatioDescriptor.cs | 19 ++-- .../Moleculars/KappaShapeIndicesDescriptor.cs | 14 --- .../Moleculars/KierHallSmartsDescriptor.cs | 14 --- .../Moleculars/LargestChainDescriptor.cs | 26 ++---- .../Moleculars/LargestPiSystemDescriptor.cs | 22 ++--- .../Moleculars/LengthOverBreadthDescriptor.cs | 23 +---- .../LongestAliphaticChainDescriptor.cs | 32 +++---- .../Descriptors/Moleculars/MDEDescriptor.cs | 17 +--- .../Moleculars/MannholdLogPDescriptor.cs | 6 +- .../Moleculars/MomentOfInertiaDescriptor.cs | 20 +---- .../Moleculars/PetitjeanNumberDescriptor.cs | 32 ++----- .../PetitjeanShapeIndexDescriptor.cs | 2 +- .../RotatableBondsCountDescriptor.cs | 29 ++---- .../Moleculars/RuleOfFiveDescriptor.cs | 24 ++--- .../Moleculars/SmallRingDescriptor.cs | 24 ----- .../Descriptors/Moleculars/TPSADescriptor.cs | 22 ++--- .../Descriptors/Moleculars/VABCDescriptor.cs | 2 +- .../Moleculars/VAdjMaDescriptor.cs | 23 ++--- .../Descriptors/Moleculars/WHIMDescriptor.cs | 18 +--- .../Moleculars/WeightDescriptor.cs | 29 +++--- .../Moleculars/WeightedPathDescriptor.cs | 15 +--- .../Moleculars/WienerNumbersDescriptor.cs | 21 ++--- .../Descriptors/Moleculars/XLogPDescriptor.cs | 12 +-- .../Moleculars/ZagrebIndexDescriptor.cs | 19 +--- NCDK/QSAR/IDescriptor.cs | 2 +- NCDKTests/IO/InChIPlainTextReaderTest.cs | 3 +- NCDKTests/IO/InChIReaderTest.cs | 3 +- .../Moleculars/ALOGPDescriptorTest.cs | 9 +- 56 files changed, 366 insertions(+), 778 deletions(-) diff --git a/NCDK/IO/InChIPlainTextReader.cs b/NCDK/IO/InChIPlainTextReader.cs index f9c6d83a..7ce262a7 100644 --- a/NCDK/IO/InChIPlainTextReader.cs +++ b/NCDK/IO/InChIPlainTextReader.cs @@ -128,9 +128,9 @@ private IChemFile ReadChemFile(IChemFile cf) var moleculeSet = cf.Builder.NewAtomContainerSet(); moleculeSet.Add(cf.Builder.NewAtomContainer(parsedContent)); - IChemModel model = cf.Builder.NewChemModel(); + var model = cf.Builder.NewChemModel(); model.MoleculeSet = moleculeSet; - IChemSequence sequence = cf.Builder.NewChemSequence(); + var sequence = cf.Builder.NewChemSequence(); sequence.Add(model); cf.Add(sequence); } @@ -141,7 +141,7 @@ private IChemFile ReadChemFile(IChemFile cf) if (exception is IOException || exception is ArgumentException) { Console.Error.WriteLine(exception.StackTrace); - throw new CDKException("Error while reading INChI file: " + exception.Message, exception); + throw new CDKException($"Error while reading INChI file: {exception.Message}", exception); } else throw; diff --git a/NCDK/IO/InChIReader.cs b/NCDK/IO/InChIReader.cs index 6424be3e..d01b9297 100644 --- a/NCDK/IO/InChIReader.cs +++ b/NCDK/IO/InChIReader.cs @@ -65,7 +65,8 @@ public InChIReader(Stream input) public override bool Accepts(Type type) { - if (typeof(IChemFile).IsAssignableFrom(type)) return true; + if (typeof(IChemFile).IsAssignableFrom(type)) + return true; return false; } diff --git a/NCDK/QSAR/DescriptorValue.cs b/NCDK/QSAR/DescriptorValue.cs index a3ac33c5..d820f850 100644 --- a/NCDK/QSAR/DescriptorValue.cs +++ b/NCDK/QSAR/DescriptorValue.cs @@ -110,7 +110,7 @@ public DescriptorValue(DescriptorSpecification specification, IReadOnlyList /// - /// Note that by default if a descriptor returns a single value (such as + /// Note that by default if a descriptor returns a single value (such as /// the return array will have a single element /// /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs index 9aa73b61..18f45ab8 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ALOGPDescriptor.cs @@ -71,7 +71,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.keyword lipophilicity // @cdk.keyword refractivity // @see org.openscience.cdk.tools.CDKHydrogenAdder - public class ALOGPDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor + public class ALogPDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { IAtomContainer atomContainer; IRingSet rs; @@ -105,7 +105,7 @@ public class ALOGPDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor /// readonly static double[] REFRACVAL = new double[121]; - static ALOGPDescriptor() + static ALogPDescriptor() { // fragments for ALOGP from Ghose et al., 1998 FRAGVAL[1] = -1.5603; @@ -359,7 +359,7 @@ static ALOGPDescriptor() double alogp2 = 0.0; private static readonly string[] STRINGS = new string[] { "ALogP", "ALogp2", "AMR" }; - public ALOGPDescriptor() + public ALogPDescriptor() { try { @@ -400,7 +400,6 @@ private double[] Calculate(IAtomContainer atomContainer, string[] fragment, IRin for (int i = 0; i <= atomContainer.Atoms.Count - 1; i++) { - alogpfrag[i] = 0; try { @@ -449,7 +448,7 @@ private double[] Calculate(IAtomContainer atomContainer, string[] fragment, IRin amr += REFRACVAL[i] * frags[i]; if (frags[i] > 0) { - Debug.WriteLine("frag " + i + " --> " + frags[i]); + Debug.WriteLine($"frag {i} --> {frags[i]}"); } } alogp2 = alogp * alogp; @@ -660,25 +659,25 @@ private void CalcGroup016_018_036_037(int i) if (string.Equals(a.Symbol, "H", StringComparison.Ordinal)) continue; - if (atomContainer.GetBond(ai, a).Order == BondOrder.Single) + switch (atomContainer.GetBond(ai, a).Order) { - if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) - { - haveCsX = true; - } - - if (a.IsAromatic) - { - haveCsAr = true; - } + case BondOrder.Single: + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) + { + haveCsX = true; + } - } - else if (atomContainer.GetBond(ai, a).Order == BondOrder.Double) - { - if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) - { - haveCdX = true; - } + if (a.IsAromatic) + { + haveCsAr = true; + } + break; + case BondOrder.Double: + if (!string.Equals(a.Symbol, "C", StringComparison.Ordinal)) + { + haveCdX = true; + } + break; } } @@ -2303,12 +2302,12 @@ private static bool InSameAromaticRing(IAtomContainer atomContainer, IAtom atom1 /// /// The AlogP descriptor. - /// - /// TODO Ideally we should explicit H addition should be cached - /// + /// + /// + /// TODO: Ideally we should explicit H addition should be cached + /// /// the molecule to calculate on /// the result of the calculation - /// public DescriptorValue> Calculate(IAtomContainer atomContainer) { IAtomContainer container; @@ -2316,7 +2315,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain { container = (IAtomContainer)atomContainer.Clone(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - CDKHydrogenAdder hAdder = CDKHydrogenAdder.GetInstance(container.Builder); + var hAdder = CDKHydrogenAdder.GetInstance(container.Builder); hAdder.AddImplicitHydrogens(container); AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(container); } @@ -2336,15 +2335,12 @@ public DescriptorValue> Calculate(IAtomContainer atomContain return GetDummyDescriptorValue(new CDKException("Could not find all rings: " + e.Message)); } - string[] fragment = new string[container.Atoms.Count]; - EStateAtomTypeMatcher eStateMatcher = new EStateAtomTypeMatcher - { - RingSet = rs - }; + var fragment = new string[container.Atoms.Count]; + EStateAtomTypeMatcher eStateMatcher = new EStateAtomTypeMatcher { RingSet = rs }; for (int i = 0; i < container.Atoms.Count; i++) { - IAtomType atomType = eStateMatcher.FindMatchingAtomType(container, container.Atoms[i]); + var atomType = eStateMatcher.FindMatchingAtomType(container, container.Atoms[i]); if (atomType == null) { fragment[i] = null; @@ -2365,12 +2361,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain return GetDummyDescriptorValue(new CDKException(e.Message)); } - ArrayResult results = new ArrayResult - { - ret[0], - ret[1], - ret[2] - }; + ArrayResult results = new ArrayResult(ret); return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames); } @@ -2394,7 +2385,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = new DescriptorSpecification("http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#ALOGP", - typeof(ALOGPDescriptor).FullName, "The Chemistry Development Kit"); + typeof(ALogPDescriptor).FullName, "The Chemistry Development Kit"); public override IReadOnlyList ParameterNames => Array.Empty(); diff --git a/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs index ebaba60f..d085c2c4 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/APolDescriptor.cs @@ -57,20 +57,18 @@ public class APolDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor private static double[] polarizabilities; private static readonly string[] NAMES = { "apol" }; - /// - /// Constructor for the APolDescriptor object. - /// public APolDescriptor() { if (polarizabilities == null) { - polarizabilities = new double[]{0, 0.666793, 0.204956, 24.3, 5.6, 3.03, 1.76, 1.1, 0.802, 0.557, 0.3956, + polarizabilities = new double[] { + 0, 0.666793, 0.204956, 24.3, 5.6, 3.03, 1.76, 1.1, 0.802, 0.557, 0.3956, 23.6, 10.6, 6.8, 5.38, 3.63, 2.9, 2.18, 1.6411, 43.4, 22.8, 17.8, 14.6, 12.4, 11.6, 9.4, 8.4, 7.5, 6.8, 6.1, 7.1, 8.12, 6.07, 4.31, 3.77, 3.05, 2.4844, 47.3, 27.6, 22.7, 17.9, 15.7, 12.8, 11.4, 9.6, 8.6, 4.8, 7.2, 7.2, 10.2, 7.7, 6.6, 5.5, 5.35, 4.044, 59.6, 39.7, 31.1, 29.6, 28.2, 31.4, 30.1, 28.8, 27.7, 23.5, 25.5, 24.5, 23.6, 22.7, 21.8, 21, 21.9, 16.2, 13.1, 11.1, 9.7, 8.5, 7.6, 6.5, 5.8, 5.7, 7.6, 6.8, 7.4, 6.8, 6, 5.3, 48.7, 38.3, 32.1, 32.1, 25.4, 27.4, 24.8, 24.5, 23.3, 23, - 22.7, 20.5, 19.7, 23.8, 18.2, 17.5}; + 22.7, 20.5, 19.7, 23.8, 18.2, 17.5 }; } } @@ -80,9 +78,6 @@ public APolDescriptor() new DescriptorSpecification("http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#apol", typeof(APolDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the APolDescriptor object. - /// public override IReadOnlyList Parameters { get { return null; } @@ -105,7 +100,7 @@ public DescriptorValue> Calculate(IAtomContainer container) int atomicNumber; try { - IsotopeFactory ifac = BODRIsotopeFactory.Instance; + var ifac = BODRIsotopeFactory.Instance; IElement element; string symbol; foreach (var atom in container.Atoms) diff --git a/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs index d9e93cd8..736f6634 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AcidicGroupCountDescriptor.cs @@ -54,9 +54,6 @@ public class AcidicGroupCountDescriptor private static readonly List tools = new List(); private bool checkAromaticity; - /// - /// Creates a new . - /// public AcidicGroupCountDescriptor() { this.checkAromaticity = true; @@ -83,11 +80,11 @@ public override IReadOnlyList Parameters { if (value.Count != 1) { - throw new CDKException("AcidicGroupCountDescriptor requires 1 parameter."); + throw new CDKException(nameof(AcidicGroupCountDescriptor) + " requires 1 parameter."); } if (!(value[0] is bool)) { - throw new CDKException("The parameter must be of type bool"); + throw new CDKException("The parameter must be of type " + nameof(System.Boolean)); } // OK, all should be fine @@ -124,7 +121,8 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) int count = 0; foreach (var tool in tools) { - if (tool.Matches(atomContainer)) count += tool.MatchesCount; + if (tool.Matches(atomContainer)) + count += tool.MatchesCount; } return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(count), DescriptorNames); } diff --git a/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs index 81643579..d8023b88 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AminoAcidCountDescriptor.cs @@ -17,10 +17,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Templates; -using NCDK.QSAR.Results; using NCDK.Isomorphisms; using NCDK.Isomorphisms.MCSS; +using NCDK.QSAR.Results; +using NCDK.Templates; using System.Collections.Generic; using System.Linq; @@ -39,7 +39,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars /// Returns 20 values with names of the form nX, where X is the short versio /// of the amino acid name /// - /// + /// // @author egonw // @cdk.created 2006-01-15 // @cdk.module qsarprotein @@ -51,9 +51,6 @@ public class AminoAcidCountDescriptor : AbstractMolecularDescriptor, IMolecularD private static string[] names; - /// - /// Constructor for the AromaticAtomsCountDescriptor object. - /// public AminoAcidCountDescriptor() { var aas = AminoAcids.Proteinogenics; @@ -76,10 +73,6 @@ public AminoAcidCountDescriptor() typeof(AminoAcidCountDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the object. - /// - /// if more than one parameter or a non-bool parameter is specified public override IReadOnlyList Parameters { get { return null; } @@ -127,13 +120,13 @@ public DescriptorValue> Calculate(IAtomContainer ac) /// /// Returns the specific type of the DescriptorResult object. - /// + /// + /// /// The return value from this method really indicates what type of result will /// be obtained from the object. Note that the same result /// can be achieved by interrogating the object; this method /// allows you to do the same thing, without actually calculating the descriptor. - /// - /// + /// public override IDescriptorResult DescriptorResultType => new ArrayResult(20); /// @@ -141,11 +134,6 @@ public DescriptorValue> Calculate(IAtomContainer ac) /// public override IReadOnlyList ParameterNames => System.Array.Empty(); - /// - /// Gets the parameterType attribute of the AromaticAtomsCountDescriptor object. - /// - /// Description of the Parameter - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) { return null; diff --git a/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs index ec46e65b..106b4c2d 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AromaticAtomsCountDescriptor.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Aromaticities; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; @@ -105,7 +106,7 @@ public override IReadOnlyList Parameters /// public DescriptorValue> Calculate(IAtomContainer atomContainer) { - IAtomContainer ac = (IAtomContainer)atomContainer.Clone(); + var ac = (IAtomContainer)atomContainer.Clone(); int aromaticAtomsCount = 0; if (checkAromaticity) @@ -143,29 +144,19 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// /// Returns the specific type of the DescriptorResult object. - ///

+ ///

+ /// /// The return value from this method really indicates what type of result will /// be obtained from the object. Note that the same result /// can be achieved by interrogating the object; this method /// allows you to do the same thing, without actually calculating the descriptor. - /// - /// an object that implements the interface indicating - /// the actual type of values returned by the descriptor in the object - /// + /// + /// an object that implements the interface indicating + /// the actual type of values returned by the descriptor in the object public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - /// - /// Gets the parameterNames attribute of the AromaticAtomsCountDescriptor object. - /// - /// The parameterNames value - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity" }; - /// - /// Gets the parameterType attribute of the AromaticAtomsCountDescriptor object. - /// - /// Description of the Parameter - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) => true; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs index 1d4d6e95..595543c0 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AromaticBondsCountDescriptor.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Aromaticities; using NCDK.QSAR.Results; using NCDK.Tools.Manipulator; @@ -53,9 +54,6 @@ public class AromaticBondsCountDescriptor : AbstractMolecularDescriptor, IMolecu private bool checkAromaticity = false; private static readonly string[] NAMES = { "nAromBond" }; - /// - /// Constructor for the AromaticBondsCountDescriptor object. - /// public AromaticBondsCountDescriptor() { } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs index 68a491d2..360d457b 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/AtomCountDescriptor.cs @@ -54,9 +54,6 @@ public class AtomCountDescriptor : AbstractMolecularDescriptor, IMolecularDescri { private string elementName = "*"; - /// - /// Constructor for the AtomCountDescriptor object. - /// public AtomCountDescriptor() { elementName = "*"; @@ -70,10 +67,6 @@ public AtomCountDescriptor() typeof(AtomCountDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// Sets the parameters attribute of the AtomCountDescriptor object. - /// - /// if the number of parameters is greater than 1 or else the parameter is not of type string public override IReadOnlyList Parameters { set @@ -109,7 +102,7 @@ public override IReadOnlyList DescriptorNames } /// - /// This method calculate the number of atoms of a given type in an . + /// This method calculate the number of atoms of a given type in an . /// /// The atom container for which this descriptor is to be calculated /// Number of atoms of a certain type is returned. @@ -177,16 +170,8 @@ public DescriptorValue> Calculate(IAtomContainer container) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - /// - /// The parameterNames attribute of the AtomCountDescriptor object. - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "elementName" }; - /// - /// Gets the parameterType attribute of the AtomCountDescriptor object. - /// - /// Description of the Parameter - /// An Object whose class is that of the parameter requested public override object GetParameterType(string name) => ""; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs index 11ae8253..95ad33c7 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs @@ -17,10 +17,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Common.Collections; using MathNet.Numerics.LinearAlgebra; using NCDK.Aromaticities; using NCDK.Charges; +using NCDK.Common.Collections; using NCDK.Config; using NCDK.Graphs; using NCDK.Graphs.Matrix; @@ -28,8 +28,8 @@ using NCDK.Tools; using NCDK.Tools.Manipulator; using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -197,20 +197,17 @@ public override IReadOnlyList DescriptorNames { for (int i = 0; i < nhigh; i++) { - names[counter++] = "BCUT" + aSuffix + "-" + (i + 1) + "l"; + names[counter++] = $"BCUT{aSuffix}-{i + 1}l"; } for (int i = 0; i < nlow; i++) { - names[counter++] = "BCUT" + aSuffix + "-" + (i + 1) + "h"; + names[counter++] = $"BCUT{aSuffix}-{i + 1}h"; } } return names; } } - /// - /// The parameterNames attribute of the BCUTDescriptor object. - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "nhigh", "nlow", "checkAromaticity" }; /// @@ -318,7 +315,7 @@ public static double[][] EvalMatrix(IAtomContainer atomContainer, double[] vsd) public DescriptorValue> Calculate(IAtomContainer container) { int counter; - IAtomContainer molecule = (IAtomContainer)container.Clone(); + var molecule = (IAtomContainer)container.Clone(); // add H's in case they're not present try @@ -358,12 +355,14 @@ public DescriptorValue> Calculate(IAtomContainer container) int nheavy = 0; for (int i = 0; i < molecule.Atoms.Count; i++) { - if (!string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) nheavy++; + if (!string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) + nheavy++; } - if (nheavy == 0) return GetDummyDescriptorValue(new CDKException("No heavy atoms in the molecule")); + if (nheavy == 0) + return GetDummyDescriptorValue(new CDKException("No heavy atoms in the molecule")); - double[] diagvalue = new double[nheavy]; + var diagvalue = new double[nheavy]; // get atomic mass weighted BCUT counter = 0; @@ -381,20 +380,20 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException($"Could not calculate weight: {e.Message}", e)); } - double[][] burdenMatrix = BurdenMatrix.EvalMatrix(molecule, diagvalue); + var burdenMatrix = BurdenMatrix.EvalMatrix(molecule, diagvalue); if (HasUndefined(burdenMatrix)) return GetDummyDescriptorValue(new CDKException("Burden matrix has undefined values")); Matrix matrix; matrix = Matrix.Build.DenseOfColumnArrays(burdenMatrix); var eigenDecomposition = matrix.Evd().EigenValues; - double[] eval1 = eigenDecomposition.Select(n => n.Real).ToArray(); + var eval1 = eigenDecomposition.Select(n => n.Real).ToArray(); // get charge weighted BCUT GasteigerMarsiliPartialCharges peoe; try { LonePairElectronChecker.Saturate(molecule); - double[] charges = new double[molecule.Atoms.Count]; + var charges = new double[molecule.Atoms.Count]; peoe = new GasteigerMarsiliPartialCharges(); peoe.AssignGasteigerMarsiliSigmaPartialCharges(molecule, true); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -411,7 +410,8 @@ public DescriptorValue> Calculate(IAtomContainer container) counter = 0; for (int i = 0; i < molecule.Atoms.Count; i++) { - if (string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) continue; + if (string.Equals(molecule.Atoms[i].Symbol, "H", StringComparison.Ordinal)) + continue; diagvalue[counter] = molecule.Atoms[i].Charge.Value; counter++; } @@ -420,9 +420,9 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException("Burden matrix has undefined values")); matrix = Matrix.Build.DenseOfColumnArrays(burdenMatrix); eigenDecomposition = matrix.Evd().EigenValues; - double[] eval2 = eigenDecomposition.Select(n => n.Real).ToArray(); + var eval2 = eigenDecomposition.Select(n => n.Real).ToArray(); - int[][] topoDistance = PathTools.ComputeFloydAPSP(AdjacencyMatrix.GetMatrix(molecule)); + var topoDistance = PathTools.ComputeFloydAPSP(AdjacencyMatrix.GetMatrix(molecule)); // get polarizability weighted BCUT counter = 0; @@ -438,7 +438,7 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException("Burden matrix has undefined values")); matrix = Matrix.Build.DenseOfColumnArrays(burdenMatrix); eigenDecomposition = matrix.Evd().EigenValues; - double[] eval3 = eigenDecomposition.Select(n => n.Real).ToArray(); + var eval3 = eigenDecomposition.Select(n => n.Real).ToArray(); string[] names; string[] suffix = { "w", "c", "p" }; diff --git a/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs index 462c93ad..7a0403fe 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BPolDescriptor.cs @@ -27,7 +27,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// /// Sum of the absolute value of the difference between atomic polarizabilities - /// of all bonded atoms in the molecule (including implicit hydrogens) with polarizabilities taken from + /// of all bonded atoms in the molecule (including implicit hydrogens) with polarizabilities taken from /// http://www.sunysccc.edu/academic/mst/ptable/p-table2.htm /// /// This descriptor assumes 2-centered bonds. @@ -52,9 +52,6 @@ public class BPolDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor private static double[] polarizabilities; private static readonly string[] NAMES = { "bpol" }; - /// - /// Constructor for the APolDescriptor object - /// public BPolDescriptor() { // atomic polarizabilities ordered by atomic number from 1 to 102 @@ -77,10 +74,6 @@ public BPolDescriptor() typeof(BPolDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the BPolDescriptor object - /// - /// Description of the Exception public override IReadOnlyList Parameters { set @@ -97,8 +90,8 @@ public override IReadOnlyList Parameters public override IReadOnlyList DescriptorNames => NAMES; /// - /// This method calculate the sum of the absolute value of - /// the difference between atomic polarizabilities of all bonded atoms in the molecule + /// This method calculate the sum of the absolute value of + /// the difference between atomic polarizabilities of all bonded atoms in the molecule /// /// Parameter is the atom container. /// The sum of atomic polarizabilities @@ -156,27 +149,19 @@ public DescriptorValue> Calculate(IAtomContainer container) /// /// Returns the specific type of the DescriptorResult object. - /// + /// + /// /// The return value from this method really indicates what type of result will /// be obtained from the object. Note that the same result /// can be achieved by interrogating the object; this method - /// allows you to do the same thing, without actually calculating the descriptor. - /// + /// allows you to do the same thing, without actually calculating the descriptor. + /// public override IDescriptorResult DescriptorResultType { get; } = new Result(0.0); - /// - /// The parameterNames attribute of the BPolDescriptor object - /// public override IReadOnlyList ParameterNames => null; // no param names to return - /// - /// Gets the parameterType attribute of the BPolDescriptor object - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); } } - diff --git a/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs index b1cb63d7..2aec5a25 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BasicGroupCountDescriptor.cs @@ -16,13 +16,11 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.QSAR.Results; using NCDK.Smiles.SMARTS; using System; using System.Collections.Generic; -using System.Linq; -using NCDK.Aromaticities; -using NCDK.Tools.Manipulator; namespace NCDK.QSAR.Descriptors.Moleculars { @@ -57,9 +55,6 @@ public class BasicGroupCountDescriptor private static readonly List tools = new List(); - /// - /// Creates a new . - /// public BasicGroupCountDescriptor() { } diff --git a/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs index 2844b729..7b871bdb 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BondCountDescriptor.cs @@ -24,7 +24,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// IDescriptor based on the number of bonds of a certain bond order. + /// based on the number of bonds of a certain bond order. /// /// /// This descriptor uses these parameters: @@ -78,10 +78,6 @@ public BondCountDescriptor() { } typeof(BondCountDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the BondCountDescriptor object - /// - /// Description of the Exception public override IReadOnlyList Parameters { set @@ -121,7 +117,7 @@ public override IReadOnlyList DescriptorNames } /// - /// This method calculate the number of bonds of a given type in an atomContainer + /// This method calculate the number of bonds of a given type in an atomContainer /// /// AtomContainer /// The number of bonds of a certain type. @@ -174,16 +170,8 @@ private static bool BondMatch(BondOrder order, string orderString) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - /// - /// The parameterNames attribute of the BondCountDescriptor object - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "order" }; - /// - /// Gets the parameterType attribute of the BondCountDescriptor object - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) { if (string.Equals("order", name, StringComparison.Ordinal)) return ""; diff --git a/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs index e9066685..80afce54 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/CPSADescriptor.cs @@ -160,25 +160,16 @@ public CPSADescriptor() { } /// An ArrayList containing 29 elements in the order described above public DescriptorValue> Calculate(IAtomContainer atomContainer) { - ArrayResult retval = new ArrayResult(); + var retval = new ArrayResult(); if (!GeometryUtil.Has3DCoordinates(atomContainer)) { for (int i = 0; i < 29; i++) retval.Add(double.NaN); - return new DescriptorValue>(specification, ParameterNames, Parameters, retval, - DescriptorNames, new CDKException("Molecule must have 3D coordinates")); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames, new CDKException("Molecule must have 3D coordinates")); } - IAtomContainer container; - container = (IAtomContainer)atomContainer.Clone(); - - // IsotopeFactory factory = null; - // try { - // factory = IsotopeFactory.GetInstance(container.GetNewBuilder()); - // } catch (Exception e) { - // Debug.WriteLine(e); - // } + var container = (IAtomContainer)atomContainer.Clone(); GasteigerMarsiliPartialCharges peoe; try @@ -191,8 +182,8 @@ public DescriptorValue> Calculate(IAtomContainer atomContain Debug.WriteLine("Error in assigning Gasteiger-Marsilli charges"); for (int i = 0; i < 29; i++) retval.Add(double.NaN); - return new DescriptorValue>(specification, ParameterNames, Parameters, retval, - DescriptorNames, new CDKException("Error in getting G-M charges")); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, + DescriptorNames, new CDKException("Error in getting G-M charges")); } NumericalSurface surface; @@ -207,7 +198,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain for (int i = 0; i < 29; i++) retval.Add(double.NaN); return new DescriptorValue>(specification, ParameterNames, Parameters, retval, - DescriptorNames, new CDKException("Error in surface area calculation")); + DescriptorNames, new CDKException("Error in surface area calculation")); } //double molecularWeight = mfa.GetMass(); diff --git a/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs index 2d512e81..97583980 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/CarbonTypesDescriptor.cs @@ -67,10 +67,6 @@ public CarbonTypesDescriptor() { } typeof(CarbonTypesDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// Sets the parameters attribute of the GravitationalIndexDescriptor object. - /// - /// public override IReadOnlyList Parameters { set @@ -86,16 +82,8 @@ public override IReadOnlyList Parameters public override IReadOnlyList DescriptorNames => NAMES; - /// - /// The parameterNames attribute of the GravitationalIndexDescriptor object. - /// public override IReadOnlyList ParameterNames => null; // no param names to return - /// - /// Gets the parameterType attribute of the GravitationalIndexDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs index 660ad34b..2f710656 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiChainDescriptor.cs @@ -104,12 +104,11 @@ public override IReadOnlyList Parameters private DescriptorValue> GetDummyDescriptorValue(Exception e) { - int ndesc = DescriptorNames.Count; - ArrayResult results = new ArrayResult(ndesc); + var ndesc = DescriptorNames.Count; + var results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(specification, ParameterNames, Parameters, results, - DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } public DescriptorValue> Calculate(IAtomContainer container) @@ -118,8 +117,8 @@ public DescriptorValue> Calculate(IAtomContainer container) sp = new SmilesParser(container.Builder); // we don't make a clone, since removeHydrogens returns a deep copy - IAtomContainer localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); + var localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); + var matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); foreach (var atom in localAtomContainer.Atoms) { IAtomType type; @@ -133,7 +132,7 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException($"Error in atom typing: {atom}")); } } - CDKHydrogenAdder hAdder = CDKHydrogenAdder.GetInstance(container.Builder); + var hAdder = CDKHydrogenAdder.GetInstance(container.Builder); try { hAdder.AddImplicitHydrogens(localAtomContainer); @@ -149,11 +148,11 @@ public DescriptorValue> Calculate(IAtomContainer container) var subgraph6 = Order6(localAtomContainer); var subgraph7 = Order7(localAtomContainer); - double order3s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph3); - double order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); - double order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); - double order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); - double order7s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph7); + var order3s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph3); + var order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); + var order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); + var order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); + var order7s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph7); double order3v, order4v, order5v, order6v, order7v; try @@ -169,7 +168,7 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException("Error in substructure search: " + e.Message)); } - ArrayResult retval = new ArrayResult + var retval = new ArrayResult { order3s, order4s, diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs index 178f86d7..7b3883c9 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiClusterDescriptor.cs @@ -73,7 +73,7 @@ public ChiClusterDescriptor() { } public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = - new DescriptorSpecification( + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#chiCluster", typeof(ChiClusterDescriptor).FullName, "The Chemistry Development Kit"); @@ -85,12 +85,11 @@ public ChiClusterDescriptor() { } private DescriptorValue> GetDummyDescriptorValue(Exception e) { - int ndesc = DescriptorNames.Count; - ArrayResult results = new ArrayResult(ndesc); + var ndesc = DescriptorNames.Count; + var results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(specification, ParameterNames, Parameters, results, - DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } public DescriptorValue> Calculate(IAtomContainer container) @@ -99,8 +98,8 @@ public DescriptorValue> Calculate(IAtomContainer container) sp = new SmilesParser(container.Builder); // removeHydrogens does a deep copy, so no need to clone - IAtomContainer localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); - CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); + var localAtomContainer = AtomContainerManipulator.RemoveHydrogens(container); + var matcher = CDKAtomTypeMatcher.GetInstance(container.Builder); foreach (var atom in localAtomContainer.Atoms) { IAtomType type; @@ -129,10 +128,10 @@ public DescriptorValue> Calculate(IAtomContainer container) var subgraph5 = Order5(localAtomContainer); var subgraph6 = Order6(localAtomContainer); - double order3s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph3); - double order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); - double order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); - double order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); + var order3s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph3); + var order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); + var order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); + var order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); double order3v, order4v, order5v, order6v; try diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs index ed0dac44..e5afe252 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiIndexUtils.cs @@ -43,19 +43,20 @@ internal class ChiIndexUtils { /// /// Gets the fragments from a target matching a set of query fragments. - /// + /// + /// /// This method returns a list of lists. Each list contains the atoms of the target /// that arise in the mapping of bonds in the target molecule to the bonds in the query fragment. /// The query fragments should be constructed /// using the method of the - /// CDK class, since we are only interested in connectivity and not actual atom or bond type information. - /// + /// CDK class, since we are only interested in connectivity and not actual atom or bond type information. + /// /// The target /// An array of query fragments /// A list of lists, each list being the atoms that match the query fragments public static IEnumerable> GetFragments(IAtomContainer atomContainer, QueryAtomContainer[] queries) { - UniversalIsomorphismTester universalIsomorphismTester = new UniversalIsomorphismTester(); + var universalIsomorphismTester = new UniversalIsomorphismTester(); var uniqueSubgraphs = new List>(); foreach (var query in queries) { @@ -156,33 +157,37 @@ public static double EvalValenceIndex(IAtomContainer atomContainer, IEnumerable< var atom = atomContainer.Atoms[atomSerial]; string sym = atom.Symbol; - - if (string.Equals(sym, "S", StringComparison.Ordinal)) - { // check for some special S environments - double tmp = DeltavSulphur(atom, atomContainer); - if (tmp != -1) - { - prod = prod * tmp; - continue; - } - } - if (string.Equals(sym, "P", StringComparison.Ordinal)) - { // check for some special P environments - double tmp = DeltavPhosphorous(atom, atomContainer); - if (tmp != -1) - { - prod = prod * tmp; - continue; - } + switch (sym) + { + case "S": + { // check for some special S environments + var tmp = DeltavSulphur(atom, atomContainer); + if (tmp != -1) + { + prod = prod * tmp; + continue; + } + } + break; + case "P": + { // check for some special P environments + var tmp = DeltavPhosphorous(atom, atomContainer); + if (tmp != -1) + { + prod = prod * tmp; + continue; + } + } + break; } - int z = atom.AtomicNumber.Value; + var z = atom.AtomicNumber.Value; // TODO there should be a neater way to get the valence electron count - int zv = GetValenceElectronCount(atom); + var zv = GetValenceElectronCount(atom); - int hsupp = atom.ImplicitHydrogenCount.Value; - double deltav = (double)(zv - hsupp) / (double)(z - zv - 1); + var hsupp = atom.ImplicitHydrogenCount.Value; + var deltav = (double)(zv - hsupp) / (double)(z - zv - 1); prod = prod * deltav; } @@ -291,7 +296,7 @@ private static List> GetUniqueBondSubgraphs(IEnumerable(); foreach (var aCurrent in current) { - RMap rmap = (RMap)aCurrent; + var rmap = aCurrent; ids.Add(rmap.Id1); } ids.Sort(); diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs index 445cd19b..872301fe 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiPathClusterDescriptor.cs @@ -71,7 +71,7 @@ public ChiPathClusterDescriptor() { } public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = - new DescriptorSpecification( + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#chiPathCluster", typeof(ChiPathClusterDescriptor).FullName, "The Chemistry Development Kit"); @@ -100,7 +100,7 @@ public DescriptorValue> Calculate(IAtomContainer container) return GetDummyDescriptorValue(new CDKException("Error in atom typing: " + e.Message)); } } - CDKHydrogenAdder hAdder = CDKHydrogenAdder.GetInstance(container.Builder); + var hAdder = CDKHydrogenAdder.GetInstance(container.Builder); try { hAdder.AddImplicitHydrogens(localAtomContainer); @@ -114,9 +114,9 @@ public DescriptorValue> Calculate(IAtomContainer container) var subgraph5 = Order5(localAtomContainer); var subgraph6 = Order6(localAtomContainer); - double order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); - double order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); - double order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); + var order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); + var order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); + var order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); double order4v, order5v, order6v; try @@ -145,12 +145,11 @@ public DescriptorValue> Calculate(IAtomContainer container) private DescriptorValue> GetDummyDescriptorValue(Exception e) { - int ndesc = DescriptorNames.Count; - ArrayResult results = new ArrayResult(ndesc); + var ndesc = DescriptorNames.Count; + var results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(specification, ParameterNames, Parameters, results, - DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } /// @@ -158,7 +157,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e private IEnumerable> Order4(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[1]; + var queries = new QueryAtomContainer[1]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CC(C)CC"), false); @@ -172,7 +171,7 @@ private IEnumerable> Order4(IAtomContainer atomContainer) private IEnumerable> Order5(IAtomContainer atomContainer) { - QueryAtomContainer[] queries = new QueryAtomContainer[3]; + var queries = new QueryAtomContainer[3]; try { queries[0] = QueryAtomContainerCreator.CreateAnyAtomAnyBondContainer(sp.ParseSmiles("CC(C)CCC"), false); diff --git a/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs index b700f3cc..139bc4f4 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ChiPathDescriptor.cs @@ -74,7 +74,7 @@ public ChiPathDescriptor() public override IReadOnlyList DescriptorNames { get; } = _DescriptorNames(); private static string[] _DescriptorNames() { - string[] names = new string[16]; + var names = new string[16]; for (int i = 0; i < 8; i++) { names[i] = "SP-" + i; @@ -120,23 +120,23 @@ public DescriptorValue> Calculate(IAtomContainer container) var subgraph6 = Order6(localAtomContainer); var subgraph7 = Order7(localAtomContainer); - double order0s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph0); - double order1s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph1); - double order2s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph2); - double order3s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph3); - double order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); - double order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); - double order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); - double order7s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph7); + var order0s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph0); + var order1s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph1); + var order2s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph2); + var order3s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph3); + var order4s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph4); + var order5s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph5); + var order6s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph6); + var order7s = ChiIndexUtils.EvalSimpleIndex(localAtomContainer, subgraph7); - double order0v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph0); - double order1v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph1); - double order2v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph2); - double order3v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph3); - double order4v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph4); - double order5v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph5); - double order6v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph6); - double order7v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph7); + var order0v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph0); + var order1v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph1); + var order2v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph2); + var order3v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph3); + var order4v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph4); + var order5v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph5); + var order6v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph6); + var order7v = ChiIndexUtils.EvalValenceIndex(localAtomContainer, subgraph7); var retval = new ArrayResult { diff --git a/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs index 795aadb9..81a75e39 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/EccentricConnectivityIndexDescriptor.cs @@ -29,11 +29,11 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// /// A topological descriptor combining distance and adjacency information. + /// + /// /// This descriptor is described by Sharma et al. cdk-cite-SHA97 and has been shown /// to correlate well with a number of physical properties. The descriptor is also reported to /// have good discriminatory ability. - /// - /// /// /// The eccentric connectivity index for a hydrogen supressed molecular graph is given by the /// expression @@ -73,42 +73,28 @@ public EccentricConnectivityIndexDescriptor() { } public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = - new DescriptorSpecification( + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#eccentricConnectivityIndex", typeof(EccentricConnectivityIndexDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// the parameterNames attribute of the EccentricConnectivityIndexDescriptor object - /// public override IReadOnlyList ParameterNames => null; - - /// - /// The parameterType attribute of the EccentricConnectivityIndexDescriptor object - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; - public override IReadOnlyList DescriptorNames => NAMES; - - /// - /// the parameters attribute of the EccentricConnectivityIndexDescriptor object - /// public override IReadOnlyList Parameters { get { return null; } set { } } /// - /// Calculates the eccentric connectivity + /// Calculates the eccentric connectivity /// /// Parameter is the atom container. /// A value representing the eccentric connectivity index public DescriptorValue> Calculate(IAtomContainer container) { - IAtomContainer local = AtomContainerManipulator.RemoveHydrogens(container); + var local = AtomContainerManipulator.RemoveHydrogens(container); int natom = local.Atoms.Count; - int[][] admat = AdjacencyMatrix.GetMatrix(local); - int[][] distmat = PathTools.ComputeFloydAPSP(admat); + var admat = AdjacencyMatrix.GetMatrix(local); + var distmat = PathTools.ComputeFloydAPSP(admat); int eccenindex = 0; for (int i = 0; i < natom; i++) @@ -116,14 +102,14 @@ public DescriptorValue> Calculate(IAtomContainer container) int max = -1; for (int j = 0; j < natom; j++) { - if (distmat[i][j] > max) max = distmat[i][j]; + if (distmat[i][j] > max) + max = distmat[i][j]; } - int degree = local.GetConnectedBonds(local.Atoms[i]).Count(); + var degree = local.GetConnectedBonds(local.Atoms[i]).Count(); eccenindex += max * degree; } - Result retval = new Result(eccenindex); - return new DescriptorValue>(specification, ParameterNames, Parameters, retval, - DescriptorNames, null); + var retval = new Result(eccenindex); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames, null); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs index 275a9e21..d56cd92d 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/FMFDescriptor.cs @@ -63,7 +63,7 @@ public DescriptorValue> Calculate(IAtomContainer container) { container = Clone(container); // don't mod original - MurckoFragmenter fragmenter = new MurckoFragmenter(true, 3); + var fragmenter = new MurckoFragmenter(true, 3); Result result; try { @@ -90,7 +90,8 @@ public DescriptorValue> Calculate(IAtomContainer container) /// /// Returns the specific type of the FMF descriptor value. - /// + /// + /// /// The FMF descriptor is a single, double value. /// /// The return value from this method really indicates what type of result will @@ -102,22 +103,24 @@ public DescriptorValue> Calculate(IAtomContainer container) /// length of a descriptor calculated with the current parameters. Typically, the /// length of array result types vary with the values of the parameters. See /// for more details. - /// + /// /// an instance of the public override IDescriptorResult DescriptorResultType { get; } = new Result(); /// public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = - new DescriptorSpecification( + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#fmf", typeof(FMFDescriptor).FullName, "The Chemistry Development Kit"); /// /// Returns the names of the parameters for this descriptor. - /// Since this descriptor takes no parameters, is returned /// + /// + /// Since this descriptor takes no parameters, is returned + /// /// , since there are no parameters public override IReadOnlyList ParameterNames => null; diff --git a/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs index a1298e8b..e628fbdf 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/FractionalPSADescriptor.cs @@ -38,11 +38,13 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// Polar surface area expressed as a ratio to molecular size. Calculates tpsaEfficiency, which is + /// Polar surface area expressed as a ratio to molecular size. + /// + /// + /// Calculates tpsaEfficiency, which is /// to / molecular weight, in units of square Angstroms per Dalton. - /// /// Other related descriptors may also be useful to add, e.g. ratio of polar to hydrophobic surface area. - /// + /// // @cdk.module qsarmolecular // @cdk.githash // @cdk.dictref qsar-descriptors:fractionalPSA diff --git a/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs index dc9d367e..a075b9b9 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/FragmentComplexityDescriptor.cs @@ -25,15 +25,15 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// Class that returns the complexity of a system. + /// Class that returns the complexity of a system. /// /// /// /// The complexity is defined as cdk-cite-Nilakantan06: - ///
-    ///  C=Abs(B^2-A^2+A)+H/100
-    ///  
- /// where C=complexity, A=number of non-hydrogen atoms, B=number of bonds and H=number of heteroatoms + ///
+    /// C=Abs(B^2-A^2+A)+H/100
+    /// 
+ /// where C=complexity, A=number of non-hydrogen atoms, B=number of bonds and H=number of heteroatoms ///
/// This descriptor uses no parameters. ///
@@ -46,23 +46,22 @@ public class FragmentComplexityDescriptor : AbstractMolecularDescriptor, IMolecu { private static readonly string[] NAMES = { "fragC" }; - /// - /// Constructor for the FragmentComplexityDescriptor object. - /// public FragmentComplexityDescriptor() { } /// public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = - new DescriptorSpecification( + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#NilaComplexity", typeof(FragmentComplexityDescriptor).FullName, "The Chemistry Development Kit"); /// /// The parameters attribute of the FragmentComplexityDescriptor object. - /// This descriptor takes no parameter. /// + /// + /// This descriptor takes no parameter. + /// public override IReadOnlyList Parameters { set @@ -115,11 +114,6 @@ public DescriptorValue> Calculate(IAtomContainer container) /// public override IReadOnlyList ParameterNames => null; - /// - /// Gets the parameterType attribute of the FragmentComplexityDescriptor object. - /// - /// Description of the Parameter - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs index f00150d5..77a96a0c 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/GravitationalIndexDescriptor.cs @@ -17,9 +17,9 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Numerics; using NCDK.Config; using NCDK.Geometries; +using NCDK.Numerics; using NCDK.QSAR.Results; using System; using System.Collections.Generic; @@ -29,12 +29,12 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// /// IDescriptor characterizing the mass distribution of the molecule. + /// + /// /// Described by Katritzky et al. cdk-cite-KAT96. /// For modelling purposes the value of the descriptor is calculated /// both with and without H atoms. Furthermore the square and cube roots /// of the descriptor are also generated as described by Wessel et al. cdk-cite-WES98. - /// - /// /// /// The descriptor routine generates 9 descriptors: /// @@ -85,38 +85,23 @@ public GravitationalIndexDescriptor() { } public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = - new DescriptorSpecification( + new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#gravitationalIndex", typeof(GravitationalIndexDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the GravitationalIndexDescriptor object. - /// public override IReadOnlyList Parameters { get { return null; } set { } } - public override IReadOnlyList DescriptorNames => NAMES; - - /// - /// The parameterNames attribute of the GravitationalIndexDescriptor object. - /// public override IReadOnlyList ParameterNames => null; - - /// - /// Gets the parameterType attribute of the GravitationalIndexDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; private DescriptorValue> GetDummyDescriptorValue(Exception e) { - int ndesc = DescriptorNames.Count; - ArrayResult results = new ArrayResult(ndesc); + var ndesc = DescriptorNames.Count; + var results = new ArrayResult(ndesc); for (int i = 0; i < ndesc; i++) results.Add(double.NaN); - return new DescriptorValue>(specification, ParameterNames, Parameters, results, - DescriptorNames, e); + return new DescriptorValue>(specification, ParameterNames, Parameters, results, DescriptorNames, e); } /// @@ -155,14 +140,14 @@ public DescriptorValue> Calculate(IAtomContainer container) Vector3 p1 = bond.Atoms[0].Point3D.Value; Vector3 p2 = bond.Atoms[1].Point3D.Value; - double x1 = p1.X; - double y1 = p1.Y; - double z1 = p1.Z; - double x2 = p2.X; - double y2 = p2.Y; - double z2 = p2.Z; + var x1 = p1.X; + var y1 = p1.Y; + var z1 = p1.Z; + var x2 = p2.X; + var y2 = p2.Y; + var z2 = p2.Z; - double dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); + var dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); sum += (mass1 * mass2) / dist; } @@ -184,14 +169,14 @@ public DescriptorValue> Calculate(IAtomContainer container) Vector3 point0 = b.Atoms[0].Point3D.Value; Vector3 point1 = b.Atoms[1].Point3D.Value; - double x1 = point0.X; - double y1 = point0.Y; - double z1 = point0.Z; - double x2 = point1.X; - double y2 = point1.Y; - double z2 = point1.Z; + var x1 = point0.X; + var y1 = point0.Y; + var z1 = point0.Z; + var x2 = point1.X; + var y2 = point1.Y; + var z2 = point1.Z; - double dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); + var dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); heavysum += (mass1 * mass2) / dist; } @@ -211,13 +196,15 @@ public DescriptorValue> Calculate(IAtomContainer container) for (int j = i + 1; j < x.Count; j++) { int present = 0; - int a = x[i]; - int b = x[j]; + var a = x[i]; + var b = x[j]; for (int k = 0; k < pcount; k++) { - if ((p[k].X == a && p[k].Y == b) || (p[k].Y == a && p[k].X == b)) present = 1; + if ((p[k].X == a && p[k].Y == b) || (p[k].Y == a && p[k].X == b)) + present = 1; } - if (present == 1) continue; + if (present == 1) + continue; p[pcount].X = a; p[pcount].Y = b; pcount += 1; @@ -226,24 +213,24 @@ public DescriptorValue> Calculate(IAtomContainer container) double allheavysum = 0; foreach (var aP in p) { - int atomNumber1 = aP.X; - int atomNumber2 = aP.Y; + var atomNumber1 = aP.X; + var atomNumber2 = aP.Y; mass1 = factory.GetMajorIsotope(container.Atoms[atomNumber1].Symbol).MassNumber.Value; mass2 = factory.GetMajorIsotope(container.Atoms[atomNumber2].Symbol).MassNumber.Value; - double x1 = container.Atoms[atomNumber1].Point3D.Value.X; - double y1 = container.Atoms[atomNumber1].Point3D.Value.Y; - double z1 = container.Atoms[atomNumber1].Point3D.Value.Z; - double x2 = container.Atoms[atomNumber2].Point3D.Value.X; - double y2 = container.Atoms[atomNumber2].Point3D.Value.Y; - double z2 = container.Atoms[atomNumber2].Point3D.Value.Z; + var x1 = container.Atoms[atomNumber1].Point3D.Value.X; + var y1 = container.Atoms[atomNumber1].Point3D.Value.Y; + var z1 = container.Atoms[atomNumber1].Point3D.Value.Z; + var x2 = container.Atoms[atomNumber2].Point3D.Value.X; + var y2 = container.Atoms[atomNumber2].Point3D.Value.Y; + var z2 = container.Atoms[atomNumber2].Point3D.Value.Z; - double dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); + var dist = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2); allheavysum += (mass1 * mass2) / dist; } - ArrayResult retval = new ArrayResult(9) + var retval = new ArrayResult(9) { heavysum, Math.Sqrt(heavysum), @@ -258,8 +245,7 @@ public DescriptorValue> Calculate(IAtomContainer container) Math.Pow(allheavysum, 1.0 / 3.0) }; - return new DescriptorValue>(specification, ParameterNames, Parameters, retval, - DescriptorNames); + return new DescriptorValue>(specification, ParameterNames, Parameters, retval, DescriptorNames); } /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs index e4bb670f..1f057b49 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs @@ -77,16 +77,8 @@ public class HBondAcceptorCountDescriptor : AbstractMolecularDescriptor, IMolecu private bool checkAromaticity = false; private static readonly string[] NAMES = { "nHBAcc" }; - /// - /// Constructor for the HBondAcceptorCountDescriptor object - /// public HBondAcceptorCountDescriptor() { } - /// - /// Gets the specification attribute of the HBondAcceptorCountDescriptor object. - /// - /// The specification value - /// public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = new DescriptorSpecification( @@ -136,7 +128,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e) public DescriptorValue> Calculate(IAtomContainer atomContainer) { int hBondAcceptors = 0; - IAtomContainer ac = (IAtomContainer)atomContainer.Clone(); + var ac = (IAtomContainer)atomContainer.Clone(); // aromaticity is detected prior to descriptor calculation if the respective parameter is set to true @@ -197,17 +189,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - - /// - /// The parameterNames attribute of the HBondAcceptorCountDescriptor object. - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity" }; - - /// - /// Gets the parameterType attribute of the HBondAcceptorCountDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => false; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs index b7d3f75a..2dcab606 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/HBondDonorCountDescriptor.cs @@ -69,9 +69,6 @@ public class HBondDonorCountDescriptor : AbstractMolecularDescriptor, IMolecular { private static readonly string[] NAMES = { "nHBDon" }; - /// - /// Constructor for the HBondDonorCountDescriptor object - /// public HBondDonorCountDescriptor() { } /// @@ -84,9 +81,6 @@ public HBondDonorCountDescriptor() { } typeof(HBondDonorCountDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameter of this HBondDonorCountDescriptor instance. - /// public override IReadOnlyList Parameters { set @@ -163,15 +157,12 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// /// The parameterNames of the HBondDonorCountDescriptor. - /// as this descriptor does not have any parameters. /// + /// + /// as this descriptor does not have any parameters. + /// public override IReadOnlyList ParameterNames => null; // no parameters; thus we return null - /// - /// Gets the parameterType of the HBondDonorCountDescriptor. - /// - /// Description of the Parameter - /// as this descriptor does not have any parameters public override object GetParameterType(string name) => null; // no parameters; thus we return null IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs index b0e0efa8..0624ce46 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/HybridizationRatioDescriptor.cs @@ -41,9 +41,6 @@ namespace NCDK.QSAR.Descriptors.Moleculars // @cdk.dictref qsar-descriptors:hybratio public class HybridizationRatioDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor { - /// - /// Constructor for the HybridizationRatioDescriptor object. - /// public HybridizationRatioDescriptor() { } /// @@ -58,16 +55,14 @@ public HybridizationRatioDescriptor() { } /// /// The parameters attribute of the HybridizationRatioDescriptor object. - /// This descriptor takes no parameters /// + /// + /// This descriptor takes no parameters + /// public override IReadOnlyList Parameters { get { return Array.Empty(); } set { } } public override IReadOnlyList DescriptorNames { get; } = new string[] { "HybRatio" }; - /// - /// - /// the exception - /// a dummy value private DescriptorValue> GetDummyDescriptorValue(Exception e) { return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, e); @@ -108,14 +103,18 @@ public DescriptorValue> Calculate(IAtomContainer container) /// /// The parameterNames attribute of the HybridizationRatioDescriptor object. - /// This descriptor takes no parameters /// + /// + /// This descriptor takes no parameters + /// public override IReadOnlyList ParameterNames => Array.Empty(); /// /// Gets the parameterType attribute of the HybridizationRatioDescriptor object. - /// This descriptor takes no parameters /// + /// + /// This descriptor takes no parameters + /// /// the parameter name /// An Object whose class is that of the parameter requested public override object GetParameterType(string name) => ""; diff --git a/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs index d22636c1..298dfbd3 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/KappaShapeIndicesDescriptor.cs @@ -52,9 +52,6 @@ public class KappaShapeIndicesDescriptor : AbstractMolecularDescriptor, IMolecul { private static readonly string[] NAMES = { "Kier1", "Kier2", "Kier3" }; - /// - /// Constructor for the KappaShapeIndicesDescriptor object - /// public KappaShapeIndicesDescriptor() { } /// @@ -213,18 +210,7 @@ public DescriptorValue> Calculate(IAtomContainer container) /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(3); - /// - /// The parameterNames attribute of the - /// KappaShapeIndicesDescriptor object - /// public override IReadOnlyList ParameterNames => null; // no param names to return - - /// - /// Gets the parameterType attribute of the - /// KappaShapeIndicesDescriptor object - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs index e863d604..00066f0e 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/KierHallSmartsDescriptor.cs @@ -330,10 +330,6 @@ public KierHallSmartsDescriptor() typeof(KierHallSmartsDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the descriptor. - /// - /// if any parameters are specified public override IReadOnlyList Parameters { get @@ -402,17 +398,7 @@ public DescriptorValue> Calculate(IAtomContainer container) /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(SMARTS.Count); - /// - /// Gets the parameterNames attribute of the descriptor. - /// - /// The parameterNames value public override IReadOnlyList ParameterNames => null; - - /// - /// Gets the parameterType attribute of the descriptor. - /// - /// Description of the Parameter - /// An Object whose class is that of the parameter requested public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs index 45b7c9a9..e070a7f9 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LargestChainDescriptor.cs @@ -61,9 +61,6 @@ public class LargestChainDescriptor : AbstractMolecularDescriptor, IMolecularDes private bool checkRingSystem = false; private static readonly string[] NAMES = { "nAtomLC" }; - /// - /// Constructor for the LargestChain object. - /// public LargestChainDescriptor() { } /// @@ -76,12 +73,12 @@ public LargestChainDescriptor() { } /// /// The parameters attribute of the LargestChain object. - /// + /// + /// /// This descriptor takes two parameters, which should be Booleans to indicate whether /// aromaticity and ring member ship needs been checked (TRUE) or not (FALSE). The first /// parameter (aromaticity) is deprecated and ignored. - /// - /// + /// /// if more than one parameter or a non-bool parameter is specified public override IReadOnlyList Parameters { @@ -131,9 +128,9 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) if (!atom.IsInRing && atom.AtomicNumber != 1) included.Add(atom); } - IAtomContainer subset = SubsetMol(atomContainer, included); + var subset = SubsetMol(atomContainer, included); - AllPairsShortestPaths apsp = new AllPairsShortestPaths(subset); + var apsp = new AllPairsShortestPaths(subset); int max = 0; int numAtoms = subset.Atoms.Count; @@ -152,23 +149,12 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - - /// - /// Gets the parameterNames attribute of the LargestPiSystemDescriptor object. - /// - /// The parameterNames value public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity", "checkRingSystem" }; - - /// - /// Gets the parameterType attribute of the LargestChainDescriptor object. - /// - /// Description of the Parameter - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) => true; private static IAtomContainer SubsetMol(IAtomContainer mol, ISet include) { - IAtomContainer cpy = mol.Builder.NewAtomContainer(); + var cpy = mol.Builder.NewAtomContainer(); foreach (var atom in mol.Atoms) { if (include.Contains(atom)) diff --git a/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs index a721dedb..ea19ed9e 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LargestPiSystemDescriptor.cs @@ -71,10 +71,11 @@ public LargestPiSystemDescriptor() { } /// /// The parameters attribute of the LargestPiSystemDescriptor object. - /// - /// This descriptor takes one parameter, which should be bool to indicate whether - /// aromaticity has been checked (TRUE) or not (FALSE). /// + /// + /// This descriptor takes one parameter, which should be bool to indicate whether + /// aromaticity has been checked or not . + /// /// if more than one parameter or a non-bool parameter is specified public override IReadOnlyList Parameters { @@ -121,7 +122,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e) /// public DescriptorValue> Calculate(IAtomContainer container) { - bool[] originalFlag4 = new bool[container.Atoms.Count]; + var originalFlag4 = new bool[container.Atoms.Count]; for (int i = 0; i < originalFlag4.Length; i++) { originalFlag4[i] = container.Atoms[i].IsVisited; @@ -233,20 +234,11 @@ private void BreadthFirstSearch(IAtomContainer container, List sphere, Li } } - /// - /// The parameterNames attribute of the LargestPiSystemDescriptor object. - /// - /// The parameterNames value public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity" }; - - /// - /// Gets the parameterType attribute of the LargestPiSystemDescriptor object. - /// - /// Description of the Parameter - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) { - if (string.Equals("checkAromaticity", name, StringComparison.Ordinal)) return false; + if (string.Equals("checkAromaticity", name, StringComparison.Ordinal)) + return false; return null; } diff --git a/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs index 15576fd2..cbad9730 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LengthOverBreadthDescriptor.cs @@ -21,10 +21,10 @@ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Common.Collections; -using NCDK.Numerics; using MathNet.Numerics.LinearAlgebra; +using NCDK.Common.Collections; using NCDK.Geometries; +using NCDK.Numerics; using NCDK.QSAR.Results; using NCDK.Tools; using System; @@ -58,9 +58,6 @@ public class LengthOverBreadthDescriptor : AbstractMolecularDescriptor, IMolecul { private static readonly string[] NAMES = { "LOBMAX", "LOBMIN" }; - /// - /// Constructor for the LengthOverBreadthDescriptor object. - /// public LengthOverBreadthDescriptor() { } /// @@ -73,9 +70,6 @@ public LengthOverBreadthDescriptor() { } typeof(LengthOverBreadthDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// Sets the parameters attribute of the PetitjeanNumberDescriptor object - /// public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -108,7 +102,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain double lob, bol, area; double[] xyzRanges; - double[][] coords = Arrays.CreateJagged(atomContainer.Atoms.Count, 3); + var coords = Arrays.CreateJagged(atomContainer.Atoms.Count, 3); for (int i = 0; i < atomContainer.Atoms.Count; i++) { var p = atomContainer.Atoms[i].Point3D.Value; @@ -118,7 +112,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContain } // get the com - Vector3? acom = GeometryUtil.Get3DCentreOfMass(atomContainer); + var acom = GeometryUtil.Get3DCentreOfMass(atomContainer); if (acom == null) return GetDummyDescriptorValue(new CDKException("Error in center of mass calculation, has exact mass been set on all atoms?")); var com = acom.Value; @@ -247,16 +241,7 @@ private static double[] Extents(IAtomContainer atomContainer, double[][] coords, return ranges; } - /// - /// The parameterNames attribute of the PetitjeanNumberDescriptor object - /// public override IReadOnlyList ParameterNames => null; - - /// - /// Gets the parameterType attribute of the PetitjeanNumberDescriptor object - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs index e6ed07ab..b0352163 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/LongestAliphaticChainDescriptor.cs @@ -25,7 +25,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// Counts the number of atoms in the longest aliphatic chain. + /// Counts the number of atoms in the longest aliphatic chain. /// /// /// This descriptor uses these parameters: @@ -56,9 +56,6 @@ public class LongestAliphaticChainDescriptor : AbstractMolecularDescriptor, IMol private bool checkRingSystem = false; private static readonly string[] NAMES = { "nAtomLAC" }; - /// - /// Constructor for the LongestAliphaticChainDescriptor object. - /// public LongestAliphaticChainDescriptor() { } /// @@ -69,11 +66,12 @@ public LongestAliphaticChainDescriptor() { } typeof(LongestAliphaticChainDescriptor).FullName, "The Chemistry Development Kit"); /// - /// Sets the parameters attribute of the LongestAliphaticChainDescriptor object. - /// - /// This descriptor takes one parameter, which should be bool to indicate whether - /// aromaticity has been checked (TRUE) or not (FALSE). + /// Sets the parameters attribute of the LongestAliphaticChainDescriptor object. /// + /// + /// This descriptor takes one parameter, which should be bool to indicate whether + /// aromaticity has been checked or not . + /// /// if more than one parameter or a non-bool parameter is specified public override IReadOnlyList Parameters { @@ -141,9 +139,9 @@ private static int GetMaxDepth(int[][] adjlist, int v, int prev) /// Calculate the count of atoms of the longest aliphatic chain in the supplied . /// /// - /// The method require one parameter: - /// if checkRingSyste is true the will be set - /// + /// The method require one parameter: + /// if checkRingSyste is true the will be set + /// /// The for which this descriptor is to be calculated /// the number of atoms in the longest aliphatic chain of this AtomContainer /// @@ -166,7 +164,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) } int longest = 0; - int[][] adjlist = GraphUtil.ToAdjList(aliphaticParts); + var adjlist = GraphUtil.ToAdjList(aliphaticParts); for (int i = 0; i < adjlist.Length; i++) { // atom deg > 1 can't find the longest chain @@ -187,17 +185,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - - /// - /// The parameterNames attribute of the LongestAliphaticChainDescriptor object. - /// public override IReadOnlyList ParameterNames { get; } = new string[] { CHECK_RING_SYSTEM }; - - /// - /// Gets the parameterType attribute of the LongestAliphaticChainDescriptor object. - /// - /// - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) { if (name.Equals(CHECK_RING_SYSTEM, StringComparison.Ordinal)) diff --git a/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs index 18eccbac..874926db 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/MDEDescriptor.cs @@ -31,11 +31,11 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// /// Calculates the Molecular Distance Edge descriptor described in cdk-cite-LIU98. + /// + /// /// This class evaluates the 10 MDE descriptors described by Liu et al. and /// in addition it calculates variants where O and N are considered (as found in the DEDGE routine /// from ADAPT). - /// - /// /// /// The variants are described below: /// @@ -118,10 +118,6 @@ public MDEDescriptor() "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#mde", typeof(MDEDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the WeightDescriptor object. - /// - /// if more than 1 parameter is specified or if the parameter is not of type string public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; @@ -306,16 +302,7 @@ private static double EvalCValue(int[][] distmat, int[][] codemat, int type1, in return n / Math.Pow(Math.Pow(lambda, 1.0 / (2.0 * n)), 2); } - /// - /// The parameterNames attribute of the WeightDescriptor object. - /// public override IReadOnlyList ParameterNames => null; - - /// - /// Gets the parameterType attribute of the WeightDescriptor object. - /// - /// Description of the Parameter - /// An Object whose class is that of the parameter requested public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs index cc391d31..b7176a62 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/MannholdLogPDescriptor.cs @@ -75,13 +75,13 @@ private IDescriptorValue GetDummyDescriptorValue(Exception e) } /// - /// Calculates the Mannhold LogP for an atom container. + /// Calculates the Mannhold LogP for an atom container. /// /// to calculate the descriptor value for. /// A descriptor value wrapping a . public DescriptorValue> Calculate(IAtomContainer atomContainer) { - IAtomContainer ac = (IAtomContainer)atomContainer.Clone(); + var ac = (IAtomContainer)atomContainer.Clone(); int carbonCount = 0; int heteroCount = 0; @@ -117,7 +117,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// /// Gets the parameterType attribute for a given parameter name. It - /// always returns null, as this descriptor does not have any parameters. + /// always returns , as this descriptor does not have any parameters. /// /// Name of the parameter for which the type is requested. /// The parameterType of the given parameter. diff --git a/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs index 7c09eaa4..b5f6519f 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/MomentOfInertiaDescriptor.cs @@ -32,13 +32,13 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// /// A descriptor that calculates the moment of inertia and radius of gyration. + /// + /// /// Moment of inertia (MI) values characterize the mass distribution of a molecule. /// Related to the MI values, ratios of the MI values along the three principal axes /// are also well know modeling variables. This descriptor calculates the MI values /// along the X, Y and Z axes as well as the ratio's X/Y, X/Z and Y/Z. Finally it also /// calculates the radius of gyration of the molecule. - /// - /// /// /// The descriptor generates 7 values in the following order /// @@ -86,23 +86,9 @@ public class MomentOfInertiaDescriptor : AbstractMolecularDescriptor, IMolecular "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#momentOfInertia", typeof(MomentOfInertiaDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the MomentOfInertiaDescriptor object. - /// public override IReadOnlyList Parameters { get { return null; } set { } } - public override IReadOnlyList DescriptorNames => NAMES; - - /// - /// Tthe parameterNames attribute of the MomentOfInertiaDescriptor object. - /// public override IReadOnlyList ParameterNames => null; - - /// - /// Gets the parameterType attribute of the MomentOfInertiaDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value public override object GetParameterType(string name) => null; private DescriptorValue> GetDummyDescriptorValue(Exception e) @@ -117,7 +103,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e /// /// Calculates the 3 MI's, 3 ration and the R_gyr value. - /// + /// /// The molecule should have hydrogens /// /// Parameter is the atom container. diff --git a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs index 78337435..182fc200 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanNumberDescriptor.cs @@ -25,14 +25,15 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// According to the Petitjean definition, the eccentricity of a vertex corresponds to - /// the distance from that vertex to the most remote vertex in the graph. - /// The distance is obtained from the distance matrix as the count of edges between the two vertices. - /// If r(i) is the largest matrix entry in row i of the distance matrix D, then the radius is defined as the smallest of the r(i). - /// The graph diameter D is defined as the largest vertex eccentricity in the graph. - /// (http://www.edusoft-lc.com/molconn/manuals/400/chaptwo.html) + /// Evaluates Petitjean number. /// /// + /// According to the Petitjean definition, the eccentricity of a vertex corresponds to + /// the distance from that vertex to the most remote vertex in the graph. + /// The distance is obtained from the distance matrix as the count of edges between the two vertices. + /// If r(i) is the largest matrix entry in row i of the distance matrix D, then the radius is defined as the smallest of the r(i). + /// The graph diameter D is defined as the largest vertex eccentricity in the graph. + /// (http://www.edusoft-lc.com/molconn/manuals/400/chaptwo.html) /// This descriptor uses these parameters: /// /// @@ -61,25 +62,15 @@ public class PetitjeanNumberDescriptor : AbstractMolecularDescriptor, IMolecular { private static readonly string[] NAMES = { "PetitjeanNumber" }; - /// - /// Constructor for the PetitjeanNumberDescriptor object - /// public PetitjeanNumberDescriptor() { } - /// - /// The specification attribute of the PetitjeanNumberDescriptor object - /// public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = new DescriptorSpecification( "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#petitjeanNumber", typeof(PetitjeanNumberDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the PetitjeanNumberDescriptor object - /// public override IReadOnlyList Parameters { get { return null; } set { } } - public override IReadOnlyList DescriptorNames => NAMES; /// @@ -104,16 +95,7 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(0.0); - /// - /// The parameterNames attribute of the PetitjeanNumberDescriptor object - /// public override IReadOnlyList ParameterNames => null; - - /// - /// The parameterType attribute of the PetitjeanNumberDescriptor object - /// - /// - /// public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs index c54dbb60..05979965 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/PetitjeanShapeIndexDescriptor.cs @@ -30,7 +30,7 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// Evaluates the Petitjean shape indices, + /// Evaluates the Petitjean shape indices. /// /// /// These original Petitjean number was described by Petitjean (cdk-cite-PET92) diff --git a/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs index 0b3a8223..c56a0348 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/RotatableBondsCountDescriptor.cs @@ -27,10 +27,11 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// The number of rotatable bonds is given by the SMARTS specified by Daylight on - /// SMARTS tutorial + /// Evaluates rotatable bonds count. /// /// + /// The number of rotatable bonds is given by the SMARTS specified by Daylight on + /// SMARTS tutorial /// This descriptor uses these parameters: /// /// @@ -64,9 +65,6 @@ public class RotatableBondsCountDescriptor : AbstractMolecularDescriptor, IMolec private bool includeTerminals = false; private bool excludeAmides = false; - /// - /// Constructor for the RotatableBondsCountDescriptor object - /// public RotatableBondsCountDescriptor() { } /// @@ -78,10 +76,6 @@ public RotatableBondsCountDescriptor() { } "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#rotatableBondsCount", typeof(RotatableBondsCountDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the RotatableBondsCountDescriptor object - /// - /// public override IReadOnlyList Parameters { set @@ -108,8 +102,8 @@ public override IReadOnlyList Parameters public override IReadOnlyList DescriptorNames => new string[] { includeTerminals ? "nRotBt" : "nRotB" }; /// - /// The method calculates the number of rotatable bonds of an atom container. - /// If the bool parameter is set to true, terminal bonds are included. + /// The method calculates the number of rotatable bonds of an atom container. + /// If the boolean parameter is set to , terminal bonds are included. /// /// AtomContainer /// number of rotatable bonds @@ -181,13 +175,11 @@ public DescriptorValue> Calculate(IAtomContainer ac) /// /// Only the most common constitution is considered. Tautomeric, O\C(*)=N\*, /// and charged forms, [O-]\C(*)=N\*, are ignored. - /// + /// /// the first bonding partner /// the second bonding partner /// the parent container - /// /// if both partners are involved in an amide C-N bond - /// private static bool IsAmide(IAtom atom0, IAtom atom1, IAtomContainer ac) { if (atom0.Symbol.Equals("C", StringComparison.Ordinal) && atom1.Symbol.Equals("N", StringComparison.Ordinal)) @@ -216,16 +208,7 @@ private static int GetConnectedHCount(IAtomContainer atomContainer, IAtom atom) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - /// - /// The parameterNames attribute of the RotatableBondsCountDescriptor object - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "includeTerminals", "excludeAmides" }; - - /// - /// Gets the parameterType attribute of the RotatableBondsCountDescriptor object - /// - /// - /// public override object GetParameterType(string name) => true; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs index 840ea83c..a5f7024a 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/RuleOfFiveDescriptor.cs @@ -58,9 +58,6 @@ public class RuleOfFiveDescriptor : AbstractMolecularDescriptor, IMolecularDescr private static readonly string[] NAMES = { "LipinskiFailures" }; - /// - /// Constructor for the RuleOfFiveDescriptor object. - /// public RuleOfFiveDescriptor() { } /// @@ -72,12 +69,12 @@ public RuleOfFiveDescriptor() { } "The Chemistry Development Kit"); /// - /// The parameters attribute of the RuleOfFiveDescriptor object. + /// The parameters attribute of the RuleOfFiveDescriptor object. /// /// - /// There is only one parameter, which should be a bool indicating whether - /// aromaticity should be checked or has already been checked. The name of the paramete - /// is checkAromaticity. + /// There is only one parameter, which should be a bool indicating whether + /// aromaticity should be checked or has already been checked. The name of the paramete + /// is checkAromaticity. /// if more than 1 parameter or a non-bool parameter is specified public override IReadOnlyList Parameters { @@ -104,8 +101,8 @@ public override IReadOnlyList Parameters public override IReadOnlyList DescriptorNames => NAMES; /// - /// the method take a bool checkAromaticity: if the bool is true, it means that - /// aromaticity has to be checked. + /// the method take a bool checkAromaticity: if the bool is true, it means that + /// aromaticity has to be checked. /// /// AtomContainer for which this descriptor is to be calculated /// The number of failures of the Lipinski rule @@ -180,16 +177,7 @@ public DescriptorValue> Calculate(IAtomContainer mol) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(1); - /// - /// Gets the parameterNames attribute of the RuleOfFiveDescriptor object. - /// public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity" }; - - /// - /// Gets the parameterType attribute of the RuleOfFiveDescriptor object. - /// - /// The name of the parameter. In this case it is 'checkAromaticity'. - /// An Object of class equal to that of the parameter being requested public override object GetParameterType(string name) { return true; diff --git a/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs index 5ae07bb3..582d0e52 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/SmallRingDescriptor.cs @@ -76,41 +76,17 @@ public SmallRingDescriptor() typeof(SmallRingDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// parameters: empty array, there are none. - /// public override IReadOnlyList Parameters { set { } get { return Array.Empty(); } } - /// - /// The names of the descriptors made available by this class. - /// public override IReadOnlyList DescriptorNames => NAMES; - - /// - /// A placeholder with the descriptor size and type. - /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(NAMES.Length); - - /// - /// parameters: empty, there are none. - /// public override IReadOnlyList ParameterNames => Array.Empty(); - - /// - /// Parameter types: there aren't any. - /// public override object GetParameterType(string name) => true; - /// - /// Performs the calculation: the graph will be analyzed and ring information will be determined and wrapped - /// up into descriptors. - /// - /// the atoms and bonds that make up the molecular object - /// the various ring-based descriptors generated public DescriptorValue> Calculate(IAtomContainer mol) { this.mol = mol; diff --git a/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs index 1fde522c..b8a7baf6 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/TPSADescriptor.cs @@ -132,10 +132,6 @@ public TPSADescriptor() } } - /// - /// Gets the specification attribute of the TPSADescriptor object. - /// - /// The specification value public override IImplementationSpecification Specification => specification; private static readonly DescriptorSpecification specification = new DescriptorSpecification( @@ -145,11 +141,12 @@ public TPSADescriptor() /// /// The parameters attribute of the object. - /// + /// + /// /// The descriptor takes a bool parameter to indicate whether /// the descriptor routine should check for aromaticity () or - /// not (). - /// + /// not (). + /// public override IReadOnlyList Parameters { set @@ -315,17 +312,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(0.0); - /// - /// Gets the parameterNames attribute of the TPSADescriptor object. - /// - /// The parameterNames value + /// public override IReadOnlyList ParameterNames { get; } = new string[] { "checkAromaticity" }; - /// - /// Gets the parameterType attribute of the TPSADescriptor object. - /// - /// Description of the Parameter - /// The parameterType value + /// public override object GetParameterType(string name) => true; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs index 94acf471..45ab3c5b 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/VABCDescriptor.cs @@ -89,7 +89,6 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(); - /// public override IReadOnlyList ParameterNames { get; } = Array.Empty(); @@ -99,3 +98,4 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); } } + diff --git a/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs index 5cd3c36f..ffa212cd 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/VAdjMaDescriptor.cs @@ -24,8 +24,8 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// Vertex adjacency information (magnitude): - /// 1 + log2 m where m is the number of heavy-heavy bonds. If m is zero, then zero is returned. + /// Vertex adjacency information (magnitude): + /// 1 + log2 m where m is the number of heavy-heavy bonds. If m is zero, then zero is returned. /// (definition from MOE tutorial on line) /// /// @@ -69,18 +69,11 @@ public VAdjMaDescriptor() { } typeof(VAdjMaDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// Tthe parameters attribute of the VAdjMaDescriptor object - /// + /// public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; - /// - /// Calculates the VAdjMa descriptor for an atom container - /// - /// AtomContainer - /// VAdjMa public DescriptorValue> Calculate(IAtomContainer atomContainer) { int n = 0; // count all heavy atom - heavy atom bonds @@ -103,16 +96,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(0.0); - /// - /// The parameterNames attribute of the VAdjMaDescriptor object - /// + /// public override IReadOnlyList ParameterNames => null; - /// - /// Gets the parameterType attribute of the VAdjMaDescriptor object - /// - /// - /// + /// public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs index d088b9ec..1cbaf5dc 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WHIMDescriptor.cs @@ -224,13 +224,7 @@ public WHIMDescriptor() typeof(WHIMDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the WHIMDescriptor object. - /// The new parameter values. The Object array should have a single element - /// which should be a string. The possible values of this string are: unity, - /// mass, volume, eneg, polar - /// - /// if the parameters are of the wrong type + /// public override IReadOnlyList Parameters { set @@ -274,16 +268,10 @@ public override IReadOnlyList DescriptorNames } } - /// - /// The parameterNames attribute of the WHIMDescriptor object. - /// + /// public override IReadOnlyList ParameterNames { get; } = new string[] { "type" }; - /// - /// Gets the parameterType attribute of the WHIMDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value + /// public override object GetParameterType(string name) => ""; private DescriptorValue> GetDummyDescriptorValue(Exception e) diff --git a/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs index aa07d6d9..cea8f2bc 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WeightDescriptor.cs @@ -25,15 +25,15 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// - /// IDescriptor based on the weight of atoms of a certain element type. + /// Evaluates the weight of atoms of a certain element type. /// /// - /// - /// If the wild-card symbol * - /// is specified, the returned value is the molecular weight. - /// If an invalid element symbol is specified, the return value is - /// 0 and no exception is thrown - /// + /// + /// If the wild-card symbol * + /// is specified, the returned value is the molecular weight. + /// If an invalid element symbol is specified, the return value is + /// 0 and no exception is thrown + /// /// This descriptor uses these parameters: /// /// @@ -74,10 +74,7 @@ public WeightDescriptor() { } typeof(WeightDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the WeightDescriptor object. - /// - /// if more than 1 parameter is specified or if the parameter is not of type string + /// public override IReadOnlyList Parameters { set @@ -192,16 +189,10 @@ public DescriptorValue> Calculate(IAtomContainer container) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(0.0); - /// - /// The parameterNames attribute of the WeightDescriptor object. - /// + /// public override IReadOnlyList ParameterNames { get; } = new string[] { "elementSymbol" }; - /// - /// Gets the parameterType attribute of the WeightDescriptor object. - /// - /// Description of the Parameter - /// An Object whose class is that of the parameter requested + /// public override object GetParameterType(string name) => ""; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs index 52685ea5..bb1382ce 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WeightedPathDescriptor.cs @@ -79,23 +79,16 @@ public WeightedPathDescriptor() { } typeof(WeightedPathDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the WeightedPathDescriptor object. - /// + /// public override IReadOnlyList Parameters { get { return null; } set { } } + /// public override IReadOnlyList DescriptorNames => NAMES; - /// - /// The parameterNames attribute of the WeightedPathDescriptor object. - /// + /// public override IReadOnlyList ParameterNames => null; - /// - /// Gets the parameterType attribute of the WeightedPathDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value + /// public override object GetParameterType(string name) => null; /// diff --git a/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs index 49115c9c..7bc440c1 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/WienerNumbersDescriptor.cs @@ -65,11 +65,9 @@ public class WienerNumbersDescriptor : AbstractMolecularDescriptor, IMolecularDe double[][] matr = null; ArrayResult wienerNumbers = null; - /// - /// Constructor for the WienerNumbersDescriptor object. - /// public WienerNumbersDescriptor() - { } + { + } /// public override IImplementationSpecification Specification => specification; @@ -79,9 +77,7 @@ public WienerNumbersDescriptor() typeof(WienerNumbersDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the WienerNumbersDescriptor object. - /// + /// public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames { get; } = new string[] { "WPATH", "WPOL" }; @@ -132,17 +128,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContain /// public override IDescriptorResult DescriptorResultType { get; } = new ArrayResult(2); - /// - /// The parameterNames attribute of the WienerNumbersDescriptor object. - /// This descriptor does not return any parameters - /// + /// public override IReadOnlyList ParameterNames => null; - /// - /// Gets the parameterType attribute of the WienerNumbersDescriptor object. - /// - /// Description of the Parameter - /// An Object of class equal to that of the parameter being requested + /// public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs index bf436fef..62de9faa 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/XLogPDescriptor.cs @@ -37,11 +37,11 @@ namespace NCDK.QSAR.Descriptors.Moleculars { /// /// Prediction of logP based on the atom-type method called XLogP. + /// + /// /// Requires all hydrogens to be explicit. /// For description of the methodology see Ref. cdk-cite-WANG97 and cdk-cite-WANG00. /// Actually one molecular factor is missing (presence of para Hs donor pair). - /// - /// /// This descriptor uses these parameters: /// /// @@ -109,9 +109,6 @@ public class XLogPDescriptor : AbstractMolecularDescriptor, IMolecularDescriptor private bool salicylFlag = false; private static readonly string[] NAMES = { "XLogP" }; - /// - /// Constructor for the XLogPDescriptor object. - /// public XLogPDescriptor() { } /// @@ -124,10 +121,7 @@ public XLogPDescriptor() { } typeof(XLogPDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the XLogPDescriptor object. - /// - /// + /// public override IReadOnlyList Parameters { set diff --git a/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs index 11052821..745f0387 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/ZagrebIndexDescriptor.cs @@ -37,9 +37,6 @@ public class ZagrebIndexDescriptor : AbstractMolecularDescriptor, IMolecularDesc { private static readonly string[] NAMES = { "Zagreb" }; - /// - /// Constructor for the ZagrebIndexDescriptor object. - /// public ZagrebIndexDescriptor() { } /// @@ -52,15 +49,13 @@ public ZagrebIndexDescriptor() { } typeof(ZagrebIndexDescriptor).FullName, "The Chemistry Development Kit"); - /// - /// The parameters attribute of the ZagrebIndexDescriptor object. - /// + /// public override IReadOnlyList Parameters { get { return null; } set { } } public override IReadOnlyList DescriptorNames => NAMES; /// - /// Evaluate the Zagreb Index for a molecule. + /// Evaluate the Zagreb Index for a molecule. /// /// AtomContainer /// zagreb index @@ -87,16 +82,10 @@ public DescriptorValue> Calculate(IAtomContainer atomContainer) /// public override IDescriptorResult DescriptorResultType { get; } = new Result(0.0); - /// - /// The parameterNames attribute of the ZagrebIndexDescriptor object. - /// + /// public override IReadOnlyList ParameterNames => null; - /// - /// The parameterType attribute of the ZagrebIndexDescriptor object. - /// - /// Description of the Parameter - /// The parameterType value + /// public override object GetParameterType(string name) => null; IDescriptorValue IMolecularDescriptor.Calculate(IAtomContainer container) => Calculate(container); diff --git a/NCDK/QSAR/IDescriptor.cs b/NCDK/QSAR/IDescriptor.cs index 470a0849..92f66643 100644 --- a/NCDK/QSAR/IDescriptor.cs +++ b/NCDK/QSAR/IDescriptor.cs @@ -157,7 +157,7 @@ public interface IDescriptor /// /// /// Note that by default if a descriptor returns a single value - /// (such as + /// (such as /// the return array will have a single element /// /// diff --git a/NCDKTests/IO/InChIPlainTextReaderTest.cs b/NCDKTests/IO/InChIPlainTextReaderTest.cs index d8f64d87..c506aa60 100644 --- a/NCDKTests/IO/InChIPlainTextReaderTest.cs +++ b/NCDKTests/IO/InChIPlainTextReaderTest.cs @@ -19,7 +19,8 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ + */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Silent; using System; diff --git a/NCDKTests/IO/InChIReaderTest.cs b/NCDKTests/IO/InChIReaderTest.cs index 7eb428e0..5c1bb942 100644 --- a/NCDKTests/IO/InChIReaderTest.cs +++ b/NCDKTests/IO/InChIReaderTest.cs @@ -19,7 +19,8 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ + */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Silent; using System; diff --git a/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs index 09bf890e..a556ff44 100644 --- a/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Moleculars/ALOGPDescriptorTest.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using Microsoft.VisualStudio.TestTools.UnitTesting; using NCDK.Silent; using NCDK.QSAR.Results; @@ -29,13 +30,13 @@ namespace NCDK.QSAR.Descriptors.Moleculars /// // @cdk.module test-qsarmolecular [TestClass()] - public class ALOGPDescriptorTest : MolecularDescriptorTest + public class ALogPDescriptorTest : MolecularDescriptorTest { - private CDKHydrogenAdder hydrogenAdder; + private readonly CDKHydrogenAdder hydrogenAdder; - public ALOGPDescriptorTest() + public ALogPDescriptorTest() { - SetDescriptor(typeof(ALOGPDescriptor)); + SetDescriptor(typeof(ALogPDescriptor)); hydrogenAdder = CDKHydrogenAdder.GetInstance(ChemObjectBuilder.Instance); } From 6eee681e70abdb998460a17c4b4d9015fa210e7d Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Sun, 23 Sep 2018 15:10:40 +0900 Subject: [PATCH 6/8] Rollback LonePairElectronChecker class --- NCDK/CDK.cs | 23 +++++- .../Atomic/IPAtomicHOSEDescriptor.cs | 2 +- .../Atomic/PartialPiChargeDescriptor.cs | 2 +- .../Atomic/PartialTChargePEOEDescriptor.cs | 2 +- .../Atomic/PiElectronegativityDescriptor.cs | 2 +- .../Atomic/ProtonAffinityHOSEDescriptor.cs | 6 +- .../Bonds/BondPartialPiChargeDescriptor.cs | 2 +- .../Bonds/BondPartialTChargeDescriptor.cs | 2 +- .../Descriptors/Moleculars/BCUTDescriptor.cs | 2 +- .../SingleStructureRandomGenerator.cs | 2 +- .../PartialFilledStructureMerger.cs | 4 +- NCDK/Tools/IDeduceBondOrderTool.cs | 6 +- NCDK/Tools/IValencyChecker.cs | 15 +++- NCDK/Tools/LonePairElectronChecker.cs | 70 ++++++++-------- NCDK/Tools/SaturationChecker.cs | 77 +++++++----------- NCDKTests/AtomTypes/ReactionStructuresTest.cs | 2 +- NCDKTests/Charges/ElectronegativityTest.cs | 4 +- .../GasteigerMarsiliPartialChargesTest.cs | 8 +- .../GasteigerPEPEPartialChargesTest.cs | 14 ++-- NCDKTests/Charges/PiElectronegativityTest.cs | 4 +- NCDKTests/Charges/StabilizationChargesTest.cs | 2 +- .../ConjugatedPiSystemsDetectorTest.cs | 16 ++-- .../AtomHybridizationVSEPRDescriptorTest.cs | 4 +- .../Atomic/IPAtomicHOSEDescriptorTest.cs | 40 +++++----- .../Atomic/PartialPiChargeDescriptorTest.cs | 36 ++++----- .../PartialSigmaChargeDescriptorTest.cs | 22 ++--- .../PartialTChargePEOEDescriptorTest.cs | 12 +-- .../PiElectronegativityDescriptorTest.cs | 28 +++---- .../ProtonAffinityHOSEDescriptorTest.cs | 4 +- .../SigmaElectronegativityDescriptorTest.cs | 4 +- .../StabilizationPlusChargeDescriptorTest.cs | 16 ++-- .../Bonds/BondPartialTChargeDescriptorTest.cs | 4 +- ...ondSigmaElectronegativityDescriptorTest.cs | 2 +- .../Types/AdductionProtonLPReactionTest.cs | 4 +- .../Types/AdductionProtonPBReactionTest.cs | 4 +- .../Types/AdductionSodiumLPReactionTest.cs | 4 +- .../Types/CarbonylEliminationReactionTest.cs | 2 +- .../Types/ElectronImpactNBEReactionTest.cs | 18 ++--- .../Types/ElectronImpactPDBReactionTest.cs | 2 +- .../HeterolyticCleavagePBReactionTest.cs | 26 +++--- .../HeterolyticCleavageSBReactionTest.cs | 28 +++---- .../Types/HomolyticCleavageReactionTest.cs | 56 ++++++------- .../Types/RearrangementAnionReactionTest.cs | 6 +- .../RearrangementLonePairReactionTest.cs | 8 +- .../Types/SharingAnionReactionTest.cs | 8 +- .../Types/SharingChargeDBReactionTest.cs | 4 +- .../Types/SharingChargeSBReactionTest.cs | 16 ++-- .../Types/SharingLonePairReactionTest.cs | 4 +- .../PartialFilledStructureMergerTest.cs | 10 +-- .../Tools/LonePairElectronCheckerTest.cs | 20 ++--- NCDKTests/Tools/SaturationCheckerTest.cs | 4 +- .../Tools/StructureResonanceGeneratorTest.cs | 80 +++++++++---------- 52 files changed, 379 insertions(+), 364 deletions(-) diff --git a/NCDK/CDK.cs b/NCDK/CDK.cs index e286f285..8e757a93 100644 --- a/NCDK/CDK.cs +++ b/NCDK/CDK.cs @@ -36,6 +36,27 @@ public static class CDK /// The library version public static string Version => typeof(CDK).Assembly.GetName().Version.ToString(); - internal static Smiles.SmilesParser SilentSmilesParser { get; } = new Smiles.SmilesParser(Silent.ChemObjectBuilder.Instance); + private static Smiles.SmilesParser silentSmilesParser = null; + internal static Smiles.SmilesParser SilentSmilesParser + { + get + { + if (silentSmilesParser == null) + silentSmilesParser = new Smiles.SmilesParser(Silent.ChemObjectBuilder.Instance); + return silentSmilesParser; + } + } + + private static Tools.ILonePairElectronChecker lonePairElectronChecker; + + internal static Tools.ILonePairElectronChecker LonePairElectronChecker + { + get + { + if (lonePairElectronChecker == null) + lonePairElectronChecker = new Tools.LonePairElectronChecker(); + return lonePairElectronChecker; + } + } } } diff --git a/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs index af8fee25..c133727e 100644 --- a/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptor.cs @@ -113,7 +113,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - LonePairElectronChecker.Saturate(container); + CDK.LonePairElectronChecker.Saturate(container); } catch (CDKException e) { diff --git a/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs index db6eb3c1..dae01fbe 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PartialPiChargeDescriptor.cs @@ -172,7 +172,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) { try { - LonePairElectronChecker.Saturate(ac); + CDK.LonePairElectronChecker.Saturate(ac); } catch (CDKException e) { diff --git a/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs index 6f5d63ff..c61c04ef 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptor.cs @@ -149,7 +149,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) { try { - LonePairElectronChecker.Saturate(ac); + CDK.LonePairElectronChecker.Saturate(ac); } catch (CDKException e) { diff --git a/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs index 239e417c..a3a319fc 100644 --- a/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/PiElectronegativityDescriptor.cs @@ -136,7 +136,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer atom AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(clone); if (lpeChecker) { - LonePairElectronChecker.Saturate(atomContainer); + CDK.LonePairElectronChecker.Saturate(atomContainer); } localAtom = clone.Atoms[atomContainer.Atoms.IndexOf(atom)]; } diff --git a/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs index 4c7b5625..f8620896 100644 --- a/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptor.cs @@ -100,7 +100,7 @@ public DescriptorValue> Calculate(IAtom atom, IAtomContainer cont atom = container.Atoms[i]; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); - LonePairElectronChecker.Saturate(container); + CDK.LonePairElectronChecker.Saturate(container); } catch (CDKException) { @@ -151,8 +151,8 @@ class Affinitydb { ProtonAffinityHOSEDescriptor parent; - Dictionary> listGroup = new Dictionary>(); - Dictionary> listGroupS = new Dictionary>(); + readonly Dictionary> listGroup = new Dictionary>(); + readonly Dictionary> listGroupS = new Dictionary>(); /// /// The constructor of the IPdb. diff --git a/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs index a08dd055..3faaf0e2 100644 --- a/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/BondPartialPiChargeDescriptor.cs @@ -158,7 +158,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); if (lpeChecker) { - LonePairElectronChecker.Saturate(ac); + CDK.LonePairElectronChecker.Saturate(ac); } } catch (CDKException e) diff --git a/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs b/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs index 43b8803c..c145da06 100644 --- a/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptor.cs @@ -151,7 +151,7 @@ public DescriptorValue> Calculate(IBond bond, IAtomContainer ac) AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); if (lpeChecker) { - LonePairElectronChecker.Saturate(ac); + CDK.LonePairElectronChecker.Saturate(ac); } } catch (CDKException e) diff --git a/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs b/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs index 95ad33c7..1b858808 100644 --- a/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Moleculars/BCUTDescriptor.cs @@ -392,7 +392,7 @@ public DescriptorValue> Calculate(IAtomContainer container) GasteigerMarsiliPartialCharges peoe; try { - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); var charges = new double[molecule.Atoms.Count]; peoe = new GasteigerMarsiliPartialCharges(); peoe.AssignGasteigerMarsiliSigmaPartialCharges(molecule, true); diff --git a/NCDK/StructGen/SingleStructureRandomGenerator.cs b/NCDK/StructGen/SingleStructureRandomGenerator.cs index 6e8725d6..4cf530de 100644 --- a/NCDK/StructGen/SingleStructureRandomGenerator.cs +++ b/NCDK/StructGen/SingleStructureRandomGenerator.cs @@ -119,7 +119,7 @@ public IAtomContainer Generate() } } } while (bondFormed); - if (ConnectivityChecker.IsConnected(atomContainer) && satCheck.AllSaturated(atomContainer)) + if (ConnectivityChecker.IsConnected(atomContainer) && satCheck.IsSaturated(atomContainer)) { structureFound = true; } diff --git a/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs b/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs index 135d4348..5c44ed19 100644 --- a/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs +++ b/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs @@ -121,12 +121,12 @@ internal IAtomContainer Generate2(IChemObjectSet atomContainers) } } while (bondFormed); if (atomContainers.Count == 1 - && satCheck.AllSaturated(atomContainers[0])) + && satCheck.IsSaturated(atomContainers[0])) { structureFound = true; } } while (!structureFound && iteration < 5); - if (atomContainers.Count == 1 && satCheck.AllSaturated(atomContainers[0])) + if (atomContainers.Count == 1 && satCheck.IsSaturated(atomContainers[0])) { structureFound = true; } diff --git a/NCDK/Tools/IDeduceBondOrderTool.cs b/NCDK/Tools/IDeduceBondOrderTool.cs index d55b841d..a1f15be3 100644 --- a/NCDK/Tools/IDeduceBondOrderTool.cs +++ b/NCDK/Tools/IDeduceBondOrderTool.cs @@ -34,6 +34,10 @@ namespace NCDK.Tools // @cdk.githash public interface IDeduceBondOrderTool { - void Saturate(IAtomContainer ac); + /// + /// Saturates a molecule by setting. + /// + /// Atom container to saturate + void Saturate(IAtomContainer container); } } diff --git a/NCDK/Tools/IValencyChecker.cs b/NCDK/Tools/IValencyChecker.cs index 30e294f1..e0395da5 100644 --- a/NCDK/Tools/IValencyChecker.cs +++ b/NCDK/Tools/IValencyChecker.cs @@ -33,7 +33,20 @@ namespace NCDK.Tools // @cdk.githash public interface IValencyChecker { - bool IsSaturated(IAtomContainer ac); + /// + /// Determines of all atoms on are saturated. + /// + /// Atom container to check + /// , if it's right saturated + bool IsSaturated(IAtomContainer container); + + /// + /// Checks if in is saturated + /// by comparing it with known atom types. + /// + /// Atom to check + /// Atom container to check + /// , if it's right saturated bool IsSaturated(IAtom atom, IAtomContainer container); } } diff --git a/NCDK/Tools/LonePairElectronChecker.cs b/NCDK/Tools/LonePairElectronChecker.cs index 2642478c..fe5a9566 100644 --- a/NCDK/Tools/LonePairElectronChecker.cs +++ b/NCDK/Tools/LonePairElectronChecker.cs @@ -24,6 +24,19 @@ namespace NCDK.Tools { + /// + /// Provides methods for checking whether an atoms lone pair electrons are saturated + /// with respect to a particular atom type. + /// + public interface ILonePairElectronChecker + : IValencyChecker, IDeduceBondOrderTool + { + /// + /// Saturates in by adding the appropriate number lone pairs. + /// + void Saturate(IAtom atom, IAtomContainer container); + } + /// /// Provides methods for checking whether an atoms lone pair electrons are saturated /// with respect to a particular atom type. @@ -34,54 +47,41 @@ namespace NCDK.Tools // @cdk.keyword saturation // @cdk.keyword atom, valency // @cdk.module standard - public static class LonePairElectronChecker + public class LonePairElectronChecker + : ILonePairElectronChecker { private static AtomTypeFactory factory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", Silent.ChemObjectBuilder.Instance); - /// - /// Determines of all atoms on the AtomContainer have the - /// right number the lone pair electrons. - /// - public static bool IsSaturated(IAtomContainer container) + public LonePairElectronChecker() { - return AllSaturated(container); } - /// - /// Determines of all atoms on the AtomContainer have - /// the right number the lone pair electrons. - /// - public static bool AllSaturated(IAtomContainer ac) + /// + public bool IsSaturated(IAtomContainer ac) { Debug.WriteLine("Are all atoms saturated?"); - for (int f = 0; f < ac.Atoms.Count; f++) + foreach (var atom in ac.Atoms) { - if (!IsSaturated(ac.Atoms[f], ac)) + if (!IsSaturated(atom, ac)) return false; } return true; } - /// - /// Checks if an Atom is saturated their lone pair electrons - /// by comparing it with known AtomTypes. - /// - /// True, if it's right saturated - public static bool IsSaturated(IAtom atom, IAtomContainer ac) + /// + public bool IsSaturated(IAtom atom, IAtomContainer ac) { - IAtomType atomType = factory.GetAtomType(atom.AtomTypeName); - int lpCount = atomType.GetProperty(CDKPropertyName.LonePairCount); - int foundLPCount = ac.GetConnectedLonePairs(atom).Count(); + var atomType = factory.GetAtomType(atom.AtomTypeName); + var lpCount = atomType.GetProperty(CDKPropertyName.LonePairCount); + var foundLPCount = ac.GetConnectedLonePairs(atom).Count(); return foundLPCount >= lpCount; } - /// - /// Saturates a molecule by setting appropriate number lone pair electrons. - /// - public static void Saturate(IAtomContainer atomContainer) + /// + public void Saturate(IAtomContainer atomContainer) { Trace.TraceInformation("Saturating atomContainer by adjusting lone pair electrons..."); - bool allSaturated = AllSaturated(atomContainer); + var allSaturated = IsSaturated(atomContainer); if (!allSaturated) { for (int i = 0; i < atomContainer.Atoms.Count; i++) @@ -91,19 +91,17 @@ public static void Saturate(IAtomContainer atomContainer) } } - /// - /// Saturates an IAtom by adding the appropriate number lone pairs. - /// - public static void Saturate(IAtom atom, IAtomContainer ac) + /// + public void Saturate(IAtom atom, IAtomContainer ac) { Trace.TraceInformation("Saturating atom by adjusting lone pair electrons..."); - IAtomType atomType = factory.GetAtomType(atom.AtomTypeName); - int lpCount = atomType.GetProperty(CDKPropertyName.LonePairCount); - int missingLPs = lpCount - ac.GetConnectedLonePairs(atom).Count(); + var atomType = factory.GetAtomType(atom.AtomTypeName); + var lpCount = atomType.GetProperty(CDKPropertyName.LonePairCount); + var missingLPs = lpCount - ac.GetConnectedLonePairs(atom).Count(); for (int j = 0; j < missingLPs; j++) { - ILonePair lp = atom.Builder.NewLonePair(atom); + var lp = atom.Builder.NewLonePair(atom); ac.LonePairs.Add(lp); } } diff --git a/NCDK/Tools/SaturationChecker.cs b/NCDK/Tools/SaturationChecker.cs index a1ff221a..ab3a3fc0 100644 --- a/NCDK/Tools/SaturationChecker.cs +++ b/NCDK/Tools/SaturationChecker.cs @@ -49,35 +49,15 @@ namespace NCDK.Tools // @cdk.githash public class SaturationChecker : IValencyChecker, IDeduceBondOrderTool { - AtomTypeFactory structgenATF; - - /// - /// - /// the ChemObjectBuilder implementation used to construct the AtomType's. - protected AtomTypeFactory GetAtomTypeFactory(IChemObjectBuilder builder) - { - if (structgenATF == null) - { - try - { - structgenATF = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", - builder); - } - catch (Exception exception) - { - Debug.WriteLine(exception); - throw new CDKException("Could not instantiate AtomTypeFactory!", exception); - } - } - return structgenATF; - } + private static readonly AtomTypeFactory structgenATF = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", Silent.ChemObjectBuilder.Instance); public bool HasPerfectConfiguration(IAtom atom, IAtomContainer ac) { - double bondOrderSum = ac.GetBondOrderSum(atom); - BondOrder maxBondOrder = ac.GetMaximumBondOrder(atom); - var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); - if (!atomTypes.Any()) return true; + var bondOrderSum = ac.GetBondOrderSum(atom); + var maxBondOrder = ac.GetMaximumBondOrder(atom); + var atomTypes = structgenATF.GetAtomTypes(atom.Symbol); + if (!atomTypes.Any()) + return true; Debug.WriteLine("*** Checking for perfect configuration ***"); try { @@ -115,12 +95,7 @@ public bool HasPerfectConfiguration(IAtom atom, IAtomContainer ac) /// /// Determines of all atoms on the AtomContainer are saturated. /// - public bool IsSaturated(IAtomContainer container) - { - return AllSaturated(container); - } - - public bool AllSaturated(IAtomContainer ac) + public bool IsSaturated(IAtomContainer ac) { Debug.WriteLine("Are all atoms saturated?"); for (int f = 0; f < ac.Atoms.Count; f++) @@ -168,7 +143,7 @@ public bool IsSaturated(IBond bond, IAtomContainer atomContainer) /// public bool IsSaturated(IAtom atom, IAtomContainer ac) { - var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); + var atomTypes = structgenATF.GetAtomTypes(atom.Symbol); if (!atomTypes.Any()) return true; double bondOrderSum = 0; @@ -216,7 +191,7 @@ public bool IsSaturated(IAtom atom, IAtomContainer ac) /// oversaturated or not public bool IsOverSaturated(IAtom atom, IAtomContainer ac) { - var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); + var atomTypes = structgenATF.GetAtomTypes(atom.Symbol); if (!atomTypes.Any()) return false; var bondOrderSum = ac.GetBondOrderSum(atom); @@ -253,7 +228,7 @@ public bool IsOverSaturated(IAtom atom, IAtomContainer ac) /// the currently maximum bond order for this atom public double GetCurrentMaxBondOrder(IAtom atom, IAtomContainer ac) { - var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); + var atomTypes = structgenATF.GetAtomTypes(atom.Symbol); if (!atomTypes.Any()) return 0; var bondOrderSum = ac.GetBondOrderSum(atom); @@ -299,7 +274,7 @@ private static void UnsaturateBonds(IAtomContainer container) public void NewSaturate(IAtomContainer atomContainer) { Trace.TraceInformation("Saturating atomContainer by adjusting bond orders..."); - bool allSaturated = AllSaturated(atomContainer); + bool allSaturated = IsSaturated(atomContainer); if (!allSaturated) { var bonds = new IBond[atomContainer.Bonds.Count]; @@ -308,12 +283,14 @@ public void NewSaturate(IAtomContainer atomContainer) var succeeded = NewSaturate(bonds, atomContainer); for (int i = 0; i < bonds.Length; i++) { - if (bonds[i].Order == BondOrder.Double && bonds[i].IsAromatic - && (bonds[i].Begin.Symbol.Equals("N", StringComparison.Ordinal) - && bonds[i].End.Symbol.Equals("N", StringComparison.Ordinal))) + if (bonds[i].Order == BondOrder.Double + && bonds[i].IsAromatic + && bonds[i].Begin.Symbol.Equals("N", StringComparison.Ordinal) + && bonds[i].End.Symbol.Equals("N", StringComparison.Ordinal)) { int atomtohandle = 0; - if (string.Equals(bonds[i].Begin.Symbol, "N", StringComparison.Ordinal)) atomtohandle = 1; + if (string.Equals(bonds[i].Begin.Symbol, "N", StringComparison.Ordinal)) + atomtohandle = 1; var bondstohandle = atomContainer.GetConnectedBonds(bonds[i].Atoms[atomtohandle]); foreach (var bond in bondstohandle) { @@ -437,8 +414,8 @@ public bool NewSaturate(IBond bond, IAtomContainer atomContainer) var atom = atoms[0]; var partner = atoms[1]; Debug.WriteLine($" saturating bond: {atom.Symbol}-{partner.Symbol}"); - var atomTypes1 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(atom.Symbol); - var atomTypes2 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(partner.Symbol); + var atomTypes1 = structgenATF.GetAtomTypes(atom.Symbol); + var atomTypes2 = structgenATF.GetAtomTypes(partner.Symbol); bool bondOrderIncreased = true; while (bondOrderIncreased && !IsSaturated(bond, atomContainer)) { @@ -446,14 +423,16 @@ public bool NewSaturate(IBond bond, IAtomContainer atomContainer) bondOrderIncreased = false; foreach (var aType1 in atomTypes1) { - if (bondOrderIncreased) break; + if (bondOrderIncreased) + break; Debug.WriteLine($" considering atom type: {aType1}"); if (CouldMatchAtomType(atomContainer, atom, aType1)) { Debug.WriteLine($" trying atom type: {aType1}"); foreach (var aType2 in atomTypes2) { - if (bondOrderIncreased) break; + if (bondOrderIncreased) + break; Debug.WriteLine($" considering partner type: {aType1}"); if (CouldMatchAtomType(atomContainer, partner, aType2)) { @@ -497,7 +476,7 @@ private static bool CouldMatchAtomType(IAtomContainer atomContainer, IAtom atom, /// The method is known to fail for certain compounds. For more information, see /// cdk.test.limitations package. /// This method is known to fail, especially on pyrrole-like compounds. - /// Consider using import org.openscience.cdk.smiles.DeduceBondSystemTool, which should work better + /// Consider using , which should work better /// public void Saturate(IAtomContainer atomContainer) { @@ -508,7 +487,7 @@ public void Saturate(IAtomContainer atomContainer) { var atom = atomContainer.Atoms[f]; Debug.WriteLine($"symbol: {atom.Symbol}"); - var atomTypes1 = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); + var atomTypes1 = structgenATF.GetAtomTypes(atom.Symbol); var atomType1 = atomTypes1.FirstOrDefault(); if (atomType1 != null) { @@ -523,7 +502,7 @@ public void Saturate(IAtomContainer atomContainer) foreach (var partner in partners) { Debug.WriteLine($"Atom has {partners.Count()} partners"); - var atomType2 = GetAtomTypeFactory(atom.Builder).GetAtomTypes(partner.Symbol).FirstOrDefault(); + var atomType2 = structgenATF.GetAtomTypes(partner.Symbol).FirstOrDefault(); if (atomType2 == null) return; @@ -552,7 +531,7 @@ public void Saturate(IAtomContainer atomContainer) foreach (var partner in partners) { Debug.WriteLine("Atom has " + partners.Count() + " partners"); - var atomType2 = GetAtomTypeFactory(atom.Builder).GetAtomTypes(partner.Symbol).FirstOrDefault(); + var atomType2 = structgenATF.GetAtomTypes(partner.Symbol).FirstOrDefault(); if (atomType2 == null) return; @@ -651,7 +630,7 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, d { Trace.TraceInformation("Calculating number of missing hydrogen atoms"); // get default atom - var defaultAtom = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol).FirstOrDefault(); + var defaultAtom = structgenATF.GetAtomTypes(atom.Symbol).FirstOrDefault(); if (defaultAtom == null && throwExceptionForUnknowAtom) return 0; if (defaultAtom != null) diff --git a/NCDKTests/AtomTypes/ReactionStructuresTest.cs b/NCDKTests/AtomTypes/ReactionStructuresTest.cs index 8639b661..2c3abb03 100644 --- a/NCDKTests/AtomTypes/ReactionStructuresTest.cs +++ b/NCDKTests/AtomTypes/ReactionStructuresTest.cs @@ -726,7 +726,7 @@ public void TestM26() expected1.AddBond(expected1.Atoms[6], expected1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(expected1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); string[] expectedTypes = { "F.plus.sp2", "C.sp2", "C.minus.planar", "C.sp2", "C.sp2", "C.sp2", "C.sp2", "H", "H", "H", "H", "H" }; Assert.AreEqual(expectedTypes.Length, expected1.Atoms.Count); diff --git a/NCDKTests/Charges/ElectronegativityTest.cs b/NCDKTests/Charges/ElectronegativityTest.cs index edb60d37..14d398b1 100644 --- a/NCDKTests/Charges/ElectronegativityTest.cs +++ b/NCDKTests/Charges/ElectronegativityTest.cs @@ -60,7 +60,7 @@ public void TestCalculateSigmaElectronegativity_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) Assert.AreEqual(testResult[i], pe.CalculateSigmaElectronegativity(molecule, molecule.Atoms[i]), 0.001); @@ -80,7 +80,7 @@ public void TestCalculateSigmaElectronegativity_IAtomContainer_IAtom_Int_Int() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs b/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs index d0979f44..211ee286 100644 --- a/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs +++ b/NCDKTests/Charges/GasteigerMarsiliPartialChargesTest.cs @@ -54,7 +54,7 @@ public void TestCalculateCharges_IAtomContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); peoe.CalculateCharges(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -78,7 +78,7 @@ public void TestAssignGasteigerMarsiliSigmaPartialCharges_IAtomContainer_Boolean AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); peoe.AssignGasteigerMarsiliSigmaPartialCharges(molecule, true); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -102,7 +102,7 @@ public void TestAssignGasteigerSigmaMarsiliFactors_IAtomContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); foreach (var atom in molecule.Atoms) atom.Charge = 0.0; @@ -192,7 +192,7 @@ public void TestUndefinedPartialCharge() AddExplicitHydrogens(ac); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(ac); - LonePairElectronChecker.Saturate(ac); + CDK.LonePairElectronChecker.Saturate(ac); GasteigerMarsiliPartialCharges peoe = new GasteigerMarsiliPartialCharges(); peoe.CalculateCharges(ac); diff --git a/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs b/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs index 4120bbb9..46d56bfc 100644 --- a/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs +++ b/NCDKTests/Charges/GasteigerPEPEPartialChargesTest.cs @@ -53,7 +53,7 @@ public void TestCalculateCharges_IAtomContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); peoe.CalculateCharges(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -76,7 +76,7 @@ public void TestAromaticBondOrders() Aromaticity.CDKLegacy.Apply(mol1); AddExplicitHydrogens(mol1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); - LonePairElectronChecker.Saturate(mol1); + CDK.LonePairElectronChecker.Saturate(mol1); List oldBondOrders = new List(); for (int i = 0; i < mol1.Bonds.Count; i++) @@ -112,11 +112,11 @@ public void TestAromaticAndNonAromatic() AddExplicitHydrogens(mol1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); - LonePairElectronChecker.Saturate(mol1); + CDK.LonePairElectronChecker.Saturate(mol1); AddExplicitHydrogens(mol2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); - LonePairElectronChecker.Saturate(mol2); + CDK.LonePairElectronChecker.Saturate(mol2); peoe.CalculateCharges(mol1); peoe.CalculateCharges(mol2); @@ -140,7 +140,7 @@ public void TestAssignGasteigerPiPartialCharges_IAtomContainer_Boolean() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); peoe.AssignGasteigerPiPartialCharges(molecule, true); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -212,7 +212,7 @@ public void TestAssignrPiMarsilliFactors_IAtomContainerSet() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); foreach (var atom in molecule.Atoms) atom.Charge = 0; @@ -222,7 +222,7 @@ public void TestAssignrPiMarsilliFactors_IAtomContainerSet() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.IsNotNull(peoe.AssignrPiMarsilliFactors(set)); } diff --git a/NCDKTests/Charges/PiElectronegativityTest.cs b/NCDKTests/Charges/PiElectronegativityTest.cs index c4e51641..7ec8a06b 100644 --- a/NCDKTests/Charges/PiElectronegativityTest.cs +++ b/NCDKTests/Charges/PiElectronegativityTest.cs @@ -60,7 +60,7 @@ public void TestCalculatePiElectronegativity_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -84,7 +84,7 @@ public void TestCalculatePiElectronegativity_IAtomContainer_IAtom_Int_Int() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/Charges/StabilizationChargesTest.cs b/NCDKTests/Charges/StabilizationChargesTest.cs index 9b335461..ffd1bef8 100644 --- a/NCDKTests/Charges/StabilizationChargesTest.cs +++ b/NCDKTests/Charges/StabilizationChargesTest.cs @@ -51,7 +51,7 @@ public void TestCalculatePositive_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs b/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs index f3dd96ac..b3390778 100644 --- a/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs +++ b/NCDKTests/Graphs/Invariant/ConjugatedPiSystemsDetectorTest.cs @@ -263,7 +263,7 @@ public void TestAceticAcid() mol = (new SmilesParser(builder)).ParseSmiles("CC(=O)O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -297,7 +297,7 @@ public void TestNN_dimethylaniline_cation() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -315,7 +315,7 @@ public void Test1_fluorobutadienene() IAtomContainer mol = (new SmilesParser(builder)).ParseSmiles("FC=CC=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -335,7 +335,7 @@ public void TestEthyne_difluoro() mol = (new SmilesParser(builder)).ParseSmiles("FC#CF"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -375,7 +375,7 @@ public void Test3Aminomethane_cation() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -420,7 +420,7 @@ public void TestCyanoallene() mol = (new SmilesParser(builder)).ParseSmiles("C=C=CC#N"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -449,7 +449,7 @@ public void TestChargeWithProtonExplicit() SmilesParser sp = new SmilesParser(builder); IAtomContainer mol = sp.ParseSmiles("[H]C([H])=C([H])[C+]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); @@ -477,7 +477,7 @@ public void TestChargeWithProtonImplicit() SmilesParser sp = new SmilesParser(builder); IAtomContainer mol = sp.ParseSmiles("C=C[C+]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs index 27726b6d..46fd0cc5 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/AtomHybridizationVSEPRDescriptorTest.cs @@ -240,7 +240,7 @@ public void TestAtomHybridizationVSEPRDescriptorTest_7() AssertAtomTypesPerceived(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); AssertAtomTypesPerceived(mol); for (int i = 0; i < 3; i++) @@ -272,7 +272,7 @@ public void TestAtomHybridizationVSEPRDescriptorTest_8() AssertAtomTypesPerceived(mol); AddImplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); AssertAtomTypesPerceived(mol); for (int i = 0; i < 3; i++) diff --git a/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs index 814a9b53..5c7311fd 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/IPAtomicHOSEDescriptorTest.cs @@ -61,7 +61,7 @@ public void TestIPDescriptor1() IAtomContainer mol = sp.ParseSmiles("CCCCl"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[3], mol).Value).Value; double resultAccordingNIST = 10.8; @@ -79,7 +79,7 @@ public void TestIPDescriptor2() IAtomContainer mol = sp.ParseSmiles("CC(CC)Cl"); // not in db AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[4], mol).Value).Value; double resultAccordingNIST = 10.57; //value for CC(C)Cl @@ -97,7 +97,7 @@ public void TestNotDB() IAtomContainer mol = sp.ParseSmiles("C=CCCl"); // not in db AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[3], mol).Value).Value; double resultAccordingNIST = 10.8; //value for CCCCl aprox. @@ -115,7 +115,7 @@ public void TestIPDescriptor_1() IAtomContainer mol = sp.ParseSmiles("C-Cl"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value).Value; double resultAccordingNIST = 11.26; @@ -133,7 +133,7 @@ public void TestIPDescriptor_2() IAtomContainer mol = sp.ParseSmiles("C-C-Br"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[2], mol).Value).Value; double resultAccordingNIST = 11.29; @@ -150,7 +150,7 @@ public void TestIPDescriptor_3() IAtomContainer mol = sp.ParseSmiles("C-C-C-I"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[3], mol).Value).Value; double resultAccordingNIST = 9.27; @@ -169,7 +169,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2], mol).GetValue()).Value; // double resultAccordingNIST = 10.48; @@ -188,7 +188,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0], mol).GetValue()).Value; // double resultAccordingNIST = 7.77; @@ -207,7 +207,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[1],mol).GetValue()).Value; // double resultAccordingNIST = 8.24; @@ -226,7 +226,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2],mol).GetValue()).Value; // double resultAccordingNIST = 8.9; @@ -245,7 +245,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2], mol).GetValue()).Value; // double resultAccordingNIST = 8.5; @@ -265,7 +265,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0], mol).GetValue()).Value; // double resultAccordingNIST = 9.3; @@ -284,7 +284,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0],mol).GetValue()).Value; // double resultAccordingNIST = 9.01; @@ -304,7 +304,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[2], mol).GetValue()).Value; //// Assert.IsNotNull(result); @@ -330,7 +330,7 @@ public void TestIPDescriptor_3() // AddExplicitHydrogens(mol); // AreEqual(10, mol.Atoms.Count); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // AreEqual("Unexpected number of lone pairs", 1, mol.GetLonePairCount()); // // AreEqual("N", mol.Atoms[2].Symbol); @@ -362,7 +362,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // descriptor.Calculate(mol.Atoms[0], mol); // IReactionSet reactionSet = descriptor.ReactionSet; @@ -387,7 +387,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0],mol).GetValue()).Value; // double resultAccordingNIST = 8.03; @@ -414,7 +414,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[0],mol).GetValue()).Value; // double resultAccordingNIST = 8.64; @@ -441,7 +441,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // double result= ((Result)descriptor.Calculate(mol.Atoms[5],mol).GetValue()).Value; // double resultAccordingNIST = 7.77; @@ -469,7 +469,7 @@ public void TestIPDescriptor_3() // // AddExplicitHydrogens(mol); // - // LonePairElectronChecker.Saturate(mol); + // CDK.LonePairElectronChecker.Saturate(mol); // // descriptor.Calculate(mol.Atoms[0],mol); // diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs index a1b1ed3f..dedee933 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PartialPiChargeDescriptorTest.cs @@ -59,7 +59,7 @@ public void TestPartialPiChargeDescriptor_Methyl_Fluoride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -99,7 +99,7 @@ public void TestPartialPiChargeDescriptor_Fluoroethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -138,7 +138,7 @@ public void TestPartialPiChargeDescriptor_FormicAcid() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -185,7 +185,7 @@ public void TestPartialPiChargeDescriptor_Fluorobenzene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -227,7 +227,7 @@ public void TestPartialPiChargeDescriptor_Methoxyethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 4/* mol.Atoms.Count */; i++) { @@ -274,7 +274,7 @@ public void TestPartialPiChargeDescriptor_1_Methoxybutadiene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -320,7 +320,7 @@ public void TestPartialPiChargeDescriptoCharge_1() IAtomContainer mol = sp.ParseSmiles("F[C+]([H])[C-]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 6; i++) { @@ -367,7 +367,7 @@ public void TestPartialPiChargeDescriptoCharge_2() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -398,7 +398,7 @@ public void TestPartialPiChargeDescriptoCharge_3() SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C([H])[C+]([H])[C-]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -433,7 +433,7 @@ public void TestPartialPiChargeDescripto4() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -456,7 +456,7 @@ public void TestArticle1() AddExplicitHydrogens(mol); descriptor.Parameters = new object[] { 6, true }; - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -519,7 +519,7 @@ public void TestSousa() AddExplicitHydrogens(mol); descriptor.Parameters = new object[] { 6, true }; - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -554,7 +554,7 @@ public void TestBondNotConjugated() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); descriptor.Parameters = new object[] { 6, true }; - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -584,12 +584,12 @@ public void TestDifferentStarts() IAtomContainer mol1 = sp.ParseSmiles("C=CCC=O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); AddExplicitHydrogens(mol1); - LonePairElectronChecker.Saturate(mol1); + CDK.LonePairElectronChecker.Saturate(mol1); IAtomContainer mol2 = sp.ParseSmiles("O=CCC=C"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); AddExplicitHydrogens(mol2); - LonePairElectronChecker.Saturate(mol2); + CDK.LonePairElectronChecker.Saturate(mol2); IAtomicDescriptor descriptor1 = new PartialPiChargeDescriptor(); IAtomicDescriptor descriptor2 = new PartialPiChargeDescriptor(); @@ -621,7 +621,7 @@ public void TestBondNotConjugated1() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); descriptor.Parameters = new object[] { 6, true }; - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -653,7 +653,7 @@ public void TestBondNotConjugated2() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); descriptor.Parameters = new object[] { 6, true }; - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -684,7 +684,7 @@ public void TestLangCalculation() IAtomContainer mol = sp.ParseSmiles("c1ccc(cc1)N3c4ccccc4(c2ccccc23)"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); descriptor.Parameters = new object[] { 6, true }; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs index 0ea3d50c..08100383 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PartialSigmaChargeDescriptorTest.cs @@ -65,7 +65,7 @@ public void TestPartialSigmaChargeDescriptor_Fluoroethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -90,7 +90,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_Floride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); AddExplicitHydrogens(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -117,7 +117,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_chloride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -143,7 +143,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_bromide() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -168,7 +168,7 @@ public void TestPartialSigmaChargeDescriptor_Methyl_iodide() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -197,7 +197,7 @@ public void TestPartialSigmaChargeDescriptor_Allyl_bromide() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); double result = ((Result)descriptor.Calculate(molecule.Atoms[3], molecule).Value).Value; Assert.AreEqual(testResult, result, 0.01); @@ -246,7 +246,7 @@ public void TestPartialSigmaChargeDescriptor_Ethoxy_ethane() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); double result = ((Result)descriptor.Calculate(molecule.Atoms[2], molecule).Value).Value; Assert.AreEqual(testResult, result, 0.01); @@ -272,7 +272,7 @@ public void TestPartialSigmaChargeDescriptor_Ethanolamine() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 4; i++) { @@ -301,7 +301,7 @@ public void TestPartialSigmaChargeDescriptor_Allyl_mercaptan() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 4; i++) { @@ -373,7 +373,7 @@ public void TestPartialSigmaChargeDescriptor4() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -404,7 +404,7 @@ public void TestPartialSigmaChargeDescriptor5() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); descriptor.Parameters = new object[] { 6 }; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs index 1d500e08..3ef08811 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PartialTChargePEOEDescriptorTest.cs @@ -58,7 +58,7 @@ public void TestPartialTChargeDescriptor_Methyl_Fluoride() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); AddExplicitHydrogens(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) @@ -85,7 +85,7 @@ public void TestPartialTChargeDescriptor_Fluoroethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -116,7 +116,7 @@ public void TestPartialTChargeDescriptor_FormicAcid() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -156,7 +156,7 @@ public void TestPartialTChargeDescriptor_Fluorobenzene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < 5; i++) { @@ -189,7 +189,7 @@ public void TestPartialTChargeDescriptor_Methoxyethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { @@ -227,7 +227,7 @@ public void TestPartialTChargeDescriptor_1_Methoxybutadiene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); AddExplicitHydrogens(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); for (int i = 0; i < molecule.Atoms.Count; i++) { diff --git a/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs index 2dff5f42..4d915b06 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/PiElectronegativityDescriptorTest.cs @@ -56,7 +56,7 @@ public void TestPiElectronegativityDescriptor_Methyl_Fluoride() IAtomContainer mol = sp.ParseSmiles("FC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -87,7 +87,7 @@ public void TestPiElectronegativityDescriptor_Methyl_Chloride() IAtomContainer mol = sp.ParseSmiles("ClC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -117,7 +117,7 @@ public void TestPiElectronegativityDescriptor_Methyl_Iodide() IAtomContainer mol = sp.ParseSmiles("IC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -147,7 +147,7 @@ public void TestPiElectronegativityDescriptor_Methyl_Bromide() IAtomContainer mol = sp.ParseSmiles("BrC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -177,7 +177,7 @@ public void TestPiElectronegativityDescriptor_Methyl_Alcohol() IAtomContainer mol = sp.ParseSmiles("OC"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 4; i++) { @@ -207,7 +207,7 @@ public void TestPiElectronegativityDescriptor_Formaldehyde() IAtomContainer mol = sp.ParseSmiles("C=O"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -240,7 +240,7 @@ public void TestPiElectronegativityDescriptor_Ethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 3; i++) { double result = ((Result)descriptor.Calculate(mol.Atoms[i], mol).Value).Value; @@ -271,7 +271,7 @@ public void TestPiElectronegativityDescriptor_Fluoroethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 3; i++) { @@ -303,7 +303,7 @@ public void TestPiElectronegativityDescriptor_FormicAcid() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -335,7 +335,7 @@ public void TestPiElectronegativityDescriptor_Methoxyethylene() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -367,7 +367,7 @@ public void TestPiElectronegativity1() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -402,7 +402,7 @@ public void TestPiElectronegativity2() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < mol.Atoms.Count; i++) { @@ -437,7 +437,7 @@ public void TestCompareIonized() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molA); AddExplicitHydrogens(molA); - LonePairElectronChecker.Saturate(molA); + CDK.LonePairElectronChecker.Saturate(molA); double resultA = ((Result)descriptor.Calculate(molA.Atoms[3], molA).Value).Value; @@ -456,7 +456,7 @@ public void TestCompareIonized() AddExplicitHydrogens(molB); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molB); - LonePairElectronChecker.Saturate(molB); + CDK.LonePairElectronChecker.Saturate(molB); Assert.AreEqual(1, molB.Atoms[3].FormalCharge.Value, 0.00001); Assert.AreEqual(1, molB.SingleElectrons.Count, 0.00001); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs index 2ca14f73..11dbd3b1 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/ProtonAffinityHOSEDescriptorTest.cs @@ -69,7 +69,7 @@ public void TestAffinityDescriptor1() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[6], mol).Value).Value; double resultAccordingNIST = 753.1; @@ -90,7 +90,7 @@ public void TestAffinityDescriptor2() AddExplicitHydrogens(mol); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); double result = ((Result)descriptor.Calculate(mol.Atoms[2], mol).Value).Value; double resultAccordingNIST = 693.4; diff --git a/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs index c2c52c0d..f18a373a 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/SigmaElectronegativityDescriptorTest.cs @@ -198,7 +198,7 @@ public void TestCompareIonized() AddExplicitHydrogens(molA); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molA); - LonePairElectronChecker.Saturate(molA); + CDK.LonePairElectronChecker.Saturate(molA); double resultA = ((Result)descriptor.Calculate(molA.Atoms[3], molA).Value).Value; @@ -217,7 +217,7 @@ public void TestCompareIonized() AddExplicitHydrogens(molB); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molB); - LonePairElectronChecker.Saturate(molB); + CDK.LonePairElectronChecker.Saturate(molB); Assert.AreEqual(1, molB.Atoms[3].FormalCharge.Value, 0.00001); Assert.AreEqual(1, molB.SingleElectrons.Count, 0.00001); diff --git a/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs index 19cf0fcf..2e3a86a1 100644 --- a/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Atomic/StabilizationPlusChargeDescriptorTest.cs @@ -53,7 +53,7 @@ public void TestStabilizationPlusChargeDescriptor() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Result result = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value); @@ -74,7 +74,7 @@ public void TestNotCharged() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Result result = ((Result)descriptor.Calculate(mol.Atoms[0], mol).Value); @@ -96,7 +96,7 @@ public void TestStabilizationPlusChargeDescriptor2() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Result result = ((Result)descriptor.Calculate(mol.Atoms[1], mol).Value); @@ -118,7 +118,7 @@ public void TestStabilizationComparative() mol1.AddBond(mol1.Atoms[1], mol1.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol1); AddExplicitHydrogens(mol1); - LonePairElectronChecker.Saturate(mol1); + CDK.LonePairElectronChecker.Saturate(mol1); Result result1 = ((Result)descriptor.Calculate(mol1.Atoms[1], mol1).Value); @@ -131,7 +131,7 @@ public void TestStabilizationComparative() mol2.AddBond(mol2.Atoms[1], mol2.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol2); AddExplicitHydrogens(mol2); - LonePairElectronChecker.Saturate(mol2); + CDK.LonePairElectronChecker.Saturate(mol2); Result result2 = ((Result)descriptor.Calculate(mol2.Atoms[1], mol2).Value); @@ -144,7 +144,7 @@ public void TestStabilizationComparative() mol3.AddBond(mol3.Atoms[1], mol3.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol3); AddExplicitHydrogens(mol3); - LonePairElectronChecker.Saturate(mol3); + CDK.LonePairElectronChecker.Saturate(mol3); Result result3 = ((Result)descriptor.Calculate(mol3.Atoms[1], mol3).Value); @@ -171,7 +171,7 @@ public void TestCompareIonized() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molA); AddExplicitHydrogens(molA); - LonePairElectronChecker.Saturate(molA); + CDK.LonePairElectronChecker.Saturate(molA); double resultA = ((Result)descriptor.Calculate(molA.Atoms[3], molA).Value).Value; @@ -190,7 +190,7 @@ public void TestCompareIonized() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molB); AddExplicitHydrogens(molB); - LonePairElectronChecker.Saturate(molB); + CDK.LonePairElectronChecker.Saturate(molB); Assert.AreEqual(1, molB.Atoms[3].FormalCharge.Value, 0.00001); Assert.AreEqual(1, molB.SingleElectrons.Count, 0.00001); diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs index fa90d4e0..d285f25a 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondPartialTChargeDescriptorTest.cs @@ -50,7 +50,7 @@ public void TestBondTElectronegativityDescriptor() AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 2; i++) { @@ -71,7 +71,7 @@ public void TestBondTElectronegativityDescriptor_Allyl_bromide() IAtomContainer mol = sp.ParseSmiles("C=CCBr"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 8; i++) { diff --git a/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs b/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs index e3b0867e..7ed8b560 100644 --- a/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs +++ b/NCDKTests/QSAR/Descriptors/Bonds/BondSigmaElectronegativityDescriptorTest.cs @@ -48,7 +48,7 @@ public void TestBondSigmaElectronegativityDescriptor() IAtomContainer mol = sp.ParseSmiles("CF"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); AddExplicitHydrogens(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); for (int i = 0; i < 2; i++) { diff --git a/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs b/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs index f44f4566..531343f2 100644 --- a/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs +++ b/NCDKTests/Reactions/Types/AdductionProtonLPReactionTest.cs @@ -210,7 +210,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -247,7 +247,7 @@ private IChemObjectSet GetExpectedProducts() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs b/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs index 2d8619d9..b11568c9 100644 --- a/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs +++ b/NCDKTests/Reactions/Types/AdductionProtonPBReactionTest.cs @@ -210,7 +210,7 @@ private IChemObjectSet GetExampleReactants() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -246,7 +246,7 @@ private IChemObjectSet GetExpectedProducts() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs b/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs index e481fef0..62bcd793 100644 --- a/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs +++ b/NCDKTests/Reactions/Types/AdductionSodiumLPReactionTest.cs @@ -217,7 +217,7 @@ private IChemObjectSet GetExampleReactants() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -254,7 +254,7 @@ private IChemObjectSet GetExpectedProducts() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs b/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs index e677bf7d..2c2bba62 100644 --- a/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs +++ b/NCDKTests/Reactions/Types/CarbonylEliminationReactionTest.cs @@ -202,7 +202,7 @@ private IChemObjectSet GetExampleReactants() { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } catch (CDKException e) diff --git a/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs b/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs index c8b052b1..e0e7d053 100644 --- a/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs +++ b/NCDKTests/Reactions/Types/ElectronImpactNBEReactionTest.cs @@ -75,7 +75,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() reactant.AddBond(reactant.Atoms[5], reactant.Atoms[6], BondOrder.Single); AddExplicitHydrogens(reactant); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactant); - LonePairElectronChecker.Saturate(reactant); + CDK.LonePairElectronChecker.Saturate(reactant); foreach (var atom in reactant.Atoms) { @@ -135,7 +135,7 @@ public void TestAutomatic_Set_Active_Atom() reactant.AddBond(reactant.Atoms[5], reactant.Atoms[6], BondOrder.Single); AddExplicitHydrogens(reactant); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactant); - LonePairElectronChecker.Saturate(reactant); + CDK.LonePairElectronChecker.Saturate(reactant); var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(reactant); @@ -178,7 +178,7 @@ public void TestNsp3SingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[5], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; @@ -217,7 +217,7 @@ public void TestNsp3SingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); @@ -245,7 +245,7 @@ public void TestNsp2SingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; @@ -281,7 +281,7 @@ public void TestNsp2SingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); @@ -309,7 +309,7 @@ public void TestFspSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; @@ -345,7 +345,7 @@ public void TestFspSingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); @@ -445,7 +445,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } catch (CDKException e) diff --git a/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs b/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs index b0b1ce3e..2be7bc4a 100644 --- a/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs +++ b/NCDKTests/Reactions/Types/ElectronImpactPDBReactionTest.cs @@ -324,7 +324,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { diff --git a/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs b/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs index 955122b0..bff6df10 100644 --- a/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs +++ b/NCDKTests/Reactions/Types/HeterolyticCleavagePBReactionTest.cs @@ -126,7 +126,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -135,7 +135,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected1.Atoms[1].FormalCharge = -1; expected1.Atoms[2].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -218,7 +218,7 @@ public void TestCspDoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -227,7 +227,7 @@ public void TestCspDoubleB() expected1.Atoms[1].FormalCharge = -1; expected1.Atoms[2].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, expected1)); @@ -306,7 +306,7 @@ public void TestCspTripleB() expected1.Atoms[1].FormalCharge = -1; expected1.Atoms[2].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -338,7 +338,7 @@ public void TestNsp2DoubleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -381,7 +381,7 @@ public void TestNsp2DoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -403,7 +403,7 @@ public void TestNspTripleB() molecule.Atoms.Add(builder.NewAtom("H")); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -436,7 +436,7 @@ public void TestNspTripleB() expected1.Atoms.Add(builder.NewAtom("H")); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -460,7 +460,7 @@ public void TestOspDoubleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -495,7 +495,7 @@ public void TestOspDoubleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -520,7 +520,7 @@ public void TestCDKConstants_REACTIVE_CENTER() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); setOfReactants.Add(molecule); /* manually put the reactive center */ @@ -649,7 +649,7 @@ private IChemObjectSet GetExampleReactants() { AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs b/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs index 3bb5271b..ef52e584 100644 --- a/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs +++ b/NCDKTests/Reactions/Types/HeterolyticCleavageSBReactionTest.cs @@ -141,7 +141,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -249,7 +249,7 @@ public void TestCsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); @@ -258,7 +258,7 @@ public void TestCsp2SingleB() //CreateFromSmiles("C=[C-]") expected1.Atoms[1].FormalCharge = -1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[1].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -354,7 +354,7 @@ public void TestCspSingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[1].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -362,7 +362,7 @@ public void TestCspSingleB() //CreateFromSmiles("C#[C+]") expected1.Atoms[1].FormalCharge = +1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); product1 = setOfReactions[0].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -405,7 +405,7 @@ public void TestNsp3SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -443,7 +443,7 @@ public void TestNsp3SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -490,7 +490,7 @@ public void TestNsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -539,7 +539,7 @@ public void TestNsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -573,7 +573,7 @@ public void TestOsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -609,7 +609,7 @@ public void TestOsp2SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -650,7 +650,7 @@ public void TestFspSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -676,7 +676,7 @@ public void TestFspSingleB() expected1.Atoms.Add(builder.NewAtom("F")); expected1.Atoms[0].FormalCharge = -1; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -800,7 +800,7 @@ private IChemObjectSet GetExampleReactants() { AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } catch (Exception e) diff --git a/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs b/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs index 05e6ed04..992c58c6 100644 --- a/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs +++ b/NCDKTests/Reactions/Types/HomolyticCleavageReactionTest.cs @@ -139,7 +139,7 @@ public override void TestInitiate_IAtomContainerSet_IAtomContainerSet() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -223,7 +223,7 @@ public void TestCsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); @@ -300,7 +300,7 @@ public void TestCspSingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[1]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -379,7 +379,7 @@ public void TestCsp2DoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -449,7 +449,7 @@ public void TestCspDoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -556,7 +556,7 @@ public void TestNsp3SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -594,7 +594,7 @@ public void TestNsp3SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -648,7 +648,7 @@ public void TestNsp3ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[10], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -696,7 +696,7 @@ public void TestNsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -745,7 +745,7 @@ public void TestNsp2SingleB() expected2.AddBond(expected2.Atoms[0], expected2.Atoms[2], BondOrder.Single); expected2.AddBond(expected2.Atoms[0], expected2.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected2); - LonePairElectronChecker.Saturate(expected2); + CDK.LonePairElectronChecker.Saturate(expected2); IAtomContainer product2 = setOfReactions[0].Products[0]; queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected2); Assert.IsTrue(uiTester.IsIsomorph(product2, queryAtom)); @@ -780,7 +780,7 @@ public void TestNsp2ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -829,7 +829,7 @@ public void TestNsp2DoubleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[6], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -872,7 +872,7 @@ public void TestNsp2DoubleB() expected1.AddBond(expected1.Atoms[2], expected1.Atoms[6], BondOrder.Single); expected1.AddBond(expected1.Atoms[2], expected1.Atoms[7], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -906,7 +906,7 @@ public void TestNsp2ChargeDoubleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -944,7 +944,7 @@ public void TestNspTripleB() molecule.Atoms.Add(builder.NewAtom("H")); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -977,7 +977,7 @@ public void TestNspTripleB() expected1.Atoms.Add(builder.NewAtom("H")); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1001,7 +1001,7 @@ public void TestNspChargeTripleB() molecule.AddBond(molecule.Atoms[0], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1052,7 +1052,7 @@ public void TestOsp2SingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -1088,7 +1088,7 @@ public void TestOsp2SingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[0], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1140,7 +1140,7 @@ public void TestOsp2ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -1180,7 +1180,7 @@ public void TestOspDoubleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1215,7 +1215,7 @@ public void TestOspDoubleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[2], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[3], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1241,7 +1241,7 @@ public void TestOspChargeDoubleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1283,7 +1283,7 @@ public void TestFspSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1309,7 +1309,7 @@ public void TestFspSingleB() expected1.Atoms.Add(builder.NewAtom("F")); expected1.SingleElectrons.Add(builder.NewSingleElectron(expected1.Atoms[0])); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(uiTester.IsIsomorph(product1, queryAtom)); @@ -1431,7 +1431,7 @@ public void TestEthylbenzaldehydeManual() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1584,7 +1584,7 @@ public void TestEthylbenzaldehydeMapping() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -1659,7 +1659,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); MakeSureAtomTypesAreRecognized(molecule); } diff --git a/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs b/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs index b09f1d78..b11df9a4 100644 --- a/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs +++ b/NCDKTests/Reactions/Types/RearrangementAnionReactionTest.cs @@ -263,7 +263,7 @@ public void TestAutomaticSearchCentreActiveExample3() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); @@ -304,7 +304,7 @@ public void TestAutomaticSearchCentreActiveExample3() AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - LonePairElectronChecker.Saturate(molecule2); + CDK.LonePairElectronChecker.Saturate(molecule2); MakeSureAtomTypesAreRecognized(molecule2); IQueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(product1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule2, queryAtom)); @@ -332,7 +332,7 @@ public void TestAutomaticSearchCentreActiveExample3() AddExplicitHydrogens(molecule3); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule3); - LonePairElectronChecker.Saturate(molecule3); + CDK.LonePairElectronChecker.Saturate(molecule3); MakeSureAtomTypesAreRecognized(molecule3); queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(product2); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule3, queryAtom)); diff --git a/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs b/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs index 49b4162c..39fe6cfe 100644 --- a/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs +++ b/NCDKTests/Reactions/Types/RearrangementLonePairReactionTest.cs @@ -272,7 +272,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -308,7 +308,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) @@ -360,7 +360,7 @@ public void TestFluorobenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); IReactionProcess type = new RearrangementLonePairReaction(); @@ -398,7 +398,7 @@ public void TestFluorobenzene() molecule1.AddBond(molecule1.Atoms[6], molecule1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - LonePairElectronChecker.Saturate(molecule1); + CDK.LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, qAC)); diff --git a/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs b/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs index 1484007a..86ccce9f 100644 --- a/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingAnionReactionTest.cs @@ -140,7 +140,7 @@ public void TestCarbons() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); var setOfReactants = ChemObjectBuilder.Instance.NewAtomContainerSet(); setOfReactants.Add(molecule); @@ -165,7 +165,7 @@ public void TestCarbons() AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - LonePairElectronChecker.Saturate(molecule2); + CDK.LonePairElectronChecker.Saturate(molecule2); IQueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(product); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(molecule2, queryAtom)); @@ -273,7 +273,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -302,7 +302,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs b/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs index 9e589486..4b42731f 100644 --- a/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingChargeDBReactionTest.cs @@ -227,7 +227,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -258,7 +258,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs b/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs index a6d98e87..ca464474 100644 --- a/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingChargeSBReactionTest.cs @@ -247,7 +247,7 @@ private IChemObjectSet GetExampleReactants() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (CDKException e) { @@ -281,7 +281,7 @@ private IChemObjectSet GetExpectedProducts() try { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); } catch (CDKException e) { @@ -357,7 +357,7 @@ public void TestNsp3ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[9], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[10], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -396,7 +396,7 @@ public void TestNsp3ChargeSingleB() expected1.AddBond(expected1.Atoms[1], expected1.Atoms[5], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[6], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, queryAtom)); @@ -445,7 +445,7 @@ public void TestNsp2ChargeSingleB() molecule.AddBond(molecule.Atoms[2], molecule.Atoms[7], BondOrder.Single); molecule.AddBond(molecule.Atoms[2], molecule.Atoms[8], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[1].IsReactiveCenter = true; molecule.Atoms[2].IsReactiveCenter = true; @@ -480,7 +480,7 @@ public void TestNsp2ChargeSingleB() expected1.AddBond(expected1.Atoms[0], expected1.Atoms[3], BondOrder.Single); expected1.AddBond(expected1.Atoms[1], expected1.Atoms[4], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, queryAtom)); @@ -523,7 +523,7 @@ public void TestFspChargeSingleB() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[4], BondOrder.Single); molecule.AddBond(molecule.Atoms[1], molecule.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); molecule.Atoms[0].IsReactiveCenter = true; molecule.Atoms[1].IsReactiveCenter = true; @@ -550,7 +550,7 @@ public void TestFspChargeSingleB() expected1.Atoms.Add(builder.NewAtom("H")); expected1.AddBond(expected1.Atoms[0], expected1.Atoms[1], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(expected1); - LonePairElectronChecker.Saturate(expected1); + CDK.LonePairElectronChecker.Saturate(expected1); IAtomContainer product1 = setOfReactions[0].Products[0]; QueryAtomContainer queryAtom = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(expected1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(product1, queryAtom)); diff --git a/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs b/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs index 14b73ab0..1564d3fc 100644 --- a/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs +++ b/NCDKTests/Reactions/Types/SharingLonePairReactionTest.cs @@ -223,7 +223,7 @@ private IChemObjectSet GetExampleReactants() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { @@ -252,7 +252,7 @@ private IChemObjectSet GetExpectedProducts() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); } catch (Exception e) { diff --git a/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs b/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs index acd051ec..82303c3a 100644 --- a/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs +++ b/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs @@ -39,7 +39,7 @@ public void TestGenerate_IAtomContainerSet() var pfsm = new PartialFilledStructureMerger(); var result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().AllSaturated(result)); + Assert.IsTrue(new SaturationChecker().IsSaturated(result)); } [TestMethod()] @@ -52,7 +52,7 @@ public void TestPartialFilledStructureMerger2() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().AllSaturated(result)); + Assert.IsTrue(new SaturationChecker().IsSaturated(result)); } [TestMethod()] @@ -66,7 +66,7 @@ public void TestPartialFilledStructureMerger3() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().AllSaturated(result)); + Assert.IsTrue(new SaturationChecker().IsSaturated(result)); } [TestMethod()] @@ -80,7 +80,7 @@ public void TestPartialFilledStructureMerger4() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().AllSaturated(result)); + Assert.IsTrue(new SaturationChecker().IsSaturated(result)); } [TestMethod()] @@ -94,7 +94,7 @@ public void TestPartialFilledStructureMerger5() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().AllSaturated(result)); + Assert.IsTrue(new SaturationChecker().IsSaturated(result)); } } } diff --git a/NCDKTests/Tools/LonePairElectronCheckerTest.cs b/NCDKTests/Tools/LonePairElectronCheckerTest.cs index 38d0c572..271a44b6 100644 --- a/NCDKTests/Tools/LonePairElectronCheckerTest.cs +++ b/NCDKTests/Tools/LonePairElectronCheckerTest.cs @@ -59,7 +59,7 @@ public void TestAllSaturated_Formaldehyde() m.Bonds.Add(new Bond(c, O, BondOrder.Double)); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - Assert.IsTrue(LonePairElectronChecker.AllSaturated(m)); + Assert.IsTrue(CDK.LonePairElectronChecker.IsSaturated(m)); } [TestMethod()] @@ -82,7 +82,7 @@ public void TestAllSaturated_Methanethiol() } AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - Assert.IsFalse(LonePairElectronChecker.AllSaturated(m)); + Assert.IsFalse(CDK.LonePairElectronChecker.IsSaturated(m)); } [TestMethod()] @@ -99,7 +99,7 @@ public void TestNewSaturate_Methyl_chloride() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(3, m.GetConnectedLonePairs(cl).Count()); Assert.AreEqual(0, m.GetConnectedLonePairs(c1).Count()); } @@ -118,7 +118,7 @@ public void TestNewSaturate_Methyl_alcohol() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(2, m.GetConnectedLonePairs(o).Count()); Assert.AreEqual(0, m.GetConnectedLonePairs(c1).Count()); } @@ -139,7 +139,7 @@ public void TestNewSaturate_Methyl_alcohol_AddH() m.AddBond(m.Atoms[0], m.Atoms[4], BondOrder.Single); m.AddBond(m.Atoms[1], m.Atoms[5], BondOrder.Single); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(2, m.GetConnectedLonePairs(m.Atoms[1]).Count()); Assert.AreEqual(0, m.GetConnectedLonePairs(m.Atoms[0]).Count()); @@ -163,7 +163,7 @@ public void TestNewSaturate_Methyl_alcohol_protonated() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(1, m.GetConnectedLonePairs(o).Count()); } @@ -182,7 +182,7 @@ public void TestNewSaturate_methoxide_anion() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(3, m.GetConnectedLonePairs(o).Count()); } @@ -197,7 +197,7 @@ public void TestNewSaturate_Ammonia() m.Atoms.Add(n); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(1, m.GetConnectedLonePairs(n).Count()); } @@ -220,7 +220,7 @@ public void TestNewSaturate_methylamine_radical_cation() m.Bonds.Add(b1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); - LonePairElectronChecker.Saturate(m); + CDK.LonePairElectronChecker.Saturate(m); Assert.AreEqual(0, m.GetConnectedLonePairs(n).Count()); } @@ -235,7 +235,7 @@ public void TestNewSaturate_withHAdded() SmilesParser sp = new SmilesParser(ChemObjectBuilder.Instance); IAtomContainer mol = sp.ParseSmiles("O=C([H])[C+]([H])[C-]([H])[H]"); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); - LonePairElectronChecker.Saturate(mol); + CDK.LonePairElectronChecker.Saturate(mol); Assert.AreEqual(2, mol.GetConnectedLonePairs(mol.Atoms[0]).Count()); Assert.AreEqual(0, mol.GetConnectedLonePairs(mol.Atoms[3]).Count()); diff --git a/NCDKTests/Tools/SaturationCheckerTest.cs b/NCDKTests/Tools/SaturationCheckerTest.cs index 7bd5d5ff..7ae1a474 100644 --- a/NCDKTests/Tools/SaturationCheckerTest.cs +++ b/NCDKTests/Tools/SaturationCheckerTest.cs @@ -50,13 +50,13 @@ public void TestAllSaturated() m.Bonds.Add(new Bond(c, h2)); m.Bonds.Add(new Bond(c, h3)); m.Bonds.Add(new Bond(c, h4)); - Assert.IsTrue(satcheck.AllSaturated(m)); + Assert.IsTrue(satcheck.IsSaturated(m)); // test methane with implicit hydrogen m = new AtomContainer(); c = new Atom("C") { ImplicitHydrogenCount = 4 }; m.Atoms.Add(c); - Assert.IsTrue(satcheck.AllSaturated(m)); + Assert.IsTrue(satcheck.IsSaturated(m)); } [TestMethod()] diff --git a/NCDKTests/Tools/StructureResonanceGeneratorTest.cs b/NCDKTests/Tools/StructureResonanceGeneratorTest.cs index 03f8f186..1e906f30 100644 --- a/NCDKTests/Tools/StructureResonanceGeneratorTest.cs +++ b/NCDKTests/Tools/StructureResonanceGeneratorTest.cs @@ -155,7 +155,7 @@ public void TestSetReactions_List() // IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); // AddExplicitHydrogens(molecule); // AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - // LonePairElectronChecker.Saturate(molecule); + // CDK.LonePairElectronChecker.Saturate(molecule); // // IAtom atom = molecule.Atoms[2]; // molecule.SingleElectrons.Add(new SingleElectron(atom)); @@ -187,7 +187,7 @@ public void TestSetReactions_List() // molecule1.AddBond(molecule1.Atoms[0], molecule1.Atoms[6], BondOrder.Single); // molecule1.AddBond(molecule1.Atoms[0], molecule1.Atoms[7], BondOrder.Single); // molecule1.AddBond(molecule1.Atoms[3], molecule1.Atoms[8], BondOrder.Single); - // LonePairElectronChecker.Saturate(molecule1); + // CDK.LonePairElectronChecker.Saturate(molecule1); // IAtom atom1 = molecule1.Atoms[2]; // molecule1.SingleElectrons.Add(new SingleElectron(atom1)); // QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); @@ -201,7 +201,7 @@ public void TestSetReactions_List() //// molecule2.AddBond(molecule2.Atoms[0], molecule2.Atoms[6], BondOrder.Single); //// molecule2.AddBond(molecule2.Atoms[0], molecule2.Atoms[7], BondOrder.Single); //// molecule2.AddBond(molecule2.Atoms[3], molecule2.Atoms[8], BondOrder.Single); - //// LonePairElectronChecker.NewSaturate(molecule2); + //// CDK.LonePairElectronChecker.NewSaturate(molecule2); //// IAtom atom2a = molecule2.Atoms[2]; //// molecule2.AddElectronContainer(new SingleElectron(atom2a)); //// @@ -234,7 +234,7 @@ public void TestSetReactions_List() // IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); // AddExplicitHydrogens(molecule); // AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - // LonePairElectronChecker.Saturate(molecule); + // CDK.LonePairElectronChecker.Saturate(molecule); // // IAtom atom = molecule.Atoms[2]; // molecule.SingleElectrons.Add(new SingleElectron(atom)); @@ -250,7 +250,7 @@ public void TestSetReactions_List() // // IAtomContainer molecule1 = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CC(=O)C=O"); // AddExplicitHydrogens(molecule1); - // LonePairElectronChecker.Saturate(molecule1); + // CDK.LonePairElectronChecker.Saturate(molecule1); // IAtom atom1 = molecule1.Atoms[4]; // molecule1.SingleElectrons.Add(new SingleElectron(atom1)); // selectron = molecule1.GetConnectedLonePairsList(atom1); @@ -271,7 +271,7 @@ public void TestSetReactions_List() // IAtomContainer molecule = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CCC(=O)C(C)=O"); // AddExplicitHydrogens(molecule); // AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - // LonePairElectronChecker.Saturate(molecule); + // CDK.LonePairElectronChecker.Saturate(molecule); // // IAtom atom = molecule.Atoms[3]; // molecule.SingleElectrons.Add(new SingleElectron(atom)); @@ -287,7 +287,7 @@ public void TestSetReactions_List() // // IAtomContainer molecule1 = (new SmilesParser(ChemObjectBuilder.Instance)).ParseSmiles("CCC(=O)C(C)=O"); // AddExplicitHydrogens(molecule1); - // LonePairElectronChecker.Saturate(molecule1); + // CDK.LonePairElectronChecker.Saturate(molecule1); // // IAtom atom1 = molecule1.Atoms[6]; // molecule1.SingleElectrons.Add(new SingleElectron(atom1)); @@ -459,7 +459,7 @@ public void TestFormicAcid() molecule.AddBond(molecule.Atoms[0], molecule.Atoms[2], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gR = new StructureResonanceGenerator(); var reactionList = gR.Reactions.ToList(); @@ -479,7 +479,7 @@ public void TestFormicAcid() molecule2.AddBond(molecule2.Atoms[0], molecule2.Atoms[2], BondOrder.Double); AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - LonePairElectronChecker.Saturate(molecule2); + CDK.LonePairElectronChecker.Saturate(molecule2); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule2); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[1], qAC)); @@ -500,7 +500,7 @@ public void TestFluoroethene() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[2], BondOrder.Double); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gR = new StructureResonanceGenerator(); var setOfMolecules = gR.GetStructures(molecule); @@ -517,7 +517,7 @@ public void TestFluoroethene() molecule1.Atoms[2].FormalCharge = -1; AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - LonePairElectronChecker.Saturate(molecule1); + CDK.LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[1], qAC)); @@ -549,7 +549,7 @@ public void TestFluorobenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -575,7 +575,7 @@ public void TestFluorobenzene() molecule1.AddBond(molecule1.Atoms[6], molecule1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - LonePairElectronChecker.Saturate(molecule1); + CDK.LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[2], qAC)); @@ -599,7 +599,7 @@ public void TestFluorobenzene() molecule2.AddBond(molecule2.Atoms[6], molecule2.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - LonePairElectronChecker.Saturate(molecule2); + CDK.LonePairElectronChecker.Saturate(molecule2); IAtomContainer product2 = setOfMolecules[4]; qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule2); @@ -632,7 +632,7 @@ public void TestFluorobenzeneContainer() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); IAtomContainer container = gRI.GetContainer(molecule, molecule.Atoms[0]); @@ -666,7 +666,7 @@ public void TestFluorobenzene_symm() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(true); var setOfMolecules = gRI.GetStructures(molecule); @@ -692,7 +692,7 @@ public void TestFluorobenzene_symm() molecule1.AddBond(molecule1.Atoms[6], molecule1.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule1); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule1); - LonePairElectronChecker.Saturate(molecule1); + CDK.LonePairElectronChecker.Saturate(molecule1); QueryAtomContainer qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule1); Assert.IsTrue(new UniversalIsomorphismTester().IsIsomorph(setOfMolecules[1], qAC)); @@ -716,7 +716,7 @@ public void TestFluorobenzene_symm() molecule2.AddBond(molecule2.Atoms[6], molecule2.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule2); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule2); - LonePairElectronChecker.Saturate(molecule2); + CDK.LonePairElectronChecker.Saturate(molecule2); IAtomContainer product2 = setOfMolecules[2]; qAC = QueryAtomContainerCreator.CreateSymbolAndChargeQueryContainer(molecule2); @@ -749,7 +749,7 @@ public void TestAniline() molecule.AddBond(molecule.Atoms[6], molecule.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -781,7 +781,7 @@ public void TestAniline_Symm() molecule.AddBond(molecule.Atoms[6], molecule.Atoms[1], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(true); var setOfMolecules = gRI.GetStructures(molecule); @@ -809,7 +809,7 @@ public void TestAllyl() AddExplicitHydrogens(molecule); Assert.AreEqual(8, molecule.Atoms.Count); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var resonanceStructures = gRI.GetStructures(molecule); @@ -858,7 +858,7 @@ public void TestEthenolate() molecule.Atoms[0].FormalCharge = -1; AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(6, molecule.Atoms.Count); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); @@ -896,7 +896,7 @@ public void Test2Methylaniline() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[7], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(17, molecule.Atoms.Count); @@ -930,7 +930,7 @@ public void Test12DimethylBenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(18, molecule.Atoms.Count); @@ -972,7 +972,7 @@ public void TestPreservingAromaticity() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); bool isAromatic = Aromaticity.CDKLegacy.Apply(molecule); Assert.IsTrue(isAromatic, "Molecule is expected to be marked aromatic!"); @@ -1019,7 +1019,7 @@ public void TestCyclobutadiene() IAtomContainer molecule = TestMoleculeFactory.MakeCyclobutadiene(); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -1035,7 +1035,7 @@ public void TestBenzene() IAtomContainer molecule = TestMoleculeFactory.MakeBenzene(); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfMolecules = gRI.GetStructures(molecule); @@ -1060,7 +1060,7 @@ public void TestGetContainers_IAtomContainer() molecule.Atoms[0].FormalCharge = -1; AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.AreEqual(6, molecule.Atoms.Count); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); @@ -1104,7 +1104,7 @@ public void TestGetContainers2Groups() molecule.Atoms[7].FormalCharge = +1; AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); var setOfContainers = sRG.GetContainers(molecule); @@ -1154,7 +1154,7 @@ public void TestGetContainer_IAtomContainer_IAtom() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); IAtomContainer container = sRG.GetContainer(molecule, atom4); @@ -1201,7 +1201,7 @@ public void TestGetContainer_IAtomContainer_IBond() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); IAtomContainer container = sRG.GetContainer(molecule, molecule.Bonds[1]); @@ -1255,7 +1255,7 @@ public void TestGetID() molecule.AddBond(molecule.Atoms[6], molecule.Atoms[7], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator sRG = new StructureResonanceGenerator(); IAtomContainer container = sRG.GetContainer(molecule, atom4); @@ -1297,7 +1297,7 @@ public void TestGetContainersFluoromethylbenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1339,7 +1339,7 @@ public void TestGetContainersFluorobenzene() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1373,7 +1373,7 @@ public void Test1Propene2chloro() molecule.AddBond(molecule.Atoms[1], molecule.Atoms[3], BondOrder.Single); AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1410,7 +1410,7 @@ public void TestBenzene1bromo4methoxy() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1448,7 +1448,7 @@ public void TestBenzene1bromo4methoxy_with() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1502,7 +1502,7 @@ public void TestBenzylamine() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); StructureResonanceGenerator gRI = new StructureResonanceGenerator(); var setOfContainers = gRI.GetContainers(molecule); @@ -1539,7 +1539,7 @@ public void TestBenzylamine_Aromatic() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.IsTrue(Aromaticity.CDKLegacy.Apply(molecule)); @@ -1578,7 +1578,7 @@ public void TestBenzylamine_Aromatic_lookingSymmetry() AddExplicitHydrogens(molecule); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(molecule); - LonePairElectronChecker.Saturate(molecule); + CDK.LonePairElectronChecker.Saturate(molecule); Assert.IsTrue(Aromaticity.CDKLegacy.Apply(molecule)); From ece2a3dab71ad0a1a060b0b1b453de787eedf09e Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Mon, 24 Sep 2018 17:00:37 +0900 Subject: [PATCH 7/8] Assume many instances of AtomTypeFactory are Silent version. --- NCDK/Aromaticities/AtomTypeModel.cs | 2 +- NCDK/AtomTypes/CDKAtomTypeMatcher.cs | 4 +- NCDK/AtomTypes/StructGenAtomTypeGuesser.cs | 18 +-- NCDK/AtomTypes/StructGenMatcher.cs | 19 +-- NCDK/CDK.cs | 45 +++++++ NCDK/Charges/GasteigerPEPEPartialCharges.cs | 8 +- NCDK/Charges/InductivePartialCharges.cs | 11 +- NCDK/Geometries/Volume/VABCVolume.cs | 2 +- NCDK/IO/Mol2Reader.cs | 23 +--- NCDK/IO/PDBReader.cs | 116 +++++++++--------- .../Atomic/CovalentRadiusDescriptor.cs | 14 +-- .../InductiveAtomicHardnessDescriptor.cs | 19 +-- .../InductiveAtomicSoftnessDescriptor.cs | 14 +-- .../SingleStructureRandomGenerator.cs | 4 +- .../Stochastic/Operators/CrossoverMachine.cs | 2 +- .../PartialFilledStructureMerger.cs | 6 +- NCDK/Tools/AtomTypeAwareSaturationChecker.cs | 4 +- NCDK/Tools/CDKHydrogenAdder.cs | 20 ++- NCDK/Tools/CDKValencyChecker.cs | 17 ++- NCDK/Tools/DataFeatures.cs | 1 - NCDK/Tools/DataFeaturesTool.cs | 7 +- NCDK/Tools/GridGenerator.cs | 3 +- NCDK/Tools/LonePairElectronChecker.cs | 4 +- .../MolecularFormulaManipulator.cs | 4 +- NCDK/Tools/SaturationChecker.cs | 6 +- NCDK/Tools/SmilesValencyChecker.cs | 50 ++------ NCDK/Tools/StructureResonanceGenerator.cs | 12 +- NCDK/Validate/BasicValidator.cs | 4 +- NCDKTests/AbstractAtomContainerTest.cs | 61 ++++++--- NCDKTests/Aromaticities/KekulizationTest.cs | 32 +++-- NCDKTests/Beam/Core/AtomBuilderTest.cs | 103 ++++++++++------ NCDKTests/Beam/Core/AtomTest.cs | 20 ++- .../PartialFilledStructureMergerTest.cs | 10 +- NCDKTests/Tools/ATASaturationCheckerTest.cs | 3 +- ...educeBondOrderTestFromExplicitHydrogens.cs | 2 +- NCDKTests/Tools/SaturationCheckerTest.cs | 2 +- 36 files changed, 333 insertions(+), 339 deletions(-) diff --git a/NCDK/Aromaticities/AtomTypeModel.cs b/NCDK/Aromaticities/AtomTypeModel.cs index ff77dd2b..5077ecb5 100644 --- a/NCDK/Aromaticities/AtomTypeModel.cs +++ b/NCDK/Aromaticities/AtomTypeModel.cs @@ -169,7 +169,7 @@ private static int ElectronsForAtomType(IAtom atom) try { - var atomType = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", atom.Builder).GetAtomType(atom.AtomTypeName); + var atomType = CDK.CdkAtomTypeFactory.GetAtomType(atom.AtomTypeName); var propPiBondCount = atomType.GetProperty(CDKPropertyName.PiBondCount, 0); return propPiBondCount; } diff --git a/NCDK/AtomTypes/CDKAtomTypeMatcher.cs b/NCDK/AtomTypes/CDKAtomTypeMatcher.cs index f96a8501..84f3b236 100644 --- a/NCDK/AtomTypes/CDKAtomTypeMatcher.cs +++ b/NCDK/AtomTypes/CDKAtomTypeMatcher.cs @@ -47,7 +47,8 @@ public enum Mode RequireExplicitHydrogens = 2, } - private AtomTypeFactory factory; + private AtomTypeFactory factory = CDK.CdkAtomTypeFactory; + private readonly Mode mode; private static readonly object syncLock = new object(); @@ -56,7 +57,6 @@ public enum Mode private CDKAtomTypeMatcher(IChemObjectBuilder builder, Mode mode) { - factory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", builder); this.mode = mode; } diff --git a/NCDK/AtomTypes/StructGenAtomTypeGuesser.cs b/NCDK/AtomTypes/StructGenAtomTypeGuesser.cs index 1317113d..3c5bfc58 100644 --- a/NCDK/AtomTypes/StructGenAtomTypeGuesser.cs +++ b/NCDK/AtomTypes/StructGenAtomTypeGuesser.cs @@ -42,7 +42,8 @@ namespace NCDK.AtomTypes // @cdk.githash public class StructGenAtomTypeGuesser : IAtomTypeGuesser { - private static AtomTypeFactory factory = null; + private static readonly AtomTypeFactory factory = CDK.StructgenAtomTypeFactory; + /// /// Constructor for the StructGenMatcher object. /// @@ -58,21 +59,6 @@ public StructGenAtomTypeGuesser() { } /// the matching AtomType public IEnumerable PossibleAtomTypes(IAtomContainer atomContainer, IAtom atom) { - if (factory == null) - { - try - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", - atom.Builder); - } - catch (Exception ex1) - { - Trace.TraceError(ex1.Message); - Debug.WriteLine(ex1); - throw new CDKException("Could not instantiate the AtomType list!", ex1); - } - } - double bondOrderSum = atomContainer.GetBondOrderSum(atom); BondOrder maxBondOrder = atomContainer.GetMaximumBondOrder(atom); int charge = atom.FormalCharge.Value; diff --git a/NCDK/AtomTypes/StructGenMatcher.cs b/NCDK/AtomTypes/StructGenMatcher.cs index a0306860..87242d30 100644 --- a/NCDK/AtomTypes/StructGenMatcher.cs +++ b/NCDK/AtomTypes/StructGenMatcher.cs @@ -39,8 +39,8 @@ namespace NCDK.AtomTypes // @cdk.githash public class StructGenMatcher : IAtomTypeMatcher { - private static AtomTypeFactory factory = null; - + private static readonly AtomTypeFactory factory = CDK.StructgenAtomTypeFactory; + /// /// Constructor for the StructGenMatcher object. /// @@ -67,21 +67,6 @@ public IEnumerable FindMatchingAtomTypes(IAtomContainer atomContainer /// the matching AtomType public IAtomType FindMatchingAtomType(IAtomContainer atomContainer, IAtom atom) { - if (factory == null) - { - try - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", - atom.Builder); - } - catch (Exception ex1) - { - Trace.TraceError(ex1.Message); - Debug.WriteLine(ex1); - throw new CDKException("Could not instantiate the AtomType list!", ex1); - } - } - double bondOrderSum = atomContainer.GetBondOrderSum(atom); BondOrder maxBondOrder = atomContainer.GetMaximumBondOrder(atom); int charge = atom.FormalCharge.Value; diff --git a/NCDK/CDK.cs b/NCDK/CDK.cs index 8e757a93..8a9984d0 100644 --- a/NCDK/CDK.cs +++ b/NCDK/CDK.cs @@ -36,6 +36,39 @@ public static class CDK /// The library version public static string Version => typeof(CDK).Assembly.GetName().Version.ToString(); + private static Config.AtomTypeFactory atomTypeFactory = null; + internal static Config.AtomTypeFactory JmolAtomTypeFactory + { + get + { + if (atomTypeFactory == null) + atomTypeFactory = Config.AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", Silent.ChemObjectBuilder.Instance); + return atomTypeFactory; + } + } + + private static Config.AtomTypeFactory cdkAtomTypeFactory = null; + internal static Config.AtomTypeFactory CdkAtomTypeFactory + { + get + { + if (cdkAtomTypeFactory == null) + cdkAtomTypeFactory = Config.AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", Silent.ChemObjectBuilder.Instance); + return cdkAtomTypeFactory; + } + } + + private static Config.AtomTypeFactory structgenAtomTypeFactory = null; + internal static Config.AtomTypeFactory StructgenAtomTypeFactory + { + get + { + if (structgenAtomTypeFactory == null) + structgenAtomTypeFactory = Config.AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", Silent.ChemObjectBuilder.Instance); + return structgenAtomTypeFactory; + } + } + private static Smiles.SmilesParser silentSmilesParser = null; internal static Smiles.SmilesParser SilentSmilesParser { @@ -47,6 +80,18 @@ internal static Smiles.SmilesParser SilentSmilesParser } } + private static Tools.SaturationChecker saturationChecker; + + internal static Tools.SaturationChecker SaturationChecker + { + get + { + if (saturationChecker == null) + saturationChecker = new Tools.SaturationChecker(); + return saturationChecker; + } + } + private static Tools.ILonePairElectronChecker lonePairElectronChecker; internal static Tools.ILonePairElectronChecker LonePairElectronChecker diff --git a/NCDK/Charges/GasteigerPEPEPartialCharges.cs b/NCDK/Charges/GasteigerPEPEPartialCharges.cs index 2a1dab2a..b4e90fd7 100644 --- a/NCDK/Charges/GasteigerPEPEPartialCharges.cs +++ b/NCDK/Charges/GasteigerPEPEPartialCharges.cs @@ -62,10 +62,7 @@ public class GasteigerPEPEPartialCharges : IChargeCalculator /// The StepSize attribute of the GasteigerMarsiliPartialCharges object. public int StepSize { get; set; } = 5; - private AtomTypeFactory factory; - // Flag is set if the formal charge of a chemobject is changed due to resonance. - //private static int ISCHANGEDFC = 0x1; - // Use IsPlaced flag because it has the same mask + private static readonly AtomTypeFactory factory = CDK.JmolAtomTypeFactory; /// Corresponds an empirical influence between the electrostatic potential and the neighbours. private const double fE = 1.1; @@ -548,9 +545,6 @@ private double GetElectrostaticPotentialN(IAtomContainer ac, int atom1, double[] double sum = 0.0; try { - if (factory == null) - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", ac.Builder); - var atoms = ac.GetConnectedAtoms(ac.Atoms[atom1]); foreach (var atom in atoms) { diff --git a/NCDK/Charges/InductivePartialCharges.cs b/NCDK/Charges/InductivePartialCharges.cs index 8ce4bc2f..d982ecc5 100644 --- a/NCDK/Charges/InductivePartialCharges.cs +++ b/NCDK/Charges/InductivePartialCharges.cs @@ -41,7 +41,7 @@ public class InductivePartialCharges : IChargeCalculator { private static double[] pauling; private IsotopeFactory ifac = null; - private AtomTypeFactory factory = null; + private static readonly AtomTypeFactory factory = CDK.JmolAtomTypeFactory; /// /// Constructor for the InductivePartialCharges object. @@ -66,11 +66,6 @@ public InductivePartialCharges() /// AtomContainer public IAtomContainer AssignInductivePartialCharges(IAtomContainer ac) { - if (factory == null) - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", ac.Builder); - } - int stepsLimit = 9; var atoms = ac.Atoms.ToArray(); var pChInch = new double[atoms.Length * (stepsLimit + 1)]; @@ -217,10 +212,6 @@ public double[] GetPaulingElectronegativities(IAtomContainer ac, bool modified) /// public double GetAtomicSoftnessCore(IAtomContainer ac, int atomPosition) { - if (factory == null) - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", ac.Builder); - } IAtom target = null; double core = 0; double radiusTarget = 0; diff --git a/NCDK/Geometries/Volume/VABCVolume.cs b/NCDK/Geometries/Volume/VABCVolume.cs index dcfe7e5a..21cb2c05 100644 --- a/NCDK/Geometries/Volume/VABCVolume.cs +++ b/NCDK/Geometries/Volume/VABCVolume.cs @@ -57,7 +57,7 @@ public static class VABCVolume { "Si", 38.7923854248 }, }; - private static readonly AtomTypeFactory atomTypeList = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", Silent.ChemObjectBuilder.Instance); + private static readonly AtomTypeFactory atomTypeList = CDK.CdkAtomTypeFactory; /// /// Calculates the volume for the given . This methods assumes diff --git a/NCDK/IO/Mol2Reader.cs b/NCDK/IO/Mol2Reader.cs index cf40a015..dc5eb2fe 100644 --- a/NCDK/IO/Mol2Reader.cs +++ b/NCDK/IO/Mol2Reader.cs @@ -48,8 +48,9 @@ namespace NCDK.IO // @cdk.keyword file format, Mol2 public class Mol2Reader : DefaultChemObjectReader { - bool firstLineisMolecule = false; + private static readonly AtomTypeFactory atFactory = AtomTypeFactory.GetInstance("NCDK.Config.Data.mol2_atomtypes.xml", Silent.ChemObjectBuilder.Instance); + bool firstLineisMolecule = false; TextReader input = null; /// @@ -199,20 +200,7 @@ public virtual bool Accepts(IChemObject o) /// /// The Reaction that was read from the MDL file. private IAtomContainer ReadMolecule(IAtomContainer molecule) - { - AtomTypeFactory atFactory = null; - try - { - atFactory = AtomTypeFactory.GetInstance("NCDK.Config.Data.mol2_atomtypes.xml", - molecule.Builder); - } - catch (Exception exception) - { - string error = "Could not instantiate an AtomTypeFactory"; - Trace.TraceError(error); - Debug.WriteLine(exception); - throw new CDKException(error, exception); - } + { try { int atomCount = 0; @@ -222,14 +210,15 @@ private IAtomContainer ReadMolecule(IAtomContainer molecule) while (true) { line = input.ReadLine(); - if (line == null) return null; + if (line == null) + return null; if (line.StartsWith("@MOLECULE", StringComparison.Ordinal)) break; if (!line.StartsWithChar('#') && line.Trim().Length > 0) break; } - // ok, if we're coming from the chemfile functoion, we've alreay read the molecule RTI + // ok, if we're coming from the chemfile function, we've already read the molecule RTI if (firstLineisMolecule) molecule.Title = line; else diff --git a/NCDK/IO/PDBReader.cs b/NCDK/IO/PDBReader.cs index 10973c02..a326a993 100644 --- a/NCDK/IO/PDBReader.cs +++ b/NCDK/IO/PDBReader.cs @@ -58,7 +58,13 @@ namespace NCDK.IO // @cdk.bug 1794439 public class PDBReader : DefaultChemObjectReader { - private TextReader oInput; // The internal used TextReader + private static readonly AtomTypeFactory factory = CDK.JmolAtomTypeFactory; + + /// + /// The internal used TextReader + /// + private TextReader oInput; + private BooleanIOSetting useRebondTool; private BooleanIOSetting readConnect; private BooleanIOSetting useHetDictionary; @@ -76,9 +82,8 @@ public class PDBReader : DefaultChemObjectReader /// A mapping between HETATM 3-letter codes + atomNames to CDK atom type /// names; for example "RFB.N13" maps to "N.planar3". /// - private IDictionary hetDictionary; - - private AtomTypeFactory cdkAtomTypeFactory; + private static readonly Dictionary hetDictionary = MakeHetDictionary(); + private static readonly AtomTypeFactory cdkAtomTypeFactory = CDK.CdkAtomTypeFactory; private const string hetDictionaryPath = "type_map.txt"; /// @@ -87,7 +92,8 @@ public class PDBReader : DefaultChemObjectReader /// The Stream to read from public PDBReader(Stream oIn) : this(new StreamReader(oIn)) - { } + { + } /// /// Constructs a new PDBReader that can read Molecules from a given Reader. @@ -97,15 +103,14 @@ public PDBReader(TextReader oIn) { oInput = oIn; InitIOSettings(); - hetDictionary = null; - cdkAtomTypeFactory = null; } public override IResourceFormat Format => PDBFormat.Instance; public override bool Accepts(Type type) { - if (typeof(IChemFile).IsAssignableFrom(type)) return true; + if (typeof(IChemFile).IsAssignableFrom(type)) + return true; return false; } @@ -145,15 +150,15 @@ public override T Read(T oObj) private IChemFile ReadChemFile(IChemFile oFile) { // initialize all containers - IChemSequence oSeq = oFile.Builder.NewChemSequence(); - IChemModel oModel = oFile.Builder.NewChemModel(); + var oSeq = oFile.Builder.NewChemSequence(); + var oModel = oFile.Builder.NewChemModel(); var oSet = oFile.Builder.NewAtomContainerSet(); // some variables needed string cCol; PDBAtom oAtom; - PDBPolymer oBP = new PDBPolymer(); - IAtomContainer molecularStructure = oFile.Builder.NewAtomContainer(); + var oBP = new PDBPolymer(); + var molecularStructure = oFile.Builder.NewAtomContainer(); StringBuilder cResidue; string oObj; IMonomer oMonomer; @@ -564,12 +569,12 @@ private void AddBond(IAtomContainer molecule, int bondAtomNo, int bondedAtomNo) Trace.TraceError("Could not find bond start atom in map with serial id: ", bondAtomNo); if (!atomNumberMap.TryGetValue(bondedAtomNo, out IAtom secondAtom)) Trace.TraceError("Could not find bond target atom in map with serial id: ", bondAtomNo); - IBond bond = firstAtom.Builder.NewBond(firstAtom, secondAtom, BondOrder.Single); + var bond = firstAtom.Builder.NewBond(firstAtom, secondAtom, BondOrder.Single); for (int i = 0; i < bondsFromConnectRecords.Count; i++) { - IBond existingBond = (IBond)bondsFromConnectRecords[i]; - IAtom a = existingBond.Begin; - IAtom b = existingBond.End; + var existingBond = bondsFromConnectRecords[i]; + var a = existingBond.Begin; + var b = existingBond.End; if ((a == firstAtom && b == secondAtom) || (b == firstAtom && a == secondAtom)) { // already stored @@ -582,11 +587,9 @@ private void AddBond(IAtomContainer molecule, int bondAtomNo, int bondedAtomNo) private static bool CreateBondsWithRebondTool(IAtomContainer molecule) { - RebondTool tool = new RebondTool(2.0, 0.5, 0.5); + var tool = new RebondTool(2.0, 0.5, 0.5); try { - // configure atoms - AtomTypeFactory factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", molecule.Builder); foreach (var atom in molecule.Atoms) { try @@ -641,7 +644,7 @@ private static string ParseAtomSymbol(string str) int len = str.Length; - StringBuilder sym = new StringBuilder(); + var sym = new StringBuilder(); // try grabbing from end of line @@ -725,19 +728,19 @@ private PDBAtom ReadAtom(string cLine, int lineLength) throw new InvalidDataException("PDBReader error during ReadAtom(): line too short"); } - bool isHetatm = cLine.StartsWith("HETATM", StringComparison.Ordinal); - string atomName = cLine.Substring(12, 4).Trim(); - string resName = cLine.Substring(17, 3).Trim(); - string symbol = ParseAtomSymbol(cLine); + var isHetatm = cLine.StartsWith("HETATM", StringComparison.Ordinal); + var atomName = cLine.Substring(12, 4).Trim(); + var resName = cLine.Substring(17, 3).Trim(); + var symbol = ParseAtomSymbol(cLine); if (symbol == null) HandleError($"Cannot parse symbol from {atomName}"); - PDBAtom oAtom = new PDBAtom(symbol, new Vector3(double.Parse(cLine.Substring(30, 8), NumberFormatInfo.InvariantInfo), - double.Parse(cLine.Substring(38, 8), NumberFormatInfo.InvariantInfo), double.Parse(cLine.Substring(46, 8), NumberFormatInfo.InvariantInfo))); + var oAtom = new PDBAtom(symbol, new Vector3(double.Parse(cLine.Substring(30, 8), NumberFormatInfo.InvariantInfo), + double.Parse(cLine.Substring(38, 8), NumberFormatInfo.InvariantInfo), double.Parse(cLine.Substring(46, 8), NumberFormatInfo.InvariantInfo))); if (useHetDictionary.IsSet && isHetatm) { - string cdkType = TypeHetatm(resName, atomName); + var cdkType = TypeHetatm(resName, atomName); oAtom.AtomTypeName = cdkType; if (cdkType != null) { @@ -770,7 +773,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) } if (lineLength >= 59) { - string frag = cLine.Substring(54, Math.Min(lineLength - 54, 6)).Trim(); + var frag = cLine.Substring(54, Math.Min(lineLength - 54, 6)).Trim(); if (frag.Length > 0) { oAtom.Occupancy = double.Parse(frag, NumberFormatInfo.InvariantInfo); @@ -778,7 +781,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) } if (lineLength >= 65) { - string frag = cLine.Substring(60, Math.Min(lineLength - 60, 6)).Trim(); + var frag = cLine.Substring(60, Math.Min(lineLength - 60, 6)).Trim(); if (frag.Length > 0) { oAtom.TempFactor = double.Parse(frag, NumberFormatInfo.InvariantInfo); @@ -788,9 +791,6 @@ private PDBAtom ReadAtom(string cLine, int lineLength) { oAtom.SegID = cLine.Substring(72, Math.Min(lineLength - 72, 4)).Trim(); } - // if (lineLength >= 78) { - // oAtom.Symbol = (new string(cLine.Substring(76, 78))).Trim(); - // } if (lineLength >= 79) { string frag; @@ -822,7 +822,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) // It sets a flag in the property content of an atom, which is used when // bonds are created to check if the atom is an OXT-record => needs // special treatment. - string oxt = cLine.Substring(13, 3).Trim(); + var oxt = cLine.Substring(13, 3).Trim(); if (string.Equals(oxt, "OXT", StringComparison.Ordinal)) { @@ -839,12 +839,7 @@ private PDBAtom ReadAtom(string cLine, int lineLength) private string TypeHetatm(string resName, string atomName) { - if (hetDictionary == null) - { - ReadHetDictionary(); - cdkAtomTypeFactory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", ChemObjectBuilder.Instance); - } - string key = resName + "." + atomName; + var key = resName + "." + atomName; if (hetDictionary.ContainsKey(key)) { return hetDictionary[key]; @@ -852,35 +847,38 @@ private string TypeHetatm(string resName, string atomName) return null; } - private void ReadHetDictionary() + private static Dictionary MakeHetDictionary() { + var hetDictionary = new Dictionary(); try { - Stream ins = ResourceLoader.GetAsStream(GetType(), hetDictionaryPath); - TextReader bufferedReader = new StreamReader(ins); - hetDictionary = new Dictionary(); - string line; - while ((line = bufferedReader.ReadLine()) != null) + var ins = ResourceLoader.GetAsStream(typeof(PDBReader), hetDictionaryPath); + using (var bufferedReader = new StreamReader(ins)) { - int colonIndex = line.IndexOf(':'); - if (colonIndex == -1) continue; - string typeKey = line.Substring(0, colonIndex); - string typeValue = line.Substring(colonIndex + 1); - if (string.Equals(typeValue, "null", StringComparison.Ordinal)) + string line; + while ((line = bufferedReader.ReadLine()) != null) { - hetDictionary[typeKey] = null; - } - else - { - hetDictionary[typeKey] = typeValue; + var colonIndex = line.IndexOf(':'); + if (colonIndex == -1) + continue; + var typeKey = line.Substring(0, colonIndex); + var typeValue = line.Substring(colonIndex + 1); + if (string.Equals(typeValue, "null", StringComparison.Ordinal)) + { + hetDictionary[typeKey] = null; + } + else + { + hetDictionary[typeKey] = typeValue; + } } } - bufferedReader.Close(); } catch (IOException ioe) { Trace.TraceError(ioe.Message); } + return hetDictionary; } #region IDisposable Support @@ -906,11 +904,11 @@ protected override void Dispose(bool disposing) private void InitIOSettings() { useRebondTool = IOSettings.Add(new BooleanIOSetting("UseRebondTool", Importance.Low, - "Should the PDBReader deduce bonding patterns?", "false")); + "Should the PDBReader deduce bonding patterns?", "false")); readConnect = IOSettings.Add(new BooleanIOSetting("ReadConnectSection", Importance.Low, - "Should the CONECT be read?", "true")); + "Should the CONECT be read?", "true")); useHetDictionary = IOSettings.Add(new BooleanIOSetting("UseHetDictionary", Importance.Low, - "Should the PDBReader use the HETATM dictionary for atom types?", "false")); + "Should the PDBReader use the HETATM dictionary for atom types?", "false")); } public void CustomizeJob() diff --git a/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs index 2c2faaa5..a37c769e 100644 --- a/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/CovalentRadiusDescriptor.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Config; using NCDK.QSAR.Results; using System; @@ -49,7 +50,7 @@ namespace NCDK.QSAR.Descriptors.Atomic // @cdk.dictref qsar-descriptors:covalentradius public partial class CovalentRadiusDescriptor : IAtomicDescriptor { - private AtomTypeFactory factory = null; + private static readonly AtomTypeFactory factory = CDK.JmolAtomTypeFactory; public CovalentRadiusDescriptor() { } @@ -75,17 +76,6 @@ public CovalentRadiusDescriptor() { } /// The Covalent radius of the atom public DescriptorValue> Calculate(IAtom atom, IAtomContainer container) { - if (factory == null) - try - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", - container.Builder); - } - catch (Exception exception) - { - return new DescriptorValue>(specification, ParameterNames, Parameters, new Result(double.NaN), DescriptorNames, exception); - } - double covalentradius; try { diff --git a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs index 770b673a..f6d8e540 100644 --- a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicHardnessDescriptor.cs @@ -16,12 +16,13 @@ * along with this program; if not, write to the Free Hardware * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ -using NCDK.Numerics; + using NCDK.Config; +using NCDK.Numerics; using NCDK.QSAR.Results; using System; -using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics; namespace NCDK.QSAR.Descriptors.Atomic { @@ -52,7 +53,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public partial class InductiveAtomicHardnessDescriptor : IAtomicDescriptor { private static readonly string[] NAMES = { "indAtomHardnesss" }; - private AtomTypeFactory factory = null; + private static readonly AtomTypeFactory factory = CDK.JmolAtomTypeFactory; /// /// Constructor for the InductiveAtomicHardnessDescriptor object @@ -90,19 +91,7 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e) /// a double with polarizability of the heavy atom public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) { - if (factory == null) - try - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", - ac.Builder); - } - catch (Exception exception) - { - return GetDummyDescriptorValue(exception); - } - double atomicHardness; - double radiusTarget; var allAtoms = ac.Atoms; diff --git a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs index 453e1fa7..4119a13f 100644 --- a/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs +++ b/NCDK/QSAR/Descriptors/Atomic/InductiveAtomicSoftnessDescriptor.cs @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ + using NCDK.Numerics; using NCDK.Config; using NCDK.QSAR.Results; @@ -52,7 +53,7 @@ namespace NCDK.QSAR.Descriptors.Atomic public partial class InductiveAtomicSoftnessDescriptor : IAtomicDescriptor { private static readonly string[] NAMES = { "indAtomSoftness" }; - private AtomTypeFactory factory = null; + private static readonly AtomTypeFactory factory = CDK.JmolAtomTypeFactory; /// /// Constructor for the InductiveAtomicSoftnessDescriptor object @@ -89,17 +90,6 @@ private DescriptorValue> GetDummyDescriptorValue(Exception e) /// a double with polarizability of the heavy atom public DescriptorValue> Calculate(IAtom atom, IAtomContainer ac) { - if (factory == null) - try - { - factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.jmol_atomtypes.txt", - ac.Builder); - } - catch (Exception exception) - { - return GetDummyDescriptorValue(exception); - } - var allAtoms = ac.Atoms; double atomicSoftness; double radiusTarget; diff --git a/NCDK/StructGen/SingleStructureRandomGenerator.cs b/NCDK/StructGen/SingleStructureRandomGenerator.cs index 4cf530de..f093c328 100644 --- a/NCDK/StructGen/SingleStructureRandomGenerator.cs +++ b/NCDK/StructGen/SingleStructureRandomGenerator.cs @@ -63,8 +63,9 @@ namespace NCDK.StructGen // @cdk.githash public class SingleStructureRandomGenerator { + private static readonly SaturationChecker satCheck = CDK.SaturationChecker; + IAtomContainer atomContainer; - SaturationChecker satCheck; Maths.Random random = null; /// @@ -72,7 +73,6 @@ public class SingleStructureRandomGenerator /// public SingleStructureRandomGenerator(long seed) { - satCheck = new SaturationChecker(); random = new Maths.Random(seed); } diff --git a/NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs b/NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs index 461a59e0..a5a350cf 100644 --- a/NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs +++ b/NCDK/StructGen/Stochastic/Operators/CrossoverMachine.cs @@ -164,7 +164,7 @@ public IReadOnlyList DoCrossover(IAtomContainer dad, IAtomContai } //if the two fragments of one and only one parent have an uneven number //of attachment points, we need to rearrange them - var satCheck = new SaturationChecker(); + var satCheck = CDK.SaturationChecker; double red1attachpoints = 0; for (int i = 0; i < redChild[0].Atoms.Count; i++) { diff --git a/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs b/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs index 5c44ed19..e1c002bd 100644 --- a/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs +++ b/NCDK/StructGen/Stochastic/PartialFilledStructureMerger.cs @@ -42,14 +42,10 @@ namespace NCDK.StructGen.Stochastic // @cdk.githash public class PartialFilledStructureMerger { - SaturationChecker satCheck; + private static readonly SaturationChecker satCheck = CDK.SaturationChecker; - /// - /// Constructor for the PartialFilledStructureMerger object. - /// public PartialFilledStructureMerger() { - satCheck = new SaturationChecker(); } /// diff --git a/NCDK/Tools/AtomTypeAwareSaturationChecker.cs b/NCDK/Tools/AtomTypeAwareSaturationChecker.cs index f1aa576b..398fb7fc 100644 --- a/NCDK/Tools/AtomTypeAwareSaturationChecker.cs +++ b/NCDK/Tools/AtomTypeAwareSaturationChecker.cs @@ -49,7 +49,8 @@ namespace NCDK.Tools // @cdk.module valencycheck public class AtomTypeAwareSaturationChecker : IValencyChecker, IDeduceBondOrderTool { - SaturationChecker staturationChecker; + private static readonly SaturationChecker staturationChecker = CDK.SaturationChecker; + private BondOrder oldBondOrder; private int startBond; @@ -58,7 +59,6 @@ public class AtomTypeAwareSaturationChecker : IValencyChecker, IDeduceBondOrderT /// public AtomTypeAwareSaturationChecker() { - staturationChecker = new SaturationChecker(); } /// diff --git a/NCDK/Tools/CDKHydrogenAdder.cs b/NCDK/Tools/CDKHydrogenAdder.cs index 23ef7d30..10401629 100644 --- a/NCDK/Tools/CDKHydrogenAdder.cs +++ b/NCDK/Tools/CDKHydrogenAdder.cs @@ -45,14 +45,12 @@ namespace NCDK.Tools // @cdk.githash public class CDKHydrogenAdder { - private AtomTypeFactory atomTypeList; - private readonly string ATOM_TYPE_LIST = "NCDK.Dict.Data.cdk-atom-types.owl"; - - private static IDictionary tables = new Dictionary(); + private static readonly AtomTypeFactory atomTypeList = CDK.CdkAtomTypeFactory; + + private static Dictionary tables = new Dictionary(); private CDKHydrogenAdder(IChemObjectBuilder builder) { - if (atomTypeList == null) atomTypeList = AtomTypeFactory.GetInstance(ATOM_TYPE_LIST, builder); } public static CDKHydrogenAdder GetInstance(IChemObjectBuilder builder) @@ -91,22 +89,22 @@ public void AddImplicitHydrogens(IAtomContainer container) /// if insufficient information is present public void AddImplicitHydrogens(IAtomContainer container, IAtom atom) { - if (atom.AtomTypeName == null) throw new CDKException("IAtom is not typed! " + atom.Symbol); + if (atom.AtomTypeName == null) + throw new CDKException("IAtom is not typed! " + atom.Symbol); if (string.Equals("X", atom.AtomTypeName, StringComparison.Ordinal)) { - if (atom.ImplicitHydrogenCount == null) atom.ImplicitHydrogenCount = 0; + if (atom.ImplicitHydrogenCount == null) + atom.ImplicitHydrogenCount = 0; return; } - IAtomType type = atomTypeList.GetAtomType(atom.AtomTypeName); + var type = atomTypeList.GetAtomType(atom.AtomTypeName); if (type == null) throw new CDKException("Atom type is not a recognized CDK atom type: " + atom.AtomTypeName); if (type.FormalNeighbourCount == null) - throw new CDKException( - "Atom type is too general; cannot decide the number of implicit hydrogen to add for: " - + atom.AtomTypeName); + throw new CDKException($"Atom type is too general; cannot decide the number of implicit hydrogen to add for: {atom.AtomTypeName}"); // very simply counting: each missing explicit neighbor is a missing hydrogen atom.ImplicitHydrogenCount = type.FormalNeighbourCount - container.GetConnectedBonds(atom).Count(); diff --git a/NCDK/Tools/CDKValencyChecker.cs b/NCDK/Tools/CDKValencyChecker.cs index 392adfaa..59de2062 100644 --- a/NCDK/Tools/CDKValencyChecker.cs +++ b/NCDK/Tools/CDKValencyChecker.cs @@ -35,14 +35,12 @@ namespace NCDK.Tools // @cdk.githash public class CDKValencyChecker : IValencyChecker { - private AtomTypeFactory atomTypeList; - private const string ATOM_TYPE_LIST = "NCDK.Dict.Data.cdk-atom-types.owl"; - - private static IDictionary tables = new Dictionary(3); + private static readonly AtomTypeFactory atomTypeList = CDK.CdkAtomTypeFactory; + + private static Dictionary tables = new Dictionary(3); private CDKValencyChecker(IChemObjectBuilder builder) { - if (atomTypeList == null) atomTypeList = AtomTypeFactory.GetInstance(ATOM_TYPE_LIST, builder); } public static CDKValencyChecker GetInstance(IChemObjectBuilder builder) @@ -56,14 +54,15 @@ public bool IsSaturated(IAtomContainer atomContainer) { foreach (var atom in atomContainer.Atoms) { - if (!IsSaturated(atom, atomContainer)) return false; + if (!IsSaturated(atom, atomContainer)) + return false; } return true; } public bool IsSaturated(IAtom atom, IAtomContainer container) { - IAtomType type = atomTypeList.GetAtomType(atom.AtomTypeName); + var type = atomTypeList.GetAtomType(atom.AtomTypeName); if (type == null) throw new CDKException($"Atom type is not a recognized CDK atom type: {atom.AtomTypeName}"); @@ -73,8 +72,8 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) if (type.GetProperty(CDKPropertyName.PiBondCount) == null) throw new CDKException($"Atom type is too general; cannot determine the number of pi bonds for: {atom.AtomTypeName}"); - double bondOrderSum = container.GetBondOrderSum(atom); - BondOrder maxBondOrder = container.GetMaximumBondOrder(atom); + var bondOrderSum = container.GetBondOrderSum(atom); + var maxBondOrder = container.GetMaximumBondOrder(atom); int? hcount = atom.ImplicitHydrogenCount == null ? 0 : atom.ImplicitHydrogenCount; int piBondCount = type.GetProperty(CDKPropertyName.PiBondCount).Value; diff --git a/NCDK/Tools/DataFeatures.cs b/NCDK/Tools/DataFeatures.cs index e3e8fbda..16d1fec4 100644 --- a/NCDK/Tools/DataFeatures.cs +++ b/NCDK/Tools/DataFeatures.cs @@ -19,7 +19,6 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ using System; diff --git a/NCDK/Tools/DataFeaturesTool.cs b/NCDK/Tools/DataFeaturesTool.cs index 482313ec..8e05e799 100644 --- a/NCDK/Tools/DataFeaturesTool.cs +++ b/NCDK/Tools/DataFeaturesTool.cs @@ -19,7 +19,6 @@ * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * */ using NCDK.Features; @@ -45,8 +44,10 @@ public static DataFeatures GetSupportedDataFeatures(IAtomContainer molecule) DataFeatures features = DataFeatures.None; if (MoleculeFeaturesTool.HasElementSymbols(molecule)) features = features | DataFeatures.HasAtomElementSymbol; - if (GeometryUtil.Has2DCoordinates(molecule)) features = features | DataFeatures.Has2DCoordinates; - if (GeometryUtil.Has3DCoordinates(molecule)) features = features | DataFeatures.Has3DCoordinates; + if (GeometryUtil.Has2DCoordinates(molecule)) + features = features | DataFeatures.Has2DCoordinates; + if (GeometryUtil.Has3DCoordinates(molecule)) + features = features | DataFeatures.Has3DCoordinates; if (CrystalGeometryTools.HasCrystalCoordinates(molecule)) features = features | DataFeatures.HasFractionalCrystalCoordinates; if (MoleculeFeaturesTool.HasFormalCharges(molecule)) diff --git a/NCDK/Tools/GridGenerator.cs b/NCDK/Tools/GridGenerator.cs index ccee499c..689fb7ae 100644 --- a/NCDK/Tools/GridGenerator.cs +++ b/NCDK/Tools/GridGenerator.cs @@ -18,10 +18,9 @@ */ using NCDK.Common.Collections; -using NCDK.Common.Mathematics; +using NCDK.Numerics; using System; using System.IO; -using NCDK.Numerics; namespace NCDK.Tools { diff --git a/NCDK/Tools/LonePairElectronChecker.cs b/NCDK/Tools/LonePairElectronChecker.cs index fe5a9566..394936bd 100644 --- a/NCDK/Tools/LonePairElectronChecker.cs +++ b/NCDK/Tools/LonePairElectronChecker.cs @@ -50,8 +50,8 @@ public interface ILonePairElectronChecker public class LonePairElectronChecker : ILonePairElectronChecker { - private static AtomTypeFactory factory = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", Silent.ChemObjectBuilder.Instance); - + private static readonly AtomTypeFactory factory = CDK.CdkAtomTypeFactory; + public LonePairElectronChecker() { } diff --git a/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs b/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs index ea9b11fe..6e1bbe6d 100644 --- a/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs +++ b/NCDK/Tools/Manipulator/MolecularFormulaManipulator.cs @@ -785,12 +785,12 @@ public static double GetDBE(IMolecularFormula formula) { var valencies = new int[5]; var ac = GetAtomContainer(formula); - var factory = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", ac.Builder); + var factory = CDK.StructgenAtomTypeFactory; for (int f = 0; f < ac.Atoms.Count; f++) { var types = factory.GetAtomTypes(ac.Atoms[f].Symbol); - if (types.Count() == 0) + if (!types.Any()) throw new CDKException($"Calculation of double bond equivalents not possible due to problems with element {ac.Atoms[f].Symbol}"); valencies[(int)types.First().BondOrderSum.Value]++; } diff --git a/NCDK/Tools/SaturationChecker.cs b/NCDK/Tools/SaturationChecker.cs index ab3a3fc0..e66d7079 100644 --- a/NCDK/Tools/SaturationChecker.cs +++ b/NCDK/Tools/SaturationChecker.cs @@ -49,7 +49,11 @@ namespace NCDK.Tools // @cdk.githash public class SaturationChecker : IValencyChecker, IDeduceBondOrderTool { - private static readonly AtomTypeFactory structgenATF = AtomTypeFactory.GetInstance("NCDK.Config.Data.structgen_atomtypes.xml", Silent.ChemObjectBuilder.Instance); + private static readonly AtomTypeFactory structgenATF = CDK.StructgenAtomTypeFactory; + + public SaturationChecker() + { + } public bool HasPerfectConfiguration(IAtom atom, IAtomContainer ac) { diff --git a/NCDK/Tools/SmilesValencyChecker.cs b/NCDK/Tools/SmilesValencyChecker.cs index 114c81ea..1b3ffed8 100644 --- a/NCDK/Tools/SmilesValencyChecker.cs +++ b/NCDK/Tools/SmilesValencyChecker.cs @@ -41,17 +41,16 @@ namespace NCDK.Tools // @cdk.githash public class SmilesValencyChecker : IValencyChecker, IDeduceBondOrderTool { - private readonly string atomTypeList = null; - private AtomTypeFactory structgenATF; + private readonly AtomTypeFactory structgenATF; public SmilesValencyChecker() - : this("NCDK.Dict.Data.cdk-atom-types.owl") { + structgenATF = CDK.CdkAtomTypeFactory; } public SmilesValencyChecker(string atomTypeList) { - this.atomTypeList = atomTypeList; + structgenATF = AtomTypeFactory.GetInstance(atomTypeList, Silent.ChemObjectBuilder.Instance); Trace.TraceInformation($"Using configuration file: {atomTypeList}"); } @@ -63,7 +62,7 @@ public SmilesValencyChecker(string atomTypeList) public void Saturate(IAtomContainer atomContainer) { Trace.TraceInformation("Saturating atomContainer by adjusting bond orders..."); - var allSaturated = AllSaturated(atomContainer); + var allSaturated = IsSaturated(atomContainer); if (!allSaturated) { Trace.TraceInformation("Saturating bond orders is needed..."); @@ -92,7 +91,7 @@ public bool Saturate(IEnumerable bonds, IAtomContainer atomContainer) // determine bonds left var leftBondCount = _bonds.Count - 1; - var leftBonds = _bonds.ToList(); + var leftBonds = _bonds; // examine this bond Debug.WriteLine($"Examining this bond: {bond}"); @@ -181,8 +180,8 @@ public bool SaturateByIncreasingBondOrder(IBond bond, IAtomContainer atomContain var atom = atoms[0]; var partner = atoms[1]; Debug.WriteLine(" saturating bond: ", atom.Symbol, "-", partner.Symbol); - var atomTypes1 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(atom.Symbol); - var atomTypes2 = GetAtomTypeFactory(bond.Builder).GetAtomTypes(partner.Symbol); + var atomTypes1 = structgenATF.GetAtomTypes(atom.Symbol); + var atomTypes2 = structgenATF.GetAtomTypes(partner.Symbol); foreach (var aType1 in atomTypes1) { Debug.WriteLine($" considering atom type: {aType1}"); @@ -227,20 +226,12 @@ public bool IsSaturated(IBond bond, IAtomContainer atomContainer) return isSaturated; } - /// - /// Determines of all atoms on the AtomContainer are saturated. - /// - public bool IsSaturated(IAtomContainer container) - { - return AllSaturated(container); - } - /// /// Check all atoms are saturated. /// /// to check. /// if all atoms are saturated. - public bool AllSaturated(IAtomContainer ac) + public bool IsSaturated(IAtomContainer ac) { Debug.WriteLine("Are all atoms saturated?"); for (int f = 0; f < ac.Atoms.Count; f++) @@ -303,7 +294,7 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, double bondOrderSum, B Debug.WriteLine("Calculating number of missing hydrogen atoms"); // get default atom - var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); + var atomTypes = structgenATF.GetAtomTypes(atom.Symbol); foreach (var type in atomTypes) { if (CouldMatchAtomType(atom, bondOrderSum, maxBondOrder, type)) @@ -348,10 +339,10 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) return true; } - var atomTypes = GetAtomTypeFactory(atom.Builder).GetAtomTypes(atom.Symbol); + var atomTypes = structgenATF.GetAtomTypes(atom.Symbol); if (atomTypes.Any()) { - Trace.TraceWarning("Missing entry in atom type list for ", atom.Symbol); + Trace.TraceWarning($"Missing entry in atom type list for {atom.Symbol}"); return true; } var bondOrderSum = container.GetBondOrderSum(atom); @@ -393,7 +384,7 @@ public bool IsSaturated(IAtom atom, IAtomContainer container) // ok, the found atom was not in the list Trace.TraceError("Could not find atom type!"); - throw new CDKException("The atom with element " + atom.Symbol + " and charge " + charge + " is not found."); + throw new CDKException($"The atom with element {atom.Symbol} and charge {charge} is not found."); } public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer container) @@ -401,23 +392,6 @@ public int CalculateNumberOfImplicitHydrogens(IAtom atom, IAtomContainer contain return this.CalculateNumberOfImplicitHydrogens(atom, container.GetBondOrderSum(atom), container.GetMaximumBondOrder(atom), container.GetConnectedBonds(atom).Count()); } - protected AtomTypeFactory GetAtomTypeFactory(IChemObjectBuilder builder) - { - if (structgenATF == null) - { - try - { - structgenATF = AtomTypeFactory.GetInstance(atomTypeList, builder); - } - catch (Exception exception) - { - Debug.WriteLine(exception); - throw new CDKException("Could not instantiate AtomTypeFactory!", exception); - } - } - return structgenATF; - } - /// /// Determines if the atom can be of type . That is, it sees if this /// only differs in bond orders, or implicit hydrogen count. diff --git a/NCDK/Tools/StructureResonanceGenerator.cs b/NCDK/Tools/StructureResonanceGenerator.cs index a8c5eae2..bb993434 100644 --- a/NCDK/Tools/StructureResonanceGenerator.cs +++ b/NCDK/Tools/StructureResonanceGenerator.cs @@ -66,7 +66,7 @@ public class StructureResonanceGenerator /// /// public StructureResonanceGenerator() - : this(false) + : this(false) { } @@ -112,7 +112,9 @@ private void CallDefaultReactions() var param = new SetReactionCenter { IsSetParameter = false }; paramList.Add(param); - IReactionProcess type = new SharingLonePairReaction(); + IReactionProcess type; + + type = new SharingLonePairReaction(); try { type.ParameterList = paramList; @@ -239,7 +241,8 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) var setOfCont = molecule.Builder.NewAtomContainerSet(); var setOfMol = GetStructures(molecule); - if (setOfMol.Count == 0) return setOfCont; + if (setOfMol.Count == 0) + return setOfCont; /* extraction of all bonds which has been produced a changes of order */ var bondList = new List(); @@ -251,7 +254,8 @@ public IChemObjectSet GetContainers(IAtomContainer molecule) var bond = molecule.Bonds[j]; if (!mol.Bonds[j].Order.Equals(bond.Order)) { - if (!bondList.Contains(bond)) bondList.Add(bond); + if (!bondList.Contains(bond)) + bondList.Add(bond); } } } diff --git a/NCDK/Validate/BasicValidator.cs b/NCDK/Validate/BasicValidator.cs index 77927c5d..b08ebe45 100644 --- a/NCDK/Validate/BasicValidator.cs +++ b/NCDK/Validate/BasicValidator.cs @@ -264,7 +264,7 @@ private static ValidationReport ValidateMaxBondOrder(IBond bond) ValidationTest maxBO = new ValidationTest(bond, "Bond order exceeds the maximum for one of its atoms."); try { - var structgenATF = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", bond.Builder); + var structgenATF = CDK.CdkAtomTypeFactory; for (int i = 0; i < bond.Atoms.Count; i++) { IAtom atom = bond.Atoms[i]; @@ -357,7 +357,7 @@ private static ValidationReport ValidateBondOrderSum(IAtom atom, IAtomContainer ValidationTest checkBondSum = new ValidationTest(atom, "The atom's total bond order is too high."); try { - var structgenATF = AtomTypeFactory.GetInstance("NCDK.Dict.Data.cdk-atom-types.owl", atom.Builder); + var structgenATF = CDK.CdkAtomTypeFactory; int bos = (int)molecule.GetBondOrderSum(atom); var atomTypes = structgenATF.GetAtomTypes(atom.Symbol).ToList(); if (atomTypes.Count == 0) diff --git a/NCDKTests/AbstractAtomContainerTest.cs b/NCDKTests/AbstractAtomContainerTest.cs index 6daaa94d..efd000b9 100644 --- a/NCDKTests/AbstractAtomContainerTest.cs +++ b/NCDKTests/AbstractAtomContainerTest.cs @@ -3044,43 +3044,64 @@ public void TestGetConnectedBondCountMissingIdx() } [TestMethod()] - [ExpectedException(typeof(NoSuchAtomException))] public void TestGetConnectedLongPairsMissingAtom() { - IAtomContainer container = (IAtomContainer)NewChemObject(); - IChemObjectBuilder builder = container.Builder; - IAtom atom = builder.NewAtom(); - container.GetConnectedLonePairs(atom); + try + { + IAtomContainer container = (IAtomContainer)NewChemObject(); + IChemObjectBuilder builder = container.Builder; + IAtom atom = builder.NewAtom(); + container.GetConnectedLonePairs(atom); + Assert.Fail(); + } + catch (NoSuchAtomException) + { + } } [TestMethod()] - [ExpectedException(typeof(NoSuchAtomException))] public void TestGetConnectedSingleElecsMissingAtom() { - IAtomContainer container = (IAtomContainer)NewChemObject(); - IChemObjectBuilder builder = container.Builder; - IAtom atom = builder.NewAtom(); - container.GetConnectedSingleElectrons(atom); + try + { + IAtomContainer container = (IAtomContainer)NewChemObject(); + IChemObjectBuilder builder = container.Builder; + IAtom atom = builder.NewAtom(); + container.GetConnectedSingleElectrons(atom); + } + catch (NoSuchAtomException) + { + } } [TestMethod()] - [ExpectedException(typeof(NoSuchAtomException))] public void TestGetConnectedLongPairCountMissingAtom() { - IAtomContainer container = (IAtomContainer)NewChemObject(); - IChemObjectBuilder builder = container.Builder; - IAtom atom = builder.NewAtom(); - container.GetConnectedLonePairs(atom); + try + { + IAtomContainer container = (IAtomContainer)NewChemObject(); + IChemObjectBuilder builder = container.Builder; + IAtom atom = builder.NewAtom(); + container.GetConnectedLonePairs(atom); + } + catch (NoSuchAtomException) + { + } } [TestMethod()] - [ExpectedException(typeof(NoSuchAtomException))] public void TestGetConnectedSingleElecCountMissingAtom() { - IAtomContainer container = (IAtomContainer)NewChemObject(); - IChemObjectBuilder builder = container.Builder; - IAtom atom = builder.NewAtom(); - container.GetConnectedSingleElectrons(atom); + try + { + IAtomContainer container = (IAtomContainer)NewChemObject(); + IChemObjectBuilder builder = container.Builder; + IAtom atom = builder.NewAtom(); + container.GetConnectedSingleElectrons(atom); + } + catch (NoSuchAtomException) + { + } } [TestMethod()] diff --git a/NCDKTests/Aromaticities/KekulizationTest.cs b/NCDKTests/Aromaticities/KekulizationTest.cs index 915a3c24..ae6c68bc 100644 --- a/NCDKTests/Aromaticities/KekulizationTest.cs +++ b/NCDKTests/Aromaticities/KekulizationTest.cs @@ -111,21 +111,27 @@ public void PyrroleWithExplicitHydrogen() /// Hydrogens must be present - otherwise the kekulisation is ambiguous. [TestMethod()] - [ExpectedException(typeof(CDKException))] public void PyrroleWithMissingHydrogen() { - IAtomContainer m = new AtomContainer(); - m.Atoms.Add(Atom("N", 0, true)); - m.Atoms.Add(Atom("C", 1, true)); - m.Atoms.Add(Atom("C", 1, true)); - m.Atoms.Add(Atom("C", 1, true)); - m.Atoms.Add(Atom("C", 1, true)); - m.Bonds.Add(Bond(m, 0, 1, BondOrder.Unset, true)); - m.Bonds.Add(Bond(m, 1, 2, BondOrder.Unset, true)); - m.Bonds.Add(Bond(m, 2, 3, BondOrder.Unset, true)); - m.Bonds.Add(Bond(m, 3, 4, BondOrder.Unset, true)); - m.Bonds.Add(Bond(m, 4, 0, BondOrder.Unset, true)); - AssertBondOrders(m); + try + { + IAtomContainer m = new AtomContainer(); + m.Atoms.Add(Atom("N", 0, true)); + m.Atoms.Add(Atom("C", 1, true)); + m.Atoms.Add(Atom("C", 1, true)); + m.Atoms.Add(Atom("C", 1, true)); + m.Atoms.Add(Atom("C", 1, true)); + m.Bonds.Add(Bond(m, 0, 1, BondOrder.Unset, true)); + m.Bonds.Add(Bond(m, 1, 2, BondOrder.Unset, true)); + m.Bonds.Add(Bond(m, 2, 3, BondOrder.Unset, true)); + m.Bonds.Add(Bond(m, 3, 4, BondOrder.Unset, true)); + m.Bonds.Add(Bond(m, 4, 0, BondOrder.Unset, true)); + AssertBondOrders(m); + Assert.Fail(); + } + catch (CDKException) + { + } } /// @cdk.inchi InChI=1S/C10H8/c1-2-5-9-7-4-8-10(9)6-3-1/h1-8H diff --git a/NCDKTests/Beam/Core/AtomBuilderTest.cs b/NCDKTests/Beam/Core/AtomBuilderTest.cs index 58618257..0b8fc7fe 100644 --- a/NCDKTests/Beam/Core/AtomBuilderTest.cs +++ b/NCDKTests/Beam/Core/AtomBuilderTest.cs @@ -33,18 +33,21 @@ public void Aliphatic_element_n() } [TestMethod()] - [ExpectedException(typeof(ArgumentNullException))] public void Aliphatic_element_null() { - IAtom a = AtomBuilder.Aliphatic((Element)null) - .Build(); + try + { + IAtom a = AtomBuilder.Aliphatic((Element)null).Build(); + Assert.Fail(); + } + catch (ArgumentNullException) + { } } [TestMethod()] public void IsAromatic_element_c() { - IAtom a = AtomBuilder.Aromatic(Carbon) - .Build(); + IAtom a = AtomBuilder.Aromatic(Carbon).Build(); Assert.AreEqual(a.Element, Element.Carbon); Assert.AreEqual(a.Isotope, -1); Assert.AreEqual(a.Charge, 0); @@ -65,26 +68,33 @@ public void IsAromatic_element_n() } [TestMethod()] - [ExpectedException(typeof(ArgumentException))] public void IsAromatic_element_cl() { - IAtom a = AtomBuilder.Aromatic(Chlorine) - .Build(); + try + { + IAtom a = AtomBuilder.Aromatic(Chlorine).Build(); + Assert.Fail(); + } + catch (ArgumentException) + { } } [TestMethod()] - [ExpectedException(typeof(ArgumentNullException))] public void IsAromatic_element_null() { - IAtom a = AtomBuilder.Aromatic((Element)null) - .Build(); + try + { + IAtom a = AtomBuilder.Aromatic((Element)null).Build(); + Assert.Fail(); + } + catch (ArgumentNullException) + { } } [TestMethod()] public void Aliphatic_symbol_c() { - IAtom a = AtomBuilder.Aliphatic("C") - .Build(); + IAtom a = AtomBuilder.Aliphatic("C").Build(); Assert.AreEqual(a.Element, Element.Carbon); Assert.AreEqual(a.Isotope, -1); Assert.AreEqual(a.Charge, 0); @@ -95,8 +105,7 @@ public void Aliphatic_symbol_c() [TestMethod()] public void Aliphatic_symbol_n() { - IAtom a = AtomBuilder.Aliphatic("N") - .Build(); + IAtom a = AtomBuilder.Aliphatic("N").Build(); Assert.AreEqual(a.Element, Element.Nitrogen); Assert.AreEqual(a.Isotope, -1); Assert.AreEqual(a.Charge, 0); @@ -105,18 +114,21 @@ public void Aliphatic_symbol_n() } [TestMethod()] - [ExpectedException(typeof(ArgumentNullException))] public void Aliphatic_symbol_null() { - IAtom a = AtomBuilder.Aliphatic((string)null) - .Build(); + try + { + IAtom a = AtomBuilder.Aliphatic((string)null).Build(); + Assert.Fail(); + } + catch (ArgumentNullException) + { } } [TestMethod()] public void IsAromatic_symbol_c() { - IAtom a = AtomBuilder.Aromatic("C") - .Build(); + IAtom a = AtomBuilder.Aromatic("C").Build(); Assert.AreEqual(a.Element, Element.Carbon); Assert.AreEqual(a.Isotope, -1); Assert.AreEqual(a.Charge, 0); @@ -137,26 +149,33 @@ public void IsAromatic_symbol_n() } [TestMethod()] - [ExpectedException(typeof(ArgumentException))] public void IsAromatic_symbol_cl() { - IAtom a = AtomBuilder.Aromatic("Cl") - .Build(); + try + { + IAtom a = AtomBuilder.Aromatic("Cl").Build(); + Assert.Fail(); + } + catch (ArgumentException) + { } } [TestMethod()] - [ExpectedException(typeof(ArgumentNullException))] public void IsAromatic_symbol_null() { - IAtom a = AtomBuilder.Aromatic((string)null) - .Build(); + try + { + IAtom a = AtomBuilder.Aromatic((string)null).Build(); + Assert.Fail(); + } + catch (ArgumentNullException) + { } } [TestMethod()] public void Create_symbol_aliphatic_c() { - IAtom a = AtomBuilder.Create("C") - .Build(); + IAtom a = AtomBuilder.Create("C").Build(); Assert.AreEqual(a.Element, Element.Carbon); Assert.AreEqual(a.Isotope, -1); Assert.AreEqual(a.Charge, 0); @@ -177,11 +196,15 @@ public void Create_symbol_IsAromatic_c() } [TestMethod()] - [ExpectedException(typeof(ArgumentException))] public void Create_symbol_non_IsAromatic() { - IAtom a = AtomBuilder.Create("cl") - .Build(); + try + { + IAtom a = AtomBuilder.Create("cl").Build(); + Assert.Fail(); + } + catch (ArgumentException) + { } } [TestMethod()] @@ -290,28 +313,30 @@ public void Aliphatic_carbon_3_hydrogens() } [TestMethod()] - [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Aliphatic_carbon_negative_hydrogens() { - IAtom a = AtomBuilder.Aliphatic(Element.Carbon) + try + { + IAtom a = AtomBuilder.Aliphatic(Element.Carbon) .NumOfHydrogens(-3) .Build(); + Assert.Fail(); + } + catch (ArgumentOutOfRangeException) + { } } [TestMethod()] public void IsAromatic_Unknown_from_element() { - Assert.IsNotNull(AtomBuilder.Aromatic(Unknown) - .Build()); + Assert.IsNotNull(AtomBuilder.Aromatic(Unknown).Build()); } [TestMethod()] public void IsAromatic_Unknown_from_symbol() { - Assert.IsNotNull(AtomBuilder.Aromatic("*") - .Build()); - Assert.IsNotNull(AtomBuilder.Aromatic("R") - .Build()); + Assert.IsNotNull(AtomBuilder.Aromatic("*").Build()); + Assert.IsNotNull(AtomBuilder.Aromatic("R").Build()); } } } diff --git a/NCDKTests/Beam/Core/AtomTest.cs b/NCDKTests/Beam/Core/AtomTest.cs index e671793e..5bf7f0a0 100644 --- a/NCDKTests/Beam/Core/AtomTest.cs +++ b/NCDKTests/Beam/Core/AtomTest.cs @@ -3,7 +3,7 @@ namespace NCDK.Beam { - /// John May + /// John May [TestClass()] public class AtomTest { @@ -17,10 +17,15 @@ public void AliphaticSubsetFromElement() } [TestMethod()] - [ExpectedException(typeof(ArgumentException))] public void AliphaticSubsetInvalidElement() { - AtomImpl.AliphaticSubset.OfElement(Element.Californium); + try + { + AtomImpl.AliphaticSubset.OfElement(Element.Californium); + Assert.Fail(); + } + catch (ArgumentException) + { } } [TestMethod()] @@ -33,10 +38,15 @@ public void IsAromaticSubsetFromElement() } [TestMethod()] - [ExpectedException(typeof(ArgumentException))] public void IsAromaticSubsetInvalidElement() { - AtomImpl.AromaticSubset.OfElement(Element.Unknown); + try + { + AtomImpl.AromaticSubset.OfElement(Element.Unknown); + Assert.Fail(); + } + catch (ArgumentException) + { } } } } \ No newline at end of file diff --git a/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs b/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs index 82303c3a..74ad1a88 100644 --- a/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs +++ b/NCDKTests/StructGen/Stochastic/PartialFilledStructureMergerTest.cs @@ -39,7 +39,7 @@ public void TestGenerate_IAtomContainerSet() var pfsm = new PartialFilledStructureMerger(); var result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().IsSaturated(result)); + Assert.IsTrue(CDK.SaturationChecker.IsSaturated(result)); } [TestMethod()] @@ -52,7 +52,7 @@ public void TestPartialFilledStructureMerger2() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().IsSaturated(result)); + Assert.IsTrue(CDK.SaturationChecker.IsSaturated(result)); } [TestMethod()] @@ -66,7 +66,7 @@ public void TestPartialFilledStructureMerger3() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().IsSaturated(result)); + Assert.IsTrue(CDK.SaturationChecker.IsSaturated(result)); } [TestMethod()] @@ -80,7 +80,7 @@ public void TestPartialFilledStructureMerger4() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().IsSaturated(result)); + Assert.IsTrue(CDK.SaturationChecker.IsSaturated(result)); } [TestMethod()] @@ -94,7 +94,7 @@ public void TestPartialFilledStructureMerger5() PartialFilledStructureMerger pfsm = new PartialFilledStructureMerger(); IAtomContainer result = pfsm.Generate(acs); Assert.IsTrue(ConnectivityChecker.IsConnected(result)); - Assert.IsTrue(new SaturationChecker().IsSaturated(result)); + Assert.IsTrue(CDK.SaturationChecker.IsSaturated(result)); } } } diff --git a/NCDKTests/Tools/ATASaturationCheckerTest.cs b/NCDKTests/Tools/ATASaturationCheckerTest.cs index 0d615b0d..4196dd74 100644 --- a/NCDKTests/Tools/ATASaturationCheckerTest.cs +++ b/NCDKTests/Tools/ATASaturationCheckerTest.cs @@ -34,7 +34,8 @@ namespace NCDK.Tools [TestClass()] public class ATASaturationCheckerTest : CDKTestCase { - SaturationChecker satcheck = new SaturationChecker(); + private static readonly SaturationChecker satcheck = CDK.SaturationChecker; + private static SmilesParser sp = new SmilesParser(Silent.ChemObjectBuilder.Instance); private AtomTypeAwareSaturationChecker atasc = new AtomTypeAwareSaturationChecker(); diff --git a/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs b/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs index 825d1db7..34e425d6 100644 --- a/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs +++ b/NCDKTests/Tools/DeduceBondOrderTestFromExplicitHydrogens.cs @@ -35,7 +35,7 @@ namespace NCDK.Tools [TestClass()] public class DeduceBondOrderTestFromExplicitHydrogens : CDKTestCase { - private IDeduceBondOrderTool dboTool = new SaturationChecker(); + private static readonly IDeduceBondOrderTool dboTool = CDK.SaturationChecker; /// /// Test
InChI=1/C2H2/c1-2/h1-2H
. diff --git a/NCDKTests/Tools/SaturationCheckerTest.cs b/NCDKTests/Tools/SaturationCheckerTest.cs index 7ae1a474..75d5f66b 100644 --- a/NCDKTests/Tools/SaturationCheckerTest.cs +++ b/NCDKTests/Tools/SaturationCheckerTest.cs @@ -29,7 +29,7 @@ namespace NCDK.Tools public class SaturationCheckerTest : CDKTestCase { - SaturationChecker satcheck = new SaturationChecker(); + private static readonly SaturationChecker satcheck = CDK.SaturationChecker; [TestMethod()] public void TestAllSaturated() From 4a0457756a20ac8968c7679d19aa5e250818c2d5 Mon Sep 17 00:00:00 2001 From: Kazuya Ujihara Date: Sun, 30 Sep 2018 15:19:27 +0900 Subject: [PATCH 8/8] Include XML documentation file to NuGet package --- BuildAll.bat | 21 ++++++++++++++++++--- NCDK/NCDK.nuspec | 4 +++- NCDKDisplay/NCDK.Display.nuspec | 3 ++- README.md | 29 +++++++++++++++-------------- 4 files changed, 38 insertions(+), 19 deletions(-) diff --git a/BuildAll.bat b/BuildAll.bat index c4e12bc7..5d632459 100644 --- a/BuildAll.bat +++ b/BuildAll.bat @@ -2,11 +2,19 @@ pushd NCDK dotnet add package MathNet.Numerics.Signed dotnet add package dotNetRDF dotnet restore -call :BuildProject NCDK +call :BuildProject NCDK yes popd pushd NCDKDisplay -call :BuildProject NCDK.Display +call :BuildProject NCDK.Display yes +popd + +pushd NCDKTests +call :BuildProject NCDKTests +popd + +pushd NCDKDisplayTests +call :BuildProject NCDK.DisplayTests popd goto END @@ -14,14 +22,21 @@ goto END :BuildProject set ProjectName=%1 +set NuGetOption=%2 if "%ProjectName%" == "" exit 1 +if "%NuGetOption%" == "yes" set NuGetOption=%1 MSBuild "%ProjectName%.csproj" /t:Build /p:Configuration=Release -nuget pack "%ProjectName%.nuspec" -Prop Configuration=Release -IncludeReferencedProjects + +if "%NuGetOption%" == "" goto SkipNuGet +nuget pack "%NuGetOption%.nuspec" -Prop Configuration=Release -IncludeReferencedProjects if "%MyNuGetDir%" neq "" ( xcopy /D /Y "*.nupkg" "%MyNuGetDir%" del /Q "*.nupkg" ) +:SkipNuGet + set ProjectName= +set NuGetOption= exit /b diff --git a/NCDK/NCDK.nuspec b/NCDK/NCDK.nuspec index b6f413a0..522a4f75 100644 --- a/NCDK/NCDK.nuspec +++ b/NCDK/NCDK.nuspec @@ -2,7 +2,7 @@ NCDK - 1.4.0-alpha + 1.4.0 NCDK: library of algorithms for structural cheminformatics Kazuya Ujihara kazuya @@ -21,7 +21,9 @@ + + diff --git a/NCDKDisplay/NCDK.Display.nuspec b/NCDKDisplay/NCDK.Display.nuspec index b5770058..17356e63 100644 --- a/NCDKDisplay/NCDK.Display.nuspec +++ b/NCDKDisplay/NCDK.Display.nuspec @@ -4,7 +4,7 @@ xmlns:xi="http://www.w3.org/2001/XInclude" > NCDK.Display - 1.4.0-alpha + 1.4.0 NCDK.Display: Depiction module of NCDK Kazuya Ujihara kazuya @@ -27,5 +27,6 @@ xmlns:xi="http://www.w3.org/2001/XInclude" + diff --git a/README.md b/README.md index 3cfca698..3a683846 100644 --- a/README.md +++ b/README.md @@ -12,31 +12,32 @@ Getting Started Most of codes are written in C\#. You can learn NCDK from CDK documents, NCDKTests and NCDKDisplayTests project. -* NCDK --- Core module of NCDK -* NCDK.Display --- Depiction module of NCDK -* NCDKTests --- Unit tests for NCDK -* NCDKDisplayTests --- Unit tests for NCDK.Display -* MolViewer --- MOL file viewer, which can depict SMILES. It includes WPF control to show molecular/reaction. -* Documentation --- Sandcastle Help File Builder project +* NCDK -- Core module of NCDK +* NCDK.Display -- Depiction module of NCDK. It is based on WPF. +* NCDKTests -- Unit tests for NCDK +* NCDKDisplayTests -- Unit tests for NCDK.Display +* MolViewer -- MOL file viewer, which can depict SMILES. It includes WPF control to show molecular/reaction. +* Documentation -- Sandcastle Help File Builder project -Build ------ +Build from Command Line +----------------------- -Windows: Open Developer Command Prompt for VS 2017, and launch "BuildAll.bat". Of course, you can build with Visual Studio 2017. Open NCDKDisplay.sln and build it. +Windows: Open Developer Command Prompt for VS 2017, and launch "BuildAll.bat". Linux (.NET Core): To build NCDK.dll, launch "dotnet build --framework netstandard2.0" in NCDK directory. -Test ----- +Test from Command Line +--------------------- Windows: Launch "vstest.console.exe NCDKTests\bin\Release\netcoreapp2.1\NCDKTests.dll" and "vstest.console.exe NCDKDisplayTests\bin\Release\NCDKDisplayTests.dll". -Linux: Launch "dotnet build" and copy libinchi.so.#.## to output directory of NCDKTests, and make a libinchi.so link to it and launch "dotnet test" in NCDKTests directory. +Linux: Launch "dotnet build" to build assemblies and copy libinchi.so.#.## to output directory of NCDKTests, and make a link of libinchi.so to the libinchi.so.#.##. +And then, launch "dotnet test" in NCDKTests directory to test it. NuGet Packages -------------- -* [NCDK](https://www.nuget.org/packages/NCDK/) --- .NET Standard 2.0 and .NET Framework 4.6.1. InChI features work on Windows or Linux. -* [NCDK.Display](https://www.nuget.org/packages/NCDK.Display/) --- .NET Framework 4.6.1. +* [NCDK](https://www.nuget.org/packages/NCDK/) -- for .NET Standard 2.0 and .NET Framework 4.6.1. InChI features work only on Intel-based Windows or Intel-based Linux system. +* [NCDK.Display](https://www.nuget.org/packages/NCDK.Display/) -- for .NET Framework 4.6.1. Copyright (c) 2016-2018 Kazuya Ujihara