From a Propositional Formula to a Propositional Formula
    with non-propositional subformulas replaced with a "freezed" atomic formula.
350454
def _transform_delta(f:Formula, formula2AtomicFormula):
    """"""
    t = type(f)
    if t == PLNot:
        return PLNot(_transform_delta(f, formula2AtomicFormula))
    # elif isinstance(f, PLBinaryOperator): #PLAnd, PLOr, PLImplies, PLEquivalence
    elif t == PLAnd or t == PLOr or t == PLImplies or t == PLEquivalence:
        return t([_transform_delta(subf, formula2AtomicFormula) for subf in f.formulas])
    elif t == PLTrue or t == PLFalse:
        return f
    else:
        return formula2AtomicFormula[f]
49173
def has_same_sumformula(self, other):
        
        same_atoms = True
        for atom in set(self['atom']):
            own_atom_number = len(self[self['atom'] == atom])
            other_atom_number = len(other[other['atom'] == atom])
            same_atoms = (own_atom_number == other_atom_number)
            if not same_atoms:
                break
        return same_atoms
994813
def fermionic_constraints(a):
    
    substitutions = {}
    for i, ai in enumerate(a):
        substitutions[ai ** 2] = 0
        substitutions[Dagger(ai) ** 2] = 0
        substitutions[ai * Dagger(ai)] = 1.0 - Dagger(ai) * ai
        for aj in a[i+1:]:
            # substitutions[ai*Dagger(aj)] = -Dagger(ai)*aj
            substitutions[ai*Dagger(aj)] = -Dagger(aj)*ai
            substitutions[Dagger(ai)*aj] = -aj*Dagger(ai)
            substitutions[ai*aj] = -aj*ai
            substitutions[Dagger(ai) * Dagger(aj)] = - Dagger(aj) * Dagger(ai)

    return substitutions
297489
private Collection<CQIE> rewriteCC(QueryConnectedComponent cc, Function headAtom,  Multimap<Predicate, CQIE> edgeDP) {
		
		List<CQIE> outputRules = new LinkedList<>();	

		TreeWitnessSet tws = TreeWitnessSet.getTreeWitnesses(cc, reasoner, generators, immutabilityTools);

		if (cc.hasNoFreeTerms()) {  
			if (!cc.isDegenerate() || cc.getLoop() != null) 
				for (Function a : getAtomsForGenerators(tws.getGeneratorsOfDetachedCC(), getFreshVariable())) {
					outputRules.add(datalogFactory.getCQIE(headAtom, a));
				}
		}

		// COMPUTE AND STORE TREE WITNESS FORMULAS
		for (TreeWitness tw : tws.getTWs()) {
			log.debug("TREE WITNESS: {}", tw);		
			List<Function> twf = new LinkedList<>();
			
			// equality atoms
			Iterator<Term> i = tw.getRoots().iterator();
			Term r0 = i.next();
			while (i.hasNext()) 
				twf.add(termFactory.getFunctionEQ(i.next(), r0));
			
			// root atoms
			for (Function a : tw.getRootAtoms()) {
				if (!(a.getFunctionSymbol() instanceof TriplePredicate))
					throw new MinorOntopInternalBugException("A triple atom was expected: " + a);

				boolean isClass = ((TriplePredicate) a.getFunctionSymbol()).getClassIRI(
						a.getTerms().stream()
								.map(immutabilityTools::convertIntoImmutableTerm)
								.collect(ImmutableCollectors.toList()))
						.isPresent();

				twf.add(isClass
						? atomFactory.getMutableTripleAtom(r0, a.getTerm(1), a.getTerm(2))
						: atomFactory.getMutableTripleAtom(r0, a.getTerm(1), r0));
			}
			
			List<Function> genAtoms = getAtomsForGenerators(tw.getGenerators(), r0);			
			boolean subsumes = false;
//			for (Function a : genAtoms) 				
//				if (twf.subsumes(a)) {
//					subsumes = true;
//					log.debug("TWF {} SUBSUMES {}", twf.getAllAtoms(), a);
//					break;
//				}

			List<List<Function>> twfs = new ArrayList<>(subsumes ? 1 : genAtoms.size());
//			if (!subsumes) {
				for (Function a : genAtoms) {				
					LinkedList<Function> twfa = new LinkedList<>(twf);
					twfa.add(a); // 
					twfs.add(twfa);
				}
//			}
//			else
//				twfs.add(twf.getAllAtoms());
			
			tw.setFormula(twfs);
		}

		final String headURI = headAtom.getFunctionSymbol().getName();
		if (!cc.isDegenerate()) {
			if (tws.hasConflicts()) { 
				// there are conflicting tree witnesses
				// use compact exponential rewriting by enumerating all compatible subsets of tree witnesses
				CompatibleTreeWitnessSetIterator iterator = tws.getIterator();
				while (iterator.hasNext()) {
					Collection<TreeWitness> compatibleTWs = iterator.next();
					log.debug("COMPATIBLE: {}", compatibleTWs);
					LinkedList<Function> mainbody = new LinkedList<Function>(); 
					
					for (Edge edge : cc.getEdges()) {
						boolean contained = false;
						for (TreeWitness tw : compatibleTWs)
							if (tw.getDomain().contains(edge.getTerm0()) && tw.getDomain().contains(edge.getTerm1())) {
								contained = true;
								log.debug("EDGE {} COVERED BY {}", edge, tw);
								break;
							}
						if (!contained) {
							log.debug("EDGE {} NOT COVERED BY ANY TW",  edge);
							mainbody.addAll(edge.getAtoms());
						}
					}
					for (TreeWitness tw : compatibleTWs) {
						Function twAtom = getHeadAtom(headURI, "_TW_" + (edgeDP.size() + 1), cc.getVariables());
						mainbody.add(twAtom);				
						for (List<Function> twfa : tw.getFormula())
							edgeDP.put(twAtom.getFunctionSymbol(), datalogFactory.getCQIE(twAtom, twfa));
					}	
					mainbody.addAll(cc.getNonDLAtoms());					
					outputRules.add(datalogFactory.getCQIE(headAtom, mainbody));
				}
			}
			else {
				// no conflicting tree witnesses
				// use polynomial tree witness rewriting by treating each edge independently 
				LinkedList<Function> mainbody = new LinkedList<>();
				for (Edge edge : cc.getEdges()) {
					log.debug("EDGE {}", edge);
					
					Function edgeAtom = null;
					for (TreeWitness tw : tws.getTWs())
						if (tw.getDomain().contains(edge.getTerm0()) && tw.getDomain().contains(edge.getTerm1())) {
							if (edgeAtom == null) {
								//IRI atomURI = edge.getBAtoms().iterator().next().getIRI().getName();
								edgeAtom = getHeadAtom(headURI, 
										"_EDGE_" + (edgeDP.size() + 1) /*+ "_" + atomURI.getRawFragment()*/, cc.getVariables());
								mainbody.add(edgeAtom);				
								
								LinkedList<Function> edgeAtoms = new LinkedList<>();
								edgeAtoms.addAll(edge.getAtoms());
								edgeDP.put(edgeAtom.getFunctionSymbol(), datalogFactory.getCQIE(edgeAtom, edgeAtoms));
							}
							
							for (List<Function> twfa : tw.getFormula())
								edgeDP.put(edgeAtom.getFunctionSymbol(), datalogFactory.getCQIE(edgeAtom, twfa));
						}
					
					if (edgeAtom == null) // no tree witnesses -- direct insertion into the main body
						mainbody.addAll(edge.getAtoms());
				}
				mainbody.addAll(cc.getNonDLAtoms());
				outputRules.add(datalogFactory.getCQIE(headAtom, mainbody));
			}
		}
		else {
			// degenerate connected component
			LinkedList<Function> loopbody = new LinkedList<>();
			Loop loop = cc.getLoop();
			log.debug("LOOP {}", loop);
			if (loop != null)
				loopbody.addAll(loop.getAtoms());
			loopbody.addAll(cc.getNonDLAtoms());
			outputRules.add(datalogFactory.getCQIE(headAtom, loopbody));
		}
		return outputRules;
	}
957029
private void addClause(final Formula formula, int weight) {
    this.result = UNDEF;
    final LNGIntVector clauseVec = new LNGIntVector((int) formula.numberOfAtoms());
    for (Literal lit : formula.literals()) {
      Integer index = this.var2index.get(lit.variable());
      if (index == null) {
        index = this.solver.newLiteral(false) >> 1;
        this.var2index.put(lit.variable(), index);
        this.index2var.put(index, lit.variable());
      }
      int litNum = lit.phase() ? index * 2 : (index * 2) ^ 1;
      clauseVec.push(litNum);
    }
    if (weight == -1) {
      this.solver.addHardClause(clauseVec);
    } else {
      this.solver.setCurrentWeight(weight);
      this.solver.updateSumWeights(weight);
      this.solver.addSoftClause(weight, clauseVec);
    }
  }
431892
private Set<Inclusion> transformAxiom(final Set<? extends Axiom> axioms) {
        Set<Inclusion> res = new HashSet<Inclusion>();
        
        for(Axiom aa : axioms) {
            if(aa instanceof ConceptInclusion) {
                ConceptInclusion ci = (ConceptInclusion)aa;
                Concept lhs = ci.getLhs();
                Concept rhs = ci.getRhs();
                res.add(new GCI(transformConcept(lhs), transformConcept(rhs)));
            } else if(aa instanceof RoleInclusion) {
                RoleInclusion ri = (RoleInclusion)aa;
                Role[] lh = ri.getLhs();
                NamedRole[] lhs = new NamedRole[lh.length];
                for(int i = 0; i < lh.length; i++) {
                    lhs[i] = (NamedRole) lh[i];
                }
                NamedRole rhs = (NamedRole) ri.getRhs();
                int[] lhsInt = new int[lhs.length];
                for(int i = 0; i < lhsInt.length; i++) {
                    lhsInt[i] = factory.getRole(lhs[i].getId());
                }
                res.add(new RI(lhsInt, factory.getRole(rhs.getId())));
            } else if (aa instanceof FunctionalFeature) {
            	FunctionalFeature ff = (FunctionalFeature) aa;
            	int featureInt = factory.getFeature(((NamedFeature) ff.getFeature()).getId());
            	functionalFeatures.add(featureInt);
            } else {
            	throw new InternalError("Unknown Axiom type discovered: " + aa);
            }
        }
        
        return res;
    }
145837
public Formula formula(final FormulaFactory f) {
    if (this.operator != FType.AND && this.operator != FType.OR)
      throw new IllegalStateException("Illegal operator for formula list formula construction: " + this.operator);
    if (this.formula == null) {
      if (this.operator == FType.AND)
        this.formula = f.and(this.formulas);
      else
        this.formula = f.or(this.formulas);
    }
    return this.formula;
  }
1094275
private void processConjunctionExpression(List<TerminalNode> conjunctions) {
    Predicate conjunctionReuse;

    for (int i = conjunctions.size() - 1; i >= 0; i--) {
      Predicate rhs = currentPredicates.removeLast();
      Predicate lhs = currentPredicates.removeLast();

      switch (conjunctions.get(i).getText().toLowerCase()) {
        case "and":
          conjunctionReuse = new And(lhs, rhs);
          break;
        case "or":
          conjunctionReuse = new Or(lhs, rhs);
          break;
        default:
          conjunctionReuse = new Xor(lhs, rhs);
          break;
      }
      currentPredicates.add(conjunctionReuse);
    }
  }
1184323
private Formula constructClause(final LinkedHashSet<Literal> literals) {
    if (literals.isEmpty())
      return this.falsum();
    if (literals.size() == 1)
      return literals.iterator().next();
    Map<LinkedHashSet<? extends Formula>, Or> opOrMap = this.orsN;
    switch (literals.size()) {
      case 2:
        opOrMap = this.ors2;
        break;
      case 3:
        opOrMap = this.ors3;
        break;
      case 4:
        opOrMap = this.ors4;
        break;
      default:
        break;
    }
    Or tempOr = opOrMap.get(literals);
    if (tempOr != null)
      return tempOr;
    tempOr = new Or(literals, this, true);
    opOrMap.put(literals, tempOr);
    return tempOr;
  }
1021335
private Formula constructAnd(final LinkedHashSet<? extends Formula> operands) {
    And tempAnd = null;
    Map<LinkedHashSet<? extends Formula>, And> opAndMap = this.andsN;
    if (operands.size() > 1) {
      switch (operands.size()) {
        case 2:
          opAndMap = this.ands2;
          break;
        case 3:
          opAndMap = this.ands3;
          break;
        case 4:
          opAndMap = this.ands4;
          break;
        default:
          break;
      }
      tempAnd = opAndMap.get(operands);
    }
    if (tempAnd != null)
      return tempAnd;
    final LinkedHashSet<? extends Formula> condensedOperands = operands.size() < 2
            ? operands
            : this.condenseOperandsAnd(operands);
    if (condensedOperands == null)
      return this.falsum();
    if (condensedOperands.isEmpty())
      return this.verum();
    if (condensedOperands.size() == 1)
      return condensedOperands.iterator().next();
    final And and;
    Map<LinkedHashSet<? extends Formula>, And> condAndMap = this.andsN;
    switch (condensedOperands.size()) {
      case 2:
        condAndMap = this.ands2;
        break;
      case 3:
        condAndMap = this.ands3;
        break;
      case 4:
        condAndMap = this.ands4;
        break;
      default:
        break;
    }
    and = condAndMap.get(condensedOperands);
    if (and == null) {
      tempAnd = new And(condensedOperands, this, this.cnfCheck);
      opAndMap.put(operands, tempAnd);
      condAndMap.put(condensedOperands, tempAnd);
      return tempAnd;
    }
    opAndMap.put(operands, and);
    return and;
  }
887684
public void add(final Formula formula) {
        final Formula cnf = formula.cnf();
        switch (cnf.type()) {
            case TRUE:
                break;
            case FALSE:
            case LITERAL:
            case OR:
                this.addClause(generateClauseVector(cnf), null);
                break;
            case AND:
                for (final Formula op : cnf) {
                    this.addClause(generateClauseVector(op), null);
                }
                break;
            default:
                throw new IllegalStateException("Unexpected formula type in CNF: " + cnf.type());
        }
    }
144075
function () {
    instance = this;

    parser = new FormulaParser(instance);

    instance.formulas = Formula;
    instance.matrix = new Matrix();

    instance.custom = {};

    if (rootElement) {
      instance.matrix.scan();
    }
  }
334306
private void addClauseSetWithRelaxation(final Variable relaxationVar, final Formula formula) {
        switch (formula.type()) {
            case TRUE:
                break;
            case FALSE:
            case LITERAL:
            case OR:
                this.addClauseWithRelaxation(relaxationVar, formula);
                break;
            case AND:
                for (final Formula op : formula) { this.addClauseWithRelaxation(relaxationVar, op); }
                break;
            default:
                throw new IllegalArgumentException("Input formula ist not a valid CNF: " + formula);
        }
    }
1504
private LNGIntVector generateClauseVector(final Formula clause) {
        final LNGIntVector clauseVec = new LNGIntVector(clause.numberOfOperands());
        for (final Literal lit : clause.literals()) {
            int index = this.idxForName(lit.name());
            if (index == -1) {
                index = this.newVar(false, true);
                this.addName(lit.name(), index);
            }
            final int litNum = lit.phase() ? index * 2 : (index * 2) ^ 1;
            clauseVec.push(litNum);
        }
        return clauseVec;
    }
1037722
def _formulas(lexer, varname, fmt, nvars):
    """"""
    types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
    tok = lexer.peek_token()
    if any(isinstance(tok, t) for t in types):
        first = _sat_formula(lexer, varname, fmt, nvars)
        rest = _formulas(lexer, varname, fmt, nvars)
        return (first, ) + rest
    # null
    else:
        return tuple()
628977
@Override
    public IsaAtom toIsaAtom(){
        IsaAtom isaAtom = IsaAtom.create(getAttributeVariable(), new Variable(), getTypeId(), false, getParentQuery());
        Set<Statement> patterns = new HashSet<>();
        ReasonerQueries.atomic(isaAtom).getPattern().getPatterns().stream().flatMap(p -> p.statements().stream()).forEach(patterns::add);
        getMultiPredicate().stream().map(Predicate::getPattern).forEach(patterns::add);
        return ReasonerQueries.atomic(Graql.and(patterns), tx()).getAtom().toIsaAtom();
    }
542239
def find_atomics(formula: Formula) -> Set[PLAtomic]:
    """"""
    f = formula
    res = set()
    if isinstance(formula, PLFormula):
        res = formula.find_atomics()
    # elif isinstance(f, PLNot):
    #     res = res.union(find_atomics(f.f))
    # elif isinstance(f, PLBinaryOperator):
    #     for subf in f.formulas:
    #         res = res.union(find_atomics(subf))
    else:
        res.add(f)
    return res