Search in sources :

Example 36 with Function

use of java.util.function.Function in project aima-java by aimacode.

the class SimulatedAnnealingMaximumFinderApp method simulate.

/** Starts the experiment. */
@SuppressWarnings("unchecked")
public void simulate() {
    List<Action> actions = new ArrayList<>(1);
    actions.add(new DynamicAction("Move"));
    Problem<Double, Action> problem = new GeneralProblem<>(getRandomState(), s -> actions, (s, a) -> getSuccessor(s), s -> false);
    Function<Double, Double> func = (Function<Double, Double>) simPaneCtrl.getParamValue(PARAM_FUNC_SELECT);
    Scheduler scheduler = new Scheduler(simPaneCtrl.getParamAsInt(PARAM_K), simPaneCtrl.getParamAsDouble(PARAM_LAMBDA), simPaneCtrl.getParamAsInt(PARAM_MAX_ITER));
    search = new SimulatedAnnealingSearch<>(n -> 1 - func.apply(n.getState()), scheduler);
    search.addNodeListener(n -> updateStateView(n.getState()));
    search.findActions(problem);
    updateStateView(search.getLastSearchState());
}
Also used : Color(javafx.scene.paint.Color) java.util(java.util) IntegrableApplication(aima.gui.fx.framework.IntegrableApplication) Canvas(javafx.scene.canvas.Canvas) Action(aima.core.agent.Action) GeneralProblem(aima.core.search.framework.problem.GeneralProblem) SimulationPaneBuilder(aima.gui.fx.framework.SimulationPaneBuilder) Function(java.util.function.Function) Platform(javafx.application.Platform) Scheduler(aima.core.search.local.Scheduler) Parameter(aima.gui.fx.framework.Parameter) Paint(javafx.scene.paint.Paint) SimulationPaneCtrl(aima.gui.fx.framework.SimulationPaneCtrl) FunctionPlotterCtrl(aima.gui.fx.views.FunctionPlotterCtrl) BorderPane(javafx.scene.layout.BorderPane) DynamicAction(aima.core.agent.impl.DynamicAction) Problem(aima.core.search.framework.problem.Problem) SimulatedAnnealingSearch(aima.core.search.local.SimulatedAnnealingSearch) Pane(javafx.scene.layout.Pane) Function(java.util.function.Function) Action(aima.core.agent.Action) DynamicAction(aima.core.agent.impl.DynamicAction) Scheduler(aima.core.search.local.Scheduler) DynamicAction(aima.core.agent.impl.DynamicAction) GeneralProblem(aima.core.search.framework.problem.GeneralProblem)

Example 37 with Function

use of java.util.function.Function in project Alpha by alpha-asp.

the class AbstractSolverTests method factories.

@Parameters(name = "{0}")
public static Collection<Object[]> factories() {
    boolean enableAdditionalInternalChecks = false;
    Collection<Object[]> factories = new ArrayList<>();
    factories.add(new Object[] { "NaiveSolver", (Function<Grounder, Solver>) NaiveSolver::new });
    for (Heuristic heuristic : Heuristic.values()) {
        String name = "DefaultSolver (random " + heuristic + ")";
        Function<Grounder, Solver> instantiator = g -> {
            return new DefaultSolver(g, new Random(), heuristic, enableAdditionalInternalChecks);
        };
        factories.add(new Object[] { name, instantiator });
        name = "DefaultSolver (deterministic " + heuristic + ")";
        instantiator = g -> {
            return new DefaultSolver(g, new Random(0), heuristic, enableAdditionalInternalChecks);
        };
        factories.add(new Object[] { name, instantiator });
    }
    return factories;
}
Also used : java.util(java.util) Heuristic(at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic) Parameter(org.junit.runners.Parameterized.Parameter) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) Grounder(at.ac.tuwien.kr.alpha.grounder.Grounder) Function(java.util.function.Function) Parameterized(org.junit.runners.Parameterized) Grounder(at.ac.tuwien.kr.alpha.grounder.Grounder) Heuristic(at.ac.tuwien.kr.alpha.solver.heuristics.BranchingHeuristicFactory.Heuristic) Parameters(org.junit.runners.Parameterized.Parameters)

Example 38 with Function

use of java.util.function.Function in project aic-expresso by aic-sri-international.

the class Compilation method compile.

/**
	 * Compiles an expression to a normalized (decision-tree-like) expression.
	 * @param inputExpression
	 * @param mapFromVariableNameToTypeName
	 * @param mapFromCategoricalTypeNameToSizeString
	 * @param additionalTypes
	 * @param solverListener if not null, invoked on solver used for compilation, before and after compilation starts; returned solver on 'before' invocation is used (it may be the same one used as argument, of course).
	 * @return
	 */
public static Expression compile(Expression inputExpression, Theory theory, Map<String, String> mapFromVariableNameToTypeName, Map<String, String> mapFromUniquelyNamedConstantToTypeName, Map<String, String> mapFromCategoricalTypeNameToSizeString, Collection<Type> additionalTypes, Function<MultiIndexQuantifierEliminator, MultiIndexQuantifierEliminator> solverListener) {
    // the group actually does not matter, because we are not going to have any indices.
    AssociativeCommutativeGroup group = new Max();
    // The solver for the parameters above.
    MultiIndexQuantifierEliminator solver = new SGDPLLT();
    if (solverListener != null) {
        solver = solverListener.apply(solver);
    }
    // We use the Prolog convention of small-letter initials for constants, but we need an exception for the random variables.
    Predicate<Expression> isPrologConstant = new PrologConstantPredicate();
    Predicate<Expression> isUniquelyNamedConstantPredicate = e -> isPrologConstant.apply(e) && !mapFromVariableNameToTypeName.containsKey(e);
    Map<String, String> mapFromSymbolNameToTypeName = new LinkedHashMap<>(mapFromVariableNameToTypeName);
    mapFromSymbolNameToTypeName.putAll(mapFromUniquelyNamedConstantToTypeName);
    // Solve the problem.
    // no indices; we want to keep all variables
    List<Expression> indices = Util.list();
    Expression result = solver.solve(group, inputExpression, indices, mapFromSymbolNameToTypeName, mapFromCategoricalTypeNameToSizeString, additionalTypes, isUniquelyNamedConstantPredicate, theory);
    if (solverListener != null) {
        solverListener.apply(null);
    }
    return result;
}
Also used : Type(com.sri.ai.expresso.api.Type) MultiIndexQuantifierEliminator(com.sri.ai.grinder.sgdpllt.api.MultiIndexQuantifierEliminator) SGDPLLT(com.sri.ai.grinder.sgdpllt.core.solver.SGDPLLT) Collection(java.util.Collection) Expression(com.sri.ai.expresso.api.Expression) Function(java.util.function.Function) Theory(com.sri.ai.grinder.sgdpllt.api.Theory) LinkedHashMap(java.util.LinkedHashMap) List(java.util.List) Predicate(com.google.common.base.Predicate) Max(com.sri.ai.grinder.sgdpllt.group.Max) Map(java.util.Map) Util(com.sri.ai.util.Util) AssociativeCommutativeGroup(com.sri.ai.grinder.sgdpllt.group.AssociativeCommutativeGroup) PrologConstantPredicate(com.sri.ai.grinder.core.PrologConstantPredicate) MultiIndexQuantifierEliminator(com.sri.ai.grinder.sgdpllt.api.MultiIndexQuantifierEliminator) Max(com.sri.ai.grinder.sgdpllt.group.Max) SGDPLLT(com.sri.ai.grinder.sgdpllt.core.solver.SGDPLLT) PrologConstantPredicate(com.sri.ai.grinder.core.PrologConstantPredicate) Expression(com.sri.ai.expresso.api.Expression) AssociativeCommutativeGroup(com.sri.ai.grinder.sgdpllt.group.AssociativeCommutativeGroup) LinkedHashMap(java.util.LinkedHashMap)

Example 39 with Function

use of java.util.function.Function in project lucene-solr by apache.

the class TestMemoryIndex method testPointValues.

public void testPointValues() throws Exception {
    List<Function<Long, IndexableField>> fieldFunctions = Arrays.asList((t) -> new IntPoint("number", t.intValue()), (t) -> new LongPoint("number", t), (t) -> new FloatPoint("number", t.floatValue()), (t) -> new DoublePoint("number", t.doubleValue()));
    List<Function<Long, Query>> exactQueryFunctions = Arrays.asList((t) -> IntPoint.newExactQuery("number", t.intValue()), (t) -> LongPoint.newExactQuery("number", t), (t) -> FloatPoint.newExactQuery("number", t.floatValue()), (t) -> DoublePoint.newExactQuery("number", t.doubleValue()));
    List<Function<long[], Query>> setQueryFunctions = Arrays.asList((t) -> IntPoint.newSetQuery("number", LongStream.of(t).mapToInt(value -> (int) value).toArray()), (t) -> LongPoint.newSetQuery("number", t), (t) -> FloatPoint.newSetQuery("number", Arrays.asList(LongStream.of(t).mapToObj(value -> (float) value).toArray(Float[]::new))), (t) -> DoublePoint.newSetQuery("number", LongStream.of(t).mapToDouble(value -> (double) value).toArray()));
    List<BiFunction<Long, Long, Query>> rangeQueryFunctions = Arrays.asList((t, u) -> IntPoint.newRangeQuery("number", t.intValue(), u.intValue()), (t, u) -> LongPoint.newRangeQuery("number", t, u), (t, u) -> FloatPoint.newRangeQuery("number", t.floatValue(), u.floatValue()), (t, u) -> DoublePoint.newRangeQuery("number", t.doubleValue(), u.doubleValue()));
    for (int i = 0; i < fieldFunctions.size(); i++) {
        Function<Long, IndexableField> fieldFunction = fieldFunctions.get(i);
        Function<Long, Query> exactQueryFunction = exactQueryFunctions.get(i);
        Function<long[], Query> setQueryFunction = setQueryFunctions.get(i);
        BiFunction<Long, Long, Query> rangeQueryFunction = rangeQueryFunctions.get(i);
        Document doc = new Document();
        for (int number = 1; number < 32; number += 2) {
            doc.add(fieldFunction.apply((long) number));
        }
        MemoryIndex mi = MemoryIndex.fromDocument(doc, analyzer);
        IndexSearcher indexSearcher = mi.createSearcher();
        Query query = exactQueryFunction.apply(5L);
        assertEquals(1, indexSearcher.count(query));
        query = exactQueryFunction.apply(4L);
        assertEquals(0, indexSearcher.count(query));
        query = setQueryFunction.apply(new long[] { 3L, 9L, 19L });
        assertEquals(1, indexSearcher.count(query));
        query = setQueryFunction.apply(new long[] { 2L, 8L, 13L });
        assertEquals(1, indexSearcher.count(query));
        query = setQueryFunction.apply(new long[] { 2L, 8L, 16L });
        assertEquals(0, indexSearcher.count(query));
        query = rangeQueryFunction.apply(2L, 16L);
        assertEquals(1, indexSearcher.count(query));
        query = rangeQueryFunction.apply(24L, 48L);
        assertEquals(1, indexSearcher.count(query));
        query = rangeQueryFunction.apply(48L, 68L);
        assertEquals(0, indexSearcher.count(query));
    }
}
Also used : Query(org.apache.lucene.search.Query) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) BinaryPoint(org.apache.lucene.document.BinaryPoint) FieldType(org.apache.lucene.document.FieldType) BiFunction(java.util.function.BiFunction) IndexableField(org.apache.lucene.index.IndexableField) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) Term(org.apache.lucene.index.Term) PhraseQuery(org.apache.lucene.search.PhraseQuery) StoredField(org.apache.lucene.document.StoredField) DoublePoint(org.apache.lucene.document.DoublePoint) Document(org.apache.lucene.document.Document) TermsEnum(org.apache.lucene.index.TermsEnum) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) SortedSetDocValuesField(org.apache.lucene.document.SortedSetDocValuesField) ClassicSimilarity(org.apache.lucene.search.similarities.ClassicSimilarity) BytesRef(org.apache.lucene.util.BytesRef) BinaryDocValuesField(org.apache.lucene.document.BinaryDocValuesField) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) StandardCharsets(java.nio.charset.StandardCharsets) SortedNumericDocValues(org.apache.lucene.index.SortedNumericDocValues) MockAnalyzer(org.apache.lucene.analysis.MockAnalyzer) List(java.util.List) FieldInvertState(org.apache.lucene.index.FieldInvertState) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) LeafReader(org.apache.lucene.index.LeafReader) LuceneTestCase(org.apache.lucene.util.LuceneTestCase) MockPayloadAnalyzer(org.apache.lucene.analysis.MockPayloadAnalyzer) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) IndexReader(org.apache.lucene.index.IndexReader) BM25Similarity(org.apache.lucene.search.similarities.BM25Similarity) IndexSearcher(org.apache.lucene.search.IndexSearcher) LongPoint(org.apache.lucene.document.LongPoint) StringField(org.apache.lucene.document.StringField) NumericDocValues(org.apache.lucene.index.NumericDocValues) TestUtil(org.apache.lucene.util.TestUtil) CoreMatchers.not(org.hamcrest.CoreMatchers.not) Function(java.util.function.Function) StringContains.containsString(org.junit.internal.matchers.StringContains.containsString) Similarity(org.apache.lucene.search.similarities.Similarity) SortedSetDocValues(org.apache.lucene.index.SortedSetDocValues) IntPoint(org.apache.lucene.document.IntPoint) SortedDocValues(org.apache.lucene.index.SortedDocValues) TermStatistics(org.apache.lucene.search.TermStatistics) Before(org.junit.Before) LongStream(java.util.stream.LongStream) PostingsEnum(org.apache.lucene.index.PostingsEnum) FloatPoint(org.apache.lucene.document.FloatPoint) Analyzer(org.apache.lucene.analysis.Analyzer) IOException(java.io.IOException) Test(org.junit.Test) CollectionStatistics(org.apache.lucene.search.CollectionStatistics) TermQuery(org.apache.lucene.search.TermQuery) Field(org.apache.lucene.document.Field) DocValuesType(org.apache.lucene.index.DocValuesType) TextField(org.apache.lucene.document.TextField) IndexOptions(org.apache.lucene.index.IndexOptions) IndexSearcher(org.apache.lucene.search.IndexSearcher) Query(org.apache.lucene.search.Query) PhraseQuery(org.apache.lucene.search.PhraseQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TermQuery(org.apache.lucene.search.TermQuery) LongPoint(org.apache.lucene.document.LongPoint) Document(org.apache.lucene.document.Document) BinaryPoint(org.apache.lucene.document.BinaryPoint) DoublePoint(org.apache.lucene.document.DoublePoint) LongPoint(org.apache.lucene.document.LongPoint) IntPoint(org.apache.lucene.document.IntPoint) FloatPoint(org.apache.lucene.document.FloatPoint) IndexableField(org.apache.lucene.index.IndexableField) IntPoint(org.apache.lucene.document.IntPoint) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) FloatPoint(org.apache.lucene.document.FloatPoint) BiFunction(java.util.function.BiFunction) DoublePoint(org.apache.lucene.document.DoublePoint)

Example 40 with Function

use of java.util.function.Function in project lucene-solr by apache.

the class CloudSolrClientCacheTest method getMockLbHttpSolrClient.

private LBHttpSolrClient getMockLbHttpSolrClient(Map<String, Function> responses) throws Exception {
    LBHttpSolrClient mockLbclient = mock(LBHttpSolrClient.class);
    when(mockLbclient.request(any(LBHttpSolrClient.Req.class))).then(invocationOnMock -> {
        LBHttpSolrClient.Req req = invocationOnMock.getArgument(0);
        Function f = responses.get("request");
        if (f == null)
            return null;
        Object res = f.apply(null);
        if (res instanceof Exception)
            throw (Throwable) res;
        LBHttpSolrClient.Rsp rsp = new LBHttpSolrClient.Rsp();
        rsp.rsp = (NamedList<Object>) res;
        rsp.server = req.servers.get(0);
        return rsp;
    });
    return mockLbclient;
}
Also used : Function(java.util.function.Function) IOException(java.io.IOException) NoHttpResponseException(org.apache.http.NoHttpResponseException) SocketException(java.net.SocketException) ConnectException(java.net.ConnectException)

Aggregations

Function (java.util.function.Function)1261 List (java.util.List)606 Map (java.util.Map)447 ArrayList (java.util.ArrayList)416 Test (org.junit.Test)358 Collectors (java.util.stream.Collectors)324 HashMap (java.util.HashMap)287 Collections (java.util.Collections)284 Arrays (java.util.Arrays)271 Set (java.util.Set)255 IOException (java.io.IOException)252 Collection (java.util.Collection)192 HashSet (java.util.HashSet)191 TimeUnit (java.util.concurrent.TimeUnit)174 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)158 Optional (java.util.Optional)157 Assert (org.junit.Assert)137 Consumer (java.util.function.Consumer)134 Supplier (java.util.function.Supplier)126 CompletableFuture (java.util.concurrent.CompletableFuture)121