All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.berkeley.nlp.math.CachingDifferentiableFunction Maven / Gradle / Ivy

Go to download

The Berkeley parser analyzes the grammatical structure of natural language using probabilistic context-free grammars (PCFGs).

The newest version!
package edu.berkeley.nlp.math;

import java.util.Arrays;

import edu.berkeley.nlp.util.Pair;


public abstract class CachingDifferentiableFunction implements DifferentiableFunction {

	double[] lastX ;
	double[] lastGradient ;
	double lastValue;
	
	protected abstract Pair calculate(double[] x) ;
		
	private void ensureCache(double[] x) {
		if (!isCached(x)) {
			Pair result = calculate(x);			
			lastValue = result.getFirst();
			lastX = DoubleArrays.clone(x);
			lastGradient = DoubleArrays.clone(result.getSecond());			
		}
	}
	
	protected boolean isCached(double[] x) {
		if (lastX == null) {
			return false;
		}
		return Arrays.equals(x, lastX);
	}
	
	public void clearCache()
	{
		lastX = null;
		lastGradient = null;
	}
	

	public double[] derivativeAt(double[] x) {
		ensureCache(x);
		return lastGradient;
	}
	
	public double valueAt(double[] x) {
		ensureCache(x);
		return lastValue;
	}
	
	public abstract int dimension() ;

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy