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(sequ...
@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()) {...
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.getM...
@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...
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 p...
@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.a...
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> getMa...
@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",...
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 priv...
@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.ad...
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.n...
@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 Lo...
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[]...
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() <...
@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...
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> ...
@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",...
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) ...
@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 L2Predic...
CofactorRemover extends BiointerpretationProcessor { public void init() throws IOException { cofactorsCorpus = new CofactorsCorpus(); cofactorsCorpus.loadCorpus(); blacklistedInchisCorpus = new BlacklistedInchisCorpus(); blacklistedInchisCorpus.loadCorpus(); markInitialized(); } CofactorRemover(NoSQLAPI api); @Override...
@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(...
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> getMatc...
@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.i...
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 ...
@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>> ...
@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).con...
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.getTotalCharg...
@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<Stri...
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_FORMU...
@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...
@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_T...
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...
@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....
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...
@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); LcmsChem...
@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 nam...
@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<In...
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(); Lis...
@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<Strin...
@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")); MassCharge...
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...
@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.0633...
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...
@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(); ...
@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 vo...
@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 zi...
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 le...
@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...
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-dbconfi...
@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, "dat...
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...
@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.pi...
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(), "ME...
@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...
AbstractProductHandlerMojo extends AbstractProductHandlerAwareMojo { void makeProductsInheritDefaultConfiguration(List<Product> products, Map<String, Product> productMap) throws MojoExecutionException { Product defaultProduct = createDefaultProductContext(); productMap.put(getProductId(), defaultProduct); if (!products...
@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> ...
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(), fun...
@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.applyTo...
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...
@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.slic...
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); DenseDo...
@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.clas...
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); DenseDoubleVect...
@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() { d...
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(in...
@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 = IllegalArgumentExce...
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...
@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...
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 d...
@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[] {...
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...
@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 d...
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); DenseDouble...
@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...
@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); } retur...
@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);...
@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 ...
@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...
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[] ar...
@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); ...
@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...
@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, ...
@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 Unsuppo...
@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,...
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...
@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, ...
@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)...
@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); DenseDoubleVe...
@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); asse...
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); @Overri...
@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; } DenseDo...
@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<D...
@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>> s...
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; } D...
@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.mu...
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.multiplyE...
@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);...
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(in...
@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 =...
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; } @Ove...
@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; } DenseDo...
@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(m...
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 ro...
@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);...
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.aggrega...
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_VERTE...
@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...
@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.setMax...
@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(Custo...
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 (graph...
@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 convertSpMVOutputToDens...
@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[] {...
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 UnsupportedOperationExc...
@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(Null...
@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 (Exce...
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.addOpt...
@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 (ParseExcept...
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, Int...
@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 ...
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(SumCombi...
@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(Config...
@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 g...
@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 Recor...
@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<VectorWritab...
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); ...
@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 = linearRegressionM...
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(); } }); } SparseD...
@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 calculateCostForIt...
@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(...
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 ...
@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 = logisticReg...
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 calculateCostF...
@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})); asser...
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(); } }); } Spars...
@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())...
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 d...
@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 ...
@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)...
GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback) { this.discardCallback = discardCallback; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Overr...
@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.getUpdateTim...
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")...
GoogleConfigPropertySourceLocator implements PropertySourceLocator { public String getProjectId() { return this.projectId; } GoogleConfigPropertySourceLocator(GcpProjectIdProvider projectIdProvider, CredentialsProvider credentialsProvider, GcpConfigProperties gcpConfigProperties); @Override PropertySource<?> loca...
@Test public void testProjectIdInConfigProperties() throws IOException { when(this.gcpConfigProperties.getProjectId()).thenReturn("pariah"); this.googleConfigPropertySourceLocator = new GoogleConfigPropertySourceLocator( this.projectIdProvider, this.credentialsProvider, this.gcpConfigProperties ); assertThat(this.googl...
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; } GcsAcceptModifiedAfterFileListFilte...
@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(...
GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public boolean supportsSingleFileFiltering() { return true; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> di...
@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...
@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....
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...
@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 sli...
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(),...
@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.getAncesto...
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 Lis...
@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-heade...
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 valu...
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(findProgra...
@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...
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 command...
@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(...