package edu.neu.ccs.evergreen.model; /** * Used to create constraint. * */ public class ConstraintFactory { private static int BASE[] = new int[Constraint.MAX_RANK + 1]; static { for (int rank = 0; rank < BASE.length; rank++) { BASE[rank] = (int) Math.pow(2, Math.pow(2, rank)) - 1; } } /** * Create an or constraint with rank 1, 2, or 3. * * @param id * ID of the constraint * @param relationNumber * Relation for the constraint * @param variables * Variables in the relation * @param weight * Weight of relation * @return Relation Number */ public static Constraint createConstraint(int id, int relationNumber, int variables[], int weight) { if (variables.length > Constraint.MAX_RANK) { throw new IllegalArgumentException("Vars can not be longer than " + Constraint.MAX_RANK); } if ((relationNumber < Constraint.UNSATISFIED) || (relationNumber > Constraint.SATISFIED)) { throw new IllegalArgumentException("Relation number " + relationNumber + " is not valid."); } return new Constraint(id, relationNumber, variables, weight); } /** * Create an or constraint with rank 1, 2, or 3. * * @param id * ID of the constraint * @param variables * Variables in the relation * @param weight * Weight of relation * @return Relation Number */ public static Constraint createOr(int id, int variables[], int weight) { if (variables.length > Constraint.MAX_RANK) { throw new IllegalArgumentException("Vars can not be longer than " + Constraint.MAX_RANK); } int missing = 1; int offset = 1; for (int i = 0; i < variables.length; i++) { if (variables[i] < 0) { variables[i] = -variables[i]; missing = missing << offset; } offset *= 2; } int relationNumber = BASE[variables.length] & ~missing; for (int i = variables.length; i < Constraint.MAX_RANK; i++) { relationNumber = relationNumber | relationNumber << offset; offset *= 2; } return new Constraint(id, relationNumber, variables, weight); } /** * Create an implies constraint such that 1 or 2 implies 0. * * @param id * ID of the constraint * @param variables * Three variables * @param weight * Weight of relation * @return Relation Number */ public static Constraint createImplies(int id, int variables[], int weight) { if (variables.length != 3) { throw new IllegalArgumentException("Vars must be of length 3"); } int relationNumber = 169; if (variables[1] < 0) { variables[1] = -variables[1]; if (variables[2] < 0) { variables[2] = -variables[2]; relationNumber = 106; } else { relationNumber = 166; } } else if (variables[2] < 0) { variables[2] = -variables[2]; relationNumber = 154; } return new Constraint(id, relationNumber, variables, weight); } }