repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
JSAT
JSAT-master/JSAT/test/jsat/distributions/FisherSendorTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.distributions; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class FisherSendorTest { double[] range = new double[] { -3., -2.75, -2.5, -2.25, -2., -1.75, -1.5, -1.25, -1., -0.75, -0.5, -0.25, 0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3. }; public FisherSendorTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of logPdf method, of class FisherSendor. */ @Test public void testLogPdf() { System.out.println("logPdf"); ContinuousDistribution instance = null; double[] parmTwo0 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,-1.0755311112886419,-1.6865522751055781,-2.0677264461003304,-2.3502536967514276,-2.5765028780652766,-2.765924303489656,-2.9291924032622623,-3.072846636225469,-3.2012052668045246,-3.3172796396247555,-3.4232587102214747,-3.5207865035324826}; double[] paramTwo1 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,-0.7312989949608601,-1.3197956283990615,-1.689940033450167,-1.9693449650880337,-2.1981124382434136,-2.394181321271322,-2.5671765210819997,-2.7228852876009073,-2.865072967010014,-2.9963360392653255,-3.1185468636467606,-3.233104431080702}; double[] paramTwo2 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,-0.8606581655809521,-1.3365909264810165,-1.69115240188437,-1.9693449650880337,-2.197546214702604,-2.390793562926733,-2.5583016221696315,-2.706089989518952,-2.838297232629496,-2.957887102223775,-3.067053290028565,-3.1674642734484513}; double[] paramTwo3 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,-0.42786617867213905,-0.62825725877403,-0.8879767442017231,-1.1447298858494002,-1.3865072171614459,-1.6114279857379477,-1.8202831852372927,-2.0145516198939206,-2.1957882250863383,-2.3654318837185913,-2.5247554082772825,-2.6748652831951816}; instance = new FisherSendor(0.5, 0.5); for(int i = 0; i < range.length; i++) assertEquals(parmTwo0[i], instance.logPdf(range[i]), 1e-10); instance = new FisherSendor(0.5, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo1[i], instance.logPdf(range[i]), 1e-10); instance = new FisherSendor(3, 0.5); for(int i = 0; i < range.length; i++) assertEquals(paramTwo2[i], instance.logPdf(range[i]), 1e-10); instance = new FisherSendor(3, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo3[i], instance.logPdf(range[i]), 1e-10); } /** * Test of pdf method, of class FisherSendor. */ @Test public void testPdf() { System.out.println("pdf"); ContinuousDistribution instance = null; double[] parmTwo0 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.34111653633834343,0.18515679448477712,0.12647299825855507,0.09534497043772663,0.0760394588478015,0.06291791721274038,0.05344017883680418,0.04628919862119428,0.040713104242116736,0.03625131437838356,0.03260600809421878,0.029576164260098146}; double[] paramTwo1 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.48128339914819057,0.26718990241438084,0.1845305893239915,0.13954823524954643,0.11101250368051968,0.09124735061736179,0.07675194728217233,0.06568496075058096,0.05697897339502477,0.049969820825925305,0.04422138145022476,0.039434885680130864}; double[] paramTwo2 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.4228836632329831,0.2627398430023239,0.18430700582252596,0.13954823524954643,0.11107537937259643,0.09155699880129668,0.07743614465606578,0.06679747560359521,0.058525236030376834,0.051928520997649746,0.04655814627519772,0.042110242695782625}; double[] paramTwo3 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.6518986469044031,0.5335207799449517,0.4114874554751566,0.3183098861837907,0.2499467916526712,0.19960238111582101,0.1619798741292785,0.13338019498623793,0.11127082047753811,0.09390873395589414,0.08007789678230687,0.068916111927724}; instance = new FisherSendor(0.5, 0.5); for(int i = 0; i < range.length; i++) assertEquals(parmTwo0[i], instance.pdf(range[i]), 1e-10); instance = new FisherSendor(0.5, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo1[i], instance.pdf(range[i]), 1e-10); instance = new FisherSendor(3, 0.5); for(int i = 0; i < range.length; i++) assertEquals(paramTwo2[i], instance.pdf(range[i]), 1e-10); instance = new FisherSendor(3, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo3[i], instance.pdf(range[i]), 1e-10); } /** * Test of cdf method, of class FisherSendor. */ @Test public void testCdf() { System.out.println("cdf"); ContinuousDistribution instance = null; double[] parmTwo0 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.3727156131603777,0.4345598848424255,0.4726180836933109,0.49999999999999967,0.5212535928736133,0.5385275931078592,0.5530131159980487,0.5654401151575745,0.5762881886500197,0.5858890925015626,0.594481626266527,0.6022432216826443}; double[] paramTwo1 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.5096165742200301,0.5978642569008251,0.6531118031726221,0.6931449079784125,0.7242266764500165,0.7493719694170181,0.770285305382158,0.7880316369300455,0.8033234720594439,0.8166619182600992,0.8284130726388325,0.8388525357634297}; double[] paramTwo2 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.12886711217619012,0.21196836306995448,0.26683409112435963,0.30685509202158756,0.3379412545043875,0.36312957646202815,0.38416534040879513,0.4021357430991749,0.41776015689702894,0.4315373428052034,0.443826221767879,0.45489304152075205}; double[] paramTwo3 = new double[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0.14237848993264704,0.2917914057909287,0.40936461121441453,0.49999999999999983,0.5705897131786168,0.6264699609476689,0.6714465399972,0.7082085942090712,0.7386753434255021,0.764238177345735,0.7859230176565496,0.8044988905221148}; instance = new FisherSendor(0.5, 0.5); for(int i = 0; i < range.length; i++) assertEquals(parmTwo0[i], instance.cdf(range[i]), 1e-10); instance = new FisherSendor(0.5, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo1[i], instance.cdf(range[i]), 1e-10); instance = new FisherSendor(3, 0.5); for(int i = 0; i < range.length; i++) assertEquals(paramTwo2[i], instance.cdf(range[i]), 1e-10); instance = new FisherSendor(3, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo3[i], instance.cdf(range[i]), 1e-10); } /** * Test of invCdf method, of class FisherSendor. */ @Test public void testInvCdf() { System.out.println("invCdf"); ContinuousDistribution instance = null; double[] parmTwo0 = new double[]{5.334203456719422e-8,0.00006913318696422088,0.0007812247277505513,0.003500715803229859,0.010417164444029625,0.024615063171980367,0.0502444629207317,0.09287319888065815,0.16014839504292144,0.2629821687138465,0.41764853333136576,0.6495302481781395,1.000000000000003,1.5395741811946149,2.394357743875021,3.802539179331621,6.244208689896571,10.767368972452411,19.90269060249784,40.62553051410859,95.9954127030347,285.65586474553135,1280.041407392871,/*last 2 removed for being too large, relative accuray is still good 14464.832939334676,1.874694148340569e7*/}; double[] paramTwo1 = new double[]{1.5805047937078598e-8,0.00002048343872385061,0.00023141418709826667,0.0010360499598851547,0.003075987604420405,0.007234721118664744,0.014646188270129645,0.026711949496745824,0.04513199564708614,0.07195612582172162,0.10966587338583667,0.16130199781329901,0.23066126571683299,0.3226018002981843,0.4435251089394354,0.6021587290154584,0.8108775237950727,1.088050726896899,1.4624918050988818,1.9826371274899546,2.7377289774408404,3.91504731419958,5.996708740298692,10.807066928600696,44.75298856639894}; double[] paramTwo2 = new double[]{0.02234487644364417,0.09253204468952805,0.16675814072473877,0.25542475473363396,0.3652662510570255,0.5043787318085855,0.6837645151333946,0.9190747961282854,1.2332318638205622,1.6606916944225336,2.2546637830521425,3.0997967124662353,4.335361626028854,6.199551236541197,9.11860699346005,13.897357432466515,22.15722982470372,37.436428970554886,68.27715044736316,138.22232862855972,325.0988393330919, /*same story, see param0 965.2044193999906,4321.256239909707,48819.92782127823,6.327092862316094e7 */}; double[] paramTwo3 = new double[]{0.029582973445028582,0.10646321922955648,0.17053427217757644,0.23282567658262066,0.29615129152974795,0.3620484899223977,0.4316934431570105,0.5061867593792821,0.5866920309095274,0.674534975988236,0.7713012301239432,0.8789549312280995,1.,1.1377147615552636,1.2965103139266438,1.4825028139347958,1.7044717625527248,1.9755554278548542,2.31645862556289,2.7620609609898974,3.376652503639516,4.295058924246869,5.863923932889599,9.39291529259317,33.80322812573971}; instance = new FisherSendor(0.5, 0.5); for(int i = 0; i < parmTwo0.length; i++) assertEquals(parmTwo0[i], instance.invCdf(range[i]/6.1+0.5), 1e-8); instance = new FisherSendor(0.5, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo1[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); instance = new FisherSendor(3, 0.5); for(int i = 0; i < paramTwo2.length; i++) assertEquals(paramTwo2[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); instance = new FisherSendor(3, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo3[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); } /** * Test of min method, of class FisherSendor. */ @Test public void testMin() { System.out.println("min"); ContinuousDistribution dist = new FisherSendor(0.5, 3); assertTrue(0 == dist.min()); } /** * Test of max method, of class FisherSendor. */ @Test public void testMax() { System.out.println("max"); ContinuousDistribution dist = new FisherSendor(0.5, 3); assertTrue(Double.POSITIVE_INFINITY == dist.max()); } /** * Test of mean method, of class FisherSendor. */ @Test public void testMean() { System.out.println("mean"); ContinuousDistribution dist = new FisherSendor(0.5, 0.5); assertEquals(Double.NaN, dist.mean(), 1e-10); dist = new FisherSendor(0.5, 3); assertEquals(3, dist.mean(), 1e-10); dist = new FisherSendor(3, 0.5); assertEquals(Double.NaN, dist.mean(), 1e-10); dist = new FisherSendor(3, 3); assertEquals(3, dist.mean(), 1e-10); } /** * Test of median method, of class FisherSendor. */ @Test public void testMedian() { System.out.println("median"); ContinuousDistribution dist = new FisherSendor(0.5, 0.5); assertEquals(1.000000000000003, dist.median(), 1e-10); dist = new FisherSendor(0.5, 3); assertEquals(0.23066126571683299, dist.median(), 1e-10); dist = new FisherSendor(3, 0.5); assertEquals(4.335361626028854, dist.median(), 1e-10); dist = new FisherSendor(3, 3); assertEquals(1, dist.median(), 1e-10); } /** * Test of mode method, of class FisherSendor. */ @Test public void testMode() { System.out.println("mode"); ContinuousDistribution dist = new FisherSendor(0.5, 0.5); assertEquals(Double.NaN, dist.mode(), 1e-10); dist = new FisherSendor(0.5, 3); assertEquals(Double.NaN, dist.mode(), 1e-10); dist = new FisherSendor(3, 0.5); assertEquals(2.0/3.0/10, dist.mode(), 1e-10); dist = new FisherSendor(3, 3); assertEquals(0.2, dist.mode(), 1e-10); } /** * Test of variance method, of class FisherSendor. */ @Test public void testVariance() { System.out.println("variance"); ContinuousDistribution dist = new FisherSendor(0.5, 0.5); assertEquals(Double.NaN, dist.variance(), 1e-10); dist = new FisherSendor(0.5, 3); assertEquals(Double.NaN, dist.variance(), 1e-10); dist = new FisherSendor(3, 0.5); assertEquals(Double.NaN, dist.variance(), 1e-10); dist = new FisherSendor(3, 3); assertEquals(Double.NaN, dist.variance(), 1e-10); dist = new FisherSendor(6, 4); assertEquals(Double.NaN, dist.variance(), 1e-10); dist = new FisherSendor(4, 6); assertEquals(9.0/2.0, dist.variance(), 1e-10); } /** * Test of skewness method, of class FisherSendor. */ @Test public void testSkewness() { System.out.println("skewness"); ContinuousDistribution dist = new FisherSendor(0.5, 0.5); assertEquals(Double.NaN, dist.skewness(), 1e-10); dist = new FisherSendor(0.5, 3); assertEquals(Double.NaN, dist.skewness(), 1e-10); dist = new FisherSendor(3, 0.5); assertEquals(Double.NaN, dist.skewness(), 1e-10); dist = new FisherSendor(3, 3); assertEquals(Double.NaN, dist.skewness(), 1e-10); dist = new FisherSendor(6, 6); assertEquals(Double.NaN, dist.skewness(), 1e-10); dist = new FisherSendor(5, 7); assertEquals(10.39230484541326, dist.skewness(), 1e-10); dist = new FisherSendor(7, 5); assertEquals(Double.NaN, dist.skewness(), 1e-10); } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new FisherSendor(0.5, 0.5); ContinuousDistribution d2 = new FisherSendor(0.6, 0.5); ContinuousDistribution d3 = new FisherSendor(0.5, 0.6); ContinuousDistribution d4 = new FisherSendor(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new FisherSendor(0.5, 0.5); ContinuousDistribution d2 = new FisherSendor(0.6, 0.5); ContinuousDistribution d4 = new FisherSendor(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
15,035
48.623762
598
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/GammaTest.java
package jsat.distributions; import java.util.Arrays; import java.util.Random; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class GammaTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Gamma(0.5, 0.5); ContinuousDistribution d2 = new Gamma(0.6, 0.5); ContinuousDistribution d3 = new Gamma(0.5, 0.6); ContinuousDistribution d4 = new Gamma(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Gamma(0.5, 0.5); ContinuousDistribution d2 = new Gamma(0.6, 0.5); ContinuousDistribution d4 = new Gamma(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } @Test public void testSample(){ System.out.println("hashCode"); Gamma d1 = new Gamma(0.5, 0.5); Gamma d2 = new Gamma(1.6, 0.5); Gamma d3 = new Gamma(0.5, 2.5); Gamma d4 = new Gamma(3.5, 2.5); Random rand = RandomUtil.getRandom(); for(Gamma d : Arrays.asList(d1, d2, d3, d4)) { Vec sample = d.sampleVec(1000000, rand); assertEquals(d.mean(), sample.mean(), 1e-1); assertEquals(d.standardDeviation(), sample.standardDeviation(), 1e-1); } } }
2,101
25.275
82
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/KolmogorovTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class KolmogorovTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Kolmogorov(); ContinuousDistribution d4 = new Kolmogorov(); Integer i = new Integer(1); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Kolmogorov(); ContinuousDistribution d4 = new Kolmogorov(); assertEquals(d1.hashCode(), d4.hashCode()); } }
1,104
20.666667
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/KumaraswamyTest.java
/* * Copyright (C) 2018 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions; import jsat.linear.Vec; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class KumaraswamyTest { double[] range = new double[] { 0, 0.050000000000000000000, 0.10000000000000000000, 0.15000000000000000000, 0.20000000000000000000, 0.25000000000000000000, 0.30000000000000000000, 0.35000000000000000000, 0.40000000000000000000, 0.45000000000000000000, 0.50000000000000000000, 0.55000000000000000000, 0.60000000000000000000, 0.65000000000000000000, 0.70000000000000000000, 0.75000000000000000000, 0.80000000000000000000, 0.85000000000000000000, 0.90000000000000000000, 0.95000000000000000000, 1.0000000000000000000 }; public KumaraswamyTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of pdf method, of class Beta. */ @Test public void testPdf() { System.out.println("pdf"); ContinuousDistribution instance = null; double[] parmTwo0 = new double[]{0,1.2688612786305156476,0.95605808387038662777,0.82465035211625394177,0.75187619375943209207,0.70710678118654752440,0.67869854393773691109,0.66125255318686165196,0.65201121779749292660,0.64955703500907604881,0.65328148243818826393,0.66317644115150481346,0.67980478762776913537,0.70442591676201416669,0.73934092805487665228,0.78867513459481288225,0.86023870029448346138,0.97063614821427270704,1.1632937248661048310,1.6119126569980934130,0}; double[] paramTwo1 = new double[]{0,4.0436141291243375437,2.2177581392778258978,1.4539308481385294180,1.0249223594996214535,0.75000000000000000000,0.56019662378357973747,0.42287473165049213891,0.32039154317679829860,0.24229856737469505979,0.18198051533946385980,0.13502936045407570105,0.098386676965933508143,0.069859681082909290709,0.047832953802703781920,0.031088913245535263673,0.018691769624716090152,0.0099101022338543865007,0.0041637771599603653989,0.00098667984907572921077,0}; double[] paramTwo2 = new double[]{0,0.0037502343969749453187,0.015007505629691605257,0.033807097694255976552,0.060241449667687414717,0.094491118252306806804,0.13686025610801962669,0.18782051096329649332,0.24806946917841691238,0.31861352523454621291,0.40089186286863657703,0.49697125857422871843,0.60986783446104458546,0.74410921107585204676,0.90678568249206644591,1.1096931643111617000,1.3742360023532837230,1.7446398544038663636,2.3339504543257195014,3.5845995086146493566,0}; double[] paramTwo3 = new double[]{0,0.022494375351562500000,0.089820090000000000000,0.20113543160156250000,0.35426304000000000000,0.54505920410156250000,0.76685049000000000000,1.0099873128515625000,1.2615782400000000000,1.5054829878515625000,1.7226562500000000000,1.8919486691015625000,1.9914854400000000000,2.0007572066015625000,1.9035720900000000000,1.6920318603515625000,1.3717094400000000000,0.96821910035156250000,0.53538489000000000000,0.16522700660156250000,0}; instance = new Kumaraswamy(0.5, 0.5); for(int i = 0; i < range.length; i++) assertEquals(parmTwo0[i], instance.pdf(range[i]), 1e-10); instance = new Kumaraswamy(0.5, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo1[i], instance.pdf(range[i]), 1e-10); instance = new Kumaraswamy(3, 0.5); for(int i = 0; i < range.length; i++) assertEquals(paramTwo2[i], instance.pdf(range[i]), 1e-10); instance = new Kumaraswamy(3, 3); for(int i = 0; i < range.length; i++) assertEquals(paramTwo3[i], instance.pdf(range[i]), 1e-10); } /** * Test of cdf method, of class Beta. */ @Test public void testCdf() { System.out.println("cdf"); ContinuousDistribution instance = null; double[] parmTwo0 = new double[]{0,0.11886822651204943036,0.17309478536947049508,0.21724737919361885315,0.25650393107963101974,0.29289321881345247560,0.32748424368284583176,0.36094442988888799159,0.39374554189983548328,0.42625824036413116334,0.45880389985380301560,0.49168892271520020992,0.52523339338311016489,0.55980206137449367338,0.59584659661717006392,0.63397459621556135324,0.67508030376709367384,0.72063365580172104597,0.77346809948820408927,0.84087562877075174656,1.0000000000000000000}; double[] paramTwo1 = new double[]{0,0.53200073313743585740,0.68030607465219759292,0.76998975405533631883,0.83108350559986540570,0.87500000000000000000,0.90748443976704817441,0.93188672733837137426,0.95034880891449794576,0.96433035671228233578,0.97487373415291633540,0.98275046291896034679,0.98854800926934015733,0.99272407812897062311,0.99564209817607952752,0.99759526419164492536,0.99882332579968033854,0.99952461605776161435,0.99986486239700381844,0.99998376619954074320,1.0000000000000000000}; double[] paramTwo2 = new double[]{0,0.000062501953247079850078,0.00050012506253908986427,0.0016889262359151813113,0.0040080321609014100131,0.0078432583507785285619,0.013592376347384468371,0.021672345274856292944,0.032529070204174041716,0.046650641160335179407,0.064585653306514653604,0.086969332388007899944,0.11456225515285378704,0.14831050258911845614,0.18944463483362223815,0.23965468371272253888,0.30143003213708077415,0.37881162277454031553,0.47942339660718519764,0.62234274798436612042,1.0000000000000000000}; double[] paramTwo3 = new double[]{0,0.00037495312695312500000,0.0029970010000000000000,0.010090866568359375000,0.023808512000000000000,0.046146392822265625000,0.078832683000000000000,0.12318901876367187500,0.17997414400000000000,0.24922038376757812500,0.33007812500000000000,0.42068844470898437500,0.51810969600000000000,0.61833024096289062500,0.71640660700000000000,0.80677413940429687500,0.88378572800000000000,0.94254339940820312500,0.98009748900000000000,0.99709873784960937500,1.0000000000000000000}; instance = new Kumaraswamy(0.5, 0.5); for(int i = 0; i < range.length; i++) { assertEquals(parmTwo0[i], instance.cdf(range[i]), 1e-10); assertEquals(range[i], instance.invCdf(parmTwo0[i]), 1e-10); } instance = new Kumaraswamy(0.5, 3); for(int i = 0; i < range.length; i++) { assertEquals(paramTwo1[i], instance.cdf(range[i]), 1e-10); assertEquals(range[i], instance.invCdf(paramTwo1[i]), 1e-10); } instance = new Kumaraswamy(3, 0.5); for(int i = 0; i < range.length; i++) { assertEquals(paramTwo2[i], instance.cdf(range[i]), 1e-10); assertEquals(range[i], instance.invCdf(paramTwo2[i]), 1e-10); } instance = new Kumaraswamy(3, 3); for(int i = 0; i < range.length; i++) { assertEquals(paramTwo3[i], instance.cdf(range[i]), 1e-10); assertEquals(range[i], instance.invCdf(paramTwo3[i]), 1e-10); } } /** * Test of min method, of class Beta. */ @Test public void testMin() { System.out.println("min"); ContinuousDistribution dist = new Kumaraswamy(0.5, 3); assertTrue(0 == dist.min()); } /** * Test of max method, of class Beta. */ @Test public void testMax() { System.out.println("max"); ContinuousDistribution dist = new Kumaraswamy(0.5, 3); assertTrue(1 == dist.max()); } /** * Test of mean method, of class Beta. */ @Test public void testMean() { System.out.println("mean"); ContinuousDistribution dist = new Kumaraswamy(0.5, 0.5); assertEquals(0.53333333333333333333, dist.mean(), 1e-10); dist = new Kumaraswamy(0.5, 3); assertEquals(0.10000000000000000000, dist.mean(), 1e-10); dist = new Kumaraswamy(3, 0.5); assertEquals(0.84130926319527255671, dist.mean(), 1e-10); dist = new Kumaraswamy(3, 3); assertEquals(0.57857142857142857143, dist.mean(), 1e-10); } /** * Test of median method, of class Beta. */ @Test public void testMedian() { System.out.println("median"); ContinuousDistribution dist = new Kumaraswamy(0.5, 0.5); assertEquals(0.56250000000000000000, dist.median(), 1e-10); dist = new Kumaraswamy(0.5, 3); assertEquals(0.042559472979237107632, dist.median(), 1e-10); dist = new Kumaraswamy(3, 0.5); assertEquals(0.90856029641606982945, dist.median(), 1e-10); dist = new Kumaraswamy(3, 3); assertEquals(0.59088011327517717570, dist.median(), 1e-10); } /** * Test of mode method, of class Beta. */ @Test public void testMode() { System.out.println("mode"); ContinuousDistribution dist = new Kumaraswamy(0.5, 0.5); assertTrue(Double.isNaN(dist.mode())); dist = new Kumaraswamy(0.5, 3); assertTrue(Double.isNaN(dist.mode())); dist = new Kumaraswamy(3, 0.5); assertTrue(Double.isNaN(dist.mode())); dist = new Kumaraswamy(3, 3); assertEquals(0.62996052494743658238, dist.mode(), 1e-10); } /** * Test of variance method, of class Beta. */ @Test public void testVariance() { System.out.println("variance"); ContinuousDistribution dist = new Kumaraswamy(0.5, 0.5); assertEquals(0.12190476190476190476, dist.variance(), 1e-10); dist = new Kumaraswamy(0.5, 3); assertEquals(0.018571428571428571429, dist.variance(), 1e-10); dist = new Kumaraswamy(3, 0.5); assertEquals(0.031372883441767762274, dist.variance(), 1e-10); dist = new Kumaraswamy(3, 3); assertEquals(0.033436920222634508349, dist.variance(), 1e-10); } /** * Test of skewness method, of class Beta. */ @Test public void testSkewness() { System.out.println("skewness"); double tol = 1e-10; ContinuousDistribution dist = new Kumaraswamy(0.5, 0.5); assertEquals(-0.13530526527453140657, dist.skewness(), tol); dist = new Kumaraswamy(0.5, 3); assertEquals(2.1073213127948306253, dist.skewness(), tol); dist = new Kumaraswamy(3, 0.5); assertEquals(-1.4389341273489145202, dist.skewness(), tol); dist = new Kumaraswamy(3, 3); assertEquals(-0.27980354819056016487, dist.skewness(), tol); } }
11,422
45.060484
523
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/LaplaceTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class LaplaceTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Laplace(0.5, 0.5); ContinuousDistribution d2 = new Laplace(0.6, 0.5); ContinuousDistribution d3 = new Laplace(0.5, 0.6); ContinuousDistribution d4 = new Laplace(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Laplace(0.5, 0.5); ContinuousDistribution d2 = new Laplace(0.6, 0.5); ContinuousDistribution d4 = new Laplace(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,436
23.775862
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/LevyTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class LevyTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Levy(0.5, 0.5); ContinuousDistribution d2 = new Levy(0.6, 0.5); ContinuousDistribution d3 = new Levy(0.5, 0.6); ContinuousDistribution d4 = new Levy(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Levy(0.5, 0.5); ContinuousDistribution d2 = new Levy(0.6, 0.5); ContinuousDistribution d4 = new Levy(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,412
23.362069
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/LogNormalTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class LogNormalTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new LogNormal(0.5, 0.5); ContinuousDistribution d2 = new LogNormal(0.6, 0.5); ContinuousDistribution d3 = new LogNormal(0.5, 0.6); ContinuousDistribution d4 = new LogNormal(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new LogNormal(0.5, 0.5); ContinuousDistribution d2 = new LogNormal(0.6, 0.5); ContinuousDistribution d4 = new LogNormal(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,452
24.051724
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/LogUniformTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class LogUniformTest { static double[] testVals = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; public LogUniformTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of pdf method, of class LogUniform. */ @Test public void testPdf() { System.out.println("pdf"); LogUniform instance = new LogUniform(1e-2, 10); double[] expected = new double[] { 0, 0.14476482730108394, 0.072382413650541971, 0.048254942433694648, 0.036191206825270986, 0.028952965460216789, 0.024127471216847324, 0.020680689614440563, 0.018095603412635493, 0.016084980811231549, 0.014476482730108394 }; for(int i = 0; i < testVals.length; i++) assertEquals(expected[i], instance.pdf(testVals[i]), 1e-10); } @Test public void testLogPdf() { System.out.println("pdf"); LogUniform instance = new LogUniform(1e-2, 10); double[] expected = new double[] { -Double.MAX_VALUE,-1.9326447339160655,-2.62579191447601080,-3.0312570225841752,-3.3189390950359561,-3.5420826463501659,-3.7244042031441205,-3.8785548829713788,-4.0120862755959014,-4.1298693112522849,-4.2352298269101112 }; for(int i = 0; i < testVals.length; i++) assertEquals(expected[i], instance.logPdf(testVals[i]), 1e-10); } /** * Test of cdf method, of class LogUniform. */ @Test public void testCdf() { System.out.println("cdf"); LogUniform instance = new LogUniform(1e-2, 10); double[] expected = new double[] { 0, 0.66666666666666667, 0.76700999855466040, 0.82570708490655415, 0.86735333044265413, 0.89965666811200627, 0.92605041679454788, 0.94836601333808561, 0.96769666233064786, 0.98474750314644162, 1.0000000000000000 }; for(int i = 0; i < testVals.length; i++) assertEquals(expected[i], instance.cdf(testVals[i]), 1e-10); } /** * Test of invCdf method, of class LogUniform. */ @Test public void testInvCdf() { System.out.println("invCdf"); LogUniform instance = new LogUniform(1e-2, 10); double[] expected = new double[] { 0.014125375446227543, 0.019952623149688796, 0.028183829312644538, 0.039810717055349725, 0.056234132519034908, 0.079432823472428150, 0.11220184543019634, 0.15848931924611135, 0.22387211385683396, 0.31622776601683793, 0.44668359215096312, 0.63095734448019325, 0.89125093813374553, 1.2589254117941672, 1.7782794100389228, 2.5118864315095801, 3.5481338923357546, 5.0118723362727229, 7.0794578438413791 }; double[] ps = new double[] { 0.05, 0.1, .15, .2, .25, .3, .35, .4, .45, .5, .55, .6, .65, .7, .75, .8, .85, .9, .95 }; for(int i = 0; i < ps.length; i++) assertEquals(expected[i], instance.invCdf(ps[i]), 1e-10); } /** * Test of skewness method, of class LogUniform. */ @Test public void testSampleAndStats() { System.out.println("skewness"); LogUniform instance = new LogUniform(1e-2, 10); Vec samples = instance.sampleVec(10000, RandomUtil.getRandom()); assertEquals(instance.mean(), samples.mean(), 0.1); assertEquals(instance.median(), samples.median(), 0.1); assertEquals(instance.variance(), samples.variance(), 0.3); } /** * Test of min method, of class LogUniform. */ @Test public void testMin() { System.out.println("min"); LogUniform instance = new LogUniform(1e-2, 10); assertEquals(1e-2, instance.min(), 0.0); } /** * Test of max method, of class LogUniform. */ @Test public void testMax() { System.out.println("max"); LogUniform instance = new LogUniform(1e-2, 10); assertEquals(10, instance.max(), 0.0); } }
5,494
27.769634
230
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/LogisticTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class LogisticTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Logistic(0.5, 0.5); ContinuousDistribution d2 = new Logistic(0.6, 0.5); ContinuousDistribution d3 = new Logistic(0.5, 0.6); ContinuousDistribution d4 = new Logistic(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Logistic(0.5, 0.5); ContinuousDistribution d2 = new Logistic(0.6, 0.5); ContinuousDistribution d4 = new Logistic(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,444
23.913793
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/MaxwellBoltzmannTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.distributions; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MaxwellBoltzmannTest { double[] range = new double[] { -3., -2.75, -2.5, -2.25, -2., -1.75, -1.5, -1.25, -1., -0.75, -0.5, -0.25, 0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3. }; public MaxwellBoltzmannTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of setShape method, of class MaxwellBoltzmann. */ @Test public void testSetShape() { System.out.println("setSigma"); MaxwellBoltzmann instance = new MaxwellBoltzmann(); instance.setShape(1); try { instance.setShape(0); fail("invalid value"); } catch(Exception ex) { } try { instance.setShape(Double.POSITIVE_INFINITY); fail("invalid value"); } catch(Exception ex) { } } @Test public void testLogPdf() { System.out.println("pdf"); ContinuousDistribution instance = null; double[] param0p5 = new double[]{0,0,0,-1.0439385332046727,-0.032644172084782055,0.15328604413154664,-0.1463498109648913,-0.8250627083364721,-1.8354195947485628,-3.152118235094046,-4.760055449845001,-6.649489378532234,-8.813768347216582,-11.24814798760793,-13.949125233628672,-16.914039818281598,-20.140823873974156,-23.627838131000253,-27.37376108872511,-31.37751184509224,-35.63819501741234,-40.15506057487179,-44.92747398609669,-49.95489365775783,-55.23685362648804}; double[] param2 = new double[]{0,0,0,-5.085634116564345,-3.7227772554444543,-2.950909539228125,-2.4302328943245635,-2.0542582916961436,-1.7755526781082347,-1.568813818453718,-1.4189385332046727,-1.316184961891906,-1.2539014305762533,-1.2273435709676035,-1.233008316988344,-1.2682354016412711,-1.3309569573338274,-1.4195337143599245,-1.5326441720847819,-1.6692074284519127,-1.8283281007720154,-2.0092561582314636,-2.211357069456363,-2.4340892411174986,-2.676986709847713}; double[] param12 = new double[]{0,0,0,-10.4533170381374,-9.067673718684174,-8.25782857191229,-7.683983524230951,-7.239649546602531,-6.8773935857924,-6.571913406693438,-6.308105829777727,-6.076228994576071,-5.869631227149307,-5.683568159207324,-5.514536724672509,-5.359876656547658,-5.2175200872402145,-5.08582774704409,-4.963478135324503,-4.849390350024966,-4.74266900845618,-4.642564079804518,-4.548441032696084,-4.459758273801663,-4.3760498397541}; instance = new MaxwellBoltzmann(0.5); for(int i = 0; i < range.length; i++) assertEquals(param0p5[i], instance.logPdf(range[i]+2.5), 1e-10); instance = new MaxwellBoltzmann(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.logPdf(range[i]+2.5), 1e-10); instance = new MaxwellBoltzmann(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.logPdf(range[i]+2.5), 1e-10); } /** * Test of pdf method, of class MaxwellBoltzmann. */ @Test public void testPdf() { System.out.println("pdf"); ContinuousDistribution instance = null; double[] param0p5 = new double[]{0,0,0,0.35206532676429947,0.9678828980765735,1.1656583609930256,0.863855464211009,0.4382075123392134,0.15954654282976827,0.042761452057242244,0.008565134448952664,0.0012946830296593434,0.00014867195147342976,0.000013031409651477368,8.749271303745532e-7,4.511550678949219e-8,1.7904052000394604e-9,5.477221199315272e-11,1.2933813973854447e-12,2.3600420975525e-14,3.3306466372207283e-16,3.638134677342304e-18,3.0778394506825684e-20,2.0177406354196752e-22,1.0255085186985274e-24}; double[] param2 = new double[]{0,0,0,0.00618496385851171,0.024166757300178074,0.05229212257543626,0.08801633169107487,0.12818787833999026,0.16938980558707747,0.20829210813357238,0.24197072451914337,0.2681563798098696,0.2853891959203467,0.2930700643820856,0.2914145902482564,0.28132761428232617,0.26422428890619154,0.2418267509532137,0.21596386605275225,0.18839632404815398,0.16068198741806627,0.13408837811873256,0.10955187808480335,0.08767756381566659,0.06877006641828234}; double[] param12 = new double[]{0,0,0,0.000028852409850921587,0.00011533452737288349,0.00025922126086385847,0.00046013827113234023,0.0007175631885070832,0.0010308273097519517,0.0013991177680274776,0.0018214801671386106,0.0022968216694486633,0.002823914525031556,0.003401400027886845,0.004027792883363012,0.004701485969332062,0.005420755472140021,0.00618376637693079,0.006988578290610984,0.00783315157449754,0.008715353762572708,0.009632966240267904,0.01058369115781257,0.011565158551420455,0.012574933644946164}; instance = new MaxwellBoltzmann(0.5); for(int i = 0; i < range.length; i++) assertEquals(param0p5[i], instance.pdf(range[i]+2.5), 1e-10); instance = new MaxwellBoltzmann(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.pdf(range[i]+2.5), 1e-10); instance = new MaxwellBoltzmann(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.pdf(range[i]+2.5), 1e-10); } /** * Test of cdf method, of class MaxwellBoltzmann. */ @Test public void testCdf() { System.out.println("cdf"); ContinuousDistribution instance = null; double[] param0p5 = new double[]{0,0,0,0.030859595783726712,0.19874804309879912,0.4778328104646086,0.7385358700508893,0.8999391668806049,0.9707091134651118,0.9934259629766086,0.9988660157102147,0.9998493509837884,0.999984559501709,0.9999987773472704,0.9999999251162305,0.9999999964492564,0.9999999998695543,0.9999999999962846,0.999999999999918,0.9999999999999986,1.,1.,1.,1.,1.}; double[] param2 = new double[]{0,0,0,0.0005170279240384046,0.004078592964422811,0.013448212943120874,0.030859595783726712,0.057827731214630085,0.09503914701405697,0.1423298471325275,0.19874804309879912,0.26268851273105853,0.33207773919373457,0.40458482528702217,0.4778328104646086,0.5495880697451594,0.6179110703795754,0.6812587421193825,0.7385358700508893,0.7890991997636632,0.8327226214294071,0.8695345208664327,0.8999391668806049,0.9245331498906099,0.94402587977114}; double[] param12 = new double[]{0,0,0,2.4045762129741577e-6,0.00001922909733632211,0.00006485597263361509,0.00015359266218761825,0.0002996345070972878,0.0005170279240384046,0.0008196340833463434,0.0012210931878273434,0.0017347894670798891,0.002373816999227285,0.0031509464686337862,0.004078592964422811,0.005168784920450115,0.0064331342928277135,0.00788280806617181,0.009528501174477233,0.01138041091693437,0.013448212943120874,0.015741038875855595,0.0182674556336187,0.02103544650785194,0.024052394043691305}; instance = new MaxwellBoltzmann(0.5); for(int i = 0; i < range.length; i++) assertEquals(param0p5[i], instance.cdf(range[i]+2.5), 1e-10); instance = new MaxwellBoltzmann(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.cdf(range[i]+2.5), 1e-10); instance = new MaxwellBoltzmann(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.cdf(range[i]+2.5), 1e-10); } /** * Test of invCdf method, of class MaxwellBoltzmann. */ @Test public void testInvCdf() { System.out.println("invCdf"); ContinuousDistribution instance; double[] param0p5 = new double[] {0.15833852261996845,0.29483399443273883,0.367702453369813,0.4238115493761005,0.47166773202109047,0.514633536906765,0.5544484063052013,0.5921637017354954,0.628489130214972,0.663948955783709,0.6989632279600045,0.7338956874781447,0.7690861272275261,0.8048761358046771,0.8416338247492682,0.879782418021023,0.9198388029472511,0.9624720066447157,1.0086008009162615,1.0595722524099012,1.1175243646484285,1.1862308058829834,1.2735108480574397,1.4010354011075703,1.7157036426968402}; double[] param2 = new double[] {0.6333540904798738,1.1793359777309553,1.470809813479252,1.695246197504402,1.8866709280843619,2.05853414762706,2.2177936252208053,2.3686548069419815,2.513956520859888,2.655795823134836,2.795852911840018,2.935582749912579,3.0763445089101045,3.2195045432187084,3.3665352989970727,3.519129672084092,3.6793552117890043,3.8498880265788626,4.034403203665046,4.238289009639605,4.470097458593714,4.744923223531933,5.094043392229759,5.604141604430281,6.862814570787361}; double[] param12 = new double[] {3.8001245428792427,7.076015866385732,8.824858880875512,10.171477185026411,11.320025568506171,12.35120488576236,13.306761751324832,14.21192884165189,15.083739125159328,15.934774938809017,16.775117471040108,17.613496499475474,18.458067053460628,19.31702725931225,20.199211793982435,21.114778032504553,22.076131270734024,23.099328159473174,24.206419221990274,25.429734057837628,26.820584751562286,28.4695393411916,30.564260353378554,33.624849626581685,41.176887424724164}; instance = new MaxwellBoltzmann(0.5); for(int i = 0; i < range.length-2; i++)//-2 b/c it enters a numerically unstable range that isnt fair assertEquals(param0p5[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); instance = new MaxwellBoltzmann(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); instance = new MaxwellBoltzmann(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); } /** * Test of min method, of class MaxwellBoltzmann. */ @Test public void testMin() { System.out.println("min"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertTrue(0 == dist.min()); } /** * Test of max method, of class MaxwellBoltzmann. */ @Test public void testMax() { System.out.println("max"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertTrue(Double.POSITIVE_INFINITY == dist.max()); } /** * Test of mean method, of class MaxwellBoltzmann. */ @Test public void testMean() { System.out.println("mean"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertEquals(0.7978845608028654, dist.mean(), 1e-10); dist = new MaxwellBoltzmann(2); assertEquals(3.1915382432114616, dist.mean(), 1e-10); dist = new MaxwellBoltzmann(12); assertEquals(19.14922945926877, dist.mean(), 1e-10); } @Test public void testMedian() { System.out.println("median"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertEquals(0.7690861272275261, dist.median(), 1e-10); dist = new MaxwellBoltzmann(2); assertEquals(3.0763445089101045, dist.median(), 1e-10); dist = new MaxwellBoltzmann(12); assertEquals(18.458067053460628, dist.median(), 1e-10); } /** * Test of mode method, of class MaxwellBoltzmann. */ @Test public void testMode() { System.out.println("mode"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertEquals(0.7071067811882024, dist.mode(), 1e-10); dist = new MaxwellBoltzmann(2); assertEquals(2.828427124743843, dist.mode(), 1e-10); dist = new MaxwellBoltzmann(12); assertEquals(16.970562749522642, dist.mode(), 1e-8);//Hitting the bounds of what we can numericaly caluate well. But relative error is still in 1e-10 } /** * Test of variance method, of class MaxwellBoltzmann. */ @Test public void testVariance() { System.out.println("variance"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertEquals(0.11338022763241863, dist.variance(), 1e-10); dist = new MaxwellBoltzmann(2); assertEquals(1.814083642118698, dist.variance(), 1e-10); dist = new MaxwellBoltzmann(12); assertEquals(65.30701111627313, dist.variance(), 1e-10); } /** * Test of skewness method, of class MaxwellBoltzmann. */ @Test public void testSkewness() { System.out.println("skewness"); ContinuousDistribution dist = new MaxwellBoltzmann(0.5); assertEquals(0.48569282804959213, dist.skewness(), 1e-10); dist = new MaxwellBoltzmann(2); assertEquals(0.48569282804959213, dist.skewness(), 1e-10); dist = new MaxwellBoltzmann(12); assertEquals(0.48569282804959213, dist.skewness(), 1e-10); } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new MaxwellBoltzmann(0.5); ContinuousDistribution d2 = new MaxwellBoltzmann(0.6); ContinuousDistribution d4 = new MaxwellBoltzmann(0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new MaxwellBoltzmann(0.5); ContinuousDistribution d2 = new MaxwellBoltzmann(0.6); ContinuousDistribution d4 = new MaxwellBoltzmann(0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
14,053
47.130137
520
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/NormalTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.distributions; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NormalTest { double[] range = new double[] { -3., -2.75, -2.5, -2.25, -2., -1.75, -1.5, -1.25, -1., -0.75, -0.5, -0.25, 0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3. }; public NormalTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of setMean method, of class Normal. */ @Test public void testSetMean() { System.out.println("setMean"); double mean = 0.0; Normal instance = new Normal(); instance.setMean(mean); try { instance.setMean(Double.POSITIVE_INFINITY); fail("Can not set mean to infinity"); } catch(Exception ex) { } } /** * Test of setStndDev method, of class Normal. */ @Test public void testSetStndDev() { System.out.println("setStndDev"); Normal instance = new Normal(); instance.setStndDev(1.0); try { instance.setStndDev(Double.POSITIVE_INFINITY); fail("Can not set stnd deviation to infinity"); } catch(Exception ex) { } try { instance.setStndDev(0); fail("Can not set stnd deviation to 0"); } catch(Exception ex) { } } /** * Test of cdf method, of class Normal. */ @Test public void testCdf_3args() { System.out.println("cdf"); double[] cdfMean0Stnd1 = new double[] { 0.0013498980316301, 0.00297976323505456, 0.00620966532577614, 0.0122244726550447, 0.0227501319481792, 0.0400591568638171, 0.0668072012688581, 0.105649773666855, 0.158655253931457, 0.226627352376868, 0.308537538725987, 0.401293674317076, 0.5, 0.598706325682924, 0.691462461274013, 0.773372647623132, 0.841344746068543, 0.894350226333145, 0.933192798731142, 0.959940843136183, 0.977249868051821, 0.987775527344955, 0.993790334674224, 0.997020236764945, 0.99865010196837 }; double[] cdfMean1p5Stnd2 = new double[] { 0.0122244726550447, 0.0167933064484488, 0.0227501319481792, 0.0303963617652614, 0.0400591568638171, 0.0520812794152196, 0.0668072012688581, 0.0845657223513358, 0.105649773666855, 0.130294517136809, 0.158655253931457, 0.190786952852511, 0.226627352376868, 0.265985529048701, 0.308537538725987, 0.353830233327276, 0.401293674317076, 0.450261775169887, 0.5, 0.549738224830113, 0.598706325682924, 0.646169766672724, 0.691462461274013, 0.7340144709513, 0.773372647623132 }; for(int i = 0; i < range.length; i++) assertEquals(cdfMean0Stnd1[i], Normal.cdf(range[i], 0, 1), 1e-10); for(int i = 0; i < range.length; i++) assertEquals(cdfMean1p5Stnd2[i], Normal.cdf(range[i], 1.5, 2), 1e-10); } /** * Test of cdf method, of class Normal. */ @Test public void testCdf_double() { System.out.println("cdf"); double[] cdfMean0Stnd1 = new double[] { 0.0013498980316301, 0.00297976323505456, 0.00620966532577614, 0.0122244726550447, 0.0227501319481792, 0.0400591568638171, 0.0668072012688581, 0.105649773666855, 0.158655253931457, 0.226627352376868, 0.308537538725987, 0.401293674317076, 0.5, 0.598706325682924, 0.691462461274013, 0.773372647623132, 0.841344746068543, 0.894350226333145, 0.933192798731142, 0.959940843136183, 0.977249868051821, 0.987775527344955, 0.993790334674224, 0.997020236764945, 0.99865010196837 }; double[] cdfMean1p5Stnd2 = new double[] { 0.0122244726550447, 0.0167933064484488, 0.0227501319481792, 0.0303963617652614, 0.0400591568638171, 0.0520812794152196, 0.0668072012688581, 0.0845657223513358, 0.105649773666855, 0.130294517136809, 0.158655253931457, 0.190786952852511, 0.226627352376868, 0.265985529048701, 0.308537538725987, 0.353830233327276, 0.401293674317076, 0.450261775169887, 0.5, 0.549738224830113, 0.598706325682924, 0.646169766672724, 0.691462461274013, 0.7340144709513, 0.773372647623132 }; Normal dist = new Normal(0, 1); for(int i = 0; i < range.length; i++) assertEquals(cdfMean0Stnd1[i], dist.cdf(range[i]), 1e-10); dist = new Normal(1.5, 2); for(int i = 0; i < range.length; i++) assertEquals(cdfMean1p5Stnd2[i], dist.cdf(range[i]), 1e-10); } /** * Test of invcdf method, of class Normal. */ @Test public void testInvcdf() { System.out.println("invcdf"); double[] inCDF = new double[] { -3.3000727542547823, -1.8057072650340151, -1.1794924187821967, -0.7419660787053934, -0.39155417237863954, -0.09132059856786046, 0.17670363698649716, 0.4228030336829398, 0.6535501073566241, 0.8735200785359454, 1.0861426807957881, 1.2941759325571114, 1.5, 1.7058240674428888, 1.9138573192042119, 2.1264799214640546, 2.3464498926433754, 2.57719696631706, 2.823296363013503, 3.09132059856786, 3.3915541723786395, 3.741966078705394, 4.179492418782196, 4.805707265034015, 6.300072754254788 }; for(int i = 0; i < range.length; i++) assertEquals(inCDF[i], Normal.invcdf(range[i]/6.1+0.5, 1.5, 2), 1e-10); } /** * Test of invCdf method, of class Normal. */ @Test public void testInvCdf() { System.out.println("invCdf"); Normal instance = new Normal(1.5, 2); double[] inCDF = new double[] { -3.3000727542547823, -1.8057072650340151, -1.1794924187821967, -0.7419660787053934, -0.39155417237863954, -0.09132059856786046, 0.17670363698649716, 0.4228030336829398, 0.6535501073566241, 0.8735200785359454, 1.0861426807957881, 1.2941759325571114, 1.5, 1.7058240674428888, 1.9138573192042119, 2.1264799214640546, 2.3464498926433754, 2.57719696631706, 2.823296363013503, 3.09132059856786, 3.3915541723786395, 3.741966078705394, 4.179492418782196, 4.805707265034015, 6.300072754254788 }; for(int i = 0; i < range.length; i++) assertEquals(inCDF[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); } /** * Test of pdf method, of class Normal. */ @Test public void testPdf_3args() { System.out.println("pdf"); double[] pdfMean0Stnd1 = new double[] { 0.00443184841193801, 0.00909356250159105, 0.0175283004935685, 0.0317396518356674, 0.0539909665131881, 0.0862773188265115, 0.129517595665892, 0.182649085389022, 0.241970724519143, 0.301137432154804, 0.3520653267643, 0.386668116802849, 0.398942280401433, 0.386668116802849, 0.3520653267643, 0.301137432154804, 0.241970724519143, 0.182649085389022, 0.129517595665892, 0.0862773188265115, 0.0539909665131881, 0.0317396518356674, 0.0175283004935685, 0.00909356250159105, 0.00443184841193801 }; double[] pdfMean1p5Stnd2 = new double[] { 0.0158698259178337, 0.0208604926281693, 0.026995483256594, 0.034393137913346, 0.0431386594132558, 0.0532691340652925, 0.0647587978329459, 0.0775061327291466, 0.091324542694511, 0.10593832288785, 0.120985362259572, 0.136027499189272, 0.150568716077402, 0.164080484275188, 0.17603266338215, 0.185927546934885, 0.193334058401425, 0.197918843472375, 0.199471140200716, 0.197918843472375, 0.193334058401425, 0.185927546934885, 0.17603266338215, 0.164080484275188, 0.150568716077402 }; for(int i = 0; i < range.length; i++) assertEquals(pdfMean0Stnd1[i], Normal.pdf(range[i], 0, 1), 1e-10); for(int i = 0; i < range.length; i++) assertEquals(pdfMean1p5Stnd2[i], Normal.pdf(range[i], 1.5, 2), 1e-10); } /** * Test of pdf method, of class Normal. */ @Test public void testPdf_double() { System.out.println("pdf"); double[] pdfMean0Stnd1 = new double[] { 0.00443184841193801, 0.00909356250159105, 0.0175283004935685, 0.0317396518356674, 0.0539909665131881, 0.0862773188265115, 0.129517595665892, 0.182649085389022, 0.241970724519143, 0.301137432154804, 0.3520653267643, 0.386668116802849, 0.398942280401433, 0.386668116802849, 0.3520653267643, 0.301137432154804, 0.241970724519143, 0.182649085389022, 0.129517595665892, 0.0862773188265115, 0.0539909665131881, 0.0317396518356674, 0.0175283004935685, 0.00909356250159105, 0.00443184841193801 }; double[] pdfMean1p5Stnd2 = new double[] { 0.0158698259178337, 0.0208604926281693, 0.026995483256594, 0.034393137913346, 0.0431386594132558, 0.0532691340652925, 0.0647587978329459, 0.0775061327291466, 0.091324542694511, 0.10593832288785, 0.120985362259572, 0.136027499189272, 0.150568716077402, 0.164080484275188, 0.17603266338215, 0.185927546934885, 0.193334058401425, 0.197918843472375, 0.199471140200716, 0.197918843472375, 0.193334058401425, 0.185927546934885, 0.17603266338215, 0.164080484275188, 0.150568716077402 }; Normal dist = new Normal(0, 1); for(int i = 0; i < range.length; i++) assertEquals(pdfMean0Stnd1[i], dist.pdf(range[i]), 1e-10); dist = new Normal(1.5, 2); for(int i = 0; i < range.length; i++) assertEquals(pdfMean1p5Stnd2[i], dist.pdf(range[i]), 1e-10); } @Test public void testLogPDF_double() { double[] logPdfMean0Std1 = new double[] { -5.4189385332046727418, -4.7001885332046727418, -4.0439385332046727418, -3.4501885332046727418, -2.9189385332046727418, -2.4501885332046727418, -2.0439385332046727418, -1.7001885332046727418, -1.4189385332046727418, -1.2001885332046727418, -1.0439385332046727418, -0.95018853320467274178, -0.91893853320467274178, -0.95018853320467274178, -1.0439385332046727418, -1.2001885332046727418, -1.4189385332046727418, -1.7001885332046727418, -2.0439385332046727418, -2.4501885332046727418, -2.9189385332046727418, -3.4501885332046727418, -4.0439385332046727418, -4.7001885332046727418, -5.4189385332046727418 }; double[] logPdfMean1p5Std2 = new double[] { -4.1433357137646180512, -3.8698982137646180512, -3.6120857137646180512, -3.3698982137646180512, -3.1433357137646180512, -2.9323982137646180512, -2.7370857137646180512, -2.5573982137646180512, -2.3933357137646180512, -2.2448982137646180512, -2.1120857137646180512, -1.9948982137646180512, -1.8933357137646180512, -1.8073982137646180512, -1.7370857137646180512, -1.6823982137646180512, -1.6433357137646180512, -1.6198982137646180512, -1.6120857137646180512, -1.6198982137646180512, -1.6433357137646180512, -1.6823982137646180512, -1.7370857137646180512, -1.8073982137646180512, -1.8933357137646180512 }; Normal dist = new Normal(0, 1); for(int i = 0; i < range.length; i++) assertEquals(logPdfMean0Std1[i], dist.logPdf(range[i]), 1e-8); dist = new Normal(1.5, 2); for(int i = 0; i < range.length; i++) assertEquals(logPdfMean1p5Std2[i], dist.logPdf(range[i]), 1e-8); } /** * Test of min method, of class Normal. */ @Test public void testMin() { System.out.println("min"); Normal instance = new Normal(); assertTrue(instance.min() == Double.NEGATIVE_INFINITY); } /** * Test of max method, of class Normal. */ @Test public void testMax() { System.out.println("max"); Normal instance = new Normal(); assertTrue(instance.max() == Double.POSITIVE_INFINITY); } /** * Test of mean method, of class Normal. */ @Test public void testMean() { System.out.println("mean"); Normal instance = new Normal(0, 1); assertEquals(0.0, instance.mean(), 1e-10); } /** * Test of median method, of class Normal. */ @Test public void testMedian() { System.out.println("median"); Normal instance = new Normal(0, 1); assertEquals(0.0, instance.median(), 1e-10); } /** * Test of mode method, of class Normal. */ @Test public void testMode() { System.out.println("mode"); Normal instance = new Normal(0, 1); assertEquals(0.0, instance.mode(), 1e-10); } /** * Test of variance method, of class Normal. */ @Test public void testVariance() { System.out.println("variance"); Normal instance = new Normal(0, 1); assertEquals(1, instance.variance(), 1e-10); instance = new Normal(0, 2); assertEquals(4, instance.variance(), 1e-10); } /** * Test of standardDeviation method, of class Normal. */ @Test public void testStandardDeviation() { System.out.println("standardDeviation"); Normal instance = new Normal(0, 1); assertEquals(1, instance.standardDeviation(), 1e-10); instance = new Normal(0, 2); assertEquals(2, instance.standardDeviation(), 1e-10); } /** * Test of skewness method, of class Normal. */ @Test public void testSkewness() { System.out.println("skewness"); Normal instance = new Normal(0, 1); assertEquals(0, instance.skewness(), 1e-10); instance = new Normal(0, 2); assertEquals(0, instance.skewness(), 1e-10); } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Normal(0.5, 0.5); ContinuousDistribution d2 = new Normal(0.6, 0.5); ContinuousDistribution d3 = new Normal(0.5, 0.6); ContinuousDistribution d4 = new Normal(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Normal(0.5, 0.5); ContinuousDistribution d2 = new Normal(0.6, 0.5); ContinuousDistribution d4 = new Normal(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } @Test public void testHugeRange() { Normal n = new Normal(811.4250871080139d, 1540.8594859716793d); //original tests from TKlerx that failed assertTrue(n.cdf(44430.0d) <= 1); assertFalse(Double.isNaN(n.cdf(67043.0))); //Some more tests assertTrue(n.cdf(-44430.0d) >= 0); assertFalse(Double.isNaN(n.cdf(-67043.0))); for(double v : new double[]{44430.0d, -44430.0d, 67043, -67043}) assertTrue(n.pdf(v) >= 0 && n.pdf(v) <= 1e-20); } }
16,231
35.313199
118
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/ParetoTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class ParetoTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Pareto(0.5, 0.5); ContinuousDistribution d2 = new Pareto(0.6, 0.5); ContinuousDistribution d3 = new Pareto(0.5, 0.6); ContinuousDistribution d4 = new Pareto(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Pareto(0.5, 0.5); ContinuousDistribution d2 = new Pareto(0.6, 0.5); ContinuousDistribution d4 = new Pareto(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,427
24.052632
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/RayleighTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.distributions; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RayleighTest { double[] range = new double[] { -3., -2.75, -2.5, -2.25, -2., -1.75, -1.5, -1.25, -1., -0.75, -0.5, -0.25, 0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2., 2.25, 2.5, 2.75, 3. }; public RayleighTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of setScale method, of class Rayleigh. */ @Test public void testSetScale() { System.out.println("setSig"); Rayleigh instance = new Rayleigh(0.5); instance.setScale(1); instance.setScale(0.5); try { instance.setScale(0); fail("Invalid value, should err"); } catch(Exception ex) { } try { instance.setScale(Double.POSITIVE_INFINITY); fail("Invalid value, should err"); } catch(Exception ex) { } } /** * Test of pdf method, of class Rayleigh. */ @Test public void testPdf() { System.out.println("pdf"); ContinuousDistribution instance = null; double[] param0p5 = new double[]{0,0.8824969025845955,1.2130613194252668,0.9739574020750492,0.5413411329464508,0.2196846681170371,0.06665397922945383,0.015312437827280196,0.002683701023220095,0.0003605876765365596,0.00003726653172078671,2.9695363536993156e-6,1.8275975693655156e-7,8.699061918680616e-9,3.2056287839037744e-10,9.152905016407986e-12,2.026266487855068e-13,3.4798519123791473e-15,4.638162796478966e-17,4.799711183758816e-19,3.857499695927835e-21,2.4084408226737518e-23,1.1684402949294009e-25,4.40560158952444e-28,1.2912446784050733e-30}; double[] param2 = new double[]{0,0.06201362114126522,0.12115415430954302,0.1747692173174114,0.22062422564614886,0.2570554882495827,0.2830648507458777,0.2983490786457773,0.3032653298563167,0.29874149495738167,0.28614585110725893,0.26713371266475033,0.2434893505187623,0.21697961612140398,0.18923202097615138,0.16164527240039328,0.1353352832366127,0.11111518886956405,0.08950444730800615,0.07075994102985847,0.054921167029259275,0.041861916287831195,0.03134199871496697,0.023054207083316413,0.016663494807363458}; double[] param12 = new double[]{0,0.001735734391765489,0.0034692094482488734,0.005198170734934769,0.006920373603960896,0.0086335880503019,0.010335603523544203,0.012024233680718716,0.013697321065887724,0.015352741702467192,0.01698840958460465,0.018602281054324005,0.020192359051590503,0.0217566972249391,0.02329340389084611,0.02480064583060355,0.026276651914076816,0.027719716540384763,0.029128202886235237,0.03050054595337441,0.03183525540736211,0.03313091820066401,0.03438620097385169,0.0355998522295194,0.03677070427435814}; instance = new Rayleigh(0.5); for(int i = 0; i < range.length; i++) assertEquals(param0p5[i], instance.pdf(range[i]+3), 1e-10); instance = new Rayleigh(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.pdf(range[i]+3), 1e-10); instance = new Rayleigh(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.pdf(range[i]+3), 1e-10); } /** * Test of cdf method, of class Rayleigh. */ @Test public void testCdf() { System.out.println("cdf"); ContinuousDistribution instance = null; double[] param0p5 = new double[]{0,0.11750309741540454,0.3934693402873666,0.6753475326416503,0.8646647167633873,0.9560630663765926,0.9888910034617577,0.9978125088818172,0.9996645373720975,0.999959934702607,0.999996273346828,0.9999997300421497,0.9999999847700203,0.9999999993308414,0.9999999999771026,0.9999999999993898,0.9999999999999873,0.9999999999999998,1.,1.,1.,1.,1.,1.,1.}; double[] param2 = new double[]{0,0.007782061739756485,0.03076676552365587,0.06789750764047242,0.11750309741540454,0.17742243760133536,0.24516039801099265,0.31805924880965186,0.3934693402873666,0.4689040089646548,0.5421666382283857,0.6114418724876358,0.6753475326416503,0.7329481647736567,0.7837348331701127,0.8275783761062472,0.8646647167633873,0.8954209987109986,0.9204404912817723,0.9404126812380139,0.9560630663765926,0.9681052066378429,0.9772058191163877,0.9839622907246495,0.9888910034617577}; double[] param12 = new double[]{0,0.00021699034307820497,0.000867678904324376,0.0019512188925244756,0.003466201029630911,0.005410656605221109,0.007782061739756485,0.01057734284371692,0.013792883256083743,0.017424531042099622,0.02146760792677216,0.025916919337215627,0.03076676552365587,0.03601095372577512,0.041642811348045816,0.0476552001048236,0.05404053109323459,0.06079078074931621,0.06789750764047242,0.07535187004507038,0.08314464426797108,0.09126624363892988,0.09970673813915565,0.10845587459986206,0.11750309741540454}; instance = new Rayleigh(0.5); for(int i = 0; i < range.length; i++) assertEquals(param0p5[i], instance.cdf(range[i]+3), 1e-10); instance = new Rayleigh(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.cdf(range[i]+3), 1e-10); instance = new Rayleigh(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.cdf(range[i]+3), 1e-10); } /** * Test of invCdf method, of class Rayleigh. */ @Test public void testInvCdf() { System.out.println("invCdf"); ContinuousDistribution instance = null; double[] param0p5 = new double[] {0.06415021097594048,0.1587936611248885,0.2173601198712892,0.2651244524946627,0.3073276166341036,0.34617398318289344,0.38285868033545123,0.41813499523464237,0.45253281099872633,0.48646053511406523,0.5202601117191001,0.5542410588845034,0.5887050112577373,0.6239668877424936,0.6603769423628185,0.6983479248355227,0.7383931805037708,0.7811856713602556,0.8276574896199848,0.8791827189816046,0.9379495207658656,1.0078274461666232,1.0968422338547341,1.2272452027824763,1.549842095946111}; double[] param2 = new double[] {0.2566008439037619,0.635174644499554,0.8694404794851568,1.0604978099786508,1.2293104665364143,1.3846959327315738,1.531434721341805,1.6725399809385695,1.8101312439949053,1.945842140456261,2.0810404468764006,2.2169642355380135,2.3548200450309493,2.4958675509699746,2.641507769451274,2.7933916993420906,2.953572722015083,3.1247426854410225,3.310629958479939,3.5167308759264184,3.7517980830634623,4.031309784666493,4.3873689354189365,4.908980811129905,6.199368383784444}; double[] param12 = new double[] {1.5396050634225715,3.811047866997324,5.2166428769109405,6.362986859871905,7.375862799218486,8.308175596389443,9.18860832805083,10.035239885631416,10.860787463969432,11.675052842737566,12.486242681258403,13.301785413228082,14.128920270185695,14.975205305819848,15.849046616707644,16.760350196052542,17.721436332090498,18.748456112646135,19.863779750879633,21.10038525555851,22.510788498380773,24.187858707998956,26.324213612513617,29.453884866779433,37.19621030270666}; instance = new Rayleigh(0.5); for(int i = 0; i < range.length-2; i++)//-2 b/c it enters a numerically unstable range that isnt fair assertEquals(param0p5[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); instance = new Rayleigh(2); for(int i = 0; i < range.length; i++) assertEquals(param2[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); instance = new Rayleigh(12); for(int i = 0; i < range.length; i++) assertEquals(param12[i], instance.invCdf(range[i]/6.1+0.5), 1e-10); } @Test public void testMin() { System.out.println("min"); ContinuousDistribution dist = new Rayleigh(0.5); assertTrue(0 == dist.min()); } /** * Test of max method, of class Rayleigh. */ @Test public void testMax() { System.out.println("max"); ContinuousDistribution dist = new Rayleigh(0.5); assertTrue(Double.POSITIVE_INFINITY == dist.max()); } /** * Test of mean method, of class ChiSquared. */ @Test public void testMean() { System.out.println("mean"); ContinuousDistribution dist = new Rayleigh(0.5); assertEquals(0.6266570686577501, dist.mean(), 1e-10); dist = new Rayleigh(2); assertEquals(2.5066282746310002, dist.mean(), 1e-10); dist = new Rayleigh(12); assertEquals(15.039769647786002, dist.mean(), 1e-10); } /** * Test of median method, of class ChiSquared. */ @Test public void testMedian() { System.out.println("median"); ContinuousDistribution dist = new Rayleigh(0.5); assertEquals(0.5887050112577373, dist.median(), 1e-10); dist = new Rayleigh(2); assertEquals(2.3548200450309493, dist.median(), 1e-10); dist = new Rayleigh(12); assertEquals(14.128920270185695, dist.median(), 1e-10); } /** * Test of mode method, of class ChiSquared. */ @Test public void testMode() { System.out.println("mode"); ContinuousDistribution dist = new Rayleigh(0.5); assertEquals(0.5, dist.mode(), 1e-10); dist = new Rayleigh(2); assertEquals(2, dist.mode(), 1e-10); dist = new Rayleigh(12); assertEquals(12, dist.mode(), 1e-10); } /** * Test of variance method, of class ChiSquared. */ @Test public void testVariance() { System.out.println("variance"); ContinuousDistribution dist = new Rayleigh(0.5); assertEquals(0.10730091830127586, dist.variance(), 1e-10); dist = new Rayleigh(2); assertEquals(1.7168146928204138, dist.variance(), 1e-10); dist = new Rayleigh(12); assertEquals(61.805328941534896, dist.variance(), 1e-10); } /** * Test of skewness method, of class ChiSquared. */ @Test public void testSkewness() { System.out.println("skewness"); ContinuousDistribution dist = new Rayleigh(0.5); assertEquals(0.6311106578189364, dist.skewness(), 1e-10); dist = new Rayleigh(2); assertEquals(0.6311106578189364, dist.skewness(), 1e-10); dist = new Rayleigh(12); assertEquals(0.6311106578189364, dist.skewness(), 1e-10); } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Rayleigh(0.5); ContinuousDistribution d2 = new Rayleigh(0.6); ContinuousDistribution d4 = new Rayleigh(0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Rayleigh(0.5); ContinuousDistribution d2 = new Rayleigh(0.6); ContinuousDistribution d4 = new Rayleigh(0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
11,690
41.667883
557
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/StudentTTest.java
package jsat.distributions; import java.util.Arrays; import java.util.Random; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class StudentTTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testSample(){ System.out.println("hashCode"); StudentT d1 = new StudentT(1.9); StudentT d2 = new StudentT(2.1); Random rand = RandomUtil.getRandom(); for(StudentT d : Arrays.asList( d1, d2)) { Vec sample = d.sampleVec(100000, rand); assertEquals(d.mean(), sample.mean(), 1e-1); } } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new StudentT(0.5, 0.5,0.5); ContinuousDistribution d2 = new StudentT(0.6, 0.5,0.5); ContinuousDistribution d3 = new StudentT(0.5, 0.6,0.5); ContinuousDistribution d4 = new StudentT(0.5, 0.5,0.5); ContinuousDistribution d5 = new StudentT(0.5, 0.5,0.6); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d1.equals(d5)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new StudentT(0.5, 0.5,0.5); ContinuousDistribution d2 = new StudentT(0.6, 0.5,0.5); ContinuousDistribution d4 = new StudentT(0.5, 0.5,0.5); ContinuousDistribution d5 = new StudentT(0.5, 0.5,0.6); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); assertFalse(d1.hashCode()==d5.hashCode()); } }
2,203
25.554217
60
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/TruncatedDistributionTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions; import jsat.linear.Vec; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class TruncatedDistributionTest { static TruncatedDistribution test; static double[] vals; public TruncatedDistributionTest() { } @BeforeClass public static void setUpClass() { vals = new double[] { -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5 }; } @AfterClass public static void tearDownClass() { } @Before public void setUp() { test = new TruncatedDistribution(new Normal(-1, 2), 0, 3); } @After public void tearDown() { } /** * Test of pdf method, of class TruncatedDistribution. */ @Test public void testPdf() { System.out.println("pdf"); double[] expectedVals = new double[] { 0, 0, 0, 0.5268556714063524, 0.4233404250511103, 0.3195541179514373, 0.2265978006626938, 0.1509466771109160, 0.09446001683895860, 0 }; for(int i = 0; i < vals.length; i++) { assertEquals(expectedVals[i], test.pdf(vals[i]), 1e-4); } } @Test public void testCdf() { System.out.println("cdf"); double[] expectedVals = new double[] { 0, 0, 0, 0.2866123013348931, 0.5244537766181539, 0.7099254909327465, 0.8458397106527087, 0.9394339130936753, 1.000000000000000, 1.000000000000000 }; for(int i = 0; i < vals.length; i++) { assertEquals(expectedVals[i], test.cdf(vals[i]), 1e-4); } } /** * Test of invCdf method, of class TruncatedDistribution. */ @Test public void testInvCdf() { System.out.println("invCdf"); double[] expectedVals = new double[] { 0.1659278188451017, 0.3403064608805872, 0.5255330999226814, 0.7248810360893487, 0.9430469434588486, 1.187201184781877, 1.469235993294530, 1.811386537666672, 2.264206423889610 }; for (int i = 0; i < expectedVals.length; i++) { assertEquals(expectedVals[i], test.invCdf((i+1)/10.0), 1e-4); } } @Test public void testMean() { System.out.println("mean"); assertEquals(1.085986668284908, test.mean(), 1e-5); } @Test public void testVariance() { System.out.println("variance"); assertEquals(0.6011260859550334, test.variance(), 1e-5); } @Test public void testSkewness() { System.out.println("skewness"); assertEquals(0.5742049382125395, test.skewness(), 1e-5); } @Test public void testMedian() { System.out.println("median"); assertEquals(0.9430469434588486, test.median(), 1e-5); } //Not sure I'm going to support this... well see @Test public void testMode() { System.out.println("mode"); assertEquals(Math.nextUp(0.0), test.mode(), 1e-5); } /** * Test of min method, of class TruncatedDistribution. */ @Test public void testMin() { System.out.println("min"); assertEquals(0, test.min(), 1e-16);//can't be zero, but should be very close to it! } /** * Test of max method, of class TruncatedDistribution. */ @Test public void testMax() { System.out.println("max"); assertEquals(3, test.max(), 0.0); } }
4,480
23.756906
91
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/UniformTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class UniformTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new Uniform(0.5, 0.5); ContinuousDistribution d2 = new Uniform(0.6, 0.5); ContinuousDistribution d3 = new Uniform(0.5, 0.6); ContinuousDistribution d4 = new Uniform(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d2,d3); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new Uniform(0.5, 0.5); ContinuousDistribution d2 = new Uniform(0.6, 0.5); ContinuousDistribution d4 = new Uniform(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,429
23.655172
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/WeibullTest.java
package jsat.distributions; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class WeibullTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); ContinuousDistribution d1 = new LogNormal(0.5, 0.5); ContinuousDistribution d2 = new LogNormal(0.6, 0.5); ContinuousDistribution d3 = new LogNormal(0.5, 0.6); ContinuousDistribution d4 = new LogNormal(0.5, 0.5); Integer i = new Integer(1); assertFalse(d1.equals(d2)); assertFalse(d1.equals(d3)); assertFalse(d2.equals(d3)); assertFalse(d1.equals(i)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d4); assertEquals(d1, d1.clone()); } @Test public void testHashCode(){ System.out.println("hashCode"); ContinuousDistribution d1 = new LogNormal(0.5, 0.5); ContinuousDistribution d2 = new LogNormal(0.6, 0.5); ContinuousDistribution d4 = new LogNormal(0.5, 0.5); assertEquals(d1.hashCode(), d4.hashCode()); assertFalse(d1.hashCode()==d2.hashCode()); } }
1,450
24.017241
59
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/discrete/BinomialTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions.discrete; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class BinomialTest { static int[] testVals = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; public BinomialTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testLogPmf() { System.out.println("logPmf"); Binomial instance = new Binomial(); double[] expected_7_5 = new double[] { -4.85203026391962,-2.90612011486430,-1.80750782619619,-1.29668220243020, -1.29668220243020,-1.80750782619619,-2.90612011486430,-4.85203026391962, -Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE }; instance.setTrials(7); instance.setP(0.5); for(int i = 0; i < expected_7_5.length; i++) { assertEquals(expected_7_5[i], instance.logPmf(testVals[i]), 1e-4); } } @Test public void testPmf() { System.out.println("pmf"); Binomial instance = new Binomial(); double[] expected_7_5 = new double[] { 0.00781250000000000, 0.0546875000000000, 0.164062500000000, 0.273437500000000, 0.273437500000000, 0.164062500000000, 0.0546875000000000, 0.00781250000000000, 0, 0, 0 }; instance.setTrials(7); instance.setP(0.5); for(int i = 0; i < expected_7_5.length; i++) { assertEquals(expected_7_5[i], instance.pmf(testVals[i]), 1e-4); } } @Test public void testCdf() { System.out.println("cdf"); Binomial instance = new Binomial(); double[] expected_7_5 = new double[] { 0.00781250000000000, 0.0625000000000000, 0.226562500000000, 0.500000000000000, 0.773437500000000, 0.937500000000000, 0.992187500000000, 1.00000000000000, 1.00000000000000, 1.00000000000000, 1.00000000000000 }; instance.setTrials(7); instance.setP(0.5); for(int i = 0; i < expected_7_5.length; i++) { assertEquals(expected_7_5[i], instance.cdf(testVals[i]), 1e-4); //its hard to get the right value for the probabilities right on the line, so lets nudge them a little to make sure we map to the right spot double val; if(i == 0) val = instance.invCdf(expected_7_5[i]*.99); else val = instance.invCdf(expected_7_5[i-1]+(expected_7_5[i]-expected_7_5[i-1])*0.95); double expected = testVals[i] >= instance.max() ? instance.max() : testVals[i]; assertEquals(expected, val, 1e-3); } } @Test public void testSummaryStats() { System.out.println("stats"); Binomial instance = new Binomial(); //mean, median, variance, standard dev, skew double[] expected_7_5 = {3.50000000000000,3.00000000000000,1.75000000000000,1.32287565553230, 0}; instance.setTrials(7); instance.setP(0.5); assertEquals(expected_7_5[0], instance.mean(), 1e-4); assertEquals(expected_7_5[1], instance.median(), 1e-4); assertEquals(expected_7_5[2], instance.variance(), 1e-4); assertEquals(expected_7_5[3], instance.standardDeviation(), 1e-4); assertEquals(expected_7_5[4], instance.skewness(), 1e-4); } @Test public void testSample() { System.out.println("sample"); Binomial instance = new Binomial(); instance.setTrials(7); instance.setP(0.5); //use odd number so median is always an actual int Vec samples = instance.sampleVec(10001, RandomUtil.getRandom()); assertEquals(instance.mean(), samples.mean(), 2e-1); // assertEquals(instance.median(), samples.median(), 1e-1); double median = samples.median(); assertTrue(median == 3 || median == 4);//two vali values for this case assertEquals(instance.variance(), samples.variance(), 2e-1); assertEquals(instance.standardDeviation(), samples.standardDeviation(), 2e-1); assertEquals(instance.skewness(), samples.skewness(), 2e-1); } }
5,484
30.522989
177
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/discrete/PoissonTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions.discrete; import java.util.Arrays; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class PoissonTest { static int[] testVals = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; public PoissonTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testLogPmf() { System.out.println("logPmf"); Poisson instance = new Poisson(7); double[] expected_7 = new double[] { -7.00000000000000,-5.05408985094469,-3.80132688244932,-2.95402902206212,-2.39441323412669,-2.05794099750548,-1.90379031767822,-1.90379031767822,-2.03732171030274,-2.28863613858365,-2.64531108252238 }; for(int i = 0; i < expected_7.length; i++) { assertEquals(expected_7[i], instance.logPmf(testVals[i]), 1e-4); } } @Test public void testPmf() { System.out.println("pmf"); Poisson instance = new Poisson(7); double[] expected_7 = new double[] { 0.000911881965554516,0.00638317375888161,0.0223411081560856,0.0521292523641998,0.0912261916373497,0.127716668292290,0.149002779674338,0.149002779674338,0.130377432215046,0.101404669500591,0.0709832686504137 }; for(int i = 0; i < expected_7.length; i++) { assertEquals(expected_7[i], instance.pmf(testVals[i]), 1e-4); } } @Test public void testCdf() { System.out.println("cdf"); Poisson instance = new Poisson(7); double[] expected_7 = new double[] { 0.000911881965554516,0.00729505572443613,0.0296361638805218,0.0817654162447216,0.172991607882071,0.300708276174361,0.449711055848699,0.598713835523037,0.729091267738082,0.830495937238673,0.901479205889087 }; for(int i = 0; i < expected_7.length; i++) { assertEquals(expected_7[i], instance.cdf(testVals[i]), 1e-4); //its hard to get the right value for the probabilities right on the line, so lets nudge them a little to make sure we map to the right spot double val; if(i == 0) val = instance.invCdf(expected_7[i]*.99); else val = instance.invCdf(expected_7[i-1]+(expected_7[i]-expected_7[i-1])*0.95); double expected = testVals[i] >= instance.max() ? instance.max() : testVals[i]; assertEquals(expected, val, 1e-3); } } @Test public void testSummaryStats() { System.out.println("stats"); Poisson instance = new Poisson(7); //mean, median, variance, standard dev, skew double[] expected_7_5 = {7.00000000000000,7.00000000000000,7.00000000000000,2.64575131106459,0.377964473009227}; assertEquals(expected_7_5[0], instance.mean(), 1e-4); assertEquals(expected_7_5[1], instance.median(), 1e-4); assertEquals(expected_7_5[2], instance.variance(), 1e-4); assertEquals(expected_7_5[3], instance.standardDeviation(), 1e-4); assertEquals(expected_7_5[4], instance.skewness(), 1e-4); } @Test public void testSample() { System.out.println("sample"); //Poisson can get wonked on variance, so larger range used there /* * "however in practice, the observed variance is usually larger than * the theoretical variance and in the case of Poisson, larger than its * mean. This is known as overdispersion, an important concept that * occurs with discrete data" */ // for(int d = 1; d < 100000000; d*=2) // { // long start = System.currentTimeMillis(); // Vec samples = new Poisson(d).sampleVec(100000, RandomUtil.getRandom()); // long end = System.currentTimeMillis(); // System.out.println(d + ": " + (end-start)); // } for(Poisson instance : Arrays.asList(new Poisson(2), new Poisson(20), new Poisson(40), new Poisson(200))) { System.out.println(instance.mean()); Vec samples = instance.sampleVec(10000, RandomUtil.getRandom()); assertEquals(instance.mean(), samples.mean(), instance.getLambda()*2e-1); assertEquals(instance.median(), samples.median(), instance.getLambda()*2e-1); assertEquals(0.0, (instance.standardDeviation()-samples.standardDeviation())/instance.standardDeviation(), 0.1); assertEquals(instance.skewness(), samples.skewness(), instance.getLambda()*2e-1); } } }
5,916
32.241573
218
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/discrete/UniformDiscreteTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions.discrete; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class UniformDiscreteTest { static int[] testVals = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; public UniformDiscreteTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testLogPmf() { System.out.println("logPmf"); UniformDiscrete instance = new UniformDiscrete(2, 9); double[] expected_7 = new double[] { -Double.MAX_VALUE,-Double.MAX_VALUE,-2.07944154167984,-2.07944154167984,-2.07944154167984,-2.07944154167984,-2.07944154167984,-2.07944154167984,-2.07944154167984,-2.07944154167984,-Double.MAX_VALUE }; for(int i = 0; i < expected_7.length; i++) { assertEquals(expected_7[i], instance.logPmf(testVals[i]), 1e-4); } } @Test public void testPmf() { System.out.println("pmf"); UniformDiscrete instance = new UniformDiscrete(2, 9); double[] expected_7 = new double[] { 0,0,0.125000000000000,0.125000000000000,0.125000000000000,0.125000000000000,0.125000000000000,0.125000000000000,0.125000000000000,0.125000000000000,0 }; for(int i = 0; i < expected_7.length; i++) { assertEquals(expected_7[i], instance.pmf(testVals[i]), 1e-4); } } @Test public void testCdf() { System.out.println("cdf"); UniformDiscrete instance = new UniformDiscrete(2, 9); double[] expected_7 = new double[] { 0,0,0.125000000000000,0.250000000000000,0.375000000000000,0.500000000000000,0.625000000000000,0.750000000000000,0.875000000000000,1.00000000000000,1.00000000000000 }; for(int i = 0; i < expected_7.length; i++) { assertEquals(expected_7[i], instance.cdf(testVals[i]), 1e-4); //its hard to get the right value for the probabilities right on the line, so lets nudge them a little to make sure we map to the right spot double val; if(i == 0) val = instance.invCdf(expected_7[i]*.99); else val = instance.invCdf(expected_7[i-1]+(expected_7[i]-expected_7[i-1])*0.95); double expected; if(testVals[i] >= instance.max()) expected = instance.max(); else if(testVals[i] <= instance.min()) expected = instance.min(); else expected = testVals[i]; assertEquals(expected, val, 1e-3); } } @Test public void testSummaryStats() { System.out.println("stats"); UniformDiscrete instance = new UniformDiscrete(2, 9); //mean, median, variance, standard dev, skew double[] expected_7_5 = {5.50000000000000, 5.00000000000000, 5.25000000000000, 2.29128784747792, 0}; assertEquals(expected_7_5[0], instance.mean(), 1e-4); assertEquals(expected_7_5[1], instance.median(), 1e-4); assertEquals(expected_7_5[2], instance.variance(), 1e-4); assertEquals(expected_7_5[3], instance.standardDeviation(), 1e-4); assertEquals(expected_7_5[4], instance.skewness(), 1e-4); } @Test public void testSample() { System.out.println("sample"); UniformDiscrete instance = new UniformDiscrete(2, 9); Vec samples = instance.sampleVec(10000, RandomUtil.getRandom()); assertEquals(instance.mean(), samples.mean(), 2e-1); // assertEquals(instance.median(), samples.median(), 2e-1); assertTrue(instance.median() == 5 || instance.median() == 6);//both are valid for this case assertEquals(instance.variance(), samples.variance(), 2e-1); assertEquals(instance.standardDeviation(), samples.standardDeviation(), 2e-1); assertEquals(instance.skewness(), samples.skewness(), 2e-1); } }
5,269
30.939394
209
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/discrete/ZipfTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.distributions.discrete; import java.util.Random; import jsat.linear.DenseVector; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class ZipfTest { static Zipf Zipf_20k_half = null; static Zipf Zipf_20k_2 = null; static Zipf Zipf_inf_half = null; static Zipf Zipf_inf_2 = null; static Zipf[] Zs = null; static final int[] xs = new int[]{0,1,2,3,4,5,10,100,1000,10000,20000,20001}; public ZipfTest() { } @BeforeClass public static void setUpClass() { Zipf_20k_half = new Zipf(20000, 0.5); Zipf_20k_2 = new Zipf(20000, 2); Zipf_inf_half = new Zipf(0.5); Zipf_inf_2 = new Zipf(2); Zs = new Zipf[] { Zipf_20k_half, Zipf_20k_2, Zipf_inf_half, Zipf_inf_2, }; } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setCardinality method, of class Zipf. */ @Test public void testGetCardinality() { System.out.println("setCardinality"); assertEquals(20000, Zipf_20k_half.getCardinality(), 0); assertEquals(20000, Zipf_20k_2.getCardinality(), 0); assertEquals(Double.POSITIVE_INFINITY, Zipf_inf_half.getCardinality(), 0); assertEquals(Double.POSITIVE_INFINITY, Zipf_inf_2.getCardinality(), 0); } /** * Test of pmf method, of class Zipf. */ @Test public void testPmf() { System.out.println("pmf"); double[][] expected = new double[][] { {0,0.38487689516722987426,0.13607453124738610253,0.074069593009889181126,0.048109611895903734283,0.034424436022519451529,0.012170876075022983100,0.00038487689516722987426,0.000012170876075022983100,3.8487689516722987426e-7,1.3607453124738610253e-7,0}, {0,0.83190737344575156199,0.10398842168071894525,0.030811384201694502296,0.012998552710089868156,0.0066552589875660124959,0.00083190737344575156199,8.3190737344575156199e-7,8.3190737344575156199e-10,8.3190737344575156199e-13,1.0398842168071894525e-13,0}, {0,0.38279338399942656225,0.13533789880967029021,0.073668621098692236550,0.047849172999928320281,0.034238081118395924455,0.012104989666816425649,0.00038279338399942656225,0.000012104989666816425649,3.8279338399942656225e-7,1.3533789880967029021e-7,1.3532774910161896123e-7}, {0,0.83190737258070746868,0.10398842157258843359,0.030811384169655832173,0.012998552696573554198,0.0066552589806456597495,0.00083190737258070746868,8.3190737258070746868e-7,8.3190737258070746868e-10,8.3190737258070746868e-13,1.0398842157258843359e-13,1.0397282486904889313e-13} }; for(int z = 0; z < Zs.length; z++) { Zipf zipf = Zs[z]; for(int i = 0; i < xs.length; i++) { double ex = expected[z][i]; double acc = zipf.pmf(xs[i]); double err; if(ex == 0) err = ex-acc; else err = (ex-acc)/ex; assertEquals(0, err, 1e-3); } } } /** * Test of cdf method, of class Zipf. */ @Test public void testCdf() { System.out.println("cdf"); double[][] expected = new double[][] { {0,0.38487689516722987426,0.52095142641461597679,0.59502101942450515792,0.64313063132040889220,0.67755506734292834373,0.76795891437272322068,0.92865949153851453895,0.98110724498011254401,0.99774556774377231118,1.0000000000000000000,1.0000000000000000000}, {0,0.83190737344575156199,0.93589579512647050724,0.96670717932816500953,0.97970573203825487769,0.98636099102582089019,0.99623568881949349504,0.99995881954514754426,0.99999958550189121097,0.99999999688071128956,1.0000000000000000000,1.0000000000000000000}, {0,0.38279338399942656225,0.51813128280909685246,0.59179990390778908901,0.63964907690771740929,0.67388715802611333375,0.76380160850531216055,0.92363224140736199479,0.97579607164807706923,0.99234432371191855118,0.99458655171571673136,0.99458668704346583298}, {0,0.83190737258070746868,0.93589579415329590227,0.96670717832295173444,0.97970573101952528864,0.98636099000017094839,0.99623568778357552428,0.99995881850535814221,0.99999958446205941916,0.99999999584087906999,0.99999999896016777719,0.99999999896027175001} }; for(int z = 0; z < Zs.length; z++) { Zipf zipf = Zs[z]; for(int i = 0; i < xs.length; i++) { double ex = expected[z][i]; double acc = zipf.cdf(xs[i]); double err; if(ex == 0) err = ex-acc; else err = (ex-acc)/ex; assertEquals(0, err, 1e-3); ///and test inverse CDF while we are here // System.out.println(xs[i] + ", " + zipf.invCdf(ex) + ", " + zipf.invCdf(acc)); assertEquals(xs[i], zipf.invCdf(ex), 1.0);//I'll let you be off by one... } } } /** * Test of mean method, of class Zipf. */ @Test public void testMean() { System.out.println("mean"); double[] expected = new double[] { 108.29892902835748493,1.3683911847143409720,Double.POSITIVE_INFINITY,1.3684327776202058757 }; for(int i = 0; i < Zs.length; i++) assertEquals(expected[i], Zs[i].mean(), 1e-3); } /** * Test of mode method, of class Zipf. */ @Test public void testMode() { System.out.println("mode"); double[] expected = new double[] { 1, 1, 1, 1 }; for(int i = 0; i < Zs.length; i++) assertEquals(expected[i], Zs[i].mode(), 1e-3); } /** * Test of variance method, of class Zipf. */ @Test public void testVariance() { System.out.println("variance"); double[] expected = new double[] { 714029.31029974343795,6.8465006485901065799,Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY }; for(int i = 0; i < Zs.length; i++) assertEquals(expected[i], Zs[i].variance(), 1e-3); assertEquals(0.13066023147512419133, new Zipf(3.5).variance(), 1e-3); } /** * Test of skewness method, of class Zipf. */ @Test public void testSkewness() { System.out.println("skewness"); double[] expected = new double[] { 14.048173897535615783,927.04482492331320690,Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY }; for(int i = 0; i < Zs.length; i++) assertEquals(expected[i], Zs[i].skewness(), 1e-3); assertEquals(17.763027886751897884, new Zipf(3.5).skewness(), 1e-3); } /** * Test of min method, of class Zipf. */ @Test public void testMin() { System.out.println("min"); double[] expected = new double[] { 1, 1, 1, 1 }; for(int i = 0; i < Zs.length; i++) assertEquals(expected[i], Zs[i].min(), 0); } /** * Test of max method, of class Zipf. */ @Test public void testMax() { System.out.println("max"); double[] expected = new double[] { 20000, 20000, Double.POSITIVE_INFINITY,Double.POSITIVE_INFINITY }; for(int i = 0; i < Zs.length; i++) assertEquals(expected[i], Zs[i].max(), 0); } @Test public void testSampling() { System.out.println("max"); Random rand =RandomUtil.getRandom(); //only test the 2 cases where mean and variance are well defined for(int i = 0; i < Zs.length/2; i++) { Zipf zipf = Zs[i]; DenseVector samples = zipf.sampleVec(10000, rand); double relErrMean = (zipf.mean()-samples.mean())/zipf.mean(); assertEquals(0, relErrMean, 0.1); double relErrStd = (zipf.standardDeviation()-samples.standardDeviation())/zipf.standardDeviation(); assertEquals(0, relErrStd, 0.5); } } }
9,406
32.596429
289
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/empirical/KernelDensityEstimatorTest.java
package jsat.distributions.empirical; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.ArrayList; import java.util.List; import java.util.Random; import jsat.distributions.ContinuousDistribution; import jsat.distributions.empirical.kernelfunc.GaussKF; import jsat.distributions.empirical.kernelfunc.UniformKF; import jsat.linear.DenseVector; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class KernelDensityEstimatorTest { static List<ContinuousDistribution> unequal = new ArrayList<ContinuousDistribution>(); static ContinuousDistribution d1; static ContinuousDistribution d2; static ContinuousDistribution d3; static ContinuousDistribution d4; private static final int vecSize = 1000; @BeforeClass public static void setUpBeforeClass() throws Exception { Random r1 = new Random(5079392926462355615L); Random r2 = new Random(7628304882101574242L); double[] vec1 = new double[vecSize]; double[] vec2 = new double[vecSize]; double[] vec3 = new double[vecSize]; for(int i = 0;i<vecSize;i++){ double temp = r1.nextDouble(); vec1[i]=temp; vec2[i]=r2.nextDouble(); vec3[i]=temp; } d1 = new KernelDensityEstimator(new DenseVector(vec1)); d2 = new KernelDensityEstimator(new DenseVector(vec3)); d3 = new KernelDensityEstimator(new DenseVector(vec1), GaussKF.getInstance(), 2, vec1); d4 = new KernelDensityEstimator(new DenseVector(vec1), GaussKF.getInstance(), 2, vec1); unequal.add(d1); unequal.add(d3); unequal.add(new KernelDensityEstimator(new DenseVector(vec2))); unequal.add(new KernelDensityEstimator(new DenseVector(vec1), GaussKF.getInstance(), 1, vec1)); unequal.add(new KernelDensityEstimator(new DenseVector(vec1), UniformKF.getInstance(), 2, vec1)); unequal.add(new KernelDensityEstimator(new DenseVector(vec1), GaussKF.getInstance(), 2, vec2)); unequal.add(new KernelDensityEstimator(new DenseVector(vec2), GaussKF.getInstance(), 2, vec1)); unequal.add(new KernelDensityEstimator(new DenseVector(new double[]{1,3,5}))); unequal.add(new KernelDensityEstimator(new DenseVector(new double[]{0,3,6}))); unequal.add(new KernelDensityEstimator(new DenseVector(new double[]{1,1,1}))); unequal.add(new KernelDensityEstimator(new DenseVector(new double[]{1,1,1,1,1}))); unequal.add(new KernelDensityEstimator(new DenseVector(new double[]{2,2,2,2,3,4,4,4,4}))); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testEquals(){ System.out.println("equals"); Integer k = new Integer(1); assertFalse(d1.equals(k)); assertFalse(d1.equals(null)); assertEquals(d1, d1); assertEquals(d1, d2); assertEquals(d3, d4); assertEquals(d1, d1.clone()); for(int i = 0;i<unequal.size();i++){ for(int j = 0;j<unequal.size();j++){ if(i!=j){ assertFalse(unequal.get(i).equals(unequal.get(j))); } } } } @Test public void testHashCode(){ System.out.println("hashCode"); assertEquals(d1.hashCode(), d2.hashCode()); assertFalse(d1.hashCode()==d3.hashCode()); } }
3,366
31.375
99
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/multivariate/DirichletTest.java
package jsat.distributions.multivariate; import java.util.List; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static jsat.linear.DenseVector.*; /** * * @author Edward Raff */ public class DirichletTest { public DirichletTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of logPdf method, of class Dirichlet. */ @Test public void testLogPdf() { System.out.println("logPdf"); assertEquals(Math.log(18.0/25.0), new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(3.0/10.0, 2.0/10.0, 5.0/10.0)), 1e-13); assertEquals(Math.log(42.0/25.0), new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(7.0/10.0, 2.0/10.0, 1.0/10.0)), 1e-13); assertEquals(Math.log(96.0/25.0), new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); //If it dosnt sum to 1, its not a possible value assertEquals(-Double.MAX_VALUE, new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(5.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(-Double.MAX_VALUE, new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(1.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(-Double.MAX_VALUE, new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(-4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(-Double.MAX_VALUE, new Dirichlet(toDenseVec(2, 3, 1)).logPdf(toDenseVec(-4.0/10.0, 4.0/10.0, 10.0/10.0)), 1e-13); } /** * Test of pdf method, of class Dirichlet. */ @Test public void testPdf() { System.out.println("pdf"); assertEquals(18.0/25.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(3.0/10.0, 2.0/10.0, 5.0/10.0)), 1e-13); assertEquals(42.0/25.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(7.0/10.0, 2.0/10.0, 1.0/10.0)), 1e-13); assertEquals(96.0/25.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); //If it dosnt sum to 1, its not a possible value assertEquals(0.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(5.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(0.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(1.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(0.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(-4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(0.0, new Dirichlet(toDenseVec(2, 3, 1)).pdf(toDenseVec(-4.0/10.0, 4.0/10.0, 10.0/10.0)), 1e-13); } /** * Test of setUsingData method, of class Dirichlet. */ @Test public void testSetUsingData() { System.out.println("setUsingData"); List<Vec> dataSet = null; Dirichlet instance = new Dirichlet(DenseVector.toDenseVec(2.5, 2.5, 2.5)); dataSet = instance.sample(5000, new Random(1)); Dirichlet setI = new Dirichlet(DenseVector.toDenseVec(2.0, 2.0, 2.0)); setI.setUsingData(dataSet); //5% error would be fine Vec alpha = setI.getAlphas(); for(int i = 0; i < alpha.length(); i++ ) assertEquals(0, Math.abs(alpha.get(i)-2.5)/2.5, 0.05); } }
3,548
34.848485
134
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/multivariate/NormalMTest.java
package jsat.distributions.multivariate; import java.util.List; import java.util.Random; import jsat.linear.DenseMatrix; import jsat.linear.DenseVector; import jsat.linear.Matrix; import jsat.linear.MatrixStatistics; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NormalMTest { Vec mean; Matrix covariance; public NormalMTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { mean = DenseVector.toDenseVec(1, -1); covariance = new DenseMatrix(new double[][] { {0.9, 0.4}, {0.4, 0.3} }); } /** * Test of setCovariance method, of class NormalM. */ @Test public void testSetCovariance() { System.out.println("setCovariance"); NormalM normalM = new NormalM(mean, covariance); Matrix t1 = Matrix.eye(3);//Should fail, too big Matrix t2 = new DenseMatrix(2, 3);//Should fail, not square Matrix t3 = new DenseMatrix(3, 2);//Should fail, not square Matrix[] shouldFail = new Matrix[] {t1, t2, t3}; for (Matrix badMatrix : shouldFail) try { normalM.setCovariance(badMatrix); fail("Matrix was invalid, should have caused an exception"); } catch (ArithmeticException ex) { //Good! Should fail } } @Test public void testDiag() { System.out.println("setCovariance"); Vec diag = DenseVector.random(mean.length()); Matrix D = Matrix.diag(diag); NormalM normalM_1 = new NormalM(mean, diag); NormalM normalM_2 = new NormalM(mean, D); Random rand = RandomUtil.getRandom(); List<Vec> s1 = normalM_1.sample(10000, rand); List<Vec> s2 = normalM_2.sample(10000, rand); Vec x1 = MatrixStatistics.meanVector(s1); Vec x2 = MatrixStatistics.meanVector(s2); assertTrue(x1.equals(x2, 0.05)); assertTrue(MatrixStatistics.covarianceMatrix(x1, s1).equals(MatrixStatistics.covarianceMatrix(x2, s2), 0.05)); for(Vec x : s1) assertEquals(normalM_2.logPdf(x), normalM_1.logPdf(x), 0.05); } /** * Test of logPdf method, of class NormalM. */ @Test public void testLogPdf() { System.out.println("logPdf"); NormalM normalM = new NormalM(mean, covariance); Vec[] xVals = new Vec[] { DenseVector.toDenseVec(1, 0), DenseVector.toDenseVec(1, 1), DenseVector.toDenseVec(0, 1), DenseVector.toDenseVec(-1, 0), DenseVector.toDenseVec(0, -1), DenseVector.toDenseVec(-1, -1), DenseVector.toDenseVec(0, -11), DenseVector.toDenseVec(-11, -11), DenseVector.toDenseVec(1, -1), DenseVector.toDenseVec(-1, 1), }; double[] pVals = new double[] { -4.825148700723577e+000, -1.709787597345085e+001, -2.573423960981450e+001, -1.755242142799632e+001, -2.097875973450849e+000, -6.188785064359943e+000, -3.748251487007237e+002, -1.698251487007236e+002, -7.342396098144846e-001, -3.709787597345088e+001, }; for(int i = 0; i < pVals.length; i++) System.out.println(pVals[i] + " " + normalM.logPdf(xVals[i])); for(int i = 0; i < pVals.length; i++) assertEquals(pVals[i], normalM.logPdf(xVals[i]), 1e-12);//Slightly smaller error b/c the absolute error can get large, but relative should still be good } /** * Test of pdf method, of class NormalM. */ @Test public void testPdf() { System.out.println("pdf"); NormalM normalM = new NormalM(mean, covariance); Vec[] xVals = new Vec[] { DenseVector.toDenseVec(1, 0), DenseVector.toDenseVec(1, 1), DenseVector.toDenseVec(0, 1), DenseVector.toDenseVec(-1, 0), DenseVector.toDenseVec(0, -1), DenseVector.toDenseVec(-1, -1), DenseVector.toDenseVec(0, -11), DenseVector.toDenseVec(-11, -11), DenseVector.toDenseVec(1, -1), DenseVector.toDenseVec(-1, 1), }; double[] pVals = new double[] { 8.025360404763595e-003, 3.753935553147029e-008, 6.664410523370948e-012, 2.382759609937137e-008, 1.227168053837841e-001, 2.052318674310052e-003, 1.642503261891859e-163, 1.761469107148436e-074, 4.798702088783484e-001, 7.737437863769670e-017, }; for(int i = 0; i < pVals.length; i++) assertEquals(pVals[i], normalM.pdf(xVals[i]), 1e-14); } }
5,103
29.562874
164
java
JSAT
JSAT-master/JSAT/test/jsat/distributions/multivariate/SymmetricDirichletTest.java
package jsat.distributions.multivariate; import java.util.List; import java.util.Random; import jsat.linear.Vec; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static jsat.linear.DenseVector.*; /** * * @author Edward Raff */ public class SymmetricDirichletTest { public SymmetricDirichletTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of clone method, of class SymmetricDirichlet. */ @Test public void testClone() { System.out.println("clone"); SymmetricDirichlet first = new SymmetricDirichlet(2.5, 3); SymmetricDirichlet clone = first.clone(); first.setAlpha(1.5); assertEquals(2.5, clone.getAlpha(), 0); assertEquals(1.5, first.getAlpha(), 0); } /** * Test of logPdf method, of class SymmetricDirichlet. */ @Test public void testLogPdf() { System.out.println("logPdf"); assertEquals(Math.log(18.0/5.0), new SymmetricDirichlet(2.0, 3).logPdf(toDenseVec(3.0/10.0, 2.0/10.0, 5.0/10.0)), 1e-13); assertEquals(Math.log(2.0), new SymmetricDirichlet(1.0, 3).logPdf(toDenseVec(7.0/10.0, 2.0/10.0, 1.0/10.0)), 1e-13); assertEquals(Math.log(16128.0/3125.0), new SymmetricDirichlet(3.0, 3).logPdf(toDenseVec(4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); //If it dosnt sum to 1, its not a possible value assertEquals(-Double.MAX_VALUE, new SymmetricDirichlet(2.0, 3).logPdf(toDenseVec(5.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(-Double.MAX_VALUE, new SymmetricDirichlet(2.0, 3).logPdf(toDenseVec(1.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(-Double.MAX_VALUE, new SymmetricDirichlet(2.0, 3).logPdf(toDenseVec(-4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(-Double.MAX_VALUE, new SymmetricDirichlet(2.0, 3).logPdf(toDenseVec(-4.0/10.0, 4.0/10.0, 10.0/10.0)), 1e-13); } /** * Test of pdf method, of class SymmetricDirichlet. */ @Test public void testPdf() { System.out.println("pdf"); assertEquals(18.0/5.0, new SymmetricDirichlet(2.0, 3).pdf(toDenseVec(3.0/10.0, 2.0/10.0, 5.0/10.0)), 1e-13); assertEquals(2.0, new SymmetricDirichlet(1.0, 3).pdf(toDenseVec(7.0/10.0, 2.0/10.0, 1.0/10.0)), 1e-13); assertEquals(16128.0/3125.0, new SymmetricDirichlet(3.0, 3).pdf(toDenseVec(4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); //If it dosnt sum to 1, its not a possible value assertEquals(0.0, new SymmetricDirichlet(2.0, 3).pdf(toDenseVec(5.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(0.0, new SymmetricDirichlet(2.0, 3).pdf(toDenseVec(1.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(0.0, new SymmetricDirichlet(2.0, 3).pdf(toDenseVec(-4.0/10.0, 4.0/10.0, 2.0/10.0)), 1e-13); assertEquals(0.0, new SymmetricDirichlet(2.0, 3).pdf(toDenseVec(-4.0/10.0, 4.0/10.0, 10.0/10.0)), 1e-13); } /** * Test of setUsingData method, of class SymmetricDirichlet. */ @Test public void testSetUsingData() { System.out.println("setUsingData"); List<Vec> dataSet = null; SymmetricDirichlet instance = new SymmetricDirichlet(2.5, 3); dataSet = instance.sample(500, new Random(1)); SymmetricDirichlet setI = new SymmetricDirichlet(1.0, 3); setI.setUsingData(dataSet); //We will be happy with %5 accuracy assertEquals(0, (setI.getAlpha()-2.5)/2.5, 0.05); } }
3,837
33.890909
136
java
JSAT
JSAT-master/JSAT/test/jsat/driftdetectors/ADWINTest.java
package jsat.driftdetectors; import java.util.List; import java.util.Random; import jsat.distributions.Normal; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ADWINTest { public ADWINTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testAddSample_double_GenericType() { System.out.println("addSample"); Normal normal_0_1 = new Normal(0, 1); Normal normal_1_1 = new Normal(1, 1); Normal normal_2_1 = new Normal(2, 1); Random rand = new XORWOW(123); ADWIN<Integer> adwin = new ADWIN<Integer>(0.01, 100); //Start should not ever observe a false positive for(int i = 0; i < 400; i++) if(adwin.addSample(normal_0_1.invCdf(rand.nextDouble()), i)) assertFalse(adwin.isDrifting()); assertEquals(normal_0_1.mean(), adwin.getMean(), 0.25);//lots of samples, should be close assertEquals(400, adwin.getWidnowLength()); //drift up { boolean drifted = false; for(int i = 0; i < 400; i++) if(adwin.addSample(normal_1_1.invCdf(rand.nextDouble()), i)) { assertTrue(adwin.getDriftAge() < i+30); assertFalse(drifted); assertEquals(normal_0_1.mean(), adwin.getOldMean(), 0.25); assertEquals(normal_1_1.mean(), adwin.getNewMean(), 1.5);//few samples, lose bound List<Integer> driftedHistory = adwin.getDriftedHistory(); assertEquals(Math.min(adwin.getMaxHistory(), adwin.getDriftAge()), driftedHistory.size()); for(int j = 1; j <driftedHistory.size(); j++) { assertTrue(driftedHistory.get(j-1) > driftedHistory.get(j)); if(driftedHistory.get(j) == 0) break; } adwin.driftHandled(true); drifted = true; } assertTrue(drifted); assertEquals(normal_1_1.mean(), adwin.getMean(), 0.35); } adwin = adwin.clone(); //drift and drop NEW values this time, ie: stop ourselves from going back to where we were { boolean drifted = false; for(int i = 0; i < 400 && !drifted; i++) if(adwin.addSample(normal_0_1.invCdf(rand.nextDouble()), i)) { assertTrue(adwin.getDriftAge() < i+30); assertFalse(drifted); assertEquals(normal_1_1.mean(), adwin.getOldMean(), 0.35); assertEquals(normal_0_1.mean(), adwin.getNewMean(), 1.5);//few samples, lose bound List<Integer> driftedHistory = adwin.getDriftedHistory(); assertEquals(Math.min(adwin.getMaxHistory(), adwin.getDriftAge()), driftedHistory.size()); for(int j = 1; j <driftedHistory.size(); j++) { assertTrue(driftedHistory.get(j-1) > driftedHistory.get(j)); if(driftedHistory.get(j) == 0) break; } adwin.driftHandled(false); drifted = true; } assertEquals(normal_1_1.mean(), adwin.getMean(), 1.5);//few samples, lose bound } //drift up again { boolean drifted = false; for(int i = 0; i < 400; i++) if(adwin.addSample(normal_2_1.invCdf(rand.nextDouble()), i)) { assertTrue(adwin.getDriftAge() < i+30); assertFalse(drifted); assertEquals(normal_1_1.mean(), adwin.getOldMean(), 0.35); assertEquals(normal_2_1.mean(), adwin.getNewMean(), 1.5);//few samples, lose bound List<Integer> driftedHistory = adwin.getDriftedHistory(); assertEquals(Math.min(adwin.getMaxHistory(), adwin.getDriftAge()), driftedHistory.size()); for(int j = 1; j <driftedHistory.size(); j++) { assertTrue(driftedHistory.get(j-1) > driftedHistory.get(j)); if(driftedHistory.get(j) == 0) break; } adwin.driftHandled(); drifted = true; } assertTrue(drifted); assertEquals(normal_2_1.mean(), adwin.getMean(), 0.35); } } }
5,205
34.657534
110
java
JSAT
JSAT-master/JSAT/test/jsat/driftdetectors/DDMTest.java
package jsat.driftdetectors; import java.util.List; import java.util.Random; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class DDMTest { public DDMTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of addSample method, of class DDM. */ @Test public void testAddSample_double_GenericType() { System.out.println("addSample"); Random rand = new XORWOW(123); DDM<Integer> ddm = new DDM<Integer>(); //Start should not ever observe a false positive for(int i = 0; i < 50; i++) if(ddm.addSample(rand.nextDouble() < 0.8, i)) assertFalse(ddm.isDrifting()); assertEquals(0.8, ddm.getSuccessRate(), 0.15); //Increase ina ccuracy, still shouldn't trigger for(int i = 0; i < 50; i++) if(ddm.addSample(rand.nextDouble() < 0.9, i)) assertFalse(ddm.isDrifting()); boolean seenWarning = false; boolean seenDrift = false; //Now we should see an error for(int i = 1; i <= 100; i++) if(ddm.addSample(rand.nextDouble() < 0.7, -i))//negative to diferentiate from before { if(ddm.isWarning()) { seenWarning = true; } else if(ddm.isDrifting()) { assertTrue(i < 40);//got to detect it fast enought assertFalse(seenDrift); assertTrue(seenWarning); List<Integer> drifted = ddm.getDriftedHistory(); //make sure there is some history assertTrue(drifted.size() > 5); assertTrue(ddm.getDriftAge() > 5); assertTrue(ddm.getDriftAge() == drifted.size()); for(int j = 0; j < drifted.size(); j++) { assertTrue(drifted.get(j) < 0); if(j < drifted.size()-1) assertTrue(drifted.get(j) < drifted.get(j+1)); } ddm.driftHandled(); seenDrift = true; } } assertEquals(0.7, ddm.getSuccessRate(), 0.15); } }
2,705
26.06
96
java
JSAT
JSAT-master/JSAT/test/jsat/io/CSVTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.io; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import jsat.DataSet; import jsat.SimpleDataSet; import jsat.classifiers.*; import jsat.linear.*; import jsat.regression.RegressionDataSet; import jsat.utils.DoubleList; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class CSVTest { public CSVTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test @SuppressWarnings("unchecked") public void testReadNumericOnly() throws Exception { System.out.println("read (numeric only features)"); List<String> testLines = new ArrayList<String>(); List<Double> expetedLabel = new DoubleList(); List<Vec> expectedVec = new ArrayList<Vec>(); testLines.add("-1,0.0, 3.0, 0.0, 0.0, 0.0");//normal line expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 0.0, 0.0, 0.0)); testLines.add("1,3.0,0.0,0.0,0.0,0.0"); //line ends in a space expetedLabel.add(1.0); expectedVec.add(DenseVector.toDenseVec( 3.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("2,0.0, 3.0, 3.0, 1.0, 0.0");//normal line with many values expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 1.0, 0.0)); testLines.add("-1, 0.0, 3.0, 0.0, 2.0, 0.0");//extra spaces in between expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 0.0, 2.0, 0.0)); testLines.add("1,0.0, 0.0, 0.0, 0.0, 0.0 "); ///empty line expetedLabel.add(1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add(" 2 , 0.0, 0.0, 0.0, 0.0, 0.0"); // empty line with space expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("3, 0.0, 0.0, 0.0, 0.0, 0.0"); expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("3,0.0, 0.0, 0.0, 0.0, 0.0"); expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("-1, 10.0, 0.0, \t 2.0, 0.0, 0.0"); //extra spaces at the end expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 10.0, 0.0, 2.0, 0.0, 0.0)); testLines.add("2, 0.0, 3.0, 3.0, 0.0, 1.0");//normal line with many values expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 0.0, 1.0)); String[] newLines = new String[]{"\n", "\n\r", "\r\n", "\n\r\n"}; char comment = '#'; for (boolean endInNewLines : new boolean[]{true, false }) for(boolean endsInComments : new boolean[]{true, false}) for (String newLine : newLines) for (int i = 0; i < testLines.size(); i++) { StringBuilder input = new StringBuilder(); for (int j = 0; j < i; j++) { input.append(testLines.get(j)); if(endsInComments) { input.append(comment); input.append(testLines.get(j)); } input.append(newLine); } input.append(testLines.get(i)); if (endsInComments) { input.append(comment); input.append(testLines.get(i)); } if (endInNewLines) input.append(newLine); @SuppressWarnings("unchecked") RegressionDataSet regData = CSV.readR(0, new StringReader(input.toString()), ',', 0, comment, Collections.EMPTY_SET); SimpleDataSet smpData = CSV.read(new StringReader(input.toString()), ',', 0, comment, Collections.EMPTY_SET); ClassificationDataSet catData = CSV.readC(0, new StringReader(input.toString()), ',', 0, comment, Collections.EMPTY_SET); assertEquals(i + 1, regData.size()); for (int j = 0; j < i + 1; j++) { Vec ex_vec = expectedVec.get(j); double ex_target = expetedLabel.get(j); assertEquals(ex_target, regData.getTargetValue(j), 0.0); assertTrue(ex_vec.equals(regData.getDataPoint(j).getNumericalValues())); //simpled dataset test Vec ex_vec_inc_target = new ConcatenatedVec(new ConstantVector(ex_target, 1), ex_vec); assertTrue(ex_vec_inc_target.equals(smpData.getDataPoint(j).getNumericalValues())); //classification test assertTrue(ex_vec.equals(catData.getDataPoint(j).getNumericalValues())); int pred_indx = catData.getDataPointCategory(j); assertEquals(Integer.toString((int) ex_target) , catData.getPredicting().getOptionName(pred_indx)); } } } @Test public void testReadNumericCatFeats() throws Exception { System.out.println("read"); List<String> testLines = new ArrayList<String>(); List<Double> expetedLabel = new DoubleList(); List<Vec> expectedVec = new ArrayList<Vec>(); List<int[]> expectedCats = new ArrayList<int[]>(); CategoricalData[] cats = new CategoricalData[] { new CategoricalData(2), new CategoricalData(4), }; cats[0].setOptionName("A", 0); cats[0].setOptionName("B", 1); cats[1].setOptionName("a", 0); cats[1].setOptionName("b", 1); cats[1].setOptionName("c", 2); cats[1].setOptionName("d", 3); CategoricalData predicting = new CategoricalData(4); predicting.setOptionName("-1", 0); predicting.setOptionName("1", 1); predicting.setOptionName("2", 2); predicting.setOptionName("3", 3); testLines.add("-1,0.0, A, 3.0, 0.0, 0.0, a, 0.0");//normal line expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 0.0, 0.0, 0.0)); expectedCats.add(new int[]{0, 0}); testLines.add("1,3.0,B,0.0,0.0,0.0,b,0.0"); //line ends in a space expetedLabel.add(1.0); expectedVec.add(DenseVector.toDenseVec( 3.0, 0.0, 0.0, 0.0, 0.0)); expectedCats.add(new int[]{1, 1}); testLines.add("2,0.0, A,3.0, 3.0, 1.0, c, 0.0");//normal line with many values expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 1.0, 0.0)); expectedCats.add(new int[]{0, 2}); testLines.add("-1, 0.0,A , 3.0, 0.0, 2.0, d, 0.0");//extra spaces in between expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 0.0, 2.0, 0.0)); expectedCats.add(new int[]{0, 3}); testLines.add("1,0.0, B , 0.0, 0.0, 0.0, a , 0.0 "); ///empty line expetedLabel.add(1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); expectedCats.add(new int[]{1, 0}); testLines.add(" 2 , 0.0, A, 0.0, 0.0, 0.0, b, 0.0"); // empty line with space expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); expectedCats.add(new int[]{0, 1}); testLines.add("3, 0.0, B, 0.0, 0.0, 0.0, b, 0.0"); expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); expectedCats.add(new int[]{1, 1}); testLines.add("3,0.0, B, 0.0, 0.0, 0.0, d , 0.0"); expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); expectedCats.add(new int[]{1, 3}); testLines.add("-1, 10.0, A, 0.0, \t 2.0, 0.0, c, 0.0"); //extra spaces at the end expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 10.0, 0.0, 2.0, 0.0, 0.0)); expectedCats.add(new int[]{0, 2}); testLines.add("2, 0.0, A, 3.0, 3.0, 0.0, c , 1.0");//normal line with many values expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 0.0, 1.0)); expectedCats.add(new int[]{0, 2}); testLines.add("3,0.0, B, 0.0, 0.0, 0.0, d , NaN");//Nan numeric strng expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, Double.NaN)); expectedCats.add(new int[]{1, 3}); testLines.add("3,0.0, B, 0.0, 0.0, , d , 0.0");//Nan numeric empty string expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, Double.NaN, 0.0)); expectedCats.add(new int[]{1, 3}); testLines.add("2, 0.0, A, 3.0, 3.0, 0.0, , 1.0");//missing cat feat expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 0.0, 1.0)); expectedCats.add(new int[]{0, -1}); Set<Integer> cat_cols = new HashSet<Integer>(Arrays.asList(2, 6)); //when read back in, cat features are at the end b/c we always write out cats at the end Set<Integer> cat_cols_reed_back = new HashSet<Integer>(Arrays.asList(6, 7)); String[] newLines = new String[]{"\n", "\n\r", "\r\n", "\n\r\n"}; char comment = '#'; for (boolean endInNewLines : new boolean[]{true, false }) for(boolean endsInComments : new boolean[]{true, false}) for (String newLine : newLines) for (int i = 0; i < testLines.size(); i++) { StringBuilder input = new StringBuilder(); for (int j = 0; j < i; j++) { input.append(testLines.get(j)); if(endsInComments) { input.append(comment); input.append(testLines.get(j)); } input.append(newLine); } input.append(testLines.get(i)); if (endsInComments) { input.append(comment); input.append(testLines.get(i)); } if (endInNewLines) input.append(newLine); @SuppressWarnings("unchecked") RegressionDataSet regData = CSV.readR(0, new StringReader(input.toString()), ',', 0, comment, cat_cols); SimpleDataSet smpData = CSV.read(new StringReader(input.toString()), ',', 0, comment, cat_cols); @SuppressWarnings("unchecked") ClassificationDataSet catData = CSV.readC(0, new StringReader(input.toString()), ',', 0, comment, cat_cols); //Confirm that string -> data -> string -> data keeps everything the same StringWriter data_strng_out = new StringWriter(); CSV.write(smpData, data_strng_out); SimpleDataSet readBackIn = CSV.read(new StringReader(data_strng_out.toString()), 0, cat_cols_reed_back); compareDataSetPoints(smpData, readBackIn); assertEquals(i + 1, regData.size()); for (int j = 0; j < i + 1; j++) { Vec ex_vec = expectedVec.get(j); double ex_target = expetedLabel.get(j); int[] ex_cats = expectedCats.get(j); int[] cats_vals; String[] ex_cats_s = new String[ex_cats.length]; for(int k = 0; k < ex_cats.length; k++) ex_cats_s[k] = cats[k].getOptionName(ex_cats[k]); assertEquals(ex_target, regData.getTargetValue(j), 0.0); assertTrue(ex_vec.equals(regData.getDataPoint(j).getNumericalValues())); cats_vals = regData.getDataPoint(j).getCategoricalValues(); for(int k = 0; k < cats_vals.length; k++) assertEquals(ex_cats_s[k], regData.getCategories()[k].getOptionName(cats_vals[k])); //simpled dataset test Vec ex_vec_inc_target = new ConcatenatedVec(new ConstantVector(ex_target, 1), ex_vec); assertTrue(ex_vec_inc_target.equals(smpData.getDataPoint(j).getNumericalValues())); cats_vals = smpData.getDataPoint(j).getCategoricalValues(); for(int k = 0; k < cats_vals.length; k++) assertEquals(ex_cats_s[k], smpData.getCategories()[k].getOptionName(cats_vals[k])); //classification test assertTrue(ex_vec.equals(catData.getDataPoint(j).getNumericalValues())); int pred_indx = catData.getDataPointCategory(j); assertEquals(Integer.toString((int) ex_target) , catData.getPredicting().getOptionName(pred_indx)); cats_vals = catData.getDataPoint(j).getCategoricalValues(); for(int k = 0; k < cats_vals.length; k++) assertEquals(ex_cats_s[k], catData.getCategories()[k].getOptionName(cats_vals[k])); } } } @Test public void testWriteRead() { CategoricalData[] cats = new CategoricalData[] { new CategoricalData(2), new CategoricalData(4), new CategoricalData(3), }; cats[0].setOptionName("A", 0); cats[0].setOptionName("B", 1); cats[1].setOptionName("a", 0); cats[1].setOptionName("b", 1); cats[1].setOptionName("c", 2); cats[1].setOptionName("d", 3); cats[2].setOptionName("hello", 0); cats[2].setOptionName("hello_world", 1); cats[2].setOptionName("whats up?", 2); SimpleDataSet truth_data = new SimpleDataSet(3, cats); Random rand = RandomUtil.getRandom(); for (int i = 0; i < 100; i++) { DenseVector dv = new DenseVector(3); int[] vals = new int[3]; for (int j = 0; j < 3; j++) { dv.set(j, rand.nextInt(20)); vals[j] = rand.nextInt(cats[j].getNumOfCategories()); } truth_data.add(new DataPoint(dv, vals, cats)); } for (int lines_to_skip = 0; lines_to_skip < 10; lines_to_skip++) { StringBuilder extraLines = new StringBuilder(); for(int i = 0; i < lines_to_skip; i++) { for(int j = 0; j < rand.nextInt(1000)+1; j++) extraLines.append(i); extraLines.append("\n"); } try { StringWriter writter = new StringWriter(); CSV.write(truth_data, writter, ','); SimpleDataSet simpleIn = CSV.read(new StringReader(extraLines.toString()+writter.toString()), ',', lines_to_skip, '#', new HashSet<Integer>(Arrays.asList(3, 4, 5))); compareDataSetPoints(truth_data, simpleIn); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataWriter dw = CSV.getWriter(baos, truth_data.getCategories(), truth_data.getNumNumericalVars(), null, DataWriter.DataSetType.SIMPLE, ','); for(int i = 0; i < truth_data.size(); i++) dw.writePoint(truth_data.getDataPoint(i), 0); dw.close(); simpleIn = CSV.read(new StringReader(extraLines.toString()+new String(baos.toByteArray())), ',', lines_to_skip, '#', new HashSet<Integer>(Arrays.asList(3, 4, 5))); compareDataSetPoints(truth_data, simpleIn); } catch (IOException ex) { Logger.getLogger(CSVTest.class.getName()).log(Level.SEVERE, null, ex); } try { for (int indx = 0; indx < 3; indx++) { StringWriter writter = new StringWriter(); ClassificationDataSet trutch_c = truth_data.asClassificationDataSet(indx); CSV.write(trutch_c, writter, ','); ClassificationDataSet in = CSV.readC(0, new StringReader(extraLines.toString()+writter.toString()), ',', lines_to_skip, '#', new HashSet<Integer>(Arrays.asList(4, 5))); compareDataSetPoints(trutch_c, in); for (int i = 0; i < trutch_c.size(); i++) { String exp_s = trutch_c.getPredicting().getOptionName(trutch_c.getDataPointCategory(i)); String found_s = in.getPredicting().getOptionName(in.getDataPointCategory(i)); assertEquals(exp_s, found_s); } } } catch (IOException ex) { Logger.getLogger(CSVTest.class.getName()).log(Level.SEVERE, null, ex); } try { for (int indx = 0; indx < 3; indx++) { StringWriter writter = new StringWriter(); RegressionDataSet trutch_r = truth_data.asRegressionDataSet(indx); CSV.write(trutch_r, writter, ','); RegressionDataSet in = CSV.readR(0, new StringReader(extraLines.toString()+writter.toString()), ',', lines_to_skip, '#', new HashSet<Integer>(Arrays.asList(3, 4, 5))); compareDataSetPoints(trutch_r, in); assertTrue(trutch_r.getTargetValues().equals(in.getTargetValues())); } } catch (IOException ex) { Logger.getLogger(CSVTest.class.getName()).log(Level.SEVERE, null, ex); } } } private void compareDataSetPoints(DataSet<?> truth_data, DataSet<?> simpleIn) { assertEquals(truth_data.size(), simpleIn.size()); assertEquals(truth_data.getNumCategoricalVars(), simpleIn.getNumCategoricalVars()); assertEquals(truth_data.getNumNumericalVars(), simpleIn.getNumNumericalVars()); for(int i = 0;i < truth_data.size(); i++) { DataPoint exp = truth_data.getDataPoint(i); DataPoint found = simpleIn.getDataPoint(i); assertTrue(exp.getNumericalValues().equals(found.getNumericalValues())); for(int k = 0; k < truth_data.getNumCategoricalVars(); k++) { String exp_s = truth_data.getCategories()[k].getOptionName(exp.getCategoricalValue(k)); String found_s = simpleIn.getCategories()[k].getOptionName(found.getCategoricalValue(k)); assertEquals(exp_s, found_s); } } } }
21,075
41.837398
188
java
JSAT
JSAT-master/JSAT/test/jsat/io/JSATDataTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.io; import java.io.*; import java.util.Random; import jsat.ColumnMajorStore; import jsat.DataSet; import jsat.DataStore; import jsat.RowMajorStore; import jsat.SimpleDataSet; import jsat.classifiers.*; import jsat.datatransform.DenseSparceTransform; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.regression.RegressionDataSet; import jsat.text.GreekLetters; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class JSATDataTest { static SimpleDataSet simpleData; static SimpleDataSet byteIntegerData; public JSATDataTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { CategoricalData[] categories = new CategoricalData[3]; categories[0] = new CategoricalData(2); categories[1] = new CategoricalData(3); categories[2] = new CategoricalData(5); categories[1].setCategoryName("I love " + GreekLetters.pi);//unicide to exercise non-ascii writer simpleData = new SimpleDataSet(20, categories); Random rand = RandomUtil.getRandom(); for(int i = 0; i < 10; i++) { int[] catVals = new int[categories.length]; for(int j = 0; j < categories.length; j++) catVals[j] = rand.nextInt(categories[j].getNumOfCategories()); double[] numeric = new double[simpleData.getNumNumericalVars()]; for(int j = 0; j < numeric.length/3; j++) { numeric[rand.nextInt(numeric.length)] = rand.nextDouble(); } simpleData.add(new DataPoint(new DenseVector(numeric), catVals, categories)); simpleData.setWeight(simpleData.size()-1, rand.nextDouble()); } byteIntegerData = new SimpleDataSet(20, categories); for(int i = 0; i < 10; i++) { int[] catVals = new int[categories.length]; for(int j = 0; j < categories.length; j++) catVals[j] = rand.nextInt(categories[j].getNumOfCategories()); double[] numeric = new double[simpleData.getNumNumericalVars()]; for(int j = 0; j < numeric.length/3; j++) { numeric[rand.nextInt(numeric.length)] = rand.nextInt(Byte.MAX_VALUE); } byteIntegerData.add(new DataPoint(new DenseVector(numeric), catVals, categories)); byteIntegerData.setWeight(byteIntegerData.size()-1, rand.nextInt(Byte.MAX_VALUE-1)+1); } } @After public void tearDown() { } @Test public void testReadWriteSimpleFPTypes() throws Exception { System.out.println("ReadWriteSimple"); for(JSATData.FloatStorageMethod fpStoreMethod : JSATData.FloatStorageMethod.values()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JSATData.writeData(byteIntegerData, baos, fpStoreMethod); ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); DataSet readBack = JSATData.load(bin); checkDataSet(byteIntegerData, readBack); byteIntegerData.applyTransform(new DenseSparceTransform(0.5));//sparcify our numeric values and try again baos = new ByteArrayOutputStream(); JSATData.writeData(byteIntegerData, baos, fpStoreMethod); byte[] raw_read_back = baos.toByteArray(); bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin); checkDataSet(byteIntegerData, readBack); //what if we muck the number of data points to be a negative value? indicates streaming write scenario raw_read_back[17] = -1; raw_read_back[18] = -1; raw_read_back[19] = -1; raw_read_back[20] = -1; bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin); checkDataSet(byteIntegerData, readBack); } } /** * Test of writeData method, of class JSATData. */ @Test public void testReadWriteSimple() throws Exception { System.out.println("ReadWriteSimple"); for(DataStore store : new DataStore[]{new RowMajorStore(), new ColumnMajorStore()}) { //Prime by writting out the data ByteArrayOutputStream baos = new ByteArrayOutputStream(); JSATData.writeData(simpleData, baos); ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); DataSet readBack = JSATData.load(bin, store.clone()); checkDataSet(simpleData, readBack); simpleData.applyTransform(new DenseSparceTransform(0.5));//sparcify our numeric values and try again baos = new ByteArrayOutputStream(); JSATData.writeData(simpleData, baos); byte[] raw_read_back = baos.toByteArray(); bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin, store.clone()); checkDataSet(simpleData, readBack); //what if we muck the number of data points to be a negative value? indicates streaming write scenario raw_read_back[17] = -1; raw_read_back[18] = -1; raw_read_back[19] = -1; raw_read_back[20] = -1; bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin, store.clone()); checkDataSet(simpleData, readBack); } } @Test public void testReadWriteClassification() throws Exception { System.out.println("ReadWriteClassification"); //use the last categorical feature as the read target so that forcing as a standard dataset produces the same expected result as the original simple dataset ClassificationDataSet cds = simpleData.asClassificationDataSet(simpleData.getNumCategoricalVars()-1); for(DataStore store : new DataStore[]{new RowMajorStore(), new ColumnMajorStore()}) { //Prime by writting out the data ByteArrayOutputStream baos = new ByteArrayOutputStream(); JSATData.writeData(cds, baos); ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); //check classificaiton is right DataSet readBack = JSATData.load(bin, store.clone()); checkDataSet(cds, readBack); bin.reset(); readBack = JSATData.loadClassification(bin, store.clone()); checkDataSet(cds, readBack); //check forcing as simple bin = new ByteArrayInputStream(baos.toByteArray()); readBack = JSATData.load(bin, true, store.clone()); checkDataSet(simpleData, readBack); cds.applyTransform(new DenseSparceTransform(0.5));//sparcify our numeric values and try again simpleData.applyTransform(new DenseSparceTransform(0.5)); baos = new ByteArrayOutputStream(); JSATData.writeData(cds, baos); bin = new ByteArrayInputStream(baos.toByteArray()); //check classificaiton is right readBack = JSATData.load(bin, store.clone()); checkDataSet(cds, readBack); bin.reset(); readBack = JSATData.loadClassification(bin, store.clone()); checkDataSet(cds, readBack); //check forcing as simple byte[] raw_read_back = baos.toByteArray(); bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin, true, store.clone()); checkDataSet(simpleData, readBack); //what if we muck the number of data points to be a negative value? indicates streaming write scenario raw_read_back[17] = -1; raw_read_back[18] = -1; raw_read_back[19] = -1; raw_read_back[20] = -1; bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin, true, store.clone()); checkDataSet(simpleData, readBack); } } @Test public void testReadWriteRegression() throws Exception { System.out.println("ReadWriteRegression"); for(DataStore store : new DataStore[]{new RowMajorStore(), new ColumnMajorStore()}) { //use the last categorical feature as the read target so that forcing as a standard dataset produces the same expected result as the original simple dataset RegressionDataSet rds = simpleData.asRegressionDataSet(simpleData.getNumNumericalVars()-1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JSATData.writeData(rds, baos); ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); //check classificaiton is right DataSet readBack = JSATData.load(bin, store.clone()); checkDataSet(rds, readBack); bin.reset(); readBack = JSATData.loadRegression(bin, store.clone()); checkDataSet(rds, readBack); //check forcing as simple bin = new ByteArrayInputStream(baos.toByteArray()); readBack = JSATData.load(bin, true, store.clone()); checkDataSet(simpleData, readBack); rds.applyTransform(new DenseSparceTransform(0.5));//sparcify our numeric values and try again simpleData.applyTransform(new DenseSparceTransform(0.5)); baos = new ByteArrayOutputStream(); JSATData.writeData(rds, baos); bin = new ByteArrayInputStream(baos.toByteArray()); //check classificaiton is right readBack = JSATData.load(bin, store.clone()); checkDataSet(rds, readBack); bin.reset(); readBack = JSATData.loadRegression(bin, store.clone()); checkDataSet(rds, readBack); //check forcing as simple byte[] raw_read_back = baos.toByteArray(); bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin, true, store.clone()); checkDataSet(simpleData, readBack); //what if we muck the number of data points to be a negative value? indicates streaming write scenario raw_read_back[17] = -1; raw_read_back[18] = -1; raw_read_back[19] = -1; raw_read_back[20] = -1; bin = new ByteArrayInputStream(raw_read_back); readBack = JSATData.load(bin, true, store.clone()); checkDataSet(simpleData, readBack); //Check data-writer appraoch looks like mucked version of binary } } private void checkDataSet(DataSet ogData, DataSet cpData) { assertEquals(ogData.getClass().getCanonicalName(), cpData.getClass().getCanonicalName()); assertEquals(ogData.getNumNumericalVars(), cpData.getNumNumericalVars()); assertEquals(ogData.getNumCategoricalVars(), cpData.getNumCategoricalVars()); assertEquals(ogData.size(), cpData.size()); CategoricalData[] og_cats = ogData.getCategories(); CategoricalData[] cp_cats = ogData.getCategories(); for(int i = 0; i < og_cats.length; i++) { assertEquals(og_cats[i].getCategoryName(), cp_cats[i].getCategoryName()); assertEquals(og_cats[i].getNumOfCategories(), cp_cats[i].getNumOfCategories()); for(int j = 0; j < og_cats[i].getNumOfCategories(); j++) assertEquals(og_cats[i].getOptionName(j), cp_cats[i].getOptionName(j)); } //compare datapoint values for(int i = 0; i < ogData.size(); i++) { DataPoint og = ogData.getDataPoint(i); DataPoint cp = cpData.getDataPoint(i); assertArrayEquals(og.getCategoricalValues(), cp.getCategoricalValues()); Vec og_vec = og.getNumericalValues(); Vec cp_vec = cp.getNumericalValues(); // assertTrue(og_vec.isSparse() == cp_vec.isSparse()); assertTrue(og_vec.equals(cp_vec)); assertEquals(ogData.getWeight(i), cpData.getWeight(i), 0.0); } if(ogData instanceof ClassificationDataSet) { ClassificationDataSet ogC = (ClassificationDataSet) ogData; ClassificationDataSet cpC = (ClassificationDataSet) cpData; for(int i = 0; i < ogData.size(); i++) assertEquals(ogC.getDataPointCategory(i), cpC.getDataPointCategory(i)); } if(ogData instanceof RegressionDataSet) { RegressionDataSet ogR = (RegressionDataSet) ogData; RegressionDataSet cpR = (RegressionDataSet) cpData; for(int i = 0; i < ogData.size(); i++) assertEquals(ogR.getTargetValue(i), cpR.getTargetValue(i), 0.0); } } }
14,316
35.710256
168
java
JSAT
JSAT-master/JSAT/test/jsat/io/LIBSVMLoaderTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.io; import java.io.*; import java.util.ArrayList; import java.util.List; import jsat.ColumnMajorStore; import jsat.DataStore; import jsat.RowMajorStore; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.regression.RegressionDataSet; import jsat.utils.DoubleList; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LIBSVMLoaderTest { public LIBSVMLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of loadR method, of class LIBSVMLoader. */ @Test public void testLoadR_File() throws Exception { System.out.println("loadR"); List<String> testLines = new ArrayList<String>(); List<Double> expetedLabel = new DoubleList(); List<Vec> expectedVec = new ArrayList<Vec>(); testLines.add("-1 2:3.0");//normal line expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 0.0, 0.0, 0.0)); testLines.add("1 1:3.0 "); //line ends in a space expetedLabel.add(1.0); expectedVec.add(DenseVector.toDenseVec( 3.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("-21 2:3.0 3:3.0 4:1.0");//normal line with many values expetedLabel.add(-21.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 1.0, 0.0)); testLines.add("-1 2:3.0 4:2.0");//extra spaces in between expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 0.0, 2.0, 0.0)); testLines.add("1"); ///empty line expetedLabel.add(1.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("2 "); // empty line with space expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("3"); expetedLabel.add(3.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("4"); expetedLabel.add(4.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 0.0, 0.0, 0.0, 0.0)); testLines.add("-1 1:10 3:2.0 "); //extra spaces at the end expetedLabel.add(-1.0); expectedVec.add(DenseVector.toDenseVec( 10.0, 0.0, 2.0, 0.0, 0.0)); testLines.add("2 2:3.0 3:3.0 5:1.0");//normal line with many values expetedLabel.add(2.0); expectedVec.add(DenseVector.toDenseVec( 0.0, 3.0, 3.0, 0.0, 1.0)); String[] newLines = new String[]{"\n", "\n\r", "\r\n", "\n\r\n"}; for(DataStore ds : new DataStore[]{new RowMajorStore(), new ColumnMajorStore()}) for (boolean endInNewLines : new boolean[]{true, false }) for (String newLine : newLines) for (int i = 0; i < testLines.size(); i++) { StringBuilder input = new StringBuilder(); for (int j = 0; j < i; j++) input.append(testLines.get(j)).append(newLine); input.append(testLines.get(i)); if (endInNewLines) input.append(newLine); RegressionDataSet dataSet = LIBSVMLoader.loadR(new StringReader(input.toString()), 0.5, 5, ds); assertEquals(i + 1, dataSet.size()); for (int j = 0; j < i + 1; j++) { assertEquals(expetedLabel.get(j), dataSet.getTargetValue(j), 0.0); assertTrue(expectedVec.get(j).equals(dataSet.getDataPoint(j).getNumericalValues())); } //can I use the DataWriter to export and re-import the same data? ByteArrayOutputStream out_tmp = new ByteArrayOutputStream(); DataWriter dw = LIBSVMLoader.getWriter(out_tmp, dataSet.getNumNumericalVars(), DataWriter.DataSetType.REGRESSION); for(int k = 0; k < dataSet.size(); k++) dw.writePoint(dataSet.getDataPoint(k), dataSet.getTargetValue(k)); dw.close(); RegressionDataSet dataSet2 = LIBSVMLoader.loadR(new StringReader(new String(out_tmp.toByteArray())), 0.5, 5); assertEquals(dataSet.size(), dataSet2.size()); for (int j = 0; j < i + 1; j++) { assertEquals(dataSet.getTargetValue(j), dataSet2.getTargetValue(j), 0.0); assertTrue(dataSet2.getDataPoint(j).getNumericalValues().equals(dataSet.getDataPoint(j).getNumericalValues())); } } } }
5,905
34.578313
139
java
JSAT
JSAT-master/JSAT/test/jsat/linear/CholeskyDecompositionTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.linear; import jsat.utils.SystemInfo; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class CholeskyDecompositionTest { Matrix pascal4; Matrix pascal5; static ExecutorService threadpool = Executors.newFixedThreadPool(SystemInfo.LogicalCores+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public CholeskyDecompositionTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { pascal5 = new DenseMatrix(new double[][] { { 1, 1, 1, 1, 1}, { 1, 2, 3, 4, 5}, { 1, 3, 6, 10, 15}, { 1, 4, 10, 20, 35}, { 1, 5, 15, 35, 70} }); pascal4 = new SubMatrix(pascal5, 0, 0, 4, 4).clone(); } @Test public void testGetL() { Matrix p5L = new DenseMatrix(new double[][] { {1, 1, 1, 1, 1}, {0, 1, 2, 3, 4}, {0, 0, 1, 3, 6}, {0, 0, 0, 1, 4}, {0, 0, 0, 0, 1} }); Matrix p4L = new DenseMatrix(new double[][] { {1, 1, 1, 1}, {0, 1, 2, 3}, {0, 0, 1, 3}, {0, 0, 0, 1} }); assertTrue(p4L.equals(new CholeskyDecomposition(pascal4).getLT(), 1e-10)); assertTrue(p5L.equals(new CholeskyDecomposition(pascal5).getLT(), 1e-10)); } @Test public void testGetDet() { double detP5 = 1.0; double detP4 = 1.0; assertEquals(detP4, new CholeskyDecomposition(pascal4).getDet(), 1e-10); assertEquals(detP5, new CholeskyDecomposition(pascal5).getDet(), 1e-10); } @Test public void testSolveVec() { Vec b5 = DenseVector.toDenseVec(5, 4, 1, 3, 2); Vec b4 = DenseVector.toDenseVec(4, 2, 3, 1); Vec x5 = DenseVector.toDenseVec(-18, 84, -113, 67, -15); Vec x4 = DenseVector.toDenseVec(15, -26, 21, -6); assertTrue(x5.equals(new CholeskyDecomposition(pascal5).solve(b5), 1e-10)); assertTrue(x4.equals(new CholeskyDecomposition(pascal4).solve(b4), 1e-10)); } @Test public void testSolveMatrix() { Matrix B5 = new DenseMatrix(new double[][]{ { 2, 3, 5}, { 1, 7, 1}, { 4, 5, 5}, { 3, 9, 1}, { 2, 3, 8} }); Matrix B4 = new DenseMatrix(new double[][] { { 4, 7, 6}, { 3, 3, 5}, { 5, 7, 3}, { 7, 4, 6}, }); Matrix X5 = new DenseMatrix(new double[][]{ { 27, -47, 68}, { -81, 164, -208}, { 100, -210, 266}, { -56, 124, -156}, { 12, -28, 35} }); Matrix X4 = new DenseMatrix(new double[][] { { 11, 34, 0}, { -16, -65, 19}, { 12, 53, -19}, { -3, -15, 6}, }); assertTrue(X5.equals(new CholeskyDecomposition(pascal5).solve(B5), 1e-10)); assertTrue(X4.equals(new CholeskyDecomposition(pascal4).solve(B4), 1e-10)); } @Test public void testSolveMatrixExecutor() { Matrix B5 = new DenseMatrix(new double[][]{ { 2, 3, 5}, { 1, 7, 1}, { 4, 5, 5}, { 3, 9, 1}, { 2, 3, 8} }); Matrix B4 = new DenseMatrix(new double[][] { { 4, 7, 6}, { 3, 3, 5}, { 5, 7, 3}, { 7, 4, 6}, }); Matrix X5 = new DenseMatrix(new double[][]{ { 27, -47, 68}, { -81, 164, -208}, { 100, -210, 266}, { -56, 124, -156}, { 12, -28, 35} }); Matrix X4 = new DenseMatrix(new double[][] { { 11, 34, 0}, { -16, -65, 19}, { 12, 53, -19}, { -3, -15, 6}, }); assertTrue(X5.equals(new CholeskyDecomposition(pascal5).solve(B5, threadpool), 1e-10)); assertTrue(X4.equals(new CholeskyDecomposition(pascal4).solve(B4, threadpool), 1e-10)); } }
5,365
27.849462
117
java
JSAT
JSAT-master/JSAT/test/jsat/linear/ConcatenatedVecTest.java
package jsat.linear; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ConcatenatedVecTest { ConcatenatedVec cvec; DenseVector dvec; public ConcatenatedVecTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { List<Vec> vecs = new ArrayList<Vec>(); vecs.add(DenseVector.toDenseVec(0, 1, 2)); vecs.add(DenseVector.toDenseVec(3, 4, 5)); vecs.add(DenseVector.toDenseVec(6, 7, 8)); vecs.add(DenseVector.toDenseVec(9, 10, 11)); vecs.add(DenseVector.toDenseVec(0, 0, 14)); dvec = DenseVector.toDenseVec(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 14); cvec = new ConcatenatedVec(vecs); } @After public void tearDown() { } /** * Test of length method, of class ConcatenatedVec. */ @Test public void testLength() { System.out.println("length"); assertEquals(dvec.length(), cvec.length()); } /** * Test of get method, of class ConcatenatedVec. */ @Test public void testGet() { System.out.println("get"); for(int i = 0; i < dvec.length(); i++) assertEquals(dvec.get(i), cvec.get(i), 0.0); try { cvec.get(cvec.length()); fail("Index out of bounds should have occured"); } catch( IndexOutOfBoundsException ex) { //good, that was supposed to happen } } /** * Test of set method, of class ConcatenatedVec. */ @Test public void testSet() { System.out.println("set"); Random rand = RandomUtil.getRandom(); for(int i = 0; i < dvec.length(); i++) { double nv = rand.nextDouble(); dvec.set(i, nv); cvec.set(i, nv); } for(int i = 0; i < dvec.length(); i++) assertEquals(dvec.get(i), cvec.get(i), 0.0); } @Test public void testMutableAdd() { System.out.println("mutableAdd"); cvec.mutableAdd(-1, dvec); for(int i = 0; i < dvec.length(); i++) assertEquals(0.0, cvec.get(i), 0.0); } @Test public void testGetNonZeroIterator() { System.out.println("getNonZeroIterator"); for(int i = 0; i < dvec.length(); i++) { Iterator<IndexValue> diter = dvec.getNonZeroIterator(i); Iterator<IndexValue> citer = cvec.getNonZeroIterator(i); assertTrue(diter.hasNext() == citer.hasNext()); while(diter.hasNext()) { IndexValue dIV = diter.next(); IndexValue cIV = citer.next(); assertEquals(dIV.getIndex(), cIV.getIndex()); assertEquals(dIV.getValue(), cIV.getValue(), 0.0); assertTrue(diter.hasNext() == citer.hasNext()); } assertTrue(diter.hasNext() == citer.hasNext()); } } /** * Test of isSparse method, of class ConcatenatedVec. */ @Test public void testIsSparse() { System.out.println("isSparse"); assertFalse(cvec.isSparse()); } /** * Test of clone method, of class ConcatenatedVec. */ @Test public void testClone() { System.out.println("clone"); ConcatenatedVec cloned = cvec.clone(); cvec.mutableAdd(-1, dvec); for(int i = 0; i < dvec.length(); i++) assertEquals(0.0, cvec.get(i), 0.0); for(int i = 0; i < dvec.length(); i++) assertEquals(dvec.get(i), cloned.get(i), 0.0); } }
4,133
23.754491
86
java
JSAT
JSAT-master/JSAT/test/jsat/linear/DenseMatrixTest.java
package jsat.linear; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class DenseMatrixTest { /** * 5x5 */ static DenseMatrix A; /** * 5x5 */ static DenseMatrix B; /** * 5x7 */ static DenseMatrix C; static DenseMatrix AB; static DenseMatrix BA; static DenseMatrix AC; /** * Multi threaded pool with daemon threads */ static ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public DenseMatrixTest() { } @BeforeClass public static void setUpClass() throws Exception { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new DenseMatrix(new double[][] { {5, 3, 2, 8, 8}, {1, 8, 3, 6, 8}, {1, 2, 6, 5, 4}, {3, 9, 5, 9, 6}, {8, 3, 4, 3, 1} } ); C = new DenseMatrix(new double[][] { {1, 6, 8, 3, 1, 5, 10}, {5, 5, 3, 7, 2, 10, 0}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 2, 6, 5, 8, 1, 9} } ); AB = new DenseMatrix(new double[][] { {110, 150, 117, 157, 121}, {82, 105, 102, 121, 101}, {74, 103, 106, 121, 92}, {44, 136, 65, 135, 130}, {91, 178, 110, 171, 148} } ); BA = new DenseMatrix(new double[][] { {40, 182, 73, 187, 126}, {35, 174, 100, 161, 131}, {22, 109, 74, 115, 83}, {45, 201, 127, 193, 156}, {21, 100, 87, 123, 123} } ); AC = new DenseMatrix(new double[][] { {139, 73, 113, 167, 135, 100, 187}, {116, 54, 106, 143, 136, 81, 153}, {130, 42, 95, 142, 136, 64, 158}, {106, 79, 62, 114, 33, 123, 86}, {149, 90, 99, 173, 103, 139, 152} } ); } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_Matrix() { DenseMatrix ApB = new DenseMatrix(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(B); bCopy.mutableAdd(A); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); try { C.clone().mutableAdd(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_Matrix_ExecutorService() { DenseMatrix ApB = new DenseMatrix(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(B, threadpool); bCopy.mutableAdd(A, threadpool); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); try { C.clone().mutableAdd(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMutableAdd_double_Matrix_ExecutorService() { DenseMatrix ApB = new DenseMatrix(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(1.0, B, threadpool); bCopy.mutableAdd(1.0, A, threadpool); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); aCopy.mutableAdd(-1.0, B, threadpool); assertEquals(A, aCopy); Matrix Aadd5 = new DenseMatrix(A.rows(), A.cols()); Aadd5.mutableAdd(5.0, A, threadpool); assertEquals(A.multiply(5), Aadd5); try { C.clone().mutableAdd(1.0, A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_double() { DenseMatrix ApTwo = new DenseMatrix(new double[][] { {1+2, 5+2, 4+2, 8+2, 9+2}, {1+2, 5+2, 7+2, 3+2, 7+2}, {0+2, 3+2, 8+2, 5+2, 6+2}, {3+2, 8+2, 0+2, 7+2, 0+2}, {1+2, 9+2, 2+2, 9+2, 6+2} } ); Matrix aCopy = A.clone(); aCopy.mutableAdd(2); assertEquals(ApTwo, aCopy); } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_double_ExecutorService() { DenseMatrix ApTwo = new DenseMatrix(new double[][] { {1+2, 5+2, 4+2, 8+2, 9+2}, {1+2, 5+2, 7+2, 3+2, 7+2}, {0+2, 3+2, 8+2, 5+2, 6+2}, {3+2, 8+2, 0+2, 7+2, 0+2}, {1+2, 9+2, 2+2, 9+2, 6+2} } ); Matrix aCopy = A.clone(); aCopy.mutableAdd(2, threadpool); assertEquals(ApTwo, aCopy); } /** * Test of mutableSubtract method, of class DenseMatrix. */ @Test public void testMutableSubtract_Matrix() { DenseMatrix AmB = new DenseMatrix(new double[][] { {-4, 2, 2, 0, 1}, { 0, -3, 4, -3, -1}, {-1, 1, 2, 0, 2}, { 0, -1, -5, -2, -6}, {-7, 6, -2, 6, 5} } ); DenseMatrix BmA = new DenseMatrix(new double[][] { {-4*-1, 2*-1, 2*-1, 0*-1, 1*-1}, { 0*-1, -3*-1, 4*-1, -3*-1, -1*-1}, {-1*-1, 1*-1, 2*-1, 0*-1, 2*-1}, { 0*-1, -1*-1, -5*-1, -2*-1, -6*-1}, {-7*-1, 6*-1, -2*-1, 6*-1, 5*-1} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableSubtract(B); bCopy.mutableSubtract(A); assertEquals(AmB, aCopy); assertEquals(BmA, bCopy); try { C.clone().mutableSubtract(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableSubtract method, of class DenseMatrix. */ @Test public void testMutableSubtract_Matrix_ExecutorService() { DenseMatrix AmB = new DenseMatrix(new double[][] { {-4, 2, 2, 0, 1}, { 0, -3, 4, -3, -1}, {-1, 1, 2, 0, 2}, { 0, -1, -5, -2, -6}, {-7, 6, -2, 6, 5} } ); DenseMatrix BmA = new DenseMatrix(new double[][] { {-4*-1, 2*-1, 2*-1, 0*-1, 1*-1}, { 0*-1, -3*-1, 4*-1, -3*-1, -1*-1}, {-1*-1, 1*-1, 2*-1, 0*-1, 2*-1}, { 0*-1, -1*-1, -5*-1, -2*-1, -6*-1}, {-7*-1, 6*-1, -2*-1, 6*-1, 5*-1} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableSubtract(B, threadpool); bCopy.mutableSubtract(A, threadpool); assertEquals(AmB, aCopy); assertEquals(BmA, bCopy); try { C.clone().mutableSubtract(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector Ab = new DenseVector(Arrays.asList(148.0, 110.0, 103.0, 94.0, 149.0)); assertEquals(Ab, A.multiply(b)); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); assertEquals(Cz, C.multiply(z)); } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Vec_Double_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector store = b.deepCopy(); A.multiply(b, 3.0, store); assertEquals(new DenseVector(new double[]{ 448, 335, 311, 288, 454}), store); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); store.zeroOut(); C.multiply(z, 1.0, store); assertEquals(Cz, store); } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Matrix() { Matrix result; result = A.multiply(B); assertEquals(AB, result); result = B.multiply(A); assertEquals(BA, result); result = A.multiply(C); assertEquals(AC, result); try { C.multiply(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMultiply_Matrix_Matrix() { DenseMatrix R = new DenseMatrix(A.rows(), B.cols()); A.multiply(B, R); assertEquals(AB, R); A.multiply(B, R); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.multiply(A, R); assertEquals(BA, R); B.multiply(A, R); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.multiply(C, R); assertEquals(AC, R); A.multiply(C, R); assertEquals(AC.multiply(2), R); try { R.multiply(A, C); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { A.multiply(B, C); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Matrix_ExecutorService() { Matrix result; result = A.multiply(B, threadpool); assertEquals(AB, result); result = B.multiply(A, threadpool); assertEquals(BA, result); result = A.multiply(C, threadpool); assertEquals(AC, result); try { C.multiply(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMultiply_Matrix_ExecutorService_Matrix() { DenseMatrix R = new DenseMatrix(A.rows(), B.cols()); A.multiply(B, R, threadpool); assertEquals(AB, R); A.multiply(B, R, threadpool); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.multiply(A, R, threadpool); assertEquals(BA, R); B.multiply(A, R, threadpool); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.multiply(C, R, threadpool); assertEquals(AC, R); A.multiply(C, R, threadpool); assertEquals(AC.multiply(2), R); try { R.multiply(A, C, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { A.multiply(B, C, threadpool); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableMultiply method, of class DenseMatrix. */ @Test public void testMutableMultiply_double() { DenseMatrix AtTwo = new DenseMatrix(new double[][] { {1*2, 5*2, 4*2, 8*2, 9*2}, {1*2, 5*2, 7*2, 3*2, 7*2}, {0*2, 3*2, 8*2, 5*2, 6*2}, {3*2, 8*2, 0*2, 7*2, 0*2}, {1*2, 9*2, 2*2, 9*2, 6*2} } ); Matrix aCopy = A.clone(); aCopy.mutableMultiply(2); assertEquals(AtTwo, aCopy); } /** * Test of mutableMultiply method, of class DenseMatrix. */ @Test public void testMutableMultiply_double_ExecutorService() { DenseMatrix AtTwo = new DenseMatrix(new double[][] { {1*2, 5*2, 4*2, 8*2, 9*2}, {1*2, 5*2, 7*2, 3*2, 7*2}, {0*2, 3*2, 8*2, 5*2, 6*2}, {3*2, 8*2, 0*2, 7*2, 0*2}, {1*2, 9*2, 2*2, 9*2, 6*2} } ); Matrix aCopy = A.clone(); aCopy.mutableMultiply(2, threadpool); assertEquals(AtTwo, aCopy); } /** * Test of transpose method, of class DenseMatrix. */ @Test public void testTranspose() { DenseMatrix CTranspose = new DenseMatrix(new double[][] { {1, 5, 8, 9, 1}, {6, 5, 0, 3, 2}, {8, 3, 5, 2, 6}, {3, 7, 7, 7, 5}, {1, 2, 9, 2, 8}, {5, 10, 1, 4, 1}, {10, 0, 8, 8, 9} } ); assertEquals(CTranspose, C.transpose()); } /** * Test of get method, of class DenseMatrix. */ @Test public void testGet() { //Tests both testSet(); } /** * Test of set method, of class DenseMatrix. */ @Test public void testSet() { DenseMatrix toSet = new DenseMatrix(A.rows(), A.cols()); for(int i = 0; i < A.rows(); i++) for(int j = 0; j < A.cols(); j++) toSet.set(i, j, A.get(i, j)); assertEquals(A, toSet); } /** * Test of rows method, of class DenseMatrix. */ @Test public void testRows() { assertEquals(5, A.rows()); } /** * Test of cols method, of class DenseMatrix. */ @Test public void testCols() { assertEquals(5, A.cols()); assertEquals(7, C.cols()); } /** * Test of isSparse method, of class DenseMatrix. */ @Test public void testIsSparce() { assertEquals(false, A.isSparce()); } /** * Test of nnz method, of class DenseMatrix. */ @Test public void testNnz() { assertEquals(5*5, A.nnz()); assertEquals(5*7, C.nnz()); } /** * Test of clone method, of class DenseMatrix. */ @Test public void testCopy() { Matrix ACopy = A.clone(); assertEquals(A, ACopy); assertEquals(A.multiply(B), ACopy.multiply(B)); } /** * Test of swapRows method, of class DenseMatrix. */ @Test public void testSwapRows() { System.out.println("swapRows"); Matrix Expected = new DenseMatrix(new double[][] { {5, 5, 3, 7, 2, 10, 0}, {1, 2, 6, 5, 8, 1, 9}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 6, 8, 3, 1, 5, 10} } ); Matrix test = C.clone(); test.swapRows(1, 0); test.swapRows(1, 0); assertEquals(C, test); test.swapRows(0, 1); test.swapRows(0, 1); assertEquals(C, test); test.swapRows(3, 3); assertEquals(C, test); test.swapRows(0, 4); test.swapRows(0, 1); assertEquals(Expected, test); test = C.clone(); test.swapRows(4, 0); test.swapRows(1, 0); assertEquals(Expected, test); } /** * Test of zeroOut method, of class DenseMatrix. */ @Test public void testZeroOut() { System.out.println("zeroOut"); Matrix test = C.clone(); test.zeroOut(); for(int i = 0; i < test.rows(); i++) for(int j = 0; j < test.cols(); j++) assertEquals(0, test.get(i, j), 0); } /** * Test of lup method, of class DenseMatrix. */ @Test public void testLup_0args() { System.out.println("lup"); Matrix[] lup; lup = A.clone().lup(); assertTrue(lup[2].multiply(A).equals(lup[0].multiply(lup[1]), 1e-14)); lup = C.clone().lup(); assertTrue(lup[2].multiply(C).equals(lup[0].multiply(lup[1]), 1e-14)); lup = C.transpose().lup(); assertTrue(lup[2].multiply(C.transpose()).equals(lup[0].multiply(lup[1]), 1e-14)); } /** * Test of lup method, of class DenseMatrix. */ @Test public void testLup_ExecutorService() { System.out.println("lup"); Matrix[] lup; lup = A.clone().lup(threadpool); assertTrue(lup[2].multiply(A, threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); lup = C.clone().lup(threadpool); assertTrue(lup[2].multiply(C, threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); lup = C.transpose().lup(threadpool); assertTrue(lup[2].multiply(C.transpose(), threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); } /** * Test of mutableTranspose method, of class DenseMatrix. */ @Test public void testMutableTranspose() { System.out.println("mutableTranspose"); try { C.clone().mutableTranspose(); fail("Can not do a mutable transpose for rectangular matrix, error should have been thrown"); } catch(Exception ex) { } DenseMatrix ATranspose = new DenseMatrix(new double[][] { {1, 1, 0, 3, 1}, {5, 5, 3, 8, 9}, {4, 7, 8, 0, 2}, {8, 3, 5, 7, 9}, {9, 7, 6, 0, 6}, } ); Matrix AT = A.clone(); AT.mutableTranspose(); assertEquals(ATranspose, AT); } /** * Test of qr method, of class DenseMatrix. */ @Test public void testQr_0args() { System.out.println("qr"); Matrix[] qr; //3 properties to test // R is uper triangular // Q*Q' = I // A = Q*R qr = A.clone().qr(); assertTrue(A.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(A.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = B.clone().qr(); assertTrue(B.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(B.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.clone().qr(); assertTrue(C.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.transpose().qr(); assertTrue(C.transpose().equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.transpose().rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); } /** * Test of qr method, of class DenseMatrix. */ @Test public void testQr_ExecutorService() { System.out.println("qr"); Matrix[] qr; //3 properties to test // R is uper triangular // Q*Q' = I // A = Q*R qr = A.clone().qr(threadpool); assertTrue(A.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(A.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = B.clone().qr(threadpool); assertTrue(B.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(B.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.clone().qr(threadpool); assertTrue(C.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.transpose().qr(threadpool); assertTrue(C.transpose().equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.transpose().rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); } @Test public void testTransposeMultiply_Matrix() { Matrix result; result = A.transpose().transposeMultiply(B); assertEquals(AB, result); result = B.transpose().transposeMultiply(A); assertEquals(BA, result); result = A.transpose().transposeMultiply(C); assertEquals(AC, result); result = C.transposeMultiply(A); assertEquals(new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ), result); result = C.transposeMultiply(C); assertEquals(new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }), result); try { C.transpose().transposeMultiply(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_Matrix() { Matrix R = new DenseMatrix(A.rows(), B.cols()); A.transpose().transposeMultiply(B, R); assertEquals(AB, R); A.transpose().transposeMultiply(B, R); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.transpose().transposeMultiply(A, R); assertEquals(BA, R); B.transpose().transposeMultiply(A, R); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.transpose().transposeMultiply(C, R); assertEquals(AC, R); A.transpose().transposeMultiply(C, R); assertEquals(AC.multiply(2), R); R = new DenseMatrix(C.cols(), A.cols()); C.transposeMultiply(A, R); Matrix CtA = new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ); assertEquals(CtA, R); C.transposeMultiply(A, R); assertEquals(CtA.multiply(2), R); R = new DenseMatrix(C.cols(), C.cols()); C.transposeMultiply(C, R); Matrix CtC = new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }); assertEquals(CtC, R); C.transposeMultiply(C, R); assertEquals(CtC.multiply(2), R); try { A.transpose().transposeMultiply(B, R); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { C.transpose().transposeMultiply(A, R); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_ExecutorService() { Matrix result; result = A.transpose().transposeMultiply(B, threadpool); assertEquals(AB, result); result = B.transpose().transposeMultiply(A, threadpool); assertEquals(BA, result); result = A.transpose().transposeMultiply(C, threadpool); assertEquals(AC, result); result = C.transposeMultiply(A, threadpool); assertEquals(new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ), result); result = C.transposeMultiply(C, threadpool); assertEquals(new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }), result); try { C.transpose().transposeMultiply(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_Matrix_ExecutorService() { Matrix R = new DenseMatrix(A.rows(), B.cols()); A.transpose().transposeMultiply(B, R, threadpool); assertEquals(AB, R); A.transpose().transposeMultiply(B, R, threadpool); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.transpose().transposeMultiply(A, R, threadpool); assertEquals(BA, R); B.transpose().transposeMultiply(A, R, threadpool); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.transpose().transposeMultiply(C, R, threadpool); assertEquals(AC, R); A.transpose().transposeMultiply(C, R, threadpool); assertEquals(AC.multiply(2), R); R = new DenseMatrix(C.cols(), A.cols()); C.transposeMultiply(A, R, threadpool); Matrix CtA = new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ); assertEquals(CtA, R); C.transposeMultiply(A, R, threadpool); assertEquals(CtA.multiply(2), R); R = new DenseMatrix(C.cols(), C.cols()); C.transposeMultiply(C, R, threadpool); Matrix CtC = new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }); assertEquals(CtC, R); C.transposeMultiply(C, R, threadpool); assertEquals(CtC.multiply(2), R); try { A.transpose().transposeMultiply(B, R, threadpool); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { C.transpose().transposeMultiply(A, R, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Double_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector Ab = new DenseVector(Arrays.asList(148.0, 110.0, 103.0, 94.0, 149.0)); assertEquals(Ab, A.transpose().transposeMultiply(1.0, b)); assertEquals(Ab.multiply(7.0), A.transpose().transposeMultiply(7.0, b)); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); assertEquals(Cz, C.transpose().transposeMultiply(1.0, z)); assertEquals(Cz.multiply(19.0), C.transpose().transposeMultiply(19.0, z)); try { C.transposeMultiply(1.0, z); fail("Dimensions were in disagreement, should not have worked"); } catch(Exception ex) { } } @Test public void testChangeSize() { DenseMatrix Acpy = A.clone(); Acpy.changeSize(Acpy.rows()-1, Acpy.cols()-1); assertEquals(Acpy.rows(), A.rows()-1); assertEquals(Acpy.cols(), A.cols()-1); for(int i = 0; i < Acpy.rows(); i++) for(int j = 0; j < Acpy.cols(); j++) assertEquals(Acpy.get(i, j), A.get(i, j), 0.0); //Expand back out and make sure the values are zero on the sides Acpy.changeSize(Acpy.rows()+2, Acpy.cols()+2); assertEquals(Acpy.rows(), A.rows()+1); assertEquals(Acpy.cols(), A.cols()+1); for(int i = 0; i < Acpy.rows(); i++) for(int j = 0; j < Acpy.cols(); j++) if(i < A.rows()-1 && j < A.cols()-1) assertEquals(A.get(i, j), Acpy.get(i, j), 0.0); else assertEquals(0.0, Acpy.get(i, j), 0.0); } }
34,103
27.731255
136
java
JSAT
JSAT-master/JSAT/test/jsat/linear/EigenvalueDecompositionTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.linear; import java.util.Random; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class EigenvalueDecompositionTest { /** * A 5x5 matrix whos eigen values are complex */ Matrix A; /** * A 3x3 matrix whos eigen values are real */ Matrix B; /** * A symmetric 5x5 matrix */ Matrix pascal5; public EigenvalueDecompositionTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new DenseMatrix(new double[][] { {-149, -50, -154}, {537, 180, 546}, {-27, -9, -25}, }); pascal5 = Matrix.pascal(5); } @After public void tearDown() { } @Test public void testImageEigen5() { System.out.println("testImageEigen5"); EigenValueDecomposition evd = new EigenValueDecomposition(A); assertTrue(evd.isComplex()); } @Test public void testRealEigen3() { System.out.println("testRealEigen3"); EigenValueDecomposition evd = new EigenValueDecomposition(B); assertFalse(evd.isComplex()); assertTrue(eigenResultsRight(evd, B, 1e-8)); } @Test public void testPascal5() { System.out.println("testPascal5"); EigenValueDecomposition evd = new EigenValueDecomposition(pascal5); assertFalse(evd.isComplex()); assertTrue(eigenResultsRight(evd, pascal5, 1e-8)); } @Test public void testSymmetric70() { //Cant use pascal for large b/c it becomes unstable System.out.println("testSymmetric70"); Random rand = new Random(123); Matrix SYM = new DenseMatrix(70, 70); for(int i = 0; i < SYM.rows(); i++) { SYM.set(i, i, rand.nextDouble()*10); for(int j = i+1; j < SYM.cols(); j++) { SYM.set(i, j, rand.nextDouble()*10); SYM.set(j, i, SYM.get(i, j)); } } EigenValueDecomposition evd = new EigenValueDecomposition(SYM); assertFalse(evd.isComplex()); assertTrue(eigenResultsRight(evd, SYM, 1e-8)); } @Test public void testRealRandomGenerated() { System.out.println("testRealRandomGenerated"); //Generate a eigen value decomposition backwards, randomly creating V and D and then working to A, then decompositing A and checking the results Random rand = new Random(123); Matrix V = Matrix.random(7, 7, rand); Matrix D = Matrix.diag(DenseVector.random(7, rand).multiply(10)); SingularValueDecomposition svd = new SingularValueDecomposition(V.clone()); Matrix A = V.multiply(D).multiply(svd.getPseudoInverse()); EigenValueDecomposition evd = new EigenValueDecomposition(A); assertTrue(eigenResultsRight(evd, A, 1e-6)); } @Test public void testRealRandomGeneratedLarge() { System.out.println("testRealRandomGeneratedLarge"); //Generate a eigen value decomposition backwards, randomly creating V and D and then working to A, then decompositing A and checking the results Random rand = new Random(123); Matrix V = Matrix.random(70, 70, rand); Matrix D = Matrix.diag(DenseVector.random(70, rand).multiply(10)); SingularValueDecomposition svd = new SingularValueDecomposition(V.clone()); Matrix A = V.multiply(D).multiply(svd.getPseudoInverse()); EigenValueDecomposition evd = new EigenValueDecomposition(A); assertTrue(eigenResultsRight(evd, A, 1e-6)); } @Test public void testNonSquare() { System.out.println("testNonSquare"); EigenValueDecomposition evd = null; try { evd = new EigenValueDecomposition(new DenseMatrix(10, 12)); fail("Can not take the EVD of a non square matrix"); } catch (Exception e) { } } /** * Checks if the property of the eigen decomposition [V, D] = eig(A) that A*V = V*D holds. * @param evd the eigen value decomposition * @param A the original matrix * @param eps the allowable difference in results * @return <t>true</tt> if the decomposition was correct */ private boolean eigenResultsRight(EigenValueDecomposition evd, Matrix A, double eps) { return A.multiply(evd.getV()).equals(evd.getV().multiply(evd.getD()), eps); } }
5,153
26.859459
152
java
JSAT
JSAT-master/JSAT/test/jsat/linear/GenericMatrixTest.java
package jsat.linear; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class GenericMatrixTest { protected static class TestImp extends GenericMatrix { /** * */ private static final long serialVersionUID = 1487285165522642650L; private double[][] storage; public TestImp(double[][] storage) { this.storage = storage; } public TestImp(int rows, int cols) { storage = new double[rows][cols]; } @Override protected Matrix getMatrixOfSameType(int rows, int cols) { return new TestImp(rows, cols); } @Override public double get(int i, int j) { return storage[i][j]; } @Override public void set(int i, int j, double value) { storage[i][j] = value; } @Override public int rows() { return storage.length; } @Override public int cols() { return storage[0].length; } @Override public boolean isSparce() { return false; } @Override public void changeSize(int newRows, int newCols) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } /** * 5x5 */ static TestImp A; /** * 5x5 */ static TestImp B; /** * 5x7 */ static TestImp C; /** * 7x5 */ static TestImp D; static TestImp AB; static TestImp BA; static TestImp AC; /** * Multi threaded pool with daemon threads */ static ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public GenericMatrixTest() { } @BeforeClass public static void setUpClass() throws Exception { A = new TestImp(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new TestImp(new double[][] { {5, 3, 2, 8, 8}, {1, 8, 3, 6, 8}, {1, 2, 6, 5, 4}, {3, 9, 5, 9, 6}, {8, 3, 4, 3, 1} } ); C = new TestImp(new double[][] { {1, 6, 8, 3, 1, 5, 10}, {5, 5, 3, 7, 2, 10, 0}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 2, 6, 5, 8, 1, 9} } ); D = new TestImp(new double[][] { { 2, 4, 5, 4, 4}, {10, 3, 2, 0, 7}, { 4, 5, 1, 7, 7}, { 2, 7, 2, 4, 7}, { 6, 2, 9, 2, 4}, { 1, 5, 6, 5, 10}, { 3, 4, 1, 5, 0}, } ); AB = new TestImp(new double[][] { {110, 150, 117, 157, 121}, {82, 105, 102, 121, 101}, {74, 103, 106, 121, 92}, {44, 136, 65, 135, 130}, {91, 178, 110, 171, 148} } ); BA = new TestImp(new double[][] { {40, 182, 73, 187, 126}, {35, 174, 100, 161, 131}, {22, 109, 74, 115, 83}, {45, 201, 127, 193, 156}, {21, 100, 87, 123, 123} } ); AC = new TestImp(new double[][] { {139, 73, 113, 167, 135, 100, 187}, {116, 54, 106, 143, 136, 81, 153}, {130, 42, 95, 142, 136, 64, 158}, {106, 79, 62, 114, 33, 123, 86}, {149, 90, 99, 173, 103, 139, 152} } ); } @AfterClass public static void tearDownClass() throws Exception { } /** * Test of mutableAdd method, of class TestImp. */ @Test public void testMutableAdd_Matrix() { TestImp ApB = new TestImp(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(B); bCopy.mutableAdd(A); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); try { C.clone().mutableAdd(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableAdd method, of class TestImp. */ @Test public void testMutableAdd_Matrix_ExecutorService() { TestImp ApB = new TestImp(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(B, threadpool); bCopy.mutableAdd(A, threadpool); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); try { C.clone().mutableAdd(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMutableAdd_double_Matrix_ExecutorService() { TestImp ApB = new TestImp(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(1.0, B, threadpool); bCopy.mutableAdd(1.0, A, threadpool); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); aCopy.mutableAdd(-1.0, B, threadpool); assertEquals(A, aCopy); Matrix Aadd5 = new TestImp(A.rows(), A.cols()); Aadd5.mutableAdd(5.0, A, threadpool); assertEquals(A.multiply(5), Aadd5); try { C.clone().mutableAdd(1.0, A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableAdd method, of class TestImp. */ @Test public void testMutableAdd_double() { TestImp ApTwo = new TestImp(new double[][] { {1+2, 5+2, 4+2, 8+2, 9+2}, {1+2, 5+2, 7+2, 3+2, 7+2}, {0+2, 3+2, 8+2, 5+2, 6+2}, {3+2, 8+2, 0+2, 7+2, 0+2}, {1+2, 9+2, 2+2, 9+2, 6+2} } ); Matrix aCopy = A.clone(); aCopy.mutableAdd(2); assertEquals(ApTwo, aCopy); } /** * Test of mutableAdd method, of class TestImp. */ @Test public void testMutableAdd_double_ExecutorService() { TestImp ApTwo = new TestImp(new double[][] { {1+2, 5+2, 4+2, 8+2, 9+2}, {1+2, 5+2, 7+2, 3+2, 7+2}, {0+2, 3+2, 8+2, 5+2, 6+2}, {3+2, 8+2, 0+2, 7+2, 0+2}, {1+2, 9+2, 2+2, 9+2, 6+2} } ); Matrix aCopy = A.clone(); aCopy.mutableAdd(2, threadpool); assertEquals(ApTwo, aCopy); } /** * Test of mutableSubtract method, of class TestImp. */ @Test public void testMutableSubtract_Matrix() { TestImp AmB = new TestImp(new double[][] { {-4, 2, 2, 0, 1}, { 0, -3, 4, -3, -1}, {-1, 1, 2, 0, 2}, { 0, -1, -5, -2, -6}, {-7, 6, -2, 6, 5} } ); TestImp BmA = new TestImp(new double[][] { {-4*-1, 2*-1, 2*-1, 0*-1, 1*-1}, { 0*-1, -3*-1, 4*-1, -3*-1, -1*-1}, {-1*-1, 1*-1, 2*-1, 0*-1, 2*-1}, { 0*-1, -1*-1, -5*-1, -2*-1, -6*-1}, {-7*-1, 6*-1, -2*-1, 6*-1, 5*-1} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableSubtract(B); bCopy.mutableSubtract(A); assertEquals(AmB, aCopy); assertEquals(BmA, bCopy); try { C.clone().mutableSubtract(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableSubtract method, of class TestImp. */ @Test public void testMutableSubtract_Matrix_ExecutorService() { TestImp AmB = new TestImp(new double[][] { {-4, 2, 2, 0, 1}, { 0, -3, 4, -3, -1}, {-1, 1, 2, 0, 2}, { 0, -1, -5, -2, -6}, {-7, 6, -2, 6, 5} } ); TestImp BmA = new TestImp(new double[][] { {-4*-1, 2*-1, 2*-1, 0*-1, 1*-1}, { 0*-1, -3*-1, 4*-1, -3*-1, -1*-1}, {-1*-1, 1*-1, 2*-1, 0*-1, 2*-1}, { 0*-1, -1*-1, -5*-1, -2*-1, -6*-1}, {-7*-1, 6*-1, -2*-1, 6*-1, 5*-1} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableSubtract(B, threadpool); bCopy.mutableSubtract(A, threadpool); assertEquals(AmB, aCopy); assertEquals(BmA, bCopy); try { C.clone().mutableSubtract(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of multiply method, of class TestImp. */ @Test public void testMultiply_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector Ab = new DenseVector(Arrays.asList(148.0, 110.0, 103.0, 94.0, 149.0)); assertEquals(Ab, A.multiply(b)); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); assertEquals(Cz, C.multiply(z)); } /** * Test of multiply method, of class TestImp. */ @Test public void testMultiply_Vec_Double_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector store = b.deepCopy(); A.multiply(b, 3.0, store); assertEquals(new DenseVector(new double[]{ 448, 335, 311, 288, 454}), store); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); store.zeroOut(); C.multiply(z, 1.0, store); assertEquals(Cz, store); } /** * Test of multiply method, of class TestImp. */ @Test public void testMultiply_Matrix() { Matrix result; result = A.multiply(B); assertEquals(AB, result); result = B.multiply(A); assertEquals(BA, result); result = A.multiply(C); assertEquals(AC, result); try { C.multiply(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMultiplyTranspose_Matrix_Matrix() { TestImp AmBt = new TestImp(new double[][] { {164, 173, 111, 194, 72}, {114, 136, 96 , 152, 67}, {113, 126, 103, 148, 62}, { 95, 109, 54, 144, 69}, {156, 181, 100, 211, 76} } ); TestImp DmBt = new TestImp(new double[][] { { 96, 105, 76, 127, 64}, {119, 96, 56, 109, 104}, {149, 145, 83, 167, 79}, {123, 144, 76, 157, 64}, {102, 93, 90, 123, 100}, {152, 169, 112, 183, 72}, { 69, 68, 42, 95, 55}, } ); TestImp tmp = new TestImp(5, 5); A.multiplyTranspose(B, tmp); assertEquals(AmBt, tmp); tmp = new TestImp(7, 5); D.multiplyTranspose(B, tmp); assertEquals(DmBt, tmp); } @Test public void testMultiplyTranspose_Matrix_Matrix_Exector() { TestImp AmBt = new TestImp(new double[][] { {164, 173, 111, 194, 72}, {114, 136, 96 , 152, 67}, {113, 126, 103, 148, 62}, { 95, 109, 54, 144, 69}, {156, 181, 100, 211, 76} } ); TestImp DmBt = new TestImp(new double[][] { { 96, 105, 76, 127, 64}, {119, 96, 56, 109, 104}, {149, 145, 83, 167, 79}, {123, 144, 76, 157, 64}, {102, 93, 90, 123, 100}, {152, 169, 112, 183, 72}, { 69, 68, 42, 95, 55}, } ); TestImp tmp = new TestImp(5, 5); A.multiplyTranspose(B, tmp, threadpool); assertEquals(AmBt, tmp); tmp = new TestImp(7, 5); D.multiplyTranspose(B, tmp, threadpool); assertEquals(DmBt, tmp); } @Test public void testMultiply_Matrix_Matrix() { TestImp R = new TestImp(A.rows(), B.cols()); A.multiply(B, R); assertEquals(AB, R); A.multiply(B, R); assertEquals(AB.multiply(2), R); R = new TestImp(B.rows(), A.cols()); B.multiply(A, R); assertEquals(BA, R); B.multiply(A, R); assertEquals(BA.multiply(2), R); R = new TestImp(A.rows(), C.cols()); A.multiply(C, R); assertEquals(AC, R); A.multiply(C, R); assertEquals(AC.multiply(2), R); try { R.multiply(A, C); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { A.multiply(B, C); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of multiply method, of class TestImp. */ @Test public void testMultiply_Matrix_ExecutorService() { Matrix result; result = A.multiply(B, threadpool); assertEquals(AB, result); result = B.multiply(A, threadpool); assertEquals(BA, result); result = A.multiply(C, threadpool); assertEquals(AC, result); try { C.multiply(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMultiply_Matrix_ExecutorService_Matrix() { TestImp R = new TestImp(A.rows(), B.cols()); A.multiply(B, R, threadpool); assertEquals(AB, R); A.multiply(B, R, threadpool); assertEquals(AB.multiply(2), R); R = new TestImp(B.rows(), A.cols()); B.multiply(A, R, threadpool); assertEquals(BA, R); B.multiply(A, R, threadpool); assertEquals(BA.multiply(2), R); R = new TestImp(A.rows(), C.cols()); A.multiply(C, R, threadpool); assertEquals(AC, R); A.multiply(C, R, threadpool); assertEquals(AC.multiply(2), R); try { R.multiply(A, C, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { A.multiply(B, C, threadpool); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableMultiply method, of class TestImp. */ @Test public void testMutableMultiply_double() { TestImp AtTwo = new TestImp(new double[][] { {1*2, 5*2, 4*2, 8*2, 9*2}, {1*2, 5*2, 7*2, 3*2, 7*2}, {0*2, 3*2, 8*2, 5*2, 6*2}, {3*2, 8*2, 0*2, 7*2, 0*2}, {1*2, 9*2, 2*2, 9*2, 6*2} } ); Matrix aCopy = A.clone(); aCopy.mutableMultiply(2); assertEquals(AtTwo, aCopy); } /** * Test of mutableMultiply method, of class TestImp. */ @Test public void testMutableMultiply_double_ExecutorService() { TestImp AtTwo = new TestImp(new double[][] { {1*2, 5*2, 4*2, 8*2, 9*2}, {1*2, 5*2, 7*2, 3*2, 7*2}, {0*2, 3*2, 8*2, 5*2, 6*2}, {3*2, 8*2, 0*2, 7*2, 0*2}, {1*2, 9*2, 2*2, 9*2, 6*2} } ); Matrix aCopy = A.clone(); aCopy.mutableMultiply(2, threadpool); assertEquals(AtTwo, aCopy); } /** * Test of transpose method, of class TestImp. */ @Test public void testTranspose() { TestImp CTranspose = new TestImp(new double[][] { {1, 5, 8, 9, 1}, {6, 5, 0, 3, 2}, {8, 3, 5, 2, 6}, {3, 7, 7, 7, 5}, {1, 2, 9, 2, 8}, {5, 10, 1, 4, 1}, {10, 0, 8, 8, 9} } ); assertEquals(CTranspose, C.transpose()); } /** * Test of get method, of class TestImp. */ @Test public void testGet() { //Tests both testSet(); } /** * Test of set method, of class TestImp. */ @Test public void testSet() { TestImp toSet = new TestImp(A.rows(), A.cols()); for(int i = 0; i < A.rows(); i++) for(int j = 0; j < A.cols(); j++) toSet.set(i, j, A.get(i, j)); assertEquals(A, toSet); } /** * Test of rows method, of class TestImp. */ @Test public void testRows() { assertEquals(5, A.rows()); } /** * Test of cols method, of class TestImp. */ @Test public void testCols() { assertEquals(5, A.cols()); assertEquals(7, C.cols()); } /** * Test of isSparse method, of class TestImp. */ @Test public void testIsSparce() { assertEquals(false, A.isSparce()); } /** * Test of nnz method, of class TestImp. */ @Test public void testNnz() { assertEquals(5*5, A.nnz()); assertEquals(5*7, C.nnz()); } /** * Test of clone method, of class TestImp. */ @Test public void testCopy() { Matrix ACopy = A.clone(); assertEquals(A, ACopy); assertEquals(A.multiply(B), ACopy.multiply(B)); } /** * Test of swapRows method, of class TestImp. */ @Test public void testSwapRows() { System.out.println("swapRows"); Matrix Expected = new TestImp(new double[][] { {5, 5, 3, 7, 2, 10, 0}, {1, 2, 6, 5, 8, 1, 9}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 6, 8, 3, 1, 5, 10} } ); Matrix test = C.clone(); test.swapRows(1, 0); test.swapRows(1, 0); assertEquals(C, test); test.swapRows(0, 1); test.swapRows(0, 1); assertEquals(C, test); test.swapRows(3, 3); assertEquals(C, test); test.swapRows(0, 4); test.swapRows(0, 1); assertEquals(Expected, test); test = C.clone(); test.swapRows(4, 0); test.swapRows(1, 0); assertEquals(Expected, test); } /** * Test of zeroOut method, of class TestImp. */ @Test public void testZeroOut() { System.out.println("zeroOut"); Matrix test = C.clone(); test.zeroOut(); for(int i = 0; i < test.rows(); i++) for(int j = 0; j < test.cols(); j++) assertEquals(0, test.get(i, j), 0); } /** * Test of lup method, of class TestImp. */ @Test public void testLup_0args() { System.out.println("lup"); Matrix[] lup; lup = A.clone().lup(); assertTrue(lup[2].multiply(A).equals(lup[0].multiply(lup[1]), 1e-14)); lup = C.clone().lup(); assertTrue(lup[2].multiply(C).equals(lup[0].multiply(lup[1]), 1e-14)); lup = C.transpose().lup(); assertTrue(lup[2].multiply(C.transpose()).equals(lup[0].multiply(lup[1]), 1e-14)); } /** * Test of lup method, of class TestImp. */ @Test public void testLup_ExecutorService() { System.out.println("lup"); Matrix[] lup; lup = A.clone().lup(threadpool); assertTrue(lup[2].multiply(A, threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); lup = C.clone().lup(threadpool); assertTrue(lup[2].multiply(C, threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); lup = C.transpose().lup(threadpool); assertTrue(lup[2].multiply(C.transpose(), threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); } /** * Test of mutableTranspose method, of class TestImp. */ @Test public void testMutableTranspose() { System.out.println("mutableTranspose"); try { C.clone().mutableTranspose(); fail("Can not do a mutable transpose for rectangular matrix, error should have been thrown"); } catch(Exception ex) { } TestImp ATranspose = new TestImp(new double[][] { {1, 1, 0, 3, 1}, {5, 5, 3, 8, 9}, {4, 7, 8, 0, 2}, {8, 3, 5, 7, 9}, {9, 7, 6, 0, 6}, } ); Matrix AT = A.clone(); AT.mutableTranspose(); assertEquals(ATranspose, AT); } /** * Test of qr method, of class TestImp. */ @Test public void testQr_0args() { System.out.println("qr"); Matrix[] qr; //3 properties to test // R is uper triangular // Q*Q' = I // A = Q*R qr = A.clone().qr(); assertTrue(A.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(A.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = B.clone().qr(); assertTrue(B.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(B.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.clone().qr(); assertTrue(C.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(C.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.transpose().qr(); assertTrue(C.transpose().equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(C.transpose().rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); } /** * Test of qr method, of class TestImp. */ @Test public void testQr_ExecutorService() { System.out.println("qr"); Matrix[] qr; //3 properties to test // R is uper triangular // Q*Q' = I // A = Q*R qr = A.clone().qr(threadpool); assertTrue(A.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(A.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = B.clone().qr(threadpool); assertTrue(B.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(B.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.clone().qr(threadpool); assertTrue(C.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(C.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.transpose().qr(threadpool); assertTrue(C.transpose().equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(Matrix.eye(C.transpose().rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); } @Test public void testTransposeMultiply_Matrix() { Matrix result; result = A.transpose().transposeMultiply(B); assertEquals(AB, result); result = B.transpose().transposeMultiply(A); assertEquals(BA, result); result = A.transpose().transposeMultiply(C); assertEquals(AC, result); result = C.transposeMultiply(A); assertEquals(new TestImp(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ), result); result = C.transposeMultiply(C); assertEquals(new TestImp(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }), result); try { C.transpose().transposeMultiply(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_Matrix() { Matrix R = new TestImp(A.rows(), B.cols()); A.transpose().transposeMultiply(B, R); assertEquals(AB, R); A.transpose().transposeMultiply(B, R); assertEquals(AB.multiply(2), R); R = new TestImp(B.rows(), A.cols()); B.transpose().transposeMultiply(A, R); assertEquals(BA, R); B.transpose().transposeMultiply(A, R); assertEquals(BA.multiply(2), R); R = new TestImp(A.rows(), C.cols()); A.transpose().transposeMultiply(C, R); assertEquals(AC, R); A.transpose().transposeMultiply(C, R); assertEquals(AC.multiply(2), R); R = new TestImp(C.cols(), A.cols()); C.transposeMultiply(A, R); Matrix CtA = new TestImp(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ); assertEquals(CtA, R); C.transposeMultiply(A, R); assertEquals(CtA.multiply(2), R); R = new TestImp(C.cols(), C.cols()); C.transposeMultiply(C, R); Matrix CtC = new TestImp(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }); assertEquals(CtC, R); C.transposeMultiply(C, R); assertEquals(CtC.multiply(2), R); try { A.transpose().transposeMultiply(B, R); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { C.transpose().transposeMultiply(A, R); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_ExecutorService() { Matrix result; result = A.transpose().transposeMultiply(B, threadpool); assertEquals(AB, result); result = B.transpose().transposeMultiply(A, threadpool); assertEquals(BA, result); result = A.transpose().transposeMultiply(C, threadpool); assertEquals(AC, result); result = C.transposeMultiply(A, threadpool); assertEquals(new TestImp(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ), result); result = C.transposeMultiply(C, threadpool); assertEquals(new TestImp(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }), result); try { C.transpose().transposeMultiply(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_Matrix_ExecutorService() { Matrix R = new TestImp(A.rows(), B.cols()); A.transpose().transposeMultiply(B, R, threadpool); assertEquals(AB, R); A.transpose().transposeMultiply(B, R, threadpool); assertEquals(AB.multiply(2), R); R = new TestImp(B.rows(), A.cols()); B.transpose().transposeMultiply(A, R, threadpool); assertEquals(BA, R); B.transpose().transposeMultiply(A, R, threadpool); assertEquals(BA.multiply(2), R); R = new TestImp(A.rows(), C.cols()); A.transpose().transposeMultiply(C, R, threadpool); assertEquals(AC, R); A.transpose().transposeMultiply(C, R, threadpool); assertEquals(AC.multiply(2), R); R = new TestImp(C.cols(), A.cols()); C.transposeMultiply(A, R, threadpool); Matrix CtA = new TestImp(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ); assertEquals(CtA, R); C.transposeMultiply(A, R, threadpool); assertEquals(CtA.multiply(2), R); R = new TestImp(C.cols(), C.cols()); C.transposeMultiply(C, R, threadpool); Matrix CtC = new TestImp(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }); assertEquals(CtC, R); C.transposeMultiply(C, R, threadpool); assertEquals(CtC.multiply(2), R); try { A.transpose().transposeMultiply(B, R, threadpool); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { C.transpose().transposeMultiply(A, R, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Double_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector Ab = new DenseVector(Arrays.asList(148.0, 110.0, 103.0, 94.0, 149.0)); assertEquals(Ab, A.transpose().transposeMultiply(1.0, b)); assertEquals(Ab.multiply(7.0), A.transpose().transposeMultiply(7.0, b)); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); assertEquals(Cz, C.transpose().transposeMultiply(1.0, z)); assertEquals(Cz.multiply(19.0), C.transpose().transposeMultiply(19.0, z)); try { C.transposeMultiply(1.0, z); fail("Dimensions were in disagreement, should not have worked"); } catch(Exception ex) { } } }
36,593
27.127594
139
java
JSAT
JSAT-master/JSAT/test/jsat/linear/HessenbergFormTest.java
package jsat.linear; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ExecutorService; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class HessenbergFormTest { /** * 5x5 */ static DenseMatrix A, hessA; /** * 2x2 test matrix */ static DenseMatrix f; /** * Multi threaded pool with daemon threads */ static ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public HessenbergFormTest() { } @BeforeClass public static void setUpClass() throws Exception { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); hessA = new DenseMatrix(new double[][] { { 1.000000000000000, -11.457431093955016, -7.374707356495900, -0.099215299078182, 0.575430671538097}, { -3.316624790355400, 13.636363636363633, 3.580749763336201, -7.121112733469424, -1.875518953902302}, { 0, 11.971729785189224, 10.034550906364995, -2.235016742983057, 1.182382333254766}, { 0, 0, -7.708011539446948, -0.430619433926174, -3.219873923950582}, { 0, 0, 0, 0.098549849397624, 2.759704891197538} }); f = new DenseMatrix(new double[][] { {8, 5}, {6, 9} } ); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of hess method, of class HessenbergForm. */ @Test public void testHess_Matrix() { System.out.println("hess"); Matrix test; test = A.clone(); HessenbergForm.hess(test); assertTrue(test.equals(hessA, 1e-14)); //f is 2x2, so it is its own upper hessenberg forn test = f.clone(); HessenbergForm.hess(f); assertEquals(test, f); } @Test public void testHess_Matrix_Executor() { System.out.println("hess"); Matrix test; test = A.clone(); HessenbergForm.hess(test, threadpool); assertTrue(test.equals(hessA, 1e-14)); //f is 2x2, so it is its own upper hessenberg forn test = f.clone(); HessenbergForm.hess(f, threadpool); assertEquals(test, f); } }
3,088
23.515873
136
java
JSAT
JSAT-master/JSAT/test/jsat/linear/LUPDecompositionTest.java
package jsat.linear; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Executors; import java.util.Arrays; import java.util.concurrent.ExecutorService; import jsat.utils.SystemInfo; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LUPDecompositionTest { /** * 5x5 */ static DenseMatrix A; /** * 5x5 */ static DenseMatrix B; /** * 5x7 */ static DenseMatrix C; static ExecutorService threadpool = Executors.newFixedThreadPool(SystemInfo.LogicalCores+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public LUPDecompositionTest() { } @BeforeClass public static void setUpClass() throws Exception { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new DenseMatrix(new double[][] { {5, 3, 2, 8, 8}, {1, 8, 3, 6, 8}, {1, 2, 6, 5, 4}, {3, 9, 5, 9, 6}, {8, 3, 4, 3, 1} } ); C = new DenseMatrix(new double[][] { {1, 6, 8, 3, 1, 5, 10}, {5, 5, 3, 7, 2, 10, 0}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 2, 6, 5, 8, 1, 9} } ); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of isSquare method, of class LUPDecomposition. */ @Test public void testIsSquare() { System.out.println("isSquare"); LUPDecomposition instance = new LUPDecomposition(C); assertFalse(instance.isSquare()); instance = new LUPDecomposition(C.transpose()); assertFalse(instance.isSquare()); instance = new LUPDecomposition(A); assertTrue(instance.isSquare()); } /** * Test of det method, of class LUPDecomposition. */ @Test public void testDet() { System.out.println("det"); LUPDecomposition instance = null; instance = new LUPDecomposition(A); assertEquals(3073, instance.det(), 1e-10); instance = new LUPDecomposition(B); assertEquals(-8068, instance.det(), 1e-10); instance = new LUPDecomposition(C); try { instance.det(); fail("Can not take the determinant of a non square matrix"); } catch(ArithmeticException ex) { } } /** * Test of solve method, of class LUPDecomposition. */ @Test public void testSolve_Vec() { System.out.println("solve"); Vec b = new DenseVector(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0 )); LUPDecomposition instance = null; instance = new LUPDecomposition(A); Vec x = instance.solve(b); assertTrue(A.multiply(x).equals(b, 1e-10)); instance = new LUPDecomposition(C); x = instance.solve(b); assertTrue(C.multiply(x).equals(b, 1e-10)); } /** * Test of solve method, of class LUPDecomposition. */ @Test public void testSolve_Matrix() { System.out.println("solve"); LUPDecomposition instance = null; Matrix x; instance = new LUPDecomposition(A); x = instance.solve(B); assertTrue(A.multiply(x).equals(B, 1e-10)); instance = new LUPDecomposition(A); x = instance.solve(C); assertTrue(A.multiply(x).equals(C, 1e-10)); instance = new LUPDecomposition(C); x = instance.solve(A); assertTrue(C.multiply(x).equals(A, 1e-10)); instance = new LUPDecomposition(C.transpose()); try { instance.solve(A); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } instance = new LUPDecomposition(A); try { instance.solve(C.transpose()); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } } /** * Test of solve method, of class LUPDecomposition. */ @Test public void testSolve_Matrix_ExecutorService() { System.out.println("solve"); LUPDecomposition instance = null; Matrix x; instance = new LUPDecomposition(A); x = instance.solve(B, threadpool); assertTrue(A.multiply(x).equals(B, 1e-10)); instance = new LUPDecomposition(A); x = instance.solve(C, threadpool); assertTrue(A.multiply(x).equals(C, 1e-10)); instance = new LUPDecomposition(C); x = instance.solve(A, threadpool); assertTrue(C.multiply(x).equals(A, 1e-10)); instance = new LUPDecomposition(C.transpose()); try { instance.solve(A, threadpool); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } instance = new LUPDecomposition(A); try { instance.solve(C.transpose(), threadpool); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } } /** * Test of forwardSub method, of class LUPDecomposition. */ @Test public void testForwardSub_Matrix_Vec() { System.out.println("forwardSub"); DenseMatrix L = new DenseMatrix(new double[][] { {1.0000, 0, 0, 0, 0}, {0.1111, 1.0000, 0, 0, 0}, {0.1111, 0.2941, 1.0000, 0, 0}, {0.5556, 0.5882, -0.7697, 1.0000, 0}, {0.8889, -0.4706, 1.9719, -1.1457, 1.0000} } ); Vec b = new DenseVector(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0 )); Vec x = LUPDecomposition.forwardSub(L, b); assertTrue(L.multiply(x).equals(b, 1e-10)); try { b = new DenseVector(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0 , 6.0)); LUPDecomposition.forwardSub(L, b); fail("Dimensions dont agree!"); } catch(ArithmeticException ex) { } try { b = new DenseVector(Arrays.asList(1.0, 2.0, 3.0, 4.0)); LUPDecomposition.forwardSub(L, b); fail("Dimensions dont agree!"); } catch(ArithmeticException ex) { } } /** * Test of forwardSub method, of class LUPDecomposition. */ @Test public void testForwardSub_Matrix_Matrix() { System.out.println("forwardSub"); DenseMatrix L = new DenseMatrix(new double[][] { {1.0000, 0, 0, 0, 0}, {0.1111, 1.0000, 0, 0, 0}, {0.1111, 0.2941, 1.0000, 0, 0}, {0.5556, 0.5882, -0.7697, 1.0000, 0}, {0.8889, -0.4706, 1.9719, -1.1457, 1.0000} } ); DenseMatrix b = new DenseMatrix(new double[][] { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} } ); Matrix x = LUPDecomposition.forwardSub(L, b); assertTrue(L.multiply(x).equals(b, 1e-10)); } /** * Test of forwardSub method, of class LUPDecomposition. */ @Test public void testForwardSub_3args() { System.out.println("forwardSub"); DenseMatrix L = new DenseMatrix(new double[][] { {1.0000, 0, 0, 0, 0}, {0.1111, 1.0000, 0, 0, 0}, {0.1111, 0.2941, 1.0000, 0, 0}, {0.5556, 0.5882, -0.7697, 1.0000, 0}, {0.8889, -0.4706, 1.9719, -1.1457, 1.0000} } ); DenseMatrix b = new DenseMatrix(new double[][] { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} } ); Matrix x = LUPDecomposition.forwardSub(L, b, threadpool); assertTrue(L.multiply(x).equals(b, 1e-10)); } /** * Test of backSub method, of class LUPDecomposition. */ @Test public void testBackSub_Matrix_Vec() { System.out.println("backSub"); DenseMatrix U = new DenseMatrix(new double[][] { {9.0000, 3.0000, 2.0000, 7.0000, 2.0000}, { 0, 5.6667, 7.7778, 2.2222, 0.7778}, { 0, 0, 3.4902, 3.5686, 7.5490}, { 0, 0, 0, 4.5506, 6.2416}, { 0, 0, 0, 0, -0.1469} } ); Vec b = new DenseVector(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0 )); Vec x = LUPDecomposition.backSub(U, b); assertTrue(U.multiply(x).equals(b, 1e-10)); } /** * Test of backSub method, of class LUPDecomposition. */ @Test public void testBackSub_Matrix_Matrix() { System.out.println("backSub"); DenseMatrix U = new DenseMatrix(new double[][] { {9.0000, 3.0000, 2.0000, 7.0000, 2.0000}, { 0, 5.6667, 7.7778, 2.2222, 0.7778}, { 0, 0, 3.4902, 3.5686, 7.5490}, { 0, 0, 0, 4.5506, 6.2416}, { 0, 0, 0, 0, -0.1469} } ); DenseMatrix b = new DenseMatrix(new double[][] { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} } ); Matrix x = LUPDecomposition.backSub(U, b); assertTrue(U.multiply(x).equals(b, 1e-10)); } /** * Test of backSub method, of class LUPDecomposition. */ @Test public void testBackSub_3args() { System.out.println("backSub"); DenseMatrix U = new DenseMatrix(new double[][] { {9.0000, 3.0000, 2.0000, 7.0000, 2.0000}, { 0, 5.6667, 7.7778, 2.2222, 0.7778}, { 0, 0, 3.4902, 3.5686, 7.5490}, { 0, 0, 0, 4.5506, 6.2416}, { 0, 0, 0, 0, -0.1469} } ); DenseMatrix b = new DenseMatrix(new double[][] { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} } ); Matrix x = LUPDecomposition.backSub(U, b, threadpool); assertTrue(U.multiply(x).equals(b, 1e-10)); } }
11,701
25.778032
117
java
JSAT
JSAT-master/JSAT/test/jsat/linear/LanczosTest.java
/* * This implementation has been contributed under the Public Domain. */ package jsat.linear; import java.util.Random; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author edwardraff */ public class LanczosTest { public LanczosTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testImplicitSymmetric() { System.out.println("test Implicit Symmetric case"); Random rand = new Random(123); Matrix A = DenseMatrix.random(70, 40, rand); int k = 4; Matrix A_AT = A.multiplyTranspose(A); Matrix AT_A = A.transposeMultiply(A); Lanczos AAT_explicit = new Lanczos(A_AT, k, true, true); Lanczos AAT_implicit = new Lanczos(A, k, true, false); Vec expected = AAT_explicit.getEigenValues(); Vec result = AAT_implicit.getEigenValues(); Vec relative_diffs = expected.subtract(result).pairwiseDivide(expected); for(int i = 0; i < k; i++) assertEquals(0, relative_diffs.get(i), 0.1); Lanczos ATA_explicit = new Lanczos(AT_A, k, false, true); Lanczos ATA_implicit = new Lanczos(A, k, false, false); expected = ATA_explicit.getEigenValues(); result = ATA_implicit.getEigenValues(); relative_diffs = expected.subtract(result).pairwiseDivide(expected); for(int i = 0; i < k; i++) assertEquals(0, relative_diffs.get(i), 0.1); } @Test public void testSymmetric() { System.out.println("test Symmetric case"); //Generate a eigen value decomposition backwards, randomly creating V and D and then working to A, then decompositing A and checking the results Random rand = new Random(123); Matrix D = Matrix.diag(DenseVector.random(70, rand).multiply(10)); D.set(0, 0, 900); D.set(1, 1, 700); D.set(2, 2, 400); D.set(3, 3, 300); int k = 4; //Lazy construction of orthonormal matrix to be eigen vectors Matrix V = Matrix.random(70, 70, rand); SingularValueDecomposition svd = new SingularValueDecomposition(V.clone()); V = svd.getU(); Matrix A = V.multiply(D).multiply(V.transpose()); Lanczos lanczos = new Lanczos(A, k, false, true); Vec eigen_values = lanczos.getEigenValues(); for(int i = 0; i < k; i ++) assertEquals(D.get(i, i), eigen_values.get(i), 0.05); //Do the eigen values match up too? for(int j = 0; j < V.rows(); j++) { Vec expected = new SubVector(0, k, V.getRow(j)); Vec result = lanczos.getEigenVectors().getRow(j); expected.applyFunction(Math::abs); result.applyFunction(Math::abs); Vec relative_diffs = expected.subtract(result).pairwiseDivide(expected); for(int i = 0; i < k; i++) assertEquals(0, relative_diffs.get(i), 0.1); } //Test full decomposition for sanity lanczos = new Lanczos(A, A.rows(), false, true); Matrix A_rec = lanczos.getEigenVectors().clone(); Matrix.diagMult(A_rec, lanczos.getEigenValues()); A_rec = A_rec.multiplyTranspose(lanczos.getEigenVectors()); // diff in norms should be relatively near zero, adjusted for magnitud of input assertEquals(0.0, A.subtract(A_rec).frobenius()/A.frobenius(), 0.01); } }
3,926
28.977099
152
java
JSAT
JSAT-master/JSAT/test/jsat/linear/MatrixOfVecsTest.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jsat.linear; import java.util.Arrays; import java.util.concurrent.*; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MatrixOfVecsTest { /** * 5x5 */ static MatrixOfVecs A; /** * 5x5 */ static MatrixOfVecs B; /** * 5x7 */ static MatrixOfVecs C; static MatrixOfVecs AB; static MatrixOfVecs BA; static MatrixOfVecs AC; /** * Multi threaded pool with daemon threads */ static ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public MatrixOfVecsTest() { } @BeforeClass public static void setUpClass() { A = new MatrixOfVecs(new Vec[] { DenseVector.toDenseVec(1, 5, 4, 8, 9), DenseVector.toDenseVec(1, 5, 7, 3, 7), DenseVector.toDenseVec(0, 3, 8, 5, 6), DenseVector.toDenseVec(3, 8, 0, 7, 0), DenseVector.toDenseVec(1, 9, 2, 9, 6) } ); B = new MatrixOfVecs(new Vec[] { DenseVector.toDenseVec(5, 3, 2, 8, 8), DenseVector.toDenseVec(1, 8, 3, 6, 8), DenseVector.toDenseVec(1, 2, 6, 5, 4), DenseVector.toDenseVec(3, 9, 5, 9, 6), DenseVector.toDenseVec(8, 3, 4, 3, 1) } ); C = new MatrixOfVecs(new Vec[] { DenseVector.toDenseVec(1, 6, 8, 3, 1, 5, 10), DenseVector.toDenseVec(5, 5, 3, 7, 2, 10, 0), DenseVector.toDenseVec(8, 0, 5, 7, 9, 1, 8), DenseVector.toDenseVec(9, 3, 2, 7, 2, 4, 8), DenseVector.toDenseVec(1, 2, 6, 5, 8, 1, 9) } ); AB = new MatrixOfVecs(new Vec[] { DenseVector.toDenseVec(110, 150, 117, 157, 121), DenseVector.toDenseVec(82, 105, 102, 121, 101), DenseVector.toDenseVec(74, 103, 106, 121, 92), DenseVector.toDenseVec(44, 136, 65, 135, 130), DenseVector.toDenseVec(91, 178, 110, 171, 148) } ); BA = new MatrixOfVecs(new Vec[] { DenseVector.toDenseVec(40, 182, 73, 187, 126), DenseVector.toDenseVec(35, 174, 100, 161, 131), DenseVector.toDenseVec(22, 109, 74, 115, 83), DenseVector.toDenseVec(45, 201, 127, 193, 156), DenseVector.toDenseVec(21, 100, 87, 123, 123) } ); AC = new MatrixOfVecs(new Vec[] { DenseVector.toDenseVec(139, 73, 113, 167, 135, 100, 187), DenseVector.toDenseVec(116, 54, 106, 143, 136, 81, 153), DenseVector.toDenseVec(130, 42, 95, 142, 136, 64, 158), DenseVector.toDenseVec(106, 79, 62, 114, 33, 123, 86), DenseVector.toDenseVec(149, 90, 99, 173, 103, 139, 152) } ); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_Matrix() { DenseMatrix ApB = new DenseMatrix(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(B); bCopy.mutableAdd(A); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); try { C.clone().mutableAdd(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_Matrix_ExecutorService() { DenseMatrix ApB = new DenseMatrix(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(B, threadpool); bCopy.mutableAdd(A, threadpool); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); try { C.clone().mutableAdd(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMutableAdd_double_Matrix_ExecutorService() { DenseMatrix ApB = new DenseMatrix(new double[][] { {6, 8, 6, 16, 17}, {2, 13, 10, 9, 15}, {1, 5, 14, 10, 10}, {6, 17, 5, 16, 6}, {9, 12, 6, 12, 7} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableAdd(1.0, B, threadpool); bCopy.mutableAdd(1.0, A, threadpool); assertEquals(ApB, aCopy); assertEquals(ApB, bCopy); aCopy.mutableAdd(-1.0, B, threadpool); assertEquals(A, aCopy); Matrix Aadd5 = new DenseMatrix(A.rows(), A.cols()); Aadd5.mutableAdd(5.0, A, threadpool); assertEquals(A.multiply(5), Aadd5); try { C.clone().mutableAdd(1.0, A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_double() { DenseMatrix ApTwo = new DenseMatrix(new double[][] { {1+2, 5+2, 4+2, 8+2, 9+2}, {1+2, 5+2, 7+2, 3+2, 7+2}, {0+2, 3+2, 8+2, 5+2, 6+2}, {3+2, 8+2, 0+2, 7+2, 0+2}, {1+2, 9+2, 2+2, 9+2, 6+2} } ); Matrix aCopy = A.clone(); aCopy.mutableAdd(2); assertEquals(ApTwo, aCopy); } /** * Test of mutableAdd method, of class DenseMatrix. */ @Test public void testMutableAdd_double_ExecutorService() { DenseMatrix ApTwo = new DenseMatrix(new double[][] { {1+2, 5+2, 4+2, 8+2, 9+2}, {1+2, 5+2, 7+2, 3+2, 7+2}, {0+2, 3+2, 8+2, 5+2, 6+2}, {3+2, 8+2, 0+2, 7+2, 0+2}, {1+2, 9+2, 2+2, 9+2, 6+2} } ); Matrix aCopy = A.clone(); aCopy.mutableAdd(2, threadpool); assertEquals(ApTwo, aCopy); } /** * Test of mutableSubtract method, of class DenseMatrix. */ @Test public void testMutableSubtract_Matrix() { DenseMatrix AmB = new DenseMatrix(new double[][] { {-4, 2, 2, 0, 1}, { 0, -3, 4, -3, -1}, {-1, 1, 2, 0, 2}, { 0, -1, -5, -2, -6}, {-7, 6, -2, 6, 5} } ); DenseMatrix BmA = new DenseMatrix(new double[][] { {-4*-1, 2*-1, 2*-1, 0*-1, 1*-1}, { 0*-1, -3*-1, 4*-1, -3*-1, -1*-1}, {-1*-1, 1*-1, 2*-1, 0*-1, 2*-1}, { 0*-1, -1*-1, -5*-1, -2*-1, -6*-1}, {-7*-1, 6*-1, -2*-1, 6*-1, 5*-1} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableSubtract(B); bCopy.mutableSubtract(A); assertEquals(AmB, aCopy); assertEquals(BmA, bCopy); try { C.clone().mutableSubtract(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableSubtract method, of class DenseMatrix. */ @Test public void testMutableSubtract_Matrix_ExecutorService() { DenseMatrix AmB = new DenseMatrix(new double[][] { {-4, 2, 2, 0, 1}, { 0, -3, 4, -3, -1}, {-1, 1, 2, 0, 2}, { 0, -1, -5, -2, -6}, {-7, 6, -2, 6, 5} } ); DenseMatrix BmA = new DenseMatrix(new double[][] { {-4*-1, 2*-1, 2*-1, 0*-1, 1*-1}, { 0*-1, -3*-1, 4*-1, -3*-1, -1*-1}, {-1*-1, 1*-1, 2*-1, 0*-1, 2*-1}, { 0*-1, -1*-1, -5*-1, -2*-1, -6*-1}, {-7*-1, 6*-1, -2*-1, 6*-1, 5*-1} } ); Matrix aCopy = A.clone(); Matrix bCopy = B.clone(); aCopy.mutableSubtract(B, threadpool); bCopy.mutableSubtract(A, threadpool); assertEquals(AmB, aCopy); assertEquals(BmA, bCopy); try { C.clone().mutableSubtract(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector Ab = new DenseVector(Arrays.asList(148.0, 110.0, 103.0, 94.0, 149.0)); assertEquals(Ab, A.multiply(b)); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); assertEquals(Cz, C.multiply(z)); } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Vec_Double_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector store = b.deepCopy(); A.multiply(b, 3.0, store); assertEquals(new DenseVector(new double[]{ 448, 335, 311, 288, 454}), store); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); store.zeroOut(); C.multiply(z, 1.0, store); assertEquals(Cz, store); } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Matrix() { Matrix result; result = A.multiply(B); assertEquals(AB, result); result = B.multiply(A); assertEquals(BA, result); result = A.multiply(C); assertEquals(AC, result); try { C.multiply(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMultiply_Matrix_Matrix() { DenseMatrix R = new DenseMatrix(A.rows(), B.cols()); A.multiply(B, R); assertEquals(AB, R); A.multiply(B, R); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.multiply(A, R); assertEquals(BA, R); B.multiply(A, R); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.multiply(C, R); assertEquals(AC, R); A.multiply(C, R); assertEquals(AC.multiply(2), R); try { R.multiply(A, C); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { A.multiply(B, C); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of multiply method, of class DenseMatrix. */ @Test public void testMultiply_Matrix_ExecutorService() { Matrix result; result = A.multiply(B, threadpool); assertEquals(AB, result); result = B.multiply(A, threadpool); assertEquals(BA, result); result = A.multiply(C, threadpool); assertEquals(AC, result); try { C.multiply(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testMultiply_Matrix_ExecutorService_Matrix() { DenseMatrix R = new DenseMatrix(A.rows(), B.cols()); A.multiply(B, R, threadpool); assertEquals(AB, R); A.multiply(B, R, threadpool); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.multiply(A, R, threadpool); assertEquals(BA, R); B.multiply(A, R, threadpool); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.multiply(C, R, threadpool); assertEquals(AC, R); A.multiply(C, R, threadpool); assertEquals(AC.multiply(2), R); try { R.multiply(A, C, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { A.multiply(B, C, threadpool); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } /** * Test of mutableMultiply method, of class DenseMatrix. */ @Test public void testMutableMultiply_double() { DenseMatrix AtTwo = new DenseMatrix(new double[][] { {1*2, 5*2, 4*2, 8*2, 9*2}, {1*2, 5*2, 7*2, 3*2, 7*2}, {0*2, 3*2, 8*2, 5*2, 6*2}, {3*2, 8*2, 0*2, 7*2, 0*2}, {1*2, 9*2, 2*2, 9*2, 6*2} } ); Matrix aCopy = A.clone(); aCopy.mutableMultiply(2); assertEquals(AtTwo, aCopy); } /** * Test of mutableMultiply method, of class DenseMatrix. */ @Test public void testMutableMultiply_double_ExecutorService() { DenseMatrix AtTwo = new DenseMatrix(new double[][] { {1*2, 5*2, 4*2, 8*2, 9*2}, {1*2, 5*2, 7*2, 3*2, 7*2}, {0*2, 3*2, 8*2, 5*2, 6*2}, {3*2, 8*2, 0*2, 7*2, 0*2}, {1*2, 9*2, 2*2, 9*2, 6*2} } ); Matrix aCopy = A.clone(); aCopy.mutableMultiply(2, threadpool); assertEquals(AtTwo, aCopy); } /** * Test of transpose method, of class DenseMatrix. */ @Test public void testTranspose() { DenseMatrix CTranspose = new DenseMatrix(new double[][] { {1, 5, 8, 9, 1}, {6, 5, 0, 3, 2}, {8, 3, 5, 2, 6}, {3, 7, 7, 7, 5}, {1, 2, 9, 2, 8}, {5, 10, 1, 4, 1}, {10, 0, 8, 8, 9} } ); assertEquals(CTranspose, C.transpose()); } /** * Test of get method, of class DenseMatrix. */ @Test public void testGet() { //Tests both testSet(); } /** * Test of set method, of class DenseMatrix. */ @Test public void testSet() { DenseMatrix toSet = new DenseMatrix(A.rows(), A.cols()); for(int i = 0; i < A.rows(); i++) for(int j = 0; j < A.cols(); j++) toSet.set(i, j, A.get(i, j)); assertEquals(A, toSet); } /** * Test of rows method, of class DenseMatrix. */ @Test public void testRows() { assertEquals(5, A.rows()); } /** * Test of cols method, of class DenseMatrix. */ @Test public void testCols() { assertEquals(5, A.cols()); assertEquals(7, C.cols()); } /** * Test of isSparse method, of class DenseMatrix. */ @Test public void testIsSparce() { assertEquals(false, A.isSparce()); } /** * Test of nnz method, of class DenseMatrix. */ @Test public void testNnz() { assertEquals(5*5, A.nnz()); assertEquals(5*7, C.nnz()); } /** * Test of clone method, of class DenseMatrix. */ @Test public void testCopy() { Matrix ACopy = A.clone(); assertEquals(A, ACopy); assertEquals(A.multiply(B), ACopy.multiply(B)); } /** * Test of swapRows method, of class DenseMatrix. */ @Test public void testSwapRows() { System.out.println("swapRows"); Matrix Expected = new DenseMatrix(new double[][] { {5, 5, 3, 7, 2, 10, 0}, {1, 2, 6, 5, 8, 1, 9}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 6, 8, 3, 1, 5, 10} } ); Matrix test = C.clone(); test.swapRows(1, 0); test.swapRows(1, 0); assertEquals(C, test); test.swapRows(0, 1); test.swapRows(0, 1); assertEquals(C, test); test.swapRows(3, 3); assertEquals(C, test); test.swapRows(0, 4); test.swapRows(0, 1); assertEquals(Expected, test); test = C.clone(); test.swapRows(4, 0); test.swapRows(1, 0); assertEquals(Expected, test); } /** * Test of zeroOut method, of class DenseMatrix. */ @Test public void testZeroOut() { System.out.println("zeroOut"); Matrix test = C.clone(); test.zeroOut(); for(int i = 0; i < test.rows(); i++) for(int j = 0; j < test.cols(); j++) assertEquals(0, test.get(i, j), 0); } /** * Test of lup method, of class DenseMatrix. */ @Test public void testLup_0args() { System.out.println("lup"); Matrix[] lup; lup = A.clone().lup(); assertTrue(lup[2].multiply(A).equals(lup[0].multiply(lup[1]), 1e-14)); lup = C.clone().lup(); assertTrue(lup[2].multiply(C).equals(lup[0].multiply(lup[1]), 1e-14)); lup = C.transpose().lup(); assertTrue(lup[2].multiply(C.transpose()).equals(lup[0].multiply(lup[1]), 1e-14)); } /** * Test of lup method, of class DenseMatrix. */ @Test public void testLup_ExecutorService() { System.out.println("lup"); Matrix[] lup; lup = A.clone().lup(threadpool); assertTrue(lup[2].multiply(A, threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); lup = C.clone().lup(threadpool); assertTrue(lup[2].multiply(C, threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); lup = C.transpose().lup(threadpool); assertTrue(lup[2].multiply(C.transpose(), threadpool).equals(lup[0].multiply(lup[1], threadpool), 1e-14)); } /** * Test of mutableTranspose method, of class DenseMatrix. */ @Test public void testMutableTranspose() { System.out.println("mutableTranspose"); try { C.clone().mutableTranspose(); fail("Can not do a mutable transpose for rectangular matrix, error should have been thrown"); } catch(Exception ex) { } DenseMatrix ATranspose = new DenseMatrix(new double[][] { {1, 1, 0, 3, 1}, {5, 5, 3, 8, 9}, {4, 7, 8, 0, 2}, {8, 3, 5, 7, 9}, {9, 7, 6, 0, 6}, } ); Matrix AT = A.clone(); AT.mutableTranspose(); assertEquals(ATranspose, AT); } /** * Test of qr method, of class DenseMatrix. */ @Test public void testQr_0args() { System.out.println("qr"); Matrix[] qr; //3 properties to test // R is uper triangular // Q*Q' = I // A = Q*R qr = A.clone().qr(); assertTrue(A.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(A.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = B.clone().qr(); assertTrue(B.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(B.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.clone().qr(); assertTrue(C.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.transpose().qr(); assertTrue(C.transpose().equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.transpose().rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); } /** * Test of qr method, of class DenseMatrix. */ @Test public void testQr_ExecutorService() { System.out.println("qr"); Matrix[] qr; //3 properties to test // R is uper triangular // Q*Q' = I // A = Q*R qr = A.clone().qr(threadpool); assertTrue(A.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(A.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = B.clone().qr(threadpool); assertTrue(B.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(B.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.clone().qr(threadpool); assertTrue(C.equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); qr = C.transpose().qr(threadpool); assertTrue(C.transpose().equals(qr[0].multiply(qr[1]), 1e-14)); assertTrue(DenseMatrix.eye(C.transpose().rows()).equals(qr[0].multiply(qr[0].transpose()), 1e-14)); } @Test public void testTransposeMultiply_Matrix() { Matrix result; result = A.transpose().transposeMultiply(B); assertEquals(AB, result); result = B.transpose().transposeMultiply(A); assertEquals(BA, result); result = A.transpose().transposeMultiply(C); assertEquals(AC, result); result = C.transposeMultiply(A); assertEquals(new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ), result); result = C.transposeMultiply(C); assertEquals(new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }), result); try { C.transpose().transposeMultiply(A); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_Matrix() { Matrix R = new DenseMatrix(A.rows(), B.cols()); A.transpose().transposeMultiply(B, R); assertEquals(AB, R); A.transpose().transposeMultiply(B, R); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.transpose().transposeMultiply(A, R); assertEquals(BA, R); B.transpose().transposeMultiply(A, R); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.transpose().transposeMultiply(C, R); assertEquals(AC, R); A.transpose().transposeMultiply(C, R); assertEquals(AC.multiply(2), R); R = new DenseMatrix(C.cols(), A.cols()); C.transposeMultiply(A, R); Matrix CtA = new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ); assertEquals(CtA, R); C.transposeMultiply(A, R); assertEquals(CtA.multiply(2), R); R = new DenseMatrix(C.cols(), C.cols()); C.transposeMultiply(C, R); Matrix CtC = new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }); assertEquals(CtC, R); C.transposeMultiply(C, R); assertEquals(CtC.multiply(2), R); try { A.transpose().transposeMultiply(B, R); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { C.transpose().transposeMultiply(A, R); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_ExecutorService() { Matrix result; result = A.transpose().transposeMultiply(B, threadpool); assertEquals(AB, result); result = B.transpose().transposeMultiply(A, threadpool); assertEquals(BA, result); result = A.transpose().transposeMultiply(C, threadpool); assertEquals(AC, result); result = C.transposeMultiply(A, threadpool); assertEquals(new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ), result); result = C.transposeMultiply(C, threadpool); assertEquals(new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }), result); try { C.transpose().transposeMultiply(A, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Matrix_Matrix_ExecutorService() { Matrix R = new DenseMatrix(A.rows(), B.cols()); A.transpose().transposeMultiply(B, R, threadpool); assertEquals(AB, R); A.transpose().transposeMultiply(B, R, threadpool); assertEquals(AB.multiply(2), R); R = new DenseMatrix(B.rows(), A.cols()); B.transpose().transposeMultiply(A, R, threadpool); assertEquals(BA, R); B.transpose().transposeMultiply(A, R, threadpool); assertEquals(BA.multiply(2), R); R = new DenseMatrix(A.rows(), C.cols()); A.transpose().transposeMultiply(C, R, threadpool); assertEquals(AC, R); A.transpose().transposeMultiply(C, R, threadpool); assertEquals(AC.multiply(2), R); R = new DenseMatrix(C.cols(), A.cols()); C.transposeMultiply(A, R, threadpool); Matrix CtA = new DenseMatrix(new double[][] { {34, 135, 105, 135, 98}, {22, 97, 63, 102, 101}, {23, 140, 105, 166, 159}, {36, 172, 127, 174, 148}, {17, 130, 106, 145, 125}, {28, 119, 100, 112, 127}, {43, 219, 122, 257, 192}, } ); assertEquals(CtA, R); C.transposeMultiply(A, R, threadpool); assertEquals(CtA.multiply(2), R); R = new DenseMatrix(C.cols(), C.cols()); C.transposeMultiply(C, R, threadpool); Matrix CtC = new DenseMatrix(new double[][] { {172, 60, 87, 162, 109, 100, 155}, { 60, 74, 81, 84, 38, 94, 102}, { 87, 81, 138, 124, 111, 89, 190}, {162, 84, 124, 181, 134, 125, 187}, {109, 38, 111, 134, 154, 50, 170}, {100, 94, 89, 125, 50, 143, 99}, {155, 102, 190, 187, 170, 99, 309}, }); assertEquals(CtC, R); C.transposeMultiply(C, R, threadpool); assertEquals(CtC.multiply(2), R); try { A.transpose().transposeMultiply(B, R, threadpool); fail("Expected error about target matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } try { C.transpose().transposeMultiply(A, R, threadpool); fail("Expected error about matrix dimensions"); } catch(ArithmeticException ex) { //Good! We expected failure } } @Test public void testTransposeMultiply_Double_Vec() { DenseVector b = new DenseVector(Arrays.asList(4.0, 5.0, 2.0, 6.0, 7.0)); DenseVector z = new DenseVector(Arrays.asList(2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 0.0)); DenseVector Ab = new DenseVector(Arrays.asList(148.0, 110.0, 103.0, 94.0, 149.0)); assertEquals(Ab, A.transpose().transposeMultiply(1.0, b)); assertEquals(Ab.multiply(7.0), A.transpose().transposeMultiply(7.0, b)); DenseVector Cz = new DenseVector(Arrays.asList(62.0, 100.0, 88.0, 74.0, 68.0)); assertEquals(Cz, C.transpose().transposeMultiply(1.0, z)); assertEquals(Cz.multiply(19.0), C.transpose().transposeMultiply(19.0, z)); try { C.transposeMultiply(1.0, z); fail("Dimensions were in disagreement, should not have worked"); } catch(Exception ex) { } } @Test public void testChangeSize() { MatrixOfVecs Acpy = A.clone(); Acpy.changeSize(Acpy.rows()-1, Acpy.cols()-1); assertEquals(Acpy.rows(), A.rows()-1); assertEquals(Acpy.cols(), A.cols()-1); for(int i = 0; i < Acpy.rows(); i++) for(int j = 0; j < Acpy.cols(); j++) assertEquals(Acpy.get(i, j), A.get(i, j), 0.0); //Expand back out and make sure the values are zero on the sides Acpy.changeSize(Acpy.rows()+2, Acpy.cols()+2); assertEquals(Acpy.rows(), A.rows()+1); assertEquals(Acpy.cols(), A.cols()+1); for(int i = 0; i < Acpy.rows(); i++) for(int j = 0; j < Acpy.cols(); j++) if(i < A.rows()-1 && j < A.cols()-1) assertEquals(A.get(i, j), Acpy.get(i, j), 0.0); else assertEquals(0.0, Acpy.get(i, j), 0.0); } }
34,836
28.103592
136
java
JSAT
JSAT-master/JSAT/test/jsat/linear/MatrixStatisticsTest.java
/* * Copyright (C) 2018 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear; import java.util.List; import java.util.Random; import jsat.distributions.multivariate.NormalM; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MatrixStatisticsTest { public MatrixStatisticsTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testMCD() { Random rand = RandomUtil.getRandom(); Vec mainMean = new DenseVector(5); Matrix mainCov = Matrix.random(5, 5, rand); mainCov = mainCov.multiplyTranspose(mainCov); Vec offMean = DenseVector.random(5, rand).multiply(1000); Matrix offCov = Matrix.random(5, 5, rand); offCov = offCov.multiplyTranspose(offCov).multiply(550); NormalM main = new NormalM(mainMean, mainCov); NormalM off = new NormalM(offMean, offCov); double mainRatio = 0.6; for(boolean parallel : new boolean[]{false,true}) for(int N : new int[]{550, 1000, 1499, 3000}) { int n_m = (int) (N*mainRatio); int n_o = (int) (N*(1-mainRatio)); List<Vec> vecs = main.sample(n_m, rand); vecs.addAll(off.sample(n_o, rand)); Vec estMean = new DenseVector(5); Matrix estCov = new DenseMatrix(5, 5); MatrixStatistics.FastMCD(estMean, estCov, vecs, parallel); assertTrue(estMean.equals(mainMean, 0.2)); //Let cov be looser, but dif of 1.0 is still way closer than the huge 55x of the offCov assertTrue(estCov.equals(mainCov, 0.5)); //and confirm dumb estimate isn't very good estMean.zeroOut(); MatrixStatistics.meanVector(estMean, vecs); estCov.zeroOut(); MatrixStatistics.covarianceMatrix(estMean, estCov, vecs); assertFalse(estMean.equals(mainMean, 0.2)); assertFalse(estCov.equals(mainCov, 1.0)); } } }
3,121
27.907407
100
java
JSAT
JSAT-master/JSAT/test/jsat/linear/MatrixTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.linear; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.math.OnLineStatistics; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MatrixTest { private static ExecutorService ex; public MatrixTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of OuterProductUpdate method, of class Matrix. */ @Test public void testOuterProductUpdate_4args() { System.out.println("OuterProductUpdate"); Matrix A = Matrix.eye(4); Vec x = new DenseVector(new double[]{1, 2, 3, 4}); Vec y = new DenseVector(new double[]{5, 6, 7, 8}); double c = 2.0; double[][] expected = new double[][] { {11, 12, 14, 16}, {20, 25, 28, 32}, {30, 36, 43, 48}, {40, 48, 56, 65}, }; Matrix.OuterProductUpdate(A, x, y, c); for(int i = 0; i < expected.length; i++) for(int j = 0; j < expected.length; j++) assertEquals(expected[i][j], A.get(i, j), 0.0); } /** * Test of OuterProductUpdate method, of class Matrix. */ @Test public void testOuterProductUpdate_5args() { System.out.println("OuterProductUpdate"); Matrix A = Matrix.eye(4); Vec x = new DenseVector(new double[]{1, 2, 3, 4}); Vec y = new DenseVector(new double[]{5, 6, 7, 8}); double c = 2.0; double[][] expected = new double[][] { {11, 12, 14, 16}, {20, 25, 28, 32}, {30, 36, 43, 48}, {40, 48, 56, 65}, }; Matrix.OuterProductUpdate(A, x, y, c, ex); for(int i = 0; i < expected.length; i++) for(int j = 0; j < expected.length; j++) assertEquals(expected[i][j], A.get(i, j), 0.0); } /** * Test of eye method, of class Matrix. */ @Test public void testEye() { System.out.println("eye"); for(int k = 1; k < 10; k++) { Matrix I = Matrix.eye(k); for(int i = 0; i < I.rows(); i++) for(int j = 0; j < I.cols(); j++) if(i == j) assertEquals(1.0, I.get(i, j), 0.0); else assertEquals(0.0, I.get(i, j), 0.0); } } /** * Test of random method, of class Matrix. */ @Test public void testRandom() { System.out.println("random"); int rows = 100; int cols = 100; Random rand = RandomUtil.getRandom(); DenseMatrix result = Matrix.random(rows, cols, rand); OnLineStatistics stats = new OnLineStatistics(); for (int i = 0; i < result.rows(); i++) for (int j = 0; j < result.cols(); j++) stats.add(result.get(i, j)); //if its all random from [0, 1], the mean should be 0.5 assertEquals(0.5, stats.getMean(), 0.05); } /** * Test of diag method, of class Matrix. */ @Test public void testDiag() { System.out.println("diag"); assertEquals(Matrix.eye(5), Matrix.diag(new ConstantVector(1.0, 5))); } /** * Test of diagMult method, of class Matrix. */ @Test public void testDiagMult_Matrix_Vec() { //TODO add diagonal test case System.out.println("diagMult"); Matrix A = new DenseMatrix(new double[][] { { 0, 8, 7, 5, 5}, { 6, 10, 4, 8, 4}, {10, 7, 5, 8, 6}, { 5, 2, 2, 5, 5}, { 6, 7, 10, 5, 8}, }); Vec b = new DenseVector(new double[]{4, -3, 3, -4, 2}); double[][] expected = new double[][] { { 0, -24, 21, -20, 10}, {24, -30, 12, -32, 8}, {40, -21, 15, -32, 12}, {20, -6, 6, -20, 10}, {24, -21, 30, -20, 16}, }; Matrix.diagMult(A, b); assertEquals(new DenseMatrix(expected), A); } /** * Test of diagMult method, of class Matrix. */ @Test public void testDiagMult_Vec_Matrix() { //TODO add diagonal test case System.out.println("diagMult"); Matrix A = new DenseMatrix(new double[][] { { 0, 8, 7, 5, 5}, { 6, 10, 4, 8, 4}, {10, 7, 5, 8, 6}, { 5, 2, 2, 5, 5}, { 6, 7, 10, 5, 8}, }); Vec b = new DenseVector(new double[]{4, -3, 3, -4, 2}); double[][] expected = new double[][] { { 0, 32, 28, 20, 20}, {-18, -30, -12, -24, -12}, { 30, 21, 15, 24, 18}, {-20, -8, -8, -20, -20}, { 12, 14, 20, 10, 16}, }; Matrix.diagMult(b, A); assertEquals(new DenseMatrix(expected), A); } /** * Test of isSymmetric method, of class Matrix. */ @Test public void testIsSymmetric_Matrix_double() { System.out.println("isSymmetric"); Matrix A = Matrix.eye(5); assertTrue(Matrix.isSymmetric(A, 0.0)); A.set(3, 4, 2.0); A.set(4, 3, 2.0); assertTrue(Matrix.isSymmetric(A, 0.0)); A.set(3, 2, 0.01); assertFalse(Matrix.isSymmetric(A, 0.0)); assertTrue(Matrix.isSymmetric(A, 0.1)); } /** * Test of isSymmetric method, of class Matrix. */ @Test public void testIsSymmetric_Matrix() { System.out.println("isSymmetric"); Matrix A = Matrix.eye(5); assertTrue(Matrix.isSymmetric(A)); A.set(3, 4, 2.0); A.set(4, 3, 2.0); assertTrue(Matrix.isSymmetric(A)); A.set(3, 2, 2); assertFalse(Matrix.isSymmetric(A)); } /** * Test of pascal method, of class Matrix. */ @Test public void testPascal() { System.out.println("pascal"); Matrix P = Matrix.pascal(6); for(int i = 0; i < P.rows(); i++) { assertEquals(1.0, P.get(i, 0), 0.0); assertEquals(1.0, P.get(0, i), 0.0); } for(int i = 1; i < P.rows(); i++) for(int j = 1; j < P.cols(); j++) assertEquals(P.get(i-1, j)+P.get(i, j-1), P.get(i, j), 0.0); } }
7,386
24.472414
77
java
JSAT
JSAT-master/JSAT/test/jsat/linear/Poly2VecTest.java
package jsat.linear; import java.util.Iterator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class Poly2VecTest { Vec baseVec; Vec denseBase; Vec truePolyVec; Vec truePolyDense; int[] x, y; public Poly2VecTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { baseVec = new DenseVector(new double[]{2.0, 0.0, 3.0, 5.0, 0.0, 0.0, 7.0, 0.0}); denseBase = new DenseVector(new double[]{2.0, 3.0, 5.0, 7.0}); truePolyVec = new DenseVector(45); truePolyDense = new DenseVector(15); truePolyDense.set(0, 1.0); truePolyVec.set(0, 1.0); for(int i = 0; i < baseVec.length(); i++) truePolyVec.set(i+1, baseVec.get(i)); for(int i = 0; i < denseBase.length(); i++) truePolyDense.set(i+1, denseBase.get(i)); int offSet = baseVec.length()+1; int pos = 0; x = new int[truePolyVec.length()]; y = new int[truePolyVec.length()]; for(int i = 0; i < baseVec.length(); i++) for(int j = i; j < baseVec.length(); j++) { x[pos] = i; y[pos] = j; truePolyVec.set(offSet + (pos++), baseVec.get(i)*baseVec.get(j)); } offSet = denseBase.length()+1; pos = 0; for(int i = 0; i < denseBase.length(); i++) for(int j = i; j < denseBase.length(); j++) { truePolyDense.set(offSet + (pos++), denseBase.get(i)*denseBase.get(j)); } } @After public void tearDown() { } /** * Test of length method, of class Poly2Vec. */ @Test public void testLength() { System.out.println("length"); Poly2Vec polyDense = new Poly2Vec(denseBase); assertEquals(truePolyDense.length(), polyDense.length()); Poly2Vec polyVec = new Poly2Vec(baseVec); assertEquals(truePolyVec.length(), polyVec.length()); } /** * Test of nnz method, of class Poly2Vec. */ @Test public void testNnz() { System.out.println("nnz"); Poly2Vec polyDense = new Poly2Vec(denseBase); assertEquals(truePolyDense.nnz(), polyDense.nnz()); Poly2Vec polyVec = new Poly2Vec(baseVec); assertEquals(truePolyVec.nnz(), polyVec.nnz()); } /** * Test of get method, of class Poly2Vec. */ @Test public void testGet() { System.out.println("get"); Poly2Vec polyDense = new Poly2Vec(denseBase); for(int i = 0; i < truePolyDense.length(); i++) assertEquals(truePolyDense.get(i), polyDense.get(i), 0.0); Poly2Vec polyVec = new Poly2Vec(baseVec); for(int i = 0; i < truePolyVec.length(); i++) assertEquals(truePolyVec.get(i), polyVec.get(i), 0.0); try { polyVec.get(-1); fail("Should not be able to access Index"); } catch(IndexOutOfBoundsException ex) { //good! } try { polyVec.get(polyVec.length()); fail("Should not be able to access Index"); } catch(IndexOutOfBoundsException ex) { //good! } } /** * Test of set method, of class Poly2Vec. */ @Test public void testSet() { System.out.println("set"); Poly2Vec polyVec = new Poly2Vec(baseVec); try { polyVec.set(2, Double.MAX_VALUE); fail("Should not be able to alter poly vec wrappers"); } catch(Exception ex) { //good! } } /** * Test of isSparse method, of class Poly2Vec. */ @Test public void testIsSparse() { System.out.println("isSparse"); Poly2Vec polyVec = new Poly2Vec(baseVec); assertFalse(polyVec.isSparse()); polyVec = new Poly2Vec(new SparseVector(baseVec)); assertTrue(polyVec.isSparse()); } /** * Test of clone method, of class Poly2Vec. */ @Test public void testClone() { System.out.println("clone"); assertEquals(truePolyDense, new Poly2Vec(new SparseVector(denseBase)).clone()); assertEquals(truePolyVec, new Poly2Vec(new SparseVector(baseVec)).clone()); } /** * Test of getNonZeroIterator method, of class Poly2Vec. */ @Test public void testGetNonZeroIterator() { System.out.println("getNonZeroIterator"); Poly2Vec polyDense = new Poly2Vec(denseBase); for(int i = 0; i < truePolyDense.length(); i++) { Iterator<IndexValue> trueIter = truePolyDense.getNonZeroIterator(i); Iterator<IndexValue> polyIter = polyDense.getNonZeroIterator(i); assertTrue(trueIter.hasNext() == polyIter.hasNext()); while(trueIter.hasNext()) { assertTrue(trueIter.hasNext() == polyIter.hasNext()); IndexValue trueIV = trueIter.next(); IndexValue polyIV = polyIter.next(); assertEquals(trueIV.getIndex(), polyIV.getIndex()); assertEquals(trueIV.getValue(), polyIV.getValue(), 0.0); assertTrue(trueIter.hasNext() == polyIter.hasNext()); } } Poly2Vec polyVec = new Poly2Vec(baseVec); for(int i = 0; i < truePolyVec.length(); i++) { Iterator<IndexValue> trueIter = truePolyVec.getNonZeroIterator(i); Iterator<IndexValue> polyIter = polyVec.getNonZeroIterator(i); assertTrue(trueIter.hasNext() == polyIter.hasNext()); while(trueIter.hasNext()) { assertTrue(trueIter.hasNext() == polyIter.hasNext()); IndexValue trueIV = trueIter.next(); IndexValue polyIV = polyIter.next(); assertEquals(trueIV.getIndex(), polyIV.getIndex()); assertEquals(trueIV.getValue(), polyIV.getValue(), 0.0); assertTrue(trueIter.hasNext() == polyIter.hasNext()); } } } }
6,657
27.092827
88
java
JSAT
JSAT-master/JSAT/test/jsat/linear/QRDecompositionTest.java
package jsat.linear; import java.util.Arrays; import jsat.utils.SystemInfo; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class QRDecompositionTest { /** * 5x5 */ static DenseMatrix A; /** * 5x5 */ static DenseMatrix B; /** * 5x7 */ static DenseMatrix C; static ExecutorService threadpool = Executors.newFixedThreadPool(SystemInfo.LogicalCores+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public QRDecompositionTest() { } @BeforeClass public static void setUpClass() throws Exception { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new DenseMatrix(new double[][] { {5, 3, 2, 8, 8}, {1, 8, 3, 6, 8}, {1, 2, 6, 5, 4}, {3, 9, 5, 9, 6}, {8, 3, 4, 3, 1} } ); C = new DenseMatrix(new double[][] { {1, 6, 8, 3, 1, 5, 10}, {5, 5, 3, 7, 2, 10, 0}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 2, 6, 5, 8, 1, 9} } ); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of absDet method, of class QRDecomposition. */ @Test public void testAbsDet() { System.out.println("absDet"); QRDecomposition instance = null; instance = new QRDecomposition(A); assertEquals(3073, instance.absDet(), 1e-10); instance = new QRDecomposition(B); assertEquals(8068, instance.absDet(), 1e-10); instance = new QRDecomposition(C); try { instance.absDet(); fail("Can not take the determinant of a non square matrix"); } catch(ArithmeticException ex) { } } /** * Test of solve method, of class QRDecomposition. */ @Test public void testSolve_Vec() { System.out.println("solve"); Vec b = new DenseVector(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0 )); QRDecomposition instance = null; instance = new QRDecomposition(A); Vec x = instance.solve(b); assertTrue(A.multiply(x).equals(b, 1e-10)); instance = new QRDecomposition(C); x = instance.solve(b); assertTrue(C.multiply(x).equals(b, 1e-10)); } /** * Test of solve method, of class QRDecomposition. */ @Test public void testSolve_Matrix() { System.out.println("solve"); QRDecomposition instance = null; Matrix x; instance = new QRDecomposition(A); x = instance.solve(B); assertTrue(A.multiply(x).equals(B, 1e-10)); instance = new QRDecomposition(A); x = instance.solve(C); assertTrue(A.multiply(x).equals(C, 1e-10)); instance = new QRDecomposition(C); x = instance.solve(A); assertTrue(C.multiply(x).equals(A, 1e-10)); instance = new QRDecomposition(C.transpose()); try { instance.solve(A); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } instance = new QRDecomposition(A); try { instance.solve(C.transpose()); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } } /** * Test of solve method, of class QRDecomposition. */ @Test public void testSolve_Matrix_ExecutorService() { System.out.println("solve"); QRDecomposition instance = null; Matrix x; instance = new QRDecomposition(A); x = instance.solve(B, threadpool); assertTrue(A.multiply(x).equals(B, 1e-10)); instance = new QRDecomposition(A); x = instance.solve(C, threadpool); assertTrue(A.multiply(x).equals(C, 1e-10)); instance = new QRDecomposition(C); x = instance.solve(A, threadpool); assertTrue(C.multiply(x).equals(A, 1e-10)); instance = new QRDecomposition(C.transpose()); try { instance.solve(A, threadpool); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } instance = new QRDecomposition(A); try { instance.solve(C.transpose(), threadpool); fail("The matrix dimensions do not agree!"); } catch(ArithmeticException ex) { } } }
5,414
23.174107
117
java
JSAT
JSAT-master/JSAT/test/jsat/linear/ShiftedVecTest.java
package jsat.linear; import java.util.Iterator; import java.util.Random; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ShiftedVecTest { private Vec a_base; private Vec b_base; private double shift_a; private double shift_b; private Vec a_dense; private Vec a_sparse; private Vec b_dense; private Vec b_sparse; private Vec rand_x; private Vec rand_y; public ShiftedVecTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { a_base = new SparseVector(12, 6); a_base.set(0, 1.0); a_base.set(1, 2.0); a_base.set(3, -2.0); a_base.set(4, 5.0); a_base.set(8, -3.0); a_base.set(11, 1.0); b_base = new SparseVector(12, 6); b_base.set(0, 1.0); b_base.set(1, -2.0); b_base.set(3, -3.0); b_base.set(4, 4.0); b_base.set(7, -2.0); b_base.set(10, 1.0); shift_a = -1; shift_b = 2; a_dense = new DenseVector(a_base); a_sparse = new SparseVector(a_base); a_dense.mutableAdd(shift_a); a_sparse.mutableAdd(shift_a); b_dense = new DenseVector(b_base); b_sparse = new SparseVector(b_base); b_dense.mutableAdd(shift_b); b_sparse.mutableAdd(shift_b); Random rand = RandomUtil.getRandom(); rand_x = new DenseVector(a_base.length()); rand_y = new DenseVector(a_base.length()); for(int i =0 ; i < rand_x.length(); i++) { rand_x.set(i, Math.round(rand.nextDouble()*10)); rand_y.set(i, Math.round(rand.nextDouble()*10)); } } @After public void tearDown() { } /** * Test of setShift method, of class ShiftedVec. */ @Test public void testSetShift() { System.out.println("setShift"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(shift_a, a.getShift(), 0.0); a.setShift(shift_b); assertEquals(shift_b, a.getShift(), 0.0); } /** * Test of embedShift method, of class ShiftedVec. */ @Test public void testEmbedShift() { System.out.println("embedShift"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.embedShift(); assertEquals(0.0, a.getShift(), 0.0); assertTrue(a.getBase().equals(a_dense, 1e-10)); } /** * Test of length method, of class ShiftedVec. */ @Test public void testLength() { System.out.println("length"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_base.length(), a.length()); } /** * Test of get method, of class ShiftedVec. */ @Test public void testGet() { System.out.println("get"); ShiftedVec a = new ShiftedVec(a_base, shift_a); ShiftedVec b = new ShiftedVec(b_base, shift_b); for(int i =0 ; i < a.length(); i++) { assertEquals(a_dense.get(i), a.get(i), 1e-10); assertEquals(b_dense.get(i), b.get(i), 1e-10); } } /** * Test of set method, of class ShiftedVec. */ @Test public void testSet() { System.out.println("set"); ShiftedVec a = new ShiftedVec(a_base, shift_a); Random rand = RandomUtil.getRandom(); for(int round = 0; round < 100; round++) { int indx = rand.nextInt(a.length()); double tmp = rand.nextDouble(); a.set(indx, tmp); assertEquals(tmp, a.get(indx), 1e-10); assertEquals(tmp-shift_a, a_base.get(indx), 1e-10); } } /** * Test of increment method, of class ShiftedVec. */ @Test public void testIncrement() { System.out.println("increment"); ShiftedVec a = new ShiftedVec(a_base, shift_a); for(int i =0 ; i < a.length(); i++) { a.increment(i, (i+1)); a_dense.increment(i, (i+1)); assertEquals(a_dense.get(i), a.get(i), 1e-10); } } /** * Test of mutableAdd method, of class ShiftedVec. */ @Test public void testMutableAdd_Vec() { System.out.println("mutableAdd"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutableAdd(rand_x); a_dense.mutableAdd(rand_x); assertTrue(a.equals(a_dense, 1e-10)); ShiftedVec b = new ShiftedVec(b_base, shift_b); b.mutableAdd(a); b_dense.mutableAdd(a_dense); assertTrue(b.equals(b_dense, 1e-10)); } /** * Test of mutableAdd method, of class ShiftedVec. */ @Test public void testMutableAdd_double() { System.out.println("mutableAdd"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutableAdd(10); a_dense.mutableAdd(10); assertTrue(a.equals(a_dense, 1e-10)); ShiftedVec b = new ShiftedVec(b_base, shift_b); b.mutableAdd(2); b_dense.mutableAdd(2); assertTrue(b.equals(b_dense, 1e-10)); } /** * Test of mutableAdd method, of class ShiftedVec. */ @Test public void testMutableAdd_double_Vec() { System.out.println("mutableAdd"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutableAdd(10, rand_x); a_dense.mutableAdd(10, rand_x); assertTrue(a.equals(a_dense, 1e-10)); ShiftedVec b = new ShiftedVec(b_base, shift_b); b.mutableAdd(-3, a); b_dense.mutableAdd(-3, a_dense); assertTrue(b.equals(b_dense, 1e-10)); } /** * Test of mutableDivide method, of class ShiftedVec. */ @Test public void testMutableDivide() { System.out.println("mutableDivide"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutableDivide(10); a_dense.mutableDivide(10); assertTrue(a.equals(a_dense, 1e-10)); } /** * Test of mutableMultiply method, of class ShiftedVec. */ @Test public void testMutableMultiply() { System.out.println("mutableMultiply"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutableMultiply(10); a_dense.mutableMultiply(10); assertTrue(a.equals(a_dense, 1e-10)); ShiftedVec b = new ShiftedVec(b_base, shift_b); b.mutableMultiply(0); b_dense.mutableMultiply(0); assertTrue(b.equals(b_dense, 1e-10)); assertEquals(0.0, b.getShift(), 0.0); } /** * Test of mutablePairwiseDivide method, of class ShiftedVec. */ @Test public void testMutablePairwiseDivide() { System.out.println("mutablePairwiseDivide"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutablePairwiseDivide(rand_x.add(1)); a_dense.mutablePairwiseDivide(rand_x.add(1)); assertTrue(a.equals(a_dense, 1e-10)); } /** * Test of mutablePairwiseMultiply method, of class ShiftedVec. */ @Test public void testMutablePairwiseMultiply() { System.out.println("mutablePairwiseMultiply"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.mutablePairwiseDivide(rand_x); a_dense.mutablePairwiseDivide(rand_x); assertTrue(a.equals(a_dense, 1e-10)); } /** * Test of dot method, of class ShiftedVec. */ @Test public void testDot() { System.out.println("dot"); ShiftedVec a = new ShiftedVec(a_base, shift_a); ShiftedVec b = new ShiftedVec(b_base, shift_b); assertEquals(a_dense.dot(rand_x), a.dot(rand_x), 1e-10); assertEquals(a_dense.dot(rand_x), rand_x.dot(a), 1e-10); assertEquals(a_dense.dot(b_dense), a.dot(b), 1e-10);//shift on shift assertEquals(a_dense.dot(b_dense), a.dot(b_dense), 1e-10);//shift on dense assertEquals(a_dense.dot(b_dense), a_dense.dot(b), 1e-10);//dense on shift assertEquals(a_dense.dot(b_dense), a.dot(b_sparse), 1e-10);//shift on sparse assertEquals(a_dense.dot(b_dense), a_sparse.dot(b), 1e-10);//sparse on shift } /** * Test of zeroOut method, of class ShiftedVec. */ @Test public void testZeroOut() { System.out.println("zeroOut"); ShiftedVec a = new ShiftedVec(a_base, shift_a); a.zeroOut(); for(int i = 0; i < a.length(); i++) assertEquals(0.0, a.get(i), 0.0); assertEquals(0.0, a.getShift(), 0.0); } /** * Test of pNorm method, of class ShiftedVec. */ @Test public void testPNorm() { System.out.println("pNorm"); ShiftedVec a = new ShiftedVec(a_base, shift_a); double[] ps = {0.5, 1, 2, 2.5, 3, 10 }; for(double p : ps) assertEquals(a_dense.pNorm(p), a.pNorm(p), 1e-10); } /** * Test of mean method, of class ShiftedVec. */ @Test public void testMean() { System.out.println("mean"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.mean(), a.mean(), 1e-10); } /** * Test of variance method, of class ShiftedVec. */ @Test public void testVariance() { System.out.println("variance"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.variance(), a.variance(), 1e-10); } /** * Test of standardDeviation method, of class ShiftedVec. */ @Test public void testStandardDeviation() { System.out.println("standardDeviation"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.standardDeviation(), a.standardDeviation(), 1e-10); } /** * Test of kurtosis method, of class ShiftedVec. */ @Test public void testKurtosis() { System.out.println("kurtosis"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.kurtosis(), a.kurtosis(), 1e-10); } /** * Test of max method, of class ShiftedVec. */ @Test public void testMax() { System.out.println("max"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.max(), a.max(), 1e-10); } /** * Test of min method, of class ShiftedVec. */ @Test public void testMin() { System.out.println("min"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.min(), a.min(), 1e-10); } /** * Test of median method, of class ShiftedVec. */ @Test public void testMedian() { System.out.println("median"); ShiftedVec a = new ShiftedVec(a_base, shift_a); assertEquals(a_dense.median(), a.median(), 1e-10); } /** * Test of getNonZeroIterator method, of class ShiftedVec. */ @Test public void testGetNonZeroIterator() { System.out.println("getNonZeroIterator"); ShiftedVec a = new ShiftedVec(a_base, shift_a); ShiftedVec b = new ShiftedVec(b_base, shift_b); ShiftedVec c = new ShiftedVec(new ConstantVector(1.0, 12), -1); for(int start = 0; start < a.length(); start++) { Iterator<IndexValue> expIter = a_sparse.getNonZeroIterator(start); Iterator<IndexValue> actIter = a.getNonZeroIterator(start); assertTrue(expIter.hasNext() == actIter.hasNext()); while(expIter.hasNext()) { IndexValue expIV = expIter.next(); IndexValue actIV = actIter.next(); assertEquals(expIV.getIndex(), actIV.getIndex()); assertEquals(expIV.getValue(), actIV.getValue(), 1e-10); } assertTrue(expIter.hasNext() == actIter.hasNext()); //2nd pair expIter = b_sparse.getNonZeroIterator(start); actIter = b.getNonZeroIterator(start); assertTrue(expIter.hasNext() == actIter.hasNext()); while(expIter.hasNext()) { IndexValue expIV = expIter.next(); IndexValue actIV = actIter.next(); assertEquals(expIV.getIndex(), actIV.getIndex()); assertEquals(expIV.getValue(), actIV.getValue(), 1e-10); assertTrue(expIter.hasNext() == actIter.hasNext()); } assertTrue(expIter.hasNext() == actIter.hasNext()); //3rd pair expIter = new SparseVector(c.length()).getNonZeroIterator(start); actIter = c.getNonZeroIterator(start); assertTrue(expIter.hasNext() == actIter.hasNext()); while(expIter.hasNext()) { IndexValue expIV = expIter.next(); IndexValue actIV = actIter.next(); assertEquals(expIV.getIndex(), actIV.getIndex()); assertEquals(expIV.getValue(), actIV.getValue(), 1e-10); assertTrue(expIter.hasNext() == actIter.hasNext()); } assertTrue(expIter.hasNext() == actIter.hasNext()); } } /** * Test of isSparse method, of class ShiftedVec. */ @Test public void testIsSparse() { System.out.println("isSparse"); assertTrue(new ShiftedVec(a_base, shift_a).isSparse()); assertFalse(new ShiftedVec(a_dense, shift_a).isSparse()); } /** * Test of clone method, of class ShiftedVec. */ @Test public void testClone() { System.out.println("clone"); ShiftedVec a = new ShiftedVec(a_base, shift_a); ShiftedVec a_clone = a.clone(); assertTrue(a.equals(a_dense, 1e-10)); assertTrue(a_clone.equals(a_dense, 1e-10)); a.mutableAdd(rand_x); assertFalse(a.equals(a_dense, 1e-10)); assertTrue(a_clone.equals(a_dense, 1e-10)); } }
14,880
26.00726
84
java
JSAT
JSAT-master/JSAT/test/jsat/linear/SingularValueDecompositionTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.linear; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import jsat.utils.SystemInfo; import java.util.concurrent.ExecutorService; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SingularValueDecompositionTest { /** * 5x5 */ static DenseMatrix A; /** * 5x5 */ static DenseMatrix B; /** * Rank 3 5x5 */ static DenseMatrix D; /** * 5x7 */ static DenseMatrix C; /** * 7 x 5 */ static DenseMatrix E; private static final double delta = 1e-10; static ExecutorService threadpool = Executors.newFixedThreadPool(SystemInfo.LogicalCores+1, new ThreadFactory() { public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } }); public SingularValueDecompositionTest() { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new DenseMatrix(new double[][] { {5, 3, 2, 8, 8}, {1, 8, 3, 6, 8}, {1, 2, 6, 5, 4}, {3, 9, 5, 9, 6}, {8, 3, 4, 3, 1} } ); C = new DenseMatrix(new double[][] { {1, 6, 8, 3, 1, 5, 10}, {5, 5, 3, 7, 2, 10, 0}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 2, 6, 5, 8, 1, 9} } ); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { A = new DenseMatrix(new double[][] { {1, 5, 4, 8, 9}, {1, 5, 7, 3, 7}, {0, 3, 8, 5, 6}, {3, 8, 0, 7, 0}, {1, 9, 2, 9, 6} } ); B = new DenseMatrix(new double[][] { {5, 3, 2, 8, 8}, {1, 8, 3, 6, 8}, {1, 2, 6, 5, 4}, {3, 9, 5, 9, 6}, {8, 3, 4, 3, 1} } ); D = new DenseMatrix(new double[][] { {5, 3, 2, 0, 0}, {1, 8, 3, 0, 0}, {1, 2, 6, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} } ); C = new DenseMatrix(new double[][] { {1, 6, 8, 3, 1, 5, 10}, {5, 5, 3, 7, 2, 10, 0}, {8, 0, 5, 7, 9, 1, 8}, {9, 3, 2, 7, 2, 4, 8}, {1, 2, 6, 5, 8, 1, 9} } ); E = new DenseMatrix(new double[][] { {4, 4, 4, 2, 4}, {1, 5, 2, 3, 0}, {4, 2, 3, 4, 0}, {1, 9, 4, 2, 7}, {5, 7, 4, 3, 5}, {5, 9, 3, 0, 9}, {5, 4, 5, 8, 4} }); } /** * Test of getSingularValues method, of class SingularValueDecomposition. */ @Test public void testGetSingularValues() { System.out.println("getSingularValues"); double[] sValsATrue = new double[] {25.615015549269760, 9.967372402268001 , 4.046901102951370 , 2.356215314072247, 1.262262517005518}; double[] sValsDTrue = new double[] {10.866928472828468, 4.351234464538032, 3.997076957108316, 0, 0}; double[] sValsCTrue = new double[] {29.846912916029009, 11.902860295602228, 9.905493706861000, 6.102122989264148, 1.768896722137177}; double[] sValsA = new SingularValueDecomposition(A).getSingularValues(); double[] sValsD = new SingularValueDecomposition(D).getSingularValues(); double[] sValsC = new SingularValueDecomposition(C).getSingularValues(); for(int i = 0; i < sValsA.length; i++) { assertEquals(sValsATrue[i], sValsA[i], delta); assertEquals(sValsCTrue[i], sValsC[i], delta); assertEquals(sValsDTrue[i], sValsD[i], delta); } } /** * Test of getNorm2 method, of class SingularValueDecomposition. */ @Test public void testGetNorm2() { System.out.println("getNorm2"); double trueNormA = 25.615015549269760; double trueNormC = 29.846912916029009; double trueNormD = 10.866928472828468; assertEquals(trueNormA, new SingularValueDecomposition(A).getNorm2(), delta); assertEquals(trueNormC, new SingularValueDecomposition(C).getNorm2(), delta); assertEquals(trueNormD, new SingularValueDecomposition(D).getNorm2(), delta); } /** * Test of getCondition method, of class SingularValueDecomposition. */ @Test public void testGetCondition() { System.out.println("getCondition"); double trueCondA = 20.292938437272621; double trueCondC = 16.873180068968665; double trueCondD = Double.POSITIVE_INFINITY; assertEquals(trueCondA, new SingularValueDecomposition(A).getCondition(), delta); assertEquals(trueCondC, new SingularValueDecomposition(C).getCondition(), delta); assertEquals(trueCondD, new SingularValueDecomposition(D).getCondition(), delta); } /** * Test of getRank method, of class SingularValueDecomposition. */ @Test public void testGetRank_0args() { System.out.println("getRank"); int rankA = 5; int rankC = 5; int rankD = 3; assertEquals(rankA, new SingularValueDecomposition(A).getRank()); assertEquals(rankC, new SingularValueDecomposition(C).getRank()); assertEquals(rankD, new SingularValueDecomposition(D).getRank()); } /** * Test of getRank method, of class SingularValueDecomposition. */ @Test public void testGetRank_double() { System.out.println("getRank"); double tol = 5.0;//A very large tolerance! int rankA = 2; int rankC = 4; int rankD = 1; assertEquals(rankA, new SingularValueDecomposition(A).getRank(tol)); assertEquals(rankC, new SingularValueDecomposition(C).getRank(tol)); assertEquals(rankD, new SingularValueDecomposition(D).getRank(tol)); } /** * Test of getInverseSingularValues method, of class SingularValueDecomposition. */ @Test public void testGetInverseSingularValues_0args() { System.out.println("getInverseSingularValues"); double[] sValsATrue = new double[] {1.0/25.615015549269760, 1.0/9.967372402268001 , 1.0/4.046901102951370 , 1.0/2.356215314072247, 1.0/1.262262517005518}; double[] sValsDTrue = new double[] {1.0/10.866928472828468, 1.0/4.351234464538032, 1.0/3.997076957108316, 0, 0}; double[] sValsCTrue = new double[] {1.0/29.846912916029009, 1.0/11.902860295602228, 1.0/9.905493706861000, 1.0/6.102122989264148, 1.0/1.768896722137177}; double[] sValsA = new SingularValueDecomposition(A).getInverseSingularValues(); double[] sValsD = new SingularValueDecomposition(D).getInverseSingularValues(); double[] sValsC = new SingularValueDecomposition(C).getInverseSingularValues(); for(int i = 0; i < sValsA.length; i++) { assertEquals(sValsATrue[i], sValsA[i], delta); assertEquals(sValsCTrue[i], sValsC[i], delta); assertEquals(sValsDTrue[i], sValsD[i], delta); } } /** * Test of getInverseSingularValues method, of class SingularValueDecomposition. */ @Test public void testGetInverseSingularValues_double() { System.out.println("getInverseSingularValues"); double tol = 5.0; double[] sValsATrue = new double[] {1.0/25.615015549269760, 1.0/9.967372402268001 , 0 , 0, 0}; double[] sValsDTrue = new double[] {1.0/10.866928472828468, 0, 0, 0, 0}; double[] sValsCTrue = new double[] {1.0/29.846912916029009, 1.0/11.902860295602228, 1.0/9.905493706861000, 1.0/6.102122989264148, 0}; double[] sValsA = new SingularValueDecomposition(A).getInverseSingularValues(tol); double[] sValsD = new SingularValueDecomposition(D).getInverseSingularValues(tol); double[] sValsC = new SingularValueDecomposition(C).getInverseSingularValues(tol); for(int i = 0; i < sValsA.length; i++) { assertEquals(sValsATrue[i], sValsA[i], delta); assertEquals(sValsCTrue[i], sValsC[i], delta); assertEquals(sValsDTrue[i], sValsD[i], delta); } } /** * Test of getPseudoInverse method, of class SingularValueDecomposition. */ @Test public void testGetPseudoInverse() { System.out.println("getPseudoInverse"); Matrix truePInvC = new DenseMatrix(new double[][] { { 0.062400933442643, -0.016718531213984, 0.168007905973973, -0.020034948098766, -0.198766823807711 }, { -0.005194625607728, 0.020172975789774, -0.094455454689009, 0.047276210963183, 0.067661938176502 }, { 0.167355234385855, 0.005639718873814, 0.223102518285777, -0.190852367999693, -0.206282098318648 }, { -0.111390759232766, 0.034725918075815, -0.129066299672170, 0.102432370984900, 0.160549895284892 }, { -0.060231213795913, 0.032065710226917, 0.023059509602175, -0.051296309654649, 0.087923910856982 }, { 0.011210049988905, 0.065859577351507, -0.017972473278131, -0.017808318790801, -0.002532636559622 }, { -0.003172181333343, -0.061497842572707, -0.093209356832114, 0.109623741697116, 0.088614156738433 } }); Matrix truePInvD = new DenseMatrix(new double[][] { { 0.222222222222222, -0.074074074074074, -0.037037037037037, 0, 0}, { -0.015873015873016, 0.148148148148148, -0.068783068783069, 0, 0}, { -0.031746031746032, -0.037037037037037, 0.195767195767196, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0} }); Matrix pInvC = new SingularValueDecomposition(C.clone()).getPseudoInverse(); Matrix pInvD = new SingularValueDecomposition(D.clone()).getPseudoInverse(); assertTrue(truePInvD.equals(pInvD, delta)); assertTrue(truePInvC.equals(pInvC, delta)); } /** * Test of getPseudoDet method, of class SingularValueDecomposition. */ @Test public void testGetPseudoDet_0args() { System.out.println("getPseudoDet"); double pDetA = 3073; double pDetB = 8068; double pDetC = 3.798484118697878e+004; double pDetD = 189; assertEquals(pDetA, new SingularValueDecomposition(A).getPseudoDet(), delta); assertEquals(pDetB, new SingularValueDecomposition(B).getPseudoDet(), delta); assertEquals(pDetC, new SingularValueDecomposition(C).getPseudoDet(), delta); assertEquals(pDetD, new SingularValueDecomposition(D).getPseudoDet(), delta); } /** * Test of solve method, of class SingularValueDecomposition. */ @Test public void testSolve_Vec() { System.out.println("solve"); Vec b = DenseVector.toDenseVec(1.0, 2.0, 3.0, 4.0, 5.0); SingularValueDecomposition instance = null; instance = new SingularValueDecomposition(A.clone()); Vec x = instance.solve(b); assertTrue(A.multiply(x).equals(b, delta)); instance = new SingularValueDecomposition(C.transpose()); try { x = instance.solve(b); fail("Should not have occured"); } catch(ArithmeticException ex) { } } /** * Test of solve method, of class SingularValueDecomposition. */ @Test public void testSolve_Matrix() { System.out.println("solve"); SingularValueDecomposition instance = null; Matrix x; instance = new SingularValueDecomposition(A.clone()); x = instance.solve(B); assertTrue(A.multiply(x).equals(B, delta)); instance = new SingularValueDecomposition(A.clone()); x = instance.solve(C); assertTrue(A.multiply(x).equals(C, delta)); instance = new SingularValueDecomposition(A.clone()); x = instance.solve(D); assertTrue(A.multiply(x).equals(D, delta)); instance = new SingularValueDecomposition(C.clone()); x = instance.solve(E.transpose()); assertTrue(C.multiply(x).equals(E.transpose(), delta)); instance = new SingularValueDecomposition(C.transpose()); x = instance.solve(E); assertTrue(C.transposeMultiply(x).equals(E, instance.getCondition())); } /** * Test of solve method, of class SingularValueDecomposition. */ @Test public void testSolve_Matrix_ExecutorService() { System.out.println("solve"); SingularValueDecomposition instance = null; Matrix x; instance = new SingularValueDecomposition(A.clone()); x = instance.solve(B, threadpool); assertTrue(A.multiply(x).equals(B, delta)); instance = new SingularValueDecomposition(A.clone()); x = instance.solve(C, threadpool); assertTrue(A.multiply(x).equals(C, delta)); instance = new SingularValueDecomposition(A.clone()); x = instance.solve(D, threadpool); assertTrue(A.multiply(x).equals(D, delta)); instance = new SingularValueDecomposition(C.clone()); x = instance.solve(E.transpose(), threadpool); assertTrue(C.multiply(x).equals(E.transpose(), delta)); instance = new SingularValueDecomposition(C.transpose()); x = instance.solve(E, threadpool); assertTrue(C.transposeMultiply(x).equals(E, instance.getCondition())); } }
14,927
33.878505
168
java
JSAT
JSAT-master/JSAT/test/jsat/linear/SparseMatrixTest.java
package jsat.linear; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.utils.FakeExecutor; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SparseMatrixTest { /* * NOTE: True resultes computed with octave and stroed as row, column, value * pairs. These are obtained using the find(X) comand. This also means the * incicies are 1 based, so -1 will be used. */ private Matrix A; private Matrix B; private Matrix C; private Matrix Ct; private static ExecutorService ex; public SparseMatrixTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { A = new SparseMatrix(6, 6, 2); A.set(0, 0, 1.0); A.set(0, 4, 4.0); A.set(1, 3, 3.0); A.set(2, 1, 2.0); A.set(2, 2, -7.0); A.set(3, 1, 1.0); A.set(4, 5, 1.0); A.set(5, 4, 3.0); B = new SparseMatrix(6, 6); B.set(0, 4, 2.0); B.set(1, 0, 3.0); B.set(1, 3, 2.0); B.set(2, 4, 5.0); B.set(2, 5, 1.0); B.set(3, 2, 3.0); B.set(3, 5, 4.0); B.set(4, 0, 2.0); B.set(5, 1, -2.0); B.set(5, 3, 1.0); C = new SparseMatrix(6, 8); Ct = new SparseMatrix(8, 6); C.set(0, 2, 1.0); C.set(0, 7, 1.0); C.set(1, 5, 1.0); C.set(2, 0, 1.0); C.set(2, 7, 1.0); C.set(3, 2, 1.0); C.set(3, 3, 1.0); C.set(3, 4, 1.0); C.set(4, 6, 1.0); C.set(5, 1, 1.0); Ct.set(2, 0, 1.0); Ct.set(7, 0, 1.0); Ct.set(5, 1, 1.0); Ct.set(0, 2, 1.0); Ct.set(7, 2, 1.0); Ct.set(2, 3, 1.0); Ct.set(3, 3, 1.0); Ct.set(4, 3, 1.0); Ct.set(6, 4, 1.0); Ct.set(1, 5, 1.0); } @After public void tearDown() { } /** * Test of mutableAdd method, of class SparseMatrix. */ @Test public void testMutableAdd_double_Matrix() { System.out.println("mutableAdd"); int[] r = new int[] { 1, 2, 5, 3, 4, 6, 3, 4, 2, 6, 1, 3, 6, 3, 4, 5 }; int[] c = new int[] { 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6 }; double[] v = new double[] { 1, 6, 4, 2, 1, -4, -7, 6, 7, 2, 8, 10, 3, 2, 8, 1 }; A.mutableAdd(2.0, B); checkAgainstRCV(A, v, r, c); try { A.mutableAdd(2, C); fail("Matrix dimensions do not agree"); } catch (ArithmeticException ex) { } } /** * Test of mutableAdd method, of class SparseMatrix. */ @Test public void testMutableAdd_3args() { System.out.println("mutableAdd"); int[] r = new int[] { 1, 2, 5, 3, 4, 6, 3, 4, 2, 6, 1, 3, 6, 3, 4, 5 }; int[] c = new int[] { 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6 }; double[] v = new double[] { 1, 6, 4, 2, 1, -4, -7, 6, 7, 2, 8, 10, 3, 2, 8, 1 }; A.mutableAdd(2.0, B, ex); checkAgainstRCV(A, v, r, c); try { A.mutableAdd(2, C, ex); fail("Matrix dimensions do not agree"); } catch (ArithmeticException ex) { } } /** * Test of mutableAdd method, of class SparseMatrix. */ @Test public void testMutableAdd_double() { System.out.println("mutableAdd"); DenseMatrix truth = new DenseMatrix(new double[][] { {2, 2, 2, 2, 4, 2}, {5, 2, 2, 4, 2, 2}, {2, 2, 2, 2, 7, 3}, {2, 2, 5, 2, 2, 6}, {4, 2, 2, 2, 2, 2}, {2, 0, 2, 3, 2, 2}, }); B.mutableAdd(2); assertTrue(B.equals(truth, 1e-20)); assertEquals(B.rows()*B.cols()-1, B.nnz()); } /** * Test of mutableAdd method, of class SparseMatrix. */ @Test public void testMutableAdd_double_ExecutorService() { System.out.println("mutableAdd"); DenseMatrix truth = new DenseMatrix(new double[][] { {2, 2, 2, 2, 4, 2}, {5, 2, 2, 4, 2, 2}, {2, 2, 2, 2, 7, 3}, {2, 2, 5, 2, 2, 6}, {4, 2, 2, 2, 2, 2}, {2, 0, 2, 3, 2, 2}, }); B.mutableAdd(2, ex); assertTrue(B.equals(truth, 1e-20)); assertEquals(B.rows()*B.cols()-1, B.nnz()); } /** * Test of multiply method, of class SparseMatrix. */ @Test public void testMultiply_3args_1() { System.out.println("multiply"); Vec b = new DenseVector(new double[] { 5, 3, 3, 5, 4, 6 }); Vec A2b = new DenseVector(new double[] { 42, 30, -30, 6, 12, 24 }); Vec B2b = new DenseVector(new double[] { 16, 50, 52, 66, 20, -2 }); Vec Ct2b = new DenseVector(new double[] { 6, 12, 20, 10, 10, 6, 8, 16 }); DenseVector c = new DenseVector(6); c.zeroOut(); A.multiply(b, 2, c); assertTrue(c.equals(A2b, 1e-20)); c.zeroOut(); B.multiply(b, 2, c); assertTrue(c.equals(B2b, 1e-20)); try { c.zeroOut(); C.multiply(b, 2, c); fail("Target vector does not agre, should have failed"); } catch(Exception ex) { } try { c.zeroOut(); Ct.multiply(b, 2, c); fail("Target vector does not agre, should have failed"); } catch(Exception ex) { } c = new DenseVector(8); c.zeroOut(); Ct.multiply(b, 2, c); assertTrue(c.equals(Ct2b, 1e-20)); } /** * Test of multiply method, of class SparseMatrix. */ @Test public void testMultiply_Matrix_Matrix() { System.out.println("multiply"); SparseMatrix tmp; int[] rAB = new int[] { 1, 3, 4, 6, 5, 2, 3, 4, 5, 1, 3, 2, 3 }; int[] cAB = new int[] { 1, 1, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, 6 }; double[] vAB = new double[] { 8, 6, 3, 6, -2, 9, 4, 2, 1, 2, -35, 12, -7 }; tmp = new SparseMatrix(6, 6); A.multiply(B, tmp); checkAgainstRCV(tmp, vAB, rAB, cAB); int[] rBA = new int[] { 2, 5, 2, 4, 6, 4, 6, 2, 3, 4, 5, 1, 3 }; int[] cBA = new int[] { 1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6 }; double[] vBA = new double[] { 3, 2, 2, 6, 1, -21, -6, 12, 3, 12, 8, 2, 5 }; tmp = new SparseMatrix(6, 6); B.multiply(A, tmp); checkAgainstRCV(tmp, vBA, rBA, cBA); int[] rAC = new int[] { 3, 5, 1, 2, 2, 2, 3, 4, 1, 6, 1, 3 }; int[] cAC = new int[] { 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8 }; double[] vAC = new double[] { -7, 1, 1, 3, 3, 3, 2, 1, 4, 3, 1, -7 }; tmp = new SparseMatrix(6, 8); A.multiply(C, tmp); checkAgainstRCV(tmp, vAC, rAC, cAC); int[] rCtB = new int[] { 6, 7, 2, 3, 4, 5, 2, 6, 1, 3, 8, 1, 3, 4, 5, 8 }; int[] cCtB = new int[] { 1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6 }; double[] vCtB = new double[] { 3, 2, -2, 3, 3, 3, 1, 2, 5, 2, 7, 1, 4, 4, 4, 1 }; tmp = new SparseMatrix(8, 6); Ct.multiply(B, tmp); checkAgainstRCV(tmp, vCtB, rCtB, cCtB); try { A.multiply(Ct, C); fail("Should have failed, matrix dimensions dont agree"); } catch(ArithmeticException ex) { } } /** * Test of multiply method, of class SparseMatrix. */ @Test public void testMultiply_3args_2() { System.out.println("multiply"); SparseMatrix tmp; int[] rAB = new int[] { 1, 3, 4, 6, 5, 2, 3, 4, 5, 1, 3, 2, 3 }; int[] cAB = new int[] { 1, 1, 1, 1, 2, 3, 4, 4, 4, 5, 5, 6, 6 }; double[] vAB = new double[] { 8, 6, 3, 6, -2, 9, 4, 2, 1, 2, -35, 12, -7 }; tmp = new SparseMatrix(6, 6); A.multiply(B, tmp, ex); checkAgainstRCV(tmp, vAB, rAB, cAB); int[] rBA = new int[] { 2, 5, 2, 4, 6, 4, 6, 2, 3, 4, 5, 1, 3 }; int[] cBA = new int[] { 1, 1, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6 }; double[] vBA = new double[] { 3, 2, 2, 6, 1, -21, -6, 12, 3, 12, 8, 2, 5 }; tmp = new SparseMatrix(6, 6); B.multiply(A, tmp, ex); checkAgainstRCV(tmp, vBA, rBA, cBA); int[] rAC = new int[] { 3, 5, 1, 2, 2, 2, 3, 4, 1, 6, 1, 3 }; int[] cAC = new int[] { 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8 }; double[] vAC = new double[] { -7, 1, 1, 3, 3, 3, 2, 1, 4, 3, 1, -7 }; tmp = new SparseMatrix(6, 8); A.multiply(C, tmp, ex); checkAgainstRCV(tmp, vAC, rAC, cAC); int[] rCtB = new int[] { 6, 7, 2, 3, 4, 5, 2, 6, 1, 3, 8, 1, 3, 4, 5, 8 }; int[] cCtB = new int[] { 1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6 }; double[] vCtB = new double[] { 3, 2, -2, 3, 3, 3, 1, 2, 5, 2, 7, 1, 4, 4, 4, 1 }; tmp = new SparseMatrix(8, 6); Ct.multiply(B, tmp, ex); checkAgainstRCV(tmp, vCtB, rCtB, cCtB); try { A.multiply(Ct, C, ex); fail("Should have failed, matrix dimensions dont agree"); } catch(ArithmeticException ex) { } } @Test public void testMultiplyTranspose() { System.out.println("multiplyTranspose"); int[] rAC = new int[] { 3, 5, 1, 2, 2, 2, 3, 4, 1, 6, 1, 3 }; int[] cAC = new int[] { 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8 }; double[] vAC = new double[] { -7, 1, 1, 3, 3, 3, 2, 1, 4, 3, 1, -7 }; SparseMatrix tmp = new SparseMatrix(6, 8); A.multiplyTranspose(Ct, tmp); checkAgainstRCV(tmp, vAC, rAC, cAC); } @Test public void testMultiplyTranspose_Executor() { System.out.println("multiplyTranspose_Executor"); int[] rAC = new int[] { 3, 5, 1, 2, 2, 2, 3, 4, 1, 6, 1, 3 }; int[] cAC = new int[] { 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 8 }; double[] vAC = new double[] { -7, 1, 1, 3, 3, 3, 2, 1, 4, 3, 1, -7 }; SparseMatrix tmp = new SparseMatrix(6, 8); A.multiplyTranspose(Ct, tmp, new FakeExecutor()); checkAgainstRCV(tmp, vAC, rAC, cAC); } /** * Test of mutableMultiply method, of class SparseMatrix. */ @Test public void testMutableMultiply_double() { System.out.println("mutableMultiply"); int[] r = new int[] { 1, 3, 4, 3, 2, 1, 6, 5 }; int[] c = new int[] { 1, 2, 2, 3, 4, 5, 5, 6 }; double[] v = new double[] { 3, 6, 3, -21, 9, 12, 9, 3 }; A.mutableMultiply(3.0); checkAgainstRCV(A, v, r, c); } /** * Test of mutableMultiply method, of class SparseMatrix. */ @Test public void testMutableMultiply_double_ExecutorService() { System.out.println("mutableMultiply"); int[] r = new int[] { 1, 3, 4, 3, 2, 1, 6, 5 }; int[] c = new int[] { 1, 2, 2, 3, 4, 5, 5, 6 }; double[] v = new double[] { 3, 6, 3, -21, 9, 12, 9, 3 }; A.mutableMultiply(3.0, ex); checkAgainstRCV(A, v, r, c); } /** * Test of mutableTranspose method, of class SparseMatrix. */ @Test public void testMutableTranspose() { System.out.println("mutableTranspose"); int[] r = new int[] { 1, 5, 4, 2, 3, 2, 6, 5 }; int[] c = new int[] { 1, 1, 2, 3, 3, 4, 5, 6 }; double[] v = new double[] { 1, 4, 3, 2, -7, 1, 1, 3 }; A.mutableTranspose(); checkAgainstRCV(A, v, r, c); try { C.mutableTranspose(); fail("C is not square, should have failed"); } catch(Exception ex) { } } /** * Test of transpose method, of class SparseMatrix. */ @Test public void testTranspose() { System.out.println("transpose"); int[] rAt = new int[] { 1, 5, 4, 2, 3, 2, 6, 5 }; int[] cAt = new int[] { 1, 1, 2, 3, 3, 4, 5, 6 }; double[] vAt = new double[] { 1, 4, 3, 2, -7, 1, 1, 3 }; SparseMatrix tmp = new SparseMatrix(6, 6); A.transpose(tmp); checkAgainstRCV(tmp, vAt, rAt, cAt); tmp = new SparseMatrix(Ct.rows(), Ct.cols()); C.transpose(tmp); assertTrue(tmp.equals(Ct)); } /** * Test of transposeMultiply method, of class SparseMatrix. */ @Test public void testTransposeMultiply_Matrix_Matrix() { System.out.println("transposeMultiply"); SparseMatrix tmp; int[] rAtB = new int[] { 4, 6, 5, 2, 4, 5, 1, 2, 3, 5, 2, 3 }; int[] cAtB = new int[] { 1, 1, 2, 3, 4, 4, 5, 5, 5, 5, 6, 6 }; double[] vAtB = new double[] { 9, 2, -6, 3, 6, 3, 2, 10, -35, 8, 6, -7 }; tmp = new SparseMatrix(6, 6); A.transposeMultiply(B, tmp); checkAgainstRCV(tmp, vAtB, rAtB, cAtB); int[] rBtA = new int[] { 5, 3, 5, 6, 5, 6, 1, 4, 2, 4, 5, 1 }; int[] cBtA = new int[] { 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6 }; double[] vBtA = new double[] { 2, 3, 10, 6, -35, -7, 9, 6, -6, 3, 8, 2 }; tmp = new SparseMatrix(6, 6); B.transposeMultiply(A, tmp); checkAgainstRCV(tmp, vBtA, rBtA, cBtA); int[] rAtC = new int[] { 2, 3, 5, 1, 2, 5, 2, 2, 4, 6, 1, 2, 3, 5 }; int[] cAtC = new int[] { 1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 8, 8, 8, 8 }; double[] vAtC = new double[] { 2, -7, 3, 1, 1, 4, 1, 1, 3, 1, 1, 2, -7, 4 }; tmp = new SparseMatrix(6, 8); A.transposeMultiply(C, tmp); checkAgainstRCV(tmp, vAtC, rAtC, cAtC); int[] rCtB = new int[] { 6, 7, 2, 3, 4, 5, 2, 6, 1, 3, 8, 1, 3, 4, 5, 8 }; int[] cCtB = new int[] { 1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6 }; double[] vCtB = new double[] { 3, 2, -2, 3, 3, 3, 1, 2, 5, 2, 7, 1, 4, 4, 4, 1 }; tmp = new SparseMatrix(8, 6); C.transposeMultiply(B, tmp); checkAgainstRCV(tmp, vCtB, rCtB, cCtB); try { A.transposeMultiply(Ct, C); fail("Should have failed, matrix dimensions dont agree"); } catch(ArithmeticException ex) { } } /** * Test of transposeMultiply method, of class SparseMatrix. */ @Test public void testTransposeMultiply_3args_1() { System.out.println("transposeMultiply"); SparseMatrix tmp; int[] rAtB = new int[] { 4, 6, 5, 2, 4, 5, 1, 2, 3, 5, 2, 3 }; int[] cAtB = new int[] { 1, 1, 2, 3, 4, 4, 5, 5, 5, 5, 6, 6 }; double[] vAtB = new double[] { 9, 2, -6, 3, 6, 3, 2, 10, -35, 8, 6, -7 }; tmp = new SparseMatrix(6, 6); A.transposeMultiply(B, tmp, ex); checkAgainstRCV(tmp, vAtB, rAtB, cAtB); int[] rBtA = new int[] { 5, 3, 5, 6, 5, 6, 1, 4, 2, 4, 5, 1 }; int[] cBtA = new int[] { 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 6 }; double[] vBtA = new double[] { 2, 3, 10, 6, -35, -7, 9, 6, -6, 3, 8, 2 }; tmp = new SparseMatrix(6, 6); B.transposeMultiply(A, tmp, ex); checkAgainstRCV(tmp, vBtA, rBtA, cBtA); int[] rAtC = new int[] { 2, 3, 5, 1, 2, 5, 2, 2, 4, 6, 1, 2, 3, 5 }; int[] cAtC = new int[] { 1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 8, 8, 8, 8 }; double[] vAtC = new double[] { 2, -7, 3, 1, 1, 4, 1, 1, 3, 1, 1, 2, -7, 4 }; tmp = new SparseMatrix(6, 8); A.transposeMultiply(C, tmp, ex); checkAgainstRCV(tmp, vAtC, rAtC, cAtC); int[] rCtB = new int[] { 6, 7, 2, 3, 4, 5, 2, 6, 1, 3, 8, 1, 3, 4, 5, 8 }; int[] cCtB = new int[] { 1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 6 }; double[] vCtB = new double[] { 3, 2, -2, 3, 3, 3, 1, 2, 5, 2, 7, 1, 4, 4, 4, 1 }; tmp = new SparseMatrix(8, 6); C.transposeMultiply(B, tmp, ex); checkAgainstRCV(tmp, vCtB, rCtB, cCtB); try { A.transposeMultiply(Ct, C); fail("Should have failed, matrix dimensions dont agree"); } catch(ArithmeticException ex) { } } /** * Test of transposeMultiply method, of class SparseMatrix. */ @Test public void testTransposeMultiply_3args_2() { System.out.println("transposeMultiply"); Vec b = new DenseVector(new double[] { 5, 3, 3, 5, 4, 6 }); Vec A2b = new DenseVector(new double[] { 10, 22, -42, 18, 76, 8 }); Vec B2b = new DenseVector(new double[] { 34, -24, 30, 24, 50, 46 }); Vec Ct2b = new DenseVector(new double[] { 6, 12, 20, 10, 10, 6, 8, 16 }); DenseVector c = new DenseVector(6); c.zeroOut(); A.transposeMultiply(2, b, c); assertTrue(c.equals(A2b, 1e-20)); c.zeroOut(); B.transposeMultiply(2, b, c); assertTrue(c.equals(B2b, 1e-20)); try { c.zeroOut(); Ct.transposeMultiply(2, b, c);//b is wrong size fail("Target vector does not agre, should have failed"); } catch(Exception ex) { } try { c.zeroOut(); C.transposeMultiply(2, b, c);//c is wrong size fail("Target vector does not agre, should have failed"); } catch(Exception ex) { } c = new DenseVector(8); c.zeroOut(); C.transposeMultiply(2, b, c); assertTrue(c.equals(Ct2b, 1e-20)); } /** * Test of getRowView method, of class SparseMatrix. */ @Test public void testGetRowView() { System.out.println("getRowView"); Vec row = A.getRowView(0); row.set(0, 0.0); row.set(4, -1.0); assertEquals(7, A.nnz()); assertEquals(0.0, A.get(0, 0), 1e-20); assertEquals(-1.0, A.get(0, 4), 1e-20); } /** * Test of get method, of class SparseMatrix. */ @Test public void testGet() { System.out.println("get"); assertEquals(1.0, A.get(0, 0), 1e-20); assertEquals(4.0, A.get(0, 4), 1e-20); assertEquals(0.0, A.get(3, 0), 1e-20); assertEquals(1.0, A.get(3, 1), 1e-20); } /** * Test of set method, of class SparseMatrix. */ @Test public void testSet() { System.out.println("set"); A.set(0, 0, 0.0); A.set(0, 4, -1.0); A.set(3, 0, -2.0); assertEquals(8, A.nnz()); assertEquals(0.0, A.get(0, 0), 1e-20); assertEquals(-1.0, A.get(0, 4), 1e-20); assertEquals(-2.0, A.get(3, 0), 1e-20); assertEquals(1.0, A.get(3, 1), 1e-20); } /** * Test of increment method, of class SparseMatrix. */ @Test public void testIncrement() { System.out.println("increment"); A.increment(0, 4, -1.0); A.increment(3, 0, -2.0); assertEquals(9, A.nnz()); assertEquals(1.0, A.get(0, 0), 1e-20); assertEquals(3.0, A.get(0, 4), 1e-20); assertEquals(-2.0, A.get(3, 0), 1e-20); assertEquals(1.0, A.get(3, 1), 1e-20); } /** * Test of rows method, of class SparseMatrix. */ @Test public void testRows() { System.out.println("rows"); assertEquals(6, A.rows()); assertEquals(6, B.rows()); assertEquals(6, C.rows()); assertEquals(8, Ct.rows()); } /** * Test of cols method, of class SparseMatrix. */ @Test public void testCols() { System.out.println("cols"); assertEquals(6, A.cols()); assertEquals(6, B.cols()); assertEquals(8, C.cols()); assertEquals(6, Ct.cols()); } /** * Test of isSparce method, of class SparseMatrix. */ @Test public void testIsSparce() { System.out.println("isSparce"); assertTrue(A.isSparce()); assertTrue(B.isSparce()); assertTrue(C.isSparce()); assertTrue(Ct.isSparce()); } /** * Test of swapRows method, of class SparseMatrix. */ @Test public void testSwapRows() { System.out.println("swapRows"); int[] r = new int[] { 6, 3, 4, 3, 2, 1, 6, 5 }; int[] c = new int[] { 1, 2, 2, 3, 4, 5, 5, 6 }; double[] v = new double[] { 1, 2, 1, -7, 3, 3, 4, 1 }; A.swapRows(0, 5); checkAgainstRCV(A, v, r, c); } /** * Test of zeroOut method, of class SparseMatrix. */ @Test public void testZeroOut() { System.out.println("zeroOut"); A.zeroOut(); assertEquals(0, A.nnz()); for(int i = 0; i < A.rows(); i++) for(int j = 0; j < A.cols(); j++) assertEquals(0.0, A.get(i, j), 1e-20); } /** * Test of clone method, of class SparseMatrix. */ @Test public void testClone() { System.out.println("clone"); Matrix AClone = A.clone(); assertTrue(AClone.equals(A)); assertFalse(AClone == A); A.zeroOut(); assertFalse(AClone.equals(A)); assertEquals(8, AClone.nnz()); assertEquals(0, A.nnz()); } @Test public void testNnz() { System.out.println("mutableAdd"); assertEquals(8, A.nnz()); assertEquals(10, B.nnz()); assertEquals(10, C.nnz()); assertEquals(10, Ct.nnz()); } @Test public void testChangeSize() { System.out.println("changeSize"); Matrix Acpy = A.clone(); Acpy.changeSize(Acpy.rows()-1, Acpy.cols()-1); assertEquals(Acpy.rows(), A.rows()-1); assertEquals(Acpy.cols(), A.cols()-1); for(int i = 0; i < Acpy.rows(); i++) for(int j = 0; j < Acpy.cols(); j++) assertEquals(Acpy.get(i, j), A.get(i, j), 0.0); //Expand back out and make sure the values are zero on the sides Acpy.changeSize(Acpy.rows()+2, Acpy.cols()+2); assertEquals(Acpy.rows(), A.rows()+1); assertEquals(Acpy.cols(), A.cols()+1); for(int i = 0; i < Acpy.rows(); i++) for(int j = 0; j < Acpy.cols(); j++) if(i < A.rows()-1 && j < A.cols()-1) assertEquals(A.get(i, j), Acpy.get(i, j), 0.0); else assertEquals(0.0, Acpy.get(i, j), 0.0); } /** * * @param tmp the matrix to check * @param v the value stored for each non zero index * @param r the row for each non zero index, 1 based * @param c the column for each non zero index, 1 based */ private void checkAgainstRCV(Matrix tmp, double[] v, int[] r, int[] c) { assertEquals(v.length, tmp.nnz()); for(int i = 0; i < v.length; i++) assertEquals(v[i], tmp.get(r[i]-1, c[i]-1), 1e-20); } }
26,106
22.083112
81
java
JSAT
JSAT-master/JSAT/test/jsat/linear/SparseVectorTest.java
package jsat.linear; import jsat.math.Function; import jsat.math.IndexFunction; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SparseVectorTest { private SparseVector x; private SparseVector y; public SparseVectorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { x = new SparseVector(20); x.set(0, 2.0); x.set(3, 4.0); x.set(7, 1.0); x.set(10, 2.0); x.set(15, 3.0); x.set(18, 2.0); x.set(19, 5.0); y = new SparseVector(20); y.set(1, 2.0); y.set(3, 4.0); y.set(8, 1.0); y.set(9, 1.0); y.set(10, 2.0); y.set(15, 3.0); y.set(17, 2.0); y.set(18, 5.0); } @After public void tearDown() { } /** * Test of length method, of class SparseVector. */ @Test public void testLength() { System.out.println("length"); assertEquals(20, x.length()); assertEquals(20, y.length()); } /** * Test of setLength method, of class SparseVector. */ @Test public void testSetLength() { System.out.println("setLength"); assertEquals(20, x.length()); assertEquals(20, y.length()); y.setLength(25); assertEquals(20, x.length()); assertEquals(25, y.length()); try { y.setLength(5); fail("Set length should have been too small"); } catch(Exception ex) { } } /** * Test of nnz method, of class SparseVector. */ @Test public void testNnz() { System.out.println("nnz"); assertEquals(7, x.nnz()); assertEquals(8, y.nnz()); } /** * Test of increment method, of class SparseVector. */ @Test public void testIncrement() { System.out.println("increment"); x.increment(0, 2.0); x.increment(19, -2.0); assertEquals(4.0, x.get(0), 1e-15); assertEquals(3.0, x.get(19), 1e-15); y.increment(0, 2.0); y.increment(19, -2.0); assertEquals(2.0, y.get(0), 1e-15); assertEquals(-2.0, y.get(19), 1e-15); } /** * Test of get method, of class SparseVector. */ @Test public void testGet() { System.out.println("get"); assertEquals(2.0, x.get(0), 1e-15); assertEquals(4.0, x.get(3), 1e-15); assertEquals(1.0, x.get(7), 1e-15); assertEquals(2.0, x.get(10), 1e-15); assertEquals(3.0, x.get(15), 1e-15); assertEquals(2.0, x.get(18), 1e-15); assertEquals(5.0, x.get(19), 1e-15); assertEquals(0.0, x.get(1), 1e-15); assertEquals(0.0, x.get(2), 1e-15); assertEquals(0.0, x.get(16), 1e-15); assertEquals(2.0, y.get(1), 1e-15); assertEquals(4.0, y.get(3), 1e-15); assertEquals(1.0, y.get(8), 1e-15); assertEquals(1.0, y.get(9), 1e-15); assertEquals(2.0, y.get(10), 1e-15); assertEquals(3.0, y.get(15), 1e-15); assertEquals(2.0, y.get(17), 1e-15); assertEquals(5.0, y.get(18), 1e-15); assertEquals(0.0, y.get(0), 1e-15); assertEquals(0.0, y.get(2), 1e-15); assertEquals(0.0, y.get(16), 1e-15); } /** * Test of set method, of class SparseVector. */ @Test public void testSet() { System.out.println("set"); x.set(0, 9.0); x.set(3, 9.0); x.set(7, 9.0); x.set(10, 9.0); x.set(1, 9.0); x.set(16, 9.0); assertEquals(9.0, x.get(0), 1e-15); assertEquals(9.0, x.get(3), 1e-15); assertEquals(9.0, x.get(7), 1e-15); assertEquals(9.0, x.get(10), 1e-15); assertEquals(3.0, x.get(15), 1e-15); assertEquals(2.0, x.get(18), 1e-15); assertEquals(5.0, x.get(19), 1e-15); assertEquals(9.0, x.get(1), 1e-15); assertEquals(0.0, x.get(2), 1e-15); assertEquals(9.0, x.get(16), 1e-15); //now the y values y.set(10, 9.0); y.set(15, 9.0); y.set(17, 9.0); y.set(18, 9.0); y.set(0, 9.0); y.set(16, 9.0); assertEquals(2.0, y.get(1), 1e-15); assertEquals(4.0, y.get(3), 1e-15); assertEquals(1.0, y.get(8), 1e-15); assertEquals(1.0, y.get(9), 1e-15); assertEquals(9.0, y.get(10), 1e-15); assertEquals(9.0, y.get(15), 1e-15); assertEquals(9.0, y.get(17), 1e-15); assertEquals(9.0, y.get(18), 1e-15); assertEquals(9.0, y.get(0), 1e-15); assertEquals(0.0, y.get(2), 1e-15); assertEquals(9.0, y.get(16), 1e-15); } /** * Test of sortedCopy method, of class SparseVector. */ @Test public void testSortedCopy() { System.out.println("sortedCopy"); Vec sorted = x.sortedCopy(); double lastVal = Double.NEGATIVE_INFINITY; for(int i = 0; i < sorted.length(); i++) { assertTrue(lastVal <= sorted.get(i)); lastVal = sorted.get(i); } } /** * Test of min method, of class SparseVector. */ @Test public void testMin() { System.out.println("min"); assertEquals(0.0, x.min(), 1e-15); y.set(15, -5.0); assertEquals(-5.0, y.min(), 1e-15); } /** * Test of max method, of class SparseVector. */ @Test public void testMax() { System.out.println("max"); assertEquals(5.0, x.max(), 1e-15); y.set(15, -5.0); assertEquals(5.0, y.max(), 1e-15); } /** * Test of sum method, of class SparseVector. */ @Test public void testSum() { System.out.println("sum"); assertEquals(19.0, x.sum(), 1e-15); assertEquals(20.0, y.sum(), 1e-15); } /** * Test of variance method, of class SparseVector. */ @Test public void testVariance() { System.out.println("variance"); assertEquals(2.2475, x.variance(), 1e-14); assertEquals(2.2, y.variance(), 1e-14); } /** * Test of median method, of class SparseVector. */ @Test public void testMedian() { System.out.println("median"); assertEquals(0.0, x.median(), 1e-15); assertEquals(0.0, y.median(), 1e-15); x.mutableAdd(y); assertEquals(1.0, x.median(), 1e-15); } /** * Test of skewness method, of class SparseVector. */ @Test public void testSkewness() { System.out.println("skewness"); assertEquals(1.53870671976305, x.skewness(), 1e-14); assertEquals(1.49347441061993, y.skewness(), 1e-14); } /** * Test of kurtosis method, of class SparseVector. */ @Test public void testKurtosis() { System.out.println("kurtosis"); assertEquals(0.83542831548092615574590, x.kurtosis(), 1e-14); assertEquals(0.80165289256198347107438, y.kurtosis(), 1e-14); } /** * Test of dot method, of class SparseVector. */ @Test public void testDot() { System.out.println("dot"); assertEquals(6.30000000000000e+01, x.dot(x), 1e-14); assertEquals(6.40000000000000e+01, y.dot(y), 1e-14); assertEquals(3.90000000000000e+01, y.dot(x), 1e-14); assertEquals(3.90000000000000e+01, x.dot(y), 1e-14); } /** * Test of multiply method, of class SparseVector. */ @Test public void testMultiply() { System.out.println("multiply"); double c = 0.5; Matrix A = Matrix.pascal(20); Vec b = new DenseVector(20); x.multiply(c, A, b); DenseVector truth = new DenseVector(new double[] { 9.50000000000000e+00, 1.17000000000000e+02, 1.02400000000000e+03, 6.79100000000000e+03, 3.65035000000000e+04, 1.66677000000000e+05, 6.67777000000000e+05, 2.40242100000000e+06, 7.89524000000000e+06, 2.40138700000000e+07, 6.82963280000000e+07, 1.83124137000000e+08, 4.66043078500000e+08, 1.13203426200000e+09, 2.63681749700000e+09, 5.91310906500000e+09, 1.28100303500000e+10, 2.68885048480000e+10, 5.48258186510000e+10, 1.08840104671000e+11, }); assertTrue(b.equals(truth, 1e-13)); } /** * Test of mutableAdd method, of class SparseVector. */ @Test public void testMutableAdd_double() { System.out.println("mutableAdd"); x.mutableAdd(1.0); DenseVector truth = new DenseVector(new double[]{ 3.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 5.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 2.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 3.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 4.00000000000000e+00, 1.00000000000000e+00, 1.00000000000000e+00, 3.00000000000000e+00, 6.00000000000000e+00, }); assertTrue(x.equals(truth, 1e-15)); } /** * Test of mutableAdd method, of class SparseVector. */ @Test public void testMutableAdd_double_Vec() { System.out.println("mutableAdd"); double c = 0.5; x.mutableAdd(c, y); DenseVector truth = new DenseVector(new double[]{ 2.00000000000000e+00, 1.00000000000000e+00, 0.00000000000000e+00, 6.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.00000000000000e+00, 5.00000000000000e-01, 5.00000000000000e-01, 3.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 4.50000000000000e+00, 0.00000000000000e+00, 1.00000000000000e+00, 4.50000000000000e+00, 5.00000000000000e+00, }); assertTrue(x.equals(truth, 1e-15)); } /** * Test of mutableMultiply method, of class SparseVector. */ @Test public void testMutableMultiply() { System.out.println("mutableMultiply"); x.mutableMultiply(2); DenseVector truth = new DenseVector(new double[]{ 4.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 8.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 2.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 4.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 6.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 4.00000000000000e+00, 1.00000000000000e+01, }); assertTrue(x.equals(truth, 1e-15)); } /** * Test of mutableDivide method, of class SparseVector. */ @Test public void testMutableDivide() { System.out.println("mutableDivide"); x.mutableDivide(2); DenseVector truth = new DenseVector(new double[]{ 1.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 2.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 5.00000000000000e-01, 0.00000000000000e+00, 0.00000000000000e+00, 1.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.50000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.00000000000000e+00, 2.50000000000000e+00, }); assertTrue(x.equals(truth, 1e-15)); } /** * Test of pNormDist method, of class SparseVector. */ @Test public void testPNormDist() { System.out.println("pNormDist"); assertEquals(1.70000000000000e+01, x.pNormDist(1, y), 1e-14); assertEquals(7.00000000000000e+00, x.pNormDist(2, y), 1e-14); assertEquals(5.24534393385174e+00, x.pNormDist(4, y), 1e-14); assertEquals(1.70000000000000e+01, y.pNormDist(1, x), 1e-14); assertEquals(7.00000000000000e+00, y.pNormDist(2, x), 1e-14); assertEquals(5.24534393385174e+00, y.pNormDist(4, x), 1e-14); assertEquals(0, x.pNormDist(4, x), 1e-14); assertEquals(0, y.pNormDist(1, y), 1e-14); } /** * Test of pNorm method, of class SparseVector. */ @Test public void testPNorm() { System.out.println("pNorm"); assertEquals(1.90000000000000e+01, x.pNorm(1), 1e-14); assertEquals(7.93725393319377e+00, x.pNorm(2), 1e-14); assertEquals(5.63881425400494e+00, x.pNorm(4), 1e-14); assertEquals(2.00000000000000e+01, y.pNorm(1), 1e-14); assertEquals(8.00000000000000e+00, y.pNorm(2), 1e-14); assertEquals(5.64020810264779e+00, y.pNorm(4), 1e-14); } /** * Test of clone method, of class SparseVector. */ @Test public void testClone() { System.out.println("clone"); SparseVector yClone = y.clone(); yClone.mutableSubtract(y); yClone.mutableAdd(x); assertEquals(3.90000000000000e+01, y.dot(yClone), 1e-14); } /** * Test of normalize method, of class SparseVector. */ @Test public void testNormalize() { System.out.println("normalize"); x.normalize(); DenseVector truth = new DenseVector(new double[]{ 2.51976315339485e-01, 0.00000000000000e+00, 0.00000000000000e+00, 5.03952630678970e-01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.25988157669742e-01, 0.00000000000000e+00, 0.00000000000000e+00, 2.51976315339485e-01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 3.77964473009227e-01, 0.00000000000000e+00, 0.00000000000000e+00, 2.51976315339485e-01, 6.29940788348712e-01, }); assertTrue(x.equals(truth, 1e-14)); } /** * Test of mutablePairwiseMultiply method, of class SparseVector. */ @Test public void testMutablePairwiseMultiply() { System.out.println("mutablePairwiseMultiply"); DenseVector truth = new DenseVector(new double[]{ 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.60000000000000e+01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 4.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 9.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.00000000000000e+01, 0.00000000000000e+00, }); Vec result = x.pairwiseMultiply(y); assertTrue(truth.equals(result, 1e-14)); } /** * Test of mutablePairwiseDivide method, of class SparseVector. */ @Test public void testMutablePairwiseDivide() { System.out.println("mutablePairwiseDivide"); DenseVector truth = new DenseVector(new double[]{ 2.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 8.00000000000000e-01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 6.66666666666667e-01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 7.50000000000000e-01, 0.00000000000000e+00, 0.00000000000000e+00, 3.33333333333333e-01, 5.00000000000000e+00, }); y.mutableAdd(1);//avoid dividion by zero x.mutablePairwiseDivide(y); assertTrue(truth.equals(x, 1e-14)); } /** * Test of equals method, of class SparseVector. */ @Test public void testEquals_Object() { System.out.println("equals"); assertTrue(y.equals(y)); assertTrue(x.equals(x)); assertTrue(x.equals(new DenseVector(x))); assertFalse(y.equals(x)); assertFalse(x.equals(y)); } /** * Test of equals method, of class SparseVector. */ @Test public void testEquals_Object_double() { System.out.println("equals"); assertFalse(x.equals(y, 1e-15)); assertFalse(x.equals(y, 4.5)); assertTrue(x.equals(y, 5.5)); assertTrue(x.equals(y, 10)); } /** * Test of arrayCopy method, of class SparseVector. */ @Test public void testArrayCopy() { System.out.println("arrayCopy"); double[] xArray = x.arrayCopy(); for(int i = 0; i < x.length(); i++) assertEquals(x.get(i), xArray[i], 0.0); } /** * Test of applyFunction method, of class SparseVector. */ @Test public void testApplyFunction() { System.out.println("applyFunction"); x.applyFunction((x) -> -x); DenseVector truth = new DenseVector(new double[]{ -2.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -4.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -1.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -2.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -3.00000000000000e+00, -0.00000000000000e+00, -0.00000000000000e+00, -2.00000000000000e+00, -5.00000000000000e+00, }); assertTrue(x.equals(truth, 1e-20)); } /** * Test of applyIndexFunction method, of class SparseVector. */ @Test public void testApplyIndexFunction() { System.out.println("applyIndexFunction"); IndexFunction f = new IndexFunction() { /** * */ private static final long serialVersionUID = 2804170945957432993L; @Override public double indexFunc(double value, int index) { if(index < 0) return 0; return value*index; } }; x.applyIndexFunction(f); DenseVector truth = new DenseVector(new double[]{ 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 1.20000000000000e+01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 7.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 2.00000000000000e+01, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 0.00000000000000e+00, 4.50000000000000e+01, 0.00000000000000e+00, 0.00000000000000e+00, 3.60000000000000e+01, 9.50000000000000e+01, }); assertEquals(6, x.nnz()); } /** * Test of zeroOut method, of class SparseVector. */ @Test public void testZeroOut() { System.out.println("zeroOut"); x.zeroOut(); for(int i = 0; i < x.length(); i++) assertEquals(0.0, x.get(i), 0.0); } /** * Test of getNonZeroIterator method, of class SparseVector. */ @Test public void testGetNonZeroIterator() { System.out.println("getNonZeroIterator"); assertEquals(0, x.getNonZeroIterator(0).next().getIndex()); assertEquals(1, y.getNonZeroIterator(0).next().getIndex()); assertEquals(18, x.getNonZeroIterator(16).next().getIndex()); assertEquals(17, y.getNonZeroIterator(16).next().getIndex()); assertEquals(19, x.getNonZeroIterator(19).next().getIndex()); assertFalse(y.getNonZeroIterator(19).hasNext()); } /** * Test of hashCode method, of class SparseVector. */ @Test public void testHashCode() { System.out.println("hashCode"); assertEquals(new DenseVector(y).hashCode(), y.hashCode()); assertEquals(new DenseVector(x).hashCode(), x.hashCode()); } /** * Test of isSparse method, of class SparseVector. */ @Test public void testIsSparse() { System.out.println("isSparse"); assertTrue(x.isSparse()); assertTrue(y.isSparse()); } }
23,066
25.302166
69
java
JSAT
JSAT-master/JSAT/test/jsat/linear/SubVectorTest.java
package jsat.linear; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SubVectorTest { private Vec x; private Vec y; public SubVectorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { x = new SparseVector(20); x.set(3, 1.0); x.set(6, 1.0); x.set(7, 1.0); x.set(12, 1.0); x.set(15, 1.0); x.set(19, 1.0); y = new DenseVector(x); } @After public void tearDown() { } /** * Test of length method, of class SubVector. */ @Test public void testLength() { System.out.println("length"); SubVector subX = new SubVector(2, 7, x); assertEquals(7, subX.length()); SubVector subY = new SubVector(2, 7, y); assertEquals(7, subY.length()); } /** * Test of get method, of class SubVector. */ @Test public void testGet() { System.out.println("get"); SubVector subX = new SubVector(2, 7, x); assertEquals(0.0, subX.get(2 - 2), 1e-20); assertEquals(1.0, subX.get(3 - 2), 1e-20); assertEquals(0.0, subX.get(4 - 2), 1e-20); assertEquals(0.0, subX.get(5 - 2), 1e-20); assertEquals(1.0, subX.get(6 - 2), 1e-20); assertEquals(1.0, subX.get(7 - 2), 1e-20); assertEquals(0.0, subX.get(8 - 2), 1e-20); try { assertEquals(0.0, subX.get(9 - 2), 1e-20); fail("Should not have been able to access value"); } catch (Exception ex) { } SubVector subY = new SubVector(2, 7, y); assertEquals(0.0, subY.get(2 - 2), 1e-20); assertEquals(1.0, subY.get(3 - 2), 1e-20); assertEquals(0.0, subY.get(4 - 2), 1e-20); assertEquals(0.0, subY.get(5 - 2), 1e-20); assertEquals(1.0, subY.get(6 - 2), 1e-20); assertEquals(1.0, subY.get(7 - 2), 1e-20); assertEquals(0.0, subY.get(8 - 2), 1e-20); try { assertEquals(0.0, subY.get(9 - 2), 1e-20); fail("Should not have been able to access value"); } catch (Exception ex) { } } /** * Test of set method, of class SubVector. */ @Test public void testSet() { System.out.println("set"); SubVector subX = new SubVector(2, 7, x); subX.set(2 - 2, -1.0); subX.set(3 - 2, -1.0); subX.set(4 - 2, -1.0); assertEquals(-1.0, subX.get(2 - 2), 1e-20); assertEquals(-1.0, subX.get(3 - 2), 1e-20); assertEquals(-1.0, subX.get(4 - 2), 1e-20); assertEquals(-1.0, x.get(2), 1e-20); assertEquals(-1.0, x.get(3), 1e-20); assertEquals(-1.0, x.get(4), 1e-20); try { subX.set(9-2, -1.0); fail("Should not have been able to access value"); } catch (Exception ex) { } SubVector subY = new SubVector(2, 7, y); subY.set(2 - 2, -1.0); subY.set(3 - 2, -1.0); subY.set(4 - 2, -1.0); assertEquals(-1.0, subY.get(2 - 2), 1e-20); assertEquals(-1.0, subY.get(3 - 2), 1e-20); assertEquals(-1.0, subY.get(4 - 2), 1e-20); assertEquals(-1.0, y.get(2), 1e-20); assertEquals(-1.0, y.get(3), 1e-20); assertEquals(-1.0, y.get(4), 1e-20); try { subY.set(9-2, -1.0); fail("Should not have been able to access value"); } catch (Exception ex) { } } /** * Test of isSparse method, of class SubVector. */ @Test public void testIsSparse() { System.out.println("isSparse"); SubVector subX = new SubVector(2, 7, x); assertTrue(subX.isSparse()); SubVector subY = new SubVector(2, 7, y); assertFalse(subY.isSparse()); } /** * Test of getNonZeroIterator method, of class SubVector. */ @Test public void testGetNonZeroIterator() { System.out.println("getNonZeroIterator"); int firstSeen = -1; int lastSeen = -1; SubVector subX = new SubVector(2, 13, x); firstSeen = subX.getNonZeroIterator(2).next().getIndex(); for(IndexValue iv : subX) lastSeen = iv.getIndex(); assertEquals(6-2, firstSeen); assertEquals(12-2, lastSeen); firstSeen = -1; lastSeen = -1; SubVector subY = new SubVector(2, 13, y); firstSeen = subY.getNonZeroIterator(2).next().getIndex(); for(IndexValue iv : subY) lastSeen = iv.getIndex(); assertEquals(6-2, firstSeen); assertEquals(12-2, lastSeen); } /** * Test of clone method, of class SubVector. */ @Test public void testClone() { System.out.println("clone"); SubVector subX = new SubVector(2, 7, x); Vec subXClone = subX.clone(); assertTrue(subXClone.equals(subX)); assertFalse(subX == subXClone); SubVector subY = new SubVector(2, 7, y); Vec subYClone = subY.clone(); assertTrue(subYClone.equals(subY)); assertFalse(subY == subYClone); } }
5,677
23.903509
65
java
JSAT
JSAT-master/JSAT/test/jsat/linear/TruncatedSVDTest.java
/* * This implementation contributed under the Public Domain. */ package jsat.linear; import java.util.Arrays; import java.util.Random; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author edwardraff */ public class TruncatedSVDTest { public TruncatedSVDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSomeMethod() { Random rand = RandomUtil.getRandom(123); Matrix X_tall = DenseMatrix.random(100, 40, rand); Matrix X_wide = DenseMatrix.random(40, 100, rand); for(Matrix X : Arrays.asList(X_tall, X_wide)) { double origNorm = X.frobenius(); double prevNorm = X.frobenius(); for(int k = 1; k < 40; k+= 4) { TruncatedSVD svd = new TruncatedSVD(X, k); Matrix U = svd.getU(); Matrix V = svd.getV(); Matrix R = U.clone(); Matrix.diagMult(R, DenseVector.toDenseVec(svd.getSingularValues())); R = R.multiply(V); double cur_rec_cost = R.subtract(X).frobenius(); assertTrue(cur_rec_cost < prevNorm); assertTrue(cur_rec_cost < origNorm); prevNorm = cur_rec_cost; } } } }
1,670
21.581081
84
java
JSAT
JSAT-master/JSAT/test/jsat/linear/VecWithNormTest.java
package jsat.linear; import java.util.Random; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class VecWithNormTest { Vec x, xNrmd; Vec a, b, c; public VecWithNormTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { Random rand = new Random(546); x = DenseVector.random(20, rand); xNrmd = new VecWithNorm(x.clone()); a = new SparseVector(x.length()); b = new SparseVector(x.length()); c = new SparseVector(x.length()); for(int i = 0; i < 5; i++) { a.set(rand.nextInt(a.length()), rand.nextGaussian()); b.set(rand.nextInt(b.length()), rand.nextGaussian()); c.set(rand.nextInt(c.length()), rand.nextGaussian()); } } @After public void tearDown() { } /** * Test of length method, of class VecWithNorm. */ @Test public void testLength() { System.out.println("length"); assertEquals(x.length(), xNrmd.length()); } /** * Test of get method, of class VecWithNorm. */ @Test public void testGet() { System.out.println("get"); for(int i = 0; i < x.length(); i++) assertEquals(x.get(i), xNrmd.get(i), 0.0); } /** * Test of set method, of class VecWithNorm. */ @Test public void testSet() { System.out.println("set"); int index = 16; double val = Math.PI; x.set(index, val); xNrmd.set(index, val); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of clone method, of class VecWithNorm. */ @Test public void testClone() { System.out.println("clone"); Vec xN = x.clone(); Vec xNN = xNrmd.clone(); assertEquals(xN, x); assertEquals(xNN, xNrmd); assertNotSame(xNN, xNrmd); } /** * Test of mutableAdd method, of class VecWithNorm. */ @Test public void testMutableAdd_double() { System.out.println("mutableAdd"); double val = 3.9; x.mutableAdd(val); xNrmd.mutableAdd(val); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of mutableAdd method, of class VecWithNorm. */ @Test public void testMutableAdd_double_Vec() { System.out.println("mutableAdd"); double val = 2.555; x.mutableAdd(val, a); xNrmd.mutableAdd(val, a); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); x.mutableAdd(val, b); xNrmd.mutableAdd(val, b); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); x.mutableAdd(val, c); xNrmd.mutableAdd(val, c); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of mutablePairwiseMultiply method, of class VecWithNorm. */ @Test public void testMutablePairwiseMultiply() { System.out.println("mutablePairwiseMultiply"); x.mutablePairwiseMultiply(a); xNrmd.mutablePairwiseMultiply(a); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); x.mutablePairwiseMultiply(b); xNrmd.mutablePairwiseMultiply(b); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); x.mutablePairwiseMultiply(c); xNrmd.mutablePairwiseMultiply(c); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of mutableMultiply method, of class VecWithNorm. */ @Test public void testMutableMultiply() { System.out.println("mutableMultiply"); double c = 1.6; x.mutableMultiply(c); xNrmd.mutableMultiply(c); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of mutableDivide method, of class VecWithNorm. */ @Test public void testMutableDivide() { System.out.println("mutableDivide"); double c = 2.54; x.mutableDivide(c); xNrmd.mutableDivide(c); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of zeroOut method, of class VecWithNorm. */ @Test public void testZeroOut() { System.out.println("zeroOut"); x.zeroOut(); xNrmd.zeroOut(); assertEquals(x.pNorm(2), xNrmd.pNorm(2), 1e-6); } /** * Test of nnz method, of class VecWithNorm. */ @Test public void testNnz() { System.out.println("nnz"); assertEquals(x.nnz(), xNrmd.nnz()); x.set(5, 0.0); xNrmd.set(5, 0.0); assertEquals(x.nnz(), xNrmd.nnz()); } }
5,135
21.042918
68
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/ChebyshevDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ChebyshevDistanceTest { static private ExecutorService ex; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public ChebyshevDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); expected = new double[][] { { 0 , 1 , 0.5 , 4 , }, { 1 , 0 , 0.5 , 3 , }, { 0.5 , 0.5 , 0.0 , 3.5 , }, { 4 , 3 , 3.5 , 0 , } }; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); ChebyshevDistance dist = new ChebyshevDistance(); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { ChebyshevDistance d = dist.clone(); assertEquals(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-12); assertEquals(expected[i][j], d.dist(i, j, vecs, cache), 1e-12); assertEquals(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-12); assertEquals(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-12); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); ChebyshevDistance instance = new ChebyshevDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); ChebyshevDistance instance = new ChebyshevDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
4,444
26.955975
121
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/CosineDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class CosineDistanceTest { static private ExecutorService ex; static private Vec negOnes; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public CosineDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { negOnes = new DenseVector(5); negOnes.mutableAdd(-1.0); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(negOnes, ones, half, inc); //was computed as 1-x'y/(||x|| ||y||) expected = new double[][] { { 2.22044604925e-16 , 2.0 , 2.0 , 1.81649658093 , }, { 2.0 , 2.22044604925e-16 , 2.22044604925e-16 , 0.183503419072 , }, { 2.0 , 2.22044604925e-16 , 2.22044604925e-16 , 0.183503419072 , }, { 1.81649658093 , 0.183503419072 , 0.183503419072 , 0.0 , }, }; //so lets get it to just x'y/(||x|| ||y||) for(int i = 0; i < expected.length; i++) for(int j = 0; j < expected[i].length; j++) expected[i][j] = (expected[i][j]*-1)+1; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); CosineDistance dist = new CosineDistance(); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { CosineDistance d = dist.clone(); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(vecs.get(i), vecs.get(j))), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, j, vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache)), 1e-8); } cache = null; for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { CosineDistance d = dist.clone(); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(vecs.get(i), vecs.get(j))), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, j, vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache)), 1e-8); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); CosineDistance instance = new CosineDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); CosineDistance instance = new CosineDistance(); assertTrue(instance.metricBound() > 0); assertEquals(1.0, instance.metricBound(), 0.0); } }
5,730
31.01676
153
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/CosineDistanceTestNormalized.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class CosineDistanceTestNormalized { static private ExecutorService ex; static private Vec negOnes; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public CosineDistanceTestNormalized() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { negOnes = new DenseVector(5); negOnes.mutableAdd(-1.0); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(negOnes, ones, half, inc); for(Vec v : vecs) v.normalize(); //was computed as 1-x'y/(||x|| ||y||) expected = new double[][] { { 2.22044604925e-16 , 2.0 , 2.0 , 1.81649658093 , }, { 2.0 , 2.22044604925e-16 , 2.22044604925e-16 , 0.183503419072 , }, { 2.0 , 2.22044604925e-16 , 2.22044604925e-16 , 0.183503419072 , }, { 1.81649658093 , 0.183503419072 , 0.183503419072 , 0.0 , }, }; //so lets get it to just x'y/(||x|| ||y||) for(int i = 0; i < expected.length; i++) for(int j = 0; j < expected[i].length; j++) expected[i][j] = (expected[i][j]*-1)+1; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); CosineDistanceNormalized dist = new CosineDistanceNormalized(); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { CosineDistanceNormalized d = dist.clone(); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(vecs.get(i), vecs.get(j))), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, j, vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache)), 1e-8); } cache = null; for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { CosineDistanceNormalized d = dist.clone(); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(vecs.get(i), vecs.get(j))), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, j, vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), vecs, cache)), 1e-8); assertEquals(expected[i][j], CosineDistance.distanceToCosine(d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache)), 1e-8); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); CosineDistanceNormalized instance = new CosineDistanceNormalized(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); CosineDistanceNormalized instance = new CosineDistanceNormalized(); assertTrue(instance.metricBound() > 0); assertEquals(1.0, instance.metricBound(), 0.0); } }
5,883
31.508287
153
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/EuclideanDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class EuclideanDistanceTest { static private ExecutorService ex; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public EuclideanDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); expected = new double[][] { { 0.0 , 2.2360679775 , 1.11803398875 , 5.47722557505 , }, { 2.2360679775 , 0.0 , 1.11803398875 , 3.87298334621 , }, { 1.11803398875 , 1.11803398875 , 0.0 , 4.60977222865 , }, { 5.47722557505 , 3.87298334621 , 4.60977222865 , 0.0 , }, }; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); EuclideanDistance dist = new EuclideanDistance(); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { EuclideanDistance d = dist.clone(); assertEquals(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8); assertEquals(expected[i][j], d.dist(i, j, vecs, cache), 1e-8); assertEquals(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8); assertEquals(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
4,577
27.792453
120
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/JaccardDistanceTest.java
/* * Copyright (C) 2017 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.List; import java.util.concurrent.ExecutorService; import jsat.linear.DenseVector; import jsat.linear.Vec; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class JaccardDistanceTest { public JaccardDistanceTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of dist method, of class JaccardDistance. */ @Test public void testDist_Vec_Vec() { System.out.println("dist"); Vec a = DenseVector.toDenseVec(0.0, 1.0, 0.0, 2.0, 5.0); Vec b = DenseVector.toDenseVec(1.0, 0.0, 0.0, 3.0, 0.0); double unweightedSim = 1.0/4; double weightedSim = 2.0/10; JaccardDistance j = new JaccardDistance(false); JaccardDistance wj = new JaccardDistance(true); assertEquals(unweightedSim, j.eval(a, b), 1e-12); assertEquals(1-unweightedSim, j.dist(a, b), 1e-12); assertEquals(unweightedSim, j.eval(b, a), 1e-12); assertEquals(1-unweightedSim, j.dist(b, a), 1e-12); assertEquals(weightedSim, wj.eval(a, b), 1e-12); assertEquals(1-weightedSim, wj.dist(a, b), 1e-12); assertEquals(weightedSim, wj.eval(b, a), 1e-12); assertEquals(1-weightedSim, wj.dist(b, a), 1e-12); assertEquals(1.0, j.eval(a, a), 1e-12); assertEquals(0.0, j.dist(a, a), 1e-12); assertEquals(1.0, j.eval(b, b), 1e-12); assertEquals(0.0, j.dist(b, b), 1e-12); assertEquals(1.0, wj.eval(a, a), 1e-12); assertEquals(0.0, wj.dist(a, a), 1e-12); assertEquals(1.0, wj.eval(b, b), 1e-12); assertEquals(0.0, wj.dist(b, b), 1e-12); } /** * Test of isSymmetric method, of class JaccardDistance. */ @Test public void testIsSymmetric() { System.out.println("isSymmetric"); JaccardDistance instance = new JaccardDistance(); boolean expResult = true; boolean result = instance.isSymmetric(); assertEquals(expResult, result); } /** * Test of isSubadditive method, of class JaccardDistance. */ @Test public void testIsSubadditive() { System.out.println("isSubadditive"); JaccardDistance instance = new JaccardDistance(); boolean expResult = true; boolean result = instance.isSubadditive(); assertEquals(expResult, result); } /** * Test of isIndiscemible method, of class JaccardDistance. */ @Test public void testIsIndiscemible() { System.out.println("isIndiscemible"); JaccardDistance instance = new JaccardDistance(); boolean expResult = true; boolean result = instance.isIndiscemible(); assertEquals(expResult, result); } /** * Test of metricBound method, of class JaccardDistance. */ @Test public void testMetricBound() { System.out.println("metricBound"); JaccardDistance instance = new JaccardDistance(); double expResult = 1.0; double result = instance.metricBound(); assertEquals(expResult, result, 0.0); } /** * Test of supportsAcceleration method, of class JaccardDistance. */ @Test public void testSupportsAcceleration() { System.out.println("supportsAcceleration"); JaccardDistance instance = new JaccardDistance(); boolean expResult = false; boolean result = instance.supportsAcceleration(); assertEquals(expResult, result); } /** * Test of getAccelerationCache method, of class JaccardDistance. */ @Test public void testGetAccelerationCache_List() { System.out.println("getAccelerationCache"); List<? extends Vec> vecs = null; JaccardDistance instance = new JaccardDistance(); List<Double> expResult = null; List<Double> result = instance.getAccelerationCache(vecs); assertEquals(expResult, result); } /** * Test of getAccelerationCache method, of class JaccardDistance. */ @Test public void testGetAccelerationCache_List_ExecutorService() { System.out.println("getAccelerationCache"); List<? extends Vec> vecs = null; ExecutorService threadpool = null; JaccardDistance instance = new JaccardDistance(); List<Double> expResult = null; List<Double> result = instance.getAccelerationCache(vecs, true); assertEquals(expResult, result); } /** * Test of getQueryInfo method, of class JaccardDistance. */ @Test public void testGetQueryInfo() { System.out.println("getQueryInfo"); Vec q = null; JaccardDistance instance = new JaccardDistance(); List<Double> expResult = null; List<Double> result = instance.getQueryInfo(q); assertEquals(expResult, result); } /** * Test of normalized method, of class JaccardDistance. */ @Test public void testNormalized() { System.out.println("normalized"); JaccardDistance instance = new JaccardDistance(); boolean expResult = true; boolean result = instance.normalized(); assertEquals(expResult, result); } }
6,348
27.990868
72
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/MahalanobisDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static jsat.TestTools.*; import jsat.distributions.multivariate.NormalM; import jsat.linear.*; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MahalanobisDistanceTest { static private ExecutorService ex; static private Matrix trueCov; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public MahalanobisDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { trueCov = new DenseMatrix(5, 5); Random rand = RandomUtil.getRandom(); for(int i = 0; i < trueCov.rows(); i++) for(int j = 0; j < trueCov.cols(); j++) trueCov.set(i, j, rand.nextDouble()); trueCov = trueCov.multiplyTranspose(trueCov);//guaranteed Positive Semi Definite now zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); Matrix trueInv = new SingularValueDecomposition(trueCov.clone()).getPseudoInverse(); expected = new double[4][4]; for (int i = 0; i < expected.length; i++) { Vec vi = vecs.get(i); for (int j = 0; j < expected.length; j++) { Vec vj = vecs.get(j); Vec dif = vi.subtract(vj); expected[i][j] = Math.sqrt(dif.dot(trueInv.multiply(dif))); } } } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); NormalM normal = new NormalM(new ConstantVector(0.0, 5), trueCov.clone()); MahalanobisDistance dist = new MahalanobisDistance(); dist.train(normal.sample(1000, RandomUtil.getRandom())); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { MahalanobisDistance d = dist.clone(); assertEqualsRelDiff(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, j, vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-1); } } @Test public void testDist_Vec_Vec_ExecutorService() { System.out.println("dist"); NormalM normal = new NormalM(new ConstantVector(0.0, 5), trueCov.clone()); MahalanobisDistance dist = new MahalanobisDistance(); dist.train(normal.sample(1000, RandomUtil.getRandom()), true); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { MahalanobisDistance d = dist.clone(); assertEqualsRelDiff(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, j, vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-1); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
7,033
30.684685
127
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/ManhattanDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ManhattanDistanceTest { static private ExecutorService ex; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public ManhattanDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); expected = new double[][] { { 0 , 5 , 2.5 , 10 , }, { 5 , 0 , 2.5 , 7 , }, { 2.5 , 2.5 , 0.0 , 8.5 , }, { 10 , 7 , 8.5 , 0 , }, }; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); ManhattanDistance dist = new ManhattanDistance(); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { ManhattanDistance d = dist.clone(); assertEquals(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-12); assertEquals(expected[i][j], d.dist(i, j, vecs, cache), 1e-12); assertEquals(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-12); assertEquals(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-12); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); ManhattanDistance instance = new ManhattanDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); ManhattanDistance instance = new ManhattanDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
4,447
26.974843
121
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/MinkowskiDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.*; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MinkowskiDistanceTest { static private ExecutorService ex; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expectedP2; static private double[][] expectedP1; static private double[][] expectedP1p5; public MinkowskiDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); expectedP2 = new double[][] { { 0.0 , 2.2360679775 , 1.11803398875 , 5.47722557505 , }, { 2.2360679775 , 0.0 , 1.11803398875 , 3.87298334621 , }, { 1.11803398875 , 1.11803398875 , 0.0 , 4.60977222865 , }, { 5.47722557505 , 3.87298334621 , 4.60977222865 , 0.0 , }, }; expectedP1 = new double[][] { { 0 , 5 , 2.5 , 10 , }, { 5 , 0 , 2.5 , 7 , }, { 2.5 , 2.5 , 0.0 , 8.5 , }, { 10 , 7 , 8.5 , 0 , }, }; expectedP1p5 = new double[][] { { 0.0 , 2.92401773821 , 1.46200886911 , 6.61786032327 , }, { 2.92401773821 , 0.0 , 1.46200886911 , 4.64919159806 , }, { 1.46200886911 , 1.46200886911 , 0.0 , 5.54151812966 , }, { 6.61786032327 , 4.64919159806 , 5.54151812966 , 0.0 , }, }; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); MinkowskiDistance dist = new MinkowskiDistance(2.5); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for(int rounds = 0; rounds < 3; rounds++) { //some code so that dense on dense, dense on sparse, and sparse on sparse all get run if(rounds == 1) for(int i = 0; i <vecs.size(); i+=2) vecs.set(i, new SparseVector(vecs.get(i))); else if(rounds == 2) for(int i = 1; i <vecs.size(); i+=2) vecs.set(i, new SparseVector(vecs.get(i))); for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { MinkowskiDistance d = dist.clone(); d.setP(2.0); assertEquals(2.5, dist.getP(), 0.0); assertEquals(expectedP2[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8); assertEquals(expectedP2[i][j], d.dist(i, j, vecs, cache), 1e-8); assertEquals(expectedP2[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8); assertEquals(expectedP2[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8); d.setP(1.0); assertEquals(expectedP1[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8); assertEquals(expectedP1[i][j], d.dist(i, j, vecs, cache), 1e-8); assertEquals(expectedP1[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8); assertEquals(expectedP1[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8); d.setP(1.5); assertEquals(expectedP1p5[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8); assertEquals(expectedP1p5[i][j], d.dist(i, j, vecs, cache), 1e-8); assertEquals(expectedP1p5[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8); assertEquals(expectedP1p5[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8); } } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
6,720
32.108374
128
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/NormalizedEuclideanDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.SimpleDataSet; import static jsat.TestTools.*; import jsat.classifiers.CategoricalData; import jsat.classifiers.DataPoint; import jsat.distributions.multivariate.NormalM; import jsat.linear.*; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NormalizedEuclideanDistanceTest { static private ExecutorService ex; static private Matrix trueCov; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public NormalizedEuclideanDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { trueCov = new DenseMatrix(5, 5); for(int i = 0; i < trueCov.rows(); i++) trueCov.set(i, i, i+1.0); zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); Vec trueWeight = DenseVector.toDenseVec(1, 1.0/(2*2), 1.0/(3*3), 1.0/(4*4), 1.0/(5*5)); WeightedEuclideanDistance weighted = new WeightedEuclideanDistance(trueWeight); expected = new double[4][4]; for (int i = 0; i < expected.length; i++) for (int j = 0; j < expected.length; j++) expected[i][j] = weighted.dist(vecs.get(i), vecs.get(j)); } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); NormalM normal = new NormalM(new ConstantVector(0.0, 5), trueCov.clone()); NormalizedEuclideanDistance dist = new NormalizedEuclideanDistance(); dist.train(normal.sample(30000, RandomUtil.getRandom())); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int rounds = 0; rounds < 3; rounds++) { //some code so that dense on dense, dense on sparse, and sparse on sparse all get run if (rounds == 1) for (int i = 0; i < vecs.size(); i += 2) vecs.set(i, new SparseVector(vecs.get(i))); else if (rounds == 2) for (int i = 1; i < vecs.size(); i += 2) vecs.set(i, new SparseVector(vecs.get(i))); for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { NormalizedEuclideanDistance d = dist.clone(); assertEqualsRelDiff(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, j, vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-1); } } } @Test public void testDist_Vec_Vec_ExecutorService() { System.out.println("dist"); NormalM normal = new NormalM(new ConstantVector(0.0, 5), trueCov.clone()); NormalizedEuclideanDistance dist = new NormalizedEuclideanDistance(); dist.train(normal.sample(30000, RandomUtil.getRandom()), true); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for(int rounds = 0; rounds < 3; rounds++) { //some code so that dense on dense, dense on sparse, and sparse on sparse all get run if(rounds == 1) for(int i = 0; i <vecs.size(); i+=2) vecs.set(i, new SparseVector(vecs.get(i))); else if(rounds == 2) for(int i = 1; i <vecs.size(); i+=2) vecs.set(i, new SparseVector(vecs.get(i))); for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { NormalizedEuclideanDistance d = dist.clone(); assertEqualsRelDiff(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, j, vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-1); assertEqualsRelDiff(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-1); } } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); EuclideanDistance instance = new EuclideanDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
7,957
32.297071
131
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/PearsonDistanceTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.linear.distancemetrics; import jsat.linear.DenseVector; import jsat.linear.SparseVector; import jsat.linear.Vec; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class PearsonDistanceTest { Vec x1, x2, x3, x4, x5; public PearsonDistanceTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { x1 = new DenseVector(new double[]{43, 21, 25, 42, 57, 59}); x2 = new DenseVector(new double[]{99, 65, 79, 75, 87, 81}); x3 = new DenseVector(new double[]{ 0, 12, 0, 38, 19, 0}); x4 = new DenseVector(new double[]{ 0, 60, 27, 0, 13, 9}); x5 = new DenseVector(new double[]{ 0, 0, 25, 42, 0, 0}); } @After public void tearDown() { } /** * Test of correlation method, of class PearsonDistance. */ @Test public void testCorrelation() { System.out.println("correlation"); Vec[][] pairs = new Vec[][] { {x1, x2}, {x2, x1}, {x2, x2}, {x3, x4}, {x4, x3}, {x1, x5}, {x3, x5}, {x4, x5}, }; double[] expectedVals = new double[] { 0.5298089018901744, 0.5298089018901744, 1.0, -0.16532953228838151, -0.16532953228838151, -0.2587220950032312, 0.5995147431422027, -0.2625496015918526, }; for(int i = 0; i < pairs.length; i++) { double result = PearsonDistance.correlation(pairs[i][0], pairs[i][1], false); double expected = expectedVals[i]; assertEquals(expected, result, 1e-14); result = PearsonDistance.correlation(pairs[i][1], pairs[i][0], false); assertEquals(expected, result, 1e-14); } //on sparse inputs for(int i = 0; i < pairs.length; i++) { double result = PearsonDistance.correlation(new SparseVector(pairs[i][0]), new SparseVector(pairs[i][1]), false); double expected = expectedVals[i]; assertEquals(expected, result, 1e-14); result = PearsonDistance.correlation(new SparseVector(pairs[i][1]), new SparseVector(pairs[i][0]), false); assertEquals(expected, result, 1e-14); } } @Test public void testCorrelationBNZ() { System.out.println("correlation"); Vec[][] pairs = new Vec[][] { {x1, x2}, {x2, x1}, {x2, x2}, {x3, x4}, {x4, x3}, {x1, x5}, {x3, x5}, {x4, x5}, }; double[] expectedVals = new double[] { 0.5298089018901744, 0.5298089018901744, 1.0, -0.7254024447917231, -0.7254024447917231, 0.7425697235686509, 1.0, 1.0, }; for(int i = 0; i < pairs.length; i++) { double result = PearsonDistance.correlation(pairs[i][0], pairs[i][1], true); double expected = expectedVals[i]; assertEquals(expected, result, 1e-14); result = PearsonDistance.correlation(pairs[i][1], pairs[i][0], true); assertEquals(expected, result, 1e-14); } //on sparse inputs for(int i = 0; i < pairs.length; i++) { double result = PearsonDistance.correlation(new SparseVector(pairs[i][0]), new SparseVector(pairs[i][1]), true); double expected = expectedVals[i]; assertEquals(expected, result, 1e-14); result = PearsonDistance.correlation(new SparseVector(pairs[i][1]), new SparseVector(pairs[i][0]), true); assertEquals(expected, result, 1e-14); } } }
4,310
26.812903
125
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/SquaredEuclideanDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SquaredEuclideanDistanceTest { static private ExecutorService ex; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public SquaredEuclideanDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); expected = new double[][] { { 0.0 , 2.2360679775 , 1.11803398875 , 5.47722557505 , }, { 2.2360679775 , 0.0 , 1.11803398875 , 3.87298334621 , }, { 1.11803398875 , 1.11803398875 , 0.0 , 4.60977222865 , }, { 5.47722557505 , 3.87298334621 , 4.60977222865 , 0.0 , }, }; for(int i = 0; i < expected.length; i++) for(int j = 0; j < expected[i].length; j++) expected[i][j] *= expected[i][j]; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); SquaredEuclideanDistance dist = new SquaredEuclideanDistance(); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { SquaredEuclideanDistance d = dist.clone(); assertEquals(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8); assertEquals(expected[i][j], d.dist(i, j, vecs, cache), 1e-8); assertEquals(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8); assertEquals(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); SquaredEuclideanDistance instance = new SquaredEuclideanDistance(); assertTrue(instance.isSymmetric()); assertFalse(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); SquaredEuclideanDistance instance = new SquaredEuclideanDistance(); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
4,796
28.611111
120
java
JSAT
JSAT-master/JSAT/test/jsat/linear/distancemetrics/WeightedEuclideanDistanceTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.distancemetrics; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class WeightedEuclideanDistanceTest { static private ExecutorService ex; static private Vec weights; static private Vec zero; static private Vec ones; static private Vec half; static private Vec inc; static private List<Vec> vecs; static private double[][] expected; public WeightedEuclideanDistanceTest() { } @BeforeClass public static void setUpClass() { ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); } @AfterClass public static void tearDownClass() { ex.shutdown(); } @Before public void setUp() { zero = new DenseVector(5); ones = new DenseVector(5); ones.mutableAdd(1.0); half = new DenseVector(5); half.mutableAdd(0.5); inc = new DenseVector(5); for(int i = 0; i < inc.length(); i++) inc.set(i, i); vecs = Arrays.asList(zero, ones, half, inc); //weighting weights = DenseVector.toDenseVec(1, 0.5, 1, 2, 1); for(Vec v : vecs) { v.set(1, v.get(1)*2); v.set(3, v.get(3)/2); } expected = new double[][] { { 0.0 , 2.34520787991 , 1.17260393996 , 5.14781507049 , }, { 2.34520787991 , 0.0 , 1.17260393996 , 3.60555127546 , }, { 1.17260393996 , 1.17260393996 , 0.0 , 4.28660704987 , }, { 5.14781507049 , 3.60555127546 , 4.28660704987 , 0.0 , }, }; } @After public void tearDown() { } @Test public void testDist_Vec_Vec() { System.out.println("dist"); WeightedEuclideanDistance dist = new WeightedEuclideanDistance(weights); List<Double> cache = dist.getAccelerationCache(vecs); List<Double> cache2 = dist.getAccelerationCache(vecs, true); if(cache != null) { assertEquals(cache.size(), cache2.size()); for(int i = 0; i < cache.size(); i++) assertEquals(cache.get(i), cache2.get(i), 0.0); assertTrue(dist.supportsAcceleration()); } else { assertNull(cache2); assertFalse(dist.supportsAcceleration()); } try { dist.dist(half, new DenseVector(half.length()+1)); fail("Distance between vecs should have erred"); } catch (Exception ex) { } for (int i = 0; i < vecs.size(); i++) for (int j = 0; j < vecs.size(); j++) { WeightedEuclideanDistance d = dist.clone(); assertEquals(expected[i][j], d.dist(vecs.get(i), vecs.get(j)), 1e-8); assertEquals(expected[i][j], d.dist(i, j, vecs, cache), 1e-8); assertEquals(expected[i][j], d.dist(i, vecs.get(j), vecs, cache), 1e-8); assertEquals(expected[i][j], d.dist(i, vecs.get(j), dist.getQueryInfo(vecs.get(j)), vecs, cache), 1e-8); } } @Test public void testMetricProperties() { System.out.println("isSymmetric"); WeightedEuclideanDistance instance = new WeightedEuclideanDistance(weights); assertTrue(instance.isSymmetric()); assertTrue(instance.isSubadditive()); assertTrue(instance.isIndiscemible()); } @Test public void testMetricBound() { System.out.println("metricBound"); WeightedEuclideanDistance instance = new WeightedEuclideanDistance(weights); assertTrue(instance.metricBound() > 0); assertTrue(Double.isInfinite(instance.metricBound())); } }
4,906
28.208333
120
java
JSAT
JSAT-master/JSAT/test/jsat/linear/solvers/ConjugateGradientTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.linear.solvers; import jsat.linear.Matrix; import jsat.linear.Vec; import jsat.linear.DenseMatrix; import jsat.linear.DenseVector; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ConjugateGradientTest { public ConjugateGradientTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSolve_4args() { System.out.println("solve"); DenseMatrix A = new DenseMatrix(new double[][] { {4, 1}, {1, 3} }); DenseVector b = DenseVector.toDenseVec(1, 2); Vec x = new DenseVector(2); x = ConjugateGradient.solve(1e-13, A, x, b); assertTrue(A.multiply(x).equals(b, 1e-10)); //Test for a 5x5 matrix symmetric positive definite A = new DenseMatrix(new double[][] { {1, 1, 1, 1, 1}, {1, 8, 1, 8, 1}, {1, 1, 27, 1, 1}, {1, 8, 1, 64, 1}, {1, 1, 1, 1, 125} }); b = DenseVector.toDenseVec(1, 4, 3, 5, 2); x = new DenseVector(5); x = ConjugateGradient.solve(1e-13, A, x, b); assertTrue(A.multiply(x).equals(b, 1e-10)); } @Test public void testSolve_Matrix_Vec() { System.out.println("solve"); DenseMatrix A = new DenseMatrix(new double[][] { {4, 1}, {1, 3} }); DenseVector b = DenseVector.toDenseVec(1, 2); Vec x = new DenseVector(2); x = ConjugateGradient.solve(A, b); assertTrue(A.multiply(x).equals(b, 1e-8)); //Test for a 5x5 matrix symmetric positive definite A = new DenseMatrix(new double[][] { {1, 1, 1, 1, 1}, {1, 8, 1, 8, 1}, {1, 1, 27, 1, 1}, {1, 8, 1, 64, 1}, {1, 1, 1, 1, 125} }); b = DenseVector.toDenseVec(1, 4, 3, 5, 2); x = new DenseVector(5); x = ConjugateGradient.solve(A, b); assertTrue(A.multiply(x).equals(b, 1e-8)); } @Test public void testSolveCGNR_4args() { System.out.println("solveCGNR"); double eps = 1e-14; DenseMatrix A = new DenseMatrix(new double[][] { {9 , 3, 9, 5, 9, 6, 9, 3}, {10, 8, 3, 4, 3, 1, 1, 2}, {5 , 3, 2, 8, 8, 1, 6, 8}, {1 , 8, 3, 6, 8, 5, 5, 3}, {1 , 2, 6, 5, 4, 8, 0, 5}, }); DenseVector b = DenseVector.toDenseVec(1, 4, 3, 5, 2); Vec x = new DenseVector(A.cols()); x = ConjugateGradient.solveCGNR(eps, A, x, b); assertTrue(A.multiply(x).equals(b, 1e-10)); //This is under determined, exact result will not be possible A = new DenseMatrix(new double[][] { {4 , 8, 8, 1}, {1 , 9, 4, 1}, {10, 1, 9, 9}, {0 , 4, 2, 6}, {8 , 3, 3, 5}, }); x = new DenseVector(A.cols()); x = ConjugateGradient.solveCGNR(eps, A, x, b); double error = A.multiply(x).subtract(b).pNorm(2); assertEquals(1.0125, error, 1e-4);//True result computed with matlab } @Test public void testSolveCGNR_Matrix_Vec() { System.out.println("solveCGNR"); DenseMatrix A = new DenseMatrix(new double[][] { {9 , 3, 9, 5, 9, 6, 9, 3}, {10, 8, 3, 4, 3, 1, 1, 2}, {5 , 3, 2, 8, 8, 1, 6, 8}, {1 , 8, 3, 6, 8, 5, 5, 3}, {1 , 2, 6, 5, 4, 8, 0, 5}, }); DenseVector b = DenseVector.toDenseVec(1, 4, 3, 5, 2); Vec x; x = ConjugateGradient.solveCGNR(A, b); assertTrue(A.multiply(x).equals(b, 1e-8)); //This is under determined, exact result will not be possible A = new DenseMatrix(new double[][] { {4 , 8, 8, 1}, {1 , 9, 4, 1}, {10, 1, 9, 9}, {0 , 4, 2, 6}, {8 , 3, 3, 5}, }); x = ConjugateGradient.solveCGNR(A, b); double error = A.multiply(x).subtract(b).pNorm(2); assertEquals(1.0125, error, 1e-4);//True result computed with matlab } @Test public void testSolve_5args() { System.out.println("solve"); //Test for a 5x5 matrix symmetric positive definite DenseMatrix A = new DenseMatrix(new double[][] { {1, 1, 1, 1, 1}, {1, 8, 1, 8, 1}, {1, 1, 27, 1, 1}, {1, 8, 1, 64, 1}, {1, 1, 1, 1, 125} }); DenseVector b = DenseVector.toDenseVec(1, 4, 3, 5, 2); DenseMatrix Minv = new DenseMatrix(new double[][] { {1.0000, 0 , 0 , 0 , 0}, {0 , 0.1250, 0 , 0 , 0}, {0 , 0 , 0.0370, 0 , 0}, {0 , 0 , 0 , 0.0156 , 0}, {0 , 0 , 0 , 0 , 0.0080}, }); Vec x = new DenseVector(5); x = ConjugateGradient.solve(1e-13, A, x, b, Minv); assertTrue(A.multiply(x).equals(b, 1e-3));//Our Minv only has 4 sig figs //DO it again using the identiy matrix as the precondition (which dosnt actually help, but makes sure the code is runnig right) Minv = Matrix.eye(5); x = ConjugateGradient.solve(1e-13, A, x, b, Minv); assertTrue(A.multiply(x).equals(b, 1e-10)); } }
6,954
27.504098
135
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/BallTreeTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.EnumSet; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.DoubleList; import jsat.utils.IntList; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class BallTreeTest { public BallTreeTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(int leaf_size : new int[]{2, 10, 40}) for (BallTree.PivotSelection pm : BallTree.PivotSelection.values()) for (BallTree.ConstructionMethod cm : BallTree.ConstructionMethod.values()) for (boolean parallel : new boolean[]{true, false}) { BallTree<Vec> collection0 = new BallTree<>(new EuclideanDistance(), cm, pm); collection0.setLeafSize(leaf_size); collection0 = collection0.clone(); collection0.build(parallel, vecCol); collection0 = collection0.clone(); IntList trueNN = new IntList(); DoubleList trueNN_dists = new DoubleList(); IntList foundNN = new IntList(); DoubleList foundNN_dists = new DoubleList(); for (int iters = 0; iters < 10; iters++) for (double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex = rand.nextInt(vecCol.size()); Vec query = vecCol.get(randIndex); vecCol.search(query, range, trueNN, trueNN_dists); collection0.search(query, range, foundNN, foundNN_dists); assertEquals(trueNN.size(), foundNN.size()); assertEquals(trueNN_dists.size(), foundNN_dists.size()); for (int i = 0; i < trueNN.size(); i++) { assertEquals(trueNN.get(i), foundNN.get(i)); assertEquals(trueNN_dists.get(i), trueNN_dists.get(i), 0.0); } } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(int leaf_size : new int[]{2, 10, 40}) for (BallTree.PivotSelection pm : BallTree.PivotSelection.values()) for (BallTree.ConstructionMethod cm : BallTree.ConstructionMethod.values()) for (boolean parallel : new boolean[]{true, false}) { BallTree<Vec> collection0 = new BallTree<>(new EuclideanDistance(), cm, pm); collection0.setLeafSize(leaf_size); collection0 = collection0.clone(); collection0.build(parallel, vecCol); collection0 = collection0.clone(); IntList trueNN = new IntList(); DoubleList trueNN_dists = new DoubleList(); IntList foundNN = new IntList(); DoubleList foundNN_dists = new DoubleList(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); Vec query = vecCol.get(randIndex); vecCol.search(query, neighbours, trueNN, trueNN_dists); collection0.search(query, neighbours, foundNN, foundNN_dists); assertEquals(trueNN.size(), foundNN.size()); assertEquals(trueNN_dists.size(), foundNN_dists.size()); for (int i = 0; i < trueNN.size(); i++) { assertEquals(trueNN.get(i), foundNN.get(i)); assertEquals(trueNN_dists.get(i), trueNN_dists.get(i), 0.0); } } } } @Test public void testSearch_Vec_int_incramental() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); for(int leaf_size : new int[]{2, 10, 40}) for (BallTree.PivotSelection pm : BallTree.PivotSelection.values()) for (BallTree.ConstructionMethod cm : BallTree.ConstructionMethod.values()) { BallTree<Vec> collection0 = new BallTree(new EuclideanDistance(), cm, pm); collection0.setLeafSize(leaf_size); for(Vec v : vecCol) collection0.insert(v); IntList trueNN = new IntList(); DoubleList trueNN_dists = new DoubleList(); IntList foundNN = new IntList(); DoubleList foundNN_dists = new DoubleList(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); Vec query = vecCol.get(randIndex); vecCol.search(query, neighbours, trueNN, trueNN_dists); collection0.search(query, neighbours, foundNN, foundNN_dists); assertEquals(trueNN.size(), foundNN.size()); assertEquals(trueNN_dists.size(), foundNN_dists.size()); for (int i = 0; i < trueNN.size(); i++) { assertEquals(trueNN.get(i), foundNN.get(i)); assertEquals(trueNN_dists.get(i), trueNN_dists.get(i), 0.0); } } } } }
8,204
36.986111
100
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/CoverTreeTest.java
/* * Copyright (C) 2017 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.DistanceCounter; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.DoubleList; import jsat.utils.IntList; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class CoverTreeTest { static List<VectorCollection<Vec>> collectionFactories; public CoverTreeTest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<VectorCollection<Vec>>(); collectionFactories.add(new CoverTree<>(new EuclideanDistance())); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), range); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), neighbours); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(factory.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest0.get(i)), foundTrue.get(i).equals(foundTest0.get(i), 1e-13)); } assertEquals(factory.getClass().getName() + " failed " + neighbours, foundTrue.size(), foundTest1.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(factory.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest1.get(i)), foundTrue.get(i).equals(foundTest1.get(i), 1e-13)); } } } } @Test public void testSearch_Vec_int_incramental() { System.out.println("search_inc"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); CoverTree<Vec> collection0 = new CoverTree(new EuclideanDistance()); for(Vec v : vecCol) collection0.insert(v); IntList trueNN = new IntList(); DoubleList trueNN_dists = new DoubleList(); IntList foundNN = new IntList(); DoubleList foundNN_dists = new DoubleList(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); Vec query = vecCol.get(randIndex); vecCol.search(query, neighbours, trueNN, trueNN_dists); collection0.search(query, neighbours, foundNN, foundNN_dists); assertEquals(trueNN.size(), foundNN.size()); assertEquals(trueNN_dists.size(), foundNN_dists.size()); for (int i = 0; i < trueNN.size(); i++) { assertEquals(trueNN.get(i), foundNN.get(i)); assertEquals(trueNN_dists.get(i), trueNN_dists.get(i), 0.0); } } } }
8,688
37.617778
166
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/DCITest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.TestTools; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.DoubleList; import jsat.utils.IntList; import jsat.utils.SystemInfo; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class DCITest { static List<VectorCollection<Vec>> collectionFactories; public DCITest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<>(); collectionFactories.add(new DCI<>(25, 5)); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2500; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1 = TestTools.deepCopy(collection1); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); collection1 = TestTools.deepCopy(collection1); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex= rand.nextInt(vecCol.size()); IntList nn_true = new IntList(); IntList nn_test = new IntList(); DoubleList nd_true = new DoubleList(); DoubleList nd_test = new DoubleList(); vecCol.search(vecCol.get(randIndex), range, nn_true, nd_true); collection0.search(vecCol.get(randIndex), range, nn_test, nd_test); int found = (int) nn_test.streamInts().filter(nn_true::contains).count(); //Since DCI is approximate, allow for missing half assertEquals(nn_true.size(), found, nn_true.size()/2.0); collection1.search(vecCol.get(randIndex), range, nn_test, nd_test); found = (int) nn_test.streamInts().filter(nn_true::contains).count(); //Since DCI is approximate, allow for missing half assertEquals(nn_true.size(), found, nn_true.size()/2.0); } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2500; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); IntList nn_true = new IntList(); IntList nn_test = new IntList(); DoubleList nd_true = new DoubleList(); DoubleList nd_test = new DoubleList(); vecCol.search(vecCol.get(randIndex), neighbours, nn_true, nd_true); collection0.search(vecCol.get(randIndex), neighbours, nn_test, nd_test); int found = (int) nn_test.streamInts().filter(nn_true::contains).count(); //Since DCI is approximate, allow for missing half assertEquals(neighbours, found, neighbours/2.0); collection1.search(vecCol.get(randIndex), neighbours, nn_test, nd_test); found = (int) nn_test.streamInts().filter(nn_true::contains).count(); //Since DCI is approximate, allow for missing half assertEquals(neighbours, found, neighbours/2.0); } } } // @Test public void testSearch_Vec_int_incramental() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); IncrementalCollection<Vec> collection0 = new VPTree<Vec>(new EuclideanDistance()); for(Vec v : vecCol) collection0.insert(v); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); assertEquals(collection0.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(collection0.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest0.get(i)), foundTrue.get(i).equals(foundTest0.get(i), 1e-13)); } } } }
7,180
32.556075
166
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/DualTreeTest.java
/* * Copyright (C) 2018 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.DoubleList; import jsat.utils.IntList; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class DualTreeTest { public DualTreeTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of search method, of class DualTree. */ @Test public void testSearch_Radius_DT() { System.out.println("search_radius_dt"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> A = new VectorArray<>(new EuclideanDistance()); VectorArray<Vec> B = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2500; i++) { A.add(DenseVector.random(3, rand)); B.add(DenseVector.random(3, rand)); } List<List<Integer>> nn_true = new ArrayList<>(); List<List<Double>> dists_true = new ArrayList<>(); double min_radius = 0.1; double max_radius = 0.2; for(int i = 0; i < B.size(); i++) { List<Integer> nn = new IntList(); List<Double> dd = new DoubleList(); A.search(B.get(i), max_radius, nn, dd); //remove everyone that was too close while(!dd.isEmpty() && dd.get(0) < min_radius) { nn.remove(0); dd.remove(0); } nn_true.add(nn); dists_true.add(dd); } // VPTree<Vec> A_dt = new VPTree<>(); // VPTree<Vec> B_dt = new VPTree<>(); // for(DualTree<Vec> base : Arrays.asList(new SVPTree<>())) // for(DualTree<Vec> base : Arrays.asList(new VPTree<>())) for(boolean parallel : new boolean[]{false,true}) for(DualTree<Vec> base : Arrays.asList(new BallTree<>(), new VPTree<>())) { // System.out.println(base.getClass().getCanonicalName()); DualTree<Vec> A_dt = base.clone(); DualTree<Vec> B_dt = base.clone(); A_dt.build(A); B_dt.build(B); List<List<Integer>> nn_found = new ArrayList<>(); List<List<Double>> dists_found = new ArrayList<>(); A_dt.search(B_dt, min_radius, max_radius, nn_found, dists_found, parallel); for(int i = 0; i < B.size(); i++) { List<Integer> nn_t = nn_true.get(i); List<Integer> nn_f = nn_found.get(i); List<Double> dd_t = dists_true.get(i); List<Double> dd_f = dists_found.get(i); assertEquals(nn_t.size(), nn_f.size()); assertEquals(dd_t.size(), dd_f.size()); for(int j = 0; j < nn_t.size(); j++) { assertEquals(nn_t.get(j), nn_f.get(j)); assertEquals(dd_t.get(j), dd_f.get(j), 1e-10); } } } } @Test public void testSearch_knn_DT() { System.out.println("search_knn_dt"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> A = new VectorArray<>(new EuclideanDistance()); VectorArray<Vec> B = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2500; i++) { A.add(DenseVector.random(3, rand)); B.add(DenseVector.random(3, rand)); } List<List<Integer>> nn_true = new ArrayList<>(); List<List<Double>> dists_true = new ArrayList<>(); int K = 9; for(int i = 0; i < B.size(); i++) { List<Integer> nn = new IntList(); List<Double> dd = new DoubleList(); A.search(B.get(i), K, nn, dd); nn_true.add(nn); dists_true.add(dd); } // for(DualTree<Vec> base : Arrays.asList(new VPTree<>())) // for(DualTree<Vec> base : Arrays.asList(new SVPTree<>())) for(boolean parallel : new boolean[]{false, true}) for(DualTree<Vec> base : Arrays.asList(new BallTree<>(), new VPTreeMV<>())) { // System.out.println(base.getClass().getCanonicalName()); DualTree<Vec> A_dt = base.clone(); DualTree<Vec> B_dt = base.clone(); A_dt.build(A); B_dt.build(B); List<List<Integer>> nn_found = new ArrayList<>(); List<List<Double>> dists_found = new ArrayList<>(); A_dt.search(B_dt, K, nn_found, dists_found, parallel); for(int i = 0; i < B.size(); i++) { List<Integer> nn_t = nn_true.get(i); List<Integer> nn_f = nn_found.get(i); List<Double> dd_t = dists_true.get(i); List<Double> dd_f = dists_found.get(i); assertEquals(nn_t.size(), nn_f.size()); assertEquals(dd_t.size(), dd_f.size()); for(int j = 0; j < nn_t.size(); j++) { assertEquals(nn_t.get(j), nn_f.get(j)); assertEquals(dd_t.get(j), dd_f.get(j), 1e-10); } } } } }
6,788
29.039823
91
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/KDTreeTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.DoubleList; import jsat.utils.IntList; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class KDTreeTest { static List<VectorCollection<Vec>> collectionFactories; public KDTreeTest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<VectorCollection<Vec>>(); for(KDTree.PivotSelection pivot : KDTree.PivotSelection.values()) collectionFactories.add(new KDTree<>(pivot)); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2050; i++) vecCol.add(DenseVector.random(3, rand)); ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); for(VectorCollection<Vec> factory : collectionFactories) { VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.001, 0.1, 0.25, 0.5}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), range); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } } } ex.shutdownNow(); } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 2050; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), neighbours); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed " + neighbours, foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed " + neighbours, nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int_incramental() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); for(int leaf_size : new int[]{10, 40}) for (KDTree.PivotSelection pm : KDTree.PivotSelection.values()) { KDTree<Vec> collection0 = new KDTree(pm); collection0.setLeafSize(leaf_size); for(Vec v : vecCol) collection0.insert(v); IntList trueNN = new IntList(); DoubleList trueNN_dists = new DoubleList(); IntList foundNN = new IntList(); DoubleList foundNN_dists = new DoubleList(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); Vec query = vecCol.get(randIndex); vecCol.search(query, neighbours, trueNN, trueNN_dists); collection0.search(query, neighbours, foundNN, foundNN_dists); assertEquals(trueNN.size(), foundNN.size()); assertEquals(trueNN_dists.size(), foundNN_dists.size()); for (int i = 0; i < trueNN.size(); i++) { assertEquals(trueNN.get(i), foundNN.get(i)); assertEquals(trueNN_dists.get(i), trueNN_dists.get(i), 0.0); } } } } }
9,433
39.48927
148
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/RTreeTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.SystemInfo; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class RTreeTest { static List<VectorCollection<Vec>> collectionFactories; public RTreeTest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<>(); collectionFactories.add(new RTree<>()); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } // @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), range); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), neighbours); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed " + neighbours, foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed " + neighbours, nn.get(0).equals(v, 1e-13)); } } } } }
7,227
38.282609
126
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/RandomBallCoverTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.SystemInfo; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class RandomBallCoverTest { static List<VectorCollection<Vec>> collectionFactories; public RandomBallCoverTest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<VectorCollection<Vec>>(); collectionFactories.add(new RandomBallCover<Vec>()); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), range); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), neighbours); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(factory.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest0.get(i)), foundTrue.get(i).equals(foundTest0.get(i), 1e-13)); } assertEquals(factory.getClass().getName() + " failed " + neighbours, foundTrue.size(), foundTest1.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(factory.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest1.get(i)), foundTrue.get(i).equals(foundTest1.get(i), 1e-13)); } } } } @Test public void testSearch_Vec_int_incramental() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); IncrementalCollection<Vec> collection0 = new RandomBallCover<Vec>(new EuclideanDistance()); for(Vec v : vecCol) collection0.insert(v); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); assertEquals(collection0.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(collection0.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest0.get(i)), foundTrue.get(i).equals(foundTest0.get(i), 1e-13)); } } } }
8,496
39.080189
166
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/VPTreeMVTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.SystemInfo; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class VPTreeMVTest { static List<VectorCollection<Vec>> collectionFactories; public VPTreeMVTest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<VectorCollection<Vec>>(); for(VPTree.VPSelection samplingStrat : VPTree.VPSelection.values()) collectionFactories.add(new VPTreeMV<Vec>(new EuclideanDistance(), samplingStrat)); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), range); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), neighbours); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed " + neighbours, foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed " + neighbours, nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int_incramental() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); IncrementalCollection<Vec> collection0 = new VPTreeMV<Vec>(new EuclideanDistance()); for(Vec v : vecCol) collection0.insert(v); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); assertEquals(collection0.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(collection0.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest0.get(i)), foundTrue.get(i).equals(foundTest0.get(i), 1e-13)); } } } }
8,804
39.763889
166
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/VPTreeTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.IntList; import jsat.utils.SystemInfo; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class VPTreeTest { static List<VectorCollection<Vec>> collectionFactories; public VPTreeTest() { } @BeforeClass public static void setUpClass() { collectionFactories = new ArrayList<>(); for(VPTree.VPSelection samplingStrat : VPTree.VPSelection.values()) collectionFactories.add(new VPTree<>(new EuclideanDistance(), samplingStrat)); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); collection0 = collection0.clone(); collection1 = collection1.clone(); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(double range : new double[]{0.25, 0.5, 0.75, 2.0}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), range); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), range); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); ex.shutdownNow(); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 4, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest1 = collection1.search(vecCol.get(randIndex), neighbours); VectorArray<VecPaired<Vec, Double>> testSearch0 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest0); assertEquals(factory.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch0.search(v, 1); assertTrue(factory.getClass().getName() + " failed", nn.get(0).equals(v, 1e-13)); } VectorArray<VecPaired<Vec, Double>> testSearch1 = new VectorArray<VecPaired<Vec, Double>>(new EuclideanDistance(), foundTest1); assertEquals(factory.getClass().getName() + " failed " + neighbours, foundTrue.size(), foundTest1.size()); for(Vec v : foundTrue) { List<? extends VecPaired<VecPaired<Vec, Double>, Double>> nn = testSearch1.search(v, 1); assertTrue(factory.getClass().getName() + " failed " + neighbours, nn.get(0).equals(v, 1e-13)); } } } } @Test public void testSearch_BulkKNN() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 250; i++) vecCol.add(DenseVector.random(3, rand)); VectorArray<Vec> queries = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < SystemInfo.LogicalCores*2; i++) queries.add(DenseVector.random(3, rand)); for(VectorCollection<Vec> factory : collectionFactories) { ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); VectorCollection<Vec> collection0 = factory.clone(); collection0.build(vecCol, new EuclideanDistance()); VectorCollection<Vec> collection1 = factory.clone(); collection1.build(true, vecCol, new EuclideanDistance()); ex.shutdownNow(); List<List<Integer>> neighbors_true = new ArrayList<>(); List<List<Double>> distances_true = new ArrayList<>(); List<List<Integer>> neighbors_0 = new ArrayList<>(); List<List<Double>> distances_0 = new ArrayList<>(); List<List<Integer>> neighbors_1 = new ArrayList<>(); List<List<Double>> distances_1 = new ArrayList<>(); for(int neighbours : new int[]{1, 2, 4, 10, 20}) { vecCol.search((List<Vec>) queries, neighbours, neighbors_true, distances_true, true); collection0.search((List<Vec>) queries, neighbours, neighbors_0, distances_0, false); collection1.search((List<Vec>) queries, neighbours, neighbors_1, distances_1, true); System.out.println(neighbours); for(int i = 0; i < neighbors_true.size(); i++) { List<Integer> n_t_i = neighbors_true.get(i); List<Integer> n_0_i = neighbors_0.get(i); List<Integer> n_1_i = neighbors_1.get(i); List<Double> d_t_i = distances_true.get(i); List<Double> d_0_i = distances_0.get(i); List<Double> d_1_i = distances_1.get(i); for(int j = 0; j < neighbors_true.get(i).size(); j++) { assertEquals(n_t_i.get(j), n_0_i.get(j)); assertEquals(n_t_i.get(j), n_1_i.get(j)); assertEquals(d_t_i.get(j), d_0_i.get(j)); assertEquals(d_t_i.get(j), d_1_i.get(j)); } } } } } @Test public void testSearch_Vec_int_incramental() { System.out.println("search"); Random rand = new XORWOW(123); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(int i = 0; i < 1000; i++) vecCol.add(DenseVector.random(3, rand)); IncrementalCollection<Vec> collection0 = new VPTree<Vec>(new EuclideanDistance()); for(Vec v : vecCol) collection0.insert(v); for(int iters = 0; iters < 10; iters++) for(int neighbours : new int[]{1, 2, 5, 10, 20}) { int randIndex= rand.nextInt(vecCol.size()); List<? extends VecPaired<Vec, Double>> foundTrue = vecCol.search(vecCol.get(randIndex), neighbours); List<? extends VecPaired<Vec, Double>> foundTest0 = collection0.search(vecCol.get(randIndex), neighbours); assertEquals(collection0.getClass().getName() + " failed", foundTrue.size(), foundTest0.size()); for(int i = 0; i < foundTrue.size(); i++) { assertTrue(collection0.getClass().getName() + " failed " + (i+1) + "'th / " + neighbours + " " + foundTrue.get(i).pNormDist(2, foundTest0.get(i)), foundTrue.get(i).equals(foundTest0.get(i), 1e-13)); } } } }
11,123
39.304348
166
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/VectorArrayTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.linear.vectorcollection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.DoubleList; import jsat.utils.IntList; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class VectorArrayTest { static List<Vec> simpleSet; public VectorArrayTest() { } @BeforeClass public static void setUpClass() { simpleSet = new ArrayList<Vec>(); for(int i = 0 ; i < 1000; i++) simpleSet.add(DenseVector.toDenseVec(i)); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of search method, of class VectorArray. */ @Test public void testSearch_Vec_double() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); vecCol.addAll(simpleSet); for(int iters = 0; iters < 100; iters++) for(double range : new double[]{2.0, 5.0, 10.0}) { int randIndex= rand.nextInt(simpleSet.size()); List<? extends VecPaired<Vec, Double>> found = vecCol.search(simpleSet.get(randIndex), range); int min = (int) Math.max(randIndex-range, 0); int max = (int) Math.min(randIndex+range, simpleSet.size()-1); for(Vec v : found) assertTrue(min <= v.get(0) && v.get(0) <= max); assertEquals(1+max-min, found.size()); } } /** * Test of search method, of class VectorArray. */ @Test public void testSearch_Vec_int() { System.out.println("search"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> vecCol = new VectorArray<Vec>(new EuclideanDistance()); for(Vec v : simpleSet) vecCol.add(v); for(int numNeighbours = 1; numNeighbours < 100; numNeighbours++) { //get from the midle to avoid more complicated code to hangle edges int randIndex= numNeighbours+rand.nextInt(simpleSet.size()-numNeighbours*2); List<? extends VecPaired<Vec, Double>> found = vecCol.search(simpleSet.get(randIndex), numNeighbours); int min = Math.max(randIndex-(numNeighbours)/2, 0); int max = Math.min(randIndex+(numNeighbours)/2, simpleSet.size()-1); for(Vec v : found) assertTrue(min <= v.get(0) && v.get(0) <= max); assertEquals(numNeighbours, found.size()); } } @Test public void testSearch_Radius_DT() { System.out.println("search_radius_dt"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> A = new VectorArray<>(new EuclideanDistance()); VectorArray<Vec> B = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2500; i++) { A.add(DenseVector.random(3, rand)); B.add(DenseVector.random(3, rand)); } List<List<Integer>> nn_true = new ArrayList<>(); List<List<Double>> dists_true = new ArrayList<>(); double min_radius = 0.1; double max_radius = 0.2; for(int i = 0; i < B.size(); i++) { List<Integer> nn = new IntList(); List<Double> dd = new DoubleList(); A.search(B.get(i), max_radius, nn, dd); //remove everyone that was too close while(!dd.isEmpty() && dd.get(0) < min_radius) { nn.remove(0); dd.remove(0); } nn_true.add(nn); dists_true.add(dd); } for(boolean p : new boolean[]{true, false}) for(VectorCollection<Vec> base : Arrays.asList(new VectorArray<>())) { VectorCollection<Vec> A_dt = base.clone(); VectorCollection<Vec> B_dt = base.clone(); A_dt.build(A); B_dt.build(B); List<List<Integer>> nn_found = new ArrayList<>(); List<List<Double>> dists_found = new ArrayList<>(); A_dt.search(B_dt, min_radius, max_radius, nn_found, dists_found, p); for(int i = 0; i < B.size(); i++) { List<Integer> nn_t = nn_true.get(i); List<Integer> nn_f = nn_found.get(i); List<Double> dd_t = dists_true.get(i); List<Double> dd_f = dists_found.get(i); assertEquals(nn_t.size(), nn_f.size()); assertEquals(dd_t.size(), dd_f.size()); for(int j = 0; j < nn_t.size(); j++) { assertEquals(nn_t.get(j), nn_f.get(j)); assertEquals(dd_t.get(j), dd_f.get(j), 1e-10); } } } } @Test public void testSearch_knn_DT() { System.out.println("search_knn_dt"); Random rand = RandomUtil.getRandom(); VectorArray<Vec> A = new VectorArray<>(new EuclideanDistance()); VectorArray<Vec> B = new VectorArray<>(new EuclideanDistance()); for(int i = 0; i < 2500; i++) { A.add(DenseVector.random(3, rand)); B.add(DenseVector.random(3, rand)); } List<List<Integer>> nn_true = new ArrayList<>(); List<List<Double>> dists_true = new ArrayList<>(); int K = 9; for(int i = 0; i < B.size(); i++) { List<Integer> nn = new IntList(); List<Double> dd = new DoubleList(); A.search(B.get(i), K, nn, dd); nn_true.add(nn); dists_true.add(dd); } for(boolean p : new boolean[]{true, false}) for(VectorCollection<Vec> base : Arrays.asList(new VectorArray<>())) { // System.out.println(base.getClass().getCanonicalName()); VectorCollection<Vec> A_dt = base.clone(); VectorCollection<Vec> B_dt = base.clone(); A_dt.build(A); B_dt.build(B); List<List<Integer>> nn_found = new ArrayList<>(); List<List<Double>> dists_found = new ArrayList<>(); A_dt.search(B_dt, K, nn_found, dists_found, p); for(int i = 0; i < B.size(); i++) { List<Integer> nn_t = nn_true.get(i); List<Integer> nn_f = nn_found.get(i); List<Double> dd_t = dists_true.get(i); List<Double> dd_f = dists_found.get(i); assertEquals(nn_t.size(), nn_f.size()); assertEquals(dd_t.size(), dd_f.size()); for(int j = 0; j < nn_t.size(); j++) { assertEquals(nn_t.get(j), nn_f.get(j)); assertEquals(dd_t.get(j), dd_f.get(j), 1e-10); } } } } }
8,518
29.20922
114
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/lsh/E2LSHTest.java
package jsat.linear.vectorcollection.lsh; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.distancemetrics.EuclideanDistance; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class E2LSHTest { public E2LSHTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of searchR method, of class E2LSH. */ @Test public void testSearchR_Vec() { System.out.println("searchR"); //Test case, create an easy data set of 10 clusters, get all the neighbors for each main cluster //use dimension as the number of clusters and how many poitns are in each cluster int dim = 10; List<Vec> mainVecs = new ArrayList<Vec>(dim); for(int i = 0; i < dim; i++) { DenseVector dv = new DenseVector(dim); dv.set(i, dim*dim); mainVecs.add(dv); } Random rand = RandomUtil.getRandom(); List<Vec> extraVecs = new ArrayList<Vec>(); for(int i = 0; i < mainVecs.size(); i++) { for(int j = 0; j < mainVecs.size(); j++) { DenseVector newVec = new DenseVector(dim); newVec.set(i, dim*dim); for(int k = 0; k < newVec.length(); k++) newVec.increment(k, rand.nextDouble()); extraVecs.add(newVec); } } List<Vec> allVecs = new ArrayList<Vec>(mainVecs); allVecs.addAll(extraVecs); Collections.shuffle(allVecs); E2LSH<Vec> e2lsh = new E2LSH<Vec>(allVecs, dim, 0.1, 4, 5, 0.1, new EuclideanDistance()); for(Vec v : mainVecs) assertEquals(dim+1, e2lsh.searchR(v).size()); } }
2,279
23.516129
104
java
JSAT
JSAT-master/JSAT/test/jsat/linear/vectorcollection/lsh/RandomProjectionLSHTest.java
package jsat.linear.vectorcollection.lsh; import java.util.*; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.linear.VecPaired; import jsat.linear.distancemetrics.CosineDistanceNormalized; import jsat.linear.vectorcollection.VectorArray; import jsat.math.OnLineStatistics; import jsat.utils.IntSet; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RandomProjectionLSHTest { public RandomProjectionLSHTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of search method, of class RandomProjectionLSH. */ @Test public void testSearch_Vec_double() { System.out.println("search"); List<VecPaired<Vec, Integer>> normalVecs = new ArrayList<VecPaired<Vec, Integer>>(); Random rand = RandomUtil.getRandom(); for(int i = 0; i < 100; i++) { DenseVector dv = new DenseVector(20); for(int j = 0; j < dv.length(); j++) dv.set(j, rand.nextGaussian()); dv.normalize(); normalVecs.add(new VecPaired<Vec, Integer>(dv, i)); } CosineDistanceNormalized dm = new CosineDistanceNormalized(); VectorArray<VecPaired<Vec, Integer>> naiveVC = new VectorArray<VecPaired<Vec, Integer>>(dm, normalVecs); RandomProjectionLSH<VecPaired<Vec, Integer>> rpVC = new RandomProjectionLSH<VecPaired<Vec, Integer>>(normalVecs, 16, true); OnLineStatistics knnStats = new OnLineStatistics(); for(Vec v : normalVecs) knnStats.add(naiveVC.search(v, 11).get(10).getPair());//first nn is itselft double searchDist = knnStats.getMean()+knnStats.getStandardDeviation()*2; Set<Integer> inTruth = new IntSet(); for(Vec v : normalVecs)//now use the stats to compare results { List<? extends VecPaired<VecPaired<Vec, Integer>, Double>> trueResults = naiveVC.search(v, searchDist); List<? extends VecPaired<VecPaired<Vec, Integer>, Double>> aprxResults = rpVC.search(v, searchDist); inTruth.clear(); for(VecPaired<VecPaired<Vec, Integer>,Double> vp : trueResults) inTruth.add(vp.getVector().getPair()); int contained = 0; for(VecPaired<VecPaired<Vec, Integer>,Double> vp : aprxResults) if(inTruth.contains(vp.getVector().getPair())) contained++; //Recall must be at least 0.5, should be an easy target assertTrue(contained >= inTruth.size()/2); } } /** * Test of search method, of class RandomProjectionLSH. */ @Test public void testSearch_Vec_int() { System.out.println("search"); List<VecPaired<Vec, Integer>> normalVecs = new ArrayList<VecPaired<Vec, Integer>>(); Random rand = RandomUtil.getRandom(); for(int i = 0; i < 100; i++) { DenseVector dv = new DenseVector(20); for(int j = 0; j < dv.length(); j++) dv.set(j, rand.nextGaussian()); dv.normalize(); normalVecs.add(new VecPaired<Vec, Integer>(dv, i)); } CosineDistanceNormalized dm = new CosineDistanceNormalized(); VectorArray<VecPaired<Vec, Integer>> naiveVC = new VectorArray<VecPaired<Vec, Integer>>(dm, normalVecs); RandomProjectionLSH<VecPaired<Vec, Integer>> rpVC = new RandomProjectionLSH<VecPaired<Vec, Integer>>(normalVecs, 16, true); Set<Integer> inTruth = new IntSet(); for(Vec v : normalVecs)//now use the stats to compare results { List<? extends VecPaired<VecPaired<Vec, Integer>, Double>> trueResults = naiveVC.search(v, 15); List<? extends VecPaired<VecPaired<Vec, Integer>, Double>> aprxResults = rpVC.search(v, 15); inTruth.clear(); for(VecPaired<VecPaired<Vec, Integer>,Double> vp : trueResults) inTruth.add(vp.getVector().getPair()); int contained = 0; for(VecPaired<VecPaired<Vec, Integer>,Double> vp : aprxResults) if(inTruth.contains(vp.getVector().getPair())) contained++; //Recall must be at least 0.5, should be an easy target assertTrue(contained >= inTruth.size()/2); } } }
4,863
31.864865
131
java
JSAT
JSAT-master/JSAT/test/jsat/math/ComplexTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.math; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Edward Raff */ public class ComplexTest { Complex a, b, c, d, aClone, bClone, cClone, dClone; public ComplexTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { a = new Complex(2, 1); aClone = a.clone(); b = new Complex(3, 7); bClone = b.clone(); c = new Complex(9, -4); cClone = c.clone(); d = new Complex(-5, 3); dClone = d.clone(); } @After public void tearDown() { } /** * Test of I method, of class Complex. */ @Test public void testI() { System.out.println("I"); Complex result = Complex.I(); assertEquals(0.0, result.getReal(), 0.0); assertEquals(1.0, result.getImag(), 0.0); } /** * Test of getReal method, of class Complex. */ @Test public void testGetReal() { System.out.println("getReal"); assertEquals(2.0, a.getReal(), 0.0); assertEquals(3.0, b.getReal(), 0.0); assertEquals(9.0, c.getReal(), 0.0); assertEquals(-5.0, d.getReal(), 0.0); } /** * Test of getImag method, of class Complex. */ @Test public void testGetImag() { System.out.println("getImag"); assertEquals(1.0, a.getImag(), 0.0); assertEquals(7.0, b.getImag(), 0.0); assertEquals(-4.0, c.getImag(), 0.0); assertEquals(3.0, d.getImag(), 0.0); } /** * Test of mutableAdd method, of class Complex. */ @Test public void testMutableAdd_double_double() { System.out.println("mutableAdd"); a.mutableAdd(b.getReal(), b.getImag()); assertEquals(new Complex(5, 8), a); assertEquals(new Complex(3, 7), b); c.mutableAdd(d.getReal(), d.getImag()); assertEquals(new Complex(4, -1), c); assertEquals(new Complex(-5, 3), d); } /** * Test of mutableAdd method, of class Complex. */ @Test public void testMutableAdd_Complex() { System.out.println("mutableAdd"); a.mutableAdd(b); assertEquals(new Complex(5, 8), a); assertEquals(new Complex(3, 7), b); c.mutableAdd(d); assertEquals(new Complex(4, -1), c); assertEquals(new Complex(-5, 3), d); } /** * Test of add method, of class Complex. */ @Test public void testAdd() { System.out.println("add"); Complex result = a.add(b); assertEquals(result, new Complex(5, 8)); assertEquals(aClone, a); assertEquals(bClone, b); result = c.add(d); assertEquals(result, new Complex(4, -1)); assertEquals(cClone, c); assertEquals(dClone, d); } /** * Test of mutableSubtract method, of class Complex. */ @Test public void testMutableSubtract_double_double() { System.out.println("mutableSubtract"); a.mutableSubtract(b.getReal(), b.getImag()); assertEquals(new Complex(-1, -6), a); assertEquals(bClone, b); c.mutableSubtract(d.getReal(), d.getImag()); assertEquals(new Complex(14, -7), c); assertEquals(dClone, d); } /** * Test of mutableSubtract method, of class Complex. */ @Test public void testMutableSubtract_Complex() { System.out.println("mutableSubtract"); a.mutableSubtract(b); assertEquals(new Complex(-1, -6), a); assertEquals(bClone, b); c.mutableSubtract(d); assertEquals(new Complex(14, -7), c); assertEquals(dClone, d); } /** * Test of subtract method, of class Complex. */ @Test public void testSubtract() { System.out.println("subtract"); Complex result = a.subtract(b); assertEquals(result, new Complex(-1, -6)); assertEquals(aClone, a); assertEquals(bClone, b); result = c.subtract(d); assertEquals(result, new Complex(14, -7)); assertEquals(cClone, c); assertEquals(dClone, d); } /** * Test of cMul method, of class Complex. */ @Test public void testCMul() { System.out.println("cMul"); double r0 = a.getReal(); double i0 = a.getImag(); double r1 = b.getReal(); double i1 = b.getImag(); double[] results = new double[2]; Complex.cMul(r0, i0, r1, i1, results); assertEquals(-1.0, results[0], 0.0); assertEquals(17.0, results[1], 0.0); } /** * Test of mutableMultiply method, of class Complex. */ @Test public void testMutableMultiply_double_double() { System.out.println("mutableMultiply"); a.mutableMultiply(b.getReal(), b.getImag()); assertEquals(new Complex(-1, 17), a); assertEquals(bClone, b); c.mutableMultiply(d.getReal(), d.getImag()); assertEquals(new Complex(-33, 47), c); assertEquals(dClone, d); } /** * Test of mutableMultiply method, of class Complex. */ @Test public void testMutableMultiply_Complex() { System.out.println("mutableMultiply"); a.mutableMultiply(b); assertEquals(new Complex(-1, 17), a); assertEquals(bClone, b); c.mutableMultiply(d); assertEquals(new Complex(-33, 47), c); assertEquals(dClone, d); } /** * Test of multiply method, of class Complex. */ @Test public void testMultiply() { System.out.println("multiply"); Complex result = a.multiply(b); assertEquals(result, new Complex(-1, 17)); assertEquals(aClone, a); assertEquals(bClone, b); result = c.multiply(d); assertEquals(result, new Complex(-33, 47)); assertEquals(cClone, c); assertEquals(dClone, d); } /** * Test of cDiv method, of class Complex. */ @Test public void testCDiv() { System.out.println("cDiv"); double r0 = a.getReal(); double i0 = a.getImag(); double r1 = b.getReal(); double i1 = b.getImag(); double[] results = new double[2]; Complex.cDiv(r0, i0, r1, i1, results); assertEquals( 0.224137931034483, results[0], 1e-14); assertEquals(-0.189655172413793, results[1], 1e-14); } /** * Test of mutableDivide method, of class Complex. */ @Test public void testMutableDivide_double_double() { System.out.println("mutableDivide"); a.mutableDivide(b.getReal(), b.getImag()); assertTrue(a.equals(new Complex(0.224137931034483, -0.189655172413793), 1e-14)); assertEquals(bClone, b); c.mutableDivide(d.getReal(), d.getImag()); assertTrue(c.equals(new Complex(-1.67647058823529, -0.205882352941176), 1e-14)); assertEquals(dClone, d); } /** * Test of mutableDivide method, of class Complex. */ @Test public void testMutableDivide_Complex() { System.out.println("mutableDivide"); a.mutableDivide(b); assertTrue(a.equals(new Complex(0.224137931034483, -0.189655172413793), 1e-14)); assertEquals(bClone, b); c.mutableDivide(d); assertTrue(c.equals(new Complex(-1.67647058823529, -0.205882352941176), 1e-14)); assertEquals(dClone, d); } /** * Test of divide method, of class Complex. */ @Test public void testDivide() { System.out.println("divide"); Complex result = a.divide(b); assertTrue(result.equals(new Complex(0.224137931034483, -0.189655172413793), 1e-14)); assertEquals(aClone, a); assertEquals(bClone, b); result = c.divide(d); assertTrue(result.equals(new Complex(-1.67647058823529, -0.205882352941176), 1e-14)); assertEquals(cClone, c); assertEquals(dClone, d); } /** * Test of getMagnitude method, of class Complex. */ @Test public void testGetMagnitude() { System.out.println("getMagnitude"); assertEquals(2.23606797749979, a.getMagnitude(), 1e-14); assertEquals(7.61577310586391, b.getMagnitude(), 1e-14); assertEquals(9.8488578017961, c.getMagnitude(), 1e-14); assertEquals(5.8309518948453, d.getMagnitude(), 1e-14); } /** * Test of getArg method, of class Complex. */ @Test public void testGetArg() { System.out.println("getArg"); assertEquals(0.463647609000806, a.getArg(), 1e-14); assertEquals(1.16590454050981, b.getArg(), 1e-14); assertEquals(-0.418224329579229, c.getArg(), 1e-14); assertEquals(2.60117315331921, d.getArg(), 1e-14); } /** * Test of mutateConjugate method, of class Complex. */ @Test public void testMutateConjugate() { System.out.println("mutateConjugate"); a.mutateConjugate(); assertEquals(new Complex(aClone.getReal(), -aClone.getImag()), a); c.mutateConjugate(); assertEquals(new Complex(cClone.getReal(), -cClone.getImag()), c); d.mutateConjugate(); assertEquals(new Complex(dClone.getReal(), -dClone.getImag()), d); } /** * Test of getConjugate method, of class Complex. */ @Test public void testGetConjugate() { System.out.println("getConjugate"); Complex result = a.getConjugate(); assertEquals(aClone, a); assertEquals(new Complex(aClone.getReal(), -aClone.getImag()), result); result = c.getConjugate(); assertEquals(bClone, b); assertEquals(new Complex(cClone.getReal(), -cClone.getImag()), result); result = d.getConjugate(); assertEquals(bClone, b); assertEquals(new Complex(dClone.getReal(), -dClone.getImag()), result); } /** * Test of clone method, of class Complex. */ @Test public void testClone() { System.out.println("clone"); Complex clone = a.clone(); assertEquals(aClone, a); assertEquals(aClone, clone); clone.setReal(100); assertEquals(aClone, a); assertTrue(!clone.equals(aClone)); } }
10,705
26.172589
93
java
JSAT
JSAT-master/JSAT/test/jsat/math/ExponentialMovingStatisticsTest.java
/* * Copyright (C) 2016 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math; import java.util.ArrayList; import java.util.List; import java.util.Random; import jsat.distributions.*; import jsat.linear.Vec; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class ExponentialMovingStatisticsTest { private List<ContinuousDistribution> distributions; public ExponentialMovingStatisticsTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { //EMA has difficulty with values centered about 0 and symetric distributoins distributions = new ArrayList<ContinuousDistribution>(); distributions.add(new Normal(5, 1)); distributions.add(new Normal(3, 7)); distributions.add(new Normal(40, 7)); distributions.add(new Exponential(0.1)); distributions.add(new LogUniform(1, 100)); distributions.add(new Uniform(-10, 10)); } @After public void tearDown() { } /** * Test of setSmoothing method, of class ExponentialMovingStatistics. */ @Test public void testSetSmoothing() { System.out.println("setSmoothing"); Random rand = RandomUtil.getRandom(); for (ContinuousDistribution dist : distributions) { double smoothing = 0.01; ExponentialMovingStatistics instance = new ExponentialMovingStatistics(smoothing); Vec values = dist.sampleVec(100000, rand); for (double x : values.arrayCopy()) instance.add(x); // System.out.println(dist.toString()); // System.out.println(dist.mean() + " " + instance.getMean() + " " + smoothing); // System.out.println(dist.standardDeviation() + " " + instance.getStandardDeviation() + " " + smoothing); assertEquals(dist.mean(), instance.getMean(), Math.max(dist.mean() * 0.75, 3.5)); assertEquals(dist.standardDeviation(), instance.getStandardDeviation(), Math.max(dist.mean() * 0.75, 1.5)); } } @Test public void testSetSmoothingDrifted() { System.out.println("setSmoothing Drift"); Random rand = RandomUtil.getRandom(); for (ContinuousDistribution other_dist : distributions) for (ContinuousDistribution dist : distributions) { if(other_dist == dist) continue; double smoothing = 0.01; ExponentialMovingStatistics instance = new ExponentialMovingStatistics(smoothing); //these first onces should eventually be forgoten for (double x : other_dist.sample(100000, rand)) instance.add(x); for (double x : dist.sample(100000, rand)) instance.add(x); // System.out.println(dist.toString()); // System.out.println(dist.mean() + " " + instance.getMean() + " " + smoothing); // System.out.println(dist.standardDeviation() + " " + instance.getStandardDeviation() + " " + smoothing); assertEquals(dist.mean(), instance.getMean(), Math.max(dist.mean() * 0.75, 3.5)); assertEquals(dist.standardDeviation(), instance.getStandardDeviation(), Math.max(dist.mean() * 0.75, 1.5)); } } }
4,397
32.572519
123
java
JSAT
JSAT-master/JSAT/test/jsat/math/FastMathTest.java
package jsat.math; import java.util.Collections; import java.util.Random; import jsat.utils.DoubleList; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class FastMathTest { Random rand; public FastMathTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { rand = RandomUtil.getRandom(); } @After public void tearDown() { } public static double relErr(double expected, double actual) { return Math.abs((expected-actual)/expected); } /** * Test of log2 method, of class FastMath. */ @Test public void testLog2() { System.out.println("log2"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*1000; relErrs.add(relErr(Math.log(x)/Math.log(2), FastMath.log2(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } /** * Test of log2_2pd1 method, of class FastMath. */ @Test public void testLog2_2pd1() { System.out.println("log2_2pd1"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*1000; relErrs.add(relErr(Math.log(x)/Math.log(2), FastMath.log2_2pd1(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } /** * Test of log2_c11 method, of class FastMath. */ @Test public void testLog2_c11() { System.out.println("log2_c11"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*1000; relErrs.add(relErr(Math.log(x)/Math.log(2), FastMath.log2_c11(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } /** * Test of pow2 method, of class FastMath. */ @Test public void testPow2_int() { System.out.println("pow2"); for(int i = 0; i < 20; i++) assertEquals(Math.pow(2,i), FastMath.pow2(i), 0.0);//docs say it must be exact } /** * Test of pow2 method, of class FastMath. */ @Test public void testPow2_double() { System.out.println("pow2"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*20; relErrs.add(relErr(Math.pow(2, x), FastMath.pow2(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } /** * Test of pow method, of class FastMath. */ @Test public void testPow() { System.out.println("pow"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*20; double y = rand.nextDouble()*20; relErrs.add(relErr(Math.pow(y, x), FastMath.pow(y, x))); } Collections.sort(relErrs); //most should have lowwer rel error for best cases assertTrue(relErrs.get((int) (trials*.10)) <= 1e-4);//usually does better than this assertTrue(relErrs.get((int) (trials*.50)) <= 1e-3); assertTrue(relErrs.get((int) (trials*.75)) <= 1e-2); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-1); } /** * Test of log method, of class FastMath. */ @Test public void testLog() { System.out.println("log"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*20+1e-15; relErrs.add(relErr(Math.log(x), FastMath.log(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } /** * Test of exp method, of class FastMath. */ @Test public void testExp() { System.out.println("exp"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*50-25; relErrs.add(relErr(Math.exp(x), FastMath.exp(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } /** * Test of digamma method, of class FastMath. */ @Test public void testDigamma() { System.out.println("digamma"); DoubleList relErrs = new DoubleList(); int trials = 10000; for(int i = 0; i < trials; i++) { double x = rand.nextDouble()*50; relErrs.add(relErr(SpecialMath.digamma(x), FastMath.digamma(x))); } Collections.sort(relErrs); assertTrue(relErrs.get((int) (trials*.95)) <= 1e-3); } }
5,521
24.803738
91
java
JSAT
JSAT-master/JSAT/test/jsat/math/FunctionTest.java
/* * Copyright (C) 2018 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author edwardraff */ public class FunctionTest { public FunctionTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of forwardDifference method, of class Function. */ @Test public void testForwardDifference() { System.out.println("forwardDifference"); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec trueDeriv = f.getDerivative(); FunctionVec approxDeriv = Function.forwardDifference(f); Random rand = RandomUtil.getRandom(); for(int d = 2; d < 10; d++) for(int iter = 0; iter < 100; iter++) { Vec x = new DenseVector(d); for(int i = 0; i < x.length(); i++) x.set(i, rand.nextDouble()*2-1); Vec trueD = trueDeriv.f(x); Vec approxD = approxDeriv.f(x); assertTrue(trueD.equals(approxD, 1e-1)); } } }
2,258
25.576471
72
java
JSAT
JSAT-master/JSAT/test/jsat/math/MathTricksTest.java
package jsat.math; import java.util.Arrays; import jsat.linear.DenseVector; import jsat.linear.Vec; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MathTricksTest { public MathTricksTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of logSumExp method, of class MathTricks. */ @Test public void testLogSumExp_Vec_double() { System.out.println("logSumExp"); Vec vals = DenseVector.toDenseVec(10, 10, 3, -20, 1); double maxValue = 10.0; double expResult = 10.693664692512399350; double result = MathTricks.logSumExp(vals, maxValue); assertEquals(expResult, result, 1e-15); } /** * Test of logSumExp method, of class MathTricks. */ @Test public void testLogSumExp_doubleArr_double() { System.out.println("logSumExp"); double[] vals = new double[] {10, 10, 3, -20, 1}; double maxValue = 10.0; double expResult = 10.693664692512399350; double result = MathTricks.logSumExp(vals, maxValue); assertEquals(expResult, result, 1e-15); } /** * Test of softmax method, of class MathTricks. */ @Test public void testSoftmax_doubleArr_boolean() { System.out.println("softmax"); double[] x = new double[]{3, 1, 2}; double[] x2 = Arrays.copyOf(x, x.length); double[] xExpected = new double[]{0.6652409557748218895, 0.090030573170380457998, 0.24472847105479765}; double[] x2Expected = new double[]{0.64391425988797231, 0.087144318742032567489, 0.23688281808991013}; MathTricks.softmax(x, false); for(int i = 0; i < x.length; i++) assertEquals(xExpected[i], x[i], 1e-15); MathTricks.softmax(x2, true); for(int i = 0; i < x2.length; i++) assertEquals(x2Expected[i], x2[i], 1e-15); } /** * Test of softmax method, of class MathTricks. */ @Test public void testSoftmax_Vec_boolean() { System.out.println("softmax"); Vec x = new DenseVector(new double[]{3, 1, 2}); Vec x2 = x.clone(); Vec xExpected = new DenseVector(new double[]{0.6652409557748218895, 0.090030573170380457998, 0.24472847105479765}); Vec x2Expected = new DenseVector(new double[]{0.64391425988797231, 0.087144318742032567489, 0.23688281808991013}); MathTricks.softmax(x, false); for(int i = 0; i < x.length(); i++) assertEquals(xExpected.get(i), x.get(i), 1e-15); MathTricks.softmax(x2, true); for(int i = 0; i < x2.length(); i++) assertEquals(x2Expected.get(i), x2.get(i), 1e-15); } /** * Test of hornerPolyR method, of class MathTricks. */ @Test public void testHornerPolyR() { System.out.println("hornerPolyR"); double[] coef = new double[]{1, -4, 0, 8, 1}; assertEquals(1, MathTricks.hornerPolyR(coef, 0), 1e-15); assertEquals(6, MathTricks.hornerPolyR(coef, 1), 1e-15); assertEquals(481, MathTricks.hornerPolyR(coef, 6), 1e-15); assertEquals(2113, MathTricks.hornerPolyR(coef, -6), 1e-15); } /** * Test of hornerPoly method, of class MathTricks. */ @Test public void testHornerPoly() { System.out.println("hornerPoly"); double[] coef = new double[]{1, 8, 0, -4, 1}; assertEquals(1, MathTricks.hornerPoly(coef, 0), 1e-15); assertEquals(6, MathTricks.hornerPoly(coef, 1), 1e-15); assertEquals(481, MathTricks.hornerPoly(coef, 6), 1e-15); assertEquals(2113, MathTricks.hornerPoly(coef, -6), 1e-15); } }
4,080
27.144828
123
java
JSAT
JSAT-master/JSAT/test/jsat/math/OnLineStatisticsTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.math; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class OnLineStatisticsTest { private final double[] data = new double[] { 1.43725, 3.57142, 1.02601, 0.962941, 2.35466, 2.28253, 1.71812, 2.92907, 0.707891, 0.0136063, 2.9936, 2.06371, 0.274257, 0.23791, 0.0649932, 0.454671, 5.0087, 1.08846, 3.67667, 3.03826 }; private final double mean = 1.795236475; private final double variance = 1.885715208339471;//population variance private final double skewness = 0.5329150349287533; private final double kurt = -0.5903068502891378; private final double min = 0.0136063; private final double max = 5.0087; public OnLineStatisticsTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of add method, of class OnLineStatistics. */ @Test public void testAdd_double() { System.out.println("add(double)"); OnLineStatistics stats = new OnLineStatistics(); for(double x : data) stats.add(x); assertEquals(mean, stats.getMean(), 1e-8); assertEquals(variance, stats.getVarance(), 1e-8); assertEquals(skewness, stats.getSkewness(), 1e-8); assertEquals(kurt, stats.getKurtosis(), 1e-8); assertEquals(max, stats.getMax(), 1e-8); assertEquals(min, stats.getMin(), 1e-8); } @Test public void testAdd_double_double() { System.out.println("add(double, double)"); OnLineStatistics stats = new OnLineStatistics(); stats.add(10, 10); stats.add(100,1); assertEquals(200.0/11.0, stats.getMean(), 1e-10); assertEquals(81000.0/121.0, stats.getVarance(), 1e-10); assertEquals(9.0/Math.sqrt(10), stats.getSkewness(), 1e-10); assertEquals(91.0/10.0-3.0, stats.getKurtosis(), 1e-10); assertEquals(10, stats.getMin(), 0.0); assertEquals(100, stats.getMax(), 0.0); } /** * Test of add method, of class OnLineStatistics. */ @Test public void testRemove_OnLineStatistics_OnLineStatistics() { System.out.println("remove"); for(int j = 1; j < data.length-1; j++) { OnLineStatistics total = new OnLineStatistics(); OnLineStatistics A = new OnLineStatistics(); OnLineStatistics B = new OnLineStatistics(); for(int i = 0; i < data.length; i++) { total.add(data[i]); if( i < j) A.add(data[i]); else B.add(data[i]); } OnLineStatistics stats = OnLineStatistics.remove(total, B); assertEquals(A.getSumOfWeights(), stats.getSumOfWeights(), 1e-8); assertEquals(A.getMean(), stats.getMean(), 1e-8); if(!Double.isNaN(A.getVarance())) assertEquals(A.getVarance(), stats.getVarance(), 1e-8); //skewness and kurtosis aren't stable any more //min & max are not possible stats = OnLineStatistics.remove(total, A); assertEquals(B.getSumOfWeights(), stats.getSumOfWeights(), 1e-8); assertEquals(B.getMean(), stats.getMean(), 1e-8); if(!Double.isNaN(B.getVarance())) assertEquals(B.getVarance(), stats.getVarance(), 1e-8); } } @Test public void testAdd_OnLineStatistics_OnLineStatistics() { System.out.println("add"); for(int j = 1; j < data.length-1; j++) { OnLineStatistics A = new OnLineStatistics(); OnLineStatistics B = new OnLineStatistics(); for(int i = 0; i < data.length; i++) { if( i < j) A.add(data[i]); else B.add(data[i]); } OnLineStatistics stats = OnLineStatistics.add(A, B); assertEquals(mean, stats.getMean(), 1e-8); assertEquals(variance, stats.getVarance(), 1e-8); assertEquals(skewness, stats.getSkewness(), 1e-8); assertEquals(kurt, stats.getKurtosis(), 1e-1);//The kurtois is not numerically stable in this situation assertEquals(max, stats.getMax(), 1e-8); assertEquals(min, stats.getMin(), 1e-8); } } }
4,839
30.842105
115
java
JSAT
JSAT-master/JSAT/test/jsat/math/SpecialMathTest.java
package jsat.math; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SpecialMathTest { public SpecialMathTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of digamma method, of class SpecialMath. */ @Test public void testZeta() { System.out.println("zeta"); //Values in this range have crappy accuracy... sad panda double[] inputNW = new double[] { -10.5, -2, -1.5, }; double[] expectedNW = new double[] { 0.01114612247394282,0.,-0.02548520188983304, }; for(int i = 0; i < inputNW.length; i++) { assertEquals(expectedNW[i], SpecialMath.zeta(inputNW[i]), 1e-01); } //Decent double[] input = new double[] { -0.5, 0.2, 0.5, 0.9, 1.1, 1.3, 2, }; double[] expected = new double[] { -0.2078862249773546,-0.7339209248963376,-1.460354508809586, -9.43011401940225,10.5844484649508,3.931949211809544, 1.644934066848226 }; for(int i = 0; i < input.length; i++) { assertEquals(expected[i], SpecialMath.zeta(input[i]), 1e-5); } //Very good double[] inputVG = new double[] { 2.6, 10.4, 15, 20, 40.0, 60 }; double[] expectedVG = new double[] { 1.305477809072781,1.000751620674465,1.000030588236307, 1.000000953962033,1.00000000000091,0.999999999999997 }; for(int i = 0; i < expectedVG.length; i++) { assertEquals(expectedVG[i], SpecialMath.zeta(inputVG[i]), 1e-14); } } @Test public void testHurwitzZeta() { System.out.println("HurwitzZeta"); double[] qs = new double[]{0.1,0.5,1.0, 2.0, 5.0, 10.0, 100.0, 10000.0,100000000.0}; Map<Double, double[]> map = new HashMap<>(); map.put(0.01, new double[]{0.4135031309122915871814466,-0.003542397054926171240976755,-0.5092907140398399251076769,-1.509290714039839925107677,-4.477689918142405712644403,-9.382383020520118632585454,-95.98639332666748108896203,-9211.774695069066011783676,-8.401654211974144839796459e7}); map.put(0.1, new double[]{0.5508589422893526431278708,-0.04328209083938110987506565,-0.6030375198562417152484319,-1.603037519856241715248432,-4.302579534529935464893352,-8.428043471238167390580088,-69.79084035709398376328899,-4423.213952232936729043897,-1.760992428143437908820468e7}); map.put(0.5, new double[]{1.576009382524539159782465,-0.6048986434216303702472659,-1.460354508809586812889499,-2.460354508809586812889499,-4.244811559185760101799492,-6.165124642085415380195813,-19.94995833359374023524766,-199.9949999583333333593750,-19999.99994999999995833333}); map.put(1.01, new double[]{110.6568481839125712993911,101.9770931774823586151860,100.5779433384968724902822,99.57794333849687249028215,98.50514757993095784192333,97.77340563917338495320170,95.50404160284692200556433,91.20112953690055112993359,83.17637711442591947918317}); map.put(1.1, new double[]{23.01457794082749630826599,12.10381349568375510570908,10.58444846495080982638640,9.584448464950809826386401,8.601641508411454352102559,7.983726107059952909313114,6.312734015237240353721934,3.981091611258431755176483,1.584893193253560082885477}); map.put(2.1, new double[]{127.2351760461769027201376,5.128578172173721239121165,1.560216533503362083710517,0.5602165335033620837105168,0.1729979354308455605161300,0.07632201400329205588192001,0.005767634141331303191670303,0.00003619355156493036316464807,1.440812001070932794770381e-9}); map.put(5.1, new double[]{125893.1832634196823843001,34.43501603285013348978806,1.034185474687489623326334,0.03418547468748962332633402,0.0004909748162989681064386678,0.00002368069483671087773852296,1.570736357133068259385718e-9,9.711921694158002793357229e-18,3.865593231588839528835528e-34}); map.put(10.1, new double[]{1.258925411832412651236312e10,1097.512777261824570339265,1.000927273424515647245772,0.0009272734245156472457716332,1.050368145259780612947234e-7,1.335473778753137763579056e-10,7.254385233733663310412230e-20,4.376794942942748506660889e-38,1.741640950081049402284479e-74}); map.put(100.1, new double[]{1.258925411794167210423954e100,1.358634273092819767285223e30,1.000000000000000000000000,7.360332503047945466884606e-31,1.079201576577305340846106e-70,7.943853383747731139721367e-101,1.003915595723878904182365e-200,0.0,0.0}); map.put(-1., new double[]{-0.03833333333333333333333333,0.04166666666666666666666667,-0.08333333333333333333333333,-1.083333333333333333333333,-10.08333333333333333333333,-45.08333333333333333333333,-4950.083333333333333333333,-4.999500008333333333333333e7,-4.999999950000000083333333e15}); map.put(-2., new double[]{-0.01200000000000000000000000,0,0,-1.000000000000000000000000,-30.00000000000000000000000,-285.0000000000000000000000,-328350.0000000000000000000,-3.332833350000000000000000e11,-3.333333283333333500000000e23}); map.put(-5., new double[]{-0.003171753968253968253968254,0.003844246031746031746031746,-0.003968253968253968253968254,-1.003968253968253968253968,-1300.003968253968253968254,-120825.0039682539682539683,-1.617083325000039682539683e11,-1.666166708333333250000000e23,-1.666666616666667083333333e47}); for(Map.Entry<Double, double[]> entry : map.entrySet()) { double x = entry.getKey(); // System.out.println("x=" + x); for(int i = 0; i < qs.length; i++) { double q = qs[i]; double expected = entry.getValue()[i]; double actual = SpecialMath.zeta(x, q); double err; if(Math.abs(expected) > 0.1) err = Math.abs((expected-actual)/expected);//relative error else//absolute error err = Math.abs(expected-actual); // System.out.println("\t" + err); if(x > 0) assertEquals("Failed on zeta(" + x + "," + q + ")", 0, err, 1e-3); else assertEquals("Failed on zeta(" + x + "," + q + ")", 0, err, 1e-1); } } } @Test public void testHarmonic() { System.out.println("generalized harmonic"); long[] ms = new long[]{0, 1, 2, 5, 10, 100, 1000}; Map<Long, double[]> map = new HashMap<>(); // map.put(0L, new double[]{0,0,0,0,0,0,0}); map.put(1L, new double[]{1.000000000000000000000000,1.000000000000000000000000,1.000000000000000000000000,1.000000000000000000000000,1.000000000000000000000000,1.000000000000000000000000,1.000000000000000000000000}); map.put(2l, new double[]{2.000000000000000000000000,1.500000000000000000000000,1.250000000000000000000000,1.031250000000000000000000,1.000976562500000000000000,1.000000000000000000000000,1.000000000000000000000000}); map.put(3l, new double[]{3.000000000000000000000000,1.833333333333333333333333,1.361111111111111111111111,1.035365226337448559670782,1.000993497587808430286711,1.000000000000000000000000,1.000000000000000000000000}); map.put(5l, new double[]{5.000000000000000000000000,2.283333333333333333333333,1.463611111111111111111111,1.036661788837448559670782,1.000994553662124836536711,1.000000000000000000000000,1.000000000000000000000000}); map.put(10l, new double[]{10.00000000000000000000000,2.928968253968253968253968,1.549767731166540690350214,1.036907341344693456054928,1.000994575058549472793071,1.000000000000000000000000,1.000000000000000000000000}); map.put(100l, new double[]{100.0000000000000000000000,5.187377517639620260805118,1.634983900184892865077169,1.036927752692953288826367,1.000994575127818085230952,1.000000000000000000000000,1.000000000000000000000000}); map.put(1000l, new double[]{1000.000000000000000000000,7.485470860550344912656518,1.643934566681559803139058,1.036927755143120425914699,1.000994575127818085337146,1.000000000000000000000000,1.000000000000000000000000}); map.put(10000l, new double[]{10000.00000000000000000000,9.787606036044382264178478,1.644834071848059769806082,1.036927755143369901336365,1.000994575127818085337146,1.000000000000000000000000,1.000000000000000000000000}); // for(Map.Entry<Long, double[]> entry : map.entrySet()) { long n = entry.getKey(); // System.out.println("n=" + n); for(int i = 0; i < ms.length; i++) { long m = ms[i]; double expected = entry.getValue()[i]; double actual = SpecialMath.harmonic(n, m); double err; if(expected > 0) err = Math.abs((expected-actual)/expected);//relative error else//absolute error err = Math.abs(expected-actual); // System.out.println("\t" + err); assertEquals(0, err, 1e-5); } } } /** * Test of digamma method, of class SpecialMath. */ @Test public void testDigamma() { System.out.println("digamma"); double[] input = new double[] { -77.5, -1.5, 1, 1.4, 2, 5, 6, 9, 20, 100 }; double[] expected = new double[] { 4.356715675057194,0.7031566406452434,-0.5772156649015328, -0.0613845445851161,0.4227843350984672,1.506117668431801, 1.7061176684318,2.14064147795561,2.97052399224215,4.600161852738087 }; for(int i = 0; i < input.length; i++) assertEquals(expected[i], SpecialMath.digamma(input[i]), 1e-14); } /** * Test of reLnBn method, of class SpecialMath. */ @Test public void testReLnBn() { System.out.println("reLnBn"); int[] input = new int[] { 0, 1, 2, 3, 4, 5, 6, 10, 40, 50, 70, 100 }; double[] expected = new double[] { 0.,-0.6931471805599453,-1.791759469228055,Double.NEGATIVE_INFINITY, -3.401197381662155,Double.NEGATIVE_INFINITY,-3.737669618283368, -2.580216829592325,37.49870423894444,57.2770608118657, 102.4807960976827,180.6448160951889 }; for(int i = 0; i < input.length; i++) assertEquals(expected[i], SpecialMath.reLnBn(input[i]), 1e-11); } /** * Test of bernoulli method, of class SpecialMath. */ @Test public void testBernoulli() { System.out.println("bernoulli"); int[] input = new int[] { 0, 1, 2, 3, 4, 5, 6, 10, 14, 20 }; double[] expected = new double[] { 1.,-0.5,0.1666666666666667,0.,-0.03333333333333333,0., 0.02380952380952381,0.07575757575757576,1.166666666666667, -529.1242424242425 }; for(int i = 0; i < input.length; i++) assertEquals(expected[i], SpecialMath.bernoulli(input[i]), 1e-11); } }
11,747
44.184615
306
java
JSAT
JSAT-master/JSAT/test/jsat/math/integration/AdaptiveSimpsonTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.integration; import jsat.math.Function1D; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class AdaptiveSimpsonTest { public AdaptiveSimpsonTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of integrate method, of class AdaptiveSimpson. */ @Test public void testIntegrate() { System.out.println("integrate"); double tol = 1e-10; double expect, result; result = AdaptiveSimpson.integrate((x)->Math.sin(x), tol, -1, Math.PI); expect = 1.5403023058681397174; assertEquals(expect, result, tol); result = AdaptiveSimpson.integrate((x)->x*Math.exp(-x), tol, -1, 5); expect = -0.040427681994512802580; assertEquals(expect, result, tol); result = AdaptiveSimpson.integrate((x)->Math.log(x), tol, 0.1, 50); expect = 145.93140878070670750; assertEquals(expect, result, tol); } }
2,110
23.835294
79
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/BFGSTest.java
package jsat.math.optimization; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class BFGSTest { public BFGSTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of optimize method, of class BFGS. */ @Test public void testOptimize() { System.out.println("optimize"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(3);//D=3 means one local minima for easy evaluation for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()+0.5);//make sure we get to the right local optima RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); BFGS instance = new BFGS(); for(LineSearch lineSearch : new LineSearch[]{new BacktrackingArmijoLineSearch(), new WolfeNWLineSearch()}) { instance.setLineSearch(lineSearch); Vec w = new DenseVector(x0.length()); instance.optimize(1e-4, w, x0, f, fp); for(int i = 0; i <w.length(); i++) assertEquals(1.0, w.get(i), 1e-4); assertEquals(0.0, f.f(w), 1e-4); } } }
1,694
21.905405
114
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/LBFGSTest.java
package jsat.math.optimization; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LBFGSTest { public LBFGSTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of optimize method, of class LBFGS. */ @Test public void testOptimize() { System.out.println("optimize"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(3);//D=3 means one local minima for easy evaluation for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()+0.5);//make sure we get to the right local optima RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); LBFGS instance = new LBFGS(); for(LineSearch lineSearch : new LineSearch[]{new BacktrackingArmijoLineSearch(), new WolfeNWLineSearch()}) { instance.setLineSearch(lineSearch); Vec w = new DenseVector(x0.length()); instance.optimize(1e-5, w, x0, f, fp); for(int i = 0; i <w.length(); i++) assertEquals(1.0, w.get(i), 1e-3); assertEquals(0.0, f.f(w), 1e-4); } } }
1,699
21.972973
114
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/ModifiedOWLQNTest.java
package jsat.math.optimization; import java.util.Random; import java.util.concurrent.ExecutorService; import jsat.classifiers.CategoricalData; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.DataPoint; import jsat.classifiers.linear.LinearTools; import jsat.linear.DenseVector; import jsat.linear.IndexValue; import jsat.linear.Vec; import jsat.lossfunctions.LossFunc; import jsat.lossfunctions.SoftmaxLoss; import jsat.math.Function; import jsat.math.FunctionVec; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ModifiedOWLQNTest { public ModifiedOWLQNTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of optimize method, of class mOWLQN. */ @Test public void testOptimize() { System.out.println("optimize"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(3);//D=3 means one local minima for easy evaluation for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()+0.5); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); ModifiedOWLQN instance = new ModifiedOWLQN(); instance.setLambda(0.0); instance.setMaximumIterations(500); Vec w = new DenseVector(x0.length()); instance.optimize(1e-8, w, x0, f, fp); for (int i = 0; i < w.length(); i++) assertEquals(1.0, w.get(i), 1e-2); assertEquals(0.0, f.f(w), 1e-3); } @Test public void testOptimizeGDsteps() { System.out.println("optimize"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(3);//D=3 means one local minima for easy evaluation for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()+0.5); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); ModifiedOWLQN instance = new ModifiedOWLQN(); instance.setLambda(0.0); instance.setEps(Double.MAX_VALUE); instance.setMaximumIterations(2000); Vec w = new DenseVector(x0.length()); instance.optimize(1e-4, w, x0, f, fp); for (int i = 0; i < w.length(); i++) assertEquals(1.0, w.get(i), 0.5); assertEquals(0.0, f.f(w), 1e-1); } @Test public void testOptimizeReg() { System.out.println("optimize"); Random rand = RandomUtil.getRandom(); ClassificationDataSet data = new ClassificationDataSet(6, new CategoricalData[0], new CategoricalData(2)); for(int i = 0; i < 1000; i++) { double Z1 = rand.nextDouble()*20-10; double Z2 = rand.nextDouble()*20-10; Vec v = DenseVector.toDenseVec( Z1 + rand.nextGaussian()/10, -Z1 + rand.nextGaussian()/10, Z1+ rand.nextGaussian()/10, -Z2+ rand.nextGaussian()/10, Z2+ rand.nextGaussian()/10, -Z2+ rand.nextGaussian()/10); data.addDataPoint(v, (int) (Math.signum(Z1+0.1*Z2)+1)/2); } Vec x0 = new DenseVector(data.getNumNumericalVars()); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()*2-1); double lambda = LinearTools.maxLambdaLogisticL1(data); Function f = new LossFunction(data, new SoftmaxLoss()); FunctionVec fp = new GradFunction(data, new SoftmaxLoss()); ModifiedOWLQN instance = new ModifiedOWLQN(); instance.setLambda(lambda/2); instance.setMaximumIterations(500); Vec w = new DenseVector(x0.length()); instance.optimize(1e-4, w, x0, f, fp); assertTrue(w.nnz() <= 3); for(IndexValue iv : w) { assertTrue(iv.getIndex() < 3); if(iv.getIndex() % 2 == 0) assertTrue(iv.getValue() > 0); else assertTrue(iv.getValue() < 0); } //do it again, but don't regularize one value instance.setLambdaMultipler(DenseVector.toDenseVec(1, 1, 1, 1, 0, 1)); x0.zeroOut(); instance = instance.clone(); instance.optimize(1e-4, w, x0, f, fp); assertTrue(w.nnz() <= 4); for(IndexValue iv : w) { if(iv.getIndex() % 2 == 0) assertTrue(iv.getValue() > 0); else assertTrue(iv.getValue() < 0); } assertEquals(0.0, w.get(5), 0.0); assertEquals(0.0, w.get(3), 0.0); assertTrue(w.get(4) > 0); } public class LossFunction implements Function { private final ClassificationDataSet D; private final LossFunc loss; public LossFunction(ClassificationDataSet D, LossFunc loss) { this.D = D; this.loss = loss; } @Override public double f(Vec w, boolean parallel) { double sum = 0; double weightSum = 0; for (int i = 0; i < D.size(); i++) { DataPoint dp = D.getDataPoint(i); Vec x = dp.getNumericalValues(); double y = D.getDataPointCategory(i) * 2 - 1; sum += loss.getLoss(w.dot(x), y) * D.getWeight(i); weightSum += D.getWeight(i); } return sum / weightSum; } } public class GradFunction implements FunctionVec { private final ClassificationDataSet D; private final LossFunc loss; public GradFunction(ClassificationDataSet D, LossFunc loss) { this.D = D; this.loss = loss; } @Override public Vec f(Vec w, Vec s, boolean parallel) { if (s == null) s = w.clone(); s.zeroOut(); double weightSum = 0; for (int i = 0; i < D.size(); i++) { DataPoint dp = D.getDataPoint(i); Vec x = dp.getNumericalValues(); double y = D.getDataPointCategory(i) * 2 - 1; s.mutableAdd(loss.getDeriv(w.dot(x), y) * D.getWeight(i), x); weightSum += D.getWeight(i); } s.mutableDivide(weightSum); return s; } } }
6,912
27.566116
114
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/NelderMeadTest.java
package jsat.math.optimization; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import jsat.linear.DenseVector; import jsat.linear.Vec; import jsat.math.Function; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NelderMeadTest { public NelderMeadTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of optimize method, of class NelderMead. */ @Test public void testOptimize_8args() { System.out.println("optimize"); NelderMead instance = new NelderMead(); Function banana = new RosenbrockFunction(); DenseVector search = DenseVector.toDenseVec(1.05, 0.95, 1.05); Vec x = instance.optimize(1e-6, 1000, banana, Arrays.asList(search), true); assertEquals(0.0, banana.f(x), 1e-3);//Its a hard function to get, we often get close } }
1,195
19.982456
94
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/oned/GoldenSearchTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.oned; import jsat.linear.Vec; import jsat.math.Function1D; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class GoldenSearchTest { private static final Function1D easyMin_at_0 = (double x) -> 1+Math.pow(x, 2); public GoldenSearchTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of findMin method, of class GoldenSearch. */ @Test public void testFindMin() { System.out.println("findMin"); for(double tol = 2; tol >= 1e-8; tol/=2) { double result = GoldenSearch.findMin(-10, 10, easyMin_at_0, tol, 1000); assertEquals(0.0, result, tol*1.5); } } }
1,820
22.960526
83
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/AdaDeltaTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class AdaDeltaTest { public AdaDeltaTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; AdaDelta instance = new AdaDelta(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0).normalized(), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; AdaDelta instance = new AdaDelta(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } }
3,389
26.33871
78
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/AdaGradTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class AdaGradTest { public AdaGradTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; AdaGrad instance = new AdaGrad(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0).normalized(), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; AdaGrad instance = new AdaGrad(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } }
3,379
26.258065
78
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/AdamTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class AdamTest { public AdamTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 1.0; Adam instance = new Adam(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 1.0; Adam instance = new Adam(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } }
3,346
25.991935
78
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/NAdaGradTest.java
/* * Copyright (C) 2016 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.FixedProblems; import jsat.SimpleDataSet; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.ClassificationModelEvaluation; import jsat.classifiers.linear.LinearSGD; import jsat.datatransform.LinearTransform; import jsat.distributions.TruncatedDistribution; import jsat.distributions.Uniform; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.lossfunctions.LogisticLoss; import jsat.math.FunctionVec; import jsat.math.decayrates.NoDecay; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.GridDataGenerator; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class NAdaGradTest { public NAdaGradTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; NAdaGrad instance = new NAdaGrad(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0).normalized(), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; NAdaGrad instance = new NAdaGrad(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } @Test public void testUpdate_5args_scaled() { System.out.println("update"); Random rand = RandomUtil.getRandom(); //Test simple SGD LR on many different scalings of the data, all should work for(double scale = 0.0000001; scale <= 1000050; scale *= 10) { ClassificationDataSet train = FixedProblems.get2ClassLinear(2000, rand); ClassificationDataSet test = FixedProblems.get2ClassLinear(200, rand); LinearTransform transform = new LinearTransform(train, -1*scale, 1*scale); train.applyTransform(transform); test.applyTransform(transform); LinearSGD sgd = new LinearSGD(new LogisticLoss(), 0.5, new NoDecay(), 0.0, 0.0); sgd.setUseBias(true); sgd.setGradientUpdater(new NAdaGrad()); ClassificationModelEvaluation cme = new ClassificationModelEvaluation(sgd, train); cme.evaluateTestSet(test); assertEquals(0.0, cme.getErrorRate(), 2.0/200);//should be 0 for all, AdaGrad or SGD would not be so sucesfull } } }
4,992
29.820988
122
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/RMSPropTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class RMSPropTest { public RMSPropTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.001; RMSProp instance = new RMSProp(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.001; RMSProp instance = new RMSProp(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } }
3,368
26.169355
78
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/RpropTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.*; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RpropTest { public RpropTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.001; Rprop instance = new Rprop(); instance.setup(x0.length()); for(int i = 0; i < 10000; i++) { instance.update(x0, fp.f(x0), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.001; Rprop instance = new Rprop(); instance.setup(x0.length()); for(int i = 0; i < 10000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } }
3,242
25.581967
78
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/SGDMomentumTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class SGDMomentumTest { public SGDMomentumTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); for(boolean b : new boolean[]{true, false}) { Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; SGDMomentum instance = new SGDMomentum(0.5, b); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0).normalized(), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } } @Test public void testUpdate_5args() { System.out.println("update"); for(boolean b : new boolean[]{true, false}) { Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; SGDMomentum instance = new SGDMomentum(0.5, b); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } } }
3,685
26.924242
82
java
JSAT
JSAT-master/JSAT/test/jsat/math/optimization/stochastic/SimpleSGDTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.math.optimization.stochastic; import java.util.Random; import jsat.linear.DenseVector; import jsat.linear.SubVector; import jsat.linear.Vec; import jsat.math.FunctionVec; import jsat.math.optimization.RosenbrockFunction; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class SimpleSGDTest { public SimpleSGDTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testUpdate_3args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec x0 = new DenseVector(10); for(int i = 0; i < x0.length(); i++) x0.set(i, rand.nextDouble()); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; SimpleSGD instance = new SimpleSGD(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { instance.update(x0, fp.f(x0).normalized(), eta); instance = instance.clone(); } assertEquals(0.0, f.f(x0), 1e-1); } @Test public void testUpdate_5args() { System.out.println("update"); Random rand = RandomUtil.getRandom(); Vec xWithBias = new DenseVector(21); for(int i = 0; i < xWithBias.length(); i++) xWithBias.set(i, rand.nextDouble()); Vec x0 = new SubVector(0, 20, xWithBias); RosenbrockFunction f = new RosenbrockFunction(); FunctionVec fp = f.getDerivative(); double eta = 0.01; SimpleSGD instance = new SimpleSGD(); instance.setup(x0.length()); for(int i = 0; i < 100000; i++) { double bias = xWithBias.get(20); Vec gradWithBias = fp.f(xWithBias); gradWithBias.normalize(); double biasGrad = gradWithBias.get(20); Vec grad = new SubVector(0, 20, gradWithBias); double biasDelta = instance.update(x0, grad, eta, bias, biasGrad); xWithBias.set(20, bias-biasDelta); instance = instance.clone(); } assertEquals(0.0, f.f(xWithBias), 1e-1); } }
3,392
26.144
78
java
JSAT
JSAT-master/JSAT/test/jsat/math/rootfinding/BisectionTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.math.rootfinding; import jsat.linear.Vec; import jsat.math.rootfinding.Bisection; import jsat.math.Function1D; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static java.lang.Math.*; /** * * @author Edward Raff */ public class BisectionTest { /** * Root at 0 */ Function1D sinF = (double x) -> sin(x); /** * Root at approx -4.87906 */ Function1D polyF = (double x) -> pow(x, 3)+5*pow(x,2)+x+2; public BisectionTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of root method, of class Bisection. */ @Test public void testRoot_4args() { System.out.println("root"); double eps = 1e-15; double result = Bisection.root(-PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Bisection.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Bisection.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Bisection.root(-PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_5args() { System.out.println("root"); double eps = 1e-15; double result = Bisection.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Bisection.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Bisection.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Bisection.root(eps, -PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); } @Test public void testRoot_6args() { System.out.println("root"); double eps = 1e-15; double result = Bisection.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Bisection.root(eps, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); result = Bisection.root(eps, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = Bisection.root(eps, -6.0, 6.0, polyF); assertEquals(-4.8790576334840479813, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_7args() { System.out.println("root"); double eps = 1e-13; int maxIterations = 1000; double result = Bisection.root(eps, maxIterations, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Bisection.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); result = Bisection.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = Bisection.root(eps, maxIterations, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } }
3,538
24.832117
80
java
JSAT
JSAT-master/JSAT/test/jsat/math/rootfinding/RiddersMethodTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.math.rootfinding; import static java.lang.Math.*; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import jsat.math.Function1D; import static org.junit.Assert.assertEquals; /** * * @author Edward Raff */ public class RiddersMethodTest { /** * Root at 0 */ Function1D sinF = (double x) -> sin(x); /** * Root at approx -4.87906 */ Function1D polyF = (double x) -> pow(x, 3)+5*pow(x,2)+x+2; public RiddersMethodTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of root method, of class Bisection. */ @Test public void testRoot_4args() { System.out.println("root"); double eps = 1e-15; double result = RiddersMethod.root(-PI/2, PI/2, sinF); assertEquals(0, result, eps); result = RiddersMethod.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = RiddersMethod.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = RiddersMethod.root(-PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_5args() { System.out.println("root"); double eps = 1e-15; double result = RiddersMethod.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = RiddersMethod.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = RiddersMethod.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = RiddersMethod.root(eps, -PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); } @Test public void testRoot_6args() { System.out.println("root"); double eps = 1e-15; double result = RiddersMethod.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = RiddersMethod.root(eps, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); result = RiddersMethod.root(eps, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = RiddersMethod.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_7args() { System.out.println("root"); double eps = 1e-13; int maxIterations = 1000; double result = RiddersMethod.root(eps, maxIterations, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = RiddersMethod.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); result = RiddersMethod.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = RiddersMethod.root(eps, maxIterations, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } }
3,557
25.355556
84
java
JSAT
JSAT-master/JSAT/test/jsat/math/rootfinding/SecantTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.math.rootfinding; import static java.lang.Math.*; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import jsat.math.Function1D; import static org.junit.Assert.assertEquals; /** * * @author Edward Raff */ public class SecantTest { /** * Root at 0 */ Function1D sinF = (double x) -> sin(x); /** * Root at approx -4.87906 */ Function1D polyF = (double x) -> pow(x, 3)+5*pow(x,2)+x+2; public SecantTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of root method, of class Bisection. */ @Test public void testRoot_4args() { System.out.println("root"); double eps = 1e-15; double result = Secant.root(-PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Secant.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Secant.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Secant.root(-PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(0, sin(result+1), eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_5args() { System.out.println("root"); double eps = 1e-15; double result = Secant.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Secant.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Secant.root(eps, -6, 6,polyF); assertEquals(-4.8790576334840479813, result, eps); result = Secant.root(eps, -PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(0, sin(result+1), eps); } @Test public void testRoot_6args() { System.out.println("root"); double eps = 1e-15; double result = Secant.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Secant.root(eps, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(0, sin(result+1), eps); result = Secant.root(eps, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = Secant.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_7args() { System.out.println("root"); double eps = 1e-13; int maxIterations = 1000; double result = Secant.root(eps, maxIterations, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Secant.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(0, sin(result+1), eps); result = Secant.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = Secant.root(eps, maxIterations, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } }
3,442
24.503704
77
java
JSAT
JSAT-master/JSAT/test/jsat/math/rootfinding/ZeroinTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.math.rootfinding; import static java.lang.Math.*; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import jsat.math.Function1D; import static org.junit.Assert.assertEquals; /** * * @author Edward Raff */ public class ZeroinTest { /** * Root at 0 */ Function1D sinF = (double x) -> sin(x); /** * Root at approx -4.87906 */ Function1D polyF = (double x) -> pow(x, 3)+5*pow(x,2)+x+2; public ZeroinTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of root method, of class Bisection. */ @Test public void testRoot_4args() { System.out.println("root"); double eps = 1e-15; double result = Zeroin.root(-PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Zeroin.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Zeroin.root(-6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Zeroin.root(-PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_5args() { System.out.println("root"); double eps = 1e-15; double result = Zeroin.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Zeroin.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Zeroin.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); result = Zeroin.root(eps, -PI / 2, PI / 2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); } @Test public void testRoot_6args() { System.out.println("root"); double eps = 1e-15; double result = Zeroin.root(eps, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Zeroin.root(eps, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); result = Zeroin.root(eps, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = Zeroin.root(eps, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } /** * Test of root method, of class Bisection. */ @Test public void testRoot_7args() { System.out.println("root"); double eps = 1e-13; int maxIterations = 1000; double result = Zeroin.root(eps, maxIterations, -PI/2, PI/2, sinF); assertEquals(0, result, eps); result = Zeroin.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+1)); assertEquals(-1.0, result, eps); result = Zeroin.root(eps, maxIterations, -PI/2, PI/2, (x)->sin(x+3)); assertEquals(PI-3.0, result, eps); result = Zeroin.root(eps, maxIterations, -6, 6, polyF); assertEquals(-4.8790576334840479813, result, eps); } }
3,427
24.392593
77
java