public void addAssignmentToIndex(Assignment assignment) { for (int i = 0; i < assignment.size(); i++) { GdlConstant c = assignment.get(i); if (indices.size() <= i) indices.add(new Index()); Index index = indices.get(i); if (!index.containsKey(c)) index.put(c, new Assignments()); Assignments val = index.get(c); val.add(assignment); } }
// Warning: destructively modifies ret's assignment to fullAssn (I could save and restore, but I // don't care private DiscreteFactor constructConditionalCpt( FactorGraph mdl, Variable var, Assignment fullAssn) { List ptlList = mdl.allFactorsContaining(var); LogTableFactor ptl = new LogTableFactor(var); for (AssignmentIterator it = ptl.assignmentIterator(); it.hasNext(); it.advance()) { Assignment varAssn = it.assignment(); fullAssn.setValue(var, varAssn.get(var)); ptl.setRawValue(varAssn, sumValues(ptlList, fullAssn)); } ptl.normalize(); return ptl; }
// Coolest method in this whole thing, does the real work of the JOIN stuff private Set<Map<GdlVariable, GdlConstant>> findSatisfyingInstantiations( List<Condition> conditions, int idx, Map<GdlVariable, GdlConstant> instantiation) { Set<Map<GdlVariable, GdlConstant>> rval = new HashSet<>(); if (idx == conditions.size()) { rval.add(instantiation); return rval; } Condition cond = conditions.get(idx); Domain dom = cond.dom; Assignments assignments = null; for (int i = 0; i < cond.template.size(); i++) { GdlTerm t = cond.template.get(i); GdlConstant c = null; if (t instanceof GdlVariable) { GdlVariable v = (GdlVariable) t; if (instantiation.containsKey(v)) c = instantiation.get(v); } else if (t instanceof GdlConstant) c = (GdlConstant) t; if (c != null) { if (assignments == null) { assignments = new Assignments(); if (dom.indices.size() > i) // if this doesn't hold it is because there are no assignments and the indices // haven't been set up yet { Index index = dom.indices.get(i); if (index.containsKey(c)) // Might be no assignment which satisfies this condition assignments.addAll(index.get(c)); } } else { if (dom.indices.size() > i) { Index index = dom.indices.get(i); if (index.containsKey(c)) // Might be no assignment which satisfies this condition assignments.retainAll(index.get(c)); } else // This is when we've tried to find an assignment for a form that doesn't have any // assignments yet. Pretend it returned an empty set assignments.clear(); } } } if (assignments == null) // case where there are no constants to be consistent with { assignments = dom.assignments; } for (Assignment a : assignments) { Map<GdlVariable, GdlConstant> newInstantiation = new HashMap<>(instantiation); for (int i = 0; i < a.size(); i++) { GdlTerm t = cond.template.get(i); if (t instanceof GdlVariable) { GdlVariable var = (GdlVariable) t; if (!instantiation.containsKey(var)) newInstantiation.put(var, a.get(i)); } } rval.addAll(findSatisfyingInstantiations(conditions, idx + 1, newInstantiation)); } return rval; }