예제 #1
0
 public final void setFlags(final BitMask flags) {
   final SConstraint cstr = solver.getCstr(this.rsc);
   BitMask dest = null;
   if (cstr instanceof AbstractResourceSConstraint) {
     dest = ((AbstractResourceSConstraint) cstr).getFlags();
   } else if (cstr instanceof MetaSConstraint) {
     dest =
         ((AbstractResourceSConstraint) ((MetaSConstraint) cstr).getSubConstraints(0)).getFlags();
   }
   if (dest != null) {
     dest.clear();
     dest.set(flags);
   } else ChocoLogging.getTestLogger().info("can not apply resource filtering rules");
 }
예제 #2
0
/** Created by IntelliJ IDEA. User: hcambaza Date: 23 f�vr. 2007 Time: 16:00:01 */
public class DistanceTest {

  protected static final Logger LOGGER = ChocoLogging.getTestLogger();

  CPModel m;
  CPSolver s;

  @Before
  public void before() {
    m = new CPModel();
    s = new CPSolver();
  }

  @After
  public void after() {
    m = null;
    s = null;
  }

  @Test
  public void test1Solve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 9, k1 = 7, k2 = 6;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      IntegerVariable v2 = makeIntVar("v2", 0, 10);
      IntegerVariable v3 = makeIntVar("v3", 0, 10);
      m.addConstraint(distanceEQ(v0, v1, k));
      m.addConstraint(distanceEQ(v1, v2, k1));
      m.addConstraint(distanceEQ(v2, v3, k2));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage());
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 4);
    }
  }

  @Test
  public void test1NeqSolve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 9, k1 = 7, k2 = 6;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      IntegerVariable v2 = makeIntVar("v2", 0, 10);
      IntegerVariable v3 = makeIntVar("v3", 0, 10);

      m.addConstraint(distanceNEQ(v0, v1, k));
      m.addConstraint(distanceNEQ(v1, v2, k1));
      m.addConstraint(distanceNEQ(v2, v3, k2));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage());
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 12147);
    }
  }

  @Test
  public void test2SolveNegDoms() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 9, k1 = 7, k2 = 6;
      IntegerVariable v0 = makeIntVar("v0", -5, 5);
      IntegerVariable v1 = makeIntVar("v1", -5, 5);
      IntegerVariable v2 = makeIntVar("v2", -5, 5);
      IntegerVariable v3 = makeIntVar("v3", -5, 5);
      m.addConstraint(distanceEQ(v0, v1, k));
      m.addConstraint(distanceEQ(v1, v2, k1));
      m.addConstraint(distanceEQ(v2, v3, k2));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage());
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 4);
    }
  }

  @Test
  public void test3BoundsSolve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 9, k1 = 7, k2 = 6;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      IntegerVariable v2 = makeIntVar("v2", 0, 10);
      IntegerVariable v3 = makeIntVar("v3", 0, 10);
      m.addVariables(Options.V_BOUND, v0, v1, v2, v3);
      m.addConstraint(distanceEQ(v0, v1, k));
      m.addConstraint(distanceEQ(v1, v2, k1));
      m.addConstraint(distanceEQ(v2, v3, k2));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
        // Templates.
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 4);
    }
  }

  @Test
  public void test3GTEnumSolve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 8;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      m.addConstraint(distanceGT(v0, v1, k));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
        // Templates.
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 6);
    }
  }

  @Test
  public void test3GTBoundSolve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 8;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      m.addVariables(Options.V_BOUND, v0, v1);
      m.addConstraint(distanceGT(v0, v1, k));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
        // Templates.
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 6);
    }
  }

  @Test
  public void test3LTSolve() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      int k = 2;
      IntegerVariable v0 = makeIntVar("v0", 0, 10);
      IntegerVariable v1 = makeIntVar("v1", 0, 10);
      m.addConstraint(distanceLT(v0, v1, k));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));
      try {
        s.propagate();
      } catch (ContradictionException e) {
        LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
        // Templates.
      }
      s.solveAll();
      int nbNode = s.getNodeCount();
      LOGGER.info("solutions : " + s.getNbSolutions() + " nbNode : " + nbNode);
      assertEquals(s.getNbSolutions(), 31);
      assertEquals(nbNodeFromRegulatModel(seed), nbNode);
    }
  }

  private int nbNodeFromRegulatModel(int seed) {
    m = new CPModel();
    s = new CPSolver();
    int k = 2;
    IntegerVariable v0 = makeIntVar("v0", 0, 10);
    IntegerVariable v1 = makeIntVar("v1", 0, 10);
    List<int[]> ltuple = new LinkedList<int[]>();
    for (int i = 0; i <= 10; i++) {
      for (int j = 0; j <= 10; j++) {
        if (Math.abs(i - j) < k) ltuple.add(new int[] {i, j});
      }
    }
    m.addConstraint(regular(new IntegerVariable[] {v0, v1}, ltuple));
    s.read(m);
    s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
    s.setValIntSelector(new RandomIntValSelector(seed));
    try {
      s.propagate();
    } catch (ContradictionException e) {
      LOGGER.info(e.getMessage()); // To change body of catch statement use File | Settings | File
      // Templates.
    }
    s.solveAll();
    // LOGGER.info("solutions regular : " + s.getNbSolutions());
    return s.getNodeCount();
  }

  // ********************************************************************//
  // ****************************** Test on DistanceXYZ *****************//
  // ********************************************************************//

  @Test
  public void testDXYZProp1() {
    IntegerVariable v0 = makeIntVar("v0", 1, 4);
    IntegerVariable v1 = makeIntVar("v1", 5, 7);
    IntegerVariable v2 = makeIntVar("v2", -100, 100);
    m.addVariables(Options.V_BOUND, v0, v1, v2);
    m.addConstraint(distanceEQ(v0, v1, v2, 0));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      assertTrue(false);
    }
    assertEquals(1, s.getVar(v2).getInf());
    assertEquals(6, s.getVar(v2).getSup());
  }

  @Test
  public void testDXYZProp1bis() {

    IntegerVariable v0 = makeIntVar("v0", 1, 4);
    IntegerVariable v1 = makeIntVar("v1", 5, 7);
    IntegerVariable v2 = makeIntVar("v2", -100, 100);
    m.addVariables(Options.V_BOUND, v0, v1, v2);
    m.addConstraint(distanceEQ(v0, v1, v2, 2));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      LOGGER.info(e.getMessage());
      assertTrue(false);
    }
    assertEquals(-1, s.getVar(v2).getInf());
    assertEquals(4, s.getVar(v2).getSup());
  }

  @Test
  public void testDXYZProp2() {

    IntegerVariable v0 = makeIntVar("v0", 1, 5);
    IntegerVariable v1 = makeIntVar("v1", 5, 10);
    IntegerVariable v2 = makeIntVar("v2", 1, 2);
    m.addVariables(Options.V_BOUND, v0, v1, v2);
    m.addConstraint(distanceEQ(v0, v1, v2, 0));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      assertTrue(false);
    }
    assertEquals(3, s.getVar(v0).getInf());
    assertEquals(7, s.getVar(v1).getSup());
  }

  @Test
  public void testDXYZProp2bis() {

    IntegerVariable v0 = makeIntVar("v0", 1, 5);
    IntegerVariable v1 = makeIntVar("v1", 5, 10);
    IntegerVariable v2 = makeIntVar("v2", 1, 2);
    m.addVariables(Options.V_BOUND, v0, v1, v2);
    m.addConstraint(distanceEQ(v0, v1, v2, -1));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      assertTrue(false);
    }
    assertEquals(4, s.getVar(v0).getInf());
    assertEquals(6, s.getVar(v1).getSup());
    s.solve();
    LOGGER.info("" + s.pretty());
  }

  @Test
  public void testDXYZProp3() {

    IntegerVariable v0 = makeIntVar("v0", 1, 5);
    IntegerVariable v1 = makeIntVar("v1", 5, 6);
    IntegerVariable v2 = makeIntVar("v2", 3, 10);
    m.addVariables(Options.V_BOUND, v0, v1, v2);
    m.addConstraint(distanceEQ(v0, v1, v2, 0));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      assertTrue(false);
    }
    assertEquals(3, s.getVar(v0).getSup());
    assertEquals(5, s.getVar(v2).getSup());
  }

  @Test
  public void testDXYZProp4() {

    IntegerVariable v0 = makeIntVar("v0", -1, 5);
    IntegerVariable v1 = makeIntVar("v1", -5, 6);
    IntegerVariable v2 = makeIntVar("v2", -2, 2);
    m.addConstraint(distanceEQ(v0, v1, v2, 0));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      assertTrue(false);
    }
    assertEquals(-3, s.getVar(v1).getInf());
    assertEquals(0, s.getVar(v2).getInf());
  }

  @Test
  public void testDXYZProp5() {

    IntegerVariable v0 = makeIntVar("v0", -1, 1);
    IntegerVariable v1 = makeIntVar("v1", -5, 6);
    IntegerVariable v2 = makeIntVar("v2", 3, 10);
    m.addConstraint(distanceEQ(v0, v1, v2, 0));
    s.read(m);
    try {
      s.propagate();
    } catch (ContradictionException e) {
      assertTrue(false);
    }
    LOGGER.info("" + v1.pretty());
    assertTrue(!s.getVar(v1).canBeInstantiatedTo(0));
    assertTrue(!s.getVar(v1).canBeInstantiatedTo(1));
    assertTrue(!s.getVar(v1).canBeInstantiatedTo(-1));
    assertEquals(7, s.getVar(v2).getSup());
  }

  @Test
  public void testDXYZSolve1() {
    for (int seed = 0; seed < 10; seed++) {

      m = new CPModel();
      s = new CPSolver();
      IntegerVariable v0 = makeIntVar("v0", 0, 5);
      IntegerVariable v1 = makeIntVar("v1", 0, 5);
      IntegerVariable v2 = makeIntVar("v2", 0, 5);
      m.addConstraint(distanceEQ(v0, v1, v2, 0));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));

      s.solveAll();
      assertEquals(36, s.getNbSolutions());
    }
  }

  @Test
  public void testDXYZSolve2() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      IntegerVariable v0 = makeIntVar("v0", 3, 6);
      IntegerVariable v1 = makeIntVar("v1", -3, 4);
      IntegerVariable v2 = makeIntVar("v2", 0, 5);
      IntegerVariable v3 = makeIntVar("v3", 2, 5);

      m.addConstraint(distanceEQ(v0, v1, v2, 0));
      m.addConstraint(distanceEQ(v0, v2, v3, 0));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));

      s.solveAll();
      LOGGER.info("nbsol " + s.getNbSolutions());
      assertEquals(getNbSolByDecomp(0), s.getNbSolutions());
    }
  }

  @Test
  public void testDXYZSolve3() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      IntegerVariable v0 = makeIntVar("v0", 3, 6);
      IntegerVariable v1 = makeIntVar("v1", -3, 4);
      IntegerVariable v2 = makeIntVar("v2", 0, 5);
      IntegerVariable v3 = makeIntVar("v3", 2, 5);

      m.addConstraint(distanceLT(v0, v1, v2, 0));
      m.addConstraint(distanceLT(v0, v2, v3, 0));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));

      s.solveAll();
      LOGGER.info("nbsol " + s.getNbSolutions());
      assertEquals(getNbSolByDecomp(1), s.getNbSolutions());
    }
  }

  @Test
  public void testDXYZSolve4() {
    for (int seed = 0; seed < 10; seed++) {
      m = new CPModel();
      s = new CPSolver();
      IntegerVariable v0 = makeIntVar("v0", 3, 6);
      IntegerVariable v1 = makeIntVar("v1", -3, 4);
      IntegerVariable v2 = makeIntVar("v2", 0, 5);
      IntegerVariable v3 = makeIntVar("v3", 2, 5);

      m.addConstraint(distanceGT(v0, v1, v2, 0));
      m.addConstraint(distanceGT(v0, v2, v3, 0));
      s.read(m);
      s.setVarIntSelector(new RandomIntVarSelector(s, seed + 32));
      s.setValIntSelector(new RandomIntValSelector(seed));

      s.solveAll();
      LOGGER.info("nbsol " + s.getNbSolutions());
      assertEquals(getNbSolByDecomp(2), s.getNbSolutions());
    }
  }

  public int getNbSolByDecomp(int op) {
    Model m = new CPModel();
    Solver s = new CPSolver();
    IntegerVariable v0 = makeIntVar("v0", 3, 6);
    IntegerVariable v1 = makeIntVar("v1", -3, 4);
    IntegerVariable interV0V1 = makeIntVar("v01", -100, 100);
    IntegerVariable v2 = makeIntVar("v2", 0, 5);
    IntegerVariable interV0V2 = makeIntVar("v02", -100, 100);
    IntegerVariable v3 = makeIntVar("v3", 2, 5);

    m.addConstraint(eq(minus(v0, v1), interV0V1));
    m.addConstraint(eq(minus(v0, v2), interV0V2));
    if (op == 0) {
      m.addConstraint(abs(v2, interV0V1));
      m.addConstraint(abs(v3, interV0V2));
    } else if (op == 1) {
      IntegerVariable interV0V1bis = makeIntVar("v01b", -100, 100);
      IntegerVariable interV0V2bis = makeIntVar("v02b", -100, 100);
      m.addConstraint(abs(interV0V1bis, interV0V1));
      m.addConstraint(abs(interV0V2bis, interV0V2));
      m.addConstraint(lt(interV0V1bis, v2));
      m.addConstraint(lt(interV0V2bis, v3));
    } else {
      IntegerVariable interV0V1bis = makeIntVar("v01b", -100, 100);
      IntegerVariable interV0V2bis = makeIntVar("v02b", -100, 100);
      m.addConstraint(abs(interV0V1bis, interV0V1));
      m.addConstraint(abs(interV0V2bis, interV0V2));
      m.addConstraint(gt(interV0V1bis, v2));
      m.addConstraint(gt(interV0V2bis, v3));
    }
    s.read(m);
    s.solveAll();
    return s.getNbSolutions();
  }

  @Test
  public void testEQ() {
    Model m1 = new CPModel();
    IntegerVariable x = makeIntVar("x", 2, 10);
    IntegerVariable y = makeIntVar("y", 2, 10);

    m1.addConstraint(distanceEQ(x, y, -2));

    Model m2 = new CPModel();
    m2.addConstraint(eq(abs(minus(x, y)), -2));

    Solver s1 = new CPSolver();
    s1.read(m1);

    Solver s2 = new CPSolver();
    s2.read(m2);

    s1.solveAll();
    s2.solveAll();

    Assert.assertEquals("nb sol", s1.getNbSolutions(), s2.getNbSolutions());
  }

  @Test
  public void testNEQ() {
    Model m1 = new CPModel();
    IntegerVariable x = makeIntVar("x", 2, 4);
    IntegerVariable y = makeIntVar("y", 2, 4);

    m1.addConstraint(distanceNEQ(x, y, -2));

    Model m2 = new CPModel();
    m2.addConstraint(neq(abs(minus(x, y)), -2));

    Solver s1 = new CPSolver();
    s1.read(m1);

    Solver s2 = new CPSolver();
    s2.read(m2);

    //        s1.solveAll();
    //        s2.solveAll();
    s1.solve();
    do {
      LOGGER.info("x:" + s1.getVar(x).getVal() + " y:" + s1.getVar(y).getVal());
    } while (s1.nextSolution());
    LOGGER.info("=======");

    s2.solve();
    do {
      LOGGER.info("x:" + s2.getVar(x).getVal() + " y:" + s2.getVar(y).getVal());
    } while (s2.nextSolution());

    Assert.assertEquals("nb sol", s1.getNbSolutions(), s2.getNbSolutions());
  }

  @Test
  public void testGT() {
    Model m1 = new CPModel();
    IntegerVariable x = makeIntVar("x", 2, 10);
    IntegerVariable y = makeIntVar("y", 2, 10);

    m1.addConstraint(distanceGT(x, y, -2));

    Model m2 = new CPModel();
    m2.addConstraint(gt(abs(minus(x, y)), -2));

    Solver s1 = new CPSolver();
    s1.read(m1);

    Solver s2 = new CPSolver();
    s2.read(m2);

    s1.solveAll();
    s2.solveAll();

    Assert.assertEquals("nb sol", s1.getNbSolutions(), s2.getNbSolutions());
  }

  @Test
  public void testLT() {
    Model m1 = new CPModel();
    IntegerVariable x = makeIntVar("x", 2, 10);
    IntegerVariable y = makeIntVar("y", 2, 10);

    m1.addConstraint(distanceLT(x, y, -2));

    Model m2 = new CPModel();
    m2.addConstraint(lt(abs(minus(x, y)), -2));

    Solver s1 = new CPSolver();
    s1.read(m1);

    Solver s2 = new CPSolver();
    s2.read(m2);

    s1.solveAll();
    s2.solveAll();

    Assert.assertEquals("nb sol", s1.getNbSolutions(), s2.getNbSolutions());
  }
}
예제 #3
0
/**
 * User : cprudhom<br>
 * Mail : cprudhom(a)emn.fr<br>
 * Date : 26 avr. 2010<br>
 * Since : Choco 2.1.1<br>
 */
abstract class AbstractTestProblem {

  private static final Logger LOGGER = ChocoLogging.getTestLogger();

  public CPModel model;

  public CPSolver solver;

  public Constraint rsc;

  public IntegerVariable[] starts;

  public IntegerVariable[] durations;

  public TaskVariable[] tasks;

  public int horizon = 10000000;

  private static final Random RANDOM = new Random();

  public AbstractTestProblem() {
    super();
  }

  public AbstractTestProblem(final IntegerVariable[] starts, final IntegerVariable[] durations) {
    super();
    this.starts = starts;
    this.durations = durations;
  }

  public AbstractTestProblem(final IntegerVariable[] durations) {
    super();
    this.durations = durations;
  }

  public final void setFlags(final BitMask flags) {
    final SConstraint cstr = solver.getCstr(this.rsc);
    BitMask dest = null;
    if (cstr instanceof AbstractResourceSConstraint) {
      dest = ((AbstractResourceSConstraint) cstr).getFlags();
    } else if (cstr instanceof MetaSConstraint) {
      dest =
          ((AbstractResourceSConstraint) ((MetaSConstraint) cstr).getSubConstraints(0)).getFlags();
    }
    if (dest != null) {
      dest.clear();
      dest.set(flags);
    } else ChocoLogging.getTestLogger().info("can not apply resource filtering rules");
  }

  public static final Configuration getConfig(boolean b) {
    final PreProcessConfiguration config = new PreProcessConfiguration();
    PreProcessConfiguration.cancelPreProcess(config);
    config.putTrue(PreProcessConfiguration.DISJUNCTIVE_MODEL_DETECTION);
    config.putTrue(PreProcessConfiguration.DMD_USE_TIME_WINDOWS);
    if (b) {
      config.putTrue(PreProcessConfiguration.DMD_REMOVE_DISJUNCTIVE);
      // can change the number of solutions if it substitutes a cumulative with variable height by a
      // disjunctive.
      // config.putTrue(PreProcessConfiguration.DISJUNCTIVE_FROM_CUMULATIVE_DETECTION);
    }
    return config;
  }

  public void generateSolver(Configuration conf) {
    SolverDetectorFactory.resetIndexes(model);
    solver = conf == null ? new CPSolver() : new PreProcessCPSolver(conf);
    solver.setHorizon(horizon);
    solver.read(model);
  }

  protected abstract Constraint[] generateConstraints();

  public void initializeModel() {
    model = new CPModel();
    initializeTasks();
    final Constraint[] cstr = generateConstraints();
    if (cstr != null) {
      rsc = cstr[0];
      model.addConstraints(cstr);
    } else {
      LOGGER.severe("no model constraint ?");
    }
  }

  public void initializeTasks() {
    if (starts == null) {
      tasks = Choco.makeTaskVarArray("T", 0, horizon, durations);
    } else {
      tasks = new TaskVariable[durations.length];
      for (int i = 0; i < tasks.length; i++) {
        tasks[i] =
            Choco.makeTaskVar(
                String.format("T_%d", i),
                starts[i],
                Choco.makeIntVar(String.format("end-%d", i), 0, horizon, Options.V_BOUND),
                durations[i]);
      }
    }
  }

  public void setHorizon(final int horizon) {
    this.horizon = horizon;
  }

  protected void horizonConstraints(
      final IntegerVariable[] starts, final IntegerVariable[] durations) {
    if (horizon > 0) {
      for (int i = 0; i < starts.length; i++) {
        model.addConstraint(Choco.geq(horizon, Choco.plus(starts[i], durations[i])));
      }
    }
  }

  public IntegerVariable[] generateRandomDurations(final int n) {
    final IntegerVariable[] durations = new IntegerVariable[n];
    final int gap = horizon / n;
    int max = gap + horizon % n;
    for (int i = 0; i < n - 1; i++) {
      final int v = RANDOM.nextInt(max) + 1;
      max += gap - v;
      durations[i] = Choco.constant(v);
    }
    durations[n - 1] = Choco.constant(max);
    return durations;
  }

  public void setRandomProblem(final int size) {
    starts = null;
    durations = generateRandomDurations(size);
  }
}
예제 #4
0
public class GeostTest {

  protected static final Logger LOGGER = ChocoLogging.getTestLogger();

  int dim;
  int mode;

  @Before
  public void before() {
    dim = 3;
    mode = 0;
  }

  @Test
  public void testCustomProblem() {

    int lengths[] = {5, 3, 2};
    int widths[] = {2, 2, 1};
    int heights[] = {1, 1, 1};

    int nbOfObj = 3;

    for (int seed = 0; seed < 20; seed++) {
      // create the choco problem
      Model m = new CPModel();

      // Create Objects
      List<GeostObject> obj2 = new ArrayList<GeostObject>();

      for (int i = 0; i < nbOfObj; i++) {
        IntegerVariable shapeId = makeIntVar("sid", i, i);
        IntegerVariable coords[] = new IntegerVariable[this.dim];
        for (int j = 0; j < coords.length; j++) {
          coords[j] = makeIntVar("x" + j, 0, 2);
        }
        IntegerVariable start = makeIntVar("start", 1, 1);
        IntegerVariable duration = makeIntVar("duration", 1, 1);
        IntegerVariable end = makeIntVar("end", 1, 1);
        obj2.add(new GeostObject(dim, i, shapeId, coords, start, duration, end));
      }

      // create shiftedboxes and add them to corresponding shapes
      List<ShiftedBox> sb2 = new ArrayList<ShiftedBox>();
      int h = 0;
      while (h < nbOfObj) {

        int[] l = {lengths[h], heights[h], widths[h]};
        int[] t = {0, 0, 0};

        sb2.add(new ShiftedBox(h, t, l));
        h++;
      }

      // Create the external constraints vecotr
      List<IExternalConstraint> ectr2 = new ArrayList<IExternalConstraint>();
      // create the list od dimensions for the external constraint
      int[] ectrDim2 = new int[this.dim];
      for (int d = 0; d < 3; d++) ectrDim2[d] = d;

      // create the list of object ids for the external constraint
      int[] objOfEctr2 = new int[nbOfObj];
      for (int d = 0; d < nbOfObj; d++) {
        objOfEctr2[d] = obj2.get(d).getObjectId();
      }

      // create the external constraint of type non overlapping
      NonOverlappingModel n2 =
          new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim2, objOfEctr2);
      // add the external constraint to the vector
      ectr2.add(n2);

      // create the geost constraint object
      Constraint geost = geost(this.dim, obj2, sb2, ectr2);
      m.addConstraint(geost);
      // post the geost constraint to the choco problem
      Solver s = new CPSolver();
      s.read(m);
      s.setValIntSelector(new RandomIntValSelector(seed));
      s.setVarIntSelector(new RandomIntVarSelector(s, seed));
      s.solveAll();
      Assert.assertEquals("number of solutions", 9828, s.getNbSolutions());
    }
  }

  @Test
  @Ignore
  public void RandomProblemGeneration() {

    for (int seed = 0; seed < /*20*/ 5; seed++) {
      // nb of objects, shapes, shifted boxes and maxLength respectively
      // The nb of Obj should be equal to nb Of shapes for NOW. as For the number of the shifted
      // Boxes it should be greater or equal to thhe nb of Objects

      RandomProblemGenerator rp = new RandomProblemGenerator(this.dim, 7, 7, 9, 25);

      rp.generateProb();

      Model m = rp.getModel();

      List<IExternalConstraint> ectr = new ArrayList<IExternalConstraint>();
      int[] ectrDim = new int[this.dim];
      for (int i = 0; i < this.dim; i++) ectrDim[i] = i;

      int[] objOfEctr = new int[rp.getObjects().size()];
      for (int i = 0; i < rp.getObjects().size(); i++) {
        objOfEctr[i] = rp.getObjects().get(i).getObjectId();
      }

      NonOverlappingModel n =
          new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr);
      ectr.add(n);

      Constraint geost = geost(this.dim, rp.getObjects(), rp.getSBoxes(), ectr);
      m.addConstraint(geost);
      Solver s = new CPSolver();
      s.read(m);
      s.setValIntSelector(new RandomIntValSelector(seed));
      s.setVarIntSelector(new RandomIntVarSelector(s, seed));
      s.solveAll();
      Assert.assertEquals("number of solutions", 0, s.getNbSolutions());
    }
  }

  @Test
  public void PolyMorphicTest() {
    int[][] objects =
        new int[][] {
          {0, 0, 1, 0, 3, 0, 4, 1, 1, 1, 1, 1, 1},
          {1, 0, 1, 0, 3, 0, 4, 1, 1, 1, 1, 1, 1},
          {2, 0, 1, 0, 3, 0, 4, 1, 1, 1, 1, 1, 1},
          {3, 0, 1, 0, 3, 0, 4, 1, 1, 1, 1, 1, 1},
          {4, 0, 1, 0, 3, 0, 4, 1, 1, 1, 1, 1, 1},
          {5, 2, 2, 0, 0, 6, 6, 1, 1, 1, 1, 1, 1}
        };
    int[] shapes = new int[] {2, 1, 0};
    int[][] shiftedBoxes =
        new int[][] {
          {0, 0, 0, 3, 2},
          {1, 0, 0, 2, 3},
          {2, 0, 0, 5, 1},
          {2, 5, -6, 1, 7},
        };

    this.dim = 2;

    InputParser parser;
    new InputParser();

    InputParser.GeostProblem gp = new InputParser.GeostProblem(objects, shapes, shiftedBoxes);
    for (int seed = 0; seed < 20; seed++) {
      parser = new InputParser(gp, dim);
      try {
        parser.parse();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      Model m = new CPModel();

      // create a vector to hold in it all the external constraints we want to add to geost
      List<IExternalConstraint> ectr = new ArrayList<IExternalConstraint>();

      // ////////////Create the needed external constraints//////////////

      // first of all create a array of intergers containing all the dimensions where the constraint
      // will be active
      int[] ectrDim = new int[dim];
      for (int i = 0; i < dim; i++) ectrDim[i] = i;

      // Create an array of object ids representing all the objects that the external constraint
      // will be applied to
      int[] objOfEctr = new int[parser.getObjects().size()];
      for (int i = 0; i < parser.getObjects().size(); i++) {
        objOfEctr[i] = parser.getObjects().get(i).getObjectId();
      }

      // Create the external constraint, in our case it is the NonOverlappingModel
      // constraint (it is the only one implemented for now)
      NonOverlappingModel n =
          new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr);

      // add the created external constraint to the vector we created
      ectr.add(n);

      // /////////////Create the array of variables to make choco happy//////////////
      // vars will be stored as follows: object 1 coords(so k coordinates), sid, start, duration,
      // end,
      //                                 object 2 coords(so k coordinates), sid, start, duration,
      // end and so on ........
      // To retrieve the index of a certain variable, the formula is (nb of the object in question =
      // objId assuming objIds are consecutive and
      // start from 0) * (k + 4) + number of the variable wanted the number of the variable wanted
      // is decided as follows: 0 ... k-1
      // (the coords), k (the sid), k+1 (start), k+2 (duration), k+3 (end)

      int originOfObjects = parser.getObjects().size() * dim;
      // Number of domain  variables  to  represent the origin of all  objects
      int otherVariables =
          parser.getObjects().size()
              * 4; // each object  has 4 other variables: shapeId, start,  duration; end
      IntegerVariable[] vars = new IntegerVariable[originOfObjects + otherVariables];

      for (int i = 0; i < parser.getObjects().size(); i++) {
        for (int j = 0; j < dim; j++) {
          vars[(i * (dim + 4)) + j] = parser.getObjects().get(i).getCoordinates()[j];
        }
        vars[(i * (dim + 4)) + dim] = parser.getObjects().get(i).getShapeId();
        vars[(i * (dim + 4)) + dim + 1] = parser.getObjects().get(i).getStartTime();
        vars[(i * (dim + 4)) + dim + 2] = parser.getObjects().get(i).getDurationTime();
        vars[(i * (dim + 4)) + dim + 3] = parser.getObjects().get(i).getEndTime();
      }

      Constraint geost = geost(dim, parser.getObjects(), parser.getShiftedBoxes(), ectr);

      // /////////////Add the constraint to the choco problem//////////////
      m.addConstraint(geost);

      for (int i = 0; i < parser.getObjects().size() - 2; i++) {
        m.addConstraint(
            lex(
                parser.getObjects().get(i).getCoordinates(),
                parser.getObjects().get(i + 1).getCoordinates()));
      }

      Solver s = new CPSolver();
      s.read(m);

      s.setValIntSelector(new RandomIntValSelector(seed));
      s.setVarIntSelector(new RandomIntVarSelector(s, seed));

      s.solveAll();
      Assert.assertEquals(s.getNbSolutions(), 2);
    }
  }

  @Test
  public void testOfSharingShape() {

    int lengths[] = {5, 3, 6};
    int widths[] = {2, 4, 1};
    int heights[] = {1, 2, 4};

    int nbOfObj = 3;
    Model m = new CPModel();

    // Create Objects
    List<GeostObject> obj2 = new ArrayList<GeostObject>();

    for (int i = 0; i < nbOfObj; i++) {
      IntegerVariable shapeId = makeIntVar("sid", 0, 0);
      IntegerVariable coords[] = new IntegerVariable[this.dim];
      for (int j = 0; j < coords.length; j++) {
        coords[j] = makeIntVar("x" + j, 0, 2);
      }
      IntegerVariable start = makeIntVar("start", 1, 1);
      IntegerVariable duration = makeIntVar("duration", 1, 1);
      IntegerVariable end = makeIntVar("end", 1, 1);
      obj2.add(new GeostObject(dim, i, shapeId, coords, start, duration, end));
    }
    for (int i = 0; i < obj2.size(); i++) {
      for (int d = 0; d < this.dim; d++) {
        LOGGER.info(
            ""
                + obj2.get(i).getCoordinates()[d].getLowB()
                + "    "
                + obj2.get(i).getCoordinates()[d].getUppB());
      }
    }

    // create shiftedboxes and add them to corresponding shapes
    List<ShiftedBox> sb2 = new ArrayList<ShiftedBox>();

    int[] l = {lengths[0], heights[0], widths[0]};
    int[] t = {0, 0, 0};

    sb2.add(new ShiftedBox(0, t, l));

    List<IExternalConstraint> ectr2 = new ArrayList<IExternalConstraint>();
    int[] ectrDim2 = new int[this.dim];
    for (int d = 0; d < 3; d++) ectrDim2[d] = d;

    int[] objOfEctr2 = new int[nbOfObj];
    for (int d = 0; d < nbOfObj; d++) {
      objOfEctr2[d] = obj2.get(d).getObjectId();
    }

    NonOverlappingModel n2 =
        new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim2, objOfEctr2);
    ectr2.add(n2);

    Constraint geost2 = geost(this.dim, obj2, sb2, ectr2);
    m.addConstraint(geost2);
    Solver s = new CPSolver();
    s.read(m);
    // Here the solve will only do a test for the first constraint and not the second.
    // However for our purposes this is not important. If it is just change the code
    // of solve to take 2 constraints as parameters and then run the two solution testers
    s.solveAll();
    Assert.assertEquals(s.getNbSolutions(), 7290);
  }

  @Test
  public void exp2DTest() {

    // The data
    int dim = 2;
    int[][] domOrigins = {
      {0, 5, 0, 3},
      {0, 5, 0, 5},
      {0, 6, 0, 4},
      {0, 6, 0, 5},
      {0, 5, 0, 5},
      {0, 7, 0, 4},
      {0, 6, 0, 5},
      {0, 6, 0, 5},
      {0, 5, 0, 6},
      {0, 7, 0, 5}
    };

    int[][] shBoxes = {
      {0, 0, 0, 2, 3},
      {0, 1, 2, 2, 2},
      {1, 0, 0, 3, 2},
      {2, 0, 0, 2, 3},
      {3, 0, 0, 2, 2},
      {4, 0, 0, 3, 1},
      {4, 1, 0, 1, 2},
      {5, 0, 0, 1, 3},
      {6, 0, 0, 1, 2},
      {6, 0, 1, 2, 1},
      {7, 0, 0, 2, 1},
      {7, 1, 0, 1, 2},
      {8, 0, 0, 3, 1},
      {9, 0, 0, 1, 2}
    };
    int[] v0 = {-1, -2, -3};
    int[] v1 = {-1, 2, 3};
    int[] v2 = {-1, 2, -3};
    int[] v3 = {-1, 3, -2};

    int nbOfObj = 10;

    // create the choco problem
    Model m = new CPModel();

    // Create Objects
    List<GeostObject> obj = new ArrayList<GeostObject>();

    for (int i = 0; i < nbOfObj; i++) {
      IntegerVariable shapeId = makeIntVar("sid", i, i);
      IntegerVariable coords[] = new IntegerVariable[dim];
      coords[0] = makeIntVar("x", domOrigins[i][0], domOrigins[i][1]);
      coords[1] = makeIntVar("y", domOrigins[i][2], domOrigins[i][3]);

      IntegerVariable start = makeIntVar("start", 1, 1);
      IntegerVariable duration = makeIntVar("duration", 1, 1);
      IntegerVariable end = makeIntVar("end", 1, 1);
      obj.add(new GeostObject(dim, i, shapeId, coords, start, duration, end));
    }

    // create shiftedboxes and add them to corresponding shapes
    List<ShiftedBox> sb = new ArrayList<ShiftedBox>();
    for (int i = 0; i < shBoxes.length; i++) {
      int[] offset = {shBoxes[i][1], shBoxes[i][2]};
      int[] sizes = {shBoxes[i][3], shBoxes[i][4]};
      sb.add(new ShiftedBox(shBoxes[i][0], offset, sizes));
    }

    // Create the external constraints vecotr
    List<IExternalConstraint> ectr = new ArrayList<IExternalConstraint>();
    // create the list of dimensions for the external constraint
    int[] ectrDim = new int[dim];
    for (int d = 0; d < dim; d++) ectrDim[d] = d;

    // create the list of object ids for the external constraint
    int[] objOfEctr = new int[nbOfObj];
    for (int d = 0; d < nbOfObj; d++) {
      objOfEctr[d] = obj.get(d).getObjectId();
    }

    //		create the external constraint of type non overlapping
    NonOverlappingModel n = new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr);
    // add the external constraint to the vector
    ectr.add(n);

    // create the list of controlling vectors
    List<int[]> ctrlVs = new ArrayList<int[]>();
    ctrlVs.add(v0);
    // ctrlVs.add(v1);
    // ctrlVs.add(v2);
    // ctrlVs.add(v3);

    // create the geost constraint
    Constraint geost = geost(dim, obj, sb, ectr, ctrlVs);

    // NOTA: you can choose to not take into account of the greedy mode by creating the geost
    // constraint as follows:
    // Geost_Constraint geost = new Geost_Constraint(vars, dim, obj, sb, ectr);

    // post the geost constraint to the choco problem
    m.addConstraint(geost);

    Solver s = new CPSolver();
    s.read(m);

    // solve the probem
    s.solve();

    for (int i = 0; i < obj.size(); i++) {
      GeostObject o = obj.get(i);
      StringBuffer st = new StringBuffer();
      st.append(MessageFormat.format("Object {0}: ", o.getObjectId()));
      for (int j = 0; j < dim; j++)
        st.append(MessageFormat.format("{0} ", s.getVar(o.getCoordinates()[j])));
      LOGGER.info(st.toString());
    }
  }

  public static int[][] domOrigins = {
    {0, 1, 0, 1}, {0, 1, 0, 1}, {0, 1, 0, 3},
  };

  public static int[][] domShapes = {{0, 1}, {2, 2}, {3, 3}};

  public static int[][] shBoxes = {
    {0, 0, 0, 1, 3},
    {0, 0, 0, 2, 1},
    {1, 0, 0, 2, 1},
    {1, 1, 0, 1, 3},
    {2, 0, 0, 2, 1},
    {2, 1, 0, 1, 3},
    {2, 0, 2, 2, 1},
    {3, 0, 0, 2, 1},
  };

  @Test
  public void exp2D2Test() {

    dim = 2;
    int nbOfObj = 3;

    // create the choco problem
    Model m = new CPModel();

    // Create Objects
    List<GeostObject> objects = new ArrayList<GeostObject>();

    for (int i = 0; i < nbOfObj; i++) {
      IntegerVariable shapeId = makeIntVar("sid_" + i, domShapes[i][0], domShapes[i][1]);
      IntegerVariable coords[] = new IntegerVariable[dim];
      coords[0] = makeIntVar("x_" + i, domOrigins[i][0], domOrigins[i][1]);
      coords[1] = makeIntVar("y_" + i, domOrigins[i][2], domOrigins[i][3]);

      // ++ Modification
      // Additional Constraint
      m.addConstraint(geq(coords[0], 1));
      // -- Modification

      IntegerVariable start = makeIntVar("start", 0, 0);
      IntegerVariable duration = makeIntVar("duration", 1, 1);
      IntegerVariable end = makeIntVar("end", 1, 1);
      objects.add(new GeostObject(dim, i, shapeId, coords, start, duration, end));
    }

    // create shiftedboxes and add them to corresponding shapes
    List<ShiftedBox> sb = new ArrayList<ShiftedBox>();

    for (int i = 0; i < shBoxes.length; i++) {
      int[] offset = {shBoxes[i][1], shBoxes[i][2]};
      int[] sizes = {shBoxes[i][3], shBoxes[i][4]};
      sb.add(new ShiftedBox(shBoxes[i][0], offset, sizes));
    }

    // Create the external constraints vecotr
    List<IExternalConstraint> ectr = new ArrayList<IExternalConstraint>();

    // create the list of dimensions for the external constraint
    int[] ectrDim = new int[dim];
    for (int d = 0; d < dim; d++) ectrDim[d] = d;

    // create the list of object ids for the external constraint
    int[] objOfEctr = new int[nbOfObj];
    for (int d = 0; d < nbOfObj; d++) {
      objOfEctr[d] = objects.get(d).getObjectId();
    }

    // create the external constraint of non overlapping type
    NonOverlappingModel n = new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr);
    // add the external constraint to the ectr vector
    ectr.add(n);

    // create the geost constraint
    Constraint geost = geost(dim, objects, sb, ectr);

    // post the geost constraint to the choco problem
    m.addConstraint(geost);

    // build a solver
    Solver s = new CPSolver();
    // read the problem
    s.read(m);

    // solve the probem
    s.solve();

    Assert.assertSame("No solution expected", Boolean.FALSE, s.isFeasible());

    // print the solution
    LOGGER.info(s.pretty());
  }

  @Test
  public void test_ajdvries() {
    for (int nbO = 4; nbO < 257; nbO *= 4) {
      boolean inc = true;
      do {
        int width = nbO * 5;
        int height = nbO * 5;
        int maxX = width - 5;
        int maxY = height - 5;

        CPModel m = new CPModel();

        List<GeostObject> geosts = new Vector<GeostObject>();
        List<ShiftedBox> sb = new Vector<ShiftedBox>();

        List<IntegerVariable> x = new ArrayList<IntegerVariable>();
        List<IntegerVariable> y = new ArrayList<IntegerVariable>();
        for (int a = 0; a < 16; a++) {
          IntegerVariable varX = makeIntVar("img_" + a + "_x", 0, maxX);
          IntegerVariable varY = makeIntVar("img_" + a + "_y", 0, maxY);
          x.add(varX);

          y.add(varY);
          IntegerVariable coordinates[] = new IntegerVariable[] {varX, varY};

          geosts.add(
              new GeostObject(
                  2, a, constant(a), coordinates, constant(0), constant(1), constant(1)));

          sb.add(new ShiftedBox(a, new int[] {0, 0}, new int[] {5, 5}));
        }

        Vector<IExternalConstraint> ectr = new Vector();

        int[] ectrDim = new int[] {0, 1};
        int[] objOfEctr = new int[geosts.size()];
        for (int i = 0; i < geosts.size(); i++) {
          objOfEctr[i] = geosts.get(i).getObjectId();
        }

        NonOverlappingModel n =
            new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr);
        ectr.add(n);

        Vector<int[]> ctrlVs = new Vector<int[]>();
        int[] v0 = {1, -3, -2};
        ctrlVs.add(v0);

        // Definition of the GEOST constraint
        GeostOptions.increment = inc;
        Constraint geost = geost(2, geosts, sb, ectr, ctrlVs);
        m.addConstraint(geost);

        Solver solver = new CPSolver();
        solver.read(m);
        Assert.assertTrue(solver.solve());
        inc ^= true;
      } while (!inc);
    }
  }

  @Test
  public void testNonOverlap() {
    CPModel model = new CPModel();

    List<GeostObject> geosts = new ArrayList<GeostObject>();
    Map<Integer, ShiftedBox> boxesById = new HashMap<Integer, ShiftedBox>();

    // Blocks to be placed
    int currentShapeId = 0;
    ShiftedBox block = new ShiftedBox(currentShapeId, new int[] {0, 0}, new int[] {20, 1});
    boxesById.put(currentShapeId, block);

    IntegerVariable[] fixedCoordinates = new IntegerVariable[] {constant(0), constant(0)};
    IntegerVariable[] variableCoordinates =
        new IntegerVariable[] {makeIntVar("variable", 0, 0), constant(0)};

    geosts.add(
        new GeostObject(
            2,
            0,
            constant(currentShapeId),
            fixedCoordinates,
            constant(0),
            constant(1),
            constant(1)));

    geosts.add(
        new GeostObject(
            2,
            1,
            constant(currentShapeId),
            fixedCoordinates,
            constant(0),
            constant(1),
            constant(1)));

    List<IExternalConstraint> ectr = new ArrayList<IExternalConstraint>();

    int[] ectrDim = new int[] {0, 1};
    int[] objOfEctr = new int[geosts.size()];

    NonOverlappingModel n = new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr);
    ectr.add(n);

    List<int[]> ctrlVs = new ArrayList<int[]>();
    int[] v0 = {1, -3, -2};
    // int[] v1 = { 1, -2, 2 };
    // ctrlVs.add(v1);
    ctrlVs.add(v0);

    // Definition of the GEOST constraint
    Constraint geost =
        geost(2, geosts, new ArrayList<ShiftedBox>(boxesById.values()), ectr, ctrlVs);
    model.addConstraint(geost);

    CPSolver solver = new CPSolver();
    solver.read(model);

    Assert.assertFalse(solver.solve());
  }

  @Test
  public void testSerge() {
    // On this very first experiment, we'll consider only a single shape
    //  for each object
    // Labels to be placed are:
    // - a label of size (2,2) near (6,3) : at (7,4) or at (4,1)
    // - a label of size (2,4) near (3,2) : at (4,3) or at (0,3)
    // Graphically, this gives (a and b are alternatives for label 1, c and d for 2):
    //
    //        5                               a   a
    //        4   d   d   d   d   c   c   c   ac  a
    //        3   d   d   d   d   c   c   1c  c
    //        2               2   b   b
    //        1                   b   b
    //        0
    //            0   1   2   3   4   5   6   7   8
    //
    // Expected solutions are: "1=a,2=d", "1=b,2=c" and "1=b,2=d"

    // Both labels 1 and 2 will have a single shape each

    IntegerVariable X1 = makeIntVar("X1", 4, 7);
    IntegerVariable Y1 = makeIntVar("Y1", 1, 4);
    IntegerVariable[] p1 = new IntegerVariable[] {X1, Y1};
    GeostObject lab1 =
        new GeostObject(2, 1, constant(1), p1, constant(0), constant(1), constant(1));
    ShiftedBox sb1 = new ShiftedBox(1, new int[] {0, 0}, new int[] {2, 2});

    IntegerVariable X2 = makeIntVar("X2", 0, 4);
    IntegerVariable Y2 = makeIntVar("Y2", 3, 3);
    IntegerVariable[] p2 = new IntegerVariable[] {X2, Y2};
    GeostObject lab2 =
        new GeostObject(2, 2, constant(2), p2, constant(0), constant(1), constant(1));
    ShiftedBox sb2 = new ShiftedBox(2, new int[] {0, 0}, new int[] {4, 2});

    List<GeostObject> gos = new ArrayList<GeostObject>();
    gos.add(lab1);
    gos.add(lab2);
    List<ShiftedBox> SBs = new ArrayList<ShiftedBox>();
    SBs.add(sb1);
    SBs.add(sb2);

    int[] ectrDim = new int[] {0, 1};
    int[] objOfEctr = new int[] {1, 2}; // IDs of labels
    List<IExternalConstraint> ectr = new ArrayList<IExternalConstraint>();
    ectr.add(new NonOverlappingModel(Constants.NON_OVERLAPPING, ectrDim, objOfEctr));

    Model m = new CPModel();
    m.addConstraint(geost(2, gos, SBs, ectr));
    Solver s = new CPSolver();
    System.out.println("Avant 'Solver.read'");
    s.read(m);
    System.out.println("Avant 'Solver.solve'");
    s.solve();
    System.out.println("Apr�s 'Solver.solve'");
  }
}
예제 #5
0
/*
 * User : charles
 * Mail : cprudhom(a)emn.fr
 * Date : 12 mars 2009
 * Since : Choco 2.0.1
 * Update : Choco 2.0.1
 */
public class StrategyTest {

  protected static final Logger LOGGER = ChocoLogging.getTestLogger();

  CPSolver s;
  PatternExample pe;
  static Random random;
  boolean print = false;

  @Before
  public void before() {
    s = new CPSolver();
  }

  private void createModel() {
    pe.buildModel();
    pe.solver = new CPSolver();
    pe.solver.read(pe.model);
    pe.solver.solveAll();
  }

  private void loadQueenModel() {
    pe = new Queen();
    pe.readArgs("-n", "8");
    createModel();
  }

  private void loadMagicSquareModel() {
    pe = new MagicSquare();
    pe.readArgs("-n", "3");
    createModel();
  }

  private void loadGolombRulerModel() {
    pe = new GolombRuler();
    pe.readArgs("-s", "4");
    createModel();
  }

  @After
  public void after() {
    s = null;
    pe = null;
  }

  @Test
  public void testStrategyQ() {
    loadQueenModel();
    for (int i = 0; i < 100; i++) {
      LOGGER.info("seed:" + i);
      random = new Random(i);

      s = new CPSolver();
      s.read(pe.model);
      IntBranchingFactory bf = new IntBranchingFactory();
      IntDomainVar[] vars = s.getIntDecisionVars();

      s.attachGoal(bf.make(random, s, vars));
      checker();
    }
  }

  @Test
  public void testStrategyMS() {
    loadMagicSquareModel();
    for (int i = 0; i < 100; i++) {
      LOGGER.info("seed:" + i);
      random = new Random(i);

      s = new CPSolver();
      s.read(pe.model);
      IntBranchingFactory bf = new IntBranchingFactory();
      IntDomainVar[] vars = s.getIntDecisionVars();

      s.attachGoal(bf.make(random, s, vars));
      checker();
    }
  }

  @Test
  public void testStrategyGR() {
    loadGolombRulerModel();
    for (int i = 0; i < 100; i++) {
      LOGGER.info("seed:" + i);
      random = new Random(i);

      s = new CPSolver();
      s.read(pe.model);
      IntBranchingFactory bf = new IntBranchingFactory();
      IntDomainVar[] vars = s.getIntDecisionVars();

      s.attachGoal(bf.make(random, s, vars));
      checker();
    }
  }

  private void checker() {
    s.solveAll(); // checkSolution enbaled by assertion
    //        s.solve();
    //        if(Boolean.TRUE.equals(s.isFeasible())){
    //            do{
    //                Assert.assertTrue(s.checkSolution());
    //            }while(s.nextSolution());
    //        }
    Assert.assertEquals("feasibility incoherence", pe.solver.isFeasible(), s.isFeasible());
    Assert.assertEquals("nb sol incoherence", pe.solver.getNbSolutions(), s.getNbSolutions());
  }

  @Test
  public void testStrategy1() {
    loadQueenModel();
    s = new CPSolver();
    s.read(pe.model);
    s.attachGoal(new AssignVar(new DomOverWDeg(s), new MidVal()));
    checker();
  }

  @Test
  public void testStrategy2() {
    loadGolombRulerModel();
    s = new CPSolver();
    s.read(pe.model);
    s.attachGoal(new AssignVar(new MaxValueDomain(s), new DecreasingDomain()));
    checker();
  }
}
예제 #6
0
public class TrigoTest {

  protected static final Logger LOGGER = ChocoLogging.getTestLogger();

  @Test
  public void test1() {
    CPSolver s = new CPSolver();
    RealVar alpha = s.createRealVal("alpha", -Math.PI, Math.PI);

    RealExp exp = new RealMinus(s, new RealCos(s, alpha), new RealSin(s, alpha));
    SConstraint c = s.makeEquation(exp, s.cst(0.0));
    LOGGER.info("c = " + c.pretty());
    s.post(s.makeEquation(exp, s.cst(0.0)));

    boolean first = false;
    s.setFirstSolution(first);
    s.generateSearchStrategy();
    s.addGoal(new AssignInterval(new CyclicRealVarSelector(s), new RealIncreasingDomain()));
    s.launch();

    assertTrue("Nb sols", s.getNbSolutions() >= 2);
    assertTrue("Precision", Math.abs(Math.cos(alpha.getInf()) - Math.sin(alpha.getInf())) < 1e-8);
  }

  @Test
  public void test1bis() {
    CPModel m = new CPModel();

    RealVariable alpha = makeRealVar("alpha", -Math.PI, Math.PI);
    Constraint exp = eq(cos(alpha), sin(alpha));
    m.addConstraint(exp);

    CPSolver s = new CPSolver();
    s.read(m);
    LOGGER.info("eq = " + s.getCstr(exp).pretty());

    boolean first = false;
    s.setFirstSolution(first);
    s.generateSearchStrategy();
    s.addGoal(new AssignInterval(new CyclicRealVarSelector(s), new RealIncreasingDomain()));
    s.launch();

    assertTrue(s.getNbSolutions() >= 2);
    assertTrue(
        Math.abs(Math.cos(s.getVar(alpha).getInf()) - Math.sin(s.getVar(alpha).getInf())) < 1e-8);
  }

  @Test
  public void test2() {
    CPSolver s = new CPSolver();
    RealVar alpha = s.createRealVal("alpha", -5.5 * Math.PI, -1.5 * Math.PI);
    RealExp exp = new RealCos(s, alpha);
    s.post(s.makeEquation(exp, s.cst(1.0)));

    boolean first = false;
    s.setFirstSolution(first);
    s.generateSearchStrategy();
    s.addGoal(new AssignInterval(new CyclicRealVarSelector(s), new RealIncreasingDomain()));
    s.launch();

    assertTrue(s.getNbSolutions() >= 2);
  }

  @Test
  public void test2bis() {
    CPModel m = new CPModel();

    RealVariable alpha = makeRealVar("alpha", -5.5 * Math.PI, -1.5 * Math.PI);
    m.addVariable(alpha);
    m.addConstraint(eq(cos(alpha), 1));

    CPSolver s = new CPSolver();
    s.read(m);

    boolean first = false;
    s.setFirstSolution(first);
    s.generateSearchStrategy();
    s.addGoal(new AssignInterval(new CyclicRealVarSelector(s), new RealIncreasingDomain()));
    s.launch();

    assertTrue(s.getNbSolutions() >= 2);
  }
}