Search in sources :

Example 6 with PredictionInput

use of org.kie.kogito.explainability.model.PredictionInput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method testFinalUniqueIds.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testFinalUniqueIds(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final List<Output> goal = new ArrayList<>();
    List<Feature> features = List.of(FeatureFactory.newNumericalFeature("f-num1", 10.0, NumericalFeatureDomain.create(0, 20)));
    PredictionProvider model = TestUtils.getFeaturePassModel(0);
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(100_000L);
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed((long) seed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    final List<UUID> intermediateIds = new ArrayList<>();
    final List<UUID> executionIds = new ArrayList<>();
    final Consumer<CounterfactualResult> captureIntermediateIds = counterfactual -> {
        intermediateIds.add(counterfactual.getSolutionId());
    };
    final Consumer<CounterfactualResult> captureExecutionIds = counterfactual -> {
        executionIds.add(counterfactual.getExecutionId());
    };
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverConfig(solverConfig);
    solverConfig.withEasyScoreCalculatorClass(MockCounterFactualScoreCalculator.class);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    PredictionInput input = new PredictionInput(features);
    PredictionOutput output = new PredictionOutput(goal);
    final UUID executionId = UUID.randomUUID();
    Prediction prediction = new CounterfactualPrediction(input, output, null, executionId, null);
    final CounterfactualResult counterfactualResult = counterfactualExplainer.explainAsync(prediction, model, captureIntermediateIds.andThen(captureExecutionIds)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (CounterfactualEntity entity : counterfactualResult.getEntities()) {
        logger.debug("Entity: {}", entity);
    }
    // All intermediate ids should be unique
    assertEquals((int) intermediateIds.stream().distinct().count(), intermediateIds.size());
    // There should be at least one intermediate id
    assertTrue(intermediateIds.size() > 0);
    // There should be at least one execution id
    assertTrue(executionIds.size() > 0);
    // We should have the same number of execution ids as intermediate ids (captured from intermediate results)
    assertEquals(executionIds.size(), intermediateIds.size());
    // All execution ids should be the same
    assertEquals(1, (int) executionIds.stream().distinct().count());
    // The last intermediate id must be different from the final result id
    assertNotEquals(intermediateIds.get(intermediateIds.size() - 1), counterfactualResult.getSolutionId());
    // Captured execution ids should be the same as the one provided
    assertEquals(executionIds.get(0), executionId);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) FeatureFactory(org.kie.kogito.explainability.model.FeatureFactory) Feature(org.kie.kogito.explainability.model.Feature) LoggerFactory(org.slf4j.LoggerFactory) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) Value(org.kie.kogito.explainability.model.Value) TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) FeatureDistribution(org.kie.kogito.explainability.model.FeatureDistribution) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) Mockito.atLeast(org.mockito.Mockito.atLeast) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) CategoricalFeatureDomain(org.kie.kogito.explainability.model.domain.CategoricalFeatureDomain) DataUtils(org.kie.kogito.explainability.utils.DataUtils) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) List(java.util.List) Stream(java.util.stream.Stream) NormalDistribution(org.apache.commons.math3.distribution.NormalDistribution) Output(org.kie.kogito.explainability.model.Output) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) SolverJob(org.optaplanner.core.api.solver.SolverJob) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) Prediction(org.kie.kogito.explainability.model.Prediction) DataDomain(org.kie.kogito.explainability.model.DataDomain) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) EnvironmentMode(org.optaplanner.core.config.solver.EnvironmentMode) CompletableFuture(java.util.concurrent.CompletableFuture) SolverManager(org.optaplanner.core.api.solver.SolverManager) Function(java.util.function.Function) ArrayList(java.util.ArrayList) MockCounterFactualScoreCalculator(org.kie.kogito.explainability.local.counterfactual.score.MockCounterFactualScoreCalculator) ArgumentCaptor(org.mockito.ArgumentCaptor) NumericFeatureDistribution(org.kie.kogito.explainability.model.NumericFeatureDistribution) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) LinkedList(java.util.LinkedList) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) ValueSource(org.junit.jupiter.params.provider.ValueSource) Logger(org.slf4j.Logger) Mockito.when(org.mockito.Mockito.when) Type(org.kie.kogito.explainability.model.Type) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) TestUtils(org.kie.kogito.explainability.TestUtils) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) Config(org.kie.kogito.explainability.Config) Collections(java.util.Collections) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) ArrayList(java.util.ArrayList) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) Random(java.util.Random) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) UUID(java.util.UUID) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 7 with PredictionInput

use of org.kie.kogito.explainability.model.PredictionInput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method mockExplainerInvocation.

@SuppressWarnings("unchecked")
CounterfactualResult mockExplainerInvocation(Consumer<CounterfactualResult> intermediateResultsConsumer, Long maxRunningTimeSeconds) throws ExecutionException, InterruptedException, TimeoutException {
    // Mock SolverManager and SolverJob to guarantee deterministic test behaviour
    SolverJob<CounterfactualSolution, UUID> solverJob = mock(SolverJob.class);
    CounterfactualSolution solution = mock(CounterfactualSolution.class);
    BendableBigDecimalScore score = BendableBigDecimalScore.zero(0, 0);
    when(solverManager.solveAndListen(any(), any(), any(), any())).thenReturn(solverJob);
    when(solverJob.getFinalBestSolution()).thenReturn(solution);
    when(solution.getScore()).thenReturn(score);
    when(solverManagerFactory.apply(any())).thenReturn(solverManager);
    // Setup Explainer
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverManagerFactory(solverManagerFactory);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    // Setup mock model, what it does is not important
    Prediction prediction = new CounterfactualPrediction(new PredictionInput(Collections.emptyList()), new PredictionOutput(Collections.emptyList()), null, UUID.randomUUID(), maxRunningTimeSeconds);
    return counterfactualExplainer.explainAsync(prediction, (List<PredictionInput> inputs) -> CompletableFuture.completedFuture(Collections.emptyList()), intermediateResultsConsumer).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) UUID(java.util.UUID) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction)

Example 8 with PredictionInput

use of org.kie.kogito.explainability.model.PredictionInput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method testIntermediateUniqueIds.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testIntermediateUniqueIds(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final List<Output> goal = new ArrayList<>();
    List<Feature> features = List.of(FeatureFactory.newNumericalFeature("f-num1", 10.0, NumericalFeatureDomain.create(0, 20)));
    PredictionProvider model = TestUtils.getFeaturePassModel(0);
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(100_000L);
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed((long) seed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    final List<UUID> intermediateIds = new ArrayList<>();
    final List<UUID> executionIds = new ArrayList<>();
    final Consumer<CounterfactualResult> captureIntermediateIds = counterfactual -> {
        intermediateIds.add(counterfactual.getSolutionId());
    };
    final Consumer<CounterfactualResult> captureExecutionIds = counterfactual -> {
        executionIds.add(counterfactual.getExecutionId());
    };
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverConfig(solverConfig);
    solverConfig.withEasyScoreCalculatorClass(MockCounterFactualScoreCalculator.class);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    PredictionInput input = new PredictionInput(features);
    PredictionOutput output = new PredictionOutput(goal);
    final UUID executionId = UUID.randomUUID();
    Prediction prediction = new CounterfactualPrediction(input, output, null, executionId, null);
    final CounterfactualResult counterfactualResult = counterfactualExplainer.explainAsync(prediction, model, captureIntermediateIds.andThen(captureExecutionIds)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (CounterfactualEntity entity : counterfactualResult.getEntities()) {
        logger.debug("Entity: {}", entity);
    }
    // all intermediate Ids must be distinct
    assertEquals((int) intermediateIds.stream().distinct().count(), intermediateIds.size());
    assertEquals(1, (int) executionIds.stream().distinct().count());
    assertEquals(executionIds.get(0), executionId);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) FeatureFactory(org.kie.kogito.explainability.model.FeatureFactory) Feature(org.kie.kogito.explainability.model.Feature) LoggerFactory(org.slf4j.LoggerFactory) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) Value(org.kie.kogito.explainability.model.Value) TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) FeatureDistribution(org.kie.kogito.explainability.model.FeatureDistribution) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) Mockito.atLeast(org.mockito.Mockito.atLeast) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) CategoricalFeatureDomain(org.kie.kogito.explainability.model.domain.CategoricalFeatureDomain) DataUtils(org.kie.kogito.explainability.utils.DataUtils) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) List(java.util.List) Stream(java.util.stream.Stream) NormalDistribution(org.apache.commons.math3.distribution.NormalDistribution) Output(org.kie.kogito.explainability.model.Output) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) SolverJob(org.optaplanner.core.api.solver.SolverJob) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) Prediction(org.kie.kogito.explainability.model.Prediction) DataDomain(org.kie.kogito.explainability.model.DataDomain) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) EnvironmentMode(org.optaplanner.core.config.solver.EnvironmentMode) CompletableFuture(java.util.concurrent.CompletableFuture) SolverManager(org.optaplanner.core.api.solver.SolverManager) Function(java.util.function.Function) ArrayList(java.util.ArrayList) MockCounterFactualScoreCalculator(org.kie.kogito.explainability.local.counterfactual.score.MockCounterFactualScoreCalculator) ArgumentCaptor(org.mockito.ArgumentCaptor) NumericFeatureDistribution(org.kie.kogito.explainability.model.NumericFeatureDistribution) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) LinkedList(java.util.LinkedList) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) ValueSource(org.junit.jupiter.params.provider.ValueSource) Logger(org.slf4j.Logger) Mockito.when(org.mockito.Mockito.when) Type(org.kie.kogito.explainability.model.Type) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) TestUtils(org.kie.kogito.explainability.TestUtils) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) Config(org.kie.kogito.explainability.Config) Collections(java.util.Collections) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) ArrayList(java.util.ArrayList) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) Random(java.util.Random) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) UUID(java.util.UUID) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 9 with PredictionInput

use of org.kie.kogito.explainability.model.PredictionInput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method runCounterfactualSearch.

private CounterfactualResult runCounterfactualSearch(Long randomSeed, List<Output> goal, List<Feature> features, PredictionProvider model, double goalThresold) throws InterruptedException, ExecutionException, TimeoutException {
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(steps);
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed(randomSeed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig();
    counterfactualConfig.withSolverConfig(solverConfig).withGoalThreshold(goalThresold);
    final CounterfactualExplainer explainer = new CounterfactualExplainer(counterfactualConfig);
    final PredictionInput input = new PredictionInput(features);
    PredictionOutput output = new PredictionOutput(goal);
    Prediction prediction = new CounterfactualPrediction(input, output, null, UUID.randomUUID(), null);
    return explainer.explainAsync(prediction, model).get(predictionTimeOut, predictionTimeUnit);
}
Also used : TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction)

Example 10 with PredictionInput

use of org.kie.kogito.explainability.model.PredictionInput in project kogito-apps by kiegroup.

the class CounterfactualScoreCalculatorTest method testNullIntegerInput.

/**
 * Null values for input Integer features should not be accepted as valid
 */
@Test
void testNullIntegerInput() throws ExecutionException, InterruptedException {
    List<Feature> features = new ArrayList<>();
    List<FeatureDomain> featureDomains = new ArrayList<>();
    List<Boolean> constraints = new ArrayList<>();
    // f-1
    features.add(FeatureFactory.newNumericalFeature("f-1", 1.0));
    featureDomains.add(NumericalFeatureDomain.create(0.0, 10.0));
    constraints.add(false);
    // f-2
    features.add(FeatureFactory.newNumericalFeature("f-2", null));
    featureDomains.add(NumericalFeatureDomain.create(0, 10));
    constraints.add(false);
    // f-3
    features.add(FeatureFactory.newBooleanFeature("f-3", true));
    featureDomains.add(EmptyFeatureDomain.create());
    constraints.add(false);
    PredictionInput input = new PredictionInput(features);
    PredictionFeatureDomain domains = new PredictionFeatureDomain(featureDomains);
    IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
        CounterfactualEntityFactory.createEntities(input);
    });
    assertEquals("Null numeric features are not supported in counterfactuals", exception.getMessage());
}
Also used : PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) ArrayList(java.util.ArrayList) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) Feature(org.kie.kogito.explainability.model.Feature) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

PredictionInput (org.kie.kogito.explainability.model.PredictionInput)187 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)143 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)135 Prediction (org.kie.kogito.explainability.model.Prediction)126 Feature (org.kie.kogito.explainability.model.Feature)109 Test (org.junit.jupiter.api.Test)107 ArrayList (java.util.ArrayList)97 SimplePrediction (org.kie.kogito.explainability.model.SimplePrediction)95 Random (java.util.Random)86 PerturbationContext (org.kie.kogito.explainability.model.PerturbationContext)67 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)60 Output (org.kie.kogito.explainability.model.Output)55 LimeConfig (org.kie.kogito.explainability.local.lime.LimeConfig)54 LinkedList (java.util.LinkedList)53 LimeExplainer (org.kie.kogito.explainability.local.lime.LimeExplainer)52 Value (org.kie.kogito.explainability.model.Value)52 Saliency (org.kie.kogito.explainability.model.Saliency)50 List (java.util.List)39 LimeConfigOptimizer (org.kie.kogito.explainability.local.lime.optim.LimeConfigOptimizer)33 Type (org.kie.kogito.explainability.model.Type)31