@Test
  public void testToCNFDimacsClauses() {
    Formula a = new Var("a");
    Formula b = new Var("b");
    Formula c = new Var("c");

    Formula f = new Formula(a.not());
    assertTrue("!a".equals(f.toString()));

    List<IVecInt> clauses = f.toCNFDimacsClauses();
    assertTrue(clauses.size() == 1);
    IVecInt literals = clauses.get(0);

    // expect {-1} array
    assertTrue(literals.get(0) == -1);

    f = new Formula(b.or(a.not()).or(c));
    assertTrue("b or !a or c".equals(f.toString()));

    clauses = f.toCNFDimacsClauses();
    assertTrue(clauses.size() == 1);
    literals = clauses.get(0);

    // expect {2, -1, 3} array
    assertTrue(literals.get(0) == 2);
    assertTrue(literals.get(1) == -1);
    assertTrue(literals.get(2) == 3);
  }
示例#2
0
  /**
   * ***************************************************************** Return a list of terms that
   * have more than one documentation string.
   */
  public static ArrayList<String> termsWithMultipleDoc(KB kb) {

    Set<String> result = new HashSet();
    Set<String> withDoc = new HashSet();
    ArrayList<Formula> forms = kb.ask("arg", 0, "documentation");
    if (!forms.isEmpty()) {
      boolean isNaN = true;
      Iterator<Formula> it = forms.iterator();
      while (it.hasNext()) {
        Formula f = it.next();
        String term = f.getArgument(1); // Append term and language to make a key.
        isNaN = true;
        try {
          double dval = Double.parseDouble(term);
          isNaN = Double.isNaN(dval);
        } catch (Exception nex) {
        }
        if (isNaN) {
          String key = (term + f.getArgument(2));
          if (withDoc.contains(key)) result.add(term);
          else withDoc.add(key);
        }
        if (result.size() > 99) {
          result.add("limited to 100 results");
          break;
        }
      }
    }
    return new ArrayList(result);
  }
  @Test
  public void testNot() {
    Var a = new Var("a");

    Formula f = (a.not());
    assertTrue("!a".equals(f.toString()));
  }
  @Test
  public void testAnd() {
    Var a = new Var("a");
    Var b = new Var("b");

    Formula f = (a.and(b));
    assertTrue("a and b".equals(f.toString()));
  }
 public ConditionalExpressionUnit(Expression exp, Formula origFormula) {
   greqlEvaluator = origFormula.greqlEvaluator;
   condition = exp;
   trueFormula =
       origFormula.calculateReplacementFormula(condition, new True(greqlEvaluator)).simplify();
   falseFormula =
       origFormula.calculateReplacementFormula(condition, new False(greqlEvaluator)).simplify();
 }
  @Test
  public void testOr() {
    Var a = new Var("a");
    Var b = new Var("b");

    Formula f = (a.or(b));
    assertTrue("a or b".equals(f.toString()));
  }
  @Test
  public void testIsSatisfiedBy_empty() throws ContradictionException, TimeoutException {
    Formula f = Formula.newInstanceforSAT(new Formula()); // emptyFormula

    assertTrue(f.getModels().isEmpty());
    // emptyFormula formula is not satisfiable - not even by an emptyFormula model
    assertFalse(f.isSatisfiedBy(new Model(new int[] {})));
  }
示例#8
0
  public Object value() {
    if (value instanceof Formula) {
      Formula formula = (Formula) value;
      return formula.evaluate();
    }

    return value;
  }
  @Test
  public void testGetOp() {
    Var a = new Var("a");
    Var b = new Var("b");

    Formula f = (a.and(b));
    assertTrue(f.getOp().equals(Formula.BOP.AND));
  }
  @Test
  public void testGetRight() {
    Var a = new Var("a");
    Var b = new Var("b");

    Formula f = (a.and(b));
    assertTrue(f.getRight().equals(b));
  }
示例#11
0
  /** Type checks this function application. */
  public boolean checkTypesAndScope(Model model, Map scope) {
    boolean correct = true;

    Type[] argTypes = new Type[args.length];
    for (int i = 0; i < args.length; ++i) {
      if (args[i] instanceof Term) {
        Term arg = (Term) args[i];
        Term argInScope = arg.getTermInScope(model, scope);
        if (argInScope == null) {
          correct = false;
        } else {
          args[i] = argInScope;
          argTypes[i] = argInScope.getType();
        }
      } else if (args[i] instanceof Formula) {
        Formula arg = (Formula) args[i];
        if (!arg.checkTypesAndScope(model, scope)) {
          correct = false;
        } else {
          args[i] = arg;
          argTypes[i] = BuiltInTypes.BOOLEAN;
        }
      } else if (args[i] instanceof ExplicitSetSpec) {
        argTypes[i] = BuiltInTypes.SET;
        ExplicitSetSpec setDef = (ExplicitSetSpec) args[i];
        correct = setDef.checkTypesAndScope(model, scope);
      } else if (args[i] instanceof ImplicitSetSpec) {
        argTypes[i] = BuiltInTypes.SET;
        ImplicitSetSpec setDef = (ImplicitSetSpec) args[i];
        correct = setDef.checkTypesAndScope(model, scope);
      } else if (args[i] instanceof TupleSetSpec) {
        argTypes[i] = BuiltInTypes.SET;
        TupleSetSpec setDef = (TupleSetSpec) args[i];
        correct = setDef.checkTypesAndScope(model, scope);
      } else if (args[i] instanceof ListSpec) {
        argTypes[i] = BuiltInTypes.REAL_ARRAY;
      } else {
        throw new RuntimeException(
            "don't know how to process ArgSpec of type " + args[i].getClass().getName());
      }
    }

    if (correct && (f == null)) {
      f = model.getApplicableFunc(funcName, argTypes);
      if (f == null) {
        System.err.println(
            getLocation()
                + ": No function named "
                + funcName
                + " is applicable to arguments of types "
                + Arrays.asList(argTypes));
        return false;
      }
    }

    return correct;
  }
  @Test
  public void testIsLeaf() {
    Var a = new Var("a");
    Var b = new Var("b");

    Formula f = (a.and(b));
    assertFalse(f.isLeaf());
    assertTrue(f.getLeft().isLeaf() == true && f.getRight().isLeaf() == true);
  }
示例#13
0
  /**
   * ***************************************************************** Iterating through all
   * formulas, return a proof of an inconsistent or redundant one, if such a thing exists.
   */
  public static String kbConsistencyCheck(KB kb) {

    int timeout = 10;
    int maxAnswers = 1;
    String proof;
    String result = null;

    StringBuffer answer = new StringBuffer();
    KB empty = makeEmptyKB("consistencyCheck");

    System.out.println("=================== Consistency Testing ===================");
    try {
      Formula theQuery = new Formula();
      Collection allFormulas = kb.formulaMap.values();
      Iterator it = allFormulas.iterator();
      while (it.hasNext()) {
        Formula query = (Formula) it.next();
        FormulaPreprocessor fp = new FormulaPreprocessor();
        ArrayList processedQueries =
            fp.preProcess(query, false, kb); // may be multiple because of row vars.
        // System.out.println(" query = " + query);
        // System.out.println(" processedQueries = " + processedQueries);

        String processedQuery = null;
        Iterator q = processedQueries.iterator();

        System.out.println(
            "INFO in Diagnostics.kbConsistencyCheck(): size = " + processedQueries.size());
        while (q.hasNext()) {
          Formula f = (Formula) q.next();
          System.out.println("INFO in Diagnostics.kbConsistencyCheck(): formula = " + f.theFormula);
          processedQuery = f.makeQuantifiersExplicit(false);
          System.out.println(
              "INFO in Diagnostics.kbConsistencyCheck(): processedQuery = " + processedQuery);
          proof = StringUtils.join(empty.ask(processedQuery, timeout, maxAnswers), " ");
          StringBuffer a = new StringBuffer();
          a.append(reportAnswer(kb, proof, query, processedQuery, "Redundancy"));
          //  if (answer.length() != 0) return answer;
          answer.append(a);

          StringBuffer negatedQuery = new StringBuffer();
          negatedQuery.append("(not " + processedQuery + ")");
          proof = StringUtils.join(empty.ask(negatedQuery.toString(), timeout, maxAnswers), " ");
          a.append(reportAnswer(kb, proof, query, negatedQuery.toString(), "Inconsistency"));
          if (a.length() != 0) {
            answer.append(a);
            return answer.toString();
          }
        }
        empty.tell(query.theFormula);
      }
    } catch (Exception ex) {
      return ("Error in Diagnostics.kbConsistencyCheck() while executing query: "
          + ex.getMessage());
    }
    return "No contradictions or redundancies found.";
  }
示例#14
0
 /**
  * Returns the scenario inside a calculated member in the scenario dimension. For example, applied
  * to [Scenario].[1], returns the Scenario object representing scenario #1.
  *
  * @param member Wrapper member
  * @return Wrapped scenario
  */
 static Scenario forMember(final RolapMember member) {
   if (isScenario(member.getHierarchy())) {
     final Formula formula = ((RolapCalculatedMember) member).getFormula();
     final ResolvedFunCall resolvedFunCall = (ResolvedFunCall) formula.getExpression();
     final Calc calc = resolvedFunCall.getFunDef().compileCall(null, null);
     return ((ScenarioCalc) calc).getScenario();
   } else {
     return null;
   }
 }
示例#15
0
 /**
  * {@inheritDoc}
  *
  * @see kodkod.ast.RelationPredicate#toConstraints()
  */
 @Override
 public Formula toConstraints() {
   // relation in domain->range
   final Formula domainConstraint = relation().in(domain.product(range));
   // all v: domain | targetMult v.relation
   final Variable v = Variable.unary("v" + relation().name());
   final Formula funConstraint = v.join(relation()).apply(targetMult).forAll(v.oneOf(domain));
   // relation in domain->range && all v: domain | targetMult v.relation
   return domainConstraint.and(funConstraint);
 }
  @Test
  public void testGetModels() throws ContradictionException, TimeoutException {
    Formula instance = Formula.newInstanceforSAT(new Var("a").and(new Var("b")));

    Set<Model> expResult = new HashSet<Model>();
    expResult.add(new Model(new int[] {1, 2}));

    Set<Model> result = instance.getModels();
    assertEquals(expResult, result);
  }
  @Test
  public void testAnd() {
    Phrase a = new Phrase(new Var("a"));
    Phrase sub = new Phrase(new Var("b").and(new Var("c")));

    // Disjunction of two clauses should result in a new phrase
    Formula f = a.and(sub);
    assertTrue("a and b and c".equals(f.toString()));
    assertTrue(f instanceof Phrase);
  }
  @Test
  public void testGetModels_empty() throws ContradictionException, TimeoutException {
    Formula instance = Formula.newInstanceforSAT(new Formula());

    Set<Model> expResult = new HashSet<Model>();

    Set<Model> result = instance.getModels();
    assertEquals(expResult, result);
    assertTrue(result.isEmpty());
  }
示例#19
0
  /**
   * ***************************************************************** Returns a list of terms, each
   * of which is an instance of some exhaustively decomposed class but is not an instance of any of
   * the subclasses that constitute the exhaustive decomposition. For example, given (instance E A)
   * and (partition A B C D), then E is included in the list of terms to be returned if E is not a
   * instance of B, C, or D.
   */
  public static ArrayList<String> membersNotInAnyPartitionClass(KB kb) {

    ArrayList<String> result = new ArrayList<String>();
    try {
      TreeSet<String> reduce = new TreeSet<String>();
      // Use all partition statements and all
      // exhaustiveDecomposition statements.
      ArrayList<Formula> forms = kb.ask("arg", 0, "partition");
      if (forms == null) forms = new ArrayList<Formula>();
      ArrayList<Formula> forms2 = kb.ask("arg", 0, "exhaustiveDecomposition");
      if (forms2 != null) forms.addAll(forms2);
      boolean go = true;
      Iterator<Formula> it = forms.iterator();
      while (go && it.hasNext()) {
        Formula form = it.next();
        String parent = form.getArgument(1);
        ArrayList<String> partition = form.argumentsToArrayList(2);
        List<String> instances = kb.getTermsViaPredicateSubsumption("instance", 2, parent, 1, true);
        if ((instances != null) && !instances.isEmpty()) {
          boolean isInstanceSubsumed = false;
          boolean isNaN = true;
          String inst = null;
          Iterator<String> it2 = instances.iterator();
          while (go && it2.hasNext()) {
            isInstanceSubsumed = false;
            isNaN = true;
            inst = it2.next();
            try { // For diagnostics, try to avoid treating numbers as bonafide terms.
              double dval = Double.parseDouble(inst);
              isNaN = Double.isNaN(dval);
            } catch (Exception nex) {
            }
            if (isNaN) {
              Iterator<String> it3 = partition.iterator();
              while (it3.hasNext()) {
                String pclass = it3.next();
                if (kb.isInstanceOf(inst, pclass)) {
                  isInstanceSubsumed = true;
                  break;
                }
              }
              if (isInstanceSubsumed) continue;
              else reduce.add(inst);
            }
            if (reduce.size() > 99) go = false;
          }
        }
      }
      result.addAll(reduce);
      if (result.size() > 99) result.add("limited to 100 results");
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }
 private void processLeaf(Component file, Path<FormulaExecutorComponentVisitor.Counters> path) {
   CounterInitializationContext counterContext = new CounterInitializationContextImpl(file);
   for (Formula formula : formulas) {
     Counter counter = formula.createNewCounter();
     counter.initialize(counterContext);
     for (String metricKey : formula.getOutputMetricKeys()) {
       addNewMeasure(file, metricKey, formula, counter);
     }
     aggregateToParent(path, formula, counter);
   }
 }
  @Test
  public void testIsAtomic() {
    Var a = new Var("a");
    Var b = new Var("b");

    assertTrue(a.isAtomic()); // a literal is atomic
    assertTrue(a.not().isAtomic()); // a literal and its negation is atomic

    Formula f = (a.and(b));
    assertFalse(f.isAtomic());
    assertTrue(f.getLeft().isAtomic() == true && f.getRight().isAtomic() == true);
  }
示例#22
0
  @Test
  public void defaultMethod() throws Exception {
    Formula formula =
        new Formula() {
          @Override
          public double calculate(int a) {
            return sqrt(a * 100);
          }
        };

    assert formula.calculate(100) == 100.0;
    assert formula.sqrt(16) == 4.0;
  }
示例#23
0
 /**
  * Copy constructor
  *
  * @param f
  */
 public Formula(Formula f) {
   this();
   for (Clause c : f.getClauses()) {
     Clause temp = new Clause();
     int varSize = c.getVariables().size();
     for (int i = 0; i < varSize; i++) {
       Integer newVar = new Integer(c.getVariables().get(i));
       temp.addVariable(newVar);
     }
     this.clauses.add(temp);
   }
   this.getFinalVars().addAll(f.getFinalVars());
 }
 private void processNotLeaf(
     Component component, Path<FormulaExecutorComponentVisitor.Counters> path) {
   for (Formula formula : formulas) {
     Counter counter = path.current().getCounter(formula);
     // If there were no file under this node, the counter won't be initialized
     if (counter != null) {
       for (String metricKey : formula.getOutputMetricKeys()) {
         addNewMeasure(component, metricKey, formula, counter);
       }
       aggregateToParent(path, formula, counter);
     }
   }
 }
  @Test
  public void testEquals() {
    Var a = new Var("a");
    Var b = new Var("b");

    Formula f = a.and(b);
    Formula g = a.and(b);

    assertFalse(f == g); // two distinct instances
    assertTrue(f.equals(g)); // objects equal

    Formula h = b.and(a);
    assertFalse(f.equals(h)); // logically equivalent but objects not equal
  }
示例#26
0
  public static void main(String[] args) {
    Formula formula1 =
        new Formula() {
          @Override
          public double calculate(int a) {
            return sqrt(a * 100);
          }
        };

    formula1.calculate(100); // 100.0
    formula1.sqrt(-23); // 0.0
    Formula.positive(-4); // 0.0

    //        Formula formula2 = (a) -> sqrt( a * 100);
  }
  @Test
  public void testToString() {
    Formula emptyFormula = new Formula();
    assertTrue(emptyFormula.toString().equals(StringUtils.EMPTY));

    Var a = new Var("a");
    Var b = new Var("b");
    Var c = new Var("c");
    Var d = new Var("d");

    Formula f = (a.and(b)).or(c.and(d));
    assertTrue("(a and b) or (c and d)".equals(f.toString()));

    f = (a.not().or(b)).and(c);
    assertTrue("(!a or b) and c".equals(f.toString()));
  }
 /** Test a null formula */
 @Test
 public void testNullFormula() {
   logger.info("Test null Formula");
   String formula = null;
   Object resObject = Formula.evalFormula(formula);
   Assert.assertNull(resObject);
 }
示例#29
0
  public void testPagingInCollection() throws Exception {
    // create objects in database
    Formula formula = Formula.findByName("HTML TEST");
    Ingredient ingredient = Ingredient.findByName("LECHE");
    for (int x = 0; x <= 12; x++) {
      FormulaIngredient fi = new FormulaIngredient();
      fi.setFormula(formula);
      fi.setIngredient(ingredient);
      XPersistence.getManager().persist(fi);
    }
    XPersistence.commit();

    //
    execute("Mode.detailAndFirst");
    assertValue("name", "HTML TEST");
    assertCollectionRowCount("ingredients", 10);
    checkRowCollection("ingredients", 0);
    execute("List.goNextPage", "collection=ingredients");
    execute("List.goPreviousPage", "collection=ingredients");
    assertRowCollectionChecked("ingredients", 0);

    // remove objects from database
    String sentencia = " DELETE FROM FormulaIngredient WHERE ingredient.oid = :ingredient ";
    Query query = XPersistence.getManager().createQuery(sentencia);
    query.setParameter("ingredient", ingredient.getOid());
    query.executeUpdate();
    XPersistence.commit();
  }
  @Override
  public String toString() {
    String str = "";
    for (int i = 0; i < FormulaType.values().length; i++)
      if (leftFormulas[i] != null) str += leftFormulas[i].toString();

    return str + "==>\n" + (rightSide == null ? "" : rightSide.toString());
  }