001package org.clafer.compiler; 002 003import org.clafer.instance.InstanceModel; 004 005/** 006 * Resource limit reached on an optimization problem with the best known 007 * solution thus far. 008 * 009 * <pre> 010 * solver.limitTime(1000); 011 * try { 012 * solver.find(); 013 * } catch (ReachedLimitBestKnownException rle) { 014 * // This is an optimization problem and 1000ms has passed. 015 * // Although the solver did not complete, it returned the best known 016 * // (but possibly non-optimal) instance after 1000ms. This instance is 017 * // stored in the rle exception. 018 * while (rle.find()) { 019 * System.out.println("Approximate solutions: " + rle.instance()); 020 * } 021 * } catch (ReachedLimitException rle) { 022 * // 1000ms has passed. 023 * } 024 * </pre> 025 * 026 * @author jimmy 027 */ 028public class ReachedLimitBestKnownException extends ReachedLimitException implements OptimalInstanceIterator { 029 030 private final InstanceModel[] instances; 031 private final int[][] objectiveValues; 032 private int count = 0; 033 034 public ReachedLimitBestKnownException(InstanceModel[] instances, int[][] objectiveValues) { 035 this.instances = instances; 036 this.objectiveValues = objectiveValues; 037 } 038 039 public ReachedLimitBestKnownException(InstanceModel instance, int[] objectiveValues) { 040 this.instances = new InstanceModel[]{instance}; 041 this.objectiveValues = new int[][]{objectiveValues}; 042 } 043 044 @Override 045 public boolean find() { 046 if (count < instances.length) { 047 count++; 048 return true; 049 } 050 return false; 051 } 052 053 @Override 054 public InstanceModel instance() { 055 if (count == 0 || count > instances.length) { 056 throw new IllegalStateException("No instances. Did you forget to call find?"); 057 } 058 return instances[count - 1]; 059 } 060 061 @Override 062 public int[] optimalValues() { 063 if (count == 0 || count > instances.length) { 064 throw new IllegalStateException("No instances. Did you forget to call find?"); 065 } 066 return objectiveValues[count - 1]; 067 } 068 069 @Override 070 public int instanceCount() { 071 return count; 072 } 073}