gnu.trove.list.array.TDoubleArrayList Java Examples

The following examples show how to use gnu.trove.list.array.TDoubleArrayList. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractTapChanger.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
protected AbstractTapChanger(Ref<? extends VariantManagerHolder> network, H parent,
                             int lowTapPosition, List<S> steps, TerminalExt regulationTerminal,
                             int tapPosition, boolean regulating, double targetDeadband, String type) {
    this.network = network;
    this.parent = parent;
    this.lowTapPosition = lowTapPosition;
    this.steps = steps;
    steps.forEach(s -> s.setParent(this));
    this.regulationTerminal = regulationTerminal;
    int variantArraySize = network.get().getVariantManager().getVariantArraySize();
    this.tapPosition = new TIntArrayList(variantArraySize);
    this.regulating = new TBooleanArrayList(variantArraySize);
    this.targetDeadband = new TDoubleArrayList(variantArraySize);
    for (int i = 0; i < variantArraySize; i++) {
        this.tapPosition.add(tapPosition);
        this.regulating.add(regulating);
        this.targetDeadband.add(targetDeadband);
    }
    this.type = Objects.requireNonNull(type);
}
 
Example #2
Source File: MovingAverageTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Test the slidingWindow value is correctly assigned when initializing a
 * new MovingAverage object.
 */
@Test
public void testMovingAverageSlidingWindowInit() {
    MovingAverage ma = new MovingAverage(new TDoubleArrayList(new double[] { 3., 4., 5., }), 3);
    assertEquals(new TDoubleArrayList(new double[] { 3., 4., 5., }), ma.getSlidingWindow());
    
    ma = new MovingAverage(null, 3);
    assertEquals(new TDoubleArrayList(), ma.getSlidingWindow());
    
    try {
        MovingAverage.compute(null, 0, 0, 0);
        fail();
    }catch(Exception e) {
        assertTrue(e.getClass().isAssignableFrom(IllegalArgumentException.class));
        assertEquals("slidingWindow cannot be null.", e.getMessage());
    }
}
 
Example #3
Source File: AnomalyLikelihood.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Given a list of anomaly scores return a list of averaged records.
 * anomalyScores is assumed to be a list of records of the form:
 * <pre>
 *      Sample:
 *           dt = Tuple(2013, 8, 10, 23, 0) --> Date Fields
 *           sample = (double) 6.0
 *           metric(avg) = (double) 1.0
 * </pre>
 *           
 * @param anomalyScores     List of {@link Sample} objects (described contents above)
 * @param windowSize        Count of historical items over which to compute the average
 * 
 * @return Each record in the returned list contains [datetime field, value, averaged score]
 */
public AveragedAnomalyRecordList anomalyScoreMovingAverage(List<Sample> anomalyScores, int windowSize) {
    TDoubleList historicalValues = new TDoubleArrayList();
    double total = 0.0;
    List<Sample> averagedRecordList = new ArrayList<Sample>();
    for(Sample record : anomalyScores) {
        ////////////////////////////////////////////////////////////////////////////////////////////
        // Python version has check for malformed records here, but can't happen in java version. //
        ////////////////////////////////////////////////////////////////////////////////////////////
        
        Calculation calc = MovingAverage.compute(historicalValues, total, record.score, windowSize);
        
        Sample avgRecord = new Sample(
            record.date,
            record.value,
            calc.getAverage());
        averagedRecordList.add(avgRecord);
        total = calc.getTotal();
        
        if(LOG.isDebugEnabled()) {
            LOG.debug("Aggregating input record: {}, Result: {}", record, averagedRecordList.get(averagedRecordList.size() - 1));
        }
    }
    
    return new AveragedAnomalyRecordList(averagedRecordList, historicalValues, total);
}
 
Example #4
Source File: MovingAverageTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Tests the equality of two separate instances with identical settings and state.
 */
@Test
public void testHashCodeAndEquals() {
    MovingAverage ma = new MovingAverage(new TDoubleArrayList(new double[] { 3., 4., 5., }), 3);
    MovingAverage ma2 = new MovingAverage(new TDoubleArrayList(new double[] { 3., 4., 5., }), 3);
    
    assertTrue(ma.equals(ma2));
    assertEquals(ma.hashCode(), ma2.hashCode());
    
    // Check that internal state is changed and that the equals
    // methods reflect the change.
    ma.next(120.0);
    
    assertFalse(ma.equals(ma2));
    assertNotEquals(ma.hashCode(), ma2.hashCode());
}
 
Example #5
Source File: SpatialPooler.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Update the inhibition radius. The inhibition radius is a measure of the
 * square (or hypersquare) of columns that each a column is "connected to"
 * on average. Since columns are are not connected to each other directly, we
 * determine this quantity by first figuring out how many *inputs* a column is
 * connected to, and then multiplying it by the total number of columns that
 * exist for each input. For multiple dimension the aforementioned
 * calculations are averaged over all dimensions of inputs and columns. This
 * value is meaningless if global inhibition is enabled.
 * 
 * @param c     the {@link Connections} (spatial pooler memory)
 */
public void updateInhibitionRadius(Connections c) {
    if(c.getGlobalInhibition()) {
        c.setInhibitionRadius(ArrayUtils.max(c.getColumnDimensions()));
        return;
    }

    TDoubleArrayList avgCollected = new TDoubleArrayList();
    int len = c.getNumColumns();
    for(int i = 0;i < len;i++) {
        avgCollected.add(avgConnectedSpanForColumnND(c, i));
    }
    double avgConnectedSpan = ArrayUtils.average(avgCollected.toArray());
    double diameter = avgConnectedSpan * avgColumnsPerInput(c);
    double radius = (diameter - 1) / 2.0d;
    radius = Math.max(1, radius);
    c.setInhibitionRadius((int)(radius + 0.5));
}
 
Example #6
Source File: ConfiguredBusImpl.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
ConfiguredBusImpl(String id, String name, boolean fictitious, VoltageLevelExt voltageLevel) {
    super(id, name, fictitious, voltageLevel);
    network = voltageLevel.getNetwork().getRef();
    int variantArraySize = network.get().getVariantManager().getVariantArraySize();
    terminals = new ArrayList<>(variantArraySize);
    v = new TDoubleArrayList(variantArraySize);
    angle = new TDoubleArrayList(variantArraySize);
    connectedComponentNumber = new TIntArrayList(variantArraySize);
    synchronousComponentNumber = new TIntArrayList(variantArraySize);
    for (int i = 0; i < variantArraySize; i++) {
        terminals.add(new ArrayList<>());
        v.add(Double.NaN);
        angle.add(Double.NaN);
        connectedComponentNumber.add(-1);
        synchronousComponentNumber.add(-1);
    }
}
 
Example #7
Source File: PassThroughEncoderTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
@Ignore
private void testCloseInner(int[] bitmap1, int[] bitmap2, double expectedScore){
	PassThroughEncoder<int[]> encoder = new PassThroughEncoder<>(9, ArrayUtils.where(bitmap1, ArrayUtils.WHERE_1).length);
	encoder.setName("foo");
	
	int[] out1 = encoder.encode(bitmap1);
	encoder.setW(ArrayUtils.where(bitmap2, ArrayUtils.WHERE_1).length);
	int[] out2 = encoder.encode(bitmap2);

	TDoubleList result = encoder.closenessScores(new TDoubleArrayList(ArrayUtils.toDoubleArray(out1)), new TDoubleArrayList(ArrayUtils.toDoubleArray(out2)), true);
	assertTrue(result.size() == 1 );
	assertEquals(expectedScore, result.get(0), 0.0);
	
	encoder = PassThroughEncoder.builder()
			.n(9)
			.w(ArrayUtils.where(bitmap1, ArrayUtils.WHERE_1).length)
			.name("foo")
			.build();
	out1 = encoder.encode(bitmap1);
	encoder.setW(ArrayUtils.where(bitmap2, ArrayUtils.WHERE_1).length);
	out2 = encoder.encode(bitmap2);
	result = encoder.closenessScores(new TDoubleArrayList(ArrayUtils.toDoubleArray(out1)), new TDoubleArrayList(ArrayUtils.toDoubleArray(out2)), true);
	assertTrue(result.size() == 1 );
	assertEquals(expectedScore, result.get(0), 0.0);
}
 
Example #8
Source File: GeneratorImpl.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
GeneratorImpl(Ref<? extends VariantManagerHolder> ref,
              String id, String name, boolean fictitious, EnergySource energySource,
              double minP, double maxP,
              boolean voltageRegulatorOn, TerminalExt regulatingTerminal,
              double targetP, double targetQ, double targetV,
              double ratedS) {
    super(id, name, fictitious);
    this.energySource = energySource;
    this.minP = minP;
    this.maxP = maxP;
    this.reactiveLimits = new ReactiveLimitsHolderImpl(this, new MinMaxReactiveLimitsImpl(-Double.MAX_VALUE, Double.MAX_VALUE));
    this.regulatingTerminal = regulatingTerminal;
    this.ratedS = ratedS;
    int variantArraySize = ref.get().getVariantManager().getVariantArraySize();
    this.voltageRegulatorOn = new TBooleanArrayList(variantArraySize);
    this.targetP = new TDoubleArrayList(variantArraySize);
    this.targetQ = new TDoubleArrayList(variantArraySize);
    this.targetV = new TDoubleArrayList(variantArraySize);
    for (int i = 0; i < variantArraySize; i++) {
        this.voltageRegulatorOn.add(voltageRegulatorOn);
        this.targetP.add(targetP);
        this.targetQ.add(targetQ);
        this.targetV.add(targetV);
    }
}
 
Example #9
Source File: DanglingLineImpl.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
DanglingLineImpl(Ref<? extends VariantManagerHolder> network, String id, String name, boolean fictitious, double p0, double q0, double r, double x, double g, double b, String ucteXnodeCode) {
    super(id, name, fictitious);
    this.network = network;
    int variantArraySize = network.get().getVariantManager().getVariantArraySize();
    this.p0 = new TDoubleArrayList(variantArraySize);
    this.q0 = new TDoubleArrayList(variantArraySize);
    for (int i = 0; i < variantArraySize; i++) {
        this.p0.add(p0);
        this.q0.add(q0);
    }
    this.r = r;
    this.x = x;
    this.g = g;
    this.b = b;
    this.ucteXnodeCode = ucteXnodeCode;
}
 
Example #10
Source File: ShuntCompensatorImpl.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
ShuntCompensatorImpl(Ref<? extends VariantManagerHolder> network,
                     String id, String name, boolean fictitious, ShuntCompensatorModelWrapper model,
                     int sectionCount, TerminalExt regulatingTerminal, boolean voltageRegulatorOn,
                     double targetV, double targetDeadband) {
    super(id, name, fictitious);
    this.network = network;
    this.model = attach(model);
    this.regulatingTerminal = regulatingTerminal;
    int variantArraySize = network.get().getVariantManager().getVariantArraySize();
    this.sectionCount = new TIntArrayList(variantArraySize);
    this.voltageRegulatorOn = new TBooleanArrayList(variantArraySize);
    this.targetV = new TDoubleArrayList(variantArraySize);
    this.targetDeadband = new TDoubleArrayList(variantArraySize);
    for (int i = 0; i < variantArraySize; i++) {
        this.sectionCount.add(sectionCount);
        this.voltageRegulatorOn.add(voltageRegulatorOn);
        this.targetV.add(targetV);
        this.targetDeadband.add(targetDeadband);
    }
}
 
Example #11
Source File: SDRCategoryEncoder.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <S> TDoubleList getScalars(S input) {
    String inputCasted = (String)input;
    int index = 0;
    TDoubleList result = new TDoubleArrayList();
    if (inputCasted == null || inputCasted.isEmpty()) {
        result.add(0);
        return result;
    }
    if (!sdrByCategory.containsKey(input)) {
        if (isEncoderLearningEnabled()) {
            index = sdrByCategory.size();
            addCategory(inputCasted);
        }
    } else {
        index = sdrByCategory.getIndexByCategory(inputCasted);
    }
    result.add(index);
    return result;
}
 
Example #12
Source File: StaticVarCompensatorImpl.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
StaticVarCompensatorImpl(String id, String name, boolean fictitious, double bMin, double bMax, double voltageSetPoint, double reactivePowerSetPoint,
                         RegulationMode regulationMode, TerminalExt regulatingTerminal, Ref<? extends VariantManagerHolder> ref) {
    super(id, name, fictitious);
    this.bMin = bMin;
    this.bMax = bMax;
    int variantArraySize = ref.get().getVariantManager().getVariantArraySize();
    this.voltageSetPoint = new TDoubleArrayList(variantArraySize);
    this.reactivePowerSetPoint = new TDoubleArrayList(variantArraySize);
    this.regulationMode = new TIntArrayList(variantArraySize);
    this.regulatingTerminal = regulatingTerminal;
    for (int i = 0; i < variantArraySize; i++) {
        this.voltageSetPoint.add(voltageSetPoint);
        this.reactivePowerSetPoint.add(reactivePowerSetPoint);
        this.regulationMode.add(regulationMode.ordinal());
    }
}
 
Example #13
Source File: ScalarEncoderTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Test closenessScores for a periodic encoder
 */
@Test
public void testCloseness() {
	setUp();
	builder.name("day of week")
        .w(7)
        .radius(1.0)
        .minVal(0.0)
        .maxVal(7.0)
        .periodic(true)
        .forced(true);
	initSE();
	
	TDoubleList expValues = new TDoubleArrayList(new double[] { 2, 4, 7 });
	TDoubleList actValues = new TDoubleArrayList(new double[] { 4, 2, 1 });
	
	TDoubleList scores = se.closenessScores(expValues, actValues, false);
	for(Tuple t : ArrayUtils.zip(Arrays.asList(2, 2, 1), Arrays.asList(scores.get(0)))) {
		double a = (int)t.get(0);
		double b = (double)t.get(1);
		assertTrue(a == b);
	}
}
 
Example #14
Source File: TimeSeries.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
void parseToken(int i, String token) {
    if (dataTypes[i - 2] == null) {
        // test double parsing, in case of error we consider it a string time series
        if (Doubles.tryParse(token) != null) {
            dataTypes[i - 2] = TimeSeriesDataType.DOUBLE;
            TDoubleArrayList doubleValues = createDoubleValues();
            doubleValues.add(parseDouble(token));
            values[i - 2] = doubleValues;
        } else {
            dataTypes[i - 2] = TimeSeriesDataType.STRING;
            List<String> stringValues = createStringValues();
            stringValues.add(checkString(token));
            values[i - 2] = stringValues;
        }
    } else {
        if (dataTypes[i - 2] == TimeSeriesDataType.DOUBLE) {
            ((TDoubleArrayList) values[i - 2]).add(parseDouble(token));
        } else if (dataTypes[i - 2] == TimeSeriesDataType.STRING) {
            ((List<String>) values[i - 2]).add(checkString(token));
        } else {
            throw assertDataType(dataTypes[i - 2]);
        }
    }
}
 
Example #15
Source File: LogEncoderTest.java    From htm.java with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testClosenessCalculations() {
	setUp();
	initLE();
	
	double[] expectedValues = new double[]{1., 1., 1., 1.};
	double[] actualValues = new double[]{10000., 1000., 1., -200.};
	double[] expectedResults = new double[]{0.0, 0.25, 1.0, 1.0};
	
	for (int i = 0; i < expectedValues.length; i++) {
		assertEquals(String.format("exp: %.0f act: %.0f expR: 0.2f", expectedValues[i], actualValues[i], expectedResults[i]),
					 le.closenessScores(new TDoubleArrayList(new double[] {expectedValues[i]}), 
							 new TDoubleArrayList(new double[] {actualValues[i]}),
							 true).get(0),
					 expectedResults[i], 1e-07);
	}
}
 
Example #16
Source File: Encoder.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
public TDoubleList closenessScores(TDoubleList expValues, TDoubleList actValues, boolean fractional) {
	TDoubleList retVal = new TDoubleArrayList();

	//Fallback closenss is a percentage match
	List<EncoderTuple> encoders = getEncoders(this);
	if(encoders == null || encoders.size() < 1) {
		double err = Math.abs(expValues.get(0) - actValues.get(0));
		double closeness = -1;
		if(fractional) {
			double denom = Math.max(expValues.get(0), actValues.get(0));
			if(denom == 0) {
				denom = 1.0;
			}

			closeness = 1.0 - err/denom;
			if(closeness < 0) {
				closeness = 0;
			}
		}else{
			closeness = err;
		}

		retVal.add(closeness);
		return retVal;
	}

	int scalarIdx = 0;
	for(EncoderTuple res : getEncoders(this)) {
		TDoubleList values = res.getEncoder().closenessScores(
			expValues.subList(scalarIdx, expValues.size()), actValues.subList(scalarIdx, actValues.size()), fractional);

		scalarIdx += values.size();
		retVal.addAll(values);
	}

	return retVal;
}
 
Example #17
Source File: ScalarEncoder.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @param <S>	the input value, in this case a double
 * @return	a list of one input double
 */
@Override
public <S> TDoubleList getScalars(S d) {
    TDoubleList retVal = new TDoubleArrayList();
    retVal.add((Double)d);
    return retVal;
}
 
Example #18
Source File: MovingAverageTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Test that we get the expected exception and that window size specified
 * must be > 0.
 */
@Test
public void testProperConstruction() {
    try {
        new MovingAverage(new TDoubleArrayList(new double[] { 3., 4., 5., }), 0);
        fail();
    }catch(Exception e) {
        assertTrue(e.getClass().isAssignableFrom(IllegalArgumentException.class));
        assertEquals("Window size must be > 0", e.getMessage());
    }
}
 
Example #19
Source File: CShareableResource.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean inject(Parameters ps, ReconfigurationProblem p) throws SchedulerException {
    this.rp = p;
    this.references = new HashMap<>();
    this.clones = new HashMap<>();
    csp = p.getModel();
    this.source = p.getSourceModel();
    List<Node> nodes = p.getNodes();
    phyRcUsage = new ArrayList<>(nodes.size());
    virtRcUsage = new ArrayList<>(nodes.size());
    this.ratios = new TDoubleArrayList(nodes.size());
    id = ShareableResource.VIEW_ID_BASE + rc.getResourceIdentifier();
    for (Node nId : p.getNodes()) {
        phyRcUsage.add(csp.intVar(p.makeVarLabel("phyRcUsage('", rc.getResourceIdentifier(), "', '", nId, "')"), 0, rc.getCapacity(nId), true));
        virtRcUsage.add(csp.intVar(p.makeVarLabel("virtRcUsage('", rc.getResourceIdentifier(), "', '", nId, "')"), 0, Integer.MAX_VALUE / 100, true));
        ratios.add(UNCHECKED_RATIO);
    }
    phyRcUsage = Collections.unmodifiableList(phyRcUsage);
    virtRcUsage = Collections.unmodifiableList(virtRcUsage);

    //Bin packing for the node vmAllocation

    vmAllocation = new TIntArrayList();
    for (VM vmId : p.getVMs()) {
        VMTransition a = p.getVMAction(vmId);
        Slice slice = a.getDSlice();
        if (slice == null) {
            //The VMs will not be running, so its consumption is set to 0
            vmAllocation.add(0);
        } else {
            //We don't know about the next VM usage for the moment, -1 is used by default to allow to detect an
            //non-updated value.
            vmAllocation.add(-1);
        }
    }
    return true;

}
 
Example #20
Source File: VscConverterStationImpl.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
VscConverterStationImpl(String id, String name, boolean fictitious, float lossFactor, Ref<? extends VariantManagerHolder> ref,
                        boolean voltageRegulatorOn, double reactivePowerSetpoint, double voltageSetpoint) {
    super(id, name, fictitious, lossFactor);
    int variantArraySize = ref.get().getVariantManager().getVariantArraySize();
    this.voltageRegulatorOn = new TBooleanArrayList(variantArraySize);
    this.reactivePowerSetpoint = new TDoubleArrayList(variantArraySize);
    this.voltageSetpoint = new TDoubleArrayList(variantArraySize);
    this.voltageRegulatorOn.fill(0, variantArraySize, voltageRegulatorOn);
    this.reactivePowerSetpoint.fill(0, variantArraySize, reactivePowerSetpoint);
    this.voltageSetpoint.fill(0, variantArraySize, voltageSetpoint);
    this.reactiveLimits = new ReactiveLimitsHolderImpl(this, new MinMaxReactiveLimitsImpl(-Double.MAX_VALUE, Double.MAX_VALUE));
}
 
Example #21
Source File: RatioTapChangerImpl.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
RatioTapChangerImpl(RatioTapChangerParent parent, int lowTapPosition,
                    List<RatioTapChangerStepImpl> steps, TerminalExt regulationTerminal, boolean loadTapChangingCapabilities,
                    int tapPosition, boolean regulating, double targetV, double targetDeadband) {
    super(parent.getNetwork().getRef(), parent, lowTapPosition, steps, regulationTerminal, tapPosition, regulating, targetDeadband, "ratio tap changer");
    this.loadTapChangingCapabilities = loadTapChangingCapabilities;
    int variantArraySize = network.get().getVariantManager().getVariantArraySize();
    this.targetV = new TDoubleArrayList(variantArraySize);
    for (int i = 0; i < variantArraySize; i++) {
        this.targetV.add(targetV);
    }
}
 
Example #22
Source File: FloodFillTransformedPlane.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private void addIfInside(
		final boolean isRelevant,
		final long fillLabel,
		final long pixelLabel,
		final TLongArrayList labelCoordinates,
		final TDoubleArrayList worldCoordinates,
		final long lx,
		final long ly,
		final long lz,
		final double wx,
		final double wy,
		final double wz,
		final double zMinInclusive,
		final double zMaxInclusive)
{
	if (isRelevant && fillLabel != pixelLabel && wz >= zMinInclusive && wz <= zMaxInclusive)
	{
		if (wx > minX && wx < maxX && wy > minY && wy < maxY)
		{
			labelCoordinates.add(lx);
			labelCoordinates.add(ly);
			labelCoordinates.add(lz);

			worldCoordinates.add(wx);
			worldCoordinates.add(wy);
			worldCoordinates.add(wz);
		}
	}
}
 
Example #23
Source File: LogEncoder.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public TDoubleList closenessScores(TDoubleList expValues, TDoubleList actValues, boolean fractional) {
	TDoubleList retVal = new TDoubleArrayList();

	double expValue, actValue;
	if (expValues.get(0) > 0) {
		expValue = Math.log10(expValues.get(0));
	} else {
		expValue = minScaledValue;
	}
	if (actValues.get(0) > 0) {
		actValue = Math.log10(actValues.get(0));
	} else {
		actValue = minScaledValue;
	}

	double closeness;
	if (fractional) {
		double err = Math.abs(expValue - actValue);
		double pctErr = err / (maxScaledValue - minScaledValue);
		pctErr = Math.min(1.0,  pctErr);
		closeness = 1.0 - pctErr;
	} else {
		closeness = Math.abs(expValue - actValue);;
	}

	retVal.add(closeness);
	return retVal;
}
 
Example #24
Source File: CategoryEncoder.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public TDoubleList closenessScores(TDoubleList expValues, TDoubleList actValues, boolean fractional) {
	double expValue = expValues.get(0);
	double actValue = actValues.get(0);

	double closeness = expValue == actValue ? 1.0 : 0;
	if(!fractional) closeness = 1.0 - closeness;

	return new TDoubleArrayList(new double[]{ closeness });
}
 
Example #25
Source File: ArrayUtils.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns an array of values that test true for all of the
 * specified {@link Condition}s.
 *
 * @param values
 * @param conditions
 * @return
 */
public static double[] retainLogicalAnd(double[] values, Condition<?>[] conditions) {
    TDoubleArrayList l = new TDoubleArrayList();
    for (int i = 0; i < values.length; i++) {
        boolean result = true;
        for (int j = 0; j < conditions.length && result; j++) {
            result &= conditions[j].eval(values[i]);
        }
        if (result) l.add(values[i]);
    }
    return l.toArray();
}
 
Example #26
Source File: Anomaly.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns a list of the averages in the contained averaged record list.
 * @return
 */
public TDoubleList getMetrics() {
    TDoubleList retVal = new TDoubleArrayList();
    for(Sample s : averagedRecords) {
        retVal.add(s.score);
    }
    
    return retVal;
}
 
Example #27
Source File: Anomaly.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns a list of the sample values in the contained averaged record list.
 * @return
 */
public TDoubleList getSamples() {
    TDoubleList retVal = new TDoubleArrayList();
    for(Sample s : averagedRecords) {
        retVal.add(s.value);
    }
    
    return retVal;
}
 
Example #28
Source File: MovingAverage.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructs a new {@code MovingAverage}
 * 
 * @param historicalValues  list of entry values
 * @param windowSize        length over which to take the average
 */
public MovingAverage(TDoubleList historicalValues, double total, int windowSize) {
    if(windowSize <= 0) {
        throw new IllegalArgumentException("Window size must be > 0");
    }
    this.windowSize = windowSize;
    
    calc = new Calculation();
    calc.historicalValues = 
        historicalValues == null || historicalValues.size() < 1 ?
            new TDoubleArrayList(windowSize) : historicalValues;
    calc.total = total != -1 ? total : calc.historicalValues.sum();
}
 
Example #29
Source File: SparsePassThroughEncoderTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@Ignore
private void testCloseInner(int[] bitmap1, int outputWidth1, int[] bitmap2, int outputWidth2, double expectedScore) {
    SparsePassThroughEncoder encoder1 = new SparsePassThroughEncoder(outputWidth1, ArrayUtils.where(bitmap1, ArrayUtils.GREATER_OR_EQUAL_0).length);
    SparsePassThroughEncoder encoder2 = new SparsePassThroughEncoder(outputWidth2, ArrayUtils.where(bitmap2, ArrayUtils.GREATER_OR_EQUAL_0).length);

    int[] out1 = encoder1.encode(bitmap1);
    int[] out2 = encoder2.encode(bitmap2);

    TDoubleList result = encoder1.closenessScores(new TDoubleArrayList(ArrayUtils.toDoubleArray(out1)), new TDoubleArrayList(ArrayUtils.toDoubleArray(out2)), true);
    assertTrue(result.size() == 1);
    assertEquals(expectedScore, result.get(0), 0.0);

    encoder1 = SparsePassThroughEncoder.sparseBuilder()
            .n(outputWidth1)
            .w(ArrayUtils.where(bitmap1, ArrayUtils.GREATER_OR_EQUAL_0).length)
            .build();
    encoder2 = SparsePassThroughEncoder.sparseBuilder()
            .n(outputWidth2)
            .w(ArrayUtils.where(bitmap2, ArrayUtils.GREATER_OR_EQUAL_0).length)
            .build();

    out1 = encoder1.encode(bitmap1);
    out2 = encoder2.encode(bitmap2);

    result = encoder1.closenessScores(new TDoubleArrayList(ArrayUtils.toDoubleArray(out1)), new TDoubleArrayList(ArrayUtils.toDoubleArray(out2)), true);
    assertTrue(result.size() == 1);
    assertEquals(expectedScore, result.get(0), 0.0);
}
 
Example #30
Source File: AnomalyLikelihoodMetricsTest.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("serial")
@Test
public void testCopy() {
    double[] likelihoods = new double[] { 0.2, 0.3 };

    Sample s = new Sample(new DateTime(), 0.1, 0.1);
    List<Sample> samples = new ArrayList<>();
    samples.add(s);
    TDoubleList d = new TDoubleArrayList();
    d.add(0.5);
    double total = 0.4;
    AveragedAnomalyRecordList avges = (
            new Anomaly() {
                @Override
                public double compute(int[] activeColumns, int[] predictedColumns, double inputValue, long timestamp) {
                    return 0;
                }
            }
    ).new AveragedAnomalyRecordList(samples, d, total);

    Statistic stat = new Statistic(0.1, 0.1, 0.1);
    MovingAverage ma = new MovingAverage(new TDoubleArrayList(), 1);
    AnomalyParams params = new AnomalyParams(new String[] { Anomaly.KEY_DIST, Anomaly.KEY_MVG_AVG, Anomaly.KEY_HIST_LIKE}, stat, ma, likelihoods);

    // Test equality
    AnomalyLikelihoodMetrics metrics = new AnomalyLikelihoodMetrics(likelihoods, avges, params);
    AnomalyLikelihoodMetrics metrics2 = metrics.copy();
    assertEquals(metrics, metrics2);
}