src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
SeqDBReactionGrouper { public ReactionGroupCorpus getReactionGroupCorpus() { Map<String, ReactionGroup> sequenceToReactionGroupMap = getSequenceToReactionGroupMap(seqIterator); LOGGER.info("Done getting seq group map, found %d distinct SeqGroups.", sequenceToReactionGroupMap.size()); return new ReactionGroupCorpus(sequenceToReactionGroupMap.values()); } SeqDBReactionGrouper(Iterator<Seq> seqIterator, String dbName, Integer limit); SeqDBReactionGrouper(Iterator<Seq> seqIterator, String dbName); static void main(String[] args); ReactionGroupCorpus getReactionGroupCorpus(); static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }
@Test public void testStrictSeqGrouper_CorrectSeqGroup() { Set<Seq> sequences = new HashSet<>(); sequences.add(mockSeqA); sequences.add(mockSeqB); SeqDBReactionGrouper seqGrouper = new SeqDBReactionGrouper(sequences.iterator(), DB_NAME); int counter = 0; for (ReactionGroup group : seqGrouper.getReactionGroupCorpus()) { assertTrue("Right sequence.", group.getName().equals(NAME_A) || group.getName().equals(NAME_B)); Collection<Long> reactionIds = group.getReactionIds(); assertEquals("Three reaction ids", 3, reactionIds.size()); assertTrue("Contains first reaction ID", reactionIds.contains(REACTION_1)); assertTrue("Contains second reaction ID", reactionIds.contains(REACTION_2)); assertTrue("Contains third reaction ID", reactionIds.contains(REACTION_3)); counter++; } assertEquals("Only one seqGroup.", 1, counter); } @Test public void testStrictSeqGrouper_twoSeqGroups_rightSequences() { Set<Seq> sequences = new HashSet<>(); sequences.add(mockSeqA); sequences.add(mockSeqB); sequences.add(mockSeqC); SeqDBReactionGrouper seqGrouper = new SeqDBReactionGrouper(sequences.iterator(), DB_NAME); int counter = 0; Set<String> outputSequences = new HashSet<>(); for (ReactionGroup group : seqGrouper.getReactionGroupCorpus()) { outputSequences.add(group.getName()); counter++; } assertEquals("Two seq groups.", 2, counter); assertTrue("One seq group has first sequence.", outputSequences.contains(NAME_A) || outputSequences.contains(NAME_B)); assertTrue("One seq group has second sequence.", outputSequences.contains(NAME_C)); } @Test public void testStrictSeqGrouper_AppliesLimit() { Set<Seq> sequences = new HashSet<>(); sequences.add(mockSeqA); sequences.add(mockSeqB); sequences.add(mockSeqC); SeqDBReactionGrouper seqGrouper = new SeqDBReactionGrouper(sequences.iterator(), DB_NAME, 1); int counter = 0; for (ReactionGroup group : seqGrouper.getReactionGroupCorpus()) { counter++; } assertEquals("Only one seqGroup.", 1, counter); }
PrecursorReport { public void addLcmsData(PeakSpectrum peakSpectrum, IonCalculator ionCalculator, Set<String> ions) { for (NetworkNode node : network.getNodes()) { lcmsMap.put(node, 0.0); for (Ion ion : ionCalculator.getSelectedIons(node.getMetabolite(), ions, MS1.IonMode.POS)) { if (!peakSpectrum.getPeaksByMZ(ion.getMzValue(), 1.0).isEmpty()) { lcmsMap.put(node, 1.0); break; } } } } PrecursorReport(Metabolite target, ImmutableNetwork network); PrecursorReport( Metabolite target, ImmutableNetwork network, Map<NetworkNode, Integer> levelMap); PrecursorReport( Metabolite target, ImmutableNetwork network, Map<NetworkNode, Integer> levelMap, Map<NetworkNode, Double> lcmsMap); void addLcmsData(PeakSpectrum peakSpectrum, IonCalculator ionCalculator, Set<String> ions); Metabolite getTarget(); @JsonProperty("network") ImmutableNetwork getNetwork(); boolean isPrecursor(NetworkNode node); Integer getLevel(NetworkNode node); Double getLcmsConfidence(NetworkNode node); boolean edgeInBfsTree(NetworkNode substrate, NetworkNode product); void writeToJsonFile(File outputFile); static PrecursorReport readFromJsonFile(File inputFile); }
@Test public void testAddLcmsData() { MetabolismNetwork network = new MetabolismNetwork(); nodes.forEach(network::addNode); network.addEdgeFromInchis(Arrays.asList(INCHI_1), Arrays.asList(INCHI_2)); NetworkNode node1 = network.getNodeByInchi(INCHI_1); NetworkNode node2 = network.getNodeByInchi(INCHI_2); PrecursorReport report = network.getPrecursorReport(node2, 1); PeakSpectrum spectrum = Mockito.mock(PeakSpectrum.class); Mockito.when(spectrum.getPeaksByMZ(Mockito.any(), Mockito.any())).thenReturn(NO_PEAKS); Mockito.when(spectrum.getPeaksByMZ(MET_1_ION_1.getMzValue(), 1.0)).thenReturn(SOME_PEAKS); report.addLcmsData(spectrum, mockIonCalculator, ions); assertEquals("Metabolite 1, matching at one ion, is positive.", new Double(1.0), report.getLcmsConfidence(node1)); assertEquals("Metabolite 2, matching at no ions, is negative.", new Double(0.0), report.getLcmsConfidence(node2)); }
MetabolismNetwork implements ImmutableNetwork { @Override public List<NetworkNode> getDerivatives(NetworkNode node) { List<NetworkNode> derivatives = new ArrayList<>(); for (NetworkEdge edge : node.getOutEdges()) { edge.getProducts().forEach(p -> derivatives.add(getNodeByUID(p))); } return derivatives; } @JsonCreator private MetabolismNetwork(@JsonProperty("nodes") List<NetworkNode> nodes, @JsonProperty("edges") List<NetworkEdge> edges); MetabolismNetwork(); @Override NetworkNode getNodeByUID(Integer uid); @Override Optional<NetworkNode> getNodeOptionByUID(Integer uid); @Override NetworkNode getNodeByInchi(String inchi); @Override Optional<NetworkNode> getNodeOptionByInchi(String inchi); @Override List<NetworkNode> getNodesByMass(Double mass, Double massTolerance); @JsonIgnore @Override Collection<NetworkNode> getNodes(); Collection<NetworkEdge> getEdges(); @Override Set<NetworkNode> getSubstrates(NetworkEdge edge); @Override Set<NetworkNode> getProducts(NetworkEdge edge); @Override List<NetworkNode> getDerivatives(NetworkNode node); @Override List<NetworkNode> getPrecursors(NetworkNode node); PrecursorReport getPrecursorReport(NetworkNode startNode, int numSteps); void loadAllEdgesFromDb(MongoDB db); void loadPredictions(L2PredictionCorpus predictionCorpus); void loadEdgeFromPrediction(L2Prediction prediction); NetworkEdge addEdge(NetworkEdge edge); NetworkEdge addEdgeFromInchis(List<String> substrates, List<String> products); NetworkNode addNode(NetworkNode node); void writeToJsonFile(File outputFile); static MetabolismNetwork getNetworkFromJsonFile(File inputFile); }
@Test public void testGetDerivatives() { MetabolismNetwork network = new MetabolismNetwork(); nodes.forEach(network::addNode); network.addEdgeFromInchis(Arrays.asList(METABOLITE_1), Arrays.asList(METABOLITE_2)); network.addEdgeFromInchis(Arrays.asList(METABOLITE_1), Arrays.asList(METABOLITE_3, METABOLITE_4)); network.addEdgeFromInchis(Arrays.asList(METABOLITE_5), Arrays.asList(METABOLITE_3, METABOLITE_1)); network.addEdgeFromInchis(Arrays.asList(METABOLITE_5), Arrays.asList(METABOLITE_3, METABOLITE_2)); List<NetworkNode> derivatives = network.getDerivatives(network.getNodeByInchi(METABOLITE_1)); List<String> expectedInchis = Arrays.asList(METABOLITE_2, METABOLITE_3, METABOLITE_4); List<String> inchis = derivatives.stream().map(n -> n.getMetabolite().getStructure().get().getInchi()).collect(Collectors.toList()); assertEquals("Should be 3 derivatives.", 3, inchis.size()); assertTrue("Derivatives should be metabolites 2,3,4", inchis.containsAll(expectedInchis)); }
UniprotSeqEntry extends SequenceEntry { public DBObject getMetadata() { return this.metadata; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testMetadata() { ArrayList<DBObject> metadatas = new ArrayList<>(); List<String> uniprotAccessions = Arrays.asList("P06525", "O04080", "O04713", "O04717", "O04868", "O23821", "Q8LA61", "Q94AY6", "Q9CAZ2", "Q9CAZ3", "Q9SX08"); List<String> genbankNucleotideAccessions = Arrays.asList("M12196", "X77943", "D84240", "D84241", "D84242", "D84243", "D84244", "D84245", "D84246", "D84247", "D84248", "D84249", "D63460", "D63461", "D63462", "D63463", "D63464", "AF110456", "AB048394", "AB048395", "AY536888", "AC002291", "CP002684", "AY045612", "AY090330", "AY088010", "AF056557"); List<String> genbankProteinAccessions = Arrays.asList("AAA32728", "CAA54911", "BAA19615", "BAA19616", "BAA19617", "BAA19618", "BAA19619", "BAA19620", "BAA19621", "BAA19622", "BAA19623", "BAA19624", "BAA22983", "BAA22979", "BAA22980", "BAA22981", "BAA22982", "AAF23554", "BAB32568", "BAB32569", "AAS45601", "AAC00625", "AEE35937", "AAK73970", "AAL90991", "AAM65556", "AAD41572"); JSONObject accessions = new JSONObject(); accessions.put(Seq.AccType.uniprot.toString(), new JSONArray(uniprotAccessions)); accessions.put(Seq.AccType.genbank_nucleotide.toString(), new JSONArray(genbankNucleotideAccessions)); accessions.put(Seq.AccType.genbank_protein.toString(), new JSONArray(genbankProteinAccessions)); JSONObject obj = new JSONObject(); obj.put("xref", new JSONObject()); obj.put("name", "ADH1"); obj.put("synonyms", Collections.singletonList("ADH")); obj.put("product_names", Arrays.asList("Alcohol dehydrogenase class-P", "Alc Dehyd")); obj.put("accession", accessions); obj.put("catalytic_activity", "An alcohol + NAD(+) = an aldehyde or ketone + NADH."); metadatas.add(MongoDBToJSON.conv(obj)); assertEquals("tests whether metadata is extracted accurately", metadatas.get(0), seqEntries.get(0).getMetadata()); }
MetabolismNetwork implements ImmutableNetwork { @Override public List<NetworkNode> getPrecursors(NetworkNode node) { List<NetworkNode> precursors = new ArrayList<>(); for (NetworkEdge edge : node.getInEdges()) { edge.getSubstrates().forEach(s -> precursors.add(getNodeByUID(s))); } return precursors; } @JsonCreator private MetabolismNetwork(@JsonProperty("nodes") List<NetworkNode> nodes, @JsonProperty("edges") List<NetworkEdge> edges); MetabolismNetwork(); @Override NetworkNode getNodeByUID(Integer uid); @Override Optional<NetworkNode> getNodeOptionByUID(Integer uid); @Override NetworkNode getNodeByInchi(String inchi); @Override Optional<NetworkNode> getNodeOptionByInchi(String inchi); @Override List<NetworkNode> getNodesByMass(Double mass, Double massTolerance); @JsonIgnore @Override Collection<NetworkNode> getNodes(); Collection<NetworkEdge> getEdges(); @Override Set<NetworkNode> getSubstrates(NetworkEdge edge); @Override Set<NetworkNode> getProducts(NetworkEdge edge); @Override List<NetworkNode> getDerivatives(NetworkNode node); @Override List<NetworkNode> getPrecursors(NetworkNode node); PrecursorReport getPrecursorReport(NetworkNode startNode, int numSteps); void loadAllEdgesFromDb(MongoDB db); void loadPredictions(L2PredictionCorpus predictionCorpus); void loadEdgeFromPrediction(L2Prediction prediction); NetworkEdge addEdge(NetworkEdge edge); NetworkEdge addEdgeFromInchis(List<String> substrates, List<String> products); NetworkNode addNode(NetworkNode node); void writeToJsonFile(File outputFile); static MetabolismNetwork getNetworkFromJsonFile(File inputFile); }
@Test public void testGetPrecursors() { MetabolismNetwork network = new MetabolismNetwork(); nodes.forEach(network::addNode); network.addEdgeFromInchis(Arrays.asList(METABOLITE_2), Arrays.asList(METABOLITE_1)); network.addEdgeFromInchis(Arrays.asList(METABOLITE_3, METABOLITE_4), Arrays.asList(METABOLITE_1)); network.addEdgeFromInchis(Arrays.asList(METABOLITE_1, METABOLITE_3), Arrays.asList(METABOLITE_5)); network.addEdgeFromInchis(Arrays.asList(METABOLITE_2, METABOLITE_3), Arrays.asList(METABOLITE_5)); List<NetworkNode> precursors = network.getPrecursors(network.getNodeByInchi(METABOLITE_1)); List<String> expectedInchis = Arrays.asList(METABOLITE_2, METABOLITE_3, METABOLITE_4); List<String> inchis = precursors.stream().map(n -> n.getMetabolite().getStructure().get().getInchi()).collect(Collectors.toList()); assertEquals("Should be 3 precursors.", 3, inchis.size()); assertTrue("Precursors should be metabolites 2,3,4", inchis.containsAll(expectedInchis)); }
ReactionMerger extends BiointerpretationProcessor { protected static Map<SubstratesProducts, PriorityQueue<Long>> hashReactions(Iterator<Reaction> reactionIterator) { HashMap<SubstratesProducts, PriorityQueue<Long>> reactionGroups = new HashMap<>(); while (reactionIterator.hasNext()) { Reaction rxn = reactionIterator.next(); SubstratesProducts sp = new SubstratesProducts(rxn); PriorityQueue<Long> pq = reactionGroups.get(sp); Long id = Long.valueOf(rxn.getUUID()); if (pq != null) { pq.add(id); } else { pq = new PriorityQueue<>(1); pq.add(id); reactionGroups.put(sp, pq); } } return reactionGroups; } ReactionMerger(NoSQLAPI noSQLAPI); @Override String getName(); @Override void init(); @Override void processReactions(); }
@Test public void testHashing() throws Exception { ReactionHashingTestCase[] testCases = new ReactionHashingTestCase[] { new ReactionHashingTestCase("Rxns with same sub/prod and no cofactors/enzymes should be hashed to one bucket", 1). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Reactions with subset substrates should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L, 5L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Reactions with subset substreates should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L, 5L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with different subs. and no cofactors/enzymes should be hashed as two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{5L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxn with same sub/prod but different EC numbers should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.2", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with same sub/prod and different sub. cofactors should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[]{1L}, new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with same sub/prod and different prod. cofactors should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[]{1L}, new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with same sub/prod and different coenzymes should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[]{1L}, "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[]{2L}, "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with same sub/prod and different coefficients should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)).setSubstrateCoefficient(0, 1, 1). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)).setSubstrateCoefficient(1, 1, 2), new ReactionHashingTestCase("Rxns with same sub/prod and different conv. directions should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.RIGHT_TO_LEFT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with same sub/prod and different step directions should be hashed to two buckets", 2). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.RIGHT_TO_LEFT, "Reaction 2", Reaction.RxnDetailType.CONCRETE)), new ReactionHashingTestCase("Rxns with same sub/prod and different rxn detail types should be hashed to one bucket", 1). addRxn(new Reaction( 1L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 1", Reaction.RxnDetailType.CONCRETE)). addRxn(new Reaction( 2L, new Long[]{1L, 2L}, new Long[]{3L, 4L}, new Long[0], new Long[0], new Long[0], "1.1.1.1", ConversionDirectionType.LEFT_TO_RIGHT, StepDirection.LEFT_TO_RIGHT, "Reaction 2", Reaction.RxnDetailType.ABSTRACT)) }; for (ReactionHashingTestCase testCase : testCases) { Map<ReactionMerger.SubstratesProducts, PriorityQueue<Long>> results = ReactionMerger.hashReactions(testCase.rxnIterator()); assertEquals(testCase.getDescription(), testCase.getExpectedHashBucketCount(), Integer.valueOf(results.size())); } }
ReactionMerger extends BiointerpretationProcessor { @Override public void init() { markInitialized(); } ReactionMerger(NoSQLAPI noSQLAPI); @Override String getName(); @Override void init(); @Override void processReactions(); }
@Test public void testOrganismMigrationForDifferentProteinTypes() throws Exception { List<Reaction> testReactions = new ArrayList<>(); testReactions.add(utilsObject.makeTestReaction(new Long[]{1L, 2L, 3L}, new Long[]{4L, 5L, 6L}, false)); testReactions.add(utilsObject.makeTestReaction(new Long[]{4L, 5L, 6L}, new Long[]{7L, 8L, 9L}, true)); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, new HashMap<>()); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); ReactionMerger merger = new ReactionMerger(mockNoSQLAPI); merger.init(); merger.run(); assertEquals("Reactions should not have been merged", 2, mockAPI.getWrittenReactions().size()); Reaction writtenReaction1 = mockAPI.getWrittenReactions().get(0); assertEquals("Reaction 1 has one protein", 1, writtenReaction1.getProteinData().size()); JSONObject reaction1Protein = writtenReaction1.getProteinData().iterator().next(); assertTrue("Reaction 1's protein has an organism field", reaction1Protein.has("organism")); assertFalse("Reaction 1's protein does not have an organisms field", reaction1Protein.has("organisms")); assertTrue("Reaction 2's protein's organisms is a Long", reaction1Protein.get("organism") instanceof Long); assertEquals("Reaction 1's protein has the correct single organism id", 1L, reaction1Protein.getLong("organism")); Reaction writtenReaction2 = mockAPI.getWrittenReactions().get(1); assertEquals("Reaction 2 has one protein", 1, writtenReaction2.getProteinData().size()); JSONObject reaction2Protein = writtenReaction2.getProteinData().iterator().next(); assertFalse("Reaction 2's protein does not have an organism field", reaction2Protein.has("organism")); assertTrue("Reaction 2's protein has an organisms field", reaction2Protein.has("organisms")); assertTrue("Reaction 2's protein's organisms is a JSONArray", reaction2Protein.get("organisms") instanceof JSONArray); JSONArray reaction2ProteinOrganisms = reaction2Protein.getJSONArray("organisms"); assertEquals("Reaction 2's protein's organisms has one entry", 1L, reaction2ProteinOrganisms.length()); assertTrue("Reaction 2's protein's organisms' first entry is a long", reaction2ProteinOrganisms.get(0) instanceof Long); assertEquals("Reaction 2's protein's organisms' first entry is unchanged from the original", 1L, reaction2ProteinOrganisms.getLong(0)); } @Test public void testMergingEndToEnd() throws Exception { List<Reaction> testReactions = new ArrayList<>(); testReactions.add(utilsObject.makeTestReaction(new Long[]{1L, 2L, 3L}, new Long[]{4L, 5L, 6L})); testReactions.add(utilsObject.makeTestReaction(new Long[]{1L, 2L, 3L}, new Long[]{4L, 5L, 6L})); testReactions.add(utilsObject.makeTestReaction(new Long[]{1L, 2L, 3L}, new Long[]{4L, 5L, 6L})); testReactions.add(utilsObject.makeTestReaction(new Long[]{7L, 2L, 3L}, new Long[]{8L, 5L, 6L})); testReactions.add(utilsObject.makeTestReaction(new Long[]{7L, 2L, 3L}, new Long[]{8L, 5L, 6L})); testReactions.add(utilsObject.makeTestReaction(new Long[]{9L, 2L, 3L}, new Long[]{8L, 5L, 6L})); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, new HashMap<>()); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); ReactionMerger merger = new ReactionMerger(mockNoSQLAPI); merger.init(); merger.run(); assertEquals("Input reactions should be merged into three output reactions", 3, mockAPI.getWrittenReactions().size()); Reaction r1 = mockAPI.getWrittenReactions().get(0); assertNotNull("Merged reaction 1 should not be null", r1); assertEquals("Merged reaction 1 has expected substrates", mockAPI.readDBChemicalIdsToInchis(new Long[] {1L, 2L, 3L}), mockAPI.writeDBChemicalIdsToInchis(r1.getSubstrates()) ); assertEquals("Merged reaction 1 has expected products", mockAPI.readDBChemicalIdsToInchis(new Long[] {4L, 5L, 6L}), mockAPI.writeDBChemicalIdsToInchis(r1.getProducts()) ); assertEquals("Merged reaction 1 should have 3 protein objects", 3, r1.getProteinData().size()); Set<String> r1Sequences = new HashSet<>(3); for (JSONObject o : r1.getProteinData()) { Long id = o.getLong("id"); JSONArray sequences = o.getJSONArray("sequences"); assertNotNull("Sequences for protein %d should not be null", id); assertEquals(String.format("Protein %d should have one sequence", id), 1, sequences.length()); Seq seq = mockAPI.getWrittenSequences().get(sequences.getLong(0)); assertNotNull("Referenced seq object should not be null", seq); assertEquals("New sequence object's sequence string should match original", utilsObject.SEQ_MAP.get(id * 10L).getSequence(), seq.getSequence()); r1Sequences.add(seq.getSequence()); assertEquals("New Seq object should reference the migrated reaction by id", Long.valueOf(r1.getUUID()), seq.getReactionsCatalyzed().iterator().next()); } assertEquals("All expected sequences are accounted for", new HashSet<>(Arrays.asList("SEQA", "SEQB", "SEQC")), r1Sequences ); Reaction r2 = mockAPI.getWrittenReactions().get(1); assertNotNull("Merged reaction 2 should not be null", r2); assertEquals("Merged reaction 2 has expected substrates", mockAPI.readDBChemicalIdsToInchis(new Long[] {7L, 2L, 3L}), mockAPI.writeDBChemicalIdsToInchis(r2.getSubstrates()) ); assertEquals("Merged reaction 2 has expected products", mockAPI.readDBChemicalIdsToInchis(new Long[] {8L, 5L, 6L}), mockAPI.writeDBChemicalIdsToInchis(r2.getProducts()) ); assertEquals("Merged reaction 2 should have 2 protein objects", 2, r2.getProteinData().size()); Set<String> r2Sequences = new HashSet<>(2); for (JSONObject o : r2.getProteinData()) { Long id = o.getLong("id"); JSONArray sequences = o.getJSONArray("sequences"); assertNotNull("Sequences for protein %d should not be null", id); assertEquals(String.format("Protein %d should have one sequence", id), 1, sequences.length()); Seq seq = mockAPI.getWrittenSequences().get(sequences.getLong(0)); assertNotNull("Referenced seq object should not be null", seq); assertEquals("New sequence object's sequence string should match original", utilsObject.SEQ_MAP.get(id * 10L).getSequence(), seq.getSequence()); r2Sequences.add(seq.getSequence()); assertEquals("New Seq object should reference the migrated reaction by id", Long.valueOf(r2.getUUID()), seq.getReactionsCatalyzed().iterator().next()); } assertEquals("All expected sequences are accounted for", new HashSet<>(Arrays.asList("SEQD", "SEQE")), r2Sequences ); Reaction r3 = mockAPI.getWrittenReactions().get(2); assertNotNull("Merged reaction 3 should not be null", r3); assertEquals("Merged reaction 3 has expected substrates", mockAPI.readDBChemicalIdsToInchis(new Long[] {9L, 2L, 3L}), mockAPI.writeDBChemicalIdsToInchis(r3.getSubstrates()) ); assertEquals("Merged reaction 3 has expected products", mockAPI.readDBChemicalIdsToInchis(new Long[] {8L, 5L, 6L}), mockAPI.writeDBChemicalIdsToInchis(r3.getProducts()) ); assertEquals("Merged reaction 3 should have 1 protein objects", 1, r3.getProteinData().size()); Set<String> r3Sequences = new HashSet<>(1); for (JSONObject o : r3.getProteinData()) { Long id = o.getLong("id"); JSONArray sequences = o.getJSONArray("sequences"); assertNotNull("Sequences for protein %d should not be null", id); assertEquals(String.format("Protein %d should have one sequence", id), 1, sequences.length()); Seq seq = mockAPI.getWrittenSequences().get(sequences.getLong(0)); assertNotNull("Referenced seq object should not be null", seq); assertEquals("New sequence object's sequence string should match original", utilsObject.SEQ_MAP.get(id * 10L).getSequence(), seq.getSequence()); r3Sequences.add(seq.getSequence()); assertEquals("New Seq object should reference the migrated reaction by id", Long.valueOf(r3.getUUID()), seq.getReactionsCatalyzed().iterator().next()); } assertEquals("All expected sequences are accounted for", new HashSet<>(Arrays.asList("SEQF")), r3Sequences ); } @Test public void testCoefficientsAreCorrectlyTransferred() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Long[] substrates = {1L, 2L, 3L}; Long[] products = {4L, 5L, 6L}; Integer[] substrateCoefficients = {1, 2, 3}; Integer[] productCoefficients = {2, 3, 1}; testReactions.add(utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, false)); testReactions.add(utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, false)); for (int i = 0; i < substrates.length; i++) { assertEquals(String.format("Input reaction substrate %d has correct coefficient set", substrates[i]), substrateCoefficients[i], testReactions.get(0).getSubstrateCoefficient(substrates[i])); } for (int i = 0; i < products.length; i++) { assertEquals(String.format("Input reaction product %d has correct coefficient set", products[i]), productCoefficients[i], testReactions.get(0).getProductCoefficient(products[i])); } MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, new HashMap<>()); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); ReactionMerger merger = new ReactionMerger(mockNoSQLAPI); merger.init(); merger.run(); assertEquals("Input reactions should be merged into one output reactions", 1, mockAPI.getWrittenReactions().size()); Reaction rxn = mockAPI.getWrittenReactions().get(0); List<Long> writtenSubstrates = new ArrayList<>(Arrays.asList(rxn.getSubstrates())); List<Long> writtenProducts = new ArrayList<>(Arrays.asList(rxn.getProducts())); Collections.sort(writtenSubstrates); Collections.sort(writtenProducts); for (int i = 0; i < writtenSubstrates.size(); i++) { Integer newCoefficient = rxn.getSubstrateCoefficient(writtenSubstrates.get(i)); assertNotNull(String.format("Output reaction substrate coefficient for chemical %d is not null", i), newCoefficient); assertEquals(String.format("Coefficient for output chemical %d matches original", i), substrateCoefficients[i], newCoefficient); } for (int i = 0; i < writtenProducts.size(); i++) { Integer newCoefficient = rxn.getProductCoefficient(writtenProducts.get(i)); assertNotNull(String.format("Output reaction product coefficient for chemical %d is not null", i), newCoefficient); assertEquals(String.format("Coefficient for output chemical %d matches original", i), productCoefficients[i], newCoefficient); } }
ReactionsTransformer implements Function<L2Prediction, L2Prediction> { public L2Prediction apply(L2Prediction prediction) { if (prediction.getSubstrateIds().isEmpty() || prediction.getProductIds().isEmpty() || prediction.getSubstrateIds().size() < prediction.getSubstrates().size() || prediction.getProductIds().size() < prediction.getProducts().size()) { return prediction; } List<Long> substrateIds = prediction.getSubstrateIds(); List<Long> productIds = prediction.getProductIds(); List<Reaction> reactionsFromDB = mongoDB.getRxnsWithAll(substrateIds, productIds); List<Long> reactionsRoMatch = new ArrayList<Long>(); List<Long> reactionsNoRoMatch = new ArrayList<Long>(); for (Reaction reaction : reactionsFromDB) { if (reactionMatchesRo(reaction, prediction.getProjectorName())) { reactionsRoMatch.add(new Long(reaction.getUUID())); } else { reactionsNoRoMatch.add(new Long(reaction.getUUID())); } } prediction.setReactionsRoMatch(reactionsRoMatch); prediction.setReactionsNoRoMatch(reactionsNoRoMatch); return prediction; } ReactionsTransformer(MongoDB mongoDB); L2Prediction apply(L2Prediction prediction); }
@Test public void testReactionInDBRoMatch() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(SUBSTRATE_PREDICTION_CHEMICAL), ERO_ID_STRING, Arrays.asList(PRODUCT_PRODUCED_CHEMICAL)); testPrediction.getSubstrates().get(0).setId(SUBSTRATE_ID); testPrediction.getProducts().get(0).setId(PRODUCT_PRODUCED_ID); reaction.setMechanisticValidatorResult(validationRoMatch); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("Should return one matching reaction.", 1, result.getReactionsRoMatch().size()); assertEquals("Reaction ID should match DB response.", REACTION_ID, result.getReactionsRoMatch().get(0)); assertTrue("Should return no non-matching reactions.", result.getReactionsNoRoMatch().isEmpty()); } @Test public void testReactionInDBNoRoMatch() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(SUBSTRATE_PREDICTION_CHEMICAL), ERO_ID_STRING, Arrays.asList(PRODUCT_PRODUCED_CHEMICAL)); reaction.setMechanisticValidatorResult(validationNoRoMatch); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("Should return one non-matching reaction.", 1, result.getReactionsNoRoMatch().size()); assertEquals("Reaction ID should match DB response.", REACTION_ID, result.getReactionsNoRoMatch().get(0)); assertTrue("Should return no matching reactions.", result.getReactionsRoMatch().isEmpty()); } @Test public void testReactionNotInDB() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(SUBSTRATE_PREDICTION_CHEMICAL), ERO_ID_STRING, Arrays.asList(PRODUCT_NOT_PRODUCED_CHEMICAL)); testPrediction.getSubstrates().get(0).setId(SUBSTRATE_ID); testPrediction.getProducts().get(0).setId(PRODUCT_NOT_PRODUCED_ID); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertTrue("Should return no matching reaction.", result.getReactionsRoMatch().isEmpty()); assertTrue("Should return no non-matching reaction.", result.getReactionsNoRoMatch().isEmpty()); } @Test public void testReactionSubstrateEmpty() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(ONLY_INCHI_CHEMICAL), ERO_ID_STRING, Arrays.asList(PRODUCT_PRODUCED_CHEMICAL)); testPrediction.getProducts().get(0).setId(PRODUCT_PRODUCED_ID); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("No substrate- should return no reactions", 0, result.getReactionCount()); } @Test public void testReactionProductEmpty() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(SUBSTRATE_PREDICTION_CHEMICAL), ERO_ID_STRING, Arrays.asList(ONLY_INCHI_CHEMICAL)); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("No product- should return no reactions", 0, result.getReactionCount()); } @Test public void testReactionOneSubstrateNotInDB() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(ONLY_INCHI_CHEMICAL, SUBSTRATE_PREDICTION_CHEMICAL), ERO_ID_STRING, Arrays.asList(PRODUCT_PRODUCED_CHEMICAL)); testPrediction.getProducts().get(0).setId(PRODUCT_PRODUCED_ID); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("One substrate has no ID- should return no reactions", 0, result.getReactionCount()); } @Test public void testReactionOneProductNotInDB() { L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, Arrays.asList(SUBSTRATE_PREDICTION_CHEMICAL), ERO_ID_STRING, Arrays.asList(ONLY_INCHI_CHEMICAL, PRODUCT_PRODUCED_CHEMICAL)); testPrediction.getProducts().get(0).setId(PRODUCT_PRODUCED_ID); Function<L2Prediction, L2Prediction> filter = new ReactionsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("One substrate has no ID- should return no reactions", 0, result.getReactionCount()); }
UniprotSeqEntry extends SequenceEntry { public JSONObject getAccession() { return this.accessions; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testAccession() { List<String> uniprotAccessions = Arrays.asList("P06525", "O04080", "O04713", "O04717", "O04868", "O23821", "Q8LA61", "Q94AY6", "Q9CAZ2", "Q9CAZ3", "Q9SX08"); List<String> genbankNucleotideAccessions = Arrays.asList("M12196", "X77943", "D84240", "D84241", "D84242", "D84243", "D84244", "D84245", "D84246", "D84247", "D84248", "D84249", "D63460", "D63461", "D63462", "D63463", "D63464", "AF110456", "AB048394", "AB048395", "AY536888", "AC002291", "CP002684", "AY045612", "AY090330", "AY088010", "AF056557"); List<String> genbankProteinAccessions = Arrays.asList("AAA32728", "CAA54911", "BAA19615", "BAA19616", "BAA19617", "BAA19618", "BAA19619", "BAA19620", "BAA19621", "BAA19622", "BAA19623", "BAA19624", "BAA22983", "BAA22979", "BAA22980", "BAA22981", "BAA22982", "AAF23554", "BAB32568", "BAB32569", "AAS45601", "AAC00625", "AEE35937", "AAK73970", "AAL90991", "AAM65556", "AAD41572"); JSONObject accessions = new JSONObject(); accessions.put(Seq.AccType.uniprot.toString(), new JSONArray(uniprotAccessions)); accessions.put(Seq.AccType.genbank_nucleotide.toString(), new JSONArray(genbankNucleotideAccessions)); accessions.put(Seq.AccType.genbank_protein.toString(), new JSONArray(genbankProteinAccessions)); assertEquals("tests whether accession ID is extracted accurately", accessions.toString(), seqEntries.get(0).getAccession().toString()); }
ChemicalsTransformer implements Function<L2Prediction, L2Prediction> { public L2Prediction apply(L2Prediction prediction) { for (L2PredictionChemical predictedChemical : prediction.getProducts()) { String inchi = predictedChemical.getInchi(); Chemical product = mongoDB.getChemicalFromInChI(inchi); if (product != null) { predictedChemical.setId(product.getUuid()); predictedChemical.setName(product.getFirstName()); } } for (L2PredictionChemical predictedChemical : prediction.getSubstrates()) { String inchi = predictedChemical.getInchi(); Chemical substrate = mongoDB.getChemicalFromInChI(inchi); if (substrate != null) { predictedChemical.setId(substrate.getUuid()); predictedChemical.setName(substrate.getFirstName()); } } return prediction; } ChemicalsTransformer(MongoDB mongoDB); L2Prediction apply(L2Prediction prediction); }
@Test public void testChemicalsInDB() { List<L2PredictionChemical> testSubstrates = L2PredictionChemical.getPredictionChemicals(Arrays.asList(VALID_SUBSTRATE)); List<L2PredictionChemical> testProducts = L2PredictionChemical.getPredictionChemicals(Arrays.asList(VALID_PRODUCT)); L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, testSubstrates, GROUP_NAME, testProducts); Function<L2Prediction, L2Prediction> filter = new ChemicalsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("Should contain one substrate ID.", 1, result.getSubstrateIds().size()); assertEquals("Should contain one product ID.", 1, result.getProductIds().size()); assertEquals("Should contain correct substrate ID.", SUBSTRATE_ID, result.getSubstrateIds().get(0)); assertEquals("Should contain correct substrate name.", SUBSTRATE_NAME, result.getSubstrateNames().get(0)); assertEquals("Should contain correct product inchi.", PRODUCT_ID, result.getProductIds().get(0)); assertEquals("Should contain correct product name.", PRODUCT_NAME, result.getProductNames().get(0)); } @Test public void testSubstrateNotInDB() { List<L2PredictionChemical> testSubstrates = L2PredictionChemical.getPredictionChemicals(Arrays.asList(INVALID_INCHI)); List<L2PredictionChemical> testProducts = L2PredictionChemical.getPredictionChemicals(Arrays.asList(VALID_PRODUCT)); L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, testSubstrates, GROUP_NAME, testProducts); Function<L2Prediction, L2Prediction> filter = new ChemicalsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("Should contain no substrate ID.", 0, result.getSubstrateIds().size()); assertEquals("Should contain no substrate name.", 0, result.getSubstrateNames().size()); assertEquals("Should contain one product ID.", 1, result.getProductIds().size()); assertEquals("Should contain one product name.", 1, result.getProductNames().size()); } @Test public void testProductNotInDB() { List<L2PredictionChemical> testSubstrates = L2PredictionChemical.getPredictionChemicals(Arrays.asList(VALID_SUBSTRATE)); List<L2PredictionChemical> testProducts = L2PredictionChemical.getPredictionChemicals(Arrays.asList(INVALID_INCHI)); L2Prediction testPrediction = new L2Prediction(PREDICTION_ID, testSubstrates, GROUP_NAME, testProducts); Function<L2Prediction, L2Prediction> filter = new ChemicalsTransformer(mockMongo); L2Prediction result = filter.apply(testPrediction); assertEquals("Should contain one substrate ID.", 1, result.getSubstrateIds().size()); assertEquals("Should contain one substrate name.", 1, result.getSubstrateNames().size()); assertEquals("Should contain no product ID.", 0, result.getProductIds().size()); assertEquals("Should contain no product name.", 0, result.getProductNames().size()); }
CofactorRemover extends BiointerpretationProcessor { public void init() throws IOException { cofactorsCorpus = new CofactorsCorpus(); cofactorsCorpus.loadCorpus(); blacklistedInchisCorpus = new BlacklistedInchisCorpus(); blacklistedInchisCorpus.loadCorpus(); markInitialized(); } CofactorRemover(NoSQLAPI api); @Override String getName(); void init(); }
@Test public void testReactionWithCofactorIsTransformedCorrectlyWhileReactionWithoutCofactorIsNottransformed() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Long[] products = {4L}; Map<Long, String> idToInchi = new HashMap<>(); idToInchi.put(1L, "InChI=1/C10H15N4O15P3/c15-5-3(1-26-31(22,23)29-32(24,25)28-30(19,20)21)27-9(6(5)16)14-2-11-4-7(14)12-10(18)13-8(4)17/h2-3,5-6,9,15-16H,1H2,(H,22,23)(H,24,25)(H2,19,20,21)(H2,12,13,17,18)"); idToInchi.put(2L, "InChI=1S/CH2O2/c2-1-3/h1H,(H,2,3)/p-1"); idToInchi.put(3L, "InChI=1S/C7H5Cl3/c8-4-5-2-1-3-6(9)7(5)10/h1-3H,4H2"); Long[] substrates1 = {1L, 3L}; Long[] substrates2 = {2L}; Integer[] substrateCoefficients1 = {2, 3}; Integer[] substrateCoefficients2 = {2}; Integer[] productCoefficients = {3}; Reaction testReaction1 = utilsObject.makeTestReaction(substrates1, products, substrateCoefficients1, productCoefficients, true); Reaction testReaction2 = utilsObject.makeTestReaction(substrates2, products, substrateCoefficients2, productCoefficients, true); testReactions.add(testReaction1); testReactions.add(testReaction2); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); CofactorRemover cofactorRemover = new CofactorRemover(mockNoSQLAPI); cofactorRemover.init(); cofactorRemover.run(); assertEquals("Similar pre-cofactor removal substrates should be written as two entries", 2, mockAPI.getWrittenReactions().size()); assertEquals("Since the first reaction had a cofactor in the substrates, there should one substrate after the cofactor" + " is removed", 1, mockAPI.getWrittenReactions().get(0).getSubstrates().length); assertEquals("Since the first reaction had a cofactor in the substrates, there should be one substrate coefficients after the cofactor" + " is removed", 1, mockAPI.getWrittenReactions().get(0).getSubstrateIdsOfSubstrateCoefficients().size()); assertEquals("There should be one entry in the substrate cofactors list", 1, mockAPI.getWrittenReactions().get(0).getSubstrateCofactors().length); assertEquals("The substrate cofactor should match the correct substrate id", 1L, mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[0].longValue()); assertEquals("The write substrate should match the correct read substrate id", "InChI=1S/CH2O2/c2-1-3/h1H,(H,2,3)/p-1", mockAPI.getWrittenChemicals().get( mockAPI.getWrittenReactions().get(1).getSubstrates()[0].longValue()).getInChI()); assertEquals("Since the second reaction does not have a cofactor in the substrates, there should a substrate in the " + "write db", 1, mockAPI.getWrittenReactions().get(1).getSubstrates().length); assertEquals("There should be no entry in the substrate cofactors list", 0, mockAPI.getWrittenReactions().get(1).getSubstrateCofactors().length); } @Test public void testAllCofactorsShouldBeRemoved() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Long[] products = {4L}; Map<Long, String> idToInchi = new HashMap<>(); String testInchi1 = "InChI=1/C10H15N4O15P3/c15-5-3(1-26-31(22,23)29-32(24,25)28-30(19,20)21)27-9(6(5)16)14-2-11-4-7(14)12-10(18)13-8(4)17/h2-3,5-6,9,15-16H,1H2,(H,22,23)(H,24,25)(H2,19,20,21)(H2,12,13,17,18)"; idToInchi.put(1L, testInchi1); String test2 = "InChI=1/C14H20N6O5S/c15-6(14(23)24)1-2-26-3-7-9(21)10(22)13(25-7)20-5-19-8-11(16)17-4-18-12(8)20/h4-7,9-10,13,21-22H,1-3,15H2,(H,23,24)(H2,16,17,18)"; idToInchi.put(2L, test2); String test3 = "InChI=1/C14H20N6O5S/c15-6(14(23)24)1-2-26-3-7-9(21)10(22)13(25-7)20-5-19-8-11(16)17-4-18-12(8)20/h4-7,9-10,13,21-22H,1-3,15H2,(H,23,24)(H2,16,17,18)"; idToInchi.put(3L, test3); Integer[] substrateCoefficients = {2, 3, 3}; Integer[] productCoefficients = {3}; Long[] substrates = {1L, 2L, 3L}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); CofactorRemover cofactorRemover = new CofactorRemover(mockNoSQLAPI); cofactorRemover.init(); cofactorRemover.run(); assertEquals("Similar pre-cofactor removal substrates should be written as one entry", 1, mockAPI.getWrittenReactions().size()); assertEquals("The first reaction had 3 cofactors in the substrates, but there should be no substrates after the cofactor" + " is removed", 0, mockAPI.getWrittenReactions().get(0).getSubstrates().length); assertEquals("There should be three entries in the substrate cofactors list", 3, mockAPI.getWrittenReactions().get(0).getSubstrateCofactors().length); assertEquals("The substrate cofactor should match the correct substrate id", testInchi1, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[0].longValue()).getInChI()); assertEquals("The substrate cofactor should match the correct substrate id", test2, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[1].longValue()).getInChI()); assertEquals("The substrate cofactor should match the correct substrate id", test3, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[2].longValue()).getInChI()); } @Test public void testExistingCofactorsAreNotOverwritten() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Long[] products = {4L}; Map<Long, String> idToInchi = new HashMap<>(); String testInchi1 = "InChI=1/C10H15N4O15P3/c15-5-3(1-26-31(22,23)29-32(24,25)28-30(19,20)21)27-9(6(5)16)14-2-11-4-7(14)12-10(18)13-8(4)17/h2-3,5-6,9,15-16H,1H2,(H,22,23)(H,24,25)(H2,19,20,21)(H2,12,13,17,18)"; idToInchi.put(1L, testInchi1); String test2 = "InChI=1/C14H20N6O5S/c15-6(14(23)24)1-2-26-3-7-9(21)10(22)13(25-7)20-5-19-8-11(16)17-4-18-12(8)20/h4-7,9-10,13,21-22H,1-3,15H2,(H,23,24)(H2,16,17,18)"; idToInchi.put(2L, test2); String test3 = "InChI=1/C14H20N6O5S/c15-6(14(23)24)1-2-26-3-7-9(21)10(22)13(25-7)20-5-19-8-11(16)17-4-18-12(8)20/h4-7,9-10,13,21-22H,1-3,15H2,(H,23,24)(H2,16,17,18)"; idToInchi.put(3L, test3); Integer[] substrateCoefficients = {2, 3}; Integer[] productCoefficients = {3}; Long[] substrates = {1L, 2L}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReaction.setSubstrateCofactors(new Long[]{3L}); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, Arrays.asList(3L), utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); CofactorRemover cofactorRemover = new CofactorRemover(mockNoSQLAPI); cofactorRemover.init(); cofactorRemover.run(); assertEquals("Similar pre-cofactor removal substrates should be written as one entry", 1, mockAPI.getWrittenReactions().size()); assertEquals("The first reaction had 2 cofactors in the substrates, but there should be no substrates after the cofactor" + " is removed", 0, mockAPI.getWrittenReactions().get(0).getSubstrates().length); assertEquals("There should be three entries in the substrate cofactors list", 3, mockAPI.getWrittenReactions().get(0).getSubstrateCofactors().length); assertEquals("The substrate cofactor that was already in the reaction should persist and appear first", test3, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[0].longValue()).getInChI()); assertEquals("The substrate cofactor should match the correct substrate id", testInchi1, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[1].longValue()).getInChI()); assertEquals("The substrate cofactor should match the correct substrate id", test2, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[2].longValue()).getInChI()); } @Test public void testReactionWithNoEffectIsNotWritten() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); String testInchi1 = "InChI=1/C10H15N4O15P3/c15-5-3(1-26-31(22,23)29-32(24,25)28-30(19,20)21)27-9(6(5)16)14-2-11-4-7(14)12-10(18)13-8(4)17/h2-3,5-6,9,15-16H,1H2,(H,22,23)(H,24,25)(H2,19,20,21)(H2,12,13,17,18)"; idToInchi.put(1L, testInchi1); Integer[] substrateCoefficients = {3}; Integer[] productCoefficients = {3}; Long[] substrates = {1L}; Long[] products = {1L}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReaction.setSubstrateCofactors(new Long[]{3L}); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); CofactorRemover cofactorRemover = new CofactorRemover(mockNoSQLAPI); cofactorRemover.init(); cofactorRemover.run(); assertEquals("A reaction that imparts no change to its substrate should not be written", 0, mockAPI.getWrittenReactions().size()); } @Test public void testReactionThatChangesOnlyCofactorsIsStillWritten() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); String testInchi1 = "InChI=1/C10H15N4O15P3/c15-5-3(1-26-31(22,23)29-32(24,25)28-30(19,20)21)27-9(6(5)16)14-2-11-4-7(14)12-10(18)13-8(4)17/h2-3,5-6,9,15-16H,1H2,(H,22,23)(H,24,25)(H2,19,20,21)(H2,12,13,17,18)"; idToInchi.put(1L, testInchi1); String test2 = "InChI=1/C14H20N6O5S/c15-6(14(23)24)1-2-26-3-7-9(21)10(22)13(25-7)20-5-19-8-11(16)17-4-18-12(8)20/h4-7,9-10,13,21-22H,1-3,15H2,(H,23,24)(H2,16,17,18)"; idToInchi.put(2L, test2); String test3 = "InChI=1/C14H20N6O5S/c15-6(14(23)24)1-2-26-3-7-9(21)10(22)13(25-7)20-5-19-8-11(16)17-4-18-12(8)20/h4-7,9-10,13,21-22H,1-3,15H2,(H,23,24)(H2,16,17,18)"; idToInchi.put(3L, test3); Integer[] substrateCoefficients = {1}; Integer[] productCoefficients = {1}; Long[] substrates = {1L}; Long[] products = {1L}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReaction.setSubstrateCofactors(new Long[]{2L}); testReaction.setProductCofactors(new Long[]{3L}); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, Arrays.asList(2L, 3L), utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); CofactorRemover cofactorRemover = new CofactorRemover(mockNoSQLAPI); cofactorRemover.init(); cofactorRemover.run(); assertEquals("Similar pre-cofactor removal substrates should be written as one entry", 1, mockAPI.getWrittenReactions().size()); assertEquals("The first reaction had 1 coenzyme in the substrates, " + "but there should be no substrates after the cofactor is removed", 0, mockAPI.getWrittenReactions().get(0).getSubstrates().length); assertEquals("The first reaction had 1 coenzyme in the products, " + "but there should be no products after the cofactor is removed", 0, mockAPI.getWrittenReactions().get(0).getProducts().length); assertEquals("The old substrate/product should now exist as a coenzyme", testInchi1, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getCoenzymes()[0].longValue()).getInChI()); assertEquals("The original substrate cofactor should remain", 1, mockAPI.getWrittenReactions().get(0).getSubstrateCofactors().length); assertEquals("The substrate cofactor that was already in the reaction should persist", test2, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getSubstrateCofactors()[0].longValue()).getInChI()); assertEquals("The original product cofactor should remain", 1, mockAPI.getWrittenReactions().get(0).getSubstrateCofactors().length); assertEquals("The product cofactor should match the correct substrate id", test3, mockAPI.getWrittenChemicals().get(mockAPI.getWrittenReactions().get(0).getProductCofactors()[0].longValue()).getInChI()); }
UniprotSeqEntry extends SequenceEntry { public String getGeneName() { return this.geneName; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testGeneName() { assertEquals("tests whether gene name is extracted accurately", "ADH1", seqEntries.get(0).getGeneName()); }
BiointerpretationProcessor { public BiointerpretationProcessor(NoSQLAPI api) { this.api = api; } BiointerpretationProcessor(NoSQLAPI api); abstract String getName(); abstract void init(); void run(); }
@Test public void testBiointerpretationProcessor() throws Exception { BiointerpretationProcessor processor = new BiointerpretationProcessor(noSQLAPI.getMockNoSQLAPI()) { @Override public String getName() { return "testProcessor"; } @Override public void init() throws Exception { this.initCalled = true; } }; processor.init(); processor.run(); List<Reaction> reactions = noSQLAPI.getWrittenReactions(); Map<Long, Chemical> chemicals = noSQLAPI.getWrittenChemicals(); Map<Long, Seq> seqs = noSQLAPI.getWrittenSequences(); Map<Long, String> orgNames = noSQLAPI.getWrittenOrganismNames(); assertEquals("One reaction written to DB", 1, reactions.size()); Reaction r = reactions.get(0); assertTrue("Reaction is of type reaction", r instanceof Reaction); assertEquals("EC num matches expected", "1.1.1.1", r.getECNum()); Set<String> substrates = new HashSet<String>() {{ add("InChI=1S/12CN.2Fe.2H/c12*1-2;;;;/q12*-1;+2;+3;;"); add("InChI=1S/CH5O4P/c1-5-6(2,3)4/h1H3,(H2,2,3,4)"); }}; Set<String> products = new HashSet<String>() {{ add("InChI=1S/C7H5Cl3/c8-4-5-2-1-3-6(9)7(5)10/h1-3H,4H2"); add("InChI=1S/C8H9NO2/c1-6(10)9-7-2-4-8(11)5-3-7/h2-5,11H,1H3,(H,9,10)"); }}; for (Long id : r.getSubstrates()) { assertTrue("Substrate appears in expected set", substrates.contains(chemicals.get(id).getInChI())); } for (Long id : r.getProductCofactors()) { assertTrue("Product appears in expected set", products.contains(chemicals.get(id).getInChI())); } assertEquals("Reaction has one protein", 1, r.getProteinData().size()); JSONObject protein = r.getProteinData().iterator().next(); assertEquals("Protein organism maps to expected name", POTATO, orgNames.get(protein.getJSONArray("organisms").getLong(0))); assertEquals("One seq written to DB", 1, seqs.size()); Seq seq = seqs.values().iterator().next(); assertEquals("Protein links to single seq in DB", seq, seqs.get(protein.getJSONArray("sequences").getLong(0))); assertEquals("Sequence EC number is expected", "1.1.1.1", seq.getEc()); assertEquals("Sequence organisms is expected", POTATO, seq.getOrgName()); assertEquals("Sequence refers to one reaction", 1, seq.getReactionsCatalyzed().size()); assertEquals("Sequence refers to reaction correctly", Long.valueOf(r.getUUID()), seq.getReactionsCatalyzed().iterator().next()); }
GenbankInterpreter { public ArrayList<String> getSequenceStrings() { checkInit(); ArrayList<String> sequences = new ArrayList<>(); for (AbstractSequence sequence : this.sequences) { sequences.add(sequence.getSequenceAsString()); } return sequences; } GenbankInterpreter(File GenbankFile, String type); void init(); void printSequences(); ArrayList<String> getSequenceStrings(); void printFeaturesAndQualifiers(); ArrayList<ArrayList<String>> getFeatures(); Map<String, List<Qualifier>> getQualifiers(int sequence_index, String feature_type, String feature_source); void addQualifier(AbstractFeature<AbstractSequence<Compound>, Compound> feature, String qual_name, String qual_value); AbstractFeature<AbstractSequence<Compound>, Compound> constructFeature(String type, String source); void printDescription(); void printAccessionID(); void printHeader(); List<AbstractSequence> getSequences(); void addFeature(int bioStart, int bioEnd, AbstractFeature<AbstractSequence<Compound>, Compound> feature, int sequence_index); static void main(String[] args); static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }
@Test public void testReadSequence() { assertEquals("test whether parser extracts sequence accurately", protein_seq, giProtein.getSequenceStrings().get(0)); assertEquals("test whether parser extracts sequence accurately", dna_seq, giDna.getSequenceStrings().get(0)); }
GenbankInterpreter { public ArrayList<ArrayList<String>> getFeatures() { checkInit(); ArrayList<ArrayList<String>> all_feature_types = new ArrayList<>(); for (AbstractSequence sequence : sequences) { ArrayList<String> feature_types = new ArrayList<String>(); List<FeatureInterface<AbstractSequence<Compound>, Compound>> features = sequence.getFeatures(); for (FeatureInterface<AbstractSequence<Compound>, Compound> feature : features) { feature_types.add(feature.getType()); } all_feature_types.add(feature_types); } return all_feature_types; } GenbankInterpreter(File GenbankFile, String type); void init(); void printSequences(); ArrayList<String> getSequenceStrings(); void printFeaturesAndQualifiers(); ArrayList<ArrayList<String>> getFeatures(); Map<String, List<Qualifier>> getQualifiers(int sequence_index, String feature_type, String feature_source); void addQualifier(AbstractFeature<AbstractSequence<Compound>, Compound> feature, String qual_name, String qual_value); AbstractFeature<AbstractSequence<Compound>, Compound> constructFeature(String type, String source); void printDescription(); void printAccessionID(); void printHeader(); List<AbstractSequence> getSequences(); void addFeature(int bioStart, int bioEnd, AbstractFeature<AbstractSequence<Compound>, Compound> feature, int sequence_index); static void main(String[] args); static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }
@Test public void testReadFeatures() { List<String> protein_feature_types = new ArrayList<>(Arrays.asList("source", "Protein", "Region", "CDS", "restriction_site")); for (String feature_type : protein_feature_types) { assertTrue("test whether parser extracts feature types accurately", giProtein.getFeatures().get(0).contains(feature_type)); } List<String> dna_feature_types = new ArrayList<>(Arrays.asList("source", "5'UTR", "CDS", "sig_peptide", "mat_peptide", "regulatory")); for (String feature_type : dna_feature_types) { assertTrue("test whether parser extracts feature types accurately", giDna.getFeatures().get(0).contains(feature_type)); } }
MassCalculator2 { protected static Pair<Double, Integer> calculateMassAndCharge(String inchi) throws MolFormatException { Molecule mol = MolImporter.importMol(inchi); LOGGER.info("Exact mass vs. just mass for %s: %.6f %.6f", inchi, mol.getExactMass(), mol.getMass()); return Pair.of(mol.getExactMass(), mol.getTotalCharge()); } static void main(String[] args); static final List<Option.Builder> OPTION_BUILDERS; }
@Test public void testMC2MatchesMC1WithinMeaningfulTolerance() throws Exception { List<Map<String, String>> rows; try (InputStream is = MassCalculator2Test.class.getResourceAsStream(TEST_CASE_RESOURCE)) { TSVParser parser = new TSVParser(); parser.parse(is); rows = parser.getResults(); } int testCase = 1; for (Map<String, String> row : rows) { String inchi = row.get("InChI"); Double expectedMass = Double.valueOf(row.get("Mass")); Integer expectedCharge = Integer.valueOf(row.get("Charge")); Pair<Double, Integer> actualMassAndCharge = MassCalculator2.calculateMassAndCharge(inchi); Double threshold = ACCEPTABLE_MASS_DELTA_THRESHOLD; if (actualMassAndCharge.getRight() < 0) { threshold += ACCEPTABLE_MASS_DELTA_THRESHOLD * -1.0 * actualMassAndCharge.getRight().doubleValue(); } else if (actualMassAndCharge.getRight() > 0) { threshold += ACCEPTABLE_MASS_DELTA_THRESHOLD * actualMassAndCharge.getRight().doubleValue(); } assertEquals(String.format("Case %d: mass for %s is within delta threshold: %.6f vs. %.6f", testCase, inchi, expectedMass, actualMassAndCharge.getLeft()), expectedMass, actualMassAndCharge.getLeft(), threshold); assertEquals(String.format("Case %d: charge %s matches expected", testCase, inchi), expectedCharge, actualMassAndCharge.getRight()); testCase++; } }
MassToRawMetaboliteMapParser { void validateHeaders(List<String> headers) { if (headers.contains(DEFAULT_STRUCTURE_HEADER)) { this.metaboliteHeader = DEFAULT_STRUCTURE_HEADER; this.massToMetaboliteMap = new MassToRawMetaboliteMap(MassToRawMetaboliteMap.RawMetaboliteKind.INCHI); } else if (headers.contains(DEFAULT_FORMULA_HEADER)) { this.metaboliteHeader = DEFAULT_FORMULA_HEADER; this.massToMetaboliteMap = new MassToRawMetaboliteMap(MassToRawMetaboliteMap.RawMetaboliteKind.FORMULA); } else { String msg = String.format("Input file did not contain expected metabolite headers: %s or %s", DEFAULT_FORMULA_HEADER, DEFAULT_STRUCTURE_HEADER); LOGGER.error(msg); throw new RuntimeException(msg); } LOGGER.info("The parser will use the following metabolite header: %s", this.metaboliteHeader); this.metaboliteIndex = headers.indexOf(this.metaboliteHeader); if (headers.contains(DEFAULT_MASS_HEADER)) { String massHeader = DEFAULT_MASS_HEADER; this.massIndex = headers.indexOf(massHeader); LOGGER.info("The parser detected the following mass header: %s", massHeader); } else { if (this.metaboliteHeader.equals(DEFAULT_FORMULA_HEADER)) { throw new RuntimeException("Masses should be provided if parsing metabolites from formulae."); } this.massIndex = -1; LOGGER.warn("The parser did not detect any mass header. Masses will be computed."); } if (headers.contains(DEFAULT_NAME_HEADER)) { String namesHeader = DEFAULT_NAME_HEADER; this.nameIndex = headers.indexOf(namesHeader); LOGGER.info("The parser detected the following name header: %s", namesHeader); } else { this.nameIndex = -1; LOGGER.info("The parser did not detect any name header"); } } MassToRawMetaboliteMapParser(); MassToRawMetaboliteMapParser(File inputFile); Integer getMetaboliteIndex(); Integer getMassIndex(); Integer getNameIndex(); MassToRawMetaboliteMap getMassToMoleculeMap(); void parse(); }
@Test(expected=RuntimeException.class) public void testEmptyHeaders() { List<String> headers = new ArrayList<>(); parser = new MassToRawMetaboliteMapParser(); parser.validateHeaders(headers); }
Builder { protected void extractTriples( Iterator<LCMSSpectrum> iter, List<MZWindow> windows) throws RocksDBException, IOException { ensureUniqueMZWindowIndices(windows); ByteBuffer[] mzWindowTripleBuffers = new ByteBuffer[windows.size()]; for (int i = 0; i < mzWindowTripleBuffers.length; i++) { mzWindowTripleBuffers[i] = ByteBuffer.allocate(Long.BYTES * 4096); } long counter = -1; ByteBuffer counterBuffer = ByteBuffer.allocate(Long.BYTES); ByteBuffer valBuffer = ByteBuffer.allocate(TMzI.BYTES); List<Float> timepoints = new ArrayList<>(2000); LinkedList<MZWindow> tbdQueueTemplate = new LinkedList<>(windows); int spectrumCounter = 0; while (iter.hasNext()) { LCMSSpectrum spectrum = iter.next(); float time = spectrum.getTimeVal().floatValue(); ByteBuffer triplesForThisTime = ByteBuffer.allocate(Long.BYTES * spectrum.getIntensities().size()); RocksDBAndHandles.RocksDBWriteBatch<ColumnFamilies> writeBatch = dbAndHandles.makeWriteBatch(); LinkedList<MZWindow> workingQueue = new LinkedList<>(); LinkedList<MZWindow> tbdQueue = (LinkedList<MZWindow>) tbdQueueTemplate.clone(); for (Pair<Double, Double> mzIntensity : spectrum.getIntensities()) { counter++; Double mz = mzIntensity.getLeft(); Double intensity = mzIntensity.getRight(); counterBuffer.clear(); counterBuffer.putLong(counter); counterBuffer.flip(); valBuffer.clear(); TMzI.writeToByteBuffer(valBuffer, time, mz, intensity.floatValue()); valBuffer.flip(); while (!tbdQueue.isEmpty() && tbdQueue.peekFirst().getMin() <= mz) { workingQueue.add(tbdQueue.pop()); } while (!workingQueue.isEmpty() && workingQueue.peekFirst().getMax() < mz) { workingQueue.pop(); } for (MZWindow window : workingQueue) { counterBuffer.rewind(); mzWindowTripleBuffers[window.getIndex()] = Utils.appendOrRealloc(mzWindowTripleBuffers[window.getIndex()], counterBuffer); } counterBuffer.rewind(); valBuffer.rewind(); writeBatch.put(ColumnFamilies.ID_TO_TRIPLE, Utils.toCompactArray(counterBuffer), Utils.toCompactArray(valBuffer)); counterBuffer.rewind(); triplesForThisTime.put(counterBuffer); } writeBatch.write(); assert(triplesForThisTime.position() == triplesForThisTime.capacity()); ByteBuffer timeBuffer = ByteBuffer.allocate(Float.BYTES).putFloat(time); timeBuffer.flip(); triplesForThisTime.flip(); dbAndHandles.put(ColumnFamilies.TIMEPOINT_TO_TRIPLES, Utils.toCompactArray(timeBuffer), Utils.toCompactArray(triplesForThisTime)); timepoints.add(time); spectrumCounter++; if (spectrumCounter % 1000 == 0) { LOGGER.info("Extracted %d time spectra", spectrumCounter); } } LOGGER.info("Extracted %d total time spectra", spectrumCounter); RocksDBAndHandles.RocksDBWriteBatch<ColumnFamilies> writeBatch = dbAndHandles.makeWriteBatch(); ByteBuffer idBuffer = ByteBuffer.allocate(Integer.BYTES); for (int i = 0; i < mzWindowTripleBuffers.length; i++) { idBuffer.clear(); idBuffer.putInt(windows.get(i).getIndex()); idBuffer.flip(); ByteBuffer triplesBuffer = mzWindowTripleBuffers[i]; triplesBuffer.flip(); writeBatch.put(ColumnFamilies.WINDOW_ID_TO_TRIPLES, Utils.toCompactArray(idBuffer), Utils.toCompactArray(triplesBuffer)); } writeBatch.write(); dbAndHandles.put(ColumnFamilies.TIMEPOINTS, TIMEPOINTS_KEY, Utils.floatListToByteArray(timepoints)); dbAndHandles.flush(true); } Builder(RocksDBAndHandles<ColumnFamilies> dbAndHandles); static void main(String[] args); void close(); void processScan(List<Double> targetMZs, File scanFile); static final String OPTION_INDEX_PATH; static final String OPTION_SCAN_FILE; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; }
@Test public void testExtractTriples() throws Exception { Map<Long, TMzI> deserializedTriples = new HashMap<>(); assertEquals("All triples should have entries in the DB", 9, fakeDB.getFakeDB().get(ColumnFamilies.ID_TO_TRIPLE).size()); for (Map.Entry<List<Byte>, byte[]> entry : fakeDB.getFakeDB().get(ColumnFamilies.ID_TO_TRIPLE).entrySet()) { Long id = ByteBuffer.wrap(fakeDB.byteListToArray(entry.getKey())).getLong(); TMzI triple = TMzI.readNextFromByteBuffer(ByteBuffer.wrap(entry.getValue())); Float expectedTime = Double.valueOf(TIMES[id.intValue() / 3]).floatValue(); Double expectedMZ = MZS[id.intValue() / 3][id.intValue() % 3]; Float expectedIntensity = Double.valueOf(INTENSITIES[id.intValue() / 3][id.intValue() % 3]).floatValue(); assertEquals("Time matches expected", expectedTime, triple.getTime(), FP_TOLERANCE); assertEquals("M/z matches expected", expectedMZ, triple.getMz(), FP_TOLERANCE); assertEquals("Intensity matches expected", expectedIntensity, triple.getIntensity(), FP_TOLERANCE); deserializedTriples.put(id, triple); } for (Map.Entry<List<Byte>, byte[]> entry : fakeDB.getFakeDB().get(ColumnFamilies.WINDOW_ID_TO_TRIPLES).entrySet()) { int windowId = ByteBuffer.wrap(fakeDB.byteListToArray(entry.getKey())).getInt(); MZWindow window = windowIdsToWindows.get(windowId); List<Long> tmziIds = new ArrayList<>(entry.getValue().length / Long.BYTES); ByteBuffer valBuffer = ByteBuffer.wrap(entry.getValue()); while (valBuffer.hasRemaining()) { tmziIds.add(valBuffer.getLong()); } for (Long tripleId : tmziIds) { TMzI triple = deserializedTriples.get(tripleId); assertTrue("Triple m/z falls within range of containing window", triple.getMz() >= window.getMin() && triple.getMz() <= window.getMax() ); } } for (Map.Entry<List<Byte>, byte[]> entry : fakeDB.getFakeDB().get(ColumnFamilies.TIMEPOINT_TO_TRIPLES).entrySet()) { float time = ByteBuffer.wrap(fakeDB.byteListToArray(entry.getKey())).getFloat(); List<Long> tmziIds = new ArrayList<>(entry.getValue().length / Long.BYTES); ByteBuffer valBuffer = ByteBuffer.wrap(entry.getValue()); while (valBuffer.hasRemaining()) { tmziIds.add(valBuffer.getLong()); } for (Long tripleId : tmziIds) { TMzI triple = deserializedTriples.get(tripleId); assertEquals("Triple time matches key time", time, triple.getTime(), FP_TOLERANCE); } } }
Searcher { public List<TMzI> searchIndexInRange( Pair<Double, Double> mzRange, Pair<Double, Double> timeRange) throws RocksDBException, ClassNotFoundException, IOException { DateTime start = DateTime.now(); Pair<Float, Float> tRangeF = Pair.of(timeRange.getLeft().floatValue(), timeRange.getRight().floatValue()); LOGGER.info("Running search for %.6f <= t <= %.6f, %.6f <= m/z <= %.6f", tRangeF.getLeft(), tRangeF.getRight(), mzRange.getLeft(), mzRange.getRight() ); List<Float> timesInRange = timepointsInRange(tRangeF); byte[][] timeIndexBytes = extractValueBytes( ColumnFamilies.TIMEPOINT_TO_TRIPLES, timesInRange, Float.BYTES, ByteBuffer::putFloat ); List<MZWindow> mzWindowsInRange = mzWindowsInRange(mzRange); byte[][] mzIndexBytes = extractValueBytes( ColumnFamilies.WINDOW_ID_TO_TRIPLES, mzWindowsInRange, Integer.BYTES, (buff, mz) -> buff.putInt(mz.getIndex()) ); LOGGER.info("Found/loaded %d matching time ranges, %d matching m/z ranges", timesInRange.size(), mzWindowsInRange.size()); Set<Long> unionTimeIds = unionIdBuffers(timeIndexBytes); Set<Long> unionMzIds = unionIdBuffers(mzIndexBytes); Set<Long> intersectionIds = new HashSet<>(unionTimeIds); intersectionIds.retainAll(unionMzIds); LOGGER.info("Id intersection results: t = %d, mz = %d, t ^ mz = %d", unionTimeIds.size(), unionMzIds.size(), intersectionIds.size()); List<Long> idsToFetch = new ArrayList<>(intersectionIds); Collections.sort(idsToFetch); LOGGER.info("Collecting TMzI triples"); List<TMzI> results = new ArrayList<>(idsToFetch.size()); byte[][] resultBytes = extractValueBytes( ColumnFamilies.ID_TO_TRIPLE, idsToFetch, Long.BYTES, ByteBuffer::putLong ); for (byte[] tmziBytes : resultBytes) { results.add(TMzI.readNextFromByteBuffer(ByteBuffer.wrap(tmziBytes))); } LOGGER.info("Performing final filtering"); int preFilterTMzICount = results.size(); results = results.stream().filter(tmzi -> tmzi.getTime() >= tRangeF.getLeft() && tmzi.getTime() <= tRangeF.getRight() && tmzi.getMz() >= mzRange.getLeft() && tmzi.getMz() <= mzRange.getRight() ).collect(Collectors.toList()); LOGGER.info("Precise filtering results: %d -> %d", preFilterTMzICount, results.size()); DateTime end = DateTime.now(); LOGGER.info("Search completed in %dms", end.getMillis() - start.getMillis()); return results; } Searcher(RocksDBAndHandles<ColumnFamilies> dbAndHandles); static void main(String args[]); List<TMzI> searchIndexInRange( Pair<Double, Double> mzRange, Pair<Double, Double> timeRange); static final String OPTION_INDEX_PATH; static final String OPTION_MZ_RANGE; static final String OPTION_TIME_RANGE; static final String OPTION_OUTPUT_FILE; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; }
@Test public void searchIndexInRange() throws Exception { List<TMzI> actual = searcher.searchIndexInRange(Pair.of(100.004, 100.016), Pair.of(1.5, 3.5)); List<Triple<Float, Double, Float>> expected = Arrays.asList( Triple.of(2.0F, 100.005, 10.0F), Triple.of(2.0F, 100.010, 20.0F), Triple.of(2.0F, 100.015, 30.0F), Triple.of(3.0F, 100.010, 100.0F), Triple.of(3.0F, 100.015, 200.0F) ); assertEquals("Searcher returned expected number of TMzI tuples", expected.size(), actual.size()); for (int i = 0; i < expected.size(); i++) { Triple<Float, Double, Float> e = expected.get(i); TMzI a = actual.get(i); assertEquals("Time matches expected", e.getLeft(), a.getTime(), FP_TOLERANCE); assertEquals("M/z matches expected", e.getMiddle(), a.getMz(), FP_TOLERANCE); assertEquals("Intensity matches expected", e.getRight(), a.getIntensity(), FP_TOLERANCE); } }
LcmsChemicalFormula implements ChemicalFormula { @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Map.Entry<Element, Integer> entry : getSortedElementCounts().entrySet()) { builder.append(entry.getKey().getSymbol()); Integer count = entry.getValue(); if (count > 1) { builder.append(count.toString()); } } return builder.toString(); } LcmsChemicalFormula(String chemicalFormula); LcmsChemicalFormula(Map<Element, Integer> elementCounts); LcmsChemicalFormula(Map<Element, Integer> elementCounts, String name); Map<Element, Integer> getElementCounts(); Integer getElementCount(Element element); Double getMonoIsotopicMass(); Optional<String> getName(); @Override boolean equals(Object chemicalFormula); @Override String toString(); void fromString(String formulaString); }
@Test public void testChemicalFormulaToString() { assertEquals(acetaminophenFormulaString, acetaminophenFormula.toString()); assertEquals(sulfuricAcidFormulaString, sulfuricAcidFormula.toString()); }
LcmsChemicalFormula implements ChemicalFormula { public Double getMonoIsotopicMass() { return elementCounts .entrySet() .stream() .mapToDouble(entry -> entry.getKey().getMass() * entry.getValue()) .sum(); } LcmsChemicalFormula(String chemicalFormula); LcmsChemicalFormula(Map<Element, Integer> elementCounts); LcmsChemicalFormula(Map<Element, Integer> elementCounts, String name); Map<Element, Integer> getElementCounts(); Integer getElementCount(Element element); Double getMonoIsotopicMass(); Optional<String> getName(); @Override boolean equals(Object chemicalFormula); @Override String toString(); void fromString(String formulaString); }
@Test public void testChemicalFormulaMonoIsotopicMass() { assertEquals(151.063, acetaminophenFormula.getMonoIsotopicMass(), MASS_TOLERANCE); assertEquals(97.967, sulfuricAcidFormula.getMonoIsotopicMass(), MASS_TOLERANCE); }
LcmsChemicalFormula implements ChemicalFormula { public Integer getElementCount(Element element) { return elementCounts.getOrDefault(element, 0); } LcmsChemicalFormula(String chemicalFormula); LcmsChemicalFormula(Map<Element, Integer> elementCounts); LcmsChemicalFormula(Map<Element, Integer> elementCounts, String name); Map<Element, Integer> getElementCounts(); Integer getElementCount(Element element); Double getMonoIsotopicMass(); Optional<String> getName(); @Override boolean equals(Object chemicalFormula); @Override String toString(); void fromString(String formulaString); }
@Test public void testFormulaStringConversions() { List<String> testCases = Arrays.asList( "C20BrCl2", "BrCl2", "BrC2", "CCl", "ClC", "IFClH20CBrN10P2", "H10ClBrN4O2", "IFClH20BrN10P2" ); List<ChemicalFormula> testCasesFormulae = testCases.stream().map(LcmsChemicalFormula::new).collect(Collectors.toList()); Iterator<Integer> testCasesExpectedC = Arrays.asList(20, 0, 2, 1, 1, 1, 0, 0).iterator(); Iterator<Integer> testCasesExpectedBr = Arrays.asList(1, 1, 1, 0, 0, 1, 1, 1).iterator(); Iterator<Integer> testCasesExpectedCl = Arrays.asList(2, 2, 0, 1, 1, 1, 1, 1).iterator(); Iterator<ChemicalFormula> testCasesFormulaeIterator = testCasesFormulae.iterator(); while (testCasesFormulaeIterator.hasNext()) { ChemicalFormula formula = testCasesFormulaeIterator.next(); assertEquals(testCasesExpectedC.next(), formula.getElementCount(C)); assertEquals(testCasesExpectedBr.next(), formula.getElementCount(Br)); assertEquals(testCasesExpectedCl.next(), formula.getElementCount(Cl)); } List<String> testCasesHillOrdered = testCasesFormulae.stream().map(ChemicalFormula::toString).collect(Collectors.toList()); List<String> testCasesHillOrderedExpected = Arrays.asList( "C20BrCl2", "BrCl2", "C2Br", "CCl", "CCl", "CH20BrClFIN10P2", "BrClH10N4O2", "BrClFH20IN10P2" ); assertEquals(testCasesHillOrderedExpected, testCasesHillOrdered); }
UniprotSeqEntry extends SequenceEntry { public List<String> getGeneSynonyms() { return this.geneSynonyms; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testGeneSynonyms() { assertEquals("tests whether gene synonyms are extracted accurately", Collections.singletonList("ADH"), seqEntries.get(0).getGeneSynonyms()); }
MassChargeCalculator { public static MassChargeMap makeMassChargeMap(List<MZSource> mzSources) throws IOException { return makeMassChargeMap(mzSources, Collections.emptySet()); } static MassChargeMap makeMassChargeMap(List<MZSource> mzSources); static MassChargeMap makeMassChargeMap(List<MZSource> mzSources, Set<String> onlyConsiderIons); }
@Test public void testMakeMassChargeMap() throws Exception { List<MassChargeCalculator.MZSource> sources = Arrays.asList( new MassChargeCalculator.MZSource("InChI=1S/C7H7NO2/c8-6-3-1-5(2-4-6)7(9)10/h1-4H,8H2,(H,9,10)"), new MassChargeCalculator.MZSource("InChI=1S/C7H7NO2/c1-10-7(9)6-3-2-4-8-5-6/h2-5H,1H3")); MassChargeCalculator.MassChargeMap massChargeMap = MassChargeCalculator.makeMassChargeMap( sources, new HashSet<>(Arrays.asList("M+H", "M+Na")) ); Double expectedMonoMass = 137.047679; List<Double> expectedIonMZs = Arrays.asList(138.054979, 160.036879); List<Double> actualIonMasses = massChargeMap.ionMZsSorted(); assertEqualsWithFPErr("Unique ionic masses match expected list", expectedIonMZs, actualIonMasses ); assertEqualsPairWithFPErr("M+H ion mz maps to source mass and ion name", Arrays.asList(Pair.of("M+H", expectedMonoMass)), massChargeMap.ionMZtoMonoMassAndIonName(actualIonMasses.get(0)) ); assertEqualsPairWithFPErr("M+Na ion mz maps to source mass and ion name", Arrays.asList(Pair.of("M+Na", expectedMonoMass)), massChargeMap.ionMZtoMonoMassAndIonName(actualIonMasses.get(1)) ); for (Double ionMZ : actualIonMasses) { assertEquals(String.format("Ionic masses for %f map to two MZSources", ionMZ), new HashSet<>(sources), massChargeMap.ionMZToMZSources(ionMZ) ); } assertEqualsWithFPErr("Iterable ionMZs match expected", new HashSet<>(expectedIonMZs), StreamSupport.stream(massChargeMap.ionMZIter().spliterator(), false).collect(Collectors.toSet()) ); assertEqualsWithFPErr("Iterable monoisotopic masses match expected", Collections.singleton(expectedMonoMass), StreamSupport.stream(massChargeMap.monoisotopicMassIter().spliterator(), false).collect(Collectors.toSet()) ); assertEquals("Iterable mzSources match expected", new HashSet<>(sources), StreamSupport.stream(massChargeMap.mzSourceIter().spliterator(), false).collect(Collectors.toSet()) ); }
MassChargeCalculator { protected static Double computeMass(MZSource mzSource) { Double mass; String msg; switch (mzSource.getKind()) { case INCHI: Pair<Double, Integer> massAndCharge; try { massAndCharge = MassCalculator.calculateMassAndCharge(mzSource.getInchi()); } catch (Exception e) { LOGGER.error("Calculating mass for molecule %s failed: %s", mzSource.getInchi(), e.getMessage()); throw e; } if (massAndCharge.getRight() > 0) { LOGGER.warn("(MZSrc %d) Molecule %s has a positive charge %d; ionization may not have the expected effect", mzSource.getId(), mzSource.getInchi(), massAndCharge.getRight()); } else if (massAndCharge.getRight() < 0) { LOGGER.warn("(MZSrc %d) Molecule %s has a negative charge %d; it may not fly in positive ion mode", mzSource.getId(), mzSource.getInchi(), massAndCharge.getRight()); } mass = massAndCharge.getLeft(); break; case ARBITRARY_MASS: mass = mzSource.getArbitraryMass(); break; case PRE_EXTRACTED_MASS: mass = mzSource.getPreExtractedMass().getRight(); break; case UNKNOWN: msg = String.format("mzSource with id %d has UNKNOWN kind, which is invalid", mzSource.getId()); LOGGER.error(msg); throw new RuntimeException(msg); default: msg = String.format("mzSource with id %d has unknown kind (should be impossible): %s", mzSource.getId(), mzSource.getKind()); LOGGER.error(msg); throw new RuntimeException(msg); } return mass; } static MassChargeMap makeMassChargeMap(List<MZSource> mzSources); static MassChargeMap makeMassChargeMap(List<MZSource> mzSources, Set<String> onlyConsiderIons); }
@Test public void testComputeMass() throws Exception { List<Pair<MassChargeCalculator.MZSource, Double>> testCases = Arrays.asList( Pair.of(new MassChargeCalculator.MZSource("InChI=1S/C8H9NO2/c1-6(10)9-7-2-4-8(11)5-3-7/h2-5,11H,1H3,(H,9,10)"), 151.063329), Pair.of(new MassChargeCalculator.MZSource(151.063329), 151.063329), Pair.of(new MassChargeCalculator.MZSource(Pair.of("APAP", 151.063329)), 151.063329) ); for (Pair<MassChargeCalculator.MZSource, Double> testCase : testCases) { Double actualMass = MassChargeCalculator.computeMass(testCase.getLeft()); assertEquals( String.format("(Case %d) Actual mass is within bounds: %.6f ~ %.6f", testCase.getLeft().getId(), testCase.getRight(), actualMass), testCase.getRight(), actualMass, MASS_ERROR_TOLERANCE ); } }
UniprotSeqEntry extends SequenceEntry { public List<String> getProductName() { return this.productNames; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testProductName() { assertEquals("tests whether product names are extracted accurately", Arrays.asList("Alcohol dehydrogenase class-P", "Alc Dehyd"), seqEntries.get(0).getProductName()); }
UniprotSeqEntry extends SequenceEntry { public String getCatalyticActivity() {return this.catalyticActivity; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testCatalyticActivity() { assertEquals("tests whether catalytic activity is extracted accurately", "An alcohol + NAD(+) = an aldehyde or ketone + NADH.", seqEntries.get(0).getCatalyticActivity()); }
ZipUtils { public static void zipDir(final File zipFile, final File srcDir, final String prefix) throws IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); try { addZipPrefixes(srcDir, out, prefix); addZipDir(srcDir, out, prefix); } finally { IOUtils.closeQuietly(out); } } static void unzip(final File zipFile, final String destDir); static void unzip(final File zipFile, final String destDir, int leadingPathSegmentsToTrim); static int countNestingLevel(File zip); static void zipDir(final File zipFile, final File srcDir, final String prefix); }
@Test public void zipContainsSinglePrefix() throws IOException { File zipFile = new File(tempDir, "zip-with-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, FIRST_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String testPrefix = zipPath.substring(0, zipPath.indexOf("/")); assertEquals(FIRST_PREFIX, testPrefix); } } @Test public void zipContainsNestedPrefix() throws IOException { File zipFile = new File(tempDir, "zip-nested-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, NESTED_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String[] segments = zipPath.split("/"); if (segments.length > 1) { String testPrefix = segments[0] + "/" + segments[1]; assertEquals(NESTED_PREFIX, testPrefix); } } } @Test public void prefixedZipDoesNotContainRootDir() throws IOException { File zipFile = new File(tempDir, "zip-with-prefix-no-root.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, FIRST_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String[] segments = zipPath.split("/"); if (segments.length > 1) { String rootPath = segments[1]; assertThat(rootPath, not(equalTo(ROOT_DIR))); } } } @Test public void nestedPrefixedZipDoesNotContainRootDir() throws IOException { File zipFile = new File(tempDir, "zip-nested-prefix-no-root.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, NESTED_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String[] segments = zipPath.split("/"); if (segments.length > 2) { String rootPath = segments[2]; assertThat(rootPath, not(equalTo(ROOT_DIR))); } } } @Test public void emptyPrefixedZipContainsRootDir() throws IOException { File zipFile = new File(tempDir, "zip-empty-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, ""); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String rootPath = zipPath.substring(0, zipPath.indexOf("/")); assertEquals(ROOT_DIR, rootPath); } } @Test public void nullPrefixedZipContainsRootDir() throws IOException { File zipFile = new File(tempDir, "zip-null-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, null); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); String zipPath = zipEntry.getName(); String rootPath = zipPath.substring(0, zipPath.indexOf("/")); assertEquals(ROOT_DIR, rootPath); } } @Test public void emptyPrefixedZipFolderCountMatches() throws IOException { File zipFile = new File(tempDir, "zip-empty-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, ""); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); int numFolders = 0; while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); if (zipEntry.isDirectory()) { numFolders++; } } assertEquals(NUM_FOLDERS, numFolders); } @Test public void singlePrefixedZipFolderCountMatches() throws IOException { File zipFile = new File(tempDir, "zip-single-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, FIRST_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); int numFolders = 0; while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); if (zipEntry.isDirectory()) { numFolders++; } } assertEquals(NUM_FOLDERS, numFolders); } @Test public void nestedPrefixedZipFolderCountMatches() throws IOException { File zipFile = new File(tempDir, "zip-nested-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, NESTED_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); int numFolders = 0; while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); if (zipEntry.isDirectory()) { numFolders++; } } assertEquals(NUM_FOLDERS_NESTED_PREFIX, numFolders); } @Test public void zipFileCountMatches() throws IOException { File zipFile = new File(tempDir, "zip-single-prefix.zip"); ZipUtils.zipDir(zipFile, sourceZipDir, FIRST_PREFIX); zip = new ZipFile(zipFile); final Enumeration<? extends ZipEntry> entries = zip.entries(); int numFiles = 0; while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); if (!zipEntry.isDirectory()) { numFiles++; } } assertEquals(NUM_FILES, numFiles); }
ZipUtils { public static int countNestingLevel(File zip) throws ZipException, IOException { List<String> filenames = toList(new ZipFile(zip).entries()); return countNestingLevel(filenames); } static void unzip(final File zipFile, final String destDir); static void unzip(final File zipFile, final String destDir, int leadingPathSegmentsToTrim); static int countNestingLevel(File zip); static void zipDir(final File zipFile, final File srcDir, final String prefix); }
@Test public void detectNoPrefix() throws IOException, URISyntaxException { URL zipPath = TestZipUtils.class.getResource("zip-no-root.zip"); File zipFile = new File(zipPath.toURI()); int nestedRoots = ZipUtils.countNestingLevel(zipFile); assertEquals("No nesting should be detected", 0, nestedRoots); } @Test public void countNoNestingLevel() { List<String> filenames = Lists.newArrayList( "file1.txt", "file2.txt"); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("The number of nested roots should be detected", 0, nestedRoots); } @Test public void countOneNestingLevel() { List<String> filenames = Lists.newArrayList( "root/folder1/file.txt", "root/folder2/file.txt"); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("The number of nested roots should be detected", 1, nestedRoots); } @Test public void countNestingLevelWithEmptyList() { List<String> filenames = Lists.newArrayList(); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("Should work with an empty list", 0, nestedRoots); } @Test public void countTwoNestingLevel() { List<String> filenames = Lists.newArrayList( "root/otherRoot/file1.txt", "root/otherRoot/file2.txt"); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("The number of nested roots should be detected", 2, nestedRoots); } @Test public void countTwoNestingLevelWithEmptyDirs() { List<String> filenames = Lists.newArrayList( "root/", "root/otherRoot/", "root/otherRoot/file1.txt", "root/otherRoot/file2.txt"); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("The number of nested roots should be detected", 2, nestedRoots); } @Test public void countTwoNestingLevelWithEmptyDirsInReversedOrder() { List<String> filenames = Lists.newArrayList( "root/otherRoot/file1.txt", "root/otherRoot/file2.txt", "root/otherRoot/", "root/"); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("The number of nested roots should be detected", 2, nestedRoots); } @Test public void countOneNestingLevelWithEmptyDirs() { List<String> filenames = Lists.newArrayList( "root/folder1/file1.txt", "root/folder1/file2.txt", "root/folder1/", "root/folder2/", "root/"); int nestedRoots = ZipUtils.countNestingLevel(filenames); assertEquals("The number of nested roots should be detected", 1, nestedRoots); }
JiraProductHandler extends AbstractWebappProductHandler { static void createDbConfigXmlIfNecessary(File homeDir) throws MojoExecutionException { File dbConfigXml = new File(homeDir, "dbconfig.xml"); if (dbConfigXml.exists()) { return; } InputStream templateIn = JiraProductHandler.class.getResourceAsStream("jira-dbconfig-template.xml"); if (templateIn == null) { throw new MojoExecutionException("Missing internal resource: jira-dbconfig-template.xml"); } try { String template = IOUtils.toString(templateIn, "utf-8"); File dbFile = getHsqlDatabaseFile(homeDir); String jdbcUrl = "jdbc:hsqldb:file:" + dbFile.toURI().getPath(); String result = template.replace("@jdbc-url@", jdbcUrl); FileUtils.writeStringToFile(dbConfigXml, result, "utf-8"); } catch (IOException ioe) { throw new MojoExecutionException("Unable to create dbconfig.xml", ioe); } } JiraProductHandler(final MavenContext context, final MavenGoals goals); String getId(); @Override ProductArtifact getArtifact(); @Override ProductArtifact getTestResourcesArtifact(); int getDefaultHttpPort(); @Override Map<String, String> getSystemProperties(final Product ctx); @Override File getUserInstalledPluginsDirectory(final File webappDir, final File homeDir); @Override List<ProductArtifact> getExtraContainerDependencies(); @Override String getBundledPluginPath(Product ctx); @Override void processHomeDirectory(final Product ctx, final File homeDir); @Override List<Replacement> getReplacements(Product ctx); @Override List<File> getConfigFiles(Product product, File homeDir); @Override List<ProductArtifact> getDefaultLibPlugins(); @Override List<ProductArtifact> getDefaultBundledPlugins(); @Override void cleanupProductHomeForZip(Product product, File snapshotDir); }
@Test public void dbconfigXmlCreatedWithCorrectPath() throws Exception { JiraProductHandler.createDbConfigXmlIfNecessary(tempHome); File f = new File(tempHome, "dbconfig.xml"); assertTrue("The dbconfig.xml is created", f.exists()); assertTrue("And it's a regular file", f.isFile()); File dbFile = new File(tempHome, "database"); Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f); XPathExpression xpe = XPathFactory.newInstance().newXPath().compile("/jira-database-config/jdbc-datasource/url"); String x = xpe.evaluate(d); assertEquals("The JDBC URI for the embedded database is as expected", "jdbc:hsqldb:file:" + dbFile.toURI().getPath(), x); } @Test public void dbconfigXmlNotCreatedWhenAlreadyExists() throws MojoExecutionException, IOException { File f = new File(tempHome, "dbconfig.xml"); FileUtils.writeStringToFile(f, "Original contents"); JiraProductHandler.createDbConfigXmlIfNecessary(tempHome); String after = FileUtils.readFileToString(f); assertEquals("Original contents", after); }
MavenGoals { int pickFreePort(final int requestedPort) { ServerSocket socket = null; try { socket = new ServerSocket(requestedPort); return requestedPort > 0 ? requestedPort : socket.getLocalPort(); } catch (final IOException e) { ServerSocket zeroSocket = null; try { zeroSocket = new ServerSocket(0); return zeroSocket.getLocalPort(); } catch (final IOException ex) { throw new RuntimeException("Error opening socket", ex); } finally { closeSocket(zeroSocket); } } finally { closeSocket(socket); } } MavenGoals(final MavenContext ctx); MavenProject getContextProject(); void executeAmpsRecursively(final String ampsVersion, final String ampsGoal, Xpp3Dom cfg); void startCli(final PluginInformation pluginInformation, final int port); void createPlugin(final String productId); void copyBundledDependencies(); void extractBundledDependencies(); void compressResources(); void filterPluginDescriptor(); void runUnitTests(Map<String, Object> systemProperties); File copyWebappWar(final String productId, final File targetDirectory, final ProductArtifact artifact); void copyPlugins(final File outputDirectory, final List<ProductArtifact> artifacts); int startWebapp(final String productInstanceId, final File war, final Map<String, String> systemProperties, final List<ProductArtifact> extraContainerDependencies, final Product webappContext); void stopWebapp(final String productId, final String containerId, final Product webappContext); static String getBaseUrl(final String server, final int actualHttpPort, final String contextPath); void runTests(String testGroupId, String containerId, List<String> includes, List<String> excludes, Map<String, Object> systemProperties, final File targetDirectory); void installPlugin(PdkParams pdkParams); void uninstallPlugin(final String pluginKey, final String server, final int port, final String contextPath); void installIdeaPlugin(); File copyDist(final File targetDirectory, final ProductArtifact artifact); File copyHome(final File targetDirectory, final ProductArtifact artifact); File copyZip(final File targetDirectory, final ProductArtifact artifact, final String localName); void generateBundleManifest(final Map<String, String> instructions, final Map<String, String> basicAttributes); void generateMinimalManifest(final Map<String, String> basicAttributes); void jarWithOptionalManifest(final boolean manifestExists); void jarTests(String finalName); void generateObrXml(File dep, File obrXml); void attachArtifact(File file, String type); void release(String mavenArgs); void generateRestDocs(); }
@Test public void testPickFreePort() throws IOException { ServerSocket socket = null; try { socket = new ServerSocket(16829); int port = goals.pickFreePort(0); assertTrue(16829 != port); assertTrue(port > 0); port = goals.pickFreePort(16829); assertTrue(16829 != port); assertTrue(port > 0); assertEquals(16828, goals.pickFreePort(16828)); } finally { socket.close(); } }
MavenGoals { public void generateMinimalManifest(final Map<String, String> basicAttributes) throws MojoExecutionException { File metaInf = file(ctx.getProject().getBuild().getOutputDirectory(), "META-INF"); if (!metaInf.exists()) { metaInf.mkdirs(); } File mf = file(ctx.getProject().getBuild().getOutputDirectory(), "META-INF", "MANIFEST.MF"); Manifest m = new Manifest(); m.getMainAttributes().putValue("Manifest-Version", "1.0"); for (Map.Entry<String, String> entry : basicAttributes.entrySet()) { m.getMainAttributes().putValue(entry.getKey(), entry.getValue()); } FileOutputStream fos = null; try { fos = new FileOutputStream(mf); m.write(fos); } catch (IOException e) { throw new MojoExecutionException("Unable to create manifest", e); } finally { IOUtils.closeQuietly(fos); } } MavenGoals(final MavenContext ctx); MavenProject getContextProject(); void executeAmpsRecursively(final String ampsVersion, final String ampsGoal, Xpp3Dom cfg); void startCli(final PluginInformation pluginInformation, final int port); void createPlugin(final String productId); void copyBundledDependencies(); void extractBundledDependencies(); void compressResources(); void filterPluginDescriptor(); void runUnitTests(Map<String, Object> systemProperties); File copyWebappWar(final String productId, final File targetDirectory, final ProductArtifact artifact); void copyPlugins(final File outputDirectory, final List<ProductArtifact> artifacts); int startWebapp(final String productInstanceId, final File war, final Map<String, String> systemProperties, final List<ProductArtifact> extraContainerDependencies, final Product webappContext); void stopWebapp(final String productId, final String containerId, final Product webappContext); static String getBaseUrl(final String server, final int actualHttpPort, final String contextPath); void runTests(String testGroupId, String containerId, List<String> includes, List<String> excludes, Map<String, Object> systemProperties, final File targetDirectory); void installPlugin(PdkParams pdkParams); void uninstallPlugin(final String pluginKey, final String server, final int port, final String contextPath); void installIdeaPlugin(); File copyDist(final File targetDirectory, final ProductArtifact artifact); File copyHome(final File targetDirectory, final ProductArtifact artifact); File copyZip(final File targetDirectory, final ProductArtifact artifact, final String localName); void generateBundleManifest(final Map<String, String> instructions, final Map<String, String> basicAttributes); void generateMinimalManifest(final Map<String, String> basicAttributes); void jarWithOptionalManifest(final boolean manifestExists); void jarTests(String finalName); void generateObrXml(File dep, File obrXml); void attachArtifact(File file, String type); void release(String mavenArgs); void generateRestDocs(); }
@Test public void testGenerateMinimalManifest() throws Exception { File tempDir = File.createTempFile("TestMavenGoals", "dir"); tempDir.delete(); tempDir.mkdir(); when(build.getOutputDirectory()).thenReturn(tempDir.getAbsolutePath()); Map<String, String> attrs = ImmutableMap.of("Attribute-A", "aaa", "Attribute-B", "bbb"); goals.generateMinimalManifest(attrs); File mf = file(tempDir.getAbsolutePath(), "META-INF", "MANIFEST.MF"); assertTrue(mf.exists()); Manifest m = new Manifest(new FileInputStream(mf)); assertEquals("aaa", m.getMainAttributes().getValue("Attribute-A")); assertEquals("bbb", m.getMainAttributes().getValue("Attribute-B")); assertNull(m.getMainAttributes().getValue("Bundle-SymbolicName")); }
AbstractProductHandlerMojo extends AbstractProductHandlerAwareMojo { void makeProductsInheritDefaultConfiguration(List<Product> products, Map<String, Product> productMap) throws MojoExecutionException { Product defaultProduct = createDefaultProductContext(); productMap.put(getProductId(), defaultProduct); if (!products.isEmpty()) { for (Product product : products) { Product processedProduct = product.merge(defaultProduct); if (ProductHandlerFactory.STUDIO_CROWD.equals(processedProduct.getId())) { processedProduct.getSystemPropertyVariables().put("atlassian.dev.mode", "false"); } String instanceId = getProductInstanceId(processedProduct); productMap.put(instanceId, processedProduct); } } } @Override final void execute(); }
@Test public void testMakeProductsInheritDefaultConfiguration() throws Exception { SomeMojo mojo = new SomeMojo("foo"); Product fooProd = new Product(); fooProd.setInstanceId("foo"); fooProd.setVersion("1.0"); Product barProd = new Product(); barProd.setInstanceId("bar"); barProd.setVersion("2.0"); Map<String,Product> prodMap = new HashMap<String, Product>(); mojo.makeProductsInheritDefaultConfiguration(asList(fooProd, barProd), prodMap); assertEquals(2, prodMap.size()); assertEquals("1.0", prodMap.get("foo").getVersion()); assertEquals("/foo", prodMap.get("foo").getContextPath()); assertEquals("2.0", prodMap.get("bar").getVersion()); assertEquals("/foo", prodMap.get("bar").getContextPath()); } @Test public void testMakeProductsInheritDefaultConfigurationDifferentInstanceIds() throws Exception { SomeMojo mojo = new SomeMojo("baz"); Product fooProd = new Product(); fooProd.setInstanceId("foo"); fooProd.setVersion("1.0"); Product barProd = new Product(); barProd.setInstanceId("bar"); barProd.setVersion("2.0"); Map<String,Product> prodMap = new HashMap<String, Product>(); mojo.makeProductsInheritDefaultConfiguration(asList(fooProd, barProd), prodMap); assertEquals(3, prodMap.size()); assertEquals("1.0", prodMap.get("foo").getVersion()); assertEquals("/foo", prodMap.get("foo").getContextPath()); assertEquals("2.0", prodMap.get("bar").getVersion()); assertEquals("/foo", prodMap.get("bar").getContextPath()); assertEquals(null, prodMap.get("baz").getVersion()); assertEquals("/foo", prodMap.get("baz").getContextPath()); } @Test public void testMakeProductsInheritDefaultConfigurationNoProducts() throws Exception { SomeMojo mojo = new SomeMojo("foo"); Map<String,Product> prodMap = new HashMap<String, Product>(); mojo.makeProductsInheritDefaultConfiguration(Collections.<Product>emptyList(), prodMap); assertEquals(1, prodMap.size()); assertEquals("/foo", prodMap.get("foo").getContextPath()); }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector applyToElements(DoubleFunction func) { SparseDoubleVector newVec = new SparseDoubleVector(this.dimension, func.apply(this.defaultValue)); for (Map.Entry<Integer, Double> entry : this.elements.entrySet()) { newVec.elements.put(entry.getKey(), func.apply(entry.getValue())); } return newVec; } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testApplyToElements() { DoubleVector v1 = new SparseDoubleVector(10, 5.5); DoubleVector v2 = v1.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return value * 11; } @Override public double applyDerivative(double value) { return 0; } }); DoubleVector v3 = v1.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return value / 2 + 1.75; } @Override public double applyDerivative(double value) { return 0; } }); DoubleVector v4 = v1.applyToElements(v2, new DoubleDoubleFunction() { @Override public double apply(double x1, double x2) { return x1 + x2; } @Override public double applyDerivative(double x1, double x2) { return 0; } }); for (int i = 0; i < 10; ++i) { assertEquals(v1.get(i), 5.5, 0.000001); assertEquals(v2.get(i), 60.5, 0.000001); assertEquals(v3.get(i), 4.5, 0.000001); assertEquals(v4.get(i), 66, 0.000001); } v3.set(3, 10); v3.set(6, 10); v3.set(8, 200); v4.set(5, 100); v4.set(8, 1); DoubleVector v5 = v4.applyToElements(v3, new DoubleDoubleFunction() { @Override public double apply(double x1, double x2) { return (x1 - x2) * 10; } @Override public double applyDerivative(double x1, double x2) { return 0; } }); DoubleVector v6 = new SparseDoubleVector(10, 615); v6.set(3, 560); v6.set(5, 955); v6.set(6, 560); v6.set(8, -1990); for (int i = 0; i < v5.getDimension(); ++i) { assertEquals(v5.get(i), v6.get(i), 0.000001); } DoubleVector v7 = new DenseDoubleVector(new double[] { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }); DoubleVector v8 = v5.applyToElements(v7, new DoubleDoubleFunction() { @Override public double apply(double x1, double x2) { return (x1 + x2) * 3.3; } @Override public double applyDerivative(double x1, double x2) { return 0; } }); DoubleVector v9 = v6.applyToElements(v7, new DoubleDoubleFunction() { @Override public double apply(double x1, double x2) { return (x1 + x2) * 3.3; } @Override public double applyDerivative(double x1, double x2) { return 0; } }); for (int i = 0; i < v7.getDimension(); ++i) { assertEquals(v8.get(i), v9.get(i), 0.000001); } }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector slice(int length) { Preconditions.checkArgument(length >= 0 && length < this.dimension, String.format("length must be in range [0, %d).", this.dimension)); return this.sliceUnsafe(length); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testSlice() { DoubleVector spVec1 = new SparseDoubleVector(10, 2.25); DoubleVector spVec2 = new SparseDoubleVector(10, 0); DoubleVector spVec3 = new SparseDoubleVector(5, 2.25); DoubleVector spVec4 = new SparseDoubleVector(5, 0); spVec1.set(7, 100); spVec2.set(2, 200); assertEquals(spVec3, spVec1.sliceUnsafe(5)); assertFalse(spVec4.equals(spVec2.slice(5))); assertFalse(spVec3.equals(spVec1.slice(5, 9))); assertEquals(spVec4, spVec2.slice(5, 9)); }
DenseDoubleVector implements DoubleVector { @Override public final DoubleVector add(double scalar) { DoubleVector newv = new DenseDoubleVector(this.getLength()); for (int i = 0; i < this.getLength(); i++) { newv.set(i, this.get(i) + scalar); } return newv; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test(expected = IllegalArgumentException.class) public void testAddAbnormal() { double[] arr1 = new double[] {1, 2, 3}; double[] arr2 = new double[] {4, 5}; DoubleVector vec1 = new DenseDoubleVector(arr1); DoubleVector vec2 = new DenseDoubleVector(arr2); vec1.add(vec2); } @Test(expected = IllegalArgumentException.class) public void testDotAbnormal() { double[] arr1 = new double[] {1, 2, 3}; double[] arr2 = new double[] {4, 5}; DoubleVector vec1 = new DenseDoubleVector(arr1); DoubleVector vec2 = new DenseDoubleVector(arr2); vec1.add(vec2); } @Test public void testAdd() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); DoubleVector vec3 = vec1.addUnsafe(vec2); for (int i = 0; i < vals1.length; ++i) { assertEquals(vec3.get(i), vec1.get(i) + vec2.get(i), 0.000001); } } @Test(expected = IllegalArgumentException.class) public void testAddWithException() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1, 0}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); vec1.add(vec2); }
DenseDoubleVector implements DoubleVector { @Override public final DoubleVector subtract(double v) { DenseDoubleVector newv = new DenseDoubleVector(vector.length); for (int i = 0; i < vector.length; i++) { newv.set(i, vector[i] - v); } return newv; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test(expected = IllegalArgumentException.class) public void testSubtractAbnormal() { double[] arr1 = new double[] {1, 2, 3}; double[] arr2 = new double[] {4, 5}; DoubleVector vec1 = new DenseDoubleVector(arr1); DoubleVector vec2 = new DenseDoubleVector(arr2); vec1.subtract(vec2); } @Test public void testSubtract() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); DoubleVector vec3 = vec1.subtractUnsafe(vec2); for (int i = 0; i < vals1.length; ++i) { assertEquals(vec3.get(i), vec1.get(i) - vec2.get(i), 0.000001); } } @Test(expected = IllegalArgumentException.class) public void testSubtractWithException() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1, 0}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); vec1.subtract(vec2); }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector multiply(double scalar) { DoubleVector v = new DenseDoubleVector(this.getLength()); for (int i = 0; i < v.getLength(); i++) { v.set(i, this.get(i) * scalar); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test(expected = IllegalArgumentException.class) public void testMultiplyAbnormal() { double[] arr1 = new double[] {1, 2, 3}; double[] arr2 = new double[] {4, 5}; DoubleVector vec1 = new DenseDoubleVector(arr1); DoubleVector vec2 = new DenseDoubleVector(arr2); vec1.multiply(vec2); } @Test(expected = IllegalArgumentException.class) public void testVectorMultiplyMatrixAbnormal() { DoubleVector vec = new DenseDoubleVector(new double[]{1, 2, 3}); DoubleMatrix mat = new DenseDoubleMatrix(new double[][] { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }); vec.multiply(mat); } @Test public void testMultiply() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); DoubleVector vec3 = vec1.multiplyUnsafe(vec2); for (int i = 0; i < vals1.length; ++i) { assertEquals(vec3.get(i), vec1.get(i) * vec2.get(i), 0.000001); } } @Test(expected = IllegalArgumentException.class) public void testMultiplyWithException() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1, 0}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); vec1.multiply(vec2); }
DenseDoubleVector implements DoubleVector { @Override public double dot(DoubleVector vector) { Preconditions.checkArgument(this.vector.length == vector.getDimension(), "Dimensions of two vectors do not equal."); return this.dotUnsafe(vector); } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testDotNormal() { double[] arr1 = new double[] {1, 2, 3}; double[] arr2 = new double[] {4, 5, 6}; DoubleVector vec1 = new DenseDoubleVector(arr1); DoubleVector vec2 = new DenseDoubleVector(arr2); assertEquals(32.0, vec1.dot(vec2), 0.000001); } @Test public void testDot() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); double expected = 0.0; double res = vec1.dotUnsafe(vec2); for (int i = 0; i < vals1.length; ++i) { expected += vec1.get(i) * vec2.get(i); } assertEquals(expected, res, 0.000001); } @Test(expected = IllegalArgumentException.class) public void testDotWithException() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1, 0}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); vec1.dot(vec2); }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector slice(int length) { return slice(0, length - 1); } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test(expected = IllegalArgumentException.class) public void testSliceAbnormal() { double[] arr1 = new double[] {2, 3, 4, 5, 6}; DoubleVector vec = new DenseDoubleVector(arr1); vec.slice(2, 5); } @Test(expected = IllegalArgumentException.class) public void testSliceAbnormalEndTooLarge() { double[] arr1 = new double[] {2, 3, 4, 5, 6}; DoubleVector vec = new DenseDoubleVector(arr1); vec.slice(2, 5); } @Test(expected = IllegalArgumentException.class) public void testSliceAbnormalStartLargerThanEnd() { double[] arr1 = new double[] {2, 3, 4, 5, 6}; DoubleVector vec = new DenseDoubleVector(arr1); vec.slice(4, 3); } @Test public void testSlice() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {2, 3, 4, 5, 6}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); DoubleVector vec3 = vec1.sliceUnsafe(1, 5); assertEquals(vec2, vec3); } @Test(expected = IllegalArgumentException.class) public void testSliceWithNegativeIndices() { double[] vals = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec = new DenseDoubleVector(vals); vec.slice(-1, -9); } @Test(expected = IllegalArgumentException.class) public void testSliceWithOutofBounds() { double[] vals = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec = new DenseDoubleVector(vals); vec.slice(1, 9); } @Test(expected = IllegalArgumentException.class) public void testSliceWithNegativeLength() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec1 = new DenseDoubleVector(vals1); vec1.slice(3, 2); }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector add(DoubleVector vector) { Preconditions.checkArgument(this.dimension == vector.getDimension(), "Dimensions of two vectors are not the same."); return this.addUnsafe(vector); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testAdd() { DoubleVector spVec1 = new SparseDoubleVector(10, 1.5); DoubleVector spVec2 = new SparseDoubleVector(10); for (int i = 0; i < spVec2.getDimension(); ++i) { spVec2.set(i, 1.5); } DoubleVector expRes1 = new SparseDoubleVector(10, 3.0); assertEquals(expRes1, spVec1.add(spVec2)); DoubleVector dsVec1 = new DenseDoubleVector(10); for (int i = 0; i < dsVec1.getDimension(); ++i) { dsVec1.set(i, 1.5); } DoubleVector expRes2 = new DenseDoubleVector(10); for (int i = 0; i < expRes2.getDimension(); ++i) { expRes2.set(i, 3.0); } assertEquals(expRes2, dsVec1.add(spVec2)); }
DenseDoubleVector implements DoubleVector { @Override public final DoubleVector subtractFrom(double v) { DenseDoubleVector newv = new DenseDoubleVector(vector.length); for (int i = 0; i < vector.length; i++) { newv.set(i, v - vector[i]); } return newv; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testSubtractFrom() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec1 = new DenseDoubleVector(vals1); double constant = 10; DoubleVector vec3 = vec1.subtractFrom(constant); for (int i = 0; i < vals1.length; ++i) { assertEquals(constant - vec1.get(i), vec3.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector divide(double scalar) { DenseDoubleVector v = new DenseDoubleVector(this.getLength()); for (int i = 0; i < v.getLength(); i++) { v.set(i, this.get(i) / scalar); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testDivide() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec1 = new DenseDoubleVector(vals1); double constant = 10; DoubleVector vec3 = vec1.divide(constant); for (int i = 0; i < vals1.length; ++i) { assertEquals(vec1.get(i) / constant, vec3.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector pow(int x) { DenseDoubleVector v = new DenseDoubleVector(getLength()); for (int i = 0; i < v.getLength(); i++) { double value = 0.0d; if (x == 2) { value = vector[i] * vector[i]; } else { value = Math.pow(vector[i], x); } v.set(i, value); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testPow() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec1 = new DenseDoubleVector(vals1); int constant = 5; DoubleVector vec3 = vec1.pow(constant); for (int i = 0; i < vals1.length; ++i) { assertEquals(Math.pow(vec1.get(i), 5), vec3.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector sqrt() { DoubleVector v = new DenseDoubleVector(getLength()); for (int i = 0; i < v.getLength(); i++) { v.set(i, Math.sqrt(vector[i])); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testSqrt() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec3 = vec1.sqrt(); for (int i = 0; i < vals1.length; ++i) { assertEquals(Math.sqrt(vec1.get(i)), vec3.get(i), 0.000001); } }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector subtract(DoubleVector vector) { Preconditions.checkArgument(this.dimension == vector.getDimension(), "Dimensions of two vector are not the same."); return this.subtractUnsafe(vector); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testSubtract() { DoubleVector spVec1 = new SparseDoubleVector(10, 1.5); DoubleVector spVec2 = new SparseDoubleVector(10); DoubleVector spVec3 = new SparseDoubleVector(10, 2.2); for (int i = 0; i < spVec2.getDimension(); ++i) { spVec2.set(i, 1.2); } DoubleVector expRes1 = new SparseDoubleVector(10, 0.3); assertEquals(expRes1, spVec1.subtract(spVec2)); DoubleVector expRes2 = new SparseDoubleVector(10, -0.7); assertEquals(expRes2, spVec1.subtract(spVec3)); DoubleVector dsVec1 = new DenseDoubleVector(10); for (int i = 0; i < dsVec1.getDimension(); ++i) { dsVec1.set(i, 1.7); } DoubleVector expRes3 = new SparseDoubleVector(10, 0.2); assertEquals(expRes3, dsVec1.subtract(spVec1)); DoubleVector expRes4 = new SparseDoubleVector(10, -0.2); assertEquals(expRes4, spVec1.subtract(dsVec1)); }
DenseDoubleVector implements DoubleVector { @Override public double sum() { double sum = 0.0d; for (double aVector : vector) { sum += aVector; } return sum; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testSum() { double[] vals = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec = new DenseDoubleVector(vals); double expected = 0; double res = vec.sum(); for (int i = 0; i < vals.length; ++i) { expected += vec.get(i); } assertEquals(expected, res, 0.000001); }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector abs() { DoubleVector v = new DenseDoubleVector(getLength()); for (int i = 0; i < v.getLength(); i++) { v.set(i, Math.abs(vector[i])); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testAbs() { double[] vals = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec = new DenseDoubleVector(vals); DoubleVector vec2 = vec.abs(); for (int i = 0; i < vals.length; ++i) { assertEquals(Math.abs(vec.get(i)), vec2.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector divideFrom(double scalar) { DoubleVector v = new DenseDoubleVector(this.getLength()); for (int i = 0; i < v.getLength(); i++) { if (this.get(i) != 0.0d) { double result = scalar / this.get(i); v.set(i, result); } else { v.set(i, 0.0d); } } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testDivideFrom() { double[] vals1 = {1, 2, 3, 4, 5, 6, 7, 8}; DoubleVector vec1 = new DenseDoubleVector(vals1); double constant = 10; DoubleVector vec3 = vec1.divideFrom(constant); for (int i = 0; i < vals1.length; ++i) { assertEquals(constant / vec1.get(i), vec3.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { public DenseDoubleVector rint() { DenseDoubleVector v = new DenseDoubleVector(getLength()); for (int i = 0; i < getLength(); i++) { double d = vector[i]; v.set(i, Math.rint(d)); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testRint() { double[] vals = {11, 2, 3, 4, 15, 6, 7, 8}; DenseDoubleVector vec = new DenseDoubleVector(vals); DenseDoubleVector vec2 = vec.rint(); for (int i = 0; i < vec.getDimension(); ++i) { assertEquals(Math.rint(vec.get(i)), vec2.get(i), 0.000001); } }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector multiply(double scalar) { final double val = scalar; return this.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return val * value; } @Override public double applyDerivative(double value) { throw new UnsupportedOperationException(); } }); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testMultiply() { DoubleVector spVec1 = new SparseDoubleVector(10, 1.5); DoubleVector spVec2 = new SparseDoubleVector(10); DoubleVector spVec3 = new SparseDoubleVector(10, 2.2); DoubleVector spRes1 = spVec1.applyToElements(spVec3, new DoubleDoubleFunction() { @Override public double apply(double first, double second) { return first * second; } @Override public double applyDerivative(double value, double second) { throw new UnsupportedOperationException(); } }); assertEquals(spRes1, spVec1.multiply(spVec3)); assertEquals(spVec2, spVec1.multiply(spVec2)); }
DenseDoubleVector implements DoubleVector { public DenseDoubleVector round() { DenseDoubleVector v = new DenseDoubleVector(getLength()); for (int i = 0; i < getLength(); i++) { double d = vector[i]; v.set(i, Math.round(d)); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testRound() { double[] vals = {11, 2, 3, 4, 15, 6, 7, 8}; DenseDoubleVector vec = new DenseDoubleVector(vals); DenseDoubleVector vec2 = vec.round(); for (int i = 0; i < vec.getDimension(); ++i) { assertEquals(Math.round(vec.get(i)), vec2.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { public DenseDoubleVector ceil() { DenseDoubleVector v = new DenseDoubleVector(getLength()); for (int i = 0; i < getLength(); i++) { double d = vector[i]; v.set(i, Math.ceil(d)); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testCeil() { double[] vals = {11, 2, 3, 4, 15, 6, 7, 8}; DenseDoubleVector vec = new DenseDoubleVector(vals); DenseDoubleVector vec2 = vec.ceil(); for (int i = 0; i < vec.getDimension(); ++i) { assertEquals(Math.ceil(vec.get(i)), vec2.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { @Override public final double[] toArray() { return vector; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testToArray() { double[] vals = {1, 2, 3, 4, 5, 6, 7, 8, 9}; DenseDoubleVector vec = new DenseDoubleVector(vals); double[] vals2 = vec.toArray(); assertEquals(vals, vals2); }
DenseDoubleVector implements DoubleVector { @Override public DoubleVector deepCopy() { final double[] src = vector; final double[] dest = new double[vector.length]; System.arraycopy(src, 0, dest, 0, vector.length); return new DenseDoubleVector(dest); } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test(expected = AssertionError.class) public void deepCopy() { double[] vals1 = {0, 1, 2, 3, 4, 5, 6, 7, 8}; double[] vals2 = {8, 7, 6, 5, 4, 3, 2, 1, 0}; DoubleVector vec1 = new DenseDoubleVector(vals1); DoubleVector vec2 = new DenseDoubleVector(vals2); DoubleVector vec3 = vec1.deepCopy(); vec1 = vec1.add(vec2); assertEquals(vec1, vec3); }
DenseDoubleVector implements DoubleVector { public static DenseDoubleVector ones(int num) { return new DenseDoubleVector(num, 1.0d); } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testOnes() { DoubleVector vec = DenseDoubleVector.ones(10); for (int i = 0; i < vec.getDimension(); ++i) { assertEquals(1, vec.get(i), 0.000001); } }
DenseDoubleVector implements DoubleVector { public static DenseDoubleVector fromUpTo(double from, double to, double stepsize) { DenseDoubleVector v = new DenseDoubleVector( (int) (Math.round(((to - from) / stepsize) + 0.5))); for (int i = 0; i < v.getLength(); i++) { v.set(i, from + i * stepsize); } return v; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testFromUpTo() { double from = 11; double to = 111.5; double stepsize = 2.5; DoubleVector vec = DenseDoubleVector.fromUpTo(from, to, stepsize); int curIndex = 0; double cur = 11; while (cur <= to) { assertEquals(cur, vec.get(curIndex), 0.000001); cur += stepsize; ++curIndex; } }
DenseDoubleVector implements DoubleVector { public static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator) { List<Tuple<Double, Integer>> list = new ArrayList<Tuple<Double, Integer>>( vector.getLength()); for (int i = 0; i < vector.getLength(); i++) { list.add(new Tuple<Double, Integer>(vector.get(i), i)); } Collections.sort(list, new Comparator<Tuple<Double, Integer>>() { @Override public int compare(Tuple<Double, Integer> o1, Tuple<Double, Integer> o2) { return scoreComparator.compare(o1.getFirst(), o2.getFirst()); } }); return list; } DenseDoubleVector(); DenseDoubleVector(int length); DenseDoubleVector(int length, double val); DenseDoubleVector(double[] arr); DenseDoubleVector(double[] array, double f1); @Override final double get(int index); @Override final int getLength(); @Override int getDimension(); @Override final void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override final DoubleVector addUnsafe(DoubleVector v); @Override final DoubleVector add(double scalar); @Override final DoubleVector subtractUnsafe(DoubleVector v); @Override final DoubleVector subtract(double v); @Override final DoubleVector subtractFrom(double v); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector sqrt(); @Override double sum(); @Override DoubleVector abs(); @Override DoubleVector divideFrom(double scalar); @Override double dotUnsafe(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); int maxIndex(); @Override double min(); int minIndex(); DenseDoubleVector rint(); DenseDoubleVector round(); DenseDoubleVector ceil(); @Override final double[] toArray(); @Override boolean isSparse(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override final String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static DenseDoubleVector ones(int num); static DenseDoubleVector fromUpTo(double from, double to, double stepsize); static List<Tuple<Double, Integer>> sort(DoubleVector vector, final Comparator<Double> scoreComparator); @Override boolean isNamed(); @Override String getName(); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override double dot(DoubleVector vector); }
@Test public void testSort() { double[] vals = {12, 32, 31, 11, 52, 13, -1, -222, 2}; DoubleVector vec = new DenseDoubleVector(vals); Comparator<Double> comparator = new Comparator<Double>() { @Override public int compare(Double arg0, Double arg1) { return Double.compare(arg0, arg1); } }; List<Tuple<Double, Integer>> sorted = DenseDoubleVector.sort(vec, comparator); for (int i = 1; i < sorted.size(); ++i) { Tuple<Double, Integer> previous = sorted.get(i - 1); Tuple<Double, Integer> cur = sorted.get(i); assertTrue(previous.getFirst() <= cur.getFirst()); } }
DenseDoubleMatrix implements DoubleMatrix { @Override public final DenseDoubleMatrix multiply(double scalar) { DenseDoubleMatrix m = new DenseDoubleMatrix(this.numRows, this.numColumns); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { m.set(i, j, this.matrix[i][j] * scalar); } } return m; } DenseDoubleMatrix(); DenseDoubleMatrix(int rows, int columns); DenseDoubleMatrix(int rows, int columns, double defaultValue); DenseDoubleMatrix(int rows, int columns, Random rand); DenseDoubleMatrix(double[][] otherMatrix); DenseDoubleMatrix(DoubleVector[] vectorArray); DenseDoubleMatrix(DenseDoubleVector first); DenseDoubleMatrix(double[] v, int rows, int columns); DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix); @Override final double get(int row, int col); final double[] getColumn(int col); @Override final int getColumnCount(); @Override final DoubleVector getColumnVector(int col); final double[][] getValues(); final double[] getRow(int row); @Override final int getRowCount(); @Override final DoubleVector getRowVector(int row); @Override final void set(int row, int col, double value); final void setRow(int row, double[] value); final void setColumn(int col, double[] values); @Override void setColumnVector(int col, DoubleVector column); @Override void setRowVector(int rowIndex, DoubleVector row); String sizeToString(); final Tuple<DenseDoubleMatrix, DenseDoubleVector> splitLastColumn(); final Tuple<DenseDoubleMatrix, DenseDoubleMatrix> splitRandomMatrices( float percentage); @Override final DenseDoubleMatrix multiply(double scalar); @Override final DoubleMatrix multiplyUnsafe(DoubleMatrix other); @Override final DoubleMatrix multiplyElementWiseUnsafe(DoubleMatrix other); @Override final DoubleVector multiplyVectorUnsafe(DoubleVector v); @Override DenseDoubleMatrix transpose(); @Override DenseDoubleMatrix subtractBy(double amount); @Override DenseDoubleMatrix subtract(double amount); @Override DoubleMatrix subtractUnsafe(DoubleMatrix other); @Override DenseDoubleMatrix subtractUnsafe(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleVector vec); @Override DoubleMatrix divide(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleMatrix other); @Override DoubleMatrix divide(DoubleMatrix other); @Override DoubleMatrix divide(double scalar); @Override DoubleMatrix add(DoubleMatrix other); @Override DoubleMatrix pow(int x); @Override double max(int column); @Override double min(int column); @Override DoubleMatrix slice(int rows, int cols); @Override DoubleMatrix slice(int rowOffset, int rowMax, int colOffset, int colMax); @Override boolean isSparse(); @Override double sum(); @Override int[] columnIndices(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static DenseDoubleMatrix eye(int dimension); static DenseDoubleMatrix copy(DenseDoubleMatrix matrix); static DenseDoubleMatrix multiplyTransposedVectors( DoubleVector transposed, DoubleVector normal); static double error(DenseDoubleMatrix a, DenseDoubleMatrix b); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleFunction fun); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleMatrix other, DoubleDoubleFunction fun); @Override DoubleMatrix multiply(DoubleMatrix other); @Override DoubleMatrix multiplyElementWise(DoubleMatrix other); @Override DoubleVector multiplyVector(DoubleVector v); @Override DoubleMatrix subtract(DoubleMatrix other); @Override DoubleMatrix subtract(DoubleVector vec); }
@Test(expected = IllegalArgumentException.class) public void testMultiplyAbnormal() { double[][] mat1 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; double[][] mat2 = new double[][] { { 6, 5 }, { 4, 3 } }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleMatrix matrix2 = new DenseDoubleMatrix(mat2); matrix1.multiply(matrix2); }
DenseDoubleMatrix implements DoubleMatrix { @Override public DoubleMatrix multiplyElementWise(DoubleMatrix other) { Preconditions.checkArgument(this.numRows == other.getRowCount() && this.numColumns == other.getColumnCount(), "Matrices with different dimensions cannot be multiplied elementwise."); return this.multiplyElementWiseUnsafe(other); } DenseDoubleMatrix(); DenseDoubleMatrix(int rows, int columns); DenseDoubleMatrix(int rows, int columns, double defaultValue); DenseDoubleMatrix(int rows, int columns, Random rand); DenseDoubleMatrix(double[][] otherMatrix); DenseDoubleMatrix(DoubleVector[] vectorArray); DenseDoubleMatrix(DenseDoubleVector first); DenseDoubleMatrix(double[] v, int rows, int columns); DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix); @Override final double get(int row, int col); final double[] getColumn(int col); @Override final int getColumnCount(); @Override final DoubleVector getColumnVector(int col); final double[][] getValues(); final double[] getRow(int row); @Override final int getRowCount(); @Override final DoubleVector getRowVector(int row); @Override final void set(int row, int col, double value); final void setRow(int row, double[] value); final void setColumn(int col, double[] values); @Override void setColumnVector(int col, DoubleVector column); @Override void setRowVector(int rowIndex, DoubleVector row); String sizeToString(); final Tuple<DenseDoubleMatrix, DenseDoubleVector> splitLastColumn(); final Tuple<DenseDoubleMatrix, DenseDoubleMatrix> splitRandomMatrices( float percentage); @Override final DenseDoubleMatrix multiply(double scalar); @Override final DoubleMatrix multiplyUnsafe(DoubleMatrix other); @Override final DoubleMatrix multiplyElementWiseUnsafe(DoubleMatrix other); @Override final DoubleVector multiplyVectorUnsafe(DoubleVector v); @Override DenseDoubleMatrix transpose(); @Override DenseDoubleMatrix subtractBy(double amount); @Override DenseDoubleMatrix subtract(double amount); @Override DoubleMatrix subtractUnsafe(DoubleMatrix other); @Override DenseDoubleMatrix subtractUnsafe(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleVector vec); @Override DoubleMatrix divide(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleMatrix other); @Override DoubleMatrix divide(DoubleMatrix other); @Override DoubleMatrix divide(double scalar); @Override DoubleMatrix add(DoubleMatrix other); @Override DoubleMatrix pow(int x); @Override double max(int column); @Override double min(int column); @Override DoubleMatrix slice(int rows, int cols); @Override DoubleMatrix slice(int rowOffset, int rowMax, int colOffset, int colMax); @Override boolean isSparse(); @Override double sum(); @Override int[] columnIndices(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static DenseDoubleMatrix eye(int dimension); static DenseDoubleMatrix copy(DenseDoubleMatrix matrix); static DenseDoubleMatrix multiplyTransposedVectors( DoubleVector transposed, DoubleVector normal); static double error(DenseDoubleMatrix a, DenseDoubleMatrix b); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleFunction fun); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleMatrix other, DoubleDoubleFunction fun); @Override DoubleMatrix multiply(DoubleMatrix other); @Override DoubleMatrix multiplyElementWise(DoubleMatrix other); @Override DoubleVector multiplyVector(DoubleVector v); @Override DoubleMatrix subtract(DoubleMatrix other); @Override DoubleMatrix subtract(DoubleVector vec); }
@Test(expected = IllegalArgumentException.class) public void testMultiplyElementWiseAbnormal() { double[][] mat1 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; double[][] mat2 = new double[][] { { 6, 5 }, { 4, 3 } }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleMatrix matrix2 = new DenseDoubleMatrix(mat2); matrix1.multiplyElementWise(matrix2); }
DenseDoubleMatrix implements DoubleMatrix { @Override public DoubleVector multiplyVector(DoubleVector v) { Preconditions.checkArgument(this.numColumns == v.getDimension(), "Dimension mismatch."); return this.multiplyVectorUnsafe(v); } DenseDoubleMatrix(); DenseDoubleMatrix(int rows, int columns); DenseDoubleMatrix(int rows, int columns, double defaultValue); DenseDoubleMatrix(int rows, int columns, Random rand); DenseDoubleMatrix(double[][] otherMatrix); DenseDoubleMatrix(DoubleVector[] vectorArray); DenseDoubleMatrix(DenseDoubleVector first); DenseDoubleMatrix(double[] v, int rows, int columns); DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix); @Override final double get(int row, int col); final double[] getColumn(int col); @Override final int getColumnCount(); @Override final DoubleVector getColumnVector(int col); final double[][] getValues(); final double[] getRow(int row); @Override final int getRowCount(); @Override final DoubleVector getRowVector(int row); @Override final void set(int row, int col, double value); final void setRow(int row, double[] value); final void setColumn(int col, double[] values); @Override void setColumnVector(int col, DoubleVector column); @Override void setRowVector(int rowIndex, DoubleVector row); String sizeToString(); final Tuple<DenseDoubleMatrix, DenseDoubleVector> splitLastColumn(); final Tuple<DenseDoubleMatrix, DenseDoubleMatrix> splitRandomMatrices( float percentage); @Override final DenseDoubleMatrix multiply(double scalar); @Override final DoubleMatrix multiplyUnsafe(DoubleMatrix other); @Override final DoubleMatrix multiplyElementWiseUnsafe(DoubleMatrix other); @Override final DoubleVector multiplyVectorUnsafe(DoubleVector v); @Override DenseDoubleMatrix transpose(); @Override DenseDoubleMatrix subtractBy(double amount); @Override DenseDoubleMatrix subtract(double amount); @Override DoubleMatrix subtractUnsafe(DoubleMatrix other); @Override DenseDoubleMatrix subtractUnsafe(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleVector vec); @Override DoubleMatrix divide(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleMatrix other); @Override DoubleMatrix divide(DoubleMatrix other); @Override DoubleMatrix divide(double scalar); @Override DoubleMatrix add(DoubleMatrix other); @Override DoubleMatrix pow(int x); @Override double max(int column); @Override double min(int column); @Override DoubleMatrix slice(int rows, int cols); @Override DoubleMatrix slice(int rowOffset, int rowMax, int colOffset, int colMax); @Override boolean isSparse(); @Override double sum(); @Override int[] columnIndices(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static DenseDoubleMatrix eye(int dimension); static DenseDoubleMatrix copy(DenseDoubleMatrix matrix); static DenseDoubleMatrix multiplyTransposedVectors( DoubleVector transposed, DoubleVector normal); static double error(DenseDoubleMatrix a, DenseDoubleMatrix b); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleFunction fun); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleMatrix other, DoubleDoubleFunction fun); @Override DoubleMatrix multiply(DoubleMatrix other); @Override DoubleMatrix multiplyElementWise(DoubleMatrix other); @Override DoubleVector multiplyVector(DoubleVector v); @Override DoubleMatrix subtract(DoubleMatrix other); @Override DoubleMatrix subtract(DoubleVector vec); }
@Test public void testMultiplyVectorNormal() { double[][] mat1 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; double[] mat2 = new double[] { 6, 5, 4 }; double[] expVec = new double[] { 28, 73 }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleVector vector2 = new DenseDoubleVector(mat2); DoubleVector actVec = matrix1.multiplyVector(vector2); assertArrayEquals(expVec, actVec.toArray(), 0.000001); } @Test(expected = IllegalArgumentException.class) public void testMultiplyVectorAbnormal() { double[][] mat1 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; double[] vec2 = new double[] { 6, 5 }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleVector vector2 = new DenseDoubleVector(vec2); matrix1.multiplyVector(vector2); }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector divide(double scalar) { Preconditions.checkArgument(scalar != 0, "Scalar cannot be 0."); final double factor = scalar; return this.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return value / factor; } @Override public double applyDerivative(double value) { throw new UnsupportedOperationException(); } }); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testDivide() { DoubleVector spVec1 = new SparseDoubleVector(10, 1.5); DoubleVector spVec2 = new SparseDoubleVector(10, 6.0); DoubleVector spVec3 = new SparseDoubleVector(10, 2.2); assertEquals(spVec3, spVec1.divide(1.5 / 2.2)); assertEquals(spVec2, spVec1.divideFrom(9)); }
DenseDoubleMatrix implements DoubleMatrix { @Override public DenseDoubleMatrix subtract(double amount) { DenseDoubleMatrix m = new DenseDoubleMatrix(this.numRows, this.numColumns); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numColumns; j++) { m.set(i, j, this.matrix[i][j] - amount); } } return m; } DenseDoubleMatrix(); DenseDoubleMatrix(int rows, int columns); DenseDoubleMatrix(int rows, int columns, double defaultValue); DenseDoubleMatrix(int rows, int columns, Random rand); DenseDoubleMatrix(double[][] otherMatrix); DenseDoubleMatrix(DoubleVector[] vectorArray); DenseDoubleMatrix(DenseDoubleVector first); DenseDoubleMatrix(double[] v, int rows, int columns); DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix); @Override final double get(int row, int col); final double[] getColumn(int col); @Override final int getColumnCount(); @Override final DoubleVector getColumnVector(int col); final double[][] getValues(); final double[] getRow(int row); @Override final int getRowCount(); @Override final DoubleVector getRowVector(int row); @Override final void set(int row, int col, double value); final void setRow(int row, double[] value); final void setColumn(int col, double[] values); @Override void setColumnVector(int col, DoubleVector column); @Override void setRowVector(int rowIndex, DoubleVector row); String sizeToString(); final Tuple<DenseDoubleMatrix, DenseDoubleVector> splitLastColumn(); final Tuple<DenseDoubleMatrix, DenseDoubleMatrix> splitRandomMatrices( float percentage); @Override final DenseDoubleMatrix multiply(double scalar); @Override final DoubleMatrix multiplyUnsafe(DoubleMatrix other); @Override final DoubleMatrix multiplyElementWiseUnsafe(DoubleMatrix other); @Override final DoubleVector multiplyVectorUnsafe(DoubleVector v); @Override DenseDoubleMatrix transpose(); @Override DenseDoubleMatrix subtractBy(double amount); @Override DenseDoubleMatrix subtract(double amount); @Override DoubleMatrix subtractUnsafe(DoubleMatrix other); @Override DenseDoubleMatrix subtractUnsafe(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleVector vec); @Override DoubleMatrix divide(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleMatrix other); @Override DoubleMatrix divide(DoubleMatrix other); @Override DoubleMatrix divide(double scalar); @Override DoubleMatrix add(DoubleMatrix other); @Override DoubleMatrix pow(int x); @Override double max(int column); @Override double min(int column); @Override DoubleMatrix slice(int rows, int cols); @Override DoubleMatrix slice(int rowOffset, int rowMax, int colOffset, int colMax); @Override boolean isSparse(); @Override double sum(); @Override int[] columnIndices(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static DenseDoubleMatrix eye(int dimension); static DenseDoubleMatrix copy(DenseDoubleMatrix matrix); static DenseDoubleMatrix multiplyTransposedVectors( DoubleVector transposed, DoubleVector normal); static double error(DenseDoubleMatrix a, DenseDoubleMatrix b); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleFunction fun); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleMatrix other, DoubleDoubleFunction fun); @Override DoubleMatrix multiply(DoubleMatrix other); @Override DoubleMatrix multiplyElementWise(DoubleMatrix other); @Override DoubleVector multiplyVector(DoubleVector v); @Override DoubleMatrix subtract(DoubleMatrix other); @Override DoubleMatrix subtract(DoubleVector vec); }
@Test(expected = IllegalArgumentException.class) public void testSubtractAbnormal() { double[][] mat1 = new double[][] { {1, 2, 3}, {4, 5, 6} }; double[][] mat2 = new double[][] { {6, 5}, {4, 3} }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleMatrix matrix2 = new DenseDoubleMatrix(mat2); matrix1.subtract(matrix2); }
DenseDoubleMatrix implements DoubleMatrix { @Override public DoubleMatrix divide(DoubleVector vec) { Preconditions.checkArgument(this.getColumnCount() == vec.getDimension(), "Dimension mismatch."); return this.divideUnsafe(vec); } DenseDoubleMatrix(); DenseDoubleMatrix(int rows, int columns); DenseDoubleMatrix(int rows, int columns, double defaultValue); DenseDoubleMatrix(int rows, int columns, Random rand); DenseDoubleMatrix(double[][] otherMatrix); DenseDoubleMatrix(DoubleVector[] vectorArray); DenseDoubleMatrix(DenseDoubleVector first); DenseDoubleMatrix(double[] v, int rows, int columns); DenseDoubleMatrix(DenseDoubleVector first, DoubleMatrix otherMatrix); @Override final double get(int row, int col); final double[] getColumn(int col); @Override final int getColumnCount(); @Override final DoubleVector getColumnVector(int col); final double[][] getValues(); final double[] getRow(int row); @Override final int getRowCount(); @Override final DoubleVector getRowVector(int row); @Override final void set(int row, int col, double value); final void setRow(int row, double[] value); final void setColumn(int col, double[] values); @Override void setColumnVector(int col, DoubleVector column); @Override void setRowVector(int rowIndex, DoubleVector row); String sizeToString(); final Tuple<DenseDoubleMatrix, DenseDoubleVector> splitLastColumn(); final Tuple<DenseDoubleMatrix, DenseDoubleMatrix> splitRandomMatrices( float percentage); @Override final DenseDoubleMatrix multiply(double scalar); @Override final DoubleMatrix multiplyUnsafe(DoubleMatrix other); @Override final DoubleMatrix multiplyElementWiseUnsafe(DoubleMatrix other); @Override final DoubleVector multiplyVectorUnsafe(DoubleVector v); @Override DenseDoubleMatrix transpose(); @Override DenseDoubleMatrix subtractBy(double amount); @Override DenseDoubleMatrix subtract(double amount); @Override DoubleMatrix subtractUnsafe(DoubleMatrix other); @Override DenseDoubleMatrix subtractUnsafe(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleVector vec); @Override DoubleMatrix divide(DoubleVector vec); @Override DoubleMatrix divideUnsafe(DoubleMatrix other); @Override DoubleMatrix divide(DoubleMatrix other); @Override DoubleMatrix divide(double scalar); @Override DoubleMatrix add(DoubleMatrix other); @Override DoubleMatrix pow(int x); @Override double max(int column); @Override double min(int column); @Override DoubleMatrix slice(int rows, int cols); @Override DoubleMatrix slice(int rowOffset, int rowMax, int colOffset, int colMax); @Override boolean isSparse(); @Override double sum(); @Override int[] columnIndices(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static DenseDoubleMatrix eye(int dimension); static DenseDoubleMatrix copy(DenseDoubleMatrix matrix); static DenseDoubleMatrix multiplyTransposedVectors( DoubleVector transposed, DoubleVector normal); static double error(DenseDoubleMatrix a, DenseDoubleMatrix b); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleFunction fun); @Override /** * {@inheritDoc} */ DoubleMatrix applyToElements(DoubleMatrix other, DoubleDoubleFunction fun); @Override DoubleMatrix multiply(DoubleMatrix other); @Override DoubleMatrix multiplyElementWise(DoubleMatrix other); @Override DoubleVector multiplyVector(DoubleVector v); @Override DoubleMatrix subtract(DoubleMatrix other); @Override DoubleMatrix subtract(DoubleVector vec); }
@Test(expected = IllegalArgumentException.class) public void testDivideVectorAbnormal() { double[][] mat1 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; double[] vec2 = new double[] { 6, 5 }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleVector vector2 = new DenseDoubleVector(vec2); matrix1.divide(vector2); } @Test(expected = IllegalArgumentException.class) public void testDivideAbnormal() { double[][] mat1 = new double[][] { { 1, 2, 3 }, { 4, 5, 6 } }; double[][] mat2 = new double[][] { { 6, 5 }, { 4, 3 } }; DoubleMatrix matrix1 = new DenseDoubleMatrix(mat1); DoubleMatrix matrix2 = new DenseDoubleMatrix(mat2); matrix1.divide(matrix2); }
AverageAggregator extends AbsDiffAggregator { @Override public DoubleWritable finalizeAggregation() { return new DoubleWritable(getValue().get() / getTimesAggregated().get()); } @Override DoubleWritable finalizeAggregation(); }
@Test public void testAggregator() { AverageAggregator diff = new AverageAggregator(); diff.aggregate(new DoubleWritable(5), new DoubleWritable(2)); diff.aggregateInternal(); diff.aggregate(new DoubleWritable(5), new DoubleWritable(2)); diff.aggregateInternal(); diff.aggregate(null, new DoubleWritable(5)); diff.aggregateInternal(); assertEquals(3, diff.getTimesAggregated().get()); DoubleWritable x = diff.finalizeAggregation(); assertEquals(2, (int) x.get()); }
SSSP { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { if (args.length < 3) printUsage(); HamaConfiguration conf = new HamaConfiguration(); GraphJob ssspJob = new GraphJob(conf, SSSP.class); ssspJob.setJobName("Single Source Shortest Path"); conf.set(START_VERTEX, args[0]); ssspJob.setInputPath(new Path(args[1])); ssspJob.setOutputPath(new Path(args[2])); if (args.length == 4) { ssspJob.setNumBspTask(Integer.parseInt(args[3])); } ssspJob.setVertexClass(ShortestPathVertex.class); ssspJob.setCombinerClass(MinIntCombiner.class); ssspJob.setInputFormat(TextInputFormat.class); ssspJob.setInputKeyClass(LongWritable.class); ssspJob.setInputValueClass(Text.class); ssspJob.setPartitioner(HashPartitioner.class); ssspJob.setOutputFormat(TextOutputFormat.class); ssspJob.setVertexInputReaderClass(SSSPTextReader.class); ssspJob.setOutputKeyClass(Text.class); ssspJob.setOutputValueClass(IntWritable.class); ssspJob.setMaxIteration(Integer.MAX_VALUE); ssspJob.setVertexIDClass(Text.class); ssspJob.setVertexValueClass(IntWritable.class); ssspJob.setEdgeValueClass(IntWritable.class); long startTime = System.currentTimeMillis(); if (ssspJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); static final String START_VERTEX; }
@Test public void testShortestPaths() throws IOException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException { SSSP.main(new String[] { "0", INPUT, OUTPUT, "3" }); verifyResult(); }
DynamicGraph { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { if (args.length != 2) { printUsage(); } HamaConfiguration conf = new HamaConfiguration(new Configuration()); GraphJob graphJob = createJob(args, conf); long startTime = System.currentTimeMillis(); if (graphJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }
@Test public void test() throws IOException, InterruptedException, ClassNotFoundException { try { DynamicGraph.main(new String[] { "src/test/resources/dg.txt", OUTPUT }); verifyResult(); } finally { deleteTempDirs(); } }
BipartiteMatching { public static GraphJob createJob(String[] args, HamaConfiguration conf) throws IOException { GraphJob job = new GraphJob(conf, BipartiteMatching.class); job.setMaxIteration(30); job.setNumBspTask(2); if (args.length >= 4) job.setNumBspTask(Integer.parseInt(args[3])); if (args.length >= 3) job.setMaxIteration(Integer.parseInt(args[2])); job.setJobName("BipartiteMatching"); job.setInputPath(new Path(args[0])); job.setOutputPath(new Path(args[1])); job.setVertexClass(BipartiteMatchingVertex.class); job.setVertexIDClass(Text.class); job.setVertexValueClass(TextPair.class); job.setEdgeValueClass(NullWritable.class); job.setInputFormat(TextInputFormat.class); job.setInputKeyClass(LongWritable.class); job.setInputValueClass(Text.class); job.setVertexInputReaderClass(BipartiteMatchingVertexReader.class); job.setPartitioner(HashPartitioner.class); job.setOutputFormat(TextOutputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(TextPair.class); return job; } static GraphJob createJob(String[] args, HamaConfiguration conf); static void main(String... args); static final String SEED_CONFIGURATION_KEY; }
@Test public void testBipartiteMatching() throws IOException, InterruptedException, ClassNotFoundException { deleteTempDirs(); generateTestData(); try { HamaConfiguration conf = new HamaConfiguration(); GraphJob job = BipartiteMatching.createJob(new String[] { INPUT, OUTPUT, "30", "2" }, conf); job.setPartitioner(CustomTextPartitioner.class); job.setNumBspTask(1); long startTime = System.currentTimeMillis(); if (job.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } verifyResult(); } finally { deleteTempDirs(); } }
KCore { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { if (args.length != 2) { printUsage(); } HamaConfiguration conf = new HamaConfiguration(new Configuration()); GraphJob graphJob = createJob(args, conf); long startTime = System.currentTimeMillis(); if (graphJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }
@Test public void testKcore() throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException { try { setOutputResult(); KCore.main(new String[] { INPUT, OUTPUT }); verifyResult(); } finally { fs.exists(new Path(OUTPUT)); } }
SpMV { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { HamaConfiguration conf = new HamaConfiguration(); parseArgs(conf, args); startTask(conf); } static String getResultPath(); static void setResultPath(String resultPath); static String convertSpMVOutputToDenseVector( String SpMVoutputPathString, HamaConfiguration conf); static void readFromFile(String pathString, Writable result, HamaConfiguration conf); static void writeToFile(String pathString, Writable result, HamaConfiguration conf); static void main(String[] args); }
@Test public void runFromDriver() { try { String matrixPath = ""; String vectorPath = ""; String outputPath = ""; if (matrixPath.isEmpty() || vectorPath.isEmpty() || outputPath.isEmpty()) { LOG.info("Please setup input path for vector and matrix and output path for result."); return; } ExampleDriver.main(new String[] { "spmv", matrixPath, vectorPath, outputPath, "4" }); } catch (Exception e) { e.printStackTrace(); fail(e.getLocalizedMessage()); } }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector pow(int x) { final int p = x; return this.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return Math.pow(value, p); } @Override public double applyDerivative(double value) { throw new UnsupportedOperationException(); } }); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testPow() { DoubleVector spVec1 = new SparseDoubleVector(10, 1.5); DoubleVector spVec2 = new SparseDoubleVector(10, 1); DoubleVector spVec3 = new SparseDoubleVector(10, 2.25); assertEquals(spVec3, spVec1.pow(2)); assertEquals(spVec2, spVec1.pow(0)); }
PiEstimator { public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException { HamaConfiguration conf = new HamaConfiguration(); BSPJob bsp = new BSPJob(conf, PiEstimator.class); bsp.setJobName("Pi Estimation Example"); bsp.setBspClass(MyEstimator.class); bsp.setInputFormat(NullInputFormat.class); bsp.setOutputKeyClass(Text.class); bsp.setOutputValueClass(DoubleWritable.class); bsp.setOutputFormat(TextOutputFormat.class); FileOutputFormat.setOutputPath(bsp, TMP_OUTPUT); BSPJobClient jobClient = new BSPJobClient(conf); ClusterStatus cluster = jobClient.getClusterStatus(true); if (args.length > 0) { bsp.setNumBspTask(Integer.parseInt(args[0])); } else { bsp.setNumBspTask(cluster.getMaxTasks()); } long startTime = System.currentTimeMillis(); if (bsp.waitForCompletion(true)) { printOutput(conf); System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }
@Test public void testCorrectPiExecution() { try { PiEstimator.main(new String[] { "10" }); } catch (Exception e) { fail(e.getLocalizedMessage()); } } @Test public void testPiExecutionWithEmptyArgs() { try { PiEstimator.main(new String[10]); fail("PiEstimator should fail if the argument list has size 0"); } catch (Exception e) { } }
PageRank { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, ParseException { Options opts = new Options(); opts.addOption("i", "input_path", true, "The Location of output path."); opts.addOption("o", "output_path", true, "The Location of input path."); opts.addOption("h", "help", false, "Print usage"); opts.addOption("t", "task_num", true, "The number of tasks."); opts.addOption("f", "file_type", true, "The file type of input data. Input" + "file format which is \"text\" tab delimiter separated or \"json\"." + "Default value - Text"); if (args.length < 2) { new HelpFormatter().printHelp("pagerank -i INPUT_PATH -o OUTPUT_PATH " + "[-t NUM_TASKS] [-f FILE_TYPE]", opts); System.exit(-1); } HamaConfiguration conf = new HamaConfiguration(); GraphJob pageJob = createJob(args, conf, opts); long startTime = System.currentTimeMillis(); if (pageJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static GraphJob createJob(String[] args, HamaConfiguration conf, Options opts); static void main(String[] args); }
@Test public void testPageRank() throws IOException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException { generateTestData(); try { PageRank.main(new String[] { "-input_path", INPUT, "-output_path", OUTPUT, "-task_num", "5", "-f", "json" }); verifyResult(); } catch (ParseException e) { e.printStackTrace(); } finally { deleteTempDirs(); } }
RandBench { public static void main(String[] args) throws Exception { if (args.length < 3) { System.out.println("Usage: <sizeOfMsg> <nCommunications> <nSupersteps>"); System.exit(-1); } HamaConfiguration conf = new HamaConfiguration(); conf.setInt(SIZEOFMSG, Integer.parseInt(args[0])); conf.setInt(N_COMMUNICATIONS, Integer.parseInt(args[1])); conf.setInt(N_SUPERSTEPS, Integer.parseInt(args[2])); BSPJob bsp = new BSPJob(conf, RandBench.class); bsp.setJobName("Random Communication Benchmark"); bsp.setBspClass(RandBSP.class); bsp.setInputFormat(NullInputFormat.class); bsp.setOutputFormat(NullOutputFormat.class); BSPJobClient jobClient = new BSPJobClient(conf); ClusterStatus cluster = jobClient.getClusterStatus(false); bsp.setNumBspTask(cluster.getMaxTasks()); long startTime = System.currentTimeMillis(); if (bsp.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }
@Test public void testCorrectRandBenchExecution() { try { RandBench.main(new String[] { "10", "3", "2" }); } catch (Exception e) { fail(e.getLocalizedMessage()); } } @Test public void testRandBenchExecutionWithEmptyArgs() { try { RandBench.main(new String[10]); fail("RandBench should fail if the argument list has size < 3"); } catch (Exception e) { } }
CombineExample { public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException { HamaConfiguration conf = new HamaConfiguration(); BSPJob bsp = new BSPJob(conf, CombineExample.class); bsp.setJobName("Combine Example"); bsp.setBspClass(MyBSP.class); bsp.setCombinerClass(SumCombiner.class); bsp.setInputFormat(NullInputFormat.class); bsp.setOutputKeyClass(Text.class); bsp.setOutputValueClass(IntWritable.class); bsp.setOutputFormat(TextOutputFormat.class); FileOutputFormat.setOutputPath(bsp, TMP_OUTPUT); bsp.setNumBspTask(2); long startTime = System.currentTimeMillis(); if (bsp.waitForCompletion(true)) { printOutput(conf); System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }
@Test public void testCorrectCombineExecution() { try { CombineExample.main(new String[] {}); } catch (Exception e) { fail(e.getLocalizedMessage()); } }
SyncServiceFactory { public static PeerSyncClient getPeerSyncClient(Configuration conf) throws ClassNotFoundException { return (PeerSyncClient) ReflectionUtils.newInstance(conf .getClassByName(conf.get(SYNC_CLIENT_CLASS, ZooKeeperSyncClientImpl.class.getName())), conf); } static PeerSyncClient getPeerSyncClient(Configuration conf); static SyncClient getMasterSyncClient(Configuration conf); static SyncServer getSyncServer(Configuration conf); static SyncServerRunner getSyncServerRunner(Configuration conf); static final String SYNC_SERVER_CLASS; static final String SYNC_CLIENT_CLASS; static final String SYNC_MASTER_CLASS; }
@Test public void testClientInstantiation() throws Exception { Configuration conf = new Configuration(); PeerSyncClient syncClient = SyncServiceFactory.getPeerSyncClient(conf); assertTrue(syncClient instanceof ZooKeeperSyncClientImpl); }
SyncServiceFactory { public static SyncServer getSyncServer(Configuration conf) throws ClassNotFoundException { return (SyncServer) ReflectionUtils.newInstance(conf.getClassByName(conf .get(SYNC_SERVER_CLASS, org.apache.hama.bsp.sync.ZooKeeperSyncServerImpl.class .getCanonicalName())), conf); } static PeerSyncClient getPeerSyncClient(Configuration conf); static SyncClient getMasterSyncClient(Configuration conf); static SyncServer getSyncServer(Configuration conf); static SyncServerRunner getSyncServerRunner(Configuration conf); static final String SYNC_SERVER_CLASS; static final String SYNC_CLIENT_CLASS; static final String SYNC_MASTER_CLASS; }
@Test public void testServerInstantiation() throws Exception { Configuration conf = new Configuration(); SyncServer syncServer = SyncServiceFactory.getSyncServer(conf); assertTrue(syncServer instanceof ZooKeeperSyncServerImpl); }
VectorDoubleFileInputFormat extends FileInputFormat<VectorWritable, DoubleWritable> { @Override public RecordReader<VectorWritable, DoubleWritable> getRecordReader( InputSplit split, BSPJob job) throws IOException { return new VectorDoubleRecorderReader(job.getConfiguration(), (FileSplit) split); } @Override RecordReader<VectorWritable, DoubleWritable> getRecordReader( InputSplit split, BSPJob job); }
@Test public void testFileRead() throws Exception { VectorDoubleFileInputFormat inputFormat = new VectorDoubleFileInputFormat(); Path file = new Path("src/test/resources/vd_file_sample.txt"); InputSplit split = new FileSplit(file, 0, 1000, new String[]{"localhost"}); BSPJob job = new BSPJob(); RecordReader<VectorWritable, DoubleWritable> recordReader = inputFormat.getRecordReader(split, job); assertNotNull(recordReader); VectorWritable key = recordReader.createKey(); assertNotNull(key); DoubleWritable value = recordReader.createValue(); assertNotNull(value); assertTrue(recordReader.next(key, value)); assertEquals(new DenseDoubleVector(new double[]{2d, 3d, 4d}), key.getVector()); assertEquals(new DoubleWritable(1d), value); }
LinearRegressionModel implements RegressionModel { @Override public BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta) { return costFunction.calculateCostForItem(x, y, m, theta, this); } LinearRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }
@Test public void testCorrectCostCalculation() throws Exception { LinearRegressionModel linearRegressionModel = new LinearRegressionModel(); DoubleVector x = new DenseDoubleVector(new double[]{2, 3, 4}); double y = 1; DoubleVector theta = new DenseDoubleVector(new double[]{1, 1, 1}); BigDecimal cost = linearRegressionModel.calculateCostForItem(x, y, 2, theta); assertEquals("wrong cost calculation for linear regression", BigDecimal.valueOf(16d), cost); }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector abs() { return this.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return Math.abs(value); } @Override public double applyDerivative(double value) { throw new UnsupportedOperationException(); } }); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testAbs() { DoubleVector spVec1 = new SparseDoubleVector(10, 1.5); DoubleVector spVec2 = new SparseDoubleVector(10, 0); DoubleVector spVec3 = new SparseDoubleVector(10, -1.5); assertEquals(spVec1, spVec3.abs()); assertEquals(spVec2, spVec2.abs()); }
LinearRegressionModel implements RegressionModel { @Override public BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x) { return BigDecimal.valueOf(theta.dotUnsafe(x)); } LinearRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }
@Test public void testCorrectHypothesisCalculation() throws Exception { LinearRegressionModel linearRegressionModel = new LinearRegressionModel(); BigDecimal hypothesisValue = linearRegressionModel.applyHypothesis(new DenseDoubleVector(new double[]{1, 1, 1}), new DenseDoubleVector(new double[]{2, 3, 4})); assertEquals("wrong hypothesis value for linear regression", BigDecimal.valueOf(9d), hypothesisValue); }
LogisticRegressionModel implements RegressionModel { @Override public BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta) { return costFunction.calculateCostForItem(x, y, m, theta, this); } LogisticRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }
@Test public void testCorrectCostCalculation() throws Exception { LogisticRegressionModel logisticRegressionModel = new LogisticRegressionModel(); DoubleVector x = new DenseDoubleVector(new double[]{2, 3, 4}); double y = 1; DoubleVector theta = new DenseDoubleVector(new double[]{1, 1, 1}); BigDecimal cost = logisticRegressionModel.calculateCostForItem(x, y, 2, theta); assertEquals("wrong cost calculation for logistic regression", 6.170109486162941E-5d, cost.doubleValue(), 0.000001); }
LogisticRegressionModel implements RegressionModel { @Override public BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x) { return applyHypothesisWithPrecision(theta, x); } LogisticRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }
@Test public void testCorrectHypothesisCalculation() throws Exception { LogisticRegressionModel logisticRegressionModel = new LogisticRegressionModel(); BigDecimal hypothesisValue = logisticRegressionModel.applyHypothesis(new DenseDoubleVector(new double[]{1, 1, 1}), new DenseDoubleVector(new double[]{2, 3, 4})); assertEquals("wrong hypothesis value for logistic regression", 0.9998766054240137682597533152954043d, hypothesisValue.doubleValue(), 0.000001); }
SparseDoubleVector implements DoubleVector { @Override public DoubleVector sqrt() { return this.applyToElements(new DoubleFunction() { @Override public double apply(double value) { return Math.sqrt(value); } @Override public double applyDerivative(double value) { throw new UnsupportedOperationException(); } }); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testSqrt() { DoubleVector spVec1 = new SparseDoubleVector(10, 2.25); DoubleVector spVec2 = new SparseDoubleVector(10, 0); DoubleVector spVec3 = new SparseDoubleVector(10, 1.5); DoubleVector spVec4 = new SparseDoubleVector(10, 1); assertEquals(spVec3, spVec1.sqrt()); assertEquals(spVec2, spVec2.sqrt()); assertEquals(spVec4, spVec4.sqrt()); }
SparseDoubleVector implements DoubleVector { @Override public double sum() { double sum = 0.0; Iterator<DoubleVectorElement> itr = this.iterate(); while (itr.hasNext()) { sum += itr.next().getValue(); } return sum; } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testSum() { DoubleVector spVec1 = new SparseDoubleVector(10, 2.25); DoubleVector spVec2 = new SparseDoubleVector(10, 0); DoubleVector spVec3 = new SparseDoubleVector(10, 1.5); assertEquals(22.5, spVec1.sum(), 0.00001); assertEquals(0, spVec2.sum(), 0.000001); assertEquals(15, spVec3.sum(), 0.000001); }
SparseDoubleVector implements DoubleVector { @Override public double dot(DoubleVector vector) { Preconditions.checkArgument(this.dimension == vector.getDimension(), "Dimensions of two vectors are not equal."); return this.dotUnsafe(vector); } SparseDoubleVector(int dimension); SparseDoubleVector(int dimension, double defaultValue); @Override double get(int index); @Override int getLength(); @Override int getDimension(); @Override void set(int index, double value); @Override DoubleVector applyToElements(DoubleFunction func); @Override DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func); @Override DoubleVector addUnsafe(DoubleVector vector); @Override DoubleVector add(DoubleVector vector); @Override DoubleVector add(double scalar); @Override DoubleVector subtractUnsafe(DoubleVector vector); @Override DoubleVector subtract(DoubleVector vector); @Override DoubleVector subtract(double scalar); @Override DoubleVector subtractFrom(double scalar); @Override DoubleVector multiply(double scalar); @Override DoubleVector multiplyUnsafe(DoubleVector vector); @Override DoubleVector multiply(DoubleVector vector); @Override DoubleVector multiply(DoubleMatrix matrix); @Override DoubleVector multiplyUnsafe(DoubleMatrix matrix); @Override DoubleVector divide(double scalar); @Override DoubleVector divideFrom(double scalar); @Override DoubleVector pow(int x); @Override DoubleVector abs(); @Override DoubleVector sqrt(); @Override double sum(); @Override double dotUnsafe(DoubleVector vector); @Override double dot(DoubleVector vector); @Override DoubleVector slice(int length); @Override DoubleVector sliceUnsafe(int length); @Override DoubleVector slice(int start, int end); @Override DoubleVector sliceUnsafe(int start, int end); @Override double max(); @Override double min(); @Override double[] toArray(); @Override DoubleVector deepCopy(); @Override Iterator<DoubleVectorElement> iterateNonDefault(); @Override Iterator<DoubleVectorElement> iterate(); @Override boolean isSparse(); @Override boolean isNamed(); @Override String getName(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }
@Test public void testDot() { DoubleVector spVec1 = new SparseDoubleVector(10, 2.25); DoubleVector spVec2 = new SparseDoubleVector(10, 0); DoubleVector spVec3 = new SparseDoubleVector(10, 1.5); DoubleVector spVec4 = new SparseDoubleVector(10, 1); assertEquals(spVec1.multiply(spVec3).sum(), spVec1.dot(spVec3), 0.000001); assertEquals(spVec3.sum(), spVec3.dot(spVec4), 0.000001); assertEquals(0, spVec1.dot(spVec2), 0.000001); }
GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback) { this.discardCallback = discardCallback; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback); @Override List<BlobInfo> filterFiles(BlobInfo[] blobInfos); @Override boolean accept(BlobInfo file); @Override boolean supportsSingleFileFiltering(); }
@Test void addDiscardCallback() { GcsAcceptModifiedAfterFileListFilter filter = new GcsAcceptModifiedAfterFileListFilter(); AtomicBoolean callbackTriggered = new AtomicBoolean(false); filter.addDiscardCallback(blobInfo -> callbackTriggered.set(true)); BlobInfo blobInfo = mock(BlobInfo.class); when(blobInfo.getUpdateTime()).thenReturn(1L); filter.accept(blobInfo); assertThat(callbackTriggered.get()) .isTrue(); }
AfterExecuteDmlEvent extends ExecuteDmlEvent { @Override public int hashCode() { return Objects.hash(getStatement().hashCode(), getNumberOfRowsAffected()); } AfterExecuteDmlEvent(Statement statement, long numberOfRowsAffected); long getNumberOfRowsAffected(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void equalsHashcodeTest() { AfterExecuteDmlEvent afterExecuteDmlEventa1 = new AfterExecuteDmlEvent(Statement.of("a"), 1L); AfterExecuteDmlEvent afterExecuteDmlEventa1x = new AfterExecuteDmlEvent(Statement.of("a"), 1L); AfterExecuteDmlEvent afterExecuteDmlEventa2 = new AfterExecuteDmlEvent(Statement.of("a"), 2L); AfterExecuteDmlEvent afterExecuteDmlEventb1 = new AfterExecuteDmlEvent(Statement.of("b"), 1L); AfterExecuteDmlEvent afterExecuteDmlEventb2 = new AfterExecuteDmlEvent(Statement.of("b"), 2L); assertThat(afterExecuteDmlEventa1).isEqualTo(afterExecuteDmlEventa1); assertThat(afterExecuteDmlEventa1).isEqualTo(afterExecuteDmlEventa1x); assertThat(afterExecuteDmlEventa1).isNotEqualTo(afterExecuteDmlEventa2); assertThat(afterExecuteDmlEventb1).isNotEqualTo(afterExecuteDmlEventb2); assertThat(afterExecuteDmlEventa1).isNotEqualTo(afterExecuteDmlEventb2); assertThat(afterExecuteDmlEventa1).isNotEqualTo(null); assertThat(afterExecuteDmlEventa1).isNotEqualTo(new Object()); assertThat(afterExecuteDmlEventa1.hashCode()).isEqualTo(afterExecuteDmlEventa1.hashCode()); assertThat(afterExecuteDmlEventa1.hashCode()).isEqualTo(afterExecuteDmlEventa1x.hashCode()); assertThat(afterExecuteDmlEventa1.hashCode()).isNotEqualTo(afterExecuteDmlEventa2.hashCode()); assertThat(afterExecuteDmlEventb1.hashCode()).isNotEqualTo(afterExecuteDmlEventb2.hashCode()); assertThat(afterExecuteDmlEventa1.hashCode()).isNotEqualTo(afterExecuteDmlEventb2.hashCode()); }
GoogleConfigPropertySourceLocator implements PropertySourceLocator { public String getProjectId() { return this.projectId; } GoogleConfigPropertySourceLocator(GcpProjectIdProvider projectIdProvider, CredentialsProvider credentialsProvider, GcpConfigProperties gcpConfigProperties); @Override PropertySource<?> locate(Environment environment); String getProjectId(); }
@Test public void testProjectIdInConfigProperties() throws IOException { when(this.gcpConfigProperties.getProjectId()).thenReturn("pariah"); this.googleConfigPropertySourceLocator = new GoogleConfigPropertySourceLocator( this.projectIdProvider, this.credentialsProvider, this.gcpConfigProperties ); assertThat(this.googleConfigPropertySourceLocator.getProjectId()).isEqualTo("pariah"); }
GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public List<BlobInfo> filterFiles(BlobInfo[] blobInfos) { List<BlobInfo> list = new ArrayList<>(); for (BlobInfo file : blobInfos) { if (accept(file)) { list.add(file); } } return list; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback); @Override List<BlobInfo> filterFiles(BlobInfo[] blobInfos); @Override boolean accept(BlobInfo file); @Override boolean supportsSingleFileFiltering(); }
@Test void filterFiles() { Instant now = Instant.now(); BlobInfo oldBlob = mock(BlobInfo.class); when(oldBlob.getUpdateTime()).thenReturn(now.toEpochMilli() - 1); BlobInfo currentBlob = mock(BlobInfo.class); when(currentBlob.getUpdateTime()).thenReturn(now.toEpochMilli()); BlobInfo newBlob = mock(BlobInfo.class); when(newBlob.getUpdateTime()).thenReturn(now.toEpochMilli() + 1); ArrayList<BlobInfo> expected = new ArrayList<>(); expected.add(currentBlob); expected.add(newBlob); assertThat( new GcsAcceptModifiedAfterFileListFilter(now).filterFiles(new BlobInfo[] { oldBlob, currentBlob, newBlob })) .isEqualTo(expected); }
GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public boolean supportsSingleFileFiltering() { return true; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback); @Override List<BlobInfo> filterFiles(BlobInfo[] blobInfos); @Override boolean accept(BlobInfo file); @Override boolean supportsSingleFileFiltering(); }
@Test void supportsSingleFileFiltering() { assertThat(new GcsAcceptModifiedAfterFileListFilter().supportsSingleFileFiltering()) .isTrue(); }
GcsPersistentAcceptOnceFileListFilter extends AbstractPersistentAcceptOnceFileListFilter<BlobInfo> { @Override protected long modified(BlobInfo blobInfo) { return (blobInfo != null && blobInfo.getUpdateTime() != null) ? blobInfo.getUpdateTime() : -1; } GcsPersistentAcceptOnceFileListFilter(ConcurrentMetadataStore store, String prefix); }
@Test public void modified_blobInfoIsNull_shouldReturnMinusOne() { assertThat(new GcsPersistentAcceptOnceFileListFilter(mock(ConcurrentMetadataStore.class), "").modified(null)) .isEqualTo(-1); } @Test public void modified_updateTimeIsNull_shouldReturnMinusOne() { BlobInfo blobInfo = mock(BlobInfo.class); when(blobInfo.getUpdateTime()).thenReturn(null); assertThat( new GcsPersistentAcceptOnceFileListFilter(mock(ConcurrentMetadataStore.class), "").modified(blobInfo)) .isEqualTo(-1); }
SliceUtil { public static <T> void sliceAndExecute(T[] elements, int sliceSize, Consumer<T[]> consumer) { int num_slices = (int) (Math.ceil((double) elements.length / sliceSize)); for (int i = 0; i < num_slices; i++) { int start = i * sliceSize; int end = Math.min(start + sliceSize, elements.length); T[] slice = Arrays.copyOfRange(elements, start, end); consumer.accept(slice); } } private SliceUtil(); static void sliceAndExecute(T[] elements, int sliceSize, Consumer<T[]> consumer); }
@Test public void sliceAndExecuteTest() { Integer[] elements = getIntegers(7); List<Integer[]> slices = new ArrayList<>(); sliceAndExecute(elements, 3, slice -> { slices.add(slice); }); assertThat(slices).containsExactly(new Integer[] { 0, 1, 2 }, new Integer[] { 3, 4, 5 }, new Integer[] { 6 }); } @Test public void sliceAndExecuteEvenTest() { Integer[] elements = getIntegers(6); List<Integer[]> slices = new ArrayList<>(); sliceAndExecute(elements, 3, slice -> { slices.add(slice); }); assertThat(slices).containsExactly(new Integer[] { 0, 1, 2 }, new Integer[] { 3, 4, 5 }); } @Test public void sliceAndExecuteEmptyTest() { Integer[] elements = getIntegers(0); List<Integer[]> slices = new ArrayList<>(); sliceAndExecute(elements, 3, slice -> { slices.add(slice); }); assertThat(slices).isEmpty(); }
KeyUtil { public static Key getKeyWithoutAncestors(Key entityKey) { Key.Builder ancestorLookupKey; if (entityKey.hasName()) { ancestorLookupKey = Key.newBuilder(entityKey.getProjectId(), entityKey.getKind(), entityKey.getName()); } else { ancestorLookupKey = Key.newBuilder(entityKey.getProjectId(), entityKey.getKind(), entityKey.getId()); } ancestorLookupKey.setNamespace(entityKey.getNamespace()); return ancestorLookupKey.build(); } private KeyUtil(); static Key getKeyWithoutAncestors(Key entityKey); }
@Test public void testRemoveAncestors_NamedKeys() { Key namedKey = Key.newBuilder("project", "person", "Smith") .addAncestor(PathElement.of("person", "GrandParent")) .addAncestor(PathElement.of("person", "Parent")) .build(); Key processedKey = KeyUtil.getKeyWithoutAncestors(namedKey); assertThat(processedKey.getAncestors()).isEmpty(); } @Test public void testRemoveAncestors_IdKeys() { Key idKey = Key.newBuilder("project", "person", 46L) .addAncestor(PathElement.of("person", 22L)) .addAncestor(PathElement.of("person", 18L)) .build(); Key processedKey = KeyUtil.getKeyWithoutAncestors(idKey); assertThat(processedKey.getAncestors()).isEmpty(); }
HttpHeadersInjectAdapter implements TextMap { @Override public void put(String key, String value) { Collection<String> values = headers.get(key); if (values == null) { values = new ArrayList<>(1); headers.put(key, values); } try { values.add(value); } catch (UnsupportedOperationException ex) { if (values instanceof List) { List<String> list = new ArrayList<>(values); list.add(value); headers.put(key, list); } else if (values instanceof Set) { Set<String> set = new HashSet<>(values); set.add(value); headers.put(key, set); } else { throw ex; } } } HttpHeadersInjectAdapter(Map<String, Collection<String>> headers); @Override void put(String key, String value); @Override Iterator<Map.Entry<String, String>> iterator(); }
@Test public void putNewTraceHeaderValueInsideList() { Map<String, Collection<String>> headers = new HashMap<>(); headers.put("x-header", Arrays.asList("123:123:123:1")); HttpHeadersInjectAdapter adapter = new HttpHeadersInjectAdapter(headers); adapter.put("x-header", "123:456:456:1"); assertEquals(headers.get("x-header"), Arrays.asList("123:123:123:1", "123:456:456:1")); } @Test public void putNewTraceHeaderValueInsideUnmodifiableList() { Map<String, Collection<String>> headers = new HashMap<>(); headers.put("x-header", Collections.unmodifiableList(Arrays.asList("123:123:123:1"))); HttpHeadersInjectAdapter adapter = new HttpHeadersInjectAdapter(headers); adapter.put("x-header", "123:456:456:1"); assertEquals(headers.get("x-header"), Arrays.asList("123:123:123:1", "123:456:456:1")); } @Test public void putNewTraceHeaderValueInsideUnmodifiableSet() { Map<String, Collection<String>> headers = new HashMap<>(); headers.put("x-header", Collections.unmodifiableSet(new HashSet<>(Arrays.asList("123:123:123:1")))); HttpHeadersInjectAdapter adapter = new HttpHeadersInjectAdapter(headers); adapter.put("x-header", "123:456:456:1"); assertEquals(headers.get("x-header"), new HashSet<>(Arrays.asList("123:123:123:1", "123:456:456:1"))); }
EnvironmentHelper { public static boolean isPresent(String variable) { return getIfPresent(variable) != null; } private EnvironmentHelper(); static boolean isPresent(String variable); static String get(String variable); static String getOrDefault(String variable, String defaultValue); }
@Test void testIsPresentOnRandomString() { String random = UUID.randomUUID().toString(); assertWithMessage("Should not have an environment variable with randomized key") .that(EnvironmentHelper.isPresent(random)).isFalse(); } @Test void testIsPresentOnAdded() { String someKey = UUID.randomUUID().toString(); String value = "nothing important"; System.setProperty(someKey, value); assertWithMessage("%s should be set to %s", someKey, value) .that(EnvironmentHelper.isPresent(someKey)).isTrue(); } @Test void testIsPresentButEmpty() { String someKey = UUID.randomUUID().toString(); String value = ""; System.setProperty(someKey, value); assertWithMessage("%s should be set to %s", someKey, value) .that(EnvironmentHelper.isPresent(someKey)).isFalse(); } @Test void testLogEntryForIsPresentFailureIsEmpty() { String someKey = UUID.randomUUID().toString(); String value = ""; System.setProperty(someKey, value); String message = String.format(EnvironmentHelper.NOT_FOUND, someKey); EnvironmentHelper.isPresent(someKey); assertThat(getLogs()).doesNotContain(message); }
MetadataHelper { public static Metadata generateMetadata(Node node, Outcome outcome) { Objects.requireNonNull(outcome, "outcome"); Metadata metadata = Metadata.create(); if (node != null) { metadata.setApm(findApm(node)); metadata.setTin(findTin(node)); metadata.setNpi(findNpi(node)); metadata.setProgramName(findProgramName(node)); metadata.setCpc(deriveCpcHash(node)); metadata.setCpcProcessed(false); metadata.setRtiProcessed(false); } outcome.setStatus(metadata); return metadata; } private MetadataHelper(); static Metadata generateMetadata(Node node, Outcome outcome); }
@Test void testExtractsCpcProgramTypeFromChild() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); child.putValue(ClinicalDocumentDecoder.RAW_PROGRAM_NAME, "CPCPLUS"); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getCpc()).startsWith(Constants.CPC_DYNAMO_PARTITION_START); } @Test void testChildLacksCpcPlus() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getCpc()).isNull(); } @Test void testExtractsApm() { Node node = new Node(); node.putValue(ClinicalDocumentDecoder.PRACTICE_ID, MOCK_STRING); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getApm()).isEqualTo(MOCK_STRING); } @Test void testExtractsApmFromChild() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); child.putValue(ClinicalDocumentDecoder.PRACTICE_ID, MOCK_STRING); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getApm()).isEqualTo(MOCK_STRING); } @Test void testChildLacksApm() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getApm()).isNull(); } @Test void testExtractsTin() { Node node = new Node(); node.putValue(ClinicalDocumentDecoder.TAX_PAYER_IDENTIFICATION_NUMBER, MOCK_STRING); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getTin()).isEqualTo(MOCK_STRING); } @Test void testExtractsTinFromChild() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); child.putValue(ClinicalDocumentDecoder.TAX_PAYER_IDENTIFICATION_NUMBER, MOCK_STRING); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getTin()).isEqualTo(MOCK_STRING); } @Test void testChildLacksTin() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getTin()).isNull(); } @Test void testExtractsNpi() { Node node = new Node(); node.putValue(ClinicalDocumentDecoder.NATIONAL_PROVIDER_IDENTIFIER, MOCK_STRING); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getNpi()).isEqualTo(MOCK_STRING); } @Test void testExtractsNpiFromChild() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); child.putValue(ClinicalDocumentDecoder.NATIONAL_PROVIDER_IDENTIFIER, MOCK_STRING); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getNpi()).isEqualTo(MOCK_STRING); } @Test void testChildLacksNpi() { Node node = new Node(); Node child = new Node(); child.setType(TemplateId.CLINICAL_DOCUMENT); node.addChildNode(child); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getNpi()).isNull(); } @Test void testSuccessOutcome() { Metadata metadata = MetadataHelper.generateMetadata(new Node(), MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getOverallStatus()).isTrue(); assertThat(metadata.getConversionStatus()).isTrue(); assertThat(metadata.getValidationStatus()).isTrue(); } @Test void testConversionFailureOutcome() { Metadata metadata = MetadataHelper.generateMetadata(new Node(), MetadataHelper.Outcome.CONVERSION_ERROR); assertThat(metadata.getOverallStatus()).isFalse(); assertThat(metadata.getConversionStatus()).isFalse(); assertThat(metadata.getValidationStatus()).isFalse(); } @Test void testValidationFailureOutcome() { Metadata metadata = MetadataHelper.generateMetadata(new Node(), MetadataHelper.Outcome.VALIDATION_ERROR); assertThat(metadata.getOverallStatus()).isFalse(); assertThat(metadata.getConversionStatus()).isTrue(); assertThat(metadata.getValidationStatus()).isFalse(); } @Test void testGenerateMetadataForNullNodeReturnsSkinnyMetadata() { MetadataHelper.Outcome outcome = MetadataHelper.Outcome.VALIDATION_ERROR; Metadata comparison = Metadata.create(); comparison.setOverallStatus(false); comparison.setConversionStatus(true); comparison.setValidationStatus(false); Metadata metadata = MetadataHelper.generateMetadata(null, outcome); metadata.setCreatedDate(comparison.getCreatedDate()); assertThat(metadata).isEqualTo(comparison); } @Test void testGenerateMetadataForNullOutcomeThrowsNullPointerException() { Assertions.assertThrows(NullPointerException.class, () -> MetadataHelper.generateMetadata(new Node(), null)); } @Test void testExtractsCpcProgramType() { Node node = new Node(); node.putValue(ClinicalDocumentDecoder.RAW_PROGRAM_NAME, "CPCPLUS"); Metadata metadata = MetadataHelper.generateMetadata(node, MetadataHelper.Outcome.SUCCESS); assertThat(metadata.getCpc()).startsWith(Constants.CPC_DYNAMO_PARTITION_START); }
MeasuredInputStreamSupplier implements Supplier<InputStream> { public int size() { return size; } private MeasuredInputStreamSupplier(InputStream source); static MeasuredInputStreamSupplier terminallyTransformInputStream(InputStream source); @Override InputStream get(); int size(); }
@Test void testSize() { InputStream use = stream("mock"); Truth.assertThat(MeasuredInputStreamSupplier.terminallyTransformInputStream(use).size()).isEqualTo("mock".length()); }
RestApiApplication { public static void main(String... args) { SpringApplication.run(RestApiApplication.class, args); } static void main(String... args); }
@Test void testMain() { RestApiApplication.main(); }
CommandLineRunner implements Runnable { protected Pattern getNormalPathPattern() { if (normalPathPattern == null) { String separator = "\\" + this.fileSystem.getSeparator(); normalPathPattern = Pattern.compile("[a-zA-Z0-9_\\-\\s,." + separator + "]+"); } return normalPathPattern; } CommandLineRunner(CommandLine commandLine); CommandLineRunner(CommandLine commandLine, FileSystem fileSystem); @Override void run(); static boolean isValid(Path path); }
@Test void testWindowsFileSeparator() { FileSystem mockWindowsFileSystem = mock(FileSystem.class); when(mockWindowsFileSystem.getSeparator()).thenReturn("\\"); CommandLineRunner runner = new CommandLineRunner(line(WINDOWS_FILE), mockWindowsFileSystem); Truth.assertThat(runner.getNormalPathPattern().pattern()).contains("\\\\"); } @Test void testNixFileSeparator() { FileSystem mockWindowsFileSystem = mock(FileSystem.class); when(mockWindowsFileSystem.getSeparator()).thenReturn("/"); CommandLineRunner runner = new CommandLineRunner(line(VALID_FILE), mockWindowsFileSystem); Truth.assertThat(runner.getNormalPathPattern().pattern()).contains("\\/"); }