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 |
---|---|---|---|---|---|---|
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/PdWO3WMemristor.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
/**
* This memristor is a specific MSSMemristor with parameters tweaked to match the GST device from Li 2013
*
* @author timmolter
*/
public class PdWO3WMemristor extends MSSMemristor {
/** characteristic time scale of the device */
private static final double TC = 0.0008;
/** the number of MSS's */
private static final double N = 1000000;
private static final double G_OFF = .4E-5;
private static final double G_ON = 2.5E-5;
/** barrier potentials */
private static final double VA = .8;
private static final double VB = 1;
final static double schottkeyAlpha = 0.000000001;
final static double schottkeyBeta = 8.5;
final static double schottkeyAlphaReverse = 0.000000022;
final static double schottkeyBetaReverse = 6.2;
final static double phi = .55;
/**
* Constructor
*
* @param memristance
*/
public PdWO3WMemristor(double memristance) {
super(memristance, TC, N, G_OFF, G_ON, VA, VB, phi, schottkeyAlpha, schottkeyBeta, schottkeyAlphaReverse, schottkeyBetaReverse);
}
}
| 2,557 | 36.617647 | 132 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/Component.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
/**
* @author timmolter
*/
public abstract class Component {
}
| 1,583 | 41.810811 | 94 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/AgChalcMemristor.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
/**
* This memristor is a specific MSSMemristor with parameters tweaked to match the Boise State University's Silver-Chalcogenide device.
*
* @author timmolter
*/
public class AgChalcMemristor extends MSSMemristor {
/** characteristic time scale of the device */
private static final double TC = 0.00032;
/** the number of MSS's */
private static final double N = 1000000;
private static final double W_OFF = .91E-3;
private static final double W_ON = .87E-2;
/** barrier potentials */
private static final double VA = .17; // lower is pointier
private static final double VB = .22;
final static double schottkeyAlpha = 0; // N/A
final static double schottkeyBeta = 0; // N/A
final static double phi = 1;
/**
* Constructor
*
* @param memristance
*/
public AgChalcMemristor(double memristance) {
super(memristance, TC, N, W_OFF, W_ON, VA, VB, phi, schottkeyAlpha, schottkeyBeta, schottkeyAlpha, schottkeyBeta);
}
}
| 2,491 | 36.757576 | 134 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/MSSMemristor.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
import java.util.Random;
/**
* This memristor is based on Alex's "collection of meta-stable switches" memristor model
*
* @author timmolter
*/
public abstract class MSSMemristor {
/** Boltzman's constant */
private static final double K = 1.3806503E-23;
/** electron charge */
private static final double Q = 1.60217646E-19;
/** temperature in Kelvin */
private static final double TEMP = 298.0;
private static final double BETA = Q / (K * TEMP);
/** thermal voltage */
private static final double VT = 1.0 / BETA;
/** between 0 and 1, representing lowest and highest possible resistance */
private double nAtoNRatio;
/** characteristic time scale of the device */
private final double tc;
/** the number of MSS's */
private final double n;
/** conductance contributed from each MSS */
private final double Ga;
private final double Gb;
/** between 0 and 1, what percentage of the current comes from the MSS model? the rest comes from schottkey barrier exponential current */
private final double phi;
private final double schottkeyAlpha;
private final double schottkeyBeta;
private final double schottkeyReverseAlpha;
private final double schottkeyReverseBeta;
/** barrier potentials */
private final double vA;
private final double vB;
// DEVICE DYNAMIC VARIABLES
/** Nb is the number of MSS's in the B state */
private double Nb = 0;
private final static Random RANDOM = new Random();
/**
* Constructor
*
* @param memristance
* @param tc
* @param n
* @param wOff
* @param wOn
* @param vA
* @param vB
* @param d
* @param phi
* @param schottkeyAlpha
* @param schottkeyBeta
* @param schottkeyReverseAlpha
* @param schottkeyReverseBeta
*/
public MSSMemristor(double memristance, double tc, double n, double wOff, double wOn, double vA, double vB,
double phi, double schottkeyAlpha, double schottkeyBeta, double schottkeyReverseAlpha, double schottkeyReverseBeta) {
if (memristance > 1.0 || memristance < 0.0) {
throw new IllegalArgumentException("Memristance must be between 0 and 1, inclusive!!!");
}
this.nAtoNRatio = memristance;
this.tc = tc;
this.n = n;
Ga = wOff / n;
Gb = wOn / n;
this.vA = vA;
this.vB = vB;
this.phi = phi;
this.schottkeyAlpha = schottkeyAlpha;
this.schottkeyBeta = schottkeyBeta;
this.schottkeyReverseAlpha = schottkeyReverseAlpha;
this.schottkeyReverseBeta = schottkeyReverseBeta;
setNb();
}
/**
* update device
*
* @param voltage
* @param dt
*/
public void dG(double voltage, double dt) {
double Pa = Pa(voltage, dt);
double Pb = Pb(voltage, dt);
double u_a = (n - Nb) * Pa;
double u_b = (Nb) * Pb;
double stdv_a = Math.sqrt((n - Nb) * Pa * (1 - Pa));
double stdv_b = Math.sqrt((Nb) * Pb * (1 - Pb));
double Gab = G(u_a, stdv_a);
double Gba = G(u_b, stdv_b);
Nb += (Gab - Gba);
if (Nb > n) {
Nb = n;
}
else if (Nb < 0) {
Nb = 0;
}
}
/**
* the probability that the MSS will transition from the A state to the B state
*
* @param voltage - the voltage across the device
* @param dt
* @return
*/
private double Pa(final double voltage, final double dt) {
double exponent = -1 * (voltage - vA) / VT;
double alpha = getAlpha(dt);
double Pa = alpha / (1.0 + Math.exp(exponent));
if (Pa > 1.0) {
Pa = 1.0;
}
else if (Pa < 0.0) {
Pa = 0.0;
}
return Pa;
}
/**
* The probability that the MSS will transition from the B state to the A state
*
* @param v
* @param dt
* @return
*/
private double Pb(final double v, final double dt) {
double exponent = -1 * (v + vB) / VT;
double alpha = getAlpha(dt);
double Pb = alpha * (1.0 - 1.0 / (1.0 + Math.exp(exponent)));
if (Pb > 1.0) {
Pb = 1.0;
}
else if (Pb < 0.0) {
Pb = 0.0;
}
return Pb;
}
/**
* dt should be less than tc.
*
* @param dt
* @return
*/
private double getAlpha(double dt) {
return dt / tc;
}
private double G(double u, double stdv) {
double G = stdv * RANDOM.nextGaussian() + u;
return G;
}
/**
* get the conductance
*
* @return
*/
public double getConductance() {
double conductance = Nb * (Gb - Ga) + n * Ga;
nAtoNRatio = 1 - Nb / n;
return conductance;
}
public double getResistance() {
return 1 / getConductance();
}
private void setNb() {
if (nAtoNRatio > 1) {
nAtoNRatio = 1;
}
else if (nAtoNRatio < 0) {
nAtoNRatio = 0;
}
Nb = (1 - nAtoNRatio) * n; // note: (1- memristance) so that a memristance of 1 give a higher resitance than memristance of 0.
}
/**
* Get the current thru this memristor
*
* @return
*/
public double getCurrent(double voltage) {
double mssCurrent = voltage * getConductance();
double schottkeyCurrent = getDiodeCurrent(voltage);
return phi * mssCurrent + (1 - phi) * schottkeyCurrent;
}
private double getDiodeCurrent(double voltage) {
return schottkeyReverseAlpha * (-1 * Math.exp(-1 * schottkeyReverseBeta * voltage)) + schottkeyAlpha * (Math.exp(schottkeyBeta * voltage));
}
}
| 6,818 | 24.349442 | 143 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/AgChalcMemristor2.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
/**
* This memristor is similar to the Boise State University's Silver-Chalcogenide device, but purposely different.
*
* @author timmolter
*/
public class AgChalcMemristor2 extends MSSMemristor {
/** characteristic time scale of the device */
private static final double TC = 0.0032;
/** the number of MSS's */
private static final double N = 1000000;
private static final double W_OFF = .91E-3;
private static final double W_ON = .87E-2;
/** barrier potentials */
private static final double VA = .17; // lower is pointier
private static final double VB = .22;
final static double schottkeyAlpha = 0.00005;
final static double schottkeyBeta = 3.0;
final static double phi = 1;
/**
* Constructor
*
* @param memristance
*/
public AgChalcMemristor2(double memristance) {
super(memristance, TC, N, W_OFF, W_ON, VA, VB, phi, schottkeyAlpha, schottkeyBeta, schottkeyAlpha, schottkeyBeta);
}
}
| 2,465 | 36.363636 | 118 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/GSTMemristor.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
/**
* This memristor is a specific MSSMemristor with parameters tweaked to match the GST device from Li 2013
*
* @author timmolter
*/
public class GSTMemristor extends MSSMemristor {
/** characteristic time scale of the device */
private static final double TC = 0.00042;
/** the number of MSS's */
private static final double N = 1000000;
private static final double G_OFF = .12E-2;
private static final double G_ON = .12E-3;
/** barrier potentials */
private static final double VA = .9; // lower is pointier
private static final double VB = .6;
final static double schottkeyAlpha = 0.00005;
final static double schottkeyBeta = 3.0;
final static double phi = 0.7;
/**
* Constructor
*
* @param memristance
*/
public GSTMemristor(double memristance) {
super(memristance, TC, N, G_OFF, G_ON, VA, VB, phi, schottkeyAlpha, schottkeyBeta, schottkeyAlpha, schottkeyBeta);
}
}
| 2,448 | 36.106061 | 118 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/circuit/mss/AgInSbTeMemristor.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.circuit.mss;
/**
* This memristor is a specific MSSMemristor with parameters tweaked to match the AIST device from [Zhang 2013]
*
* @author timmolter
*/
public class AgInSbTeMemristor extends MSSMemristor {
/** characteristic time scale of the device */
private static final double TC = 0.00015;
/** the number of MSS's */
private static final double N = 1000000;
private static final double G_OFF = .1E-1;
private static final double G_ON = .4E-1;
/** barrier potentials */
private static final double VA = .23; // lower is pointier
private static final double VB = .25;
final static double schottkeyAlpha = 0; // N/A
final static double schottkeyBeta = 0; // N/A
final static double phi = 1;
/**
* Constructor
*
* @param memristance
*/
public AgInSbTeMemristor(double memristance) {
super(memristance, TC, N, G_OFF, G_ON, VA, VB, phi, schottkeyAlpha, schottkeyBeta, schottkeyAlpha, schottkeyBeta);
}
}
| 2,468 | 36.409091 | 118 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/functional/AHaHNode.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.functional;
import java.util.Random;
import java.util.Set;
public class AHaHNode {
private final int numBiasInputs;
private final int numInputs;
private final boolean isModelA;
private final double alpha;
private final double beta;
private final double noise;
private final double decay;
private final double[] w;// weights
private Set<Integer> active;// driven inputs
private double y = 0;
Random random = new Random();
/**
* Constructor
*
* @param numInputs
* @param numBiasInputs
* @param isModelA
*/
public AHaHNode(AHaHNodeBuilder aHaHNodeBuilder) {
this.numInputs = aHaHNodeBuilder.getNumInputs();
this.numBiasInputs = aHaHNodeBuilder.getNumBiasInputs();
this.isModelA = aHaHNodeBuilder.isModelA();
this.alpha = aHaHNodeBuilder.getAlpha();
this.beta = aHaHNodeBuilder.getBeta();
this.noise = aHaHNodeBuilder.getNoise();
this.decay = aHaHNodeBuilder.getDecay();
w = new double[numInputs + numBiasInputs];
for (int i = 0; i < numInputs + numBiasInputs; i++) {
w[i] = .1 * random.nextGaussian();
}
}
public double getWeight(int index) {
return w[index];
}
public double update(Set<Integer> inputSpikes) {
this.active = inputSpikes;
read();
return y;
}
private double read() {
// compute output
y = 0;
for (Integer idx : active) {
y += w[idx];
}
for (int i = 0; i < numBiasInputs; i++) {
y += w[numInputs + i];
}
// weight update-->
// input weights
for (Integer idx : active) {
w[idx] += alpha * Math.signum(y) - beta * y;
}
// bias weights
for (int i = 0; i < numBiasInputs; i++) {
if (isModelA) {
w[numInputs + i] += -alpha * Math.signum(y) + beta * y;// Functional Model A. leads to strange attractors in weight space, likely due to conversion from differentials to real numbers.
}
else {
w[numInputs + i] += -beta * y;// Functional Model B. Preferred functional model. No strange attractors and matches circuit better across tests. Not yet derived from ideal circuit, although its
// intuitively clear why it works.
}
}
for (int i = 0; i < numInputs + numBiasInputs; i++) {
w[i] += noise * random.nextGaussian();
}
for (int i = 0; i < numInputs + numBiasInputs; i++) {
w[i] *= 1 - decay;
}
return y;
}
public int getNumInputs() {
return numInputs;
}
public double getAlpha() {
return alpha;
}
public double getBeta() {
return beta;
}
}
| 4,101 | 27.486111 | 200 | java |
AHaH | AHaH-master/ahah-model/src/main/java/com/mancrd/ahah/model/functional/AHaHNodeBuilder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.model.functional;
/**
* Builder for AHaH21Circuit
*/
public class AHaHNodeBuilder {
private int numInputs;
private int numBiasInputs;
private boolean isModelA = true;
private double alpha = .001;
private double beta = .001;
private double noise = .0005;
private double decay = .0005;
/**
* return fully built object
*
* @return a AHaHNode
*/
public AHaHNode build() {
return new AHaHNode(this);
}
public AHaHNodeBuilder decay(double decay) {
this.decay = decay;
return this;
}
public AHaHNodeBuilder noise(double noise) {
this.noise = noise;
return this;
}
public AHaHNodeBuilder numInputs(int numInputs) {
this.numInputs = numInputs;
return this;
}
public AHaHNodeBuilder numBiasInputs(int numBiasInputs) {
this.numBiasInputs = numBiasInputs;
return this;
}
public AHaHNodeBuilder isModelA(boolean isModelA) {
this.isModelA = isModelA;
return this;
}
public AHaHNodeBuilder alpha(double alpha) {
this.alpha = alpha;
return this;
}
public AHaHNodeBuilder beta(double beta) {
this.beta = beta;
return this;
}
public int getNumInputs() {
return numInputs;
}
public int getNumBiasInputs() {
return numBiasInputs;
}
public boolean isModelA() {
return isModelA;
}
public double getAlpha() {
return alpha;
}
public double getBeta() {
return beta;
}
public double getNoise() {
return noise;
}
public double getDecay() {
return decay;
}
}
| 3,039 | 22.206107 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/test/java/com/mancrd/ahah/samples/spikeencoding/VoltageToSpikes.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.spikeencoding;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
public class VoltageToSpikes {
private static Set<Integer> inputSpikes = new HashSet<Integer>();
static {
inputSpikes.add(0);
}
public static void main(String[] args) {
test0();
}
public static void test0() {
AHaH21Circuit ahahNode = new AHaH21CircuitBuilder().numInputs(1).numBiasInputs(1).build();
int T = 500;
double[] vD = new double[T];
double[] yD = new double[T];
for (int i = 0; i < T; i++) {
double v = Math.sin(i * .1) + 1;
vD[i] = v;
double y = ahahNode.update(inputSpikes, 0);
yD[i] = y;
System.out.println(v + "," + y);
}
// Create Chart
Chart chart = new Chart(1000, 600, ChartTheme.Matlab);
chart.setChartTitle("V and Y");
chart.setYAxisTitle("");
chart.setXAxisTitle("");
// Series series1 = chart.addSeries("V", null, vD);
Series series2 = chart.addSeries("Y", null, yD);
// series1.setMarker(SeriesMarker.NONE);
series2.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
}
}
| 2,909 | 33.235294 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/SweepNumAhahNodesApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* @author timmolter
*/
public class SweepNumAhahNodesApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isFunctional (true) : functional or circuit AHaH model
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (10) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isFunctional = true;
boolean isSweetSpot = true;
int numSweeps4Averaging = 10;
try {
isFunctional = args[0].equals("true");
isSweetSpot = args[1].equals("true");
numSweeps4Averaging = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepNumAhahNodesApp(isFunctional).go(numSweeps4Averaging);
}
else {
new SweepNumAhahNodesApp(isFunctional).go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepNumAhahNodesApp(boolean isFunctional) {
super(isFunctional);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (int numNodes = 2; numNodes <= 24; numNodes += 1) {
xAxisValues.add(numNodes);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> xAxisValues = new ArrayList<Number>() {
// Num spikePatterns
{
add(8);
add(16);
add(32);
add(64);
add(128);
}
};
return xAxisValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
int numSpikePatterns = (Integer) orthogonalValue;
int numAhahNodes = (Integer) xAxisValue;
IClusterer clusterer;
if (isFunctional) {
clusterer = (new com.mancrd.ahah.clusterer.functional.ClustererBuilder()).ahahNodes(numAhahNodes).build();
}
else {
clusterer = (new com.mancrd.ahah.clusterer.circuit.ClustererBuilder()).ahahNodes(numAhahNodes).build();
}
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().numSpikePatterns(numSpikePatterns).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Num AHaH Nodes";
}
@Override
public String getOrthoganolName() {
return "Num Spike Patterns";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 16;
}
}
| 4,932 | 29.079268 | 149 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/Sweeper.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.eval.VergenceEvaluator;
import com.mancrd.ahah.commons.utils.FileUtils;
import com.mancrd.ahah.commons.utils.RunningStat;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public abstract class Sweeper {
public static final int LEARN_STEPS = 1000;
public static final int EVAL_STEPS = 200;
public final boolean isFunctional; // true if functional ahah node, false if circuit ahah node
public abstract List<List<ClustererDriver>> getSweepMatrix(List<Number> orthoganolValues);
public abstract List<Number> getXAxisValues();
public abstract List<Number> getOrthoganolValues();
public abstract String getChartTitle();
public abstract String getOrthoganolName();
public abstract Number getOrthoganolSweetSpotValue();
/**
* Constructor
*
* @param isFunctional
*/
public Sweeper(boolean isFunctional) {
this.isFunctional = isFunctional;
}
/**
* main entry point
*
* @throws Exception
*/
public void go() throws Exception {
List<List<VergenceEvaluator>> sweeps = sweepOrthoganol();
makeOrthogonalChart(sweeps);
}
/**
* main entry point
*
* @throws Exception
*/
public void go(int numSweeps4Averaging) throws Exception {
List<List<VergenceEvaluator>> sweeps = sweepSweetSpot(numSweeps4Averaging);
makeSweetSpotChart(sweeps);
}
/**
* @return
*/
private List<List<VergenceEvaluator>> sweepSweetSpot(int numSweeps4Averaging) {
List<List<VergenceEvaluator>> sweeps = new ArrayList<List<VergenceEvaluator>>();
// make identical orthogonal sweep values from sweet spot value
List<Number> orthogonalValues = new ArrayList<Number>();
for (int i = 0; i < numSweeps4Averaging; i++) {
orthogonalValues.add(getOrthoganolSweetSpotValue());
}
for (List<ClustererDriver> sweep : getSweepMatrix(orthogonalValues)) {
List<VergenceEvaluator> results = new ArrayList<VergenceEvaluator>();
System.out.println("New Sweep!");
for (ClustererDriver clustererDriver : sweep) {
VergenceEvaluator evaluator = this.trial(clustererDriver);
// results.add(evaluator);
System.out.println(evaluator.toCompactString());
results.add(evaluator);
}
sweeps.add(results);
}
return sweeps;
}
/**
* Do the primary and orthogonal sweeps
*
* @return
*/
public List<List<VergenceEvaluator>> sweepOrthoganol() {
List<List<VergenceEvaluator>> sweeps = new ArrayList<List<VergenceEvaluator>>();
for (List<ClustererDriver> sweep : getSweepMatrix(getOrthoganolValues())) {
List<VergenceEvaluator> results = new ArrayList<VergenceEvaluator>();
System.out.println("New Sweep!");
for (ClustererDriver clustererDriver : sweep) {
VergenceEvaluator evaluator = this.trial(clustererDriver);
// results.add(evaluator);
// System.out.println(evaluator.toCompactString());
results.add(evaluator);
}
sweeps.add(results);
}
return sweeps;
}
/**
* Run a sweep, teaching and testing
*
* @param clustererDriver
* @return
*/
private VergenceEvaluator trial(ClustererDriver clustererDriver) {
clustererDriver.learnRandom(LEARN_STEPS); // learn phase
VergenceEvaluator evaluator = clustererDriver.testAllSpikes(EVAL_STEPS); // test phase
return evaluator;
}
/**
* make a chart, either a single one or a chart matrix. Save charts as PNGs.
*
* @param sweeps
* @throws Exception
*/
private void makeOrthogonalChart(List<List<VergenceEvaluator>> sweeps) throws Exception {
List<Chart> charts = new ArrayList<Chart>();
for (int i = 0; i < sweeps.size(); i++) {
List<VergenceEvaluator> result = sweeps.get(i);
List<Number> vergenceValues = new ArrayList<Number>();
List<Number> convergenceValues = new ArrayList<Number>();
List<Number> divergenceValues = new ArrayList<Number>();
for (VergenceEvaluator vergenceEvaluator : result) {
vergenceValues.add(vergenceEvaluator.getVergence());
convergenceValues.add(vergenceEvaluator.getConvergence());
divergenceValues.add(vergenceEvaluator.getDivergence());
}
// Create Chart
Chart chart;
if (sweeps.size() == 1) {
chart = new Chart(800, 600);
}
else {
chart = new Chart(600, 400);
}
// Customize Chart
String chartTitle;
if (sweeps.size() == 1) {
chartTitle = "Vergence vs. " + getChartTitle();
}
else {
chartTitle = "Vergence vs. " + getChartTitle() + " (" + getOrthoganolName() + "=" + getOrthoganolValues().get(i) + ")";
}
chart.setChartTitle(chartTitle);
chart.setXAxisTitle(getChartTitle());
chart.setYAxisTitle("Vergence");
Series series = chart.addSeries("Vergence", getXAxisValues(), vergenceValues);
series.setMarker(SeriesMarker.NONE);
Series series1 = chart.addSeries("Convergence", getXAxisValues(), convergenceValues);
series1.setMarker(SeriesMarker.NONE);
Series series2 = chart.addSeries("Divergence", getXAxisValues(), divergenceValues);
series2.setMarker(SeriesMarker.NONE);
charts.add(chart);
}
if (sweeps.size() == 1) {
new SwingWrapper(charts.get(0)).displayChart();
}
else {
new SwingWrapper(charts).displayChartMatrix();
}
}
/**
* Make a chart with Error Bars and average values
*
* @param sweeps
* @throws Exception
*/
private void makeSweetSpotChart(List<List<VergenceEvaluator>> sweeps) throws Exception {
List<Number> averageVergenceValues = new ArrayList<Number>();
List<Number> stdVergenceValues = new ArrayList<Number>();
List<Number> averageConergenceValues = new ArrayList<Number>();
List<Number> stdConvergenceValues = new ArrayList<Number>();
List<Number> averageDivergenceValues = new ArrayList<Number>();
List<Number> stdDivergenceValues = new ArrayList<Number>();
for (int i = 0; i < sweeps.get(0).size(); i++) {
RunningStat rsVer = new RunningStat();
RunningStat rsCon = new RunningStat();
RunningStat rsDiv = new RunningStat();
for (List<VergenceEvaluator> list : sweeps) { // for each sweep
VergenceEvaluator result = list.get(i);
rsVer.put(result.getVergence());
rsCon.put(result.getConvergence());
rsDiv.put(result.getDivergence());
}
averageVergenceValues.add(rsVer.getAverage());
stdVergenceValues.add(rsVer.getStandardDeviation());
averageConergenceValues.add(rsCon.getAverage());
stdConvergenceValues.add(rsCon.getStandardDeviation());
averageDivergenceValues.add(rsDiv.getAverage());
stdDivergenceValues.add(rsDiv.getStandardDeviation());
}
Chart chart = new Chart(500, 500);
// Customize Chart
String chartTitle = "Vergence vs. " + getChartTitle() + " (" + getOrthoganolName() + "= " + getOrthoganolSweetSpotValue() + ", n= " + sweeps.size() + ")";
chart.setChartTitle(chartTitle);
chart.setXAxisTitle(getChartTitle());
chart.setYAxisTitle("Vergence");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
Series series = chart.addSeries(getOrthoganolName() + " = " + getOrthoganolSweetSpotValue(), getXAxisValues(), averageVergenceValues, stdVergenceValues);
series.setMarker(SeriesMarker.NONE);
// Series series1 = chart.addSeries("Convergence_" + getOrthoganolSweetSpotValue(), getXAxisValues(), averageConergenceValues, stdConvergenceValues);
// series1.setMarker(SeriesMarker.NONE);
// Series series2 = chart.addSeries("Divergence_" + getOrthoganolSweetSpotValue(), getXAxisValues(), averageDivergenceValues, stdDivergenceValues);
// series2.setMarker(SeriesMarker.NONE);
// Results
String functionalOrCircuit = isFunctional ? "Functional" : "Circuit";
FileUtils.mkDirIfNotExists("./Results/");
FileUtils.mkDirIfNotExists("./Results/Clusterer/");
FileUtils.mkDirIfNotExists("./Results/Clusterer/" + getChartTitle().replace(" ", "_") + "/");
FileUtils.mkDirIfNotExists("./Results/Clusterer/" + getChartTitle().replace(" ", "_") + "/" + functionalOrCircuit + "/");
CSVExporter.writeCSVColumns(series, "./Results/Clusterer/" + getChartTitle().replace(" ", "_") + "/" + functionalOrCircuit + "/");
// CSVExporter.writeCSVColumns(series1, "./Results/Clusterer/" + getChartTitle().replace(" ", "_") + "/" + functionalOrCircuit + "/");
// CSVExporter.writeCSVColumns(series2, "./Results/Clusterer/" + getChartTitle().replace(" ", "_") + "/" + functionalOrCircuit + "/");
new SwingWrapper(chart).displayChart();
}
}
| 10,472 | 34.989691 | 158 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/SweepNumSpikePatternsApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* @author timmolter
*/
public class SweepNumSpikePatternsApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isFunctional (true) : functional or circuit AHaH model
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (10) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isFunctional = true;
boolean isSweetSpot = true;
int numSweeps4Averaging = 10;
try {
isFunctional = args[0].equals("true");
isSweetSpot = args[1].equals("true");
numSweeps4Averaging = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepNumSpikePatternsApp(isFunctional).go(numSweeps4Averaging);
}
else {
new SweepNumSpikePatternsApp(isFunctional).go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepNumSpikePatternsApp(boolean isFunctional) {
super(isFunctional);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (int numSpikePatterns = 16; numSpikePatterns <= 32; numSpikePatterns += 2) {
xAxisValues.add(numSpikePatterns);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> orthogonalValues = new ArrayList<Number>() {
{
// num noise bits
add(4);
add(8);
add(16);
add(32);
}
};
return orthogonalValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
int numNoiseBits = (Integer) orthogonalValue;
int numSpikePatterns = (Integer) xAxisValue;
IClusterer clusterer;
if (isFunctional) {
clusterer = (new com.mancrd.ahah.clusterer.functional.ClustererBuilder()).build();
}
else {
clusterer = (new com.mancrd.ahah.clusterer.circuit.ClustererBuilder()).build();
}
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().numSpikePatterns(numSpikePatterns).numNoiseBits(numNoiseBits).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Number Spike Patterns";
}
@Override
public String getOrthoganolName() {
return "Num Noise Bits";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 3;
}
}
| 4,954 | 29.030303 | 172 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/SweepNumNoiseBitsVsNumSpikePatternsApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* @author timmolter
*/
public class SweepNumNoiseBitsVsNumSpikePatternsApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isFunctional (true) : functional or circuit AHaH model
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (3) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isFunctional = true;
boolean isSweetSpot = true;
int numSweeps4Averaging = 10;
try {
isFunctional = args[0].trim().equals("true");
isSweetSpot = args[1].trim().equals("true");
numSweeps4Averaging = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepNumNoiseBitsVsNumSpikePatternsApp(isFunctional).go(numSweeps4Averaging);
}
else {
new SweepNumNoiseBitsVsNumSpikePatternsApp(isFunctional).go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepNumNoiseBitsVsNumSpikePatternsApp(boolean isFunctional) {
super(isFunctional);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (int noiseBits = 0; noiseBits <= 10; noiseBits += 1) {
xAxisValues.add(noiseBits);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> orthogonalValues = new ArrayList<Number>() {
{
// numSpikePatterns
add(16); // default
add(32);
add(64);
add(128);
}
};
return orthogonalValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
int numSpikePatterns = (Integer) orthogonalValue;
int numNoiseBits = (Integer) xAxisValue;
IClusterer clusterer;
if (isFunctional) {
clusterer = (new com.mancrd.ahah.clusterer.functional.ClustererBuilder()).build();
}
else {
clusterer = (new com.mancrd.ahah.clusterer.circuit.ClustererBuilder()).build();
}
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().numSpikePatterns(numSpikePatterns).numNoiseBits(numNoiseBits).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Number Noise Bits";
}
@Override
public String getOrthoganolName() {
return "Number Spike Patterns";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 64;
}
}
| 5,015 | 29.216867 | 172 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/SweepNumNoiseBitsVsSpikePatternLengthApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* @author timmolter
*/
public class SweepNumNoiseBitsVsSpikePatternLengthApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isFunctional (true) : functional or circuit AHaH model
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (10) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isFunctional = true;
boolean isSweetSpot = true;
int numSweeps4Averaging = 10;
try {
isFunctional = args[0].equals("true");
isSweetSpot = args[1].equals("true");
numSweeps4Averaging = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepNumNoiseBitsVsSpikePatternLengthApp(isFunctional).go(numSweeps4Averaging);
}
else {
new SweepNumNoiseBitsVsSpikePatternLengthApp(isFunctional).go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepNumNoiseBitsVsSpikePatternLengthApp(boolean isFunctional) {
super(isFunctional);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (int noiseBits = 0; noiseBits <= 16; noiseBits += 1) {
xAxisValues.add(noiseBits);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> orthogonalValues = new ArrayList<Number>() {
{
// spikePatternLength
add(16); // default
add(32);
add(64);
add(128);
}
};
return orthogonalValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
int spikePatternLength = (Integer) orthogonalValue;
int numNoiseBits = (Integer) xAxisValue;
IClusterer clusterer;
if (isFunctional) {
clusterer = (new com.mancrd.ahah.clusterer.functional.ClustererBuilder()).build();
}
else {
clusterer = (new com.mancrd.ahah.clusterer.circuit.ClustererBuilder()).build();
}
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().spikePatternLength(spikePatternLength).numNoiseBits(numNoiseBits).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Number Noise Bits";
}
@Override
public String getOrthoganolName() {
return "Spike Pattern Length";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 16;
}
}
| 5,017 | 29.228916 | 176 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/ClustererDriver.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.eval.VergenceEvaluator;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* Given a IClusterer and a RandomSpikesGenerator, this class is used to teach and test a Clusterer.
*
* @author timmolter
*/
public class ClustererDriver {
IClusterer clusterer;
RandomSpikePatternGenerator randomSpikesGenerator;
/**
* Constructor
*/
public ClustererDriver(IClusterer clusterer, RandomSpikePatternGenerator randomSpikesGenerator) {
this.clusterer = clusterer;
this.randomSpikesGenerator = randomSpikesGenerator;
}
/**
* Inputs only a single spikes in the spikes list randomly picked for each trial. Features are cloned with noise. Total inputs will be N, where
* N=numTrials
*
* @param numTrials
*/
public void learnRandom(int numTrials) {
for (int i = 0; i < numTrials; i++) {
int spikesId = randomSpikesGenerator.getRandomSpikeId();
Set<String> spikes = randomSpikesGenerator.getClonedSpikePatternWithNoise(spikesId);
this.clusterer.put(spikes);
}
}
/**
* Inputs all spikes in the spikes list randomly picked for each trial. Features are cloned with noise. Total inputs will be N*numSpikes, where
* N=numTrials
*
* @param numTrials
*/
public void learnAll(int numTrials) {
for (int i = 0; i < numTrials; i++) {
for (int j = 0; j < randomSpikesGenerator.getSpikePatterns().size(); j++) {
Set<String> spikes = randomSpikesGenerator.getClonedSpikePatternWithNoise(j);
this.clusterer.put(spikes);
}
}
}
/**
* Tests every single spikes in the spikes list for each trial. Features are cloned with noise. Total inputs will be M*N, where M=numFeatures and
* N=numTrials
*
* @param numTrials
*/
public VergenceEvaluator testAllSpikes(int numTrials) {
VergenceEvaluator evaluator = new VergenceEvaluator();
List<Set<String>> spikesList = randomSpikesGenerator.getSpikePatterns();
for (int t = 0; t < numTrials; t++) {
for (int spikeId = 0; spikeId < spikesList.size(); spikeId++) {
Set<String> spikes = randomSpikesGenerator.getClonedSpikePatternWithNoise(spikeId);
int labelId = this.clusterer.put(spikes);
evaluator.update(spikeId, labelId);
}
}
return evaluator;
}
/**
* Tests only a single spikes in the spikes list randomly picked for each trial. Features are cloned with noise. Total inputs will be N, where
* N=numTrials
*
* @param numTrials
*/
public VergenceEvaluator testRandomSpikes(int numTrials) {
VergenceEvaluator evaluator = new VergenceEvaluator();
for (int t = 0; t < numTrials; t++) {
int featureId = randomSpikesGenerator.getRandomSpikeId();
Set<String> spikes = randomSpikesGenerator.getClonedSpikePatternWithNoise(featureId);
int labelId = this.clusterer.put(spikes);
evaluator.update(featureId, labelId);
}
return evaluator;
}
}
| 4,595 | 34.627907 | 147 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/SweepNoiseTypeApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.syndata.NoiseInjector.Noise;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* @author timmolter
*/
public class SweepNoiseTypeApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isFunctional (true) : functional or circuit AHaH model
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (3) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isFunctional = true;
boolean isSweetSpot = true;
int numSweeps4Averaging = 3;
try {
isFunctional = args[0].equals("true");
isSweetSpot = args[1].equals("true");
numSweeps4Averaging = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepNoiseTypeApp(isFunctional).go(numSweeps4Averaging);
}
else {
new SweepNoiseTypeApp(isFunctional).go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepNoiseTypeApp(boolean isFunctional) {
super(isFunctional);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (int noiseBits = 0; noiseBits <= 64; noiseBits += 4) {
xAxisValues.add(noiseBits);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> orthogonalValues = new ArrayList<Number>() {
{
// noise type
add(1);
// add(2);
// add(3);
// add(4);
}
};
return orthogonalValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
IClusterer clusterer;
if (isFunctional) {
clusterer = (new com.mancrd.ahah.clusterer.functional.ClustererBuilder()).build();
}
else {
clusterer = (new com.mancrd.ahah.clusterer.circuit.ClustererBuilder()).build();
}
Noise noise = Noise.FLIP;
if (orthogonalValue.equals(1)) {
noise = Noise.ADDITIVE;
}
else if (orthogonalValue.equals(2)) {
noise = Noise.SUBTRACTIVE;
}
else if (orthogonalValue.equals(3)) {
noise = Noise.ADD_SUBTRACT;
}
else if (orthogonalValue.equals(4)) {
noise = Noise.FLIP;
}
int numNoiseBits = (Integer) xAxisValue;
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().numNoiseBits(numNoiseBits).noise(noise).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Noise Type vs Noise Amount";
}
@Override
public String getOrthoganolName() {
return "Noise Type";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 4;// flip noise. Not really the "sweet spot", just a choice.
}
}
| 5,333 | 28.633333 | 150 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/SweepSpikePatternLengthApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
/**
* @author timmolter
*/
public class SweepSpikePatternLengthApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isFunctional (true) : functional or circuit AHaH model
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (10) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isFunctional = true;
boolean isSweetSpot = true;
int numSweeps4Averaging = 10;
try {
isFunctional = args[0].equals("true");
isSweetSpot = args[1].equals("true");
numSweeps4Averaging = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepSpikePatternLengthApp(isFunctional).go(numSweeps4Averaging);
}
else {
new SweepSpikePatternLengthApp(isFunctional).go();
}
}
public SweepSpikePatternLengthApp(boolean isFunctional) {
super(isFunctional);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (int spikePatternLength = 16; spikePatternLength <= 64; spikePatternLength += 4) {
xAxisValues.add(spikePatternLength);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> orthogonalValues = new ArrayList<Number>() {
{
// Max Input Spikes
add(512);
add(1024); // current default
add(2048);
add(4096);
}
};
return orthogonalValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
int maxInputSpikes = (Integer) orthogonalValue;
int spikePatternLength = (Integer) xAxisValue;
IClusterer clusterer;
if (isFunctional) {
clusterer = new com.mancrd.ahah.clusterer.functional.ClustererBuilder().numInputs((Integer) orthogonalValue).build();
}
else {
clusterer = new com.mancrd.ahah.clusterer.circuit.ClustererBuilder().numInputs((Integer) orthogonalValue).build();
}
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().maxInputSpikes(maxInputSpikes).spikePatternLength(spikePatternLength).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Spike Pattern Length";
}
@Override
public String getOrthoganolName() {
return "Max Input Spikes";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 256;
}
}
| 5,022 | 30.993631 | 180 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/circuit/SimpleVergenceApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep.circuit;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.circuit.ClustererBuilder;
import com.mancrd.ahah.clusterer.eval.VergenceEvaluator;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
import com.mancrd.ahah.samples.clusterer.sweep.ClustererDriver;
/**
* @author timmolter
*/
public class SimpleVergenceApp {
/**
* @param args
*/
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
SimpleVergenceApp simpleVergenceApp = new SimpleVergenceApp();
simpleVergenceApp.go();
System.out.println((System.currentTimeMillis() - startTime) + " ms");
}
private void go() {
int maxInputSpikes = 256;
int numAhahNodes = 16;
int numBias = 1;
int spikePatternLength = 16;
int numSpikePatterns = 16;
int numNoiseBits = 10;
int numLearnSteps = 100;
int numTestSteps = 100;
IClusterer clusterer = new ClustererBuilder().ahahNodes(numAhahNodes).numInputs(maxInputSpikes).numBias(numBias).build();
RandomSpikePatternGenerator randomSpikesGenerator =
new RandomSpikePatternGenerator.Builder().maxInputSpikes(maxInputSpikes).spikePatternLength(spikePatternLength).numSpikePatterns(numSpikePatterns).numNoiseBits(numNoiseBits).build();
ClustererDriver rdd = new ClustererDriver(clusterer, randomSpikesGenerator);
System.out.println("Learning");
rdd.learnAll(numLearnSteps);
System.out.println("Testing");
VergenceEvaluator ve = rdd.testAllSpikes(numTestSteps);
System.out.println(ve.toVergenceString());
}
}
| 3,113 | 37.444444 | 190 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/functional/SimpleVergenceApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep.functional;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.eval.VergenceEvaluator;
import com.mancrd.ahah.clusterer.functional.ClustererBuilder;
import com.mancrd.ahah.clusterer.syndata.NoiseInjector.Noise;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
import com.mancrd.ahah.samples.clusterer.sweep.ClustererDriver;
/**
* @author timmolter
*/
public class SimpleVergenceApp {
/**
* @param args
*/
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
SimpleVergenceApp simpleVergenceApp = new SimpleVergenceApp();
simpleVergenceApp.go();
System.out.println((System.currentTimeMillis() - startTime) + " ms");
}
private void go() {
int numInputs = 1024;
int numAhahNodes = 24;
int numSpikePatterns = 32;
int spikePatternLength = 32;
int numNoiseBits = 8;
int numLearnSteps = 1000;
int numTestSteps = 1000;
Noise noise = Noise.ADD_SUBTRACT;
IClusterer clusterer = new ClustererBuilder().ahahNodes(numAhahNodes).numInputs(numInputs).build();
RandomSpikePatternGenerator randomSpikesGenerator =
new RandomSpikePatternGenerator.Builder().noise(noise).numNoiseBits(numNoiseBits).maxInputSpikes(numInputs).spikePatternLength(spikePatternLength).numSpikePatterns(numSpikePatterns).build();
ClustererDriver rdd = new ClustererDriver(clusterer, randomSpikesGenerator);
rdd.learnAll(numLearnSteps);
VergenceEvaluator ve = rdd.testAllSpikes(numTestSteps);
System.out.println(ve.toVergenceString());
}
}
| 3,109 | 38.367089 | 198 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/functional/SweepLearningRateApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep.functional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.functional.ClustererBuilder;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
import com.mancrd.ahah.samples.clusterer.sweep.ClustererDriver;
import com.mancrd.ahah.samples.clusterer.sweep.Sweeper;
/**
* @author timmolter
*/
public class SweepLearningRateApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (10) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isSweetSpot = true;
int numSweeps4Averaging = 10;
try {
isSweetSpot = args[0].equals("true");
numSweeps4Averaging = Integer.parseInt(args[1]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepLearningRateApp().go(numSweeps4Averaging);
}
else {
new SweepLearningRateApp().go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepLearningRateApp() {
super(true);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (double learningRate = .0001; learningRate <= 0.002; learningRate += .0001) {
xAxisValues.add(learningRate);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> xAxisValues = new ArrayList<Number>() {
{
// numSpikePatterns
add(16);
add(32);
add(64);
}
};
return xAxisValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
double learningRate = (Double) xAxisValue;
int numSpikePatterns = (Integer) orthogonalValue;
IClusterer clusterer = new ClustererBuilder().learningRate(learningRate).build();
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().numSpikePatterns(numSpikePatterns).build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Learning Rate";
}
@Override
public String getOrthoganolName() {
return "Num Spike Patterns";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return 16;
}
}
| 4,695 | 29.102564 | 149 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/sweep/functional/SweepInitWeightMagApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.sweep.functional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.clusterer.functional.ClustererBuilder;
import com.mancrd.ahah.clusterer.syndata.RandomSpikePatternGenerator;
import com.mancrd.ahah.samples.clusterer.sweep.ClustererDriver;
import com.mancrd.ahah.samples.clusterer.sweep.Sweeper;
/**
* @author timmolter
*/
public class SweepInitWeightMagApp extends Sweeper {
/**
* This app takes the following arguments:
* <ul>
* <li>isSweetSpot (true) : does experiment averaging at sweetspot orthogonal value if true. if false does separate sweeps at all orthogonal values
* <li>int numSweeps4Averaging (3) : if isSweetSpot is true, how many experiments should be used for averaging
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
boolean isSweetSpot = true;
int numSweeps4Averaging = 3;
try {
isSweetSpot = args[0].equals("true");
numSweeps4Averaging = Integer.parseInt(args[1]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (isSweetSpot) {
new SweepInitWeightMagApp().go(numSweeps4Averaging);
}
else {
new SweepInitWeightMagApp().go();
}
}
/**
* Constructor
*
* @param isFunctional
*/
public SweepInitWeightMagApp() {
super(true);
}
@Override
public List<Number> getXAxisValues() {
List<Number> xAxisValues = new ArrayList<Number>();
for (double maxWeight = .001; maxWeight <= 0.2; maxWeight += .002) {
xAxisValues.add(maxWeight);
}
return xAxisValues;
}
@Override
public List<Number> getOrthoganolValues() {
List<Number> xAxisValues = new ArrayList<Number>() {
// Learning Rate
{
add(.001);
add(.005);
add(.01);
add(.05);
}
};
return xAxisValues;
}
@Override
public List<List<ClustererDriver>> getSweepMatrix(List<Number> orthogonalValues) {
List<List<ClustererDriver>> sweepMatrix = new ArrayList<List<ClustererDriver>>();
for (Number orthogonalValue : orthogonalValues) {
List<ClustererDriver> clustererDrivers = new ArrayList<ClustererDriver>();
for (Number xAxisValue : getXAxisValues()) {
double learningRate = (Double) orthogonalValue;
double initWeightMag = (Double) xAxisValue;
IClusterer clusterer = new ClustererBuilder().learningRate(learningRate).maxInitWeight(initWeightMag).build();
RandomSpikePatternGenerator randomSpikesGenerator = new RandomSpikePatternGenerator.Builder().build();
clustererDrivers.add(new ClustererDriver(clusterer, randomSpikesGenerator));
}
sweepMatrix.add(clustererDrivers);
}
return sweepMatrix;
}
@Override
public String getChartTitle() {
return "Initial Weight Magnitude";
}
@Override
public String getOrthoganolName() {
return "Learning Rate";
}
@Override
public Number getOrthoganolSweetSpotValue() {
return .08;
}
}
| 4,697 | 29.309677 | 149 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/ClusteringApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual;
import com.mancrd.ahah.samples.clusterer.visual.oned.Sliding1d;
import com.mancrd.ahah.samples.clusterer.visual.oned.SlidingMany1d;
import com.mancrd.ahah.samples.clusterer.visual.oned.Static1d;
import com.mancrd.ahah.samples.clusterer.visual.twod.ClosePack2d;
import com.mancrd.ahah.samples.clusterer.visual.twod.CurveDot2d;
import com.mancrd.ahah.samples.clusterer.visual.twod.MickyMouse2d;
import com.mancrd.ahah.samples.clusterer.visual.twod.Sliding2d;
import com.mancrd.ahah.samples.clusterer.visual.twod.Static2d;
import com.mancrd.ahah.samples.clusterer.visual.twod.StaticRandom2d;
/**
* @author timmolter
*/
public class ClusteringApp {
/**
* This app takes the following arguments:
* <ul>
* <li>int sampleNumber (0): the id of the sample animation to run [0 to 9]
* <p>
*
* @param args
*/
public static void main(String[] args) {
int sampleNumber = 0;
try {
sampleNumber = Integer.parseInt(args[0]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
switch (sampleNumber) {
case 0:
new ClusteringFrame(new Static1d());
break;
case 1:
new ClusteringFrame(new Sliding1d());
break;
case 2:
new ClusteringFrame(new SlidingMany1d());
break;
case 3:
new ClusteringFrame(new Static2d());
break;
case 4:
new ClusteringFrame(new MickyMouse2d());
break;
case 5:
new ClusteringFrame(new ClosePack2d());
break;
case 6:
new ClusteringFrame(new StaticRandom2d());
break;
case 7:
new ClusteringFrame(new CurveDot2d());
break;
case 8:
new ClusteringFrame(new Sliding2d());
break;
case 9:
break;
default:
break;
}
}
}
| 3,292 | 31.93 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/ClusteringFrame.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @author timmolter
*/
public class ClusteringFrame extends JFrame {
/**
* Constructor
*/
public ClusteringFrame(JPanel jPanel) {
add(jPanel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("Clustering Animation");
setResizable(false);
setVisible(true);
}
}
| 1,986 | 33.859649 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/Slideable.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual;
/**
* @author timmolter
*/
public interface Slideable {
/** how fast the blob should slide per 1000 frame refreshes */
public int getSlideRate();
}
| 1,680 | 41.025 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/ClusteringPanel.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import com.mancrd.ahah.clusterer.IClusterer;
import com.mancrd.ahah.commons.spikes.KNearestNeighbors;
/**
* @author timmolter
*/
public class ClusteringPanel extends JPanel implements Runnable {
protected boolean isRunning = false;
private final int DELAY = 5;
private Thread animator;
protected BasicStroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);
protected Random random = new Random();
protected int cycleCount = 0;
protected int direction = 1;
protected IClusterer clusterer;
protected KNearestNeighbors kNearestNeighbors;
protected HashMap<Integer, Color> colorMap = new HashMap<Integer, Color>();
/**
* Constructor
*/
public ClusteringPanel() {
setBackground(Color.WHITE);
setDoubleBuffered(true);
// Space bar for pausing
KeyStroke spaceBar = KeyStroke.getKeyStroke(' ');
this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(spaceBar, "pause");
this.getActionMap().put("pause", new PauseAction());
}
@Override
public void addNotify() {
super.addNotify();
animator = new Thread(this);
animator.start();
}
@Override
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true) {
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
private class PauseAction extends AbstractAction {
public PauseAction() {
super("pause");
}
@Override
public void actionPerformed(ActionEvent e) {
isRunning = !isRunning;
}
}
}
| 3,581 | 26.984375 | 98 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/StaticRandom2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
/**
* @author timmolter
*/
public class StaticRandom2d extends ClusteringPanel2d {
private List<Blob2d> blobCenters = new ArrayList<Blob2d>();
public static void main(String[] args) {
new ClusteringFrame(new StaticRandom2d());
}
/**
* Constructor
*/
public StaticRandom2d() {
this.blobCenters = new ArrayList<Blob2d>();
int numCenters = 12;
int blobSize = 10;
for (int i = 0; i < numCenters; i++) {
blobCenters.add(new Blob2d((int) ((100 * (Math.random() - .5)) + 50), (int) (100 * (Math.random() - .5) + 50), (int) (Math.random() * blobSize)));
}
int bigBlobX = 50;
int bigBlobY = 50;
int bigBlobSize = 20;
for (int i = 0; i < 1; i++) {// until I change how new centers are added in the kNN spike encoder, the total frequency of a cluster needs to be
// equal to the others. This is just an artificat of the kNN algo.
blobCenters.add(new Blob2d(bigBlobX, bigBlobY, bigBlobSize));
blobCenters.add(new Blob2d(bigBlobX, bigBlobY, bigBlobSize));
}
}
@Override
public List<Blob2d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelSize() {
return 300;
}
@Override
public int getNumSpikes() {
return 24;
}
}
| 2,924 | 31.142857 | 152 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/Sliding2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
import com.mancrd.ahah.samples.clusterer.visual.Slideable;
/**
* @author timmolter
*/
public class Sliding2d extends ClusteringPanel2d implements Slideable {
private final List<Blob2d> blobCenters = new ArrayList<Blob2d>();
public static void main(String[] args) {
new ClusteringFrame(new Sliding2d());
}
/**
* Constructor
*/
public Sliding2d() {
blobCenters.add(new Blob2d(10, 20, 10));
blobCenters.add(new Blob2d(10, 50, 10));
blobCenters.add(new Blob2d(10, 80, 10));
blobCenters.add(new Blob2d(50, 50, 10));
}
@Override
public List<Blob2d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelSize() {
return 300;
}
@Override
public int getNumSpikes() {
return 64;
}
@Override
public int getSlideRate() {
return 40;
}
}
| 2,474 | 28.464286 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/Static2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
/**
* @author timmolter
*/
public class Static2d extends ClusteringPanel2d {
private final List<Blob2d> blobCenters = new ArrayList<Blob2d>();
public static void main(String[] args) {
new ClusteringFrame(new Static2d());
}
/**
* Constructor
*/
public Static2d() {
blobCenters.add(new Blob2d(50, 50, 20));
blobCenters.add(new Blob2d(85, 85, 20));
blobCenters.add(new Blob2d(15, 15, 20));
blobCenters.add(new Blob2d(15, 85, 20));
blobCenters.add(new Blob2d(85, 15, 20));
}
@Override
public List<Blob2d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelSize() {
return 600;
}
@Override
public int getNumSpikes() {
return 64;
}
}
| 2,374 | 29.063291 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/ClosePack2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
/**
* @author timmolter
*/
public class ClosePack2d extends ClusteringPanel2d {
private final List<Blob2d> blobCenters = new ArrayList<Blob2d>();
public static void main(String[] args) {
new ClusteringFrame(new ClosePack2d());
}
/**
* Constructor
*/
public ClosePack2d() {
blobCenters.add(new Blob2d(30, 50, 10));
blobCenters.add(new Blob2d(50, 50, 5));
blobCenters.add(new Blob2d(45, 45, 5));
blobCenters.add(new Blob2d(40, 40, 5));
blobCenters.add(new Blob2d(45, 55, 5));
blobCenters.add(new Blob2d(40, 60, 5));
}
@Override
public List<Blob2d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelSize() {
return 300;
}
@Override
public int getNumSpikes() {
return 64;
}
}
| 2,423 | 29.3 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/MickyMouse2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
/**
* @author timmolter
*/
public class MickyMouse2d extends ClusteringPanel2d {
private final List<Blob2d> blobCenters = new ArrayList<Blob2d>();
public static void main(String[] args) {
new ClusteringFrame(new MickyMouse2d());
}
/**
* Constructor
*/
public MickyMouse2d() {
for (int i = 0; i < 5; i++) {
blobCenters.add(new Blob2d(50, 70, 40));
blobCenters.add(new Blob2d(20, 20, 10));
blobCenters.add(new Blob2d(65, 40, 10));
}
}
@Override
public List<Blob2d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelSize() {
return 300;
}
@Override
public int getNumSpikes() {
return 64;
}
}
| 2,343 | 28.3 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/Coordinate2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
/**
* @author timmolter
*/
public final class Coordinate2d {
private final int xCoord;
private final int yCoord;
private final int colorIdx;
/**
* Constructor
*
* @param xCoord
* @param yCoord
* @param colorIdx
*/
public Coordinate2d(int xCoord, int yCoord, int colorIdx) {
this.xCoord = xCoord;
this.yCoord = yCoord;
this.colorIdx = colorIdx;
}
public int getxCoord() {
return xCoord;
}
public int getyCoord() {
return yCoord;
}
public int getColorIdx() {
return colorIdx;
}
}
| 2,086 | 28.814286 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/Blob2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
/**
* @author timmolter
*/
public final class Blob2d {
private int xCoord;
private int yCoord;
private final int radius;
/**
* Constructor
*
* @param xCoord
* @param yCoord
* @param radius
*/
public Blob2d(int xCoord, int yCoord, int radius) {
this.xCoord = xCoord;
this.yCoord = yCoord;
this.radius = radius;
}
public int getxCoord() {
return xCoord;
}
public void setxCoord(int xCoord) {
this.xCoord = xCoord;
}
public int getyCoord() {
return yCoord;
}
public void setyCoord(int yCoord) {
this.yCoord = yCoord;
}
public int getRadius() {
return radius;
}
}
| 2,188 | 26.3625 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/ClusteringPanel2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import com.mancrd.ahah.clusterer.functional.ClustererBuilder;
import com.mancrd.ahah.commons.spikes.KNearestNeighbors;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringPanel;
import com.mancrd.ahah.samples.clusterer.visual.Slideable;
/**
* @author timmolter
*/
public abstract class ClusteringPanel2d extends ClusteringPanel {
static final int DOT_RADIUS = 8;
// All Coordinates
Queue<Coordinate2d> fifo;
/**
* Constructor
*/
public ClusteringPanel2d() {
super();
setPreferredSize(new Dimension(getPanelSize(), getPanelSize()));
// Spike Encoder
kNearestNeighbors = new KNearestNeighbors(512, 2, .01);
clusterer = new ClustererBuilder().numInputs(60000).ahahNodes(24).learningRate(.003).maxInitWeight(.003).build();
fifo = new LinkedList<Coordinate2d>();
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
if (isRunning) {
cycle();
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(stroke);
// 1. draw blob center cross marks
g2d.setColor(Color.BLACK);
for (int i = 0; i < getBlobs().size(); i++) {
int xCoord = getBlobs().get(i).getxCoord();
int yCoord = getBlobs().get(i).getyCoord();
g2d.drawLine(xCoord * getPanelSize() / 100, yCoord * getPanelSize() / 100 - 15, xCoord * getPanelSize() / 100, yCoord * getPanelSize() / 100 + 15);
g2d.drawLine(xCoord * getPanelSize() / 100 - 15, yCoord * getPanelSize() / 100, xCoord * getPanelSize() / 100 + 15, yCoord * getPanelSize() / 100);
}
// 2. draw blobs
for (Coordinate2d coordinate : fifo) {
// System.out.println(coordinate.getColorIdx());
Color color = colorMap.get(coordinate.getColorIdx());
if (color == null) {
colorMap.put(coordinate.getColorIdx(), new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
}
g2d.setColor(color);
g2d.fillOval(coordinate.getxCoord() - DOT_RADIUS, coordinate.getyCoord() - DOT_RADIUS, DOT_RADIUS, DOT_RADIUS);
}
}
else {
Toolkit.getDefaultToolkit().sync();
g.drawString("Press Spacebar to Continue.", 15, 15);
}
g.dispose();
}
/**
* Update entire Surface state
*/
public void cycle() {
cycleCount++;
if (this instanceof Slideable) {
for (int i = 0; i < getBlobs().size() - 1; i++) {
if (cycleCount % (1000 / ((Slideable) this).getSlideRate()) == 0) {
getBlobs().get(i).setxCoord(1 * direction + getBlobs().get(i).getxCoord());
}
if (getBlobs().get(i).getxCoord() * getPanelSize() / 100 <= 0) {
direction = 1; // switch direction
}
else if (getBlobs().get(i).getxCoord() * getPanelSize() / 100 >= getPanelSize() - 1) {
direction = -1; // switch direction
}
}
}
// pick a random blob center
Blob2d blob2d = getBlobs().get(random.nextInt(getBlobs().size()));
fifo.add(getCoordinate(blob2d));
if (fifo.size() > 75 * getBlobs().size()) {
fifo.remove();
}
}
/**
* Given a center of blob, return random points next to it picked from a Gaussian distribution
*
* @param blob
* @return Coordinate - the featureset and label
*/
private Coordinate2d getCoordinate(Blob2d blob) {
int xCoord = -1;
int yCoord = -1;
do { // pick a random point offset from the blob center
xCoord = (blob.getxCoord() * getPanelSize() / 100 + (int) (random.nextGaussian() * blob.getRadius()));
yCoord = (blob.getyCoord() * getPanelSize() / 100 + (int) (random.nextGaussian() * blob.getRadius()));
} while (xCoord < 0 && xCoord > getPanelSize() && yCoord < 0 && yCoord > getPanelSize());
double[] d = { xCoord, yCoord };
Set<String> spikes = kNearestNeighbors.encode(d, getNumSpikes());
// Set<String> spikes = treeBinnerVector.encode(d);
// System.out.println(spikes);
return new Coordinate2d(xCoord, yCoord, clusterer.put(spikes));
}
/** as a percentage of the width */
public abstract List<Blob2d> getBlobs();
public abstract int getPanelSize();
public abstract int getNumSpikes();
} | 6,075 | 33.134831 | 155 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/twod/CurveDot2d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.twod;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
/**
* @author timmolter
*/
public class CurveDot2d extends ClusteringPanel2d {
private final List<Blob2d> blobCenters = new ArrayList<Blob2d>();
public static void main(String[] args) {
new ClusteringFrame(new CurveDot2d());
}
/**
* Constructor
*/
public CurveDot2d() {
for (int y = 10; y < 90; y += 2) {
blobCenters.add(new Blob2d((int) (-.02 * Math.pow(y - 50, 2) + 85), y, 15));// curve
blobCenters.add(new Blob2d(40, 50, 25));// center blob
}
// blobCenters.add(new Blob2d(40, 50, 100));// noise
// blobCenters.add(new Blob2d(40, 50, 100));// noise
// blobCenters.add(new Blob2d(40, 50, 100));// noise
}
@Override
public List<Blob2d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelSize() {
return 300;
}
@Override
public int getNumSpikes() {
return 128;
}
}
| 2,526 | 29.445783 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/oned/ClusteringPanel1d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.oned;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import com.mancrd.ahah.clusterer.functional.ClustererBuilder;
import com.mancrd.ahah.commons.spikes.KNearestNeighbors;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringPanel;
import com.mancrd.ahah.samples.clusterer.visual.Slideable;
/**
* @author timmolter
*/
public abstract class ClusteringPanel1d extends ClusteringPanel {
static final int PANEL_HEIGHT = 260;
protected Queue<Coordinate1d> fifo;
/**
* Constructor
*/
public ClusteringPanel1d() {
super();
setPreferredSize(new Dimension(getPanelWidth(), PANEL_HEIGHT));
kNearestNeighbors = new KNearestNeighbors(512, 1, .1);
clusterer = new ClustererBuilder().numInputs(60000).ahahNodes(24).learningRate(.003).maxInitWeight(.003).build();
fifo = new LinkedList<Coordinate1d>();
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
if (isRunning) {
cycle();
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(stroke);
// 1. draw blob centers
g2d.setColor(Color.BLACK);
for (int i = 0; i < getBlobs().size(); i++) {
int xCoord = getBlobs().get(i).getxCoord();
g2d.drawLine(xCoord * getPanelWidth() / 100, 0, xCoord * getPanelWidth() / 100, PANEL_HEIGHT);
}
// 2. draw blobs
for (Coordinate1d coordinate : fifo) {
// System.out.println(coordinate.getColorIdx());
Color color = colorMap.get(coordinate.getColorIdx());
if (color == null) {
color = new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255));
colorMap.put(coordinate.getColorIdx(), color);
}
g2d.setColor(color);
g2d.fillRect(coordinate.getxCoord(), (int) (PANEL_HEIGHT * .25), 2, (int) (PANEL_HEIGHT * .5));
}
}
else {
g.drawString("Press Spacebar to Continue.", 15, 15);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
/**
* Update entire Surface state
*/
public void cycle() {
cycleCount++;
if (this instanceof Slideable) {
if (cycleCount % (1000 / ((Slideable) this).getSlideRate()) == 0) {
getBlobs().get(0).setxCoord(1 * direction + getBlobs().get(0).getxCoord());
}
if (getBlobs().get(0).getxCoord() * getPanelWidth() / 100 <= 0) {
direction = 1; // switch direction
}
else if (getBlobs().get(0).getxCoord() * getPanelWidth() / 100 >= getPanelWidth() - 1) {
direction = -1; // switch direction
}
}
// pick a random blob center
Blob1d blob1d = getBlobs().get(random.nextInt(getBlobs().size()));
fifo.add(getCoordinate(blob1d));
if (fifo.size() > 20 * getBlobs().size()) {
fifo.remove();
}
}
/**
* @param centerOfBlob
* @return
*/
private Coordinate1d getCoordinate(Blob1d blob) {
int xCoord = -1;
do { // pick a random point offset from the blob center
xCoord = (blob.getxCoord() * getPanelWidth() / 100 + (int) (random.nextGaussian() * blob.getRadius()));
} while (xCoord < 0 && xCoord > getPanelWidth());
double[] d = { xCoord };
Set<String> spikes = kNearestNeighbors.encode(d, getNumSpikes());
return new Coordinate1d(xCoord, clusterer.put(spikes));
}
/** as a percentage of the width */
public abstract List<Blob1d> getBlobs();
public abstract int getPanelWidth();
public abstract int getNumSpikes();
} | 5,290 | 31.262195 | 117 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/oned/Sliding1d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.oned;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
import com.mancrd.ahah.samples.clusterer.visual.Slideable;
/**
* @author timmolter
*/
public class Sliding1d extends ClusteringPanel1d implements Slideable {
private final List<Blob1d> blobCenters = new ArrayList<Blob1d>();
public static void main(String[] args) {
new ClusteringFrame(new Sliding1d());
}
/**
* Constructor
*/
public Sliding1d() {
blobCenters.add(new Blob1d(20, 10));
blobCenters.add(new Blob1d(50, 10));
}
@Override
public List<Blob1d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelWidth() {
return 512;
}
@Override
public int getSlideRate() {
return 100;
}
@Override
public int getNumSpikes() {
return 128;
}
}
| 2,380 | 27.686747 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/oned/SlidingMany1d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.oned;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
import com.mancrd.ahah.samples.clusterer.visual.Slideable;
/**
* @author timmolter
*/
public class SlidingMany1d extends ClusteringPanel1d implements Slideable {
private final List<Blob1d> blobCenters = new ArrayList<Blob1d>();
public static void main(String[] args) {
new ClusteringFrame(new SlidingMany1d());
}
/**
* Constructor
*/
public SlidingMany1d() {
blobCenters.add(new Blob1d(10, 10));
blobCenters.add(new Blob1d(20, 10));
blobCenters.add(new Blob1d(50, 10));
blobCenters.add(new Blob1d(80, 10));
}
@Override
public List<Blob1d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelWidth() {
return 512;
}
@Override
public int getSlideRate() {
return 80;
}
@Override
public int getNumSpikes() {
return 128;
}
}
| 2,473 | 28.105882 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/oned/Blob1d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.oned;
/**
* @author timmolter
*/
public final class Blob1d {
private int xCoord;
private final int radius;
/**
* Constructor
*
* @param yCoord
* @param radius
*/
public Blob1d(int xCoord, int radius) {
this.xCoord = xCoord;
this.radius = radius;
}
public int getxCoord() {
return xCoord;
}
public void setxCoord(int xCoord) {
this.xCoord = xCoord;
}
public int getRadius() {
return radius;
}
}
| 1,987 | 28.671642 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/oned/Coordinate1d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.oned;
/**
* @author timmolter
*/
public final class Coordinate1d {
private final int xCoord;
private final int colorIdx;
/**
* Constructor
*
* @param xCoord
* @param colorIdx
*/
public Coordinate1d(int xCoord, int colorIdx) {
this.xCoord = xCoord;
this.colorIdx = colorIdx;
}
public int getxCoord() {
return xCoord;
}
public int getColorIdx() {
return colorIdx;
}
}
| 1,949 | 30.451613 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/clusterer/visual/oned/Static1d.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.clusterer.visual.oned;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.samples.clusterer.visual.ClusteringFrame;
/**
* Random points along a line picked from a Gaussian distribution centered at N blobs are eventually clustered and labeled in an unsupervised manner
* by the clusterer
*
* @author timmolter
*/
public class Static1d extends ClusteringPanel1d {
public static void main(String[] args) {
new ClusteringFrame(new Static1d());
}
private final List<Blob1d> blobCenters = new ArrayList<Blob1d>();
/**
* Constructor
*/
public Static1d() {
blobCenters.add(new Blob1d(20, 40));
blobCenters.add(new Blob1d(90, 10));
blobCenters.add(new Blob1d(50, 30));
blobCenters.add(new Blob1d(70, 10));
blobCenters.add(new Blob1d(40, 10));
}
@Override
public List<Blob1d> getBlobs() {
return blobCenters;
}
@Override
public int getPanelWidth() {
return 1024;
}
@Override
public int getNumSpikes() {
return 64;
}
}
| 2,528 | 30.222222 | 148 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/reuters21578/Reuters21578App.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.reuters21578;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.xeiam.datasets.reuters21578.Reuters21578;
import com.xeiam.datasets.reuters21578.Reuters21578DAO;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class Reuters21578App {
public static DecimalFormat df = new DecimalFormat(".000");
/**
* This app takes the following arguments:
* <ul>
* <li>int numTrainingEpochs = (5)
*
* @param args
* @throws InterruptedException
* @throws IOException
*/
public static void main(String[] args) throws InterruptedException, IOException {
File tempDBFile = Reuters21578DAO.init(); // setup data
Reuters21578App rca = new Reuters21578App();
rca.go(args);
Reuters21578DAO.release(tempDBFile); // release data resources
}
public void go(String[] args) throws IOException {
int numTrainingEpoch = 3;
try {
numTrainingEpoch = Integer.parseInt(args[0]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
Classifier classifier = new Classifier();
Reuters21578SpikeEncoder reuters21578SpikeEncoder = new Reuters21578SpikeEncoder();
System.out.println("getting data from DB...");
List<Reuters21578> trainSet = Reuters21578DAO.selectModApte("TRAIN", true);
// Collections.shuffle(trainSet);
System.out.println("trainSet size =" + trainSet.size());
System.out.println("training...");
long startTime = System.currentTimeMillis();
for (int i = 0; i < numTrainingEpoch; i++) {
System.out.println(" epoch " + (i + 1));
for (Reuters21578 reuters21578 : trainSet) {
String[] topicTrueLabels = reuters21578.getTopics().split(",");
long[] spikes = reuters21578SpikeEncoder.encode(reuters21578);
classifier.update(topicTrueLabels, spikes);
// System.out.println("Spike Pattern Length = " + spikes.length);
}
}
System.out.println("time elapsed training= " + (System.currentTimeMillis() - startTime));
System.out.println("runtime total memory: " + Runtime.getRuntime().totalMemory());
System.out.println("totalClassificationTime= " + (double) classifier.getTotalClassificationTimeInNanoSeconds() / 1000000000 + " s");
System.out.println("totalNumSpikesProcessed= " + classifier.getNumSpikesProcessed());
System.out.println("averageSpikesProcessedPerUpdate= " + classifier.getNumSpikesProcessed() / (double) classifier.getNumUpdates());
System.out.println("averageLabelsProcessedPerUpdate= " + classifier.getNumLabelsProcessed() / (double) classifier.getNumUpdates());
System.out.println("spikesProcessingRate= " + classifier.getNumSpikesProcessed() / ((double) classifier.getTotalClassificationTimeInNanoSeconds() / 1000000000) + " spikes/s");
System.out.println("Spike Pattern Space = " + reuters21578SpikeEncoder.getSpikePatternSpace());
// test
System.out.println("testing");
// only measure performance on top-10 labels (this is what most published benchmarks do).
Set<String> labels = new HashSet<String>();
labels.add("earn");
labels.add("acq");
labels.add("money-fx");
labels.add("grain");
labels.add("crude");
labels.add("trade");
labels.add("interest");
labels.add("ship");
labels.add("wheat");
labels.add("corn");
int numSteps = 100;
double[] confidenceThresholds = new double[numSteps];
double inc = 1.0 / numSteps;
for (int i = 0; i < confidenceThresholds.length; i++) {
confidenceThresholds[i] = i * inc;
}
// evaluators for keeping track of performance for each confidence threshold
ClassificationEvaluator[] evaluators = new ClassificationEvaluator[numSteps];
for (int i = 0; i < evaluators.length; i++) {
evaluators[i] = new ClassificationEvaluator(labels);
}
List<Reuters21578> testSet = Reuters21578DAO.selectModApte("TEST", true);
System.out.println("testSet size =" + testSet.size());
for (Reuters21578 reuters21578 : testSet) {
String[] topicTrueLabels = reuters21578.getTopics().split(",");
long[] spikes = reuters21578SpikeEncoder.encode(reuters21578);
ClassifierOutput classifierOutput = classifier.update(topicTrueLabels, spikes);
for (int i = 0; i < evaluators.length; i++) {
evaluators[i].update(new HashSet(Arrays.asList(topicTrueLabels)), classifierOutput.getSortedLabels(confidenceThresholds[i]));
}
}
double maxF1 = 0;
int cIdx = 0;
// plot results---->
// performance vs confidence thresholds
double[] accuracy = new double[numSteps];
double[] precision = new double[numSteps];
double[] recall = new double[numSteps];
double[] f1 = new double[numSteps];
for (int i = 0; i < numSteps; i++) {
accuracy[i] = evaluators[i].getAccuracyMicroAve();
precision[i] = evaluators[i].getPrecisionMicroAve();
recall[i] = evaluators[i].getRecallMicroAve();
f1[i] = evaluators[i].getF1MicroAve();
if (f1[i] > maxF1) {// get the best confidence threshold
maxF1 = f1[i];
cIdx = i;
}
}
// print the performance of all labels at best confidence threshold-->
System.out.println(evaluators[cIdx].toString());
// classifierDB.close();
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
// chart.setChartTitle("Reuters21578 App - F1=" + df.format(maxF1) + " w/ConfidenceThreshold=" + df.format(confidenceThresholds[cIdx]));
chart.setChartTitle("Reuters21578 - Functional");
chart.setXAxisTitle("Confidence Threshold");
chart.setYAxisTitle("Score");
// chart.getStyleManager().setXAxisMax(1.01);
Series accuracy_series = chart.addSeries("Accuracy", confidenceThresholds, accuracy);
accuracy_series.setMarker(SeriesMarker.NONE);
Series precision_series = chart.addSeries("Precision", confidenceThresholds, precision);
precision_series.setMarker(SeriesMarker.NONE);
Series recall_series = chart.addSeries("Recall", confidenceThresholds, recall);
recall_series.setMarker(SeriesMarker.NONE);
Series f1_series = chart.addSeries("F1", confidenceThresholds, f1);
f1_series.setMarker(SeriesMarker.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/Reuters_Supervised.png", 300);
new SwingWrapper(chart).displayChart();
System.out.println("Num AHaH Nodes = " + classifier.getNumUniqueLabels());
}
}
| 8,525 | 39.794258 | 179 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/reuters21578/Reuters21578SpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.reuters21578;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.commons.spikes.SpikeEncoder;
import com.xeiam.datasets.reuters21578.Reuters21578;
/**
* Typical bag-of-words encoder
*
* @author alexnugent
*/
public class Reuters21578SpikeEncoder extends SpikeEncoder<Reuters21578> {
private static final String parseRegEx = " |,|\\.|:|'|\\(|\\)";
private static Calendar cal = Calendar.getInstance();
public Reuters21578SpikeEncoder() {
}
@Override
public Set<String> getSpikes(Reuters21578 story) {
Set<String> spikes = new HashSet<String>();
// date
cal.setTime(story.getDate());
spikes.add("month=" + cal.get(Calendar.MONTH));
spikes.add("day_of_week=" + cal.get(Calendar.DAY_OF_WEEK));
spikes.add("year=" + cal.get(Calendar.YEAR));
spikes.add("day_of_month=" + cal.get(Calendar.DAY_OF_MONTH));
spikes.add("am_pm=" + cal.get(Calendar.AM_PM));
spikes.add("hour_of_day=" + cal.get(Calendar.HOUR_OF_DAY));
spikes.add("week_of_month=" + cal.get(Calendar.WEEK_OF_MONTH));
spikes.add("week_of_year=" + cal.get(Calendar.WEEK_OF_YEAR));
// places
addToFeatures(story.getPlaces().split(","), "place=", spikes);
// people
addToFeatures(story.getPeople().split(","), "people=", spikes);
// orgs
addToFeatures(story.getOrgs().split(","), "orgs=", spikes);
// exchanges
addToFeatures(story.getExchanges().split(","), "exchanges=", spikes);
// title
addToFeatures(story.getTitle().split(" "), "titleword=", spikes);
// dateline
addToFeatures(story.getDateline().split(" "), "dateline=", spikes);
// company
addToFeatures(story.getCompanies().split(","), "company=", spikes);
// story body
String[] words = story.getBody().toLowerCase().split(parseRegEx);
addToFeatures(words, "", spikes);
// features.add(0);// bias is zero
return spikes;
}
private void addToFeatures(String[] features, String concat, Set<String> spikes) {
if (features.length == 0) {
return;
}
for (int i = 0; i < features.length; i++) {
spikes.add(concat + features[i].toLowerCase());
}
}
@Override
public short getUniquePositiveID() {
// TODO Auto-generated method stub
return 0;
}
}
| 3,811 | 33.035714 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/reuters21578/Reuters21578SemiSupervisedApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.reuters21578;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.classifier.ClassificationRate;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.xeiam.datasets.reuters21578.Reuters21578;
import com.xeiam.datasets.reuters21578.Reuters21578DAO;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class Reuters21578SemiSupervisedApp {
public static DecimalFormat df = new DecimalFormat(".000");
/**
* <ul>
* <li>double unsupervisedConfidenceThreshold (1.0): confidence threshold, above which unsupervised learning will take place
* <li>double startAuto (.25): percentage through data when unsupervised learning starts;
* <li>double learningRate (.5): classifier learning rate
*
* @param args
* @throws InterruptedException
* @throws IOException
*/
public static void main(String[] args) throws InterruptedException, IOException {
Reuters21578SemiSupervisedApp rca = new Reuters21578SemiSupervisedApp();
rca.go(args);
}
public void go(String[] args) throws IOException {
double unsupervisedConfidenceThreshold = 1;
double startAuto = .25;
float learningRate = .5f;
try {
unsupervisedConfidenceThreshold = Double.parseDouble(args[0]);
startAuto = Double.parseDouble(args[1]);
learningRate = Float.parseFloat(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
Classifier classifier = new Classifier();
classifier.setLearningRate(learningRate);
classifier.setUnsupervisedConfidenceThreshold(unsupervisedConfidenceThreshold);
classifier.setUnsupervisedEnabled(true);
Reuters21578SpikeEncoder reuters21578SpikeEncoder = new Reuters21578SpikeEncoder();
// only measure performance on top-10 labels (this is what most published benchmarks do).
String[] labelArray = { "earn", "acq", "money-fx", "grain", "crude", "trade", "interest", "ship", "wheat", "corn" };
Set<String> labels = new HashSet<String>(Arrays.asList(labelArray));
ClassificationEvaluator evaluator = new ClassificationEvaluator(labels);
System.out.println("training");
List<Reuters21578> dataSet = Reuters21578DAO.selectModApte("TRAIN", true);
dataSet.addAll(Reuters21578DAO.selectModApte("TEST", true));
Collections.shuffle(dataSet);// this insures
List<double[]> plotData = new ArrayList<double[]>();
for (int i = 0; i < labelArray.length; i++) {
plotData.add(new double[(dataSet.size())]);
}
for (int i = 0; i < dataSet.size(); i++) {
Reuters21578 reuters21578 = dataSet.get(i);
String[] topicTrueLabels = reuters21578.getTopics().split(",");
long[] spikes = reuters21578SpikeEncoder.encode(reuters21578);
ClassifierOutput classifierOutput;
if ((double) i / dataSet.size() < startAuto) {
classifierOutput = classifier.update(topicTrueLabels, spikes);
}
else {
classifierOutput = classifier.update(null, spikes);// learn unsupervised. From
}
evaluator.update(new HashSet(Arrays.asList(topicTrueLabels)), classifierOutput.getSortedLabels(0.0));
for (int j = 0; j < labelArray.length; j++) {
ClassificationRate cr = evaluator.getClassificationRate(labelArray[j]);
if (cr != null) {
plotData.get(j)[i] = cr.getF1();
}
}
}
Chart chart = new Chart(600, 300, ChartTheme.Matlab);
chart.setXAxisTitle("Sample Number");
chart.setYAxisTitle("F1 Score");
for (int j = 0; j < labelArray.length; j++) {
Series series = chart.addSeries(labelArray[j], null, plotData.get(j));
series.setMarker(SeriesMarker.NONE);
}
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/Reuters_Semi_Supervised.png", 300);
}
}
| 5,809 | 38.256757 | 126 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/breastcancer/BreastCancerSpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.breastcancer;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.commons.spikes.AHaHA2D;
import com.mancrd.ahah.commons.spikes.SpikeEncoder;
import com.xeiam.datasets.breastcancerwisconsinorginal.BreastCancer;
/**
* Converts the data set into a spike code for use in the AHaH Classifier (or any other optimal linear classifier).
*
* @author alexnugent
*/
public class BreastCancerSpikeEncoder extends SpikeEncoder<BreastCancer> {
private final int treeBinnerDepth = 2;
private final AHaHA2D[] encoders = new AHaHA2D[9];
/**
* Constructor
*/
public BreastCancerSpikeEncoder() {
for (int i = 0; i < encoders.length; i++) {
encoders[i] = new AHaHA2D(treeBinnerDepth);
}
}
@Override
public Set<String> getSpikes(BreastCancer breastCancer) {
Set<String> spikes = new HashSet<String>();
/**
* 1. Sample code number id number
* <p>
* 2. Clump Thickness 1 - 10
* <p>
* 3. Uniformity of Cell Size 1 - 10
* <p>
* 4. Uniformity of Cell Shape 1 - 10
* <p>
* 5. Marginal Adhesion 1 - 10
* <p>
* 6. Single Epithelial Cell Size 1 - 10
* <p>
* 7. Bare Nuclei 1 - 10
* <p>
* 8. Bland Chromatin 1 - 10
* <p>
* 9. Normal Nucleoli 1 - 10
* <p>
* 10. Mitoses 1 - 10
* <p>
* 11. Class: (2 for benign, 4 for malignant)
*/
addToSpikes("ClumpThickness:", encoders[0].putAndParse(breastCancer.getClumpThickness()), spikes);
addToSpikes("UniformityOfCellSize:", encoders[1].putAndParse(breastCancer.getUniformityOfCellSize()), spikes);
addToSpikes("UniformityOfCellShape:", encoders[2].putAndParse(breastCancer.getUniformityOfCellShape()), spikes);
addToSpikes("MarginalAdhesion:", encoders[3].putAndParse(breastCancer.getMarginalAdhesion()), spikes);
addToSpikes("EpithelialCellSize:", encoders[4].putAndParse(breastCancer.getSingleEpithelialCellSize()), spikes);
addToSpikes("BareNuclei:", encoders[5].putAndParse(breastCancer.getBareNuclei()), spikes);
addToSpikes("BlandChromatin:", encoders[6].putAndParse(breastCancer.getBlandChromatin()), spikes);
addToSpikes("NormalNucleoli:", encoders[7].putAndParse(breastCancer.getNormalNucleoli()), spikes);
addToSpikes("Mitoses:", encoders[8].putAndParse(breastCancer.getMitoses()), spikes);
spikes.add("BIAS");
return spikes;
}
private void addToSpikes(String concat, int[] bins, Set<String> spikes) {
for (int i = 0; i < bins.length; i++) {
spikes.add(concat + bins[i]);
}
}
@Override
public short getUniquePositiveID() { // don't worry about this.
return 1;
}
}
| 4,170 | 34.649573 | 116 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/breastcancer/BreastCancerCircuitApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.breastcancer;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder.MemristorType;
import com.xeiam.datasets.breastcancerwisconsinorginal.BreastCancer;
import com.xeiam.datasets.breastcancerwisconsinorginal.BreastCancerDAO;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author alexnugent
*/
public class BreastCancerCircuitApp {
public static DecimalFormat df = new DecimalFormat(".000");
public static void main(String[] args) throws IOException {
File tempDBFile = BreastCancerDAO.init(); // setup data
BreastCancerCircuitApp breastCancerAnalysis = new BreastCancerCircuitApp();
breastCancerAnalysis.go();
BreastCancerDAO.release(tempDBFile); // release data resources
}
private void go() throws IOException {
// initialize the ahahNode
double readPeriod = 1E-5; // increase the learning rate from default
double writePeriod = 1E-5;
int numBias = 15;
int numInputs = 70; // max number of inputs/spikes
MemristorType memristorType = MemristorType.AgChalc;
AHaH21Circuit ahahNodeCircuit = new AHaH21CircuitBuilder().numInputs(numInputs).numBiasInputs(numBias)
.readPeriod(readPeriod).writePeriod(writePeriod).memristorType(memristorType).build();
// initialize the feature factory. This code converts the raw data to a spiking representation.
BreastCancerSpikeEncoder breastCancerSpikeEncoder = new BreastCancerSpikeEncoder();
SpikeConverter spikeConverter = new SpikeConverter(); // converts the spike code produced by the feature factory to one that can be used by the circuit.
// train the classifier--->
List<BreastCancer> breastCancerTrainingData = BreastCancerDAO.selectTrainData();
System.out.println("Learning...");
for (BreastCancer breastCancer : breastCancerTrainingData) {
String[] topicTrueLabels = new String[1];
topicTrueLabels[0] = breastCancer.getCellClass() + "";
long[] spikes = breastCancerSpikeEncoder.encode(breastCancer); // get the spike representation
Set<Integer> convertedSpikes = spikeConverter.convert(spikes);
int superviseSignal = 0;
if (breastCancer.getCellClass() == 2) {
superviseSignal = 1;
}
else {
superviseSignal = -1;
}
System.out.println("Spike Pattern Length = " + convertedSpikes.size());
// System.out.println("Spikes = " + Arrays.toString(convertedSpikes.toArray()));
double y = ahahNodeCircuit.update(convertedSpikes, superviseSignal);
}
System.out.println("Spike Pattern Space = " + breastCancerSpikeEncoder.getSpikePatternSpace());
// Test the classifier
List<BreastCancer> breastCancerTestData = BreastCancerDAO.selectTestData();
System.out.println("Testing...");
Set<String> labels = new HashSet<String>(); // these are the labels we are evaluating the performance of
labels.add("2");
labels.add("4");
// we are testing the performance for a range of confidence values, from 0 to 1.
int numSteps = 100;
double[] confidenceThresholds = new double[numSteps];
double inc = .061 / numSteps;
for (int i = 0; i < confidenceThresholds.length; i++) {
confidenceThresholds[i] = i * inc;
}
// create evaluators for keeping track of performance
ClassificationEvaluator[] evaluators = new ClassificationEvaluator[numSteps];
for (int i = 0; i < evaluators.length; i++) {
evaluators[i] = new ClassificationEvaluator(labels);
}
// run through the test set
for (BreastCancer breastCancer : breastCancerTestData) {
long[] spikes = breastCancerSpikeEncoder.encode(breastCancer);
Set<Integer> convertedSpikes = spikeConverter.convert(spikes);
double y = ahahNodeCircuit.update(convertedSpikes, 0); // NOTE: no supervised labels are passed here.
// true labels for evaluation.
Set<String> trueLabels = new HashSet<String>();
trueLabels.add(breastCancer.getCellClass() + "");
for (int i = 0; i < evaluators.length; i++) {
List<String> labelOutput = new ArrayList<String>();
if (y > confidenceThresholds[i]) {
labelOutput.add("2");
}
else if (y < -confidenceThresholds[i]) {
labelOutput.add("4");
}
evaluators[i].update(trueLabels, labelOutput);
}
}
// plot results---->
double maxF1 = 0;
int cIdx = 0;
double[] accuracy = new double[numSteps];
double[] precision = new double[numSteps];
double[] recall = new double[numSteps];
double[] f1 = new double[numSteps];
for (int i = 0; i < numSteps; i++) {
accuracy[i] = evaluators[i].getAccuracyMicroAve();
precision[i] = evaluators[i].getPrecisionMicroAve();
recall[i] = evaluators[i].getRecallMicroAve();
f1[i] = evaluators[i].getF1MicroAve();
if (f1[i] > maxF1) {// get the best confidence threshold
maxF1 = f1[i];
cIdx = i;
}
}
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
// chart.setChartTitle("Wisconsin Breast Cancer Benchmark - F1=" + df.format(maxF1) + " w/ConfidenceThreshold=" + df.format(confidenceThresholds[cIdx]));
chart.setChartTitle("Breast Cancer - Circuit");
chart.setXAxisTitle("Confidence Threshold");
chart.setYAxisTitle("Score");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
Series accuracy_series = chart.addSeries("Accuracy", confidenceThresholds, accuracy);
accuracy_series.setMarker(SeriesMarker.NONE);
Series precision_series = chart.addSeries("Precision", confidenceThresholds, precision);
precision_series.setMarker(SeriesMarker.NONE);
Series recall_series = chart.addSeries("Recall", confidenceThresholds, recall);
recall_series.setMarker(SeriesMarker.NONE);
Series f1_series = chart.addSeries("F1", confidenceThresholds, f1);
f1_series.setMarker(SeriesMarker.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/Breast_Cancer_Circuit.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 8,122 | 40.025253 | 157 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/breastcancer/BreastCancerFunctionalApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.breastcancer;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.mancrd.ahah.commons.LinkWeight;
import com.xeiam.datasets.breastcancerwisconsinorginal.BreastCancer;
import com.xeiam.datasets.breastcancerwisconsinorginal.BreastCancerDAO;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author alexnugent
*/
public class BreastCancerFunctionalApp {
public static DecimalFormat df = new DecimalFormat(".000");
public static void main(String[] args) throws IOException {
File tempDBFile = BreastCancerDAO.init(); // setup data
BreastCancerFunctionalApp breastCancerAnalysis = new BreastCancerFunctionalApp();
breastCancerAnalysis.go();
BreastCancerDAO.release(tempDBFile); // release data resources
}
private void go() throws IOException {
// initialize the classifier
Classifier classifier = new Classifier();
classifier.setLearningRate(.5f);
// initialize the feature factory. This code converts the raw data to a spiking representation
BreastCancerSpikeEncoder breastCancerSpikeEncoder = new BreastCancerSpikeEncoder();
// train the classifier--->
List<BreastCancer> breastCancerTrainingData = BreastCancerDAO.selectTrainData();
System.out.println("Learning...");
for (BreastCancer breastCancer : breastCancerTrainingData) {
String[] topicTrueLabels = new String[1];
topicTrueLabels[0] = breastCancer.getCellClass() + "";
long[] spikes = breastCancerSpikeEncoder.encode(breastCancer); // get the spike representation
System.out.println(Arrays.toString(spikes));
classifier.update(topicTrueLabels, spikes); // update the classifier.
}
// Test the classifier
List<BreastCancer> breastCancerTestData = BreastCancerDAO.selectTestData();
System.out.println("Testing...");
Set<String> labels = new HashSet<String>(); // these are the labels we are evaluating the performance of
labels.add("2");
labels.add("4");
// we are testing the performance for a range of confidence values, from 0 to 1.
int numSteps = 100;
double[] confidenceThresholds = new double[numSteps];
double inc = 1.0 / numSteps;
for (int i = 0; i < confidenceThresholds.length; i++) {
confidenceThresholds[i] = i * inc;
}
// create evaluators for keeping track of performance
ClassificationEvaluator[] evaluators = new ClassificationEvaluator[numSteps];
for (int i = 0; i < evaluators.length; i++) {
evaluators[i] = new ClassificationEvaluator(labels);
}
// run through the test set
for (BreastCancer breastCancer : breastCancerTestData) {
long[] spikes = breastCancerSpikeEncoder.encode(breastCancer);
ClassifierOutput classifierOutput = classifier.update(null, spikes);// no supervised labels are passed. If labels are passed, classifier will
// continue to learn. Output is best guess *before* learning.
Set<String> trueLabels = new HashSet<String>();
trueLabels.add(breastCancer.getCellClass() + "");
for (int i = 0; i < evaluators.length; i++) {
evaluators[i].update(trueLabels, classifierOutput.getSortedLabels(confidenceThresholds[i]));
}
}
// plot results---->
double maxF1 = 0;
int cIdx = 0;
double[] accuracy = new double[numSteps];
double[] precision = new double[numSteps];
double[] recall = new double[numSteps];
double[] f1 = new double[numSteps];
for (int i = 0; i < numSteps; i++) {
accuracy[i] = evaluators[i].getAccuracyMicroAve();
precision[i] = evaluators[i].getPrecisionMicroAve();
recall[i] = evaluators[i].getRecallMicroAve();
f1[i] = evaluators[i].getF1MicroAve();
if (f1[i] > maxF1) {// get the best confidence threshold
maxF1 = f1[i];
cIdx = i;
}
}
// print the performance of all labels at best confidence threshold
System.out.println(evaluators[cIdx].toString());
List<LinkWeight> linkWeights = classifier.getLinkWeightsForLabel("2");
breastCancerSpikeEncoder.setSpikeLabel(linkWeights);
System.out.println(linkWeights);
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
// chart.setChartTitle("Wisconsin Breast Cancer Benchmark - F1=" + df.format(maxF1) + " w/ConfidenceThreshold=" + df.format(confidenceThresholds[cIdx]));
chart.setChartTitle("Breast Cancer - Functional");
chart.setXAxisTitle("Confidence Threshold");
chart.setYAxisTitle("Score");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
Series accuracy_series = chart.addSeries("Accuracy", confidenceThresholds, accuracy);
accuracy_series.setMarker(SeriesMarker.NONE);
Series precision_series = chart.addSeries("Precision", confidenceThresholds, precision);
precision_series.setMarker(SeriesMarker.NONE);
Series recall_series = chart.addSeries("Recall", confidenceThresholds, recall);
recall_series.setMarker(SeriesMarker.NONE);
Series f1_series = chart.addSeries("F1", confidenceThresholds, f1);
f1_series.setMarker(SeriesMarker.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/Breast_Cancer_Functional.png", 300);
new SwingWrapper(chart).displayChart();
System.out.println("Num AHaH Nodes = " + classifier.getNumUniqueLabels());
}
}
| 7,382 | 41.188571 | 157 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/breastcancer/SpikeConverter.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.breastcancer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* converts a relative index spike encoding to absolute and incremental index.
*
* @author alexnugent
*/
public class SpikeConverter {
private final Map<Long, Integer> spikeMap = new HashMap<Long, Integer>();
public int getMapSize() {
return spikeMap.size();
}
public Set<Integer> convert(long[] inputSpikes) {
Set<Integer> outputSpikes = new HashSet<Integer>();
for (int i = 0; i < inputSpikes.length; i++) {
Integer spikeIndex = spikeMap.get(inputSpikes[i]);
if (spikeIndex == null) {
spikeIndex = spikeMap.size();
spikeMap.put(inputSpikes[i], spikeIndex);
}
outputSpikes.add(spikeIndex);
}
return outputSpikes;
}
}
| 2,333 | 33.323529 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistImagePanel.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
/**
* @author alexnugent
*/
public class MnistImagePanel extends JPanel {
private BufferedImage image;
public MnistImagePanel(int[][] img, int scale) {
image = new BufferedImage(img.length * scale, img[0].length * scale, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < img.length; y++) {
for (int x = 0; x < img[0].length; x++) {
int value = img[y][x] << 16 | img[y][x] << 8 | img[y][x];
image.setRGB(x, y, value);
}
}
scale(scale);
setPreferredSize(new Dimension(img.length * scale, img[0].length * scale));
}
private void scale(int scale) {
int w = image.getWidth();
int h = image.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(image, after);
this.image = after;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
| 2,888 | 33.807229 | 101 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistImageDisplayApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import java.io.File;
import javax.swing.JPanel;
import com.xeiam.datasets.mnist.Mnist;
import com.xeiam.datasets.mnist.MnistDAO;
/**
* @author alexnugent
*/
public class MnistImageDisplayApp {
/**
* This app takes the following arguments:
* <ul>
* <li>int image index (0): Image index [0-69,999]
*
* @param args
*/
public static void main(String[] args) {
File tempDBFile = MnistDAO.init(); // setup data
MnistImageDisplayApp ahahTreeMnist = new MnistImageDisplayApp();
ahahTreeMnist.go(args);
MnistDAO.release(tempDBFile); // release data resources
}
public void go(String[] args) {
int imageIndex = 0;
try {
imageIndex = Integer.parseInt(args[0]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
Mnist mnistData = MnistDAO.selectSingle(imageIndex);
int[][] img = mnistData.getImageMatrix();
// paint the patches
JPanel mnistImagePanel = new MnistImagePanel(img, 10);
new MnistDigitViewer(mnistImagePanel, "Index = " + mnistData.getId() + " label = " + mnistData.getLabel());
}
}
| 2,638 | 31.9875 | 111 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistAhahTreeFeaturePatchApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import gnu.trove.set.hash.TLongHashSet;
import java.io.File;
import javax.swing.JPanel;
import com.mancrd.ahah.commons.spikes.AhahTree;
import com.xeiam.datasets.mnist.Mnist;
import com.xeiam.datasets.mnist.MnistDAO;
/**
* @author alexnugent
*/
public class MnistAhahTreeFeaturePatchApp {
/**
* This app takes the following arguments:
* <ul>
* <li>int numSamples (500): number of MNIST training samples to use
* <li>int patchSize (10): size of patch edge in pixels to feed into the AHaH tree
* <li>int resolution (8): number of features generate=2^resolution. Resolution of 8 will result in 256 features
*
* @param args
*/
public static void main(String[] args) {
File tempDBFile = MnistDAO.init(); // setup data
MnistAhahTreeFeaturePatchApp ahahTreeMnist = new MnistAhahTreeFeaturePatchApp();
ahahTreeMnist.go(args);
MnistDAO.release(tempDBFile); // release data resources
}
public void go(String[] args) {
int numSamples = 500;
int patchSize = 10;
int resolution = 8;
try {
numSamples = Integer.parseInt(args[0]);
patchSize = Integer.parseInt(args[1]);
resolution = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
AhahTree tree = new AhahTree(resolution);
MnistImagePatchStats imagePatchStats = new MnistImagePatchStats(patchSize);
for (int t = 0; t < numSamples; t++) {
Mnist mnistData = MnistDAO.selectSingle(t);
int[][] img = mnistData.getImageMatrix();
for (int i = 0; i < img.length - patchSize; i++) {
for (int j = 0; j < img[0].length - patchSize; j++) {
TLongHashSet patchSpikes = new TLongHashSet();
int[][] patch = new int[patchSize][patchSize];
for (int x = 0; x < patchSize; x++) {
for (int y = 0; y < patchSize; y++) {
if (img[i + x][j + y] > 10) {
patchSpikes.add(x * patchSize + y);
}
patch[x][y] = img[i + x][j + y];
}
}
long spike = tree.encode(patchSpikes.toArray());
imagePatchStats.update(spike, patch);
}
}
if (t % 10 == 0) {
System.out.println("t=" + t + " of " + numSamples);
}
}
// paint the patches
JPanel mnistImagePanel = new MnistImagePanel(imagePatchStats.getAllPatchAverages(.001), 5);
new MnistDigitViewer(mnistImagePanel, "AhahTree MNIST Patch Features");
// // plot patch counts
// double[] counts = imagePatchStats.getCounts();
// Chart chart = new Chart(800, 600);
// chart.setChartTitle("Feature Counts");
// chart.setXAxisTitle("Feature");
// chart.setYAxisTitle("Count");
//
// Series countSeries = chart.addSeries("Counts", null, counts);
// countSeries.setMarker(SeriesMarker.NONE);
//
// new SwingWrapper(chart).displayChart();
}
}
| 4,444 | 34 | 114 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistDigitViewer.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @author timmolter
*/
public class MnistDigitViewer extends JFrame {
public MnistDigitViewer(JPanel jPanel, String title) {
add(jPanel, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle(title);
setResizable(false);
setVisible(true);
}
}
| 1,956 | 35.240741 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.xeiam.datasets.mnist.Mnist;
import com.xeiam.datasets.mnist.MnistDAO;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.ChartType;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author alexnugent
*/
public class MnistApp {
public static DecimalFormat df = new DecimalFormat(".000");
/**
* This app takes the following arguments:
* <ul>
* <li>int poolSize (~8): pool size in pixels</li>
* <li>int patchSize = (~8): size of patch to feed into the AHaH tree</li>
* <li>int encoderResolution = (~10): number of features produced per tree=2^depth</li>
* <li>int numEncoders = (~3): more trees-->more features-->better performance-->longer run-time. Those last few tenths of a percent will cost you dearly</li>
* <li>int numTrainingEpochs = (1): not much point in running more than 2 or 3 times. 1 is epoch is ok.</li>
* <li>int numTrainingSamples = (60000): 60000 is max</li>
* <li>int numTestSamples = (10000): 10000 is max</li>
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File tempDBFile = MnistDAO.init(); // setup data
MnistApp mnistExample = new MnistApp();
mnistExample.go(args);
MnistDAO.release(tempDBFile); // release data resources
}
private void go(String[] args) throws IOException {
int poolSize = 8;
int patchSize = 8;
int encoderResolution = 10;
int numEncoders = 3;
int numTrainingEpochs = 1;
int numTrainingSamples = 60000;
int numTestSamples = 10000;
try {
poolSize = Integer.parseInt(args[0]);
patchSize = Integer.parseInt(args[1]);
encoderResolution = Integer.parseInt(args[2]);
numEncoders = Integer.parseInt(args[3]);
numTrainingEpochs = Integer.parseInt(args[4]);
numTrainingSamples = Integer.parseInt(args[5]);
numTestSamples = Integer.parseInt(args[6]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
if (numTrainingSamples > 60000) {
throw new IllegalArgumentException("Training samples limited to 60,000.");
}
if (numTestSamples > 10000) {
throw new IllegalArgumentException("Training samples limited to 10,000.");
}
MnistSpikeEncoder mnistSpikeEncoder = new MnistSpikeEncoder(poolSize, patchSize, encoderResolution, numEncoders);
Classifier classifier = new Classifier();
// classifier.setLearningRate(.3);// this speeds it up a little.
// train
System.out.println("Training...");
Set<String> labelSet = new HashSet<String>(Arrays.asList(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }));
List<Number> trainingDataX = new ArrayList<Number>();
List<Number> trainingDataY = new ArrayList<Number>();
long totalSpikeEncoderTime = 0L;
long totalClassificationTime = 0L;
for (int e = 0; e < numTrainingEpochs; e++) {
ClassificationEvaluator trainingEvaluator = new ClassificationEvaluator(labelSet);
for (int i = 0; i < numTrainingSamples; i++) {
Mnist mnistData = MnistDAO.selectSingle(i);
String[] trueLabels = new String[] { mnistData.getLabel() + "" };
// get spikes
long spikeStartTime = System.currentTimeMillis();
long[] spikes = mnistSpikeEncoder.encode(mnistData.getImageMatrix());
totalSpikeEncoderTime += System.currentTimeMillis() - spikeStartTime;
// classify
long classifiyStartTime = System.currentTimeMillis();
ClassifierOutput classifierOutput = classifier.update(trueLabels, spikes);
totalClassificationTime += System.currentTimeMillis() - classifiyStartTime;
trainingEvaluator.update(mnistData.getLabel() + "", classifierOutput.getBestGuessLabelAboveThreshold(0));
if (i % 500 == 0) {
System.out.println("sample=" + i + ", F1 = " + trainingEvaluator.getF1MicroAve() + ", numLinks=" + classifier.getNumLinks());
trainingDataX.add(i);
trainingDataY.add(trainingEvaluator.getF1MicroAve());
trainingEvaluator = new ClassificationEvaluator(labelSet);
}
// System.out.println("Spike Pattern Length = " + spikes.length);
}
}
System.out.println("totalSpikeEncoderTime= " + totalSpikeEncoderTime / 1000 + " s");
System.out.println("totalClassificationTime= " + totalClassificationTime / 1000 + " s");
System.out.println("-----------");
System.out.println("totalClassificationTime= " + (double) classifier.getTotalClassificationTimeInNanoSeconds() / 1000000000 + " s");
System.out.println("totalNumSpikesProcessed= " + classifier.getNumSpikesProcessed());
System.out.println("averageSpikesProcessedPerUpdate= " + classifier.getNumSpikesProcessed() / (double) classifier.getNumUpdates());
System.out.println("averageLabelsProcessedPerUpdate= " + classifier.getNumLabelsProcessed() / (double) classifier.getNumUpdates());
System.out.println("spikesProcessingRate= " + classifier.getNumSpikesProcessed() / ((double) classifier.getTotalClassificationTimeInNanoSeconds() / 1000000000) + " spikes/s");
System.out.println("Spike Pattern Space = " + mnistSpikeEncoder.getSpikePatternSpace());
// test
System.out.println("Testing...");
// all confidence threshold we would like to evaluate
int numSteps = 100;
double[] confidenceThresholds = new double[numSteps];
double inc = 1.0 / numSteps;
for (int i = 0; i < confidenceThresholds.length; i++) {
confidenceThresholds[i] = (i - 50) * inc;
}
// evaluators for keeping track of performance for each confidence threshold
ClassificationEvaluator[] evaluators = new ClassificationEvaluator[numSteps];
for (int i = 0; i < evaluators.length; i++) {
evaluators[i] = new ClassificationEvaluator(labelSet);
}
ClassificationEvaluator testEvaluator = new ClassificationEvaluator(labelSet);
for (int i = 60000; i < 60000 + numTestSamples; i++) {
Mnist mnistData = MnistDAO.selectSingle(i);
long[] spikes = mnistSpikeEncoder.encode(mnistData.getImageMatrix());
ClassifierOutput classifierOutput = classifier.update(null, spikes);
Set<String> trueLabels = new HashSet<String>();
trueLabels.add(mnistData.getLabel() + "");
for (int k = 0; k < evaluators.length; k++) {
evaluators[k].update(mnistData.getLabel() + "", classifierOutput.getBestGuessLabelAboveThreshold(confidenceThresholds[k]));
}
testEvaluator.update(mnistData.getLabel() + "", classifierOutput.getBestGuess().getLabelstring());
if (i % 200 == 0) {
System.out.println("sample=" + i + ", F1=" + testEvaluator.getF1MicroAve());
}
}
double bestF1 = 0;
int bestF1idx = 0;
// Plot the performance as a function of confidence threshold--->
double[] accuracy = new double[numSteps];
double[] precision = new double[numSteps];
double[] recall = new double[numSteps];
double[] f1 = new double[numSteps];
for (int i = 0; i < numSteps; i++) {
accuracy[i] = evaluators[i].getAccuracyMicroAve();
precision[i] = evaluators[i].getPrecisionMicroAve();
recall[i] = evaluators[i].getRecallMicroAve();
f1[i] = evaluators[i].getF1MicroAve();
if (f1[i] > bestF1) {// get the best confidence threshold
bestF1 = f1[i];
bestF1idx = i;
}
}
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
// chart.setChartTitle("MNIST Classification App - F1=" + df.format(bestF1) + " w/ConfidenceThreshold=" + df.format(confidenceThresholds[bestF1idx]));
chart.setChartTitle("MNIST - Functional");
chart.setXAxisTitle("Confidence Threshold");
chart.setYAxisTitle("Score");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
Series accuracy_series = chart.addSeries("Accuracy", confidenceThresholds, accuracy);
accuracy_series.setMarker(SeriesMarker.NONE);
Series precision_series = chart.addSeries("Precision", confidenceThresholds, precision);
precision_series.setMarker(SeriesMarker.NONE);
Series recall_series = chart.addSeries("Recall", confidenceThresholds, recall);
recall_series.setMarker(SeriesMarker.NONE);
Series f1_series = chart.addSeries("F1", confidenceThresholds, f1);
f1_series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/MNIST.png", 300);
// Plot the F1 scores of each digit-->
Chart chart2 = new Chart(300, 300, ChartTheme.Matlab);
chart2.setChartTitle("MNIST Digit F1 Scores");
chart2.setXAxisTitle("Digit");
chart2.setYAxisTitle("F1 Score");
chart2.getStyleManager().setChartType(ChartType.Bar);
chart2.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
chart2.getStyleManager().setYAxisMin(.90);
chart2.getStyleManager().setYAxisMax(1.0);
chart2.getStyleManager().setLegendVisible(false);
double[] digitF1Scores = new double[10];
double[] x = new double[10];
for (int i = 0; i < digitF1Scores.length; i++) {
digitF1Scores[i] = evaluators[bestF1idx].getClassificationRate("" + i).getF1();
x[i] = i;
}
chart2.addSeries("Digit F1 Scores", x, digitF1Scores);
new SwingWrapper(chart2).displayChart();
BitmapEncoder.savePNGWithDPI(chart2, "./PLOS_AHAH/Figures/MNIST_Digit_Scores.png", 300);
// plot the training data--->
Chart chart3 = new Chart(600, 400);
chart3.setChartTitle("MNIST Classification App - Training");
chart3.setXAxisTitle("Sample Number");
chart3.setYAxisTitle("F1 Score");
chart3.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
chart3.addSeries("Training", trainingDataX, trainingDataY);
new SwingWrapper(chart3).displayChart();
System.out.println("Num AHaH Nodes = " + classifier.getNumUniqueLabels());
}
}
| 12,039 | 42.941606 | 179 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistImagePatchStats.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* @author alexnugent
*/
public class MnistImagePatchStats {
private final HashMap<Long, PatchStat> features = new HashMap<Long, PatchStat>();
private final int patchSize;
private int numUpdates = 0;
public MnistImagePatchStats(int patchSize) {
this.patchSize = patchSize;
}
public double[] getCounts() {
double[] counts = new double[features.size()];
int i = 0;
for (Long s : features.keySet()) {
counts[i] = features.get(s).getCount();
i++;
}
Arrays.sort(counts);
return counts;
}
public void update(Set<Long> spikes, int[][] patch) {
for (Long spike : spikes) {
update(spike, patch);
}
}
public void update(long spike, int[][] patch) {
PatchStat patchStat = features.get(spike);
if (patchStat == null) {
patchStat = new PatchStat(patchSize);
features.put(spike, patchStat);
}
patchStat.update(patch);
numUpdates++;
}
public int[][] getAllPatchAverages(double minFrequency) {
List<int[][]> patches = new ArrayList<int[][]>();
for (Long reg : features.keySet()) {
double freq = (double) features.get(reg).getCount() / numUpdates;
if (freq > minFrequency) {
patches.add(features.get(reg).getNormPatch());
}
}
int length = (int) (patchSize * Math.ceil((Math.sqrt(patches.size()))));
int[][] bigImage = new int[length][length];
int x = 0;
int y = 0;
for (int[][] img : patches) {
for (int i = 0; i < img.length; i++) {
for (int j = 0; j < img.length; j++) {
bigImage[x + i][y + j] = img[i][j];
}
}
if (x < length - patchSize) {
x += patchSize;
}
else if (y < length - patchSize) {
x = 0;
y += patchSize;
}
else {
break;
}
}
return bigImage;
}
}
class PatchStat {
private final int[][] patchTotals;
private int n = 0;
public PatchStat(int patchSize) {
patchTotals = new int[patchSize][patchSize];
}
public void update(int[][] patch) {
for (int i = 0; i < patch.length; i++) {
for (int j = 0; j < patch[0].length; j++) {
patchTotals[i][j] += patch[i][j];
}
}
n++;
}
public int[][] getAvePatch() {
int[][] avePatch = new int[patchTotals.length][patchTotals[0].length];
for (int i = 0; i < avePatch.length; i++) {
for (int j = 0; j < avePatch[0].length; j++) {
avePatch[i][j] = (int) ((double) patchTotals[i][j] / n);
}
}
return avePatch;
}
public int[][] getNormPatch() {
int[][] avePatch = new int[patchTotals.length][patchTotals[0].length];
int max = patchTotals[0][0];
int min = max;
for (int i = 0; i < avePatch.length; i++) {
for (int j = 0; j < avePatch[0].length; j++) {
if (patchTotals[i][j] > max) {
max = patchTotals[i][j];
}
if (patchTotals[i][j] < min) {
min = patchTotals[i][j];
}
}
}
for (int i = 0; i < avePatch.length; i++) {
for (int j = 0; j < avePatch[0].length; j++) {
avePatch[i][j] = (int) (255 * (double) (patchTotals[i][j] - min) / (max - min));
}
}
return avePatch;
}
public int getCount() {
return n;
}
}
| 4,918 | 25.026455 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/mnist/MnistSpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.mnist;
import gnu.trove.set.hash.TLongHashSet;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.commons.spikes.AhahTree;
import com.mancrd.ahah.commons.spikes.SpikeEncoder;
/**
* @author alexnugent
*/
public class MnistSpikeEncoder extends SpikeEncoder<int[][]> {
private int poolSize = 8;
private int patchSize = 8;
private final AhahTree[] ahahTrees;
/**
* Constructor
*
* @param poolSize
* @param patchSize
* @param resolution
* @param numEncoders
*/
public MnistSpikeEncoder(int poolSize, int patchSize, int resolution, int numEncoders) {
ahahTrees = new AhahTree[numEncoders];
for (int i = 0; i < ahahTrees.length; i++) {
ahahTrees[i] = new AhahTree(resolution);
}
this.poolSize = poolSize;
this.patchSize = patchSize;
}
@Override
public Set<String> getSpikes(int[][] img) {
Set<String> spikes = new HashSet<String>();
for (int i = 0; i < img.length - patchSize; i++) {
for (int j = 0; j < img[0].length - patchSize; j++) {
TLongHashSet patchFeatures = new TLongHashSet();
for (int x = 0; x < patchSize; x++) {
for (int y = 0; y < patchSize; y++) {
if (img[i + x][j + y] > 10) {
patchFeatures.add(x * patchSize + y);
}
}
}
int z0 = i / poolSize;
int z1 = j / poolSize;
for (int k = 0; k < ahahTrees.length; k++) {
StringBuffer b = new StringBuffer();
b.append(k);
b.append(".");
b.append(z0);
b.append(".");
b.append(z1);
b.append(".");
b.append(ahahTrees[k].encode(patchFeatures.toArray()));
spikes.add(b.toString());
}
}
}
spikes.add("BIAS");
return spikes;
}
@Override
public short getUniquePositiveID() {
return 0;
}
}
| 3,397 | 29.612613 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/censusincome/CensusIncomeOverfittingApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.censusincome;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.xeiam.datasets.censusincome.CensusIncome;
import com.xeiam.datasets.censusincome.CensusIncomeDAO;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.SwingWrapper;
/**
* @author alexnugent
*/
public class CensusIncomeOverfittingApp {
public static DecimalFormat df = new DecimalFormat(".000");
/**
* This app takes the following arguments:
* <ul>
* <li>int numTrainingEpochs (5): number of training epochs to use</li>
*
* @param args
*/
public static void main(String[] args) {
CensusIncomeOverfittingApp censusIncomeAnalysis = new CensusIncomeOverfittingApp();
censusIncomeAnalysis.go(args);
}
private void go(String[] args) {
int numTrainingEpochs = 50;
try {
numTrainingEpochs = Integer.parseInt(args[0]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
double[] ydata = new double[numTrainingEpochs];
Classifier classifier = new Classifier();
classifier.setLearningRate(.1f);
classifier.setUnsupervisedConfidenceThreshold(10);
classifier.setUnsupervisedEnabled(false);// prevents unsupervised learning. This allows us to test the performance due to "overfiting".
CensusIncomeSpikeEncoder censusFeatureFactory = new CensusIncomeSpikeEncoder();
// train
System.out.println("training...");
Set<String> labels = new HashSet<String>();
labels.add("true");
labels.add("false");
List<CensusIncome> censusIncomeTrainData = CensusIncomeDAO.getShuffledTrainData();
List<CensusIncome> censusIncomeTestData = CensusIncomeDAO.getShuffledTestData();
for (int i = 0; i < numTrainingEpochs; i++) {
// train
for (CensusIncome censusIncome : censusIncomeTrainData) {
String[] topicTrueLabels = new String[] { censusIncome.isIncomeLessThan50k() + "" };
long[] spikes = censusFeatureFactory.encode(censusIncome);
classifier.update(topicTrueLabels, spikes);
}
// test
ClassificationEvaluator evaluator = new ClassificationEvaluator(labels);
for (CensusIncome censusIncome : censusIncomeTestData) {
long[] spikes = censusFeatureFactory.encode(censusIncome);
ClassifierOutput classifierOutput = classifier.update(null, spikes);// passing null for labels. Since unsupervised learning is turned off, classifier cannot use this test data to improve
// itself.
String trueLabel = censusIncome.isIncomeLessThan50k() + "";
// evaluator.update(trueLabels, classifierOutput.getSortedLabels(.3));
evaluator.update(trueLabel, classifierOutput.getBestGuessLabelAboveThreshold(0));
}
System.out.println(" epoch " + (i + 1) + ", Classification Rate=" + evaluator.getAccuracyMicroAve());
ydata[i] = evaluator.getAccuracyMicroAve();
}
Chart chart = new Chart(800, 600);
chart.setChartTitle("Test Performance vs Number of Training Epochs");
chart.setXAxisTitle("Trining Epochs");
chart.setYAxisTitle("F1 Micro-Averaged Score @ Confidence Threshold=.25");
Series accuracy_series = chart.addSeries("F1", null, ydata);
accuracy_series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
}
}
| 5,142 | 38.561538 | 194 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/censusincome/CensusIncomeSpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.censusincome;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.commons.spikes.AHaHA2D;
import com.mancrd.ahah.commons.spikes.SpikeEncoder;
import com.xeiam.datasets.censusincome.CensusIncome;
/**
* @author alexnugent
*/
public class CensusIncomeSpikeEncoder extends SpikeEncoder<CensusIncome> {
AHaHA2D ageBinner = new AHaHA2D(8);
AHaHA2D fnlwgtBinner = new AHaHA2D(8);
AHaHA2D educationNumBinner = new AHaHA2D(8);
AHaHA2D capitalGainBinner = new AHaHA2D(8);
AHaHA2D capitalLossBinner = new AHaHA2D(8);
AHaHA2D hoursPerWeekBinner = new AHaHA2D(8);
@Override
public Set<String> getSpikes(CensusIncome censusIncome) {
Set<String> spikes = new HashSet<String>();
// Age
int[] ageFeatures = ageBinner.putAndParse(censusIncome.getAge());
for (int i = 0; i < ageFeatures.length; i++) {
spikes.add(("0:" + ageFeatures[i]));
}
// Workclass
spikes.add(("1:" + censusIncome.getWorkclass()));
// FnlWght
int[] fnlwgtFeatures = fnlwgtBinner.putAndParse(censusIncome.getFnlwgt());
for (int i = 0; i < fnlwgtFeatures.length; i++) {
spikes.add(("2:" + fnlwgtFeatures[i]));
}
// Education
spikes.add(("3:" + censusIncome.getEducation()));
// educationNum
int[] educationNumFeatures = educationNumBinner.putAndParse(censusIncome.getEducationNum());
for (int i = 0; i < educationNumFeatures.length; i++) {
spikes.add(("4: " + educationNumFeatures[i]));
}
// maritalStatus
spikes.add(("5:" + censusIncome.getMaritalStatus()));
// occupation
spikes.add(("6:" + censusIncome.getOccupation()));
// relationship
spikes.add(("7:" + censusIncome.getRelationship()));
// race
spikes.add(("8:" + censusIncome.getRace()));
// sex
spikes.add(("9:" + censusIncome.getSex()));
// capitalGain
int[] capitalGainFeatures = capitalGainBinner.putAndParse(censusIncome.getCapitalGain());
for (int i = 0; i < capitalGainFeatures.length; i++) {
spikes.add(("10:" + capitalGainFeatures[i]));
}
// capitalLoss
int[] capitalLossFeatures = capitalLossBinner.putAndParse(censusIncome.getCapitalLoss());
for (int i = 0; i < capitalLossFeatures.length; i++) {
spikes.add(("11:" + capitalLossFeatures[i]));
}
// hoursPerWeek
int[] hoursPerWeekFeatures = hoursPerWeekBinner.putAndParse(censusIncome.getHoursPerWeek());
for (int i = 0; i < hoursPerWeekFeatures.length; i++) {
spikes.add(("12:" + hoursPerWeekFeatures[i]));
}
// native country
spikes.add(("13:" + censusIncome.getNativeCountry()));
// income less than 50k <--this is what we are trying to predict. DO NOT ADD!
spikes.add("BIAS");
return spikes;
}
@Override
public short getUniquePositiveID() {
return 0;
}
@Override
public String getSpikeLabel(int spike) {
return null;
}
}
| 4,397 | 34.756098 | 96 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/classifier/censusincome/CensusIncomeApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.classifier.censusincome;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.classifier.ClassificationEvaluator;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.xeiam.datasets.censusincome.CensusIncome;
import com.xeiam.datasets.censusincome.CensusIncomeDAO;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author alexnugent
*/
public class CensusIncomeApp {
public static DecimalFormat df = new DecimalFormat(".000");
/**
* This app takes the following arguments:
* <ul>
* <li>int numTrainingEpochs (1): number of training epochs to use</li>
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File tempDBFile = CensusIncomeDAO.init(); // setup data
CensusIncomeApp censusIncomeAnalysis = new CensusIncomeApp();
censusIncomeAnalysis.go(args);
CensusIncomeDAO.release(tempDBFile); // release data resources
}
private void go(String[] args) throws IOException {
int numTrainingEpochs = 1;
try {
numTrainingEpochs = Integer.parseInt(args[0]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
Classifier classifier = new Classifier();
// classifier.setLearningRate(.01f);
CensusIncomeSpikeEncoder censusSpikeEncoder = new CensusIncomeSpikeEncoder();
// train
System.out.println("training...");
Set<String> labels = new HashSet<String>();
labels.add("true");
labels.add("false");
for (int i = 0; i < numTrainingEpochs; i++) {
ClassificationEvaluator evaluator = new ClassificationEvaluator(labels);
List<CensusIncome> censusIncomeTrainData = CensusIncomeDAO.getShuffledTrainData();
for (CensusIncome censusIncome : censusIncomeTrainData) {
String[] topicTrueLabels = new String[] { censusIncome.isIncomeLessThan50k() + "" };
long[] spikes = censusSpikeEncoder.encode(censusIncome);
ClassifierOutput classifierOutput = classifier.update(topicTrueLabels, spikes);
evaluator.update(censusIncome.isIncomeLessThan50k() + "", classifierOutput.getBestGuessLabelAboveThreshold(0.0));
// System.out.println("Spike Pattern Length = " + spikes.length);
}
System.out.println(" epoch " + (i + 1) + ", Classification Rate=" + evaluator.getAccuracyMicroAve());
}
System.out.println("totalClassificationTime= " + (double) classifier.getTotalClassificationTimeInNanoSeconds() / 1000000000 + " s");
System.out.println("totalNumSpikesProcessed= " + classifier.getNumSpikesProcessed());
System.out.println("averageSpikesProcessedPerUpdate= " + classifier.getNumSpikesProcessed() / (double) classifier.getNumUpdates());
System.out.println("averageLabelsProcessedPerUpdate= " + classifier.getNumLabelsProcessed() / (double) classifier.getNumUpdates());
System.out.println("spikesProcessingRate= " + classifier.getNumSpikesProcessed() / ((double) classifier.getTotalClassificationTimeInNanoSeconds() / 1000000000) + " spikes/s");
System.out.println("Spike Pattern Space = " + censusSpikeEncoder.getSpikePatternSpace());
// test
System.out.println("testing...");
List<CensusIncome> censusIncomeTestData = CensusIncomeDAO.getShuffledTestData();
int numSteps = 100;
double[] confidenceThresholds = new double[numSteps];
double inc = 1.0 / numSteps;
for (int i = 0; i < confidenceThresholds.length; i++) {
confidenceThresholds[i] = i * inc;
}
ClassificationEvaluator[] evaluators = new ClassificationEvaluator[numSteps];
for (int i = 0; i < evaluators.length; i++) {
evaluators[i] = new ClassificationEvaluator(labels);
}
for (CensusIncome censusIncome : censusIncomeTestData) {
long[] spikes = censusSpikeEncoder.encode(censusIncome);
ClassifierOutput classifierOutput = classifier.update(null, spikes);
Set<String> trueLabels = new HashSet<String>();
trueLabels.add(censusIncome.isIncomeLessThan50k() + "");
for (int i = 0; i < evaluators.length; i++) {
evaluators[i].update(trueLabels, classifierOutput.getSortedLabels(confidenceThresholds[i]));
}
}
// plot results
double maxF1 = 0;
int cIdx = 0;
double[] accuracy = new double[numSteps];
double[] precision = new double[numSteps];
double[] recall = new double[numSteps];
double[] f1 = new double[numSteps];
for (int i = 0; i < numSteps; i++) {
accuracy[i] = evaluators[i].getAccuracyMicroAve();
precision[i] = evaluators[i].getPrecisionMicroAve();
recall[i] = evaluators[i].getRecallMicroAve();
f1[i] = evaluators[i].getF1MicroAve();
if (f1[i] > maxF1) {// get the best confidence threshold
maxF1 = f1[i];
cIdx = i;
}
}
// print the performance of all labels at best confidence threshold
System.out.println(evaluators[cIdx].toString());
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
// chart.setChartTitle("Census Income App - F1=" + df.format(maxF1) + " w/ConfidenceThreshold=" + df.format(confidenceThresholds[cIdx]));
chart.setChartTitle("Census Income - Functional");
chart.setXAxisTitle("Confidence Threshold");
chart.setYAxisTitle("Score");
Series accuracy_series = chart.addSeries("Accuracy", confidenceThresholds, accuracy);
accuracy_series.setMarker(SeriesMarker.NONE);
Series precision_series = chart.addSeries("Precision", confidenceThresholds, precision);
precision_series.setMarker(SeriesMarker.NONE);
Series recall_series = chart.addSeries("Recall", confidenceThresholds, recall);
recall_series.setMarker(SeriesMarker.NONE);
Series f1_series = chart.addSeries("F1", confidenceThresholds, f1);
f1_series.setMarker(SeriesMarker.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/Census_Income.png", 300);
new SwingWrapper(chart).displayChart();
System.out.println("Num AHaH Nodes = " + classifier.getNumUniqueLabels());
}
}
| 7,966 | 40.712042 | 179 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/predictor/SimpleTemporalBufferSpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.predictor;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import com.mancrd.ahah.commons.spikes.AHaHA2D;
import com.mancrd.ahah.commons.spikes.SpikeEncoder;
/**
* @author alexnugent
*/
public class SimpleTemporalBufferSpikeEncoder extends SpikeEncoder<Double> {
private final AHaHA2D binner;
private final LinkedList<Integer> buffer;
private final int bufferSize;
/**
* Constructor
*
* @param bufferSize
* @param binnerDepth
*/
public SimpleTemporalBufferSpikeEncoder(int bufferSize, int binnerDepth) {
this.bufferSize = bufferSize;
buffer = new LinkedList<Integer>();
binner = new AHaHA2D(binnerDepth);
}
@Override
public Set<String> getSpikes(Double signal) {
buffer.add(binner.put(signal));
if (buffer.size() > bufferSize) {
buffer.removeFirst();
}
String[] spikes = new String[buffer.size()];
if (buffer.size() < bufferSize) {
return array2Set(spikes);
}
for (int i = 0; i < spikes.length; i++) {
spikes[i] = i + "." + buffer.get(i);
}
// System.out.println(Arrays.toString(spikes));
return array2Set(spikes);
}
private Set<String> array2Set(String[] spikes) {
Set<String> spikesSet = new HashSet<String>();
for (int i = 0; i < spikes.length; i++) {
if (spikes[i] == null) {
spikesSet.add("0");
}
else {
spikesSet.add(spikes[i]);
}
}
return spikesSet;
}
public AHaHA2D getBinner() {
return binner;
}
@Override
public short getUniquePositiveID() {
// TODO Auto-generated method stub
return 0;
}
}
| 3,143 | 27.581818 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/predictor/ComplexSignalPredictionApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.predictor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.classifier.Classifier;
import com.mancrd.ahah.classifier.ClassifierOutput;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesColor;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author alexnugent
*/
public class ComplexSignalPredictionApp {
private int timeSteps;
private int testDuration;
// define the complex signal
private final double[] amplitudes = { .1, .5, .9, .5, .9 };
private final double[] periods = { .05, .1, .2, .08, .15 };
private final double[] phases = { .1, 0, .2, .9, .3 };
private final double drift = 0; // .01;
// parameters
private final double reconstructionConfidenceTreshold = 0;
private final int temporalBufferSize = 300; // higher for longer memory of past
private final int spikeEncoderBinnerDepth = 4; // higher for more resolution
private final double ke = .001; // exponential moving average of error.
private double[] signalData;
private double[] signalPredictionData;
private double[] error;
private final Classifier classifier = new Classifier();
private final ComplexSignalGenerator signalGenerator = new ComplexSignalGenerator(amplitudes, periods, phases, drift);
private final SimpleTemporalBufferSpikeEncoder simpleTemporalBufferSpikeEncoder = new SimpleTemporalBufferSpikeEncoder(temporalBufferSize, spikeEncoderBinnerDepth);
/**
* This app takes the following arguments:
* <ul>
* <li>int mode (1)
* <li>int timeSteps (10000)
* <li>int testDuration (300)
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ComplexSignalPredictionApp complexSignalPrediction = new ComplexSignalPredictionApp();
int mode = 1;
int timeSteps = 10000;
int testDuration = 300;
try {
mode = Integer.parseInt(args[0]);
timeSteps = Integer.parseInt(args[1]);
testDuration = Integer.parseInt(args[2]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
complexSignalPrediction.init(timeSteps, testDuration);
if (mode == 0) {
complexSignalPrediction.nonRecursivePredict();
}
else if (mode == 1) {
complexSignalPrediction.recursivePredict();
}
else {
throw new IllegalArgumentException("mode invalid");
}
}
private void init(int timeSteps, int testDuration) {
signalData = new double[timeSteps];
signalPredictionData = new double[timeSteps];
error = new double[timeSteps];
this.timeSteps = timeSteps;
this.testDuration = testDuration;
this.classifier.setLearningRate(.1f);
}
private String[] getTrueLabels(double signal) {
String[] labels = { simpleTemporalBufferSpikeEncoder.getBinner().put(signal) + "" };
return labels;
}
private void nonRecursivePredict() throws IOException {
double signalThen = 0;
double signalNow = 0;
for (int i = 0; i < timeSteps; i++) {
signalNow = signalGenerator.getSignal();
long[] signalSpikes = simpleTemporalBufferSpikeEncoder.encode(signalThen);
String[] trueLabels = getTrueLabels(signalNow);
// train the classifier with the old signal data to learn the current signal data
ClassifierOutput classifierOutput = classifier.update(trueLabels, signalSpikes);
// reconstruct the predicted spike code back into a real-value signal
double signalPrediction = reconstruct(classifierOutput, reconstructionConfidenceTreshold);
signalData[i] = signalNow;
signalPredictionData[i] = signalPrediction;
// error is computing as an exponential running average.
if (i == 0) {
error[i] = Math.abs(signalPrediction - signalNow);
}
else {
error[i] = (1 - ke) * error[i - 1] + ke * Math.abs(signalPrediction - signalNow);
}
signalThen = signalNow;
}
plotError(error);
plotSignal(signalData, signalPredictionData);
}
private void recursivePredict() throws IOException {
double signalThen = 0.0;
double signalNow = 0.0;
for (int i = 0; i < timeSteps; i++) {
if (i < timeSteps - testDuration) { // learn
signalNow = signalGenerator.getSignal();
String[] trueLabels = getTrueLabels(signalNow);
long[] spikes = simpleTemporalBufferSpikeEncoder.encode(signalThen);
ClassifierOutput classifierOutput = classifier.update(trueLabels, spikes);
signalData[i] = signalNow;
signalPredictionData[i] = reconstruct(classifierOutput, reconstructionConfidenceTreshold);
// System.out.println("Spike Pattern Length = " + spikes.length);
}
else { // recursive prediction. feed output back as input.
long[] signalSpikes = simpleTemporalBufferSpikeEncoder.encode(signalThen);
ClassifierOutput classifierOutput = classifier.update(null, signalSpikes);
signalNow = reconstruct(classifierOutput, reconstructionConfidenceTreshold);
signalData[i] = signalGenerator.getSignal();
signalPredictionData[i] = signalNow;
}
signalThen = signalNow;
}
System.out.println("Spike Pattern Space = " + simpleTemporalBufferSpikeEncoder.getSpikePatternSpace());
plotSignal(signalData, signalPredictionData);
System.out.println("Num AHaH Nodes = " + classifier.getNumUniqueLabels());
}
private double reconstruct(ClassifierOutput classifierOutput, double confidenceThreshold) {
simpleTemporalBufferSpikeEncoder.getBinner();
classifierOutput.getBestGuess();
classifierOutput.getBestGuess().getLabelstring();
return simpleTemporalBufferSpikeEncoder.getBinner().get(Integer.parseInt(classifierOutput.getBestGuess().getLabelstring()));
}
private void plotSignal(double[] signal, double[] signalPrediction) throws IOException {
List<Number> predictionData1 = new ArrayList<Number>();
List<Number> predictionData2 = new ArrayList<Number>();
List<Number> signalData = new ArrayList<Number>();
List<Number> xData0 = new ArrayList<Number>();
List<Number> xData1 = new ArrayList<Number>();
List<Number> xData2 = new ArrayList<Number>();
for (int i = timeSteps - (int) (1.33 * testDuration); i < timeSteps; i++) {
xData0.add(i);
signalData.add(signal[i]);
if (i < timeSteps - testDuration) {
predictionData1.add(signalPrediction[i]);
xData1.add(i);
}
else {
predictionData2.add(signalPrediction[i]);
xData2.add(i);
}
}
Chart chart = new Chart(600, 300, ChartTheme.Matlab);
chart.getStyleManager().setAxisTicksVisible(false);
chart.getStyleManager().setPlotGridLinesVisible(false);
chart.setXAxisTitle("Time Step");
chart.setYAxisTitle("Signal Value");
chart.getStyleManager().setAxisTitlesVisible(false);
Series signal1_series = chart.addSeries("Signal", xData0, signalData);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
signal1_series.setLineStyle(SeriesLineStyle.NONE);
signal1_series.setMarkerColor(SeriesColor.PINK);
Series signalPrediction1_series = chart.addSeries("Learning", xData1, predictionData1);
signalPrediction1_series.setMarker(SeriesMarker.NONE);
signalPrediction1_series.setLineColor(SeriesColor.BLACK);
signalPrediction1_series.setLineStyle(SeriesLineStyle.DOT_DOT);
Series signalPrediction2_series = chart.addSeries("Recursive Prediction", xData2, predictionData2);
signalPrediction2_series.setMarker(SeriesMarker.NONE);
signalPrediction2_series.setLineColor(SeriesColor.BLACK);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/Predictor_Mode_1.png", 300);
new SwingWrapper(chart).displayChart();
}
private void plotError(double[] error) {
Chart chart = new Chart(900, 350);
chart.setChartTitle("Signal Prediction");
chart.setXAxisTitle("Time Step");
chart.setYAxisTitle("Error");
Series error_series = chart.addSeries("Error", null, error);
error_series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
}
}
| 9,901 | 34.364286 | 166 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/predictor/ComplexSignalGenerator.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.predictor;
import java.util.Arrays;
/**
* @author alexnugent
*/
public class ComplexSignalGenerator {
private double[] amplitudes;
private double[] periods;
private double[] phases;
private double drift;
private double t = 0;
public ComplexSignalGenerator(int numSources) {
this.amplitudes = new double[numSources];
this.periods = new double[numSources];
this.phases = new double[numSources];
for (int i = 0; i < periods.length; i++) {
amplitudes[i] = Math.random();
phases[i] = Math.random();
periods[i] = Math.random();
}
drift = 0;// Math.random();
System.out.println(Arrays.toString(amplitudes));
System.out.println(Arrays.toString(phases));
System.out.println(Arrays.toString(periods));
}
/**
* Constructor
*
* @param amplitudes
* @param periods
* @param phases
* @param drift
*/
public ComplexSignalGenerator(double[] amplitudes, double[] periods, double[] phases, double drift) {
this.amplitudes = amplitudes;
this.periods = periods;
this.phases = phases;
this.drift = drift;
}
public double getSignal() {
double z = 0;
for (int i = 0; i < amplitudes.length; i++) {
z += amplitudes[i] * Math.sin(periods[i] * t - phases[i]);
}
t++;
return z + drift * t;
}
public double[] getAmplitudes() {
return amplitudes;
}
public void setAmplitudes(double[] amplitudes) {
this.amplitudes = amplitudes;
}
public double[] getPeriods() {
return periods;
}
public void setPeriods(double[] periods) {
this.periods = periods;
}
public double[] getPhases() {
return phases;
}
public void setPhases(double[] phases) {
this.phases = phases;
}
public double getDrift() {
return drift;
}
public void setDrift(double drift) {
this.drift = drift;
}
} | 3,377 | 24.590909 | 103 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/combinatorial/TravelingSalesman.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.combinatorial;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import com.mancrd.ahah.combinatorial.BinarySetConverter;
import com.mancrd.ahah.combinatorial.Valuator;
/**
* @author alexnugent
*/
public class TravelingSalesman implements Valuator {
private List<City> cities;
/**
* Constructor
*
* @param numCities
*/
public TravelingSalesman(int numCities) {
this.cities = new LinkedList<City>();
Random rand = new Random();
for (int i = 0; i < numCities; i++) {
cities.add(new City(rand.nextGaussian(), rand.nextGaussian(), "" + i));
}
}
@Override
public int getMaxBitLength() {
return BinarySetConverter.getNumEncodingBits(cities.size());
}
@Override
public float getConfigValue(boolean[] path) {
int[] cityPath = BinarySetConverter.getSet(cities.size(), path);
float d = 0;
for (int i = 0; i < cityPath.length - 1; i++) {
City a = cities.get(cityPath[i]);
City b = cities.get(cityPath[i + 1]);
d += a.distanceTo(b);
}
return d;
}
}
class City {
private final double xPosition;
private final double yPosition;
private final String id;
/**
* Constructor
*
* @param xPosition
* @param yPosition
* @param id
*/
public City(double xPosition, double yPosition, String id) {
this.xPosition = xPosition;
this.yPosition = yPosition;
this.id = id;
}
public double getXPosition() {
return xPosition;
}
public double getYPosition() {
return yPosition;
}
public double distanceTo(City otherCity) {
return Math.sqrt(Math.pow(xPosition - otherCity.getXPosition(), 2) + Math.pow(yPosition - otherCity.yPosition, 2));
}
@Override
public String toString() {
return id;
}
}
| 3,292 | 25.991803 | 119 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/combinatorial/StrikeSearchApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.combinatorial;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.combinatorial.RandomSearch;
import com.mancrd.ahah.combinatorial.StrikeSearch;
import com.mancrd.ahah.commons.utils.RunningStat;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Compares an AHaH "strike" search to random guessing to show that its directed search. Shows relationship between learning rate and the time and quality of solution. Default variable result in a
* test that takes about 30-60 minutes to run.
*
* @author alexnugent
*/
public class StrikeSearchApp {
private final int numAttempts = 200;
private final int maxAttempts = 5000000; // stops the search if it does not terminate before this many steps.
/**
* optimization will terminate automatically when the same solution is generated 5 times.
* if no convergence, optimization will terminate at this number of attempts.
*/
private int maxSteps = 0;
/** strike experiment */
private final List<Number> strikeDistances = new ArrayList<Number>();
private final List<Number> strikeConvergenceTimes = new ArrayList<Number>();
private final List<Number> strikeLearnRates = new ArrayList<Number>();
/** random experiment */
private final List<Number> randDistances = new ArrayList<Number>();
private final List<Number> randConvergenceTimes = new ArrayList<Number>();
/** the network of cities */
TravelingSalesman travelingSalesman;
/**
* This app takes the following arguments:
* <ul>
* <li>numCities (64) : smaller number of cities, faster this will run. Obviously.
* <li>minLearningRate (.00015f) : minimum learning rate
* <li>maxLearningRate (.0035f) : maximum learning rate
* <p>
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
StrikeSearchApp combOptApp = new StrikeSearchApp();
combOptApp.go(args);
}
private void go(String[] args) throws IOException {
int numCities = 64;
float minLearningRate = .00015f;
float maxLearningRate = .0035f;
try {
numCities = Integer.parseInt(args[0]);
minLearningRate = Float.parseFloat(args[1]);
maxLearningRate = Float.parseFloat(args[1]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
travelingSalesman = new TravelingSalesman(numCities);
aHaHStrikeSearch(numCities, minLearningRate, maxLearningRate);
randomSearch(numCities);
plotAHaHAndRand();
plotLearningRateVsValue();
plotLearningRateVsTimeToSolution();
}
/**
* finds solutions using the "strike" method
*/
public void aHaHStrikeSearch(int numCities, float minLearningRate, float maxLearningRate) {
RunningStat rs = new RunningStat();
for (int i = 0; i < numAttempts; i++) {
float learningRate = (float) (Math.random() * (maxLearningRate - minLearningRate) + minLearningRate);
StrikeSearch strikeSearch = new StrikeSearch(travelingSalesman, maxAttempts, learningRate, learningRate);
strikeSearch.run();
strikeDistances.add(strikeSearch.getBestValue());
strikeConvergenceTimes.add(strikeSearch.getConvergenceAttempts());
strikeLearnRates.add(learningRate);
if (strikeSearch.getConvergenceAttempts() > maxSteps) {
maxSteps = strikeSearch.getConvergenceAttempts();
}
System.out.println("AHAH: " + i + " of " + numAttempts + " : " + strikeSearch.getBestValue() + ", " + strikeSearch.getConvergenceAttempts());
rs.put(strikeSearch.getNumNodes());
System.out.println("Num AHaH Nodes " + i + " of " + numAttempts + " : " + strikeSearch.getNumNodes());
}
System.out.println("Num AHaH Nodes Ave. = " + rs.getAverage() + ", " + rs.getStandardDeviation());
}
/**
* finds random solutions. Alpha and beta are zero, resulting in guessing of random binary vectors.
*/
public void randomSearch(int numCities) {
for (int i = 0; i < numAttempts; i++) {
int terminate = (int) (Math.random() * maxSteps); // sample from range
TravelingSalesman travelingSalesman = new TravelingSalesman(numCities);
RandomSearch randomSearch = new RandomSearch(travelingSalesman, terminate);
randomSearch.run();
randDistances.add(randomSearch.getBestValue());
randConvergenceTimes.add(randomSearch.getConvergenceAttempts());
System.out.println("RAND: " + i + " of " + numAttempts + " : " + randomSearch.getBestValue() + ", " + randomSearch.getConvergenceAttempts());
}
}
private void plotAHaHAndRand() throws IOException {
Chart chart = new Chart(600, 250, ChartTheme.Matlab);
chart.setXAxisTitle("Convergence Time");
chart.setYAxisTitle("Distance");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideNE);
Series strikeSeries = chart.addSeries("AHaH", strikeConvergenceTimes, strikeDistances);
strikeSeries.setLineStyle(SeriesLineStyle.NONE);
Series randSeries = chart.addSeries("Random", randConvergenceTimes, randDistances);
randSeries.setLineStyle(SeriesLineStyle.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/TSP_AHaHAndRandom.png", 300);
new SwingWrapper(chart).displayChart();
}
private void plotLearningRateVsTimeToSolution() throws IOException {
Chart chart = new Chart(300, 250, ChartTheme.Matlab);
chart.setXAxisTitle("Learning Rate");
chart.setYAxisTitle("Convergence Time");
chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideNE);
Series fffSeries = chart.addSeries("Fractal Flow Fabric", strikeLearnRates, strikeConvergenceTimes);
fffSeries.setLineStyle(SeriesLineStyle.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/TSP_ConvergenceTime.png", 300);
new SwingWrapper(chart).displayChart();
}
private void plotLearningRateVsValue() throws IOException {
Chart chart = new Chart(300, 250, ChartTheme.Matlab);
chart.setXAxisTitle("Learning Rate");
chart.setYAxisTitle("Distance");
chart.getStyleManager().setLegendVisible(false);
Series fffSeries = chart.addSeries("Fractal Flow Fabric", strikeLearnRates, strikeDistances);
fffSeries.setLineStyle(SeriesLineStyle.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/TSP_MaxValue.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 8,231 | 38.014218 | 196 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/RoboticArmSpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import java.beans.PropertyChangeEvent;
import java.util.HashSet;
import java.util.Set;
import com.jme3.math.Vector3f;
import com.mancrd.ahah.commons.spikes.AHaHA2D;
import com.mancrd.ahah.commons.spikes.SpikeEncoder;
import com.xeiam.proprioceptron.roboticarm.RoboticArmGameState;
/**
* @author timmolter
*/
public class RoboticArmSpikeEncoder extends SpikeEncoder<PropertyChangeEvent> {
private static final int TREE_DEPTH = 3;
AHaHA2D difTreeBinner = new AHaHA2D(TREE_DEPTH);
AHaHA2D distanceTreeBinner = new AHaHA2D(TREE_DEPTH);
AHaHA2D jointTreeBinner = new AHaHA2D(TREE_DEPTH);
AHaHA2D jointCommandBinner = new AHaHA2D(TREE_DEPTH);
@Override
public Set<String> getSpikes(PropertyChangeEvent pce) {
Set<String> feature = new HashSet<String>();
// EnvState oldEnvState = (EnvState) pce.getOldValue();
RoboticArmGameState newEnvState = (RoboticArmGameState) pce.getNewValue();
// Here's the info for the robotic arm that we have to work with:
// private final float distLeftEye;
// private final float distRightEye;
// private final float distHead;
// private final Vector3f[] relativePositions;
// private final boolean wasCollision;
appendToFeature("DISTANCE_RIGHT_EYE=", distanceTreeBinner.putAndParse(newEnvState.getEnvState().getDistRightEye()), feature);
appendToFeature("DISTANCE_LEFT_EYE=", distanceTreeBinner.putAndParse(newEnvState.getEnvState().getDistLeftEye()), feature);
appendToFeature("DISTANCE_DIF_H2RH=", difTreeBinner.putAndParse(newEnvState.getEnvState().getDistHead() - newEnvState.getEnvState().getDistRightEye()), feature);
appendToFeature("DISTANCE_DIF_H2LH=", difTreeBinner.putAndParse(newEnvState.getEnvState().getDistHead() - newEnvState.getEnvState().getDistLeftEye()), feature);
appendToFeature("DISTANCE_DIF_EYES=", difTreeBinner.putAndParse(newEnvState.getEnvState().getDistRightEye() - newEnvState.getEnvState().getDistLeftEye()), feature);
for (int i = 0; i < newEnvState.getEnvState().getRelativePositions().length; i++) {
Vector3f jointVector = newEnvState.getEnvState().getRelativePositions()[i];
appendToFeature("JOINT_" + i + "_X=", jointTreeBinner.putAndParse(jointVector.getX()), feature);
appendToFeature("JOINT_" + i + "_Z=", jointTreeBinner.putAndParse(jointVector.getZ()), feature);
}
return feature;
}
/**
* @param header
* @param binnerStates
* @param spikes - the spike set we're adding spikes to
*/
private void appendToFeature(String header, int[] binnerStates, Set<String> spikes) {
for (int i = 0; i < binnerStates.length; i++) {
spikes.add(header + binnerStates[i]);
}
}
/**
* Given the number of joints, how many possible unique features are there
*
* @param numJoints
* @return
*/
public int getTotalNumberOfPossibleFeatures(int numJoints) {
int numberDistanceFeatures = (int) (2 * 2 * Math.pow(2, TREE_DEPTH));
int numberDifFeatures = (int) (3 * 2 * Math.pow(2, TREE_DEPTH));
int numberJointFeatures = (int) (2 * 2 * Math.pow(2, TREE_DEPTH)) * numJoints;
return numberDistanceFeatures + numberDifFeatures + numberJointFeatures;
}
@Override
public short getUniquePositiveID() {
// TODO Auto-generated method stub
return 0;
}
}
| 4,823 | 40.586207 | 168 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/AbstractRoboticArmApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.jme3.system.AppSettings;
import com.mancrd.ahah.samples.motorcontroller.roboticarm.data.RoboticArmRaw;
import com.mancrd.ahah.samples.motorcontroller.roboticarm.data.RoboticArmRawDAO;
import com.xeiam.proprioceptron.roboticarm.JointCommand;
import com.xeiam.proprioceptron.roboticarm.RoboticArm;
import com.xeiam.proprioceptron.roboticarm.Score;
import com.xeiam.yank.DBConnectionManager;
import com.xeiam.yank.PropertiesUtils;
/**
* @author timmolter
*/
public abstract class AbstractRoboticArmApp implements PropertyChangeListener {
protected RoboticArm roboticArm;
protected final List<Score> scores = new ArrayList<Score>();
private int numJoints;
/**
* Constructor
*/
protected void init(int numJoints) {
this.numJoints = numJoints;
// disable jme3 logging
Logger.getLogger("com.jme3").setLevel(Level.SEVERE);
Properties dbprops = PropertiesUtils.getPropertiesFromClasspath("DB.properties");
DBConnectionManager.INSTANCE.init(dbprops);
RoboticArmRawDAO.dropTable();
RoboticArmRawDAO.createTable();
roboticArm.setShowSettings(false);
AppSettings settings = new AppSettings(true);
settings.setResolution(500, 500);
settings.setTitle("Robotic Arm App - " + numJoints + " Joints");
roboticArm.setSettings(settings);
roboticArm.addChangeListener(this);
}
@Override
public void propertyChange(PropertyChangeEvent pce) {
if (pce.getPropertyName().equalsIgnoreCase("STATE_CHANGE")) {
List<JointCommand> jointCommands = getRoboticArmBrain().update(pce);
roboticArm.moveJoints(jointCommands);
}
else if (pce.getPropertyName().equalsIgnoreCase("LEVEL_SCORE")) {
Score score = (Score) pce.getNewValue();
printScores(score);
}
else if (pce.getPropertyName().equalsIgnoreCase("GAME_OVER")) {
// RoboticArmResultsPlotter roboticArmResultsPlotter = new RoboticArmResultsPlotter();
// roboticArmResultsPlotter.plotSimple();
// roboticArmResultsPlotter.plotLevelSummary();
DBConnectionManager.INSTANCE.release();
// System.exit(0);
}
}
/**
* Prints the scores for each level
*/
protected void printScores(Score score) {
System.out.println(score.toString());
scores.add(score);
for (int i = 0; i < score.getPillIDs().length; i++) {
RoboticArmRaw roboticArmRaw = new RoboticArmRaw();
roboticArmRaw.setAlgo(getRoboticArmBrain().getClass().getSimpleName());
roboticArmRaw.setNumjoints(numJoints);
roboticArmRaw.setLevel(score.getLevelId());
roboticArmRaw.setPillid(i);
roboticArmRaw.setEnergy(score.getActivationEnergiesRequired()[i]);
roboticArmRaw.setTime(score.getTimesElapsed()[i]);
RoboticArmRawDAO.insert(roboticArmRaw);
}
}
protected abstract AbstractRoboticArmBrain getRoboticArmBrain();
}
| 4,607 | 34.72093 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/RoboticArmAhahBrain.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.motorcontroller.Actuator;
import com.xeiam.proprioceptron.roboticarm.JointCommand;
import com.xeiam.proprioceptron.roboticarm.RoboticArmGameState;
/**
* @author timmolter
*/
public class RoboticArmAhahBrain extends AbstractRoboticArmBrain {
/** converts the robotic arm's game state to a sparse encoded feature */
private final RoboticArmSpikeEncoder roboticArmSpikeEncoder;
private final Actuator actuator;
private double e = 0;
private double numUpdates = 0;
private double numCollisions = 0;
private double totalActuation = 0;
private double performance = 0;
private final double pk = .05;
// private final int maxActuationSteps = 5;// for 9+ or more joints
private final int maxActuationSteps = 50;// for 2-9 or less joints
/**
* Constructor
*
* @param numJoints
*/
public RoboticArmAhahBrain(int numJoints, int bufferLength, int numFibersPerMuscle) {
roboticArmSpikeEncoder = new RoboticArmSpikeEncoder();
// actuator
actuator = new Actuator(numJoints, numFibersPerMuscle, bufferLength);
}
@Override
public List<JointCommand> update(PropertyChangeEvent pce) {
numUpdates++;
// 1. convert the robotic arms game state (pce) to a sparse encoded feature
long[] longspikes = roboticArmSpikeEncoder.encode(pce); // not really needed but to get the spike space it is. TODO refactor actuator to be a "classifier" using longs for spikes.
Set<String> spikes = roboticArmSpikeEncoder.getSpikes(pce);
System.out.println("Spike Pattern Length = " + spikes.size());
// 2. get the raw RoboticArmGameState
RoboticArmGameState RoboticArmGameState = (RoboticArmGameState) pce.getNewValue();
// 3. update score if there was a collision
if (RoboticArmGameState.getEnvState().wasCollision()) {
e += 1;
numCollisions++;
if (numCollisions == 1) {
performance = totalActuation;
}
else {
performance = (1 - pk) * performance + pk * totalActuation;
}
// reset total Activation
totalActuation = 0;
// System.out.println(performance);
}
// 4. get the actuations from the motor classifier
double value = (e) + 1 / (1 + RoboticArmGameState.getEnvState().getDistHead());
int[] actuations = actuator.update(spikes, value);
// 5. create the Joint Commands
List<JointCommand> jointCommands = new ArrayList<JointCommand>();
for (int i = 0; i < actuations.length; i++) {
JointCommand jointCommand = new JointCommand(i, (int) Math.signum(actuations[i]), limitActuation(Math.abs(actuations[i])));
jointCommands.add(jointCommand);
this.totalActuation += jointCommand.getSteps();
// e -= .001 * jointCommand.getSteps();
}
System.out.println("Spike Pattern Space = " + roboticArmSpikeEncoder.getSpikePatternSpace());
System.out.println("Num AHaH Nodes = " + actuator.getNumUniqueLabels());
return jointCommands;
}
private int limitActuation(int steps) {
if (steps > maxActuationSteps) {
return maxActuationSteps;
}
else {
return steps;
}
}
}
| 4,767 | 34.318519 | 182 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/RoboticArmApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import com.xeiam.proprioceptron.roboticarm.RoboticArm;
/**
* Run the Robotic Arm game with only the Classifier
*
* @author alexnugent
*/
public class RoboticArmApp extends AbstractRoboticArmApp {
private final AbstractRoboticArmBrain roboticArmBrain;
/**
* This app takes the following arguments:
* <ul>
* <li>int numJoints (9): the number of joints in the robotic arm
* <li>int startLevel (0): the level that that game should start at, zero-indexed
* <li>int numTargetsPerLevel (100): the number of pills the arm should catch before switching to the next level
* <li>int numFibersPerMuscle (20): the number of muscle fibers each muscle has
* <li>int bufferLength (1): the buffer length - controls the delay time in which the proprioceptive data feeds back into the motor controller
*
* @param args
*/
public static void main(String[] args) {
new RoboticArmApp(args);
}
/**
* Constructor
*
* @param args
*/
public RoboticArmApp(String[] args) {
// read in params from args
int numJoints = 9;
int startLevel = 0;
int numTargetsPerLevel = 100;
int numFibersPerMuscle = 20;
int bufferLength = 1;// if you increase this, may also want to decrease the learning rate in Actuator.
try {
numJoints = Integer.parseInt(args[0]);
startLevel = Integer.parseInt(args[1]);
numTargetsPerLevel = Integer.parseInt(args[2]);
numFibersPerMuscle = Integer.parseInt(args[3]);
bufferLength = Integer.parseInt(args[4]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
roboticArmBrain = new RoboticArmAhahBrain(numJoints, bufferLength, numFibersPerMuscle);
// roboticArmBrain = new RoboticArmBrainRandom(numJoints, bufferLength, numFibersPerMuscle);
roboticArm = new RoboticArm(numJoints, startLevel, numTargetsPerLevel);
init(numJoints);
roboticArm.start();
}
@Override
protected AbstractRoboticArmBrain getRoboticArmBrain() {
return roboticArmBrain;
}
} | 3,569 | 36.578947 | 144 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/AbstractRoboticArmBrain.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import java.beans.PropertyChangeEvent;
import java.util.List;
import com.xeiam.proprioceptron.roboticarm.JointCommand;
/**
* @author timmolter
*/
public abstract class AbstractRoboticArmBrain {
public abstract List<JointCommand> update(PropertyChangeEvent pce);
}
| 1,806 | 40.068182 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/RoboticArmBrainRandom.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.xeiam.proprioceptron.roboticarm.JointCommand;
import com.xeiam.proprioceptron.roboticarm.RoboticArmGameState;
/**
* @author timmolter
*/
public class RoboticArmBrainRandom extends AbstractRoboticArmBrain {
private final Random random = new Random();
/**
* Constructor
*
* @param numJoints
*/
public RoboticArmBrainRandom(int numJoints, int bufferLength, int numFibersPerMuscle) {
}
@Override
public List<JointCommand> update(PropertyChangeEvent pce) {
// RoboticArmGameState oldEnvState = (RoboticArmGameState) pce.getOldValue();
RoboticArmGameState newEnvState = (RoboticArmGameState) pce.getNewValue();
List<JointCommand> jointCommands = new ArrayList<JointCommand>();
// simulate a pause
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
int numJoints = newEnvState.getEnvState().getRelativePositions().length;
for (int i = 0; i < numJoints; i++) {
jointCommands.add(new JointCommand(i, random.nextDouble() > 0.5 ? 1 : -1, random.nextInt(100)));
}
return jointCommands;
}
}
| 2,773 | 33.675 | 102 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/RoboticArmRandomApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import com.xeiam.proprioceptron.roboticarm.RoboticArm;
/**
* Run the Robotic Arm game with only the Classifier.
*
* @author alexnugent
*/
public class RoboticArmRandomApp extends AbstractRoboticArmApp {
private static final int NUM_JOINTS = 4;
private static final int START_LEVEL_ID = 0;
private static final int NUM_TARGETS_PER_LEVEL = 50;
private static final int NUM_FIBERS_PER_MUSCLE = 100;
private static final int BUFFER_LENGTH = 1;
private final RoboticArmBrainRandom roboticArmBrainRandom;
/**
* Constructor
*/
public RoboticArmRandomApp() {
roboticArmBrainRandom = new RoboticArmBrainRandom(NUM_JOINTS, BUFFER_LENGTH, NUM_FIBERS_PER_MUSCLE);
roboticArm = new RoboticArm(NUM_JOINTS, START_LEVEL_ID, NUM_TARGETS_PER_LEVEL);
init(NUM_JOINTS);
roboticArm.start();
}
public static void main(String[] args) {
new RoboticArmRandomApp();
}
@Override
protected AbstractRoboticArmBrain getRoboticArmBrain() {
return roboticArmBrainRandom;
}
} | 2,552 | 33.972603 | 104 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/RoboticArmResultsPlotter.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.mancrd.ahah.commons.utils.RunningStat;
import com.mancrd.ahah.samples.motorcontroller.roboticarm.data.RoboticArmRaw;
import com.mancrd.ahah.samples.motorcontroller.roboticarm.data.RoboticArmRawDAO;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class RoboticArmResultsPlotter {
public void plotLevelSummary() {
List<Chart> charts = new ArrayList<Chart>();
List<RoboticArmRaw> roboticArmRaws = RoboticArmRawDAO.selectAll();
Map<Integer, RunningStat> energyData = new HashMap<Integer, RunningStat>();
Map<Integer, RunningStat> timeData = new HashMap<Integer, RunningStat>();
for (RoboticArmRaw roboticArmRaw : roboticArmRaws) {
// Energy
RunningStat rs = energyData.get(roboticArmRaw.getLevel());
if (rs == null) {
rs = new RunningStat();
}
rs.put(roboticArmRaw.getEnergy());
energyData.put(roboticArmRaw.getLevel(), rs);
// Time
rs = timeData.get(roboticArmRaw.getLevel());
if (rs == null) {
rs = new RunningStat();
}
rs.put(roboticArmRaw.getTime());
timeData.put(roboticArmRaw.getLevel(), rs);
}
String title = roboticArmRaws.get(0).getAlgo();
int numJoints = roboticArmRaws.get(0).getNumjoints();
Collection<Number> xData = new ArrayList<Number>();
Collection<Number> yData = new ArrayList<Number>();
Collection<Number> errorBars = new ArrayList<Number>();
// ///////////////////////
for (Entry<Integer, RunningStat> entrySet : energyData.entrySet()) {
int level = entrySet.getKey();
RunningStat stat = entrySet.getValue();
xData.add(level);
yData.add(stat.getAverage());
errorBars.add(stat.getStandardDeviation());
System.out.println("level: " + level + ", ave: " + stat.getAverage() + ", std: " + stat.getStandardDeviation());
System.out.println(stat.getAverage());
System.out.println(stat.getStandardDeviation());
}
// Create Chart
Chart chart = new Chart(800, 220);
// Customize Chart
chart.setChartTitle(title + " (Num Joints = " + numJoints + ")");
chart.setXAxisTitle("Level");
chart.setYAxisTitle("Required Activation Energy");
chart.getStyleManager().setLegendVisible(false);
// Series
Series series = chart.addSeries("requiredActivationEnergy", xData, yData, errorBars);
series.setLineStyle(SeriesLineStyle.NONE);
charts.add(chart);
// ////////////////
xData = new ArrayList<Number>();
yData = new ArrayList<Number>();
errorBars = new ArrayList<Number>();
for (Entry<Integer, RunningStat> entrySet : timeData.entrySet()) {
int pillId = entrySet.getKey();
RunningStat stat = entrySet.getValue();
xData.add(pillId);
yData.add(stat.getAverage());
errorBars.add(stat.getStandardDeviation());
}
// Create Chart
chart = new Chart(800, 220);
// Customize Chart
chart.setXAxisTitle("Level");
chart.setYAxisTitle("Elapsed Time (s)");
chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setChartTitleVisible(false);
// Series
series = chart.addSeries("elapsedTime", xData, yData, errorBars);
series.setLineStyle(SeriesLineStyle.NONE);
charts.add(chart);
new SwingWrapper(charts, 2, 1).displayChartMatrix();
}
public void plotSimple() {
List<Chart> charts = new ArrayList<Chart>();
Collection<Number> xData = new ArrayList<Number>();
Collection<Number> yData = new ArrayList<Number>();
List<RoboticArmRaw> roboticArmRaws = RoboticArmRawDAO.selectAll();
for (RoboticArmRaw roboticArmRaw : roboticArmRaws) {
xData.add(roboticArmRaw.getLevel());
yData.add(roboticArmRaw.getEnergy());
}
String title = roboticArmRaws.get(0).getAlgo();
int numJoints = roboticArmRaws.get(0).getNumjoints();
// Create Chart
Chart chart = new Chart(800, 220);
// Customize Chart
chart.setChartTitle(title + " (Num Joints = " + numJoints + ")");
chart.setXAxisTitle("Level");
chart.setYAxisTitle("Robotic Arm App - Required Activation Energy");
chart.getStyleManager().setLegendVisible(false);
// Series 1
Series series1 = chart.addSeries("requiredActivationEnergy", xData, yData);
series1.setLineStyle(SeriesLineStyle.NONE);
charts.add(chart);
// ////////////////
xData = new ArrayList<Number>();
yData = new ArrayList<Number>();
for (RoboticArmRaw roboticArmRaw : roboticArmRaws) {
xData.add(roboticArmRaw.getLevel());
yData.add(roboticArmRaw.getTime());
}
// Create Chart
chart = new Chart(800, 220);
// Customize Chart
chart.setXAxisTitle("Level");
chart.setYAxisTitle("Elapsed Time (s)");
chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setChartTitleVisible(false);
// Series 1
series1 = chart.addSeries("elapsedTime", xData, yData);
series1.setLineStyle(SeriesLineStyle.NONE);
charts.add(chart);
new SwingWrapper(charts, 2, 1).displayChartMatrix();
}
}
| 6,869 | 32.349515 | 118 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/data/RoboticArmRaw.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm.data;
/**
* @author timmolter
*/
public class RoboticArmRaw {
private String algo;
private int numjoints;
private int level;
private int pillid;
private int energy;
private double time;
public String getAlgo() {
return algo;
}
public void setAlgo(String algo) {
this.algo = algo;
}
public int getNumjoints() {
return numjoints;
}
public void setNumjoints(int numjoints) {
this.numjoints = numjoints;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getPillid() {
return pillid;
}
public void setPillid(int pillid) {
this.pillid = pillid;
}
public int getEnergy() {
return energy;
}
public void setEnergy(int energy) {
this.energy = energy;
}
public double getTime() {
return time;
}
public void setTime(double time) {
this.time = time;
}
}
| 2,469 | 22.75 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/motorcontroller/roboticarm/data/RoboticArmRawDAO.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.motorcontroller.roboticarm.data;
import java.util.List;
import com.xeiam.yank.DBProxy;
/**
* @author timmolter
*/
public class RoboticArmRawDAO {
public static int dropTable() {
return DBProxy.executeSQL("roboticarm", "DROP TABLE IF EXISTS ROBOTIC_ARM_RAW", null);
}
public static int createTable() {
String BREAST_CANCER_CREATE =
"CREATE CACHED TABLE ROBOTIC_ARM_RAW (algo VARCHAR(256) NOT NULL, numjoints INTEGER NOT NULL, level INTEGER NOT NULL, pillid INTEGER NOT NULL, energy INTEGER NOT NULL, time DOUBLE NOT NULL)";
return DBProxy.executeSQL("roboticarm", BREAST_CANCER_CREATE, null);
}
public static int insert(RoboticArmRaw roboticArmRaw) {
Object[] params = new Object[] {
// @formatter:off
roboticArmRaw.getAlgo(),
roboticArmRaw.getNumjoints(),
roboticArmRaw.getLevel(),
roboticArmRaw.getPillid(),
roboticArmRaw.getEnergy(),
roboticArmRaw.getTime()
// @formatter:on
};
String ROBOTIC_ARM_RAW_INSERT = "INSERT INTO ROBOTIC_ARM_RAW (ALGO, NUMJOINTS, LEVEL, PILLID, ENERGY, TIME) VALUES (?, ?, ?, ?, ?, ?)";
return DBProxy.executeSQL("roboticarm", ROBOTIC_ARM_RAW_INSERT, params);
}
public static List<RoboticArmRaw> selectAll() {
String ROBOTIC_ARM_SELECT = "SELECT * FROM ROBOTIC_ARM_RAW";
return DBProxy.queryObjectListSQL("roboticarm", ROBOTIC_ARM_SELECT, RoboticArmRaw.class, null);
}
public static List<RoboticArmRaw> selectNumJoints(String algo, int numJoints) {
Object[] params = new Object[] { algo, numJoints };
String ROBOTIC_ARM_SELECT = "SELECT * FROM ROBOTIC_ARM_RAW WHERE ALGO = ? AND NUMJOINTS = ?";
return DBProxy.queryObjectListSQL("roboticarm", ROBOTIC_ARM_SELECT, RoboticArmRaw.class, params);
}
public static List<RoboticArmRaw> selectLevel(String algo, int level) {
Object[] params = new Object[] { algo, level };
String ROBOTIC_ARM_SELECT = "SELECT * FROM ROBOTIC_ARM_RAW WHERE ALGO = ? AND LEVEL = ?";
return DBProxy.queryObjectListSQL("roboticarm", ROBOTIC_ARM_SELECT, RoboticArmRaw.class, params);
}
public static List<RoboticArmRaw> selectRunId(String algo) {
Object[] params = new Object[] { algo };
String ROBOTIC_ARM_SELECT = "SELECT * FROM ROBOTIC_ARM_RAW WHERE ALGO = ?";
return DBProxy.queryObjectListSQL("roboticarm", ROBOTIC_ARM_SELECT, RoboticArmRaw.class, params);
}
}
| 3,912 | 37.742574 | 199 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/ModelExperiment.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model;
import java.util.HashSet;
import java.util.Set;
/**
* @author timmolter
*/
public class ModelExperiment {
/**
* @return
*/
public Set<Integer> getThreePatternSpikeLogicSpikePattern() {
Set<Integer> spikes = new HashSet<Integer>();
double x0 = Math.random();
double x1 = Math.random();
if (x0 < .5) {
spikes.add(0);
}
else {
spikes.add(1);
}
if (x1 < .5) {
spikes.add(2);
}
else {
spikes.add(3);
}
return spikes;
}
public Set<Integer> getOrthogonalSpikeLogicSpikePattern() {
Set<Integer> spikes = new HashSet<Integer>();
double x0 = Math.random();
if (x0 < .5) {
spikes.add(0);
}
else {
spikes.add(1);
}
if (x0 > .5) {
spikes.add(2);
}
else {
spikes.add(3);
}
return spikes;
}
public Set<Integer> getThreePatternSpikePattern() {
double p = Math.random();
Set<Integer> spikes = new HashSet<Integer>();
if (p < .333) {
spikes.add(0);
return spikes;
}
else if (p < .666) {
spikes.add(1);
return spikes;
}
else {
spikes.add(0);
spikes.add(1);
return spikes;
}
}
public int H(double y) {
if (y > 0) {
return 1;
}
else {
return 0;
}
}
}
| 2,828 | 22.974576 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/ChartHelper.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
/**
* @author timmolter
*/
public class ChartHelper {
public static double[] getScaledArray(double[] array) {
double arrayMax = getMax(array);
double arrayMin = getMin(array);
double span = arrayMax - arrayMin;
double[] scaledArray = new double[array.length];
for (int i = 0; i < scaledArray.length; i++) {
scaledArray[i] = (array[i] - arrayMin) / span;
}
return scaledArray;
}
public static double getMax(double[] array) {
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
public static double getMin(double[] array) {
double min = Double.POSITIVE_INFINITY;
for (int i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
}
| 2,393 | 32.25 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/WeightUpdate.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
/**
*
*/
public class WeightUpdate implements Comparable<WeightUpdate> {
private final int timeStep;
private final double y;
private final double dW;
private final double dB;
/**
* Constructor
*
* @param timeStep
* @param y
* @param dW
* @param dB
*/
public WeightUpdate(int timeStep, double y, double dW, double dB) {
this.timeStep = timeStep;
this.y = y;
this.dW = dW;
this.dB = dB;
}
@Override
public int compareTo(WeightUpdate o) {
if (o.getTimeStep() > this.getTimeStep()) {
return -1;
}
else if (o.getTimeStep() < this.getTimeStep()) {
return 1;
}
return 0;
}
public int getTimeStep() {
return timeStep;
}
public double getY() {
return y;
}
public double getdW() {
return dW;
}
public double getdB() {
return dB;
}
}
| 2,383 | 25.488889 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/SpikeLogicStateOccupationFrequencyApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
import java.util.Arrays;
import java.util.Set;
import com.mancrd.ahah.commons.utils.FileUtils;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.ChartBuilder;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.ChartType;
import com.xeiam.xchart.SwingWrapper;
/**
* Shows occupation of spike-logic state attractors. Each AHaH node randomly falls into an attractor which is a logic function. This function is measured. This is repeated many times to build up a
* histogram showing that all but the XOR functions are represented by AHaH attractor states.
*
* @author timmolter
*/
public class SpikeLogicStateOccupationFrequencyApp extends CircuitModelExperiment {
/**
* @param args
*/
public static void main(String[] args) {
SpikeLogicStateOccupationFrequencyApp spikeLogicStateOccupationFrequencyApp = new SpikeLogicStateOccupationFrequencyApp();
spikeLogicStateOccupationFrequencyApp.go();
}
void go() {
int trials = 5000; // number of AHaH nodes to simulate
int timeSteps = 1000; // number of time steps per ahah node to converge
int numBias = 1;
double[] logicFunctionCounts = new double[16];
for (int trial = 0; trial < trials; trial++) {
AHaH21Circuit ahahNode = new AHaH21CircuitBuilder().numInputs(4).numBiasInputs(numBias).build();
for (int i = 0; i < timeSteps; i++) {
Set<Integer> spikePattern = getThreePatternSpikeLogicSpikePattern();
// System.out.println(spikePattern);
ahahNode.update(spikePattern, 0);
}
int lf = testSpikeLogicState(ahahNode);
logicFunctionCounts[lf]++;
}
// normalize histogram of logic functions
for (int i = 0; i < logicFunctionCounts.length; i++) {
logicFunctionCounts[i] /= trials;
}
// Plot the logic function histogram
Chart chart =
new ChartBuilder().chartType(ChartType.Bar).width(500).height(500).title("Circuit AHaH Logic State Occupation Frequency").xAxisTitle("Logic Function").yAxisTitle("Frequency").theme(
ChartTheme.Matlab).build();
chart.getStyleManager().setLegendVisible(false);
double[] x = new double[16];
for (int i = 0; i < x.length; i++) {
x[i] = i;
}
Series series = chart.addSeries("Circuit", x, logicFunctionCounts);
new SwingWrapper(chart).displayChart();
System.out.println(Arrays.toString(logicFunctionCounts));
// write to csv file
FileUtils.mkDirIfNotExists("./Results/");
FileUtils.mkDirIfNotExists("./Results/Model/");
FileUtils.mkDirIfNotExists("./Results/Model/Logic/");
CSVExporter.writeCSVColumns(series, "./Results/Model/Logic/");
}
}
| 4,379 | 36.118644 | 196 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/AHaHRuleCircuitApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.commons.utils.FileUtils;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AHaHRuleCircuitApp extends CircuitModelExperiment {
/**
* @param args
*/
public static void main(String[] args) {
AHaHRuleCircuitApp aHaHRule = new AHaHRuleCircuitApp();
aHaHRule.go();
}
/**
* Takes a four-input AHaH node and reconstructs the AHaH rule.
*/
public void go() {
int trials = 10; // number of AHaH nodes to simulate
int timeSteps = 500; // number of time steps per ahah node to converge
double Vdd = .5;
double Vss = -.5;
double readPeriod = 1E-6;
double writePeriod = 1E-6;
int numBias = 1;
List<WeightUpdate> dw = new ArrayList<WeightUpdate>();
for (int trial = 0; trial < trials; trial++) {
AHaH21Circuit ahahNode = new AHaH21CircuitBuilder().numInputs(4).numBiasInputs(numBias).readPeriod(readPeriod).writePeriod(writePeriod).Vss(Vss).Vdd(Vdd).build();
for (int i = 0; i < timeSteps; i++) {
Set<Integer> spikePattern = getOrthogonalSpikeLogicSpikePattern();
double[] beforeW = { ahahNode.getWeight(0), ahahNode.getWeight(1), ahahNode.getWeight(2), ahahNode.getWeight(3) };
double beforeBiasW = ahahNode.getWeight(4);
double y = ahahNode.update(spikePattern, 0);
double dB = ahahNode.getWeight(4) - beforeBiasW;
if (spikePattern.contains(0)) {
dw.add(new WeightUpdate(i, y, ahahNode.getWeight(0) - beforeW[0], dB));
}
if (spikePattern.contains(1)) {
dw.add(new WeightUpdate(i, y, ahahNode.getWeight(1) - beforeW[1], dB));
}
if (spikePattern.contains(2)) {
dw.add(new WeightUpdate(i, y, ahahNode.getWeight(2) - beforeW[2], dB));
}
if (spikePattern.contains(3)) {
dw.add(new WeightUpdate(i, y, ahahNode.getWeight(3) - beforeW[3], dB));
}
}
}
Collections.sort(dw);
ahahPlot(0, 200, dw);
// ahahPlot(200, 400, dw);
// ahahPlot(400, 800, dw);
// ahahPlot(0, 1000, dw);
}
public void ahahPlot(int startTime, int endTime, List<WeightUpdate> dwData) {
int startIdx = -1;
int endIdx = dwData.size();
for (int i = 0; i < dwData.size(); i++) {
if (startIdx == -1 && dwData.get(i).getTimeStep() == startTime) {
startIdx = i;
}
if (endIdx == dwData.size() && dwData.get(i).getTimeStep() == endTime) {
endIdx = i;
break;
}
}
System.out.println("startTime,endTime: " + startTime + "," + endTime);
System.out.println("startIdx,endIdx: " + startIdx + "," + endIdx);
double[] y = new double[endIdx - startIdx];
double[] dw = new double[endIdx - startIdx];
double[] db = new double[endIdx - startIdx];
for (int i = startIdx; i < endIdx; i++) {
y[i - startIdx] = dwData.get(i).getY();
dw[i - startIdx] = dwData.get(i).getdW();
db[i - startIdx] = dwData.get(i).getdB();
}
Chart chart = new Chart(500, 500, ChartTheme.Matlab);
chart.setXAxisTitle("Y");
chart.setYAxisTitle("dW");
chart.setChartTitle("AHaH 21 Circuit AHaH Rule Reconstruction, T=" + startTime + ":" + endTime + "");
chart.getStyleManager().setLegendVisible(false);
Series dwseries = chart.addSeries("Circuit_Inputs", y, dw);
dwseries.setLineStyle(SeriesLineStyle.NONE);
dwseries.setMarker(SeriesMarker.CIRCLE);
dwseries.setMarkerColor(new Color(0, 0, 255, 10));
Series dwBiasSeries = chart.addSeries("Circuit_Bias", y, db);
dwBiasSeries.setLineStyle(SeriesLineStyle.NONE);
dwBiasSeries.setMarker(SeriesMarker.CIRCLE);
dwBiasSeries.setMarkerColor(new Color(255, 0, 0, 10));
new SwingWrapper(chart).displayChart();
FileUtils.mkDirIfNotExists("./Results/");
FileUtils.mkDirIfNotExists("./Results/Model/");
FileUtils.mkDirIfNotExists("./Results/Model/AHaHRule/");
FileUtils.mkDirIfNotExists("./Results/Model/AHaHRule/Circuit/");
CSVExporter.writeCSVColumns(dwseries, "./Results/Model/AHaHRule/Circuit/");
CSVExporter.writeCSVColumns(dwBiasSeries, "./Results/Model/AHaHRule/Circuit/");
}
}
| 6,142 | 33.903409 | 168 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/SpikeLogicFuntionVsTimeApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.commons.utils.FileUtils;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* Determines the logic function of attractor states of a spike-encoded binary input. Each AHaH node will randomly converge to a stable attractor state. The purpose of this experiment is to show
* that the AHaH attractor states are stable.
* "Logical 0"-->Spike Pattern {1,z}
* "Logical 1"-->Spike Pattern {z,1}
* 'z' is a floating input
* Examples:
* Binary Logic-->Spike Logic
* 00-->1z1z
* 01-->1zz1
* 10-->z11z
* 11-->z1z1
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @author timmolter
*/
public class SpikeLogicFuntionVsTimeApp extends CircuitModelExperiment {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
SpikeLogicFuntionVsTimeApp spikeLogicFuntionVsTimeApp = new SpikeLogicFuntionVsTimeApp();
spikeLogicFuntionVsTimeApp.go();
}
void go() throws IOException {
int trials = 100; // number of AHaH nodes to simulate
int timeSteps = 50000; // number of time steps
int numBias = 1;
List<double[]> nodeLogicData = new ArrayList<double[]>();
for (int i = 0; i < trials; i++) {
nodeLogicData.add(new double[timeSteps]);
}
for (int trial = 0; trial < trials; trial++) {
AHaH21Circuit ahahNode = new AHaH21CircuitBuilder().numInputs(4).numBiasInputs(numBias).build();
for (int i = 0; i < timeSteps; i++) {
nodeLogicData.get(trial)[i] = testSpikeLogicState(ahahNode);
}
}
// Plot the ahah rule
Chart chart = new Chart(200, 300, ChartTheme.Matlab);
chart.getStyleManager().setLegendVisible(false);
chart.setXAxisTitle("Time Step");
chart.setYAxisTitle("Logic Function");
// write to csv file
FileUtils.mkDirIfNotExists("./Results/");
FileUtils.mkDirIfNotExists("./Results/Model/");
FileUtils.mkDirIfNotExists("./Results/Model/LogicVsTime/");
for (int i = 0; i < nodeLogicData.size(); i++) {
Series dw_series = chart.addSeries("node logic " + i, null, nodeLogicData.get(i));
dw_series.setLineStyle(SeriesLineStyle.SOLID);
dw_series.setMarker(SeriesMarker.NONE);
dw_series.setLineColor(Color.blue);
}
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaH_Logic_Vs_Time_Circuit.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 4,372 | 33.984 | 194 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/TwoInputAttractorsApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
import java.io.IOException;
import java.util.Set;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesColor;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class TwoInputAttractorsApp extends CircuitModelExperiment {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
TwoInputAttractorsApp twoInputAttractorsApp = new TwoInputAttractorsApp();
twoInputAttractorsApp.go();
}
void go() throws IOException {
int trials = 50; // number of AHaH nodes to simulate
int timeSteps = 500; // number of time steps per ahah node
int numBias = 1;
// Weight Attractor Plot
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
chart.setChartTitle("Attractor Basins - Circuit");
chart.setYAxisTitle("W1");
chart.setXAxisTitle("W0");
chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setAxisTicksVisible(false);
double[] finalW0 = new double[trials];
double[] finalW1 = new double[trials];
double[] startW0 = new double[trials];
double[] startW1 = new double[trials];
for (int trial = 0; trial < trials; trial++) {
AHaH21Circuit ahahNode = new AHaH21CircuitBuilder().numInputs(2).numBiasInputs(numBias).build();
double[] w0 = new double[timeSteps];
double[] w1 = new double[timeSteps];
double[] y = new double[timeSteps];
startW0[trial] = ahahNode.getWeight(0);
startW1[trial] = ahahNode.getWeight(1);
for (int i = 0; i < timeSteps; i++) {
Set<Integer> spikePattern = getThreePatternSpikePattern();
y[i] = ahahNode.update(spikePattern, 0);
w0[i] = ahahNode.getWeight(0);
w1[i] = ahahNode.getWeight(1);
}
finalW0[trial] = ahahNode.getWeight(0);
finalW1[trial] = ahahNode.getWeight(1);
// weight trace
Series weightTrace = chart.addSeries("W0", w0, w1);
weightTrace.setMarker(SeriesMarker.NONE);
weightTrace.setLineColor(SeriesColor.BLUE);
}
// final weight value trace
Series finalValueSeries = chart.addSeries("FinalValue", finalW0, finalW1);
finalValueSeries.setMarker(SeriesMarker.CIRCLE);
finalValueSeries.setMarkerColor(SeriesColor.RED);
finalValueSeries.setLineStyle(SeriesLineStyle.NONE);
// start weight value trace
Series startValueSeries = chart.addSeries("StartValue", startW0, startW1);
startValueSeries.setMarker(SeriesMarker.CIRCLE);
startValueSeries.setMarkerColor(SeriesColor.GREEN);
startValueSeries.setLineStyle(SeriesLineStyle.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaH_Attractor_Circuit.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 4,588 | 36.008065 | 102 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/CircuitModelExperiment.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.samples.model.ModelExperiment;
/**
* @author timmolter
*/
public class CircuitModelExperiment extends ModelExperiment {
public int testSpikeLogicState(AHaH21Circuit ahahNode) {
Set<Integer> spikes = new HashSet<Integer>();
// binary logic--->spike logic
// 00--->1010
spikes.add(0);
spikes.add(2);
double y00 = ahahNode.update(spikes, 0);
spikes.clear();
// 01-->1001
spikes.add(0);
spikes.add(3);
double y01 = ahahNode.update(spikes, 0);
spikes.clear();
// 10-->0110
spikes.add(1);
spikes.add(2);
double y10 = ahahNode.update(spikes, 0);
spikes.clear();
// 11-->0101
spikes.add(1);
spikes.add(3);
double y11 = ahahNode.update(spikes, 0);
StringBuffer sb = new StringBuffer();
sb.append(H(y00));
sb.append(H(y01));
sb.append(H(y10));
sb.append(H(y11));
int logicFunction = Integer.parseInt(sb.toString(), 2);
return logicFunction;
}
}
| 2,611 | 30.095238 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/DifferentialWeightApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.model.circuit.AHaH21Circuit;
import com.mancrd.ahah.model.circuit.AHaH21CircuitBuilder;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* Shows the values [Wa-Wb] (red) and [Wa+Wb] (blue) over time for a number of AHaH nodes. Demonstrates that the quantity [Wa+Wb] is constant and can thus be factored out in the derivations of the
* ideal circuit model. This enables a linear sum: sum(Wa-Wb) as a representation of "y" in the functional model.
*
* @author timmolter
*/
public class DifferentialWeightApp extends CircuitModelExperiment {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
DifferentialWeightApp differentialWeightApp = new DifferentialWeightApp();
differentialWeightApp.go();
}
void go() throws IOException {
int timeSteps = 1100; // number of time steps per ahah node to converge
int numTrials = 5;
int numBias = 1;
// Plot the weights rule
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
chart.setXAxisTitle("Time");
chart.setChartTitle("Weight and Weight Conjugate");
chart.getStyleManager().setLegendVisible(false);
for (int i = 0; i < numTrials; i++) {
AHaH21Circuit ahahNode = new AHaH21CircuitBuilder().numInputs(4).numBiasInputs(numBias).build();
List<Number> w = new ArrayList<Number>();
List<Number> w_conjugate = new ArrayList<Number>();
for (int t = 0; t < timeSteps; t++) {
Set<Integer> spikePattern = getOrthogonalSpikeLogicSpikePattern();
ahahNode.update(spikePattern, 0);
w.add(ahahNode.getSpikeInputWeightSum(spikePattern));
w_conjugate.add(ahahNode.getSpikeInputWeightMagnitudeSum(spikePattern));
}
Series w_series = chart.addSeries("sum(wa - wb)_"+i, null, w);
w_series.setLineStyle(SeriesLineStyle.SOLID);
w_series.setMarker(SeriesMarker.NONE);
w_series.setLineColor(new Color(255, 0, 0, 50));
Series wc_series = chart.addSeries("sum(wa + wb)_"+i, null, w_conjugate);
wc_series.setLineStyle(SeriesLineStyle.SOLID);
wc_series.setMarker(SeriesMarker.NONE);
wc_series.setLineColor(new Color(0, 0, 255, 50));
}
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaH_Weight_and_Weight_Conjugate.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 4,248 | 37.627273 | 196 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/AgChalcogenideHysteresisPlotB.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor;
import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor2;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through two series-connected memristors as a function of voltage applied for a sinusoidal voltage source.
*
* @author timmolter
*/
public class AgChalcogenideHysteresisPlotB {
/**
* This app takes the following arguments:
* <ul>
* <li>frequency (100): frequency of voltage source
* <li>timeStep (1E-4): time step of simulation
* <li>amplitude (.25): amplitude of voltage source
* <li>totalTime (5E-2): total simulation time.
*
* @param args
*/
public static void main(String[] args) {
AgChalcogenideHysteresisPlotB agChalcogenideHysteresisPlot = new AgChalcogenideHysteresisPlotB();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
double frequency = 100;
double timeStep = 1E-4;
double amplitude = .37;
double totalTime = 1E-2;
try {
frequency = Double.parseDouble(args[0]);
timeStep = Double.parseDouble(args[1]);
amplitude = Double.parseDouble(args[2]);
totalTime = Double.parseDouble(args[3]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
MSSMemristor m1 = new AgChalcMemristor(.5);
MSSMemristor m2 = new AgChalcMemristor2(.5);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] v1 = new double[numTimeSteps];
double[] v2 = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
current[i] = voltage[i] / (m1.getResistance() + m2.getResistance()) * 1000; // in mA
v2[i] = current[i] / m2.getConductance() / 1000;
v1[i] = voltage[i] - v2[i];
resistance[i] = voltage[i] / current[i] * 1000; // in Ohm
m1.dG(v1[i], timeStep);
m2.dG(v2[i], timeStep);
}
// Create I/V Chart
Chart chart = new Chart(600, 600, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
// chart.getStyleManager().setLegendVisible(false);
Series series1 = chart.addSeries("V", voltage, current);
series1.setMarker(SeriesMarker.NONE);
Series series2 = chart.addSeries("Va", v1, current);
series2.setMarker(SeriesMarker.NONE);
Series series3 = chart.addSeries("Vb", v2, current);
series3.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series1, "./Results/Model/Circuit/AgChalcB/");
CSVExporter.writeCSVColumns(series2, "./Results/Model/Circuit/AgChalcB/");
CSVExporter.writeCSVColumns(series3, "./Results/Model/Circuit/AgChalcB/");
}
}
| 4,841 | 38.048387 | 126 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/AgChalcogenideHysteresisPlotA.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage applied for a sinusoidal voltage source.
*
* @author timmolter
*/
public class AgChalcogenideHysteresisPlotA {
/**
* This app takes the following arguments:
* <ul>
* <li>frequency (100): frequency of voltage source
* <li>timeStep (1E-4): time step of simulation
* <li>amplitude (.25): amplitude of voltage source
* <li>totalTime (5E-2): total simulation time.
*
* @param args
*/
public static void main(String[] args) {
AgChalcogenideHysteresisPlotA agChalcogenideHysteresisPlot = new AgChalcogenideHysteresisPlotA();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
double frequency = 100;
double timeStep = 1E-4;
double amplitude = .25;
double totalTime = 5E-2;
try {
frequency = Double.parseDouble(args[0]);
timeStep = Double.parseDouble(args[1]);
amplitude = Double.parseDouble(args[2]);
totalTime = Double.parseDouble(args[3]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
MSSMemristor memristor = new AgChalcMemristor(0);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
current[i] = memristor.getCurrent(voltage[i]) * 1000; // in mA
memristor.dG(voltage[i], timeStep);
resistance[i] = voltage[i] / current[i] * 1000; // in Ohm
}
// Create Chart
Chart chart = new Chart(600, 600, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
Series series = chart.addSeries(((int) frequency + " Hz"), voltage, current);
series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/AgChalcA/");
// // Create R/V Chart
// chart = new Chart(600, 600, ChartTheme.Matlab);
// chart.setChartTitle("Resistance Loop " + frequency + " Hz");
// chart.setYAxisTitle("Resistance [Ohm]");
// chart.setXAxisTitle("Voltage [V]");
// chart.getStyleManager().setLegendVisible(false);
// series = chart.addSeries("AgChalcModelRV", voltage, resistance);
// // series.setMarker(SeriesMarker.NONE);
// new SwingWrapper(chart).displayChart();
// CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/");
}
}
| 4,764 | 38.708333 | 108 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/PdWO3WHysteresisPlot.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.driver.Driver;
import com.mancrd.ahah.model.circuit.driver.Triangle;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.mancrd.ahah.model.circuit.mss.PdWO3WMemristor;
import com.mancrd.ahah.samples.model.circuit.ChartHelper;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage applied for a sinusoidal voltage source.
* <p>
* Note: we do not know what the driving frequency is in [Chang 2011]
*
* @author timmolter
*/
public class PdWO3WHysteresisPlot {
private static final int CHART_DIM = 400;
/**
* This app takes the following arguments:
* <ul>
* <li>frequency (100): frequency of voltage source
* <li>timeStep (1E-4): time step of simulation
* <li>amplitude (.25): amplitude of voltage source
* <li>totalTime (5E-2): total simulation time.
*
* @param args
*/
public static void main(String[] args) {
PdWO3WHysteresisPlot pdWO3WHysteresisPlot = new PdWO3WHysteresisPlot();
pdWO3WHysteresisPlot.go(args);
}
private void go(String[] args) {
double frequency = 100;
double timeStep = 2E-4;
double amplitude = 1.3;
double totalTime = 5E-2;
try {
frequency = Double.parseDouble(args[0]);
timeStep = Double.parseDouble(args[1]);
amplitude = Double.parseDouble(args[2]);
totalTime = Double.parseDouble(args[3]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
MSSMemristor memristor = new PdWO3WMemristor(.8);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
Driver driver = new Triangle("V", 0, 0, amplitude, frequency);
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
voltage[i] = driver.getSignal(time[i]);
// voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
current[i] = memristor.getCurrent(voltage[i]) * 1000000; // in uA
memristor.dG(voltage[i], timeStep);
resistance[i] = voltage[i] / current[i] * 1000000; // in Ohm
}
// Create Chart
Chart chart = new Chart(CHART_DIM, CHART_DIM, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [uA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
Series series = chart.addSeries("PdWO3WDevice", voltage, current);
series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/");
saveScaledData("WOx", voltage, current);
}
private void saveScaledData(String name, double[] voltage, double[] current) {
double[] voltageScaled = ChartHelper.getScaledArray(voltage);
double[] currentScaled = ChartHelper.getScaledArray(current);
Chart chart = new Chart(CHART_DIM, CHART_DIM, ChartTheme.Matlab);
Series series = chart.addSeries(name, voltageScaled, currentScaled);
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/Combo/");
}
}
| 5,070 | 37.416667 | 108 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/AgInSbTeHysteresisPlot.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.driver.Driver;
import com.mancrd.ahah.model.circuit.driver.Triangle;
import com.mancrd.ahah.model.circuit.mss.AgInSbTeMemristor;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.mancrd.ahah.samples.model.circuit.ChartHelper;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage applied for a triangle voltage source.
* <p>
* Note: we dont know what the driving frequency is in [Zhang 2013]
*
* @author timmolter
*/
public class AgInSbTeHysteresisPlot {
private static final int CHART_DIM = 400;
/**
* This app takes the following arguments:
* <ul>
* <li>frequency (100): frequency of voltage source
* <li>timeStep (1E-4): time step of simulation
* <li>amplitude (.25): amplitude of voltage source
* <li>totalTime (5E-2): total simulation time.
*
* @param args
*/
public static void main(String[] args) {
AgInSbTeHysteresisPlot agChalcogenideHysteresisPlot = new AgInSbTeHysteresisPlot();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
double frequency = 100;
double timeStep = 1E-4;
double amplitude = .4;
double totalTime = 5E-2;
try {
frequency = Double.parseDouble(args[0]);
timeStep = Double.parseDouble(args[1]);
amplitude = Double.parseDouble(args[2]);
totalTime = Double.parseDouble(args[3]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
MSSMemristor memristor = new AgInSbTeMemristor(1);
Driver driver = new Triangle("V", 0, 0, amplitude, frequency);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
// voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
voltage[i] = driver.getSignal(time[i]);
current[i] = memristor.getCurrent(voltage[i]) * 1000; // in uA
// memristor.dG(-1 * voltage[i], timeStep);
memristor.dG(voltage[i], timeStep);
resistance[i] = voltage[i] / current[i] * 1000; // in Ohm
}
// Create Hysteresis Chart
Chart chart = new Chart(CHART_DIM, CHART_DIM, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
Series series = chart.addSeries("AgInSbTeDevice", voltage, current);
series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/");
saveScaledData("AIST", voltage, current);
}
private void saveScaledData(String name, double[] voltage, double[] current) {
double[] voltageScaled = ChartHelper.getScaledArray(voltage);
double[] currentScaled = ChartHelper.getScaledArray(current);
Chart chart = new Chart(CHART_DIM, CHART_DIM, ChartTheme.Matlab);
Series series = chart.addSeries(name, voltageScaled, currentScaled);
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/Combo/");
}
}
| 5,148 | 37.714286 | 106 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/GSTHysteresisPlot.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.driver.Driver;
import com.mancrd.ahah.model.circuit.driver.Triangle;
import com.mancrd.ahah.model.circuit.mss.GSTMemristor;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.mancrd.ahah.samples.model.circuit.ChartHelper;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage applied for a triangle voltage source.
* <p>
* Note: we dont know what the driving frequency is in [Li 2013]
*
* @author timmolter
*/
public class GSTHysteresisPlot {
private static final int CHART_DIM = 400;
/**
* This app takes the following arguments:
* <ul>
* <li>frequency (100): frequency of voltage source
* <li>timeStep (1E-4): time step of simulation
* <li>amplitude (.25): amplitude of voltage source
* <li>totalTime (5E-2): total simulation time.
*
* @param args
*/
public static void main(String[] args) {
GSTHysteresisPlot agChalcogenideHysteresisPlot = new GSTHysteresisPlot();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
double frequency = 100;
double timeStep = 2E-4;
double amplitude = -1.0;
double totalTime = 5E-2;
try {
frequency = Double.parseDouble(args[0]);
timeStep = Double.parseDouble(args[1]);
amplitude = Double.parseDouble(args[2]);
totalTime = Double.parseDouble(args[3]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
MSSMemristor memristor = new GSTMemristor(1);
Driver driver = new Triangle("V", 0, 0, amplitude, frequency);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
// voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
voltage[i] = driver.getSignal(time[i]);
current[i] = memristor.getCurrent(voltage[i]) * 1000000; // in uA
// memristor.dG(-1 * voltage[i], timeStep);
memristor.dG(voltage[i], timeStep);
resistance[i] = voltage[i] / current[i] * 1000000; // in Ohm
}
// Create Hysteresis Chart
Chart chart = new Chart(CHART_DIM, CHART_DIM, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [uA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
Series series = chart.addSeries("GSTDevice", voltage, current);
series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/");
saveScaledData("GST", voltage, current);
}
private void saveScaledData(String name, double[] voltage, double[] current) {
double[] voltageScaled = ChartHelper.getScaledArray(voltage);
double[] currentScaled = ChartHelper.getScaledArray(current);
Chart chart = new Chart(CHART_DIM, CHART_DIM, ChartTheme.Matlab);
Series series = chart.addSeries(name, voltageScaled, currentScaled);
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/Combo/");
}
}
| 5,123 | 37.238806 | 106 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/AgChalcogenidePulseTrainPlotC.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage pulses applied.
*
* @author timmolter
*/
public class AgChalcogenidePulseTrainPlotC {
public static void main(String[] args) {
AgChalcogenidePulseTrainPlotC agChalcogenideHysteresisPlot = new AgChalcogenidePulseTrainPlotC();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
// PulseDef pulseDef = new PulseDef(10, 10E-4, 1.6, -4.0);
// PulseDef pulseDef = new PulseDef(10, 10E-4, .8, -2.0);
// PulseDef pulseDef = new PulseDef(10, 10E-4, .2, -.25);
// PulseDef pulseDef = new PulseDef(20, 20E-4, .8, -2.0);
// PulseDef pulseDef = new PulseDef(20, 20E-4, 2.4, -6.0);
PulseDef pulseDef = new PulseDef(5, 5E-4, .8, -2.0);
MSSMemristor memristor = new AgChalcMemristor(0.5);
int numTimeSteps = (int) (pulseDef.getTotalTime() / pulseDef.getPulseWidth()) + 1;
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
final int numStepsBeforeSwitchingPolarity = 15;
int numSteps = 0;
boolean upPhase = false;
for (int i = 0; i < numTimeSteps; i++) {
time[i] = i;
voltage[i] = getPolarity(upPhase, pulseDef);
current[i] = memristor.getCurrent(voltage[i]) * 1000; // in mA
if (current[i] != 0) {
resistance[i] = voltage[i] / current[i] * 1000; // in Ohm
}
else {
resistance[i] = 0;
}
// update memristor
memristor.dG(voltage[i], pulseDef.getPulseWidth());
if (numSteps++ == numStepsBeforeSwitchingPolarity) {
upPhase = !upPhase;
numSteps = 0;
}
}
// Create IChart
// Chart chart = new Chart(600, 600, ChartTheme.Matlab);
// chart.setChartTitle("Pulse Train " + pulseWidth + " s, " + amplitude + " V");
// chart.setYAxisTitle("Current [mA]");
// chart.setXAxisTitle("Pulse Number");
// chart.getStyleManager().setLegendVisible(false);
// Series series = chart.addSeries("AgChalcPulseI", time, current);
// // series.setMarker(SeriesMarker.NONE);
// new SwingWrapper(chart).displayChart();
// CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/");
// resistance plot
// String seriesName = "10 µs, 0.8V , -2.0V";
String seriesName = pulseDef.toString();
// String seriesName = "1 µs, 0.8V , -2.0V";
Chart chart = new Chart(600, 600, ChartTheme.Matlab);
chart.setChartTitle("Pulse Train " + pulseDef.getPulseWidth() + " s");
chart.setYAxisTitle("Resistance [Ohm]");
chart.setXAxisTitle("Pulse Number");
chart.getStyleManager().setLegendVisible(false);
Series series = chart.addSeries(seriesName, time, resistance);
// series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/AgChalcC/");
}
private double getPolarity(boolean upPhase, PulseDef pulseDef) {
if (upPhase) {
return pulseDef.getUpPhaseVoltage();
}
else {
return pulseDef.getDownPhaseVoltage();
}
}
private class PulseDef {
private final double pulseWidth;
private final double totalTime;
private final double upPhaseVoltage;
private final double downPhaseVoltage;
/**
* Constructor
*
* @param pulseWidth
* @param amplitude
* @param totalTime
* @param upPhaseVoltage
* @param downPhaseVoltage
*/
public PulseDef(double pulseWidth, double totalTime, double upPhaseVoltage, double downPhaseVoltage) {
this.pulseWidth = pulseWidth;
this.totalTime = totalTime;
this.upPhaseVoltage = upPhaseVoltage;
this.downPhaseVoltage = downPhaseVoltage;
}
public double getPulseWidth() {
return pulseWidth / 1000000;
}
public double getTotalTime() {
return totalTime;
}
public double getUpPhaseVoltage() {
return upPhaseVoltage;
}
public double getDownPhaseVoltage() {
return downPhaseVoltage;
}
@Override
public String toString() {
return (int) pulseWidth + " µs, " + upPhaseVoltage + " V, " + downPhaseVoltage + " V";
}
}
}
| 6,111 | 32.398907 | 106 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/AgChalcogenideTimePlotD.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage applied for a sinusoidal voltage source.
*
* @author timmolter
*/
public class AgChalcogenideTimePlotD {
/**
* This app takes the following arguments:
* <ul>
* <li>frequency (100): frequency of voltage source
* <li>timeStep (1E-4): time step of simulation
* <li>amplitude (.25): amplitude of voltage source
* <li>totalTime (5E-2): total simulation time.
*
* @param args
*/
public static void main(String[] args) {
AgChalcogenideTimePlotD agChalcogenideHysteresisPlot = new AgChalcogenideTimePlotD();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
double frequency = 150;
double timeStep = 1E-4;
double amplitude = .25;
double totalTime = 2E-2;
try {
frequency = Double.parseDouble(args[0]);
timeStep = Double.parseDouble(args[1]);
amplitude = Double.parseDouble(args[2]);
totalTime = Double.parseDouble(args[3]);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
// just ignore
}
MSSMemristor memristor = new AgChalcMemristor(0);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
current[i] = memristor.getCurrent(voltage[i]) * 1000; // in mA
memristor.dG(voltage[i], timeStep);
resistance[i] = voltage[i] / current[i] * 1000; // in Ohm
}
// Create Chart
Chart chart = new Chart(600, 600, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Time [s]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
Series series = chart.addSeries(((int) frequency + " Hz"), time, current);
series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/AgChalcD/");
// // Create R/V Chart
// chart = new Chart(600, 600, ChartTheme.Matlab);
// chart.setChartTitle("Resistance Loop " + frequency + " Hz");
// chart.setYAxisTitle("Resistance [Ohm]");
// chart.setXAxisTitle("Voltage [V]");
// chart.getStyleManager().setLegendVisible(false);
// series = chart.addSeries("AgChalcModelRV", voltage, resistance);
// // series.setMarker(SeriesMarker.NONE);
// new SwingWrapper(chart).displayChart();
// CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/");
}
}
| 4,740 | 38.508333 | 108 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/circuit/devices/AgChalcogenideTrianglePlotE.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.circuit.devices;
import com.mancrd.ahah.model.circuit.driver.Driver;
import com.mancrd.ahah.model.circuit.driver.Triangle;
import com.mancrd.ahah.model.circuit.mss.AgChalcMemristor;
import com.mancrd.ahah.model.circuit.mss.MSSMemristor;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* Plots the current through the memristor as a function of voltage applied for a sinusoidal voltage source.
*
* @author timmolter
*/
public class AgChalcogenideTrianglePlotE {
/**
* @param args
*/
public static void main(String[] args) {
AgChalcogenideTrianglePlotE agChalcogenideHysteresisPlot = new AgChalcogenideTrianglePlotE();
agChalcogenideHysteresisPlot.go(args);
}
private void go(String[] args) {
// double frequency = 100;
// double timeStep = 1E-4;
// double amplitude = .05;
// double offset = .05;
// double phase = 0.0075;
// double totalTime = 5E-2;
// double initialMemristance = 1;
// String title = "100 Hz positive";
double frequency = 100;
double timeStep = 1E-4;
double amplitude = .05;
double offset = -.05;
double phase = 0.0025;
double totalTime = 5E-2;
double initialMemristance = 0;
String title = "100 Hz negative";
MSSMemristor memristor = new AgChalcMemristor(initialMemristance);
int numTimeSteps = (int) (totalTime / timeStep);
double[] current = new double[numTimeSteps];
double[] voltage = new double[numTimeSteps];
double[] time = new double[numTimeSteps];
double[] resistance = new double[numTimeSteps];
Driver driver = new Triangle("V", offset, phase, amplitude, frequency);
for (int i = 0; i < numTimeSteps; i++) {
time[i] = (i + 1) * timeStep;
// voltage[i] = amplitude * Math.sin(time[i] * 2 * Math.PI * frequency);
voltage[i] = driver.getSignal(time[i]);
System.out.println(voltage[i]);
current[i] = memristor.getCurrent(voltage[i]) * 1000; // in mA
memristor.dG(voltage[i], timeStep);
resistance[i] = voltage[i] / current[i] * 1000; // in Ohm
}
// Create Chart
Chart chart = new Chart(600, 600, ChartTheme.Matlab);
chart.setChartTitle("Hysteresis Loop " + frequency + " Hz");
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
Series series = chart.addSeries(title, voltage, current);
series.setMarker(SeriesMarker.NONE);
new SwingWrapper(chart).displayChart();
CSVExporter.writeCSVColumns(series, "./Results/Model/Circuit/AgChalcE/");
}
}
| 4,326 | 37.292035 | 108 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/functional/AHaHFunctionalExperiments.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.functional;
import java.io.IOException;
/**
* Experiments with the AHaH functional model. Compare to AHaHCircuitExperiments.
*
* @author alexnugent
*/
public class AHaHFunctionalExperiments extends FunctionalModelExperiment {
public static void main(String[] args) throws IOException {
AHaHFunctionalExperiments aHaHFunctionalExperiments = new AHaHFunctionalExperiments();
aHaHFunctionalExperiments.go();
}
private void go() throws IOException {
new TwoInputAttractorsApp().go();
// new AHaHRuleApp().go();
// new SpikeLogicStateOccupationFrequencyApp().go();
// new SpikeLogicFuntionVsTimeApp().go();
}
}
| 2,162 | 37.625 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/functional/SpikeLogicStateOccupationFrequencyApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.functional;
import java.util.Arrays;
import java.util.Set;
import com.mancrd.ahah.commons.utils.FileUtils;
import com.mancrd.ahah.model.functional.AHaHNode;
import com.mancrd.ahah.model.functional.AHaHNodeBuilder;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.ChartBuilder;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.ChartType;
import com.xeiam.xchart.SwingWrapper;
/**
* Shows occupation of spike-logic state attractors. Each AHaH node randomly falls into an attractor which is a logic function. This function is measured. This is repeated many times to build up a
* histogram showing that all but the XOR functions are represented by AHaH attractor states.
*
* @author timmolter
*/
public class SpikeLogicStateOccupationFrequencyApp extends FunctionalModelExperiment {
/**
* @param args
*/
public static void main(String[] args) {
SpikeLogicStateOccupationFrequencyApp spikeLogicStateOccupationFrequencyApp = new SpikeLogicStateOccupationFrequencyApp();
spikeLogicStateOccupationFrequencyApp.go();
}
void go() {
int trials = 5000;// number of AHaH nodes to simulate. Enough to get some good statistics.
int timeSteps = 3000;// number of time steps per ahah node to converge. Run it out to make sure it has converged.
int numBias = 1;
double[] logicFunctionCounts = new double[16];
for (int trial = 0; trial < trials; trial++) {
AHaHNode ahahNode = new AHaHNodeBuilder().numInputs(4).numBiasInputs(numBias).isModelA(isModelA).build();
for (int i = 0; i < timeSteps; i++) {
Set<Integer> spikePattern = getThreePatternSpikeLogicSpikePattern();
ahahNode.update(spikePattern);
}
int lf = testSpikeLogicState(ahahNode);
logicFunctionCounts[lf]++;
}
// normalize histogram of logic functions
for (int i = 0; i < logicFunctionCounts.length; i++) {
logicFunctionCounts[i] /= trials;
}
// Plot the logic function histogram
Chart chart =
new ChartBuilder().chartType(ChartType.Bar).width(500).height(500).title("Functional AHaH Logic State Occupation Frequency").xAxisTitle("Logic Function").yAxisTitle("Frequency").theme(
ChartTheme.Matlab).build();
chart.getStyleManager().setLegendVisible(false);
double[] x = new double[16];
for (int i = 0; i < x.length; i++) {
x[i] = i;
}
Series series = chart.addSeries("Functional", x, logicFunctionCounts);
new SwingWrapper(chart).displayChart();
System.out.println(Arrays.toString(logicFunctionCounts));
// write to csv file
FileUtils.mkDirIfNotExists("./Results/");
FileUtils.mkDirIfNotExists("./Results/Model/");
FileUtils.mkDirIfNotExists("./Results/Model/Logic/");
CSVExporter.writeCSVColumns(series, "./Results/Model/Logic/");
}
}
| 4,428 | 36.218487 | 196 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/functional/FunctionalModelExperiment.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.functional;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.model.functional.AHaHNode;
import com.mancrd.ahah.samples.model.ModelExperiment;
/**
* @author timmolter
*/
public class FunctionalModelExperiment extends ModelExperiment {
/** ModelA is inverse */
public boolean isModelA = false;
/**
* returns the logic function of the ahahNode
*
* @param ahahNode
* @return
*/
public int testSpikeLogicState(AHaHNode ahahNode) {
Set<Integer> spikes = new HashSet<Integer>();
// binary logic--->spike logic
// 00--->1010
spikes.add(0);
spikes.add(2);
double y00 = ahahNode.update(spikes);
spikes.clear();
// 01-->1001
spikes.add(0);
spikes.add(3);
double y01 = ahahNode.update(spikes);
spikes.clear();
// 10-->0110
spikes.add(1);
spikes.add(2);
double y10 = ahahNode.update(spikes);
spikes.clear();
// 11-->0101
spikes.add(1);
spikes.add(3);
double y11 = ahahNode.update(spikes);
StringBuffer buf = new StringBuffer();
buf.append(H(y00));
buf.append(H(y01));
buf.append(H(y10));
buf.append(H(y11));
int logicFunction = Integer.parseInt(buf.toString(), 2);
return logicFunction;
}
}
| 2,766 | 29.076087 | 94 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/functional/SpikeLogicFuntionVsTimeApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.functional;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.mancrd.ahah.model.functional.AHaHNode;
import com.mancrd.ahah.model.functional.AHaHNodeBuilder;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* Determines the logic function of attractor states of a spike-encoded binary input. Each AHaH node will randomly converge to a stable attractor state. The purpose of this experiment is to show
* that the AHaH attractor states are stable.
* "Logical 0"-->Spike Pattern {1,z}
* "Logical 1"-->Spike Pattern {z,1}
* 'z' is a floating input
* Examples:
* Binary Logic-->Spike Logic
* 00-->1z1z
* 01-->1zz1
* 10-->z11z
* 11-->z1z1
* NOTE!! Add -Xms512m -Xmx1024m to VM args when running this.
*
* @author timmolter
*/
public class SpikeLogicFuntionVsTimeApp extends FunctionalModelExperiment {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
SpikeLogicFuntionVsTimeApp spikeLogicFuntionVsTimeApp = new SpikeLogicFuntionVsTimeApp();
spikeLogicFuntionVsTimeApp.go();
}
public void go() throws IOException {
int trials = 100; // Number of AHaH nodes to simulate.
int timeSteps = 50000; // number of time steps
int numBias = 1;
List<double[]> nodeLogicData = new ArrayList<double[]>();
for (int i = 0; i < trials; i++) {
nodeLogicData.add(new double[timeSteps]);
}
for (int trial = 0; trial < trials; trial++) {
AHaHNode ahahNode = new AHaHNodeBuilder().numInputs(4).numBiasInputs(numBias).isModelA(isModelA).build();
for (int i = 0; i < timeSteps; i++) {
nodeLogicData.get(trial)[i] = testSpikeLogicState(ahahNode);
}
}
// Plot the ahah rule
Chart chart = new Chart(200, 300, ChartTheme.Matlab);
chart.getStyleManager().setLegendVisible(false);
chart.setXAxisTitle("Time Step");
chart.setYAxisTitle("Logic Function");
for (int i = 0; i < nodeLogicData.size(); i++) {
Series dw_series = chart.addSeries("node logic " + i, null, nodeLogicData.get(i));
dw_series.setLineStyle(SeriesLineStyle.SOLID);
dw_series.setMarker(SeriesMarker.NONE);
dw_series.setLineColor(Color.blue);
}
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaH_Logic_Vs_Time_Functional.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 4,157 | 34.237288 | 194 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/functional/TwoInputAttractorsApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.functional;
import java.io.IOException;
import java.util.Set;
import com.mancrd.ahah.model.functional.AHaHNode;
import com.mancrd.ahah.model.functional.AHaHNodeBuilder;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesColor;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* Takes many two-input AHaH nodes and presents the spike patterns 01, 10, and 11. Plots the trajectory of the weights over time for each AHaH node, showing the converges to attractor states.
*
* @author timmolter
*/
public class TwoInputAttractorsApp extends FunctionalModelExperiment {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
TwoInputAttractorsApp twoInputAttractorsApp = new TwoInputAttractorsApp();
twoInputAttractorsApp.go();
}
public void go() throws IOException {
int trials = 50; // number of AHaH nodes to simulate
int timeSteps = 5000; // number of time steps per ahah node
// Weight Attractor Plot
Chart chart = new Chart(300, 300, ChartTheme.Matlab);
chart.setChartTitle("Attractor Basins - Functional");
chart.setYAxisTitle("W1");
chart.setXAxisTitle("W0");
chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setAxisTicksVisible(false);
double[] startW0 = new double[trials];
double[] startW1 = new double[trials];
double[] finalW0 = new double[trials];
double[] finalW1 = new double[trials];
for (int trial = 0; trial < trials; trial++) {
int numBias = 1;
AHaHNode ahahNode = new AHaHNodeBuilder().numInputs(2).numBiasInputs(numBias).isModelA(isModelA).build();
double[] w0 = new double[timeSteps];
double[] w1 = new double[timeSteps];
double[] y = new double[timeSteps];
startW0[trial] = ahahNode.getWeight(0);
startW1[trial] = ahahNode.getWeight(1);
for (int i = 0; i < timeSteps; i++) {
Set<Integer> spikePattern = getThreePatternSpikePattern();
y[i] = ahahNode.update(spikePattern);
w0[i] = ahahNode.getWeight(0);
w1[i] = ahahNode.getWeight(1);
}
finalW0[trial] = ahahNode.getWeight(0);
finalW1[trial] = ahahNode.getWeight(1);
// weight trace
Series weightTrace = chart.addSeries("W0", w0, w1);
weightTrace.setMarker(SeriesMarker.NONE);
weightTrace.setLineColor(SeriesColor.BLUE);
}
// final weight value trace
Series finalValueSeries = chart.addSeries("FinalValue", finalW0, finalW1);
finalValueSeries.setMarker(SeriesMarker.CIRCLE);
finalValueSeries.setMarkerColor(SeriesColor.RED);
finalValueSeries.setLineStyle(SeriesLineStyle.NONE);
// start weight value trace
Series startValueSeries = chart.addSeries("StartValue", startW0, startW1);
startValueSeries.setMarker(SeriesMarker.CIRCLE);
startValueSeries.setMarkerColor(SeriesColor.GREEN);
startValueSeries.setLineStyle(SeriesLineStyle.NONE);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaH_Attractor_Functional.png", 300);
new SwingWrapper(chart).displayChart();
}
}
| 4,811 | 36.302326 | 191 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/model/functional/AHaHRuleFunctionalApp.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.model.functional;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.commons.utils.FileUtils;
import com.mancrd.ahah.model.functional.AHaHNode;
import com.mancrd.ahah.model.functional.AHaHNodeBuilder;
import com.xeiam.xchart.CSVExporter;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AHaHRuleFunctionalApp extends FunctionalModelExperiment {
/**
* @param args
*/
public static void main(String[] args) {
AHaHRuleFunctionalApp aHaHRule = new AHaHRuleFunctionalApp();
aHaHRule.go();
}
/**
* Takes a four-input AHaH node and reconstructs the AHaH rule.
*/
public void go() {
int trials = 10; // number of AHaH nodes to simulate
int timeSteps = 500; // number of time steps per ahah node to converge
int numBias = 1;
List<Number> dDdata = new ArrayList<Number>();
List<Number> yData = new ArrayList<Number>();
List<Number> dwBiasData = new ArrayList<Number>();
List<Number> yBiasData = new ArrayList<Number>();
for (int trial = 0; trial < trials; trial++) {
AHaHNode ahahNode = new AHaHNodeBuilder().numInputs(4).numBiasInputs(numBias).isModelA(isModelA).noise(0.00005).build(); // reduce noise so rule can be seen
for (int i = 0; i < timeSteps; i++) {
Set<Integer> spikePattern = getOrthogonalSpikeLogicSpikePattern();
double[] beforeW = { ahahNode.getWeight(0), ahahNode.getWeight(1), ahahNode.getWeight(2), ahahNode.getWeight(3) };
double beforeBiasW = ahahNode.getWeight(4);
double y = ahahNode.update(spikePattern);
dwBiasData.add(ahahNode.getWeight(4) - beforeBiasW);
yBiasData.add(y);
if (spikePattern.contains(0)) {
dDdata.add(ahahNode.getWeight(0) - beforeW[0]);
yData.add(y);
}
if (spikePattern.contains(1)) {
dDdata.add(ahahNode.getWeight(1) - beforeW[1]);
yData.add(y);
}
if (spikePattern.contains(2)) {
dDdata.add(ahahNode.getWeight(2) - beforeW[2]);
yData.add(y);
}
if (spikePattern.contains(3)) {
dDdata.add(ahahNode.getWeight(3) - beforeW[3]);
yData.add(y);
}
}
}
// Plot the ahah rule
Chart chart = new Chart(500, 500, ChartTheme.Matlab);
chart.setXAxisTitle("Y");
chart.setYAxisTitle("dW");
chart.setChartTitle("AHaH 21 Functional");
chart.getStyleManager().setLegendVisible(false);
Series dwseries = chart.addSeries("Functional_Inputs", yData, dDdata);
dwseries.setLineStyle(SeriesLineStyle.NONE);
dwseries.setMarker(SeriesMarker.CIRCLE);
dwseries.setMarkerColor(new Color(0, 0, 255, 10));
Series dwBiasSeries = chart.addSeries("Functional_Bias", yBiasData, dwBiasData);
dwBiasSeries.setLineStyle(SeriesLineStyle.NONE);
dwBiasSeries.setMarker(SeriesMarker.CIRCLE);
dwBiasSeries.setMarkerColor(new Color(255, 0, 0, 10));
new SwingWrapper(chart).displayChart();
FileUtils.mkDirIfNotExists("./Results/");
FileUtils.mkDirIfNotExists("./Results/Model/");
FileUtils.mkDirIfNotExists("./Results/Model/AHaHRule/");
FileUtils.mkDirIfNotExists("./Results/Model/AHaHRule/Functional/");
CSVExporter.writeCSVColumns(dwseries, "./Results/Model/AHaHRule/Functional/");
CSVExporter.writeCSVColumns(dwBiasSeries, "./Results/Model/AHaHRule/Functional/");
}
}
| 5,146 | 34.253425 | 162 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/clusterer/ClustererVergenceNumNoiseBitsCircuitFigure.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.clusterer;
import java.io.IOException;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class ClustererVergenceNumNoiseBitsCircuitFigure {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Clusterer/Number_Noise_Bits/Circuit/", DataOrientation.Columns, 300, 300, ChartTheme.Matlab);
chart.setChartTitle("Vergence - Circuit");
chart.setYAxisTitle("Vergence");
chart.setXAxisTitle("Number of Noise Bits");
chart.getStyleManager().setLegendVisible(false);
// chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
chart.getStyleManager().setPlotGridLinesVisible(false);
// Save it
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/ClustererCircuit.png", 300);
// Show it
new SwingWrapper(chart).displayChart();
}
}
| 2,712 | 38.318841 | 153 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/clusterer/ClustererVergenceNumNoiseBitsFunctionalFigure.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.clusterer;
import java.io.IOException;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class ClustererVergenceNumNoiseBitsFunctionalFigure {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Clusterer/Number_Noise_Bits/Functional/", DataOrientation.Columns, 300, 300, ChartTheme.Matlab);
chart.setChartTitle("Vergence - Functional");
chart.setYAxisTitle("Vergence");
chart.setXAxisTitle("Number of Noise Bits");
chart.getStyleManager().setLegendVisible(false);
// chart.getStyleManager().setLegendPosition(LegendPosition.InsideSW);
chart.getStyleManager().setPlotGridLinesVisible(false);
// Save it
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/ClustererFunctional.png", 300);
// Show it
new SwingWrapper(chart).displayChart();
}
}
| 2,724 | 38.492754 | 156 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/ComboHysteresisFigureF.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class ComboHysteresisFigureF {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Circuit/Combo", DataOrientation.Columns, 240, 240, ChartTheme.Matlab);
chart.getStyleManager().setLegendVisible(true);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
chart.getStyleManager().setPlotGridLinesVisible(false);
chart.getStyleManager().setPlotTicksMarksVisible(false);
chart.getStyleManager().setAxisTicksVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series series0 = seriesMap.get("AIST");
series0.setMarker(SeriesMarker.NONE);
// series0.setLineStyle(SeriesLineStyle.DASH_DASH);
Series series1 = seriesMap.get("GST");
series1.setMarker(SeriesMarker.NONE);
series1.setLineStyle(SeriesLineStyle.DOT_DOT);
Series series2 = seriesMap.get("WOx");
series2.setMarker(SeriesMarker.NONE);
series2.setLineStyle(SeriesLineStyle.DASH_DASH);
// Show it
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/ComboHysteresis.png", 300);
}
}
| 3,212 | 40.192308 | 136 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AHaHLogic.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.ChartType;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AHaHLogic {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Logic/", DataOrientation.Columns, 400, 300, ChartTheme.Matlab);
chart.setYAxisTitle("Frequency");
chart.setXAxisTitle("Logic Function");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideN);
chart.getStyleManager().setChartType(ChartType.Bar);
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaH_Logic.png", 300);
// Show it
new SwingWrapper(chart).displayChart();
}
}
| 2,532 | 41.216667 | 129 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.