예제 #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
/**
 * the core class that allow to represent a graph and a set of properties that can be dynamically
 * maintained.
 */
public class StoredBitSetGraph {

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

  /** list of graph properties that can be maintained for a given graph */
  public static enum Maintain {
    TRANSITIVE_CLOSURE,
    TRANSITIVE_REDUCTION,
    CONNECTED_COMP,
    NONE
  }

  /** Choco solver embedding the tree constraint */
  protected Solver solver;

  /** list of graph properties to maintain for the graph */
  protected List<Maintain> params;

  /** total number of nodes involved in the graph */
  protected int nbNodes;

  /** reference idx in a depth first search */
  protected int idx;

  /** resulting labelling of the nodes involved in the graph according to a depth first search */
  protected int[] dfsTree;

  /** backtrackable bitset matrix representing the graph */
  protected IStateBitSet[] graph;

  /** backtrackable bitset matrix representing the reverse graph */
  protected IStateBitSet[] revGraph;

  /** backtrackable bitset matrix representing the transitive closure of the graph */
  protected IStateBitSet[] tcGraph;

  /** backtrackable bitset matrix representing the reverse transitive closure of the graph */
  protected IStateBitSet[] revTcGraph;

  protected boolean needUpdate;

  /** backtrackable bitset matrix representing the transitive reduction of the graph */
  protected IStateBitSet[] trGraph;

  /** backtrackable bitset matrix representing the reverse transitive reduction of the graph */
  protected IStateBitSet[] revTrGraph;

  /** backtrackable bitset that store the source nodes of the graph */
  protected IStateBitSet srcNodes;

  /** backtrackable bitset that store the sink nodes of the graph */
  protected IStateBitSet sinkNodes;

  /** connected component structure associated with the graph */
  protected ConnectedComponents cc;

  protected Vector<IStateBitSet> setCC;
  protected IStateBitSet[] vertFromNumCC;
  protected IStateBitSet[] numFromVertCC;

  /** backtrackable integer recording the current number of connected components */
  protected IStateInt nbCC;

  /** boolean for debug and show a trace of the execution */
  protected boolean affiche;

  public StoredBitSetGraph(
      Solver solver, IStateBitSet[] graph, List<Maintain> params, boolean affiche) {
    this.solver = solver;
    this.graph = graph;
    this.params = params;
    this.nbNodes = graph.length;
    this.affiche = affiche;
    this.idx = 0;
    this.dfsTree = new int[nbNodes];
    for (int k = 0; k < nbNodes; k++) dfsTree[k] = -1;
    // initialize the set of source and sink nodes of the graph
    this.srcNodes = solver.getEnvironment().makeBitSet(nbNodes);
    this.sinkNodes = solver.getEnvironment().makeBitSet(nbNodes);
    // initialize the required graph associated with the initial one
    this.revGraph = new IStateBitSet[nbNodes];
    if (params.contains(Maintain.TRANSITIVE_CLOSURE)) {
      this.tcGraph = new IStateBitSet[nbNodes];
      this.revTcGraph = new IStateBitSet[nbNodes];
    } else {
      this.tcGraph = null;
      this.revTcGraph = null;
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) {
      this.trGraph = new IStateBitSet[nbNodes];
      this.revTrGraph = new IStateBitSet[nbNodes];
    } else {
      this.trGraph = null;
      this.revTrGraph = null;
    }
    // initialize internal data structure of the graphs
    initAllGraphs();
    createRevGraph();
    updateSpecialNodes();
    // compute required properties
    if (params.contains(Maintain.TRANSITIVE_CLOSURE)) computeTCfromScratch();
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    if (params.contains(Maintain.CONNECTED_COMP)) {
      initCCstruct();
      computeCCfromScratch();
    }
  }

  private void initCCstruct() {
    this.setCC = new Vector<IStateBitSet>(this.nbNodes);
    this.vertFromNumCC = new IStateBitSet[this.nbNodes];
    this.numFromVertCC = new IStateBitSet[this.nbNodes];
    for (int i = 0; i < this.nbNodes; i++) {
      this.setCC.add(this.solver.getEnvironment().makeBitSet(this.nbNodes));
      this.vertFromNumCC[i] = this.solver.getEnvironment().makeBitSet(this.nbNodes);
      this.numFromVertCC[i] = this.solver.getEnvironment().makeBitSet(this.nbNodes);
    }
    this.nbCC = this.solver.getEnvironment().makeInt(0);
    this.cc = new ConnectedComponents(this.solver, this.nbNodes, this.graph, this.setCC);
  }

  private void initAllGraphs() {
    for (int i = 0; i < nbNodes; i++) {
      this.revGraph[i] = solver.getEnvironment().makeBitSet(nbNodes);
      if (params.contains(Maintain.TRANSITIVE_CLOSURE)) {
        this.tcGraph[i] = solver.getEnvironment().makeBitSet(nbNodes);
        this.revTcGraph[i] = solver.getEnvironment().makeBitSet(nbNodes);
      }
      if (params.contains(Maintain.TRANSITIVE_REDUCTION)) {
        this.trGraph[i] = solver.getEnvironment().makeBitSet(nbNodes);
        this.revTrGraph[i] = solver.getEnvironment().makeBitSet(nbNodes);
      }
    }
  }

  private void createRevGraph() {
    for (int i = 0; i < nbNodes; i++) {
      for (int j = graph[i].nextSetBit(0); j >= 0; j = graph[i].nextSetBit(j + 1)) {
        revGraph[j].set(i, true);
      }
    }
  }

  private void computeTCfromScratch() {
    razTC();
    for (int i = 0; i < nbNodes; i++) {
      for (int j = graph[i].nextSetBit(0); j >= 0; j = graph[i].nextSetBit(j + 1)) {
        if (i != j) {
          tcGraph[i].set(j, true);
          revTcGraph[j].set(i, true);
        }
      }
    }
    for (int i = 0; i < nbNodes; i++) {
      for (int j = 0; j < nbNodes; j++) {
        if (tcGraph[j].get(i) && j != i) {
          for (int k = tcGraph[i].nextSetBit(0); k >= 0; k = tcGraph[i].nextSetBit(k + 1)) {
            tcGraph[j].set(k, true);
            revTcGraph[k].set(j, true);
          }
        }
      }
    }
  }

  private void addIncreTC(int i, int j) {
    if (i != j) {
      // descendants
      if (!tcGraph[i].get(j)) {
        tcGraph[i].or(tcGraph[j]);
        tcGraph[i].set(j, true);
        for (int k = revTcGraph[i].nextSetBit(0); k >= 0; k = revTcGraph[i].nextSetBit(k + 1)) {
          if (!tcGraph[k].get(j)) {
            tcGraph[k].or(tcGraph[j]);
            tcGraph[k].set(j, true);
          }
        }
        // ancestors
        revTcGraph[j].or(revTcGraph[i]);
        revTcGraph[j].set(i, true);
        for (int k = tcGraph[j].nextSetBit(0); k >= 0; k = tcGraph[j].nextSetBit(k + 1)) {
          if (!tcGraph[i].get(k)) {
            revTcGraph[k].or(revTcGraph[i]);
            revTcGraph[k].set(i, true);
          }
        }
      }
    }
  }

  private void remIncreTC(int i, int j) {
    if (i != j) {
      // reachable nodes from node i in the graph
      IStateBitSet tempDesc = getDesc(i, j, graph);
      if (needUpdate) {
        tcGraph[i] = tempDesc;
        // compute all the reachble nodes from each ancestor of i in graph
        IStateBitSet updateAnc = solver.getEnvironment().makeBitSet(nbNodes);
        for (int k = revTcGraph[i].nextSetBit(0); k >= 0; k = revTcGraph[i].nextSetBit(k + 1)) {
          if (!updateAnc.get(k)) {
            tempDesc = getDesc(k, j, graph);
            if (!needUpdate) updateAnc.or(revTcGraph[k]);
            else tcGraph[k] = tempDesc;
          }
        }
        // compute the nodes reachable from j in the reverse graph
        revTcGraph[j] = getDesc(j, i, revGraph);
        // compute all the nodes reachable from each descendant of j in the reverse graph
        IStateBitSet updateDesc = solver.getEnvironment().makeBitSet(nbNodes);
        for (int k = tcGraph[j].nextSetBit(0); k >= 0; k = tcGraph[j].nextSetBit(k + 1)) {
          if (!updateDesc.get(k)) {
            tempDesc = getDesc(k, i, revGraph);
            if (!needUpdate) updateDesc.or(tcGraph[k]);
            else revTcGraph[k] = tempDesc;
          }
        }
      }
    }
  }

  private IStateBitSet getDesc(int i, int j, IStateBitSet[] graph) {
    // retrieve the set of reachable nodes from i in the graph
    needUpdate = true;
    Stack<Integer> stack = new Stack<Integer>();
    IStateBitSet reached = solver.getEnvironment().makeBitSet(nbNodes);
    stack.push(i);
    while (!stack.isEmpty()) {
      int a = stack.pop();
      for (int b = graph[a].nextSetBit(0); b >= 0; b = graph[a].nextSetBit(b + 1)) {
        if (!stack.contains(b) && !reached.get(b)) {
          reached.set(b, true);
          if (b == j) {
            needUpdate = false;
            return reached;
          } else stack.push(b);
        }
      }
    }
    return reached;
  }

  private void razTC() {
    for (int i = 0; i < nbNodes; i++) {
      for (int j = tcGraph[i].nextSetBit(0); j >= 0; j = tcGraph[i].nextSetBit(j + 1)) {
        tcGraph[i].set(j, false);
        revTcGraph[j].set(i, false);
      }
    }
  }

  private void computeTRfromScratch() {
    razTR();
    for (int i = 0; i < nbNodes; i++) {
      for (int j = graph[i].nextSetBit(0); j >= 0; j = graph[i].nextSetBit(j + 1)) {
        trGraph[i].set(j, true);
        revTrGraph[j].set(i, true);
      }
    }
    for (int i = 0; i < nbNodes; i++) {
      int[][] num = new int[nbNodes][2];
      for (int j = 0; j < nbNodes; j++) {
        num[j][0] = -1;
        num[j][1] = -1;
      }
      idx = 0;
      for (int k = 0; k < nbNodes; k++) dfsTree[k] = -1;
      dfs(i, i, num);
    }
  }

  private void razTR() {
    for (int i = 0; i < nbNodes; i++) {
      for (int j = trGraph[i].nextSetBit(0); j >= 0; j = trGraph[i].nextSetBit(j + 1)) {
        trGraph[i].set(j, false);
        revTrGraph[j].set(i, false);
      }
    }
  }

  private int[][] dfs(int root, int u, int[][] num) {
    num[u][0] = idx++;
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (num[v][0] == -1) {
        dfsTree[v] = u;
        num = dfs(root, v, num);
      } else {
        if (num[u][1] == -1 && num[u][0] > num[v][0]) {
          int w = dfsTree[v];
          if (w == root) { // (w,v) is a transitive arc in the dfs tree
            trGraph[w].set(v, false);
            revTrGraph[v].set(w, false);
          }
        }
        // (u,v) is a transitive arc in a specific branch of the dfs tree
        if (num[v][1] != -1 && num[u][0] < num[v][0]) {
          trGraph[u].set(v, false);
          revTrGraph[v].set(u, false);
        }
      }
    }
    num[u][1] = idx++;
    return num;
  }

  private void computeCCfromScratch() {
    this.cc.getConnectedComponents(affiche);
    if (affiche) showCC();
    // record the connected components of the graph
    for (int i = 0; i < nbNodes; i++) this.numFromVertCC[i].clear();
    for (int i = 0; i < this.setCC.size(); i++) {
      IStateBitSet contain = this.setCC.elementAt(i);
      this.vertFromNumCC[i].clear();
      for (int j = contain.nextSetBit(0); j >= 0; j = contain.nextSetBit(j + 1)) {
        this.vertFromNumCC[i].set(j, true);
        this.numFromVertCC[j].set(i, true);
      }
    }
    this.nbCC.set(this.cc.getNbCC());
  }

  private void showCC() {
    for (int i = 0; i < setCC.size(); i++) {
      IStateBitSet contain = setCC.elementAt(i);
      LOGGER.info("cc(" + i + ") = " + contain.toString());
    }
    LOGGER.info("*-*-*-*-*-*-*-*-*-*-*-*-*");
  }

  //////////////////////////////////////////////////////////////////////////////////////////
  ////////////////// Algorithmes pour ajouter/retirer un arc dans graph ////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////

  /**
   * add the arc (u,v) in the graph view structure (required properties are dynamically updated)
   *
   * @param u index of a node
   * @param v index of a node
   */
  public void addArc(int u, int v) {
    // add arc
    graph[u].set(v, true);
    revGraph[v].set(u, true);
    // update properties
    if (params.contains(Maintain.TRANSITIVE_CLOSURE)) addIncreTC(u, v);
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    // update sink and source informations
    updateSpecialNodes(u, v);
    // update connected components
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * remove the arc (u,v) from the graph view structure (required properties are dynamically
   * updated)
   *
   * @param u index of a node
   * @param v index of a node
   */
  public void remArc(int u, int v) {
    // remove arc
    graph[u].set(v, false);
    revGraph[v].set(u, false);
    // update properties
    if (params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, v);
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    // update sink and source informations
    updateSpecialNodes(u, v);
    // update connected components
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * remove all the successors of node u from the graph view structure (required properties are
   * dynamically updated)
   *
   * @param u index of a node
   */
  public void remAllSucc(int u) {
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      graph[u].set(v, false);
      revGraph[v].set(u, false);
    }
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, v);
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    updateSpecialNodes();
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * remove all the successors of node u, excepted node v, from the graph view structure (required
   * properties are dynamically updated)
   *
   * @param u index of a node
   * @param v index of a node
   */
  public void remAllExcepted(int u, int v) {
    // remove all the outgoing arcs excepted (u,v)
    for (int w = graph[u].nextSetBit(0); w >= 0; w = graph[u].nextSetBit(w + 1)) {
      if (w != v) {
        graph[u].set(w, false);
        revGraph[w].set(u, false);
      }
    }
    for (int w = graph[u].nextSetBit(0); w >= 0; w = graph[u].nextSetBit(w + 1)) {
      if (w != v && params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, w);
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    updateSpecialNodes();
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * remove all the successors of node u that have an index below to idx (required properties are
   * dynamically updated)
   *
   * @param u index of a node
   * @param idx integer value
   */
  public void remAllLowerIdx(int u, int idx) {
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (v < idx) {
        graph[u].set(v, false);
        revGraph[v].set(u, false);
      }
    }
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (v < idx && params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, v);
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    updateSpecialNodes();
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * remove all the successors of node u that have an index higher than idx (required properties are
   * dynamically updated)
   *
   * @param u index of a node
   * @param idx integer value
   */
  public void remAllGreaterIdx(int u, int idx) {
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (v > idx) {
        graph[u].set(v, false);
        revGraph[v].set(u, false);
      }
    }
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (v > idx && params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, v);
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    updateSpecialNodes();
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * remove all the successors of node u that have an index below to inf and higher than sup
   * (required properties are dynamically updated)
   *
   * @param u index of a node
   * @param inf integer value
   * @param sup integer value
   */
  public void remAllIdx(int u, int inf, int sup) {
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (v < inf || v > sup) {
        graph[u].set(v, false);
        revGraph[v].set(u, false);
      }
    }
    for (int v = graph[u].nextSetBit(0); v >= 0; v = graph[u].nextSetBit(v + 1)) {
      if (v < inf || v > sup) {
        if (params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, v);
      }
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    updateSpecialNodes();
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  /**
   * all the arc (u,v), such that v belongs to the set depicted by the iterator, are removed
   *
   * @param u index of a node
   * @param deltaDomain an iterator over the removed indices
   */
  public void remAllNodes(int u, DisposableIntIterator deltaDomain) {
    while (deltaDomain.hasNext()) {
      int v = deltaDomain.next();
      graph[u].set(v, false);
      revGraph[v].set(u, false);
    }
    deltaDomain.dispose();
    while (deltaDomain.hasNext()) {
      int v = deltaDomain.next();
      if (params.contains(Maintain.TRANSITIVE_CLOSURE)) remIncreTC(u, v);
    }
    deltaDomain.dispose();
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) computeTRfromScratch();
    updateSpecialNodes();
    if (params.contains(Maintain.CONNECTED_COMP)) computeCCfromScratch();
  }

  private void updateSpecialNodes(int u, int v) {
    if (graph[u].cardinality() == 0) sinkNodes.set(u, true);
    else sinkNodes.set(u, false);
    if (revGraph[v].cardinality() == 0) srcNodes.set(v, true);
    else srcNodes.set(v, false);
  }

  private void updateSpecialNodes() {
    for (int i = 0; i < nbNodes; i++) {
      if (graph[i].cardinality() == 0) sinkNodes.set(i, true);
      else sinkNodes.set(i, false);
      if (revGraph[i].cardinality() == 0) srcNodes.set(i, true);
      else srcNodes.set(i, false);
    }
  }

  //////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////// Accesseurs pour la structure ///////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////

  public int getGraphSize() {
    return nbNodes;
  }

  public IStateBitSet getSuccessors(int i) {
    return graph[i];
  }

  public IStateBitSet getPredecessors(int i) {
    return revGraph[i];
  }

  public IStateBitSet getDescendants(int i) {
    return tcGraph[i];
  }

  public IStateBitSet getAncestors(int i) {
    return revTcGraph[i];
  }

  public IStateBitSet[] getGraph() {
    return graph;
  }

  public void setGraph(IStateBitSet[] newGraph) {
    razGraph();
    for (int i = 0; i < nbNodes; i++) {
      for (int j = newGraph[i].nextSetBit(0); j >= 0; j = newGraph[i].nextSetBit(j + 1)) {
        graph[i].set(j, true);
      }
    }
  }

  public void razGraph() {
    for (int i = 0; i < nbNodes; i++) {
      for (int j = graph[i].nextSetBit(0); j >= 0; j = graph[i].nextSetBit(j + 1)) {
        graph[i].set(j, false);
      }
    }
  }

  public IStateBitSet[] getRevGraph() {
    return revGraph;
  }

  public IStateBitSet[] getTcGraph() {
    return tcGraph;
  }

  public IStateBitSet[] getRevTcGraph() {
    return revTcGraph;
  }

  public IStateBitSet[] getTrGraph() {
    return trGraph;
  }

  public IStateBitSet[] getRevTrGraph() {
    return revTrGraph;
  }

  public IStateBitSet getSrcNodes() {
    return srcNodes;
  }

  public IStateBitSet getSinkNodes() {
    return sinkNodes;
  }

  public Vector<IStateBitSet> getSetCC() {
    return setCC;
  }

  public IStateBitSet[] getVertFromNumCC() {
    return vertFromNumCC;
  }

  public IStateBitSet[] getNumFromVertCC() {
    return numFromVertCC;
  }

  public IStateInt getNbCC() {
    return nbCC;
  }

  public String showDesc(int i, String type) {
    StringBuilder s = new StringBuilder("D_" + type + "[" + i + "] = ");
    for (int j = tcGraph[i].nextSetBit(0); j >= 0; j = tcGraph[i].nextSetBit(j + 1)) {
      s.append(j).append(" ");
    }
    return s.toString();
  }

  public void showAllDesc(String type) {
    for (int i = 0; i < nbNodes; i++) {
      StringBuffer st = new StringBuffer();
      st.append(type).append("").append(i).append(":=");
      for (int j = tcGraph[i].nextSetBit(0); j >= 0; j = tcGraph[i].nextSetBit(j + 1)) {
        st.append(" ").append(j);
      }
      LOGGER.info(st.toString());
    }
  }

  public void showGraph(String type) {
    for (int i = 0; i < nbNodes; i++) {
      StringBuffer st = new StringBuffer();
      st.append(type).append("").append(i).append(":=");
      for (int j = graph[i].nextSetBit(0); j >= 0; j = graph[i].nextSetBit(j + 1)) {
        st.append(MessageFormat.format(" {0}", j));
      }
      LOGGER.info(st.toString());
    }
  }

  public void affiche() {
    LOGGER.info("************ Graph **************");
    StringBuffer st = new StringBuffer();
    for (int i = 0; i < nbNodes; i++) {
      st.append("graph[").append(i).append("] = ");
      for (int j = graph[i].nextSetBit(0); j >= 0; j = graph[i].nextSetBit(j + 1))
        st.append(j).append(" ");
    }
    LOGGER.info(st.toString());
    LOGGER.info("*********************************");
    if (params.contains(Maintain.TRANSITIVE_CLOSURE)) {
      LOGGER.info("************ TC Graph **************");
      st = new StringBuffer();
      for (int i = 0; i < nbNodes; i++) {
        st.append("TCgraph[").append(i).append("] = ");
        for (int j = tcGraph[i].nextSetBit(0); j >= 0; j = tcGraph[i].nextSetBit(j + 1))
          st.append(j).append(" ");
      }
      LOGGER.info(st.toString());
      LOGGER.info("*********************************");
    }
    if (params.contains(Maintain.TRANSITIVE_REDUCTION)) {
      LOGGER.info("************ TR Graph **************");
      st = new StringBuffer();
      for (int i = 0; i < nbNodes; i++) {
        st.append("TRgraph[").append(i).append("] = ");
        for (int j = trGraph[i].nextSetBit(0); j >= 0; j = trGraph[i].nextSetBit(j + 1))
          st.append(j).append(" ");
      }
      LOGGER.info(st.toString());
      LOGGER.info("*********************************");
    }
  }
}
예제 #4
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);
  }
}
예제 #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 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'");
  }
}
예제 #7
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);
  }
}
예제 #8
0
 /**
  * @param message
  * @param cause
  */
 public SolverException(String message, Throwable cause) {
   super(message, cause);
   ChocoLogging.flushLogs();
 }
예제 #9
0
 /** @param cause */
 public SolverException(Throwable cause) {
   super(cause);
   ChocoLogging.flushLogs();
 }
예제 #10
0
 /** @param message */
 public SolverException(String message) {
   super(message);
   ChocoLogging.flushLogs();
 }
 public void setVerbosity(Verbosity verbosity) {
   ChocoLogging.toVerbose();
   ChocoLogging.setVerbosity(verbosity);
 }