Calculates the error between the autoencoder's reconstruction of the input and the argument instances.
This error is converted to vote scores.

@param inst the instance to get votes for

@return the votes for the instance's label [normal, outlier]
4946
@Override
	public double[] getVotesForInstance(Instance inst)
	{
		double[] votes = new double[2];

		if (this.reset == false)
		{
			double error = this.getAnomalyScore(inst);
			
			// Exponential function to convert the error [0, +inf) into a vote [1,0].
			votes[0] = Math.pow(2.0, -1.0 * (error / this.threshold));
			votes[1] = 1.0 - votes[0];
		}

		return votes;
	}
1001349
public static double[] doNaiveBayesPredictionLog(Instance inst,
            DoubleVector observedClassDistribution,
            AutoExpandVector<AttributeClassObserver> observers, AutoExpandVector<AttributeClassObserver> observers2) {
        AttributeClassObserver obs;
        double[] votes = new double[observedClassDistribution.numValues()];
        double observedClassSum = observedClassDistribution.sumOfValues();
        for (int classIndex = 0; classIndex < votes.length; classIndex++) {
            votes[classIndex] = Math.log10(observedClassDistribution.getValue(classIndex)
                    / observedClassSum);
            for (int attIndex = 0; attIndex < inst.numAttributes() - 1; attIndex++) {
                int instAttIndex = modelAttIndexToInstanceAttIndex(attIndex,
                        inst);
                if (inst.attribute(instAttIndex).isNominal()) {
                    obs = observers.get(attIndex);
                } else {
                    obs = observers2.get(attIndex);
                }

                if ((obs != null) && !inst.isMissing(instAttIndex)) {
                    votes[classIndex] += Math.log10(obs.probabilityOfAttributeValueGivenClass(inst.value(instAttIndex), classIndex));

                }
            }
        }
        return votes;

    }
1134897
private double prediction(Instance inst)
	{
		if(this.initialisePerceptron){
			return 0;
		}else{
			double[] normalizedInstance = normalizedInstance(inst); 
			double normalizedPrediction = prediction(normalizedInstance);
			return denormalizedPrediction(normalizedPrediction);
		}
	}
1129203
@Override
    public int predict(T x) {
        List<Neighbor<T,T>> neighbors = new ArrayList<>();
        nns.range(x, radius, neighbors);
        
        if (neighbors.size() < minPts) {
            return OUTLIER;
        }
        
        int[] label = new int[k + 1];
        for (Neighbor<T,T> neighbor : neighbors) {
            int yi = y[neighbor.index];
            if (yi == OUTLIER) yi = k;
            label[yi]++;
        }
        
        int c = Math.whichMax(label);
        if (c == k) c = OUTLIER;
        return c;
    }
645719
public void trainOnInstanceImpl(Instance inst) {
		accumulatedError= Math.abs(this.prediction(inst)-inst.classValue()) + fadingFactor*accumulatedError;
		nError=1+fadingFactor*nError;
		// Initialise Perceptron if necessary   
		if (this.initialisePerceptron) {
			//this.fadingFactor=this.fadingFactorOption.getValue();
			//this.classifierRandom.setSeed(randomSeedOption.getValue());
			this.classifierRandom.setSeed(randomSeed);
			this.initialisePerceptron = false; // not in resetLearningImpl() because it needs Instance!
			this.weightAttribute = new double[inst.numAttributes()];
			for (int j = 0; j < inst.numAttributes(); j++) {
				weightAttribute[j] = 2 * this.classifierRandom.nextDouble() - 1;
			}
			// Update Learning Rate
			learningRatio = originalLearningRatio;
			//this.learningRateDecay = learningRateDecayOption.getValue();

		}

		// Update attribute statistics
		this.perceptronInstancesSeen++;
		this.perceptronYSeen++;


		for(int j = 0; j < inst.numAttributes() -1; j++)
		{
			perceptronattributeStatistics.addToValue(j, inst.value(j));     
			squaredperceptronattributeStatistics.addToValue(j, inst.value(j)*inst.value(j));
		}
		this.perceptronsumY += inst.classValue();
		this.squaredperceptronsumY += inst.classValue() * inst.classValue();

		if(!constantLearningRatioDecay){
			learningRatio = originalLearningRatio / (1+ perceptronInstancesSeen*learningRateDecay); 
		}

		this.updateWeights(inst,learningRatio);
		//this.printPerceptron();
	}
1340508
@Override
    public double[] getVotesForInstance(Instance inst) {

		double vSTM[];
		double vLTM[];
		double vCM[];
		double v[];
		double distancesSTM[];
		double distancesLTM[];
        int predClassSTM = 0;
        int predClassLTM = 0;
        int predClassCM = 0;
		try {
			if (this.stm.numInstances()>0) {
				distancesSTM = get1ToNDistances(inst, this.stm);
				int nnIndicesSTM[] = nArgMin(Math.min(distancesSTM.length, this.kOption.getValue()), distancesSTM);
				vSTM = getDistanceWeightedVotes(distancesSTM, nnIndicesSTM, this.stm);
                predClassSTM = this.getClassFromVotes(vSTM);
                distancesLTM = get1ToNDistances(inst, this.ltm);
                vCM = getCMVotes(distancesSTM, this.stm, distancesLTM, this.ltm);
                predClassCM = this.getClassFromVotes(vCM);
				if (this.ltm.numInstances() >= 0) {
                    int nnIndicesLTM[] = nArgMin(Math.min(distancesLTM.length, this.kOption.getValue()), distancesLTM);
                    vLTM = getDistanceWeightedVotes(distancesLTM, nnIndicesLTM, this.ltm);
                    predClassLTM = this.getClassFromVotes(vLTM);
                }else{
                    vLTM = new double[inst.numClasses()];
                }
                int correctSTM = historySum(this.stmHistory);
                int correctLTM = historySum(this.ltmHistory);
                int correctCM = historySum(this.cmHistory);
                if(correctSTM>=correctLTM && correctSTM>=correctCM){
                    v=vSTM;
                }else if(correctLTM>correctSTM && correctLTM>=correctCM){
                    v=vLTM;
                }else{
                    v=vCM;
                }
            }else {
                v = new double[inst.numClasses()];
            }
            this.stmHistory.add((predClassSTM==inst.classValue()) ? 1 : 0);
            this.ltmHistory.add((predClassLTM==inst.classValue()) ? 1 : 0);
            this.cmHistory.add((predClassCM==inst.classValue()) ? 1 : 0);
		} catch(Exception e) {
			return new double[inst.numClasses()];
		}
		return v;
    }
62675
protected int score(MediaType contentTypeFromRequest, MediaType... expectedTypes) {
        if (contentTypeFromRequest == null) {
            return DEFAULT_SCORE;
        }
        for (MediaType expected : expectedTypes) {
            if (contentTypeFromRequest.matches(expected)) {
                return MAXIMUM_FORMAT_SCORE;
            }
        }
        return DEFAULT_SCORE;
    }
1212574
@Override
	public void trainOnInstanceImpl(Instance inst) {
		
		//System.out.print("Dstream.trainOnInstanceImpl (");
		int[]g;
		DensityGrid dg;
		CharacteristicVector cv;
		boolean recalculateN = false;	// flag indicating whether N needs to be recalculated after this instance

		// 1. Read record x = (x1,x2,...,xd)
		//printInst(inst);
		//System.out.println(") time "+this.getCurrTime());
		// Passed Instance inst
		if (!this.initialized)
		{
			//System.out.println("Not yet initialized");
			this.d = inst.numAttributes();
			//System.out.println("d = "+this.d);
			this.minVals = new int[this.d];
			this.maxVals = new int[this.d];
			//System.out.println("...data initialized");
			
			for(int i = 0 ; i < this.d ; i++)
			{
				//System.out.print(i+" ");
				if (inst.attribute(i).isNumeric())
				{
					maxVals[i] = (int) inst.value(i);
					minVals[i] = (int) inst.value(i);
				}
			}
			//System.out.println("...arrays initialized");
			recalculateN = true;
			this.initialized = true;
			//System.out.println("...boolean values initialized");
			//System.out.print("Grid list is: ");
			//printGridList();
		}		

		// 2. Determine the density grid g that contains x
		//System.out.print(" & Step 2 ");
		g = new int[this.d];

		for (int i = 0 ; i < this.d ; i++)
		{
			if (inst.attribute(i).isNumeric())
			{
				g[i] = (int) inst.value(i);
				if (g[i] > maxVals[i])
				{
					maxVals[i] = g[i];
					recalculateN = true;
				}
				else if (g[i] < minVals[i])
				{
					minVals[i] = g[i];
					recalculateN = true;
				}
			}
			else
			{
				g[i] = (int) inst.value(i);
			}
		}

		if (recalculateN)
		{
			//System.out.print(" recalculateN:");
			int n = 1;
			for (int i = 0 ; i < this.d ; i++)
			{
				//System.out.print(" "+n);
				if (inst.attribute(i).isNominal())
					n = n * inst.attribute(i).numValues();
				else
					n = n * (3+maxVals[i]-minVals[i]);
			}
			//System.out.print(" "+n);
			this.N = n;
			this.dl = this.cl/(this.N * (1.0 - this.decayFactor));
			this.dm = this.cm/(this.N * (1.0 - this.decayFactor));
			//System.out.print(" dl = " + this.dl + ", dm = " + this.dm);
			
			//Calculate the value for gap using the method defined in eq 26 of Chen and Tu 2007 
			double optionA = this.cl/this.cm;
			double optionB = ((double)this.N-this.cm)/((double)this.N-this.cl);
			gap = (int)Math.floor(Math.log(Math.max(optionA, optionB))/Math.log(this.getDecayFactor()));
			// Ensure that gap is not zero (i.e. if the procedure to calculate gap rounds down to zero, then set gap to 1 and adjust clustering every instance)
			if(gap == 0)
			{
				gap = 1;
			}
			//System.out.println(" A is "+optionA+", B is "+optionB+" and gap = "+gap);
		}

		dg = new DensityGrid(g);
		//System.out.println(dg.toString());
		
		// 3. If (g not in grid_list) insert dg to grid_list
		//System.out.println(" & Step 3 or 4");
		
		if(!this.grid_list.containsKey(dg))
		{
			//System.out.print("3 - dg wasn't in grid_list!");
			if(this.deleted_grids.containsKey(dg))
			{
				//System.out.print(" but it was in deleted_grids!");
				cv = new CharacteristicVector(this.getCurrTime(), this.deleted_grids.get(dg).intValue(), 1.0, -1, false, this.getDL(), this.getDM());
				this.deleted_grids.remove(dg);
			}
			else
				cv = new CharacteristicVector(this.getCurrTime(), -1, 1.0, -1, false, this.getDL(), this.getDM());
			
			this.grid_list.put(dg, cv);
			//System.out.print(" "+dg.toString()+" "+cv.toString());
			//System.out.println(" The size of grid_list is now "+grid_list.size());
		}
		// 4. Update the characteristic vector of dg
		else
		{
			//System.out.print("4 - dg was in grid_list!");
			cv = this.grid_list.get(dg);
				
			cv.densityWithNew(this.getCurrTime(), this.getDecayFactor());
				
			cv.setUpdateTime(this.getCurrTime());
		
			//System.out.println(" "+dg.toString()+" "+cv.toString());
		
			grid_list.put(dg, cv);
		}

		// 5. If tc == gap, then initial clustering
		// and
		// 6. If tc mod gap == 0, then:
		//    a. Detect and remove sporadic grids from grid_list
		//    b. Adjust clustering
		//System.out.println("\nCurrent Time is " + this.getCurrTime() + " and gap is " + this.gap);
		if (this.getCurrTime() != 0 && this.getCurrTime() % gap == 0)
		{
			if (this.getCurrTime() == gap)
			{
				//System.out.print(" & Step 5 x6x");
				this.initialClustering();
			}
			else
			{
				//System.out.print(" & Step x5x 6");
				this.removeSporadic();
				this.adjustClustering();
			}
		}

		// 7. Increment tc
		//System.out.println(" & Step 7");
		this.incCurrTime();

	}
383682
protected double computeWeight(Classifier learner, Instances chunk) {
        double mse_i = 0;
        double mse_r = 0;

        double f_ci;
        double voteSum;

        for (int i = 0; i < chunk.numInstances(); i++) {
            try {
                voteSum = 0;
                for (double element : learner.getVotesForInstance(chunk.instance(i))) {
                    voteSum += element;
                }

                if (voteSum > 0) {
                    f_ci = learner.getVotesForInstance(chunk.instance(i))[(int) chunk.instance(i).classValue()] / voteSum;
                    mse_i += (1 - f_ci) * (1 - f_ci);
                } else {
                    mse_i += 1;
                }
            } catch (Exception e) {
                mse_i += 1;
            }
        }

        mse_i /= this.chunkSize;
        mse_r = this.computeMseR();

        return java.lang.Math.max(mse_r - mse_i, 0);
    }
1315387
public OutlierResult run(Relation<Model> models, Relation<NumberVector> vecs, Relation<?> labels) {
    WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(models.getDBIDs(), DataStoreFactory.HINT_HOT);

    HashSet<GeneratorSingleCluster> generators = new HashSet<>();
    for(DBIDIter iditer = models.iterDBIDs(); iditer.valid(); iditer.advance()) {
      Model model = models.get(iditer);
      if(model instanceof GeneratorSingleCluster) {
        generators.add((GeneratorSingleCluster) model);
      }
    }
    if(generators.isEmpty()) {
      LOG.warning("No generator models found for dataset - all points will be considered outliers.");
    }
    for(GeneratorSingleCluster gen : generators) {
      for(int i = 0; i < gen.getDim(); i++) {
        Distribution dist = gen.getDistribution(i);
        if(!(dist instanceof NormalDistribution)) {
          throw new AbortException("TrivialGeneratedOutlier currently only supports normal distributions, got: " + dist);
        }
      }
    }

    for(DBIDIter iditer = models.iterDBIDs(); iditer.valid(); iditer.advance()) {
      double score = 1.;
      double[] v = vecs.get(iditer).toArray();
      for(GeneratorSingleCluster gen : generators) {
        double[] tv = v;
        // Transform backwards
        if(gen.getTransformation() != null) {
          tv = gen.getTransformation().applyInverse(v);
        }
        final int dim = tv.length;
        double lensq = 0.0;
        int norm = 0;
        for(int i = 0; i < dim; i++) {
          Distribution dist = gen.getDistribution(i);
          if(dist instanceof NormalDistribution) {
            NormalDistribution d = (NormalDistribution) dist;
            double delta = (tv[i] - d.getMean()) / d.getStddev();
            lensq += delta * delta;
            norm += 1;
          }
          else {
            throw new AbortException("TrivialGeneratedOutlier currently only supports normal distributions, got: " + dist);
          }
        }
        if(norm > 0.) {
          // The squared distances are ChiSquared distributed
          score = Math.min(score, ChiSquaredDistribution.cdf(lensq, norm));
        }
        else {
          score = 0.;
        }
      }
      if(expect < 1) {
        score = expect * score / (1 - score + expect);
      }
      scores.putDouble(iditer, score);
    }
    DoubleRelation scoreres = new MaterializedDoubleRelation("Model outlier scores", "model-outlier", scores, models.getDBIDs());
    OutlierScoreMeta meta = new ProbabilisticOutlierScore(0., 1.);
    return new OutlierResult(meta, scoreres);
  }
489672
public double score(StringWrapper s,StringWrapper t) {
		if (scaling) {
			int minLen = Math.min( s.unwrap().length(), t.unwrap().length() );
			return super.score(s,t) / (minLen * CHAR_EXACT_MATCH_SCORE);
		} else {
			return super.score(s,t);
		}
	}
647407
protected double computeMse(Classifier learner, Instances chunk) {
		double mse_i = 0;

		double f_ci;
		double voteSum;

		for (int i = 0; i < chunk.numInstances(); i++) {
			try {
				voteSum = 0;
				for (double element : learner.getVotesForInstance(chunk.instance(i))) {
					voteSum += element;
				}

				if (voteSum > 0) {
					f_ci = learner.getVotesForInstance(chunk.instance(i))[(int) chunk.instance(i).classValue()]
							/ voteSum;
					mse_i += (1 - f_ci) * (1 - f_ci);
				} else {
					mse_i += 1;
				}
			} catch (Exception e) {
				mse_i += 1;
			}
		}

		mse_i /= this.chunkSizeOption.getValue();

		return mse_i;
	}
1092378
@Override
    public void trainOnInstanceImpl(Instance inst) {
        this.epochs++;
        double[] Pr = new double[inst.numClasses()];
        double maxWeight = 0.0;
        double weakestExpertWeight = 1.0;
        int weakestExpertIndex = -1;
        // Loop over experts
        for (int i = 0; i < this.experts.size(); i++) {
            double[] pr = this.experts.get(i).getVotesForInstance(inst);
            int yHat = Utils.maxIndex(pr);
            if ((yHat != (int) inst.classValue())
                    && this.epochs % this.periodOption.getValue() == 0) {
                this.weights.set(i,
                        this.weights.get(i) * this.betaOption.getValue());
            }
            Pr[yHat] += this.weights.get(i);
            maxWeight = Math.max(maxWeight, this.weights.get(i));
            if (this.weights.get(i) < weakestExpertWeight) {
                weakestExpertIndex = i;
                weakestExpertWeight = weights.get(i);
            }
        }
        int yHat = Utils.maxIndex(Pr);
        if (this.epochs % this.periodOption.getValue() == 0) {
            scaleWeights(maxWeight);
            removeExperts();
            if (yHat != (int) inst.classValue()) {
                if (experts.size() == this.maxExpertsOption.getValue()) {
                    removeWeakestExpert(weakestExpertIndex);
                }
                Classifier classifier = ((Classifier) getPreparedClassOption(this.baseLearnerOption)).copy();
                classifier.resetLearning();
                this.experts.add(classifier);
                this.weights.add(1.0);
            }
        }
        // train experts
        for (Classifier expert : this.experts) {
            expert.trainOnInstance(inst);
        }
    }
1130583
def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type):
    
    scores = np.zeros(num_attributes)
    for feature_num in range(num_attributes):
        scores[feature_num] += compute_score(attr, mcmap, NN, feature_num, inst,
                                             nan_entries, headers, class_type, X, y, labels_std, data_type)
    return scores
235172
private double calculateMassT(List<IIsotope> isoToCond_new, int[] value_In) {
        double result = 0;
        for (int i = 0; i < isoToCond_new.size(); i++) {
            if (value_In[i] != 0) {
                result += isoToCond_new.get(i).getExactMass() * value_In[i];
            }
        }
        return result;
    }
65501
protected double[] firstHit(Instance inst) {
		boolean fired = false;
		int countFired = 0;
		double[] votes = new double[this.numClass];
		for (int j = 0; j < this.ruleSet.size(); j++) {
			if (this.ruleSet.get(j).ruleEvaluate(inst) == true) {
				countFired = countFired + 1;
				for (int z = 0; z < this.numClass; z++) {
					votes[z] = this.ruleSet.get(j).obserClassDistrib.getValue(z) 
							/ this.ruleSet.get(j).obserClassDistrib.sumOfValues();
					}
				return votes;
				}
			}
		if (countFired > 0) {
			fired = true;
			} else {
				fired = false;
				}
		if (fired == false) {
			votes = oberversDistribProb(inst, this.observedClassDistribution);
			}
		return votes;
		}
922079
public int compareTo(Error s) {
    if (getStart() < s.getStart()) {
      return -1;
    } else if (getStart() == s.getStart()) {
      if (getEnd() > s.getEnd()) {
        return -1;
      } else if (getEnd() < s.getEnd()) {
        return 1;
      } else {
        return 0;
      }
    } else {
      return 1;
    }
  }