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

lphy.base.function.Rep Maven / Gradle / Ivy

Go to download

The standard library of LPhy, which contains the required generative distributions and basic functions.

The newest version!
package lphy.base.function;

import lphy.base.ParameterNames;
import lphy.core.model.DeterministicFunction;
import lphy.core.model.Value;
import lphy.core.model.annotation.GeneratorInfo;
import lphy.core.model.annotation.ParameterInfo;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.SortedMap;
import java.util.TreeMap;

public class Rep extends DeterministicFunction {

    private final String xParamName = "element";
    private Value x;
    private Value times;

    public Rep(@ParameterInfo(name = xParamName, description = "the element to replicate.") Value x,
               @ParameterInfo(name = ParameterNames.TimesParamName, description = "the standard deviation of the distribution.") Value times) {

        this.x = x;
        if (x == null) throw new IllegalArgumentException("The element can't be null!");
        this.times = times;
        if (times == null) throw new IllegalArgumentException("The times can't be null!");
    }

    @GeneratorInfo(name = "rep", description = "The replication function. Takes a value and an integer representing the number of times to replicate the value. Returns a vector of the value repeated the specified number of times.")
    public Value apply(Value v, Value times) {

        Class c = v.value().getClass();
        U[] array = (U[]) Array.newInstance(c, times.value());
        Arrays.fill(array, v.value());

        return new Value<>( array, this);
    }

    public java.util.Map getParams() {
        SortedMap map = new TreeMap<>();
        map.put(xParamName, x);
        map.put(ParameterNames.TimesParamName, times);
        return map;
    }

    public void setParam(String paramName, Value value) {
        if (paramName.equals(xParamName)) x = value;
        else if (paramName.equals(ParameterNames.TimesParamName)) times = value;
        else throw new RuntimeException("Unrecognised parameter name: " + paramName);
    }

    public Value apply() {
        return apply(x, times);
    }
}