You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mahout.apache.org by sr...@apache.org on 2010/10/03 22:53:11 UTC

svn commit: r1004046 [2/4] - in /mahout/trunk: core/src/main/java/org/apache/mahout/cf/taste/impl/common/ core/src/main/java/org/apache/mahout/cf/taste/impl/common/jdbc/ core/src/main/java/org/apache/mahout/cf/taste/impl/eval/ core/src/main/java/org/ap...

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/TreeClusteringRecommender2.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/TreeClusteringRecommender2.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/TreeClusteringRecommender2.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/TreeClusteringRecommender2.java Sun Oct  3 20:53:07 2010
@@ -43,6 +43,8 @@ import org.apache.mahout.common.RandomUt
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * A {@link org.apache.mahout.cf.taste.recommender.Recommender} that clusters users, then determines the
@@ -94,12 +96,8 @@ public final class TreeClusteringRecomme
   public TreeClusteringRecommender2(DataModel dataModel, ClusterSimilarity clusterSimilarity, int numClusters)
     throws TasteException {
     super(dataModel);
-    if (clusterSimilarity == null) {
-      throw new IllegalArgumentException("clusterSimilarity is null");
-    }
-    if (numClusters < 2) {
-      throw new IllegalArgumentException("numClusters must be at least 2");
-    }
+    Preconditions.checkArgument(clusterSimilarity != null, "clusterSimilarity is null");
+    Preconditions.checkArgument(numClusters >= 2, "numClusters must be at least 2");
     this.clusterSimilarity = clusterSimilarity;
     this.numClusters = numClusters;
     this.clusteringThreshold = Double.NaN;
@@ -132,12 +130,8 @@ public final class TreeClusteringRecomme
                                     ClusterSimilarity clusterSimilarity,
                                     double clusteringThreshold) throws TasteException {
     super(dataModel);
-    if (clusterSimilarity == null) {
-      throw new IllegalArgumentException("clusterSimilarity is null");
-    }
-    if (Double.isNaN(clusteringThreshold)) {
-      throw new IllegalArgumentException("clusteringThreshold must not be NaN");
-    }
+    Preconditions.checkArgument(clusterSimilarity != null, "clusterSimilarity is null");
+    Preconditions.checkArgument(!(Double.isNaN(clusteringThreshold)), "clusteringThreshold must not be NaN");
     this.clusterSimilarity = clusterSimilarity;
     this.numClusters = Integer.MIN_VALUE;
     this.clusteringThreshold = clusteringThreshold;
@@ -156,18 +150,16 @@ public final class TreeClusteringRecomme
   
   @Override
   public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) throws TasteException {
-    if (howMany < 1) {
-      throw new IllegalArgumentException("howMany must be at least 1");
-    }
+    Preconditions.checkArgument(howMany >= 1, "howMany must be at least 1");
     buildClusters();
-    
+
     log.debug("Recommending items for user ID '{}'", userID);
-    
+
     List<RecommendedItem> recommended = topRecsByUserID.get(userID);
     if (recommended == null) {
       return Collections.emptyList();
     }
-    
+
     DataModel dataModel = getDataModel();
     List<RecommendedItem> rescored = new ArrayList<RecommendedItem>(recommended.size());
     // Only add items the user doesn't already have a preference for.
@@ -183,7 +175,7 @@ public final class TreeClusteringRecomme
       }
     }
     Collections.sort(rescored, new ByRescoreComparator(rescorer));
-    
+
     return rescored;
   }
   

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/MemoryDiffStorage.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/MemoryDiffStorage.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/MemoryDiffStorage.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/MemoryDiffStorage.java Sun Oct  3 20:53:07 2010
@@ -45,6 +45,8 @@ import org.apache.mahout.cf.taste.recomm
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * An implementation of {@link DiffStorage} that merely stores item-item diffs in memory. It is fast, but can
@@ -99,15 +101,9 @@ public final class MemoryDiffStorage imp
                            Weighting stdDevWeighted,
                            boolean compactAverages,
                            long maxEntries) throws TasteException {
-    if (dataModel == null) {
-      throw new IllegalArgumentException("dataModel is null");
-    }
-    if (dataModel.getNumItems() < 1) {
-      throw new IllegalArgumentException("dataModel has no items");
-    }
-    if (maxEntries <= 0L) {
-      throw new IllegalArgumentException("maxEntries must be positive");
-    }
+    Preconditions.checkArgument(dataModel != null, "dataModel is null");
+    Preconditions.checkArgument(dataModel.getNumItems() >= 1, "dataModel has no items");
+    Preconditions.checkArgument(maxEntries > 0L, "maxEntries must be positive");
     this.dataModel = dataModel;
     this.stdDevWeighted = stdDevWeighted == Weighting.WEIGHTED;
     this.compactAverages = compactAverages;
@@ -313,7 +309,6 @@ public final class MemoryDiffStorage imp
         if (average != null) {
           average.addDatum(userPreferences.getValue(j) - prefAValue);
         }
-        
       }
       RunningAverage itemAverage = averageItemPref.get(itemIDA);
       if (itemAverage == null) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/SlopeOneRecommender.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/SlopeOneRecommender.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/SlopeOneRecommender.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/SlopeOneRecommender.java Sun Oct  3 20:53:07 2010
@@ -38,6 +38,8 @@ import org.apache.mahout.cf.taste.recomm
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * A basic "slope one" recommender. (See an <a href="http://www.daniel-lemire.com/fr/abstracts/SDM2005.html">
@@ -94,12 +96,9 @@ public final class SlopeOneRecommender e
                              Weighting stdDevWeighting,
                              DiffStorage diffStorage) {
     super(dataModel);
-    if ((stdDevWeighting == Weighting.WEIGHTED) && (weighting == Weighting.UNWEIGHTED)) {
-      throw new IllegalArgumentException("weighted required when stdDevWeighted is set");
-    }
-    if (diffStorage == null) {
-      throw new IllegalArgumentException("diffStorage is null");
-    }
+    Preconditions.checkArgument(stdDevWeighting != Weighting.WEIGHTED || weighting != Weighting.UNWEIGHTED,
+      "weighted required when stdDevWeighted is set");
+    Preconditions.checkArgument(diffStorage != null, "diffStorage is null");
     this.weighted = weighting == Weighting.WEIGHTED;
     this.stdDevWeighted = stdDevWeighting == Weighting.WEIGHTED;
     this.diffStorage = diffStorage;
@@ -107,19 +106,16 @@ public final class SlopeOneRecommender e
   
   @Override
   public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) throws TasteException {
-    if (howMany < 1) {
-      throw new IllegalArgumentException("howMany must be at least 1");
-    }
-    
+    Preconditions.checkArgument(howMany >= 1, "howMany must be at least 1");
     log.debug("Recommending items for user ID '{}'", userID);
-    
+
     FastIDSet possibleItemIDs = diffStorage.getRecommendableItemIDs(userID);
-    
+
     TopItems.Estimator<Long> estimator = new Estimator(userID);
-    
+
     List<RecommendedItem> topItems = TopItems.getTopItems(howMany, possibleItemIDs.iterator(), rescorer,
       estimator);
-    
+
     log.debug("Recommendations are: {}", topItems);
     return topItems;
   }

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/file/FileDiffStorage.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/file/FileDiffStorage.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/file/FileDiffStorage.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/file/FileDiffStorage.java Sun Oct  3 20:53:07 2010
@@ -40,6 +40,8 @@ import org.apache.mahout.common.FileLine
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * {@link DiffStorage} which reads pre-computed diffs from a file and stores in memory. The file should have
@@ -76,18 +78,12 @@ public final class FileDiffStorage imple
    *           if data file does not exist or is a directory
    */
   public FileDiffStorage(File dataFile, long maxEntries) throws FileNotFoundException {
-    if (dataFile == null) {
-      throw new IllegalArgumentException("dataFile is null");
-    }
+    Preconditions.checkArgument(dataFile != null, "dataFile is null");
     if (!dataFile.exists() || dataFile.isDirectory()) {
       throw new FileNotFoundException(dataFile.toString());
     }
-    if (maxEntries <= 0L) {
-      throw new IllegalArgumentException("maxEntries must be positive");
-    }
-    
+    Preconditions.checkArgument(maxEntries > 0L, "maxEntries must be positive");
     log.info("Creating FileDataModel for file {}", dataFile);
-    
     this.dataFile = dataFile.getAbsoluteFile();
     this.lastModified = dataFile.lastModified();
     this.maxEntries = maxEntries;
@@ -101,7 +97,7 @@ public final class FileDiffStorage imple
   private void buildDiffs() {
     if (buildAverageDiffsLock.writeLock().tryLock()) {
       try {
-        
+
         averageDiffs.clear();
         allRecommendableItemIDs.clear();
         
@@ -129,19 +125,15 @@ public final class FileDiffStorage imple
   }
   
   private long processLine(String line, char delimiter, long averageCount) {
-    
+
     if ((line.length() == 0) || (line.charAt(0) == COMMENT_CHAR)) {
       return averageCount;
     }
     
     int delimiterOne = line.indexOf(delimiter);
-    if (delimiterOne < 0) {
-      throw new IllegalArgumentException("Bad line: " + line);
-    }
+    Preconditions.checkArgument(delimiterOne >= 0, "Bad line: %s", line);
     int delimiterTwo = line.indexOf(delimiter, delimiterOne + 1);
-    if (delimiterTwo < 0) {
-      throw new IllegalArgumentException("Bad line: " + line);
-    }
+    Preconditions.checkArgument(delimiterTwo >= 0, "Bad line: %s", line);
     
     long itemID1 = Long.parseLong(line.substring(0, delimiterOne));
     long itemID2 = Long.parseLong(line.substring(delimiterOne + 1, delimiterTwo));

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/jdbc/AbstractJDBCDiffStorage.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/jdbc/AbstractJDBCDiffStorage.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/jdbc/AbstractJDBCDiffStorage.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/slopeone/jdbc/AbstractJDBCDiffStorage.java Sun Oct  3 20:53:07 2010
@@ -42,6 +42,8 @@ import org.apache.mahout.common.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * A {@link DiffStorage} which stores diffs in a database. Database-specific implementations subclass this
@@ -96,10 +98,9 @@ public abstract class AbstractJDBCDiffSt
     AbstractJDBCComponent.checkNotNullAndLog("deleteDiffsSQL", deleteDiffsSQL);
     AbstractJDBCComponent.checkNotNullAndLog("createDiffsSQL", createDiffsSQL);
     AbstractJDBCComponent.checkNotNullAndLog("diffsExistSQL", diffsExistSQL);
+
+    Preconditions.checkArgument(minDiffCount >= 0, "minDiffCount is not positive");
     
-    if (minDiffCount < 0) {
-      throw new IllegalArgumentException("minDiffCount is not positive");
-    }
     this.dataSource = dataModel.getDataSource();
     this.getDiffSQL = getDiffSQL;
     this.getDiffsSQL = getDiffsSQL;
@@ -341,4 +342,4 @@ public abstract class AbstractJDBCDiffSt
   public void refresh(Collection<Refreshable> alreadyRefreshed) {
     refreshHelper.refresh(alreadyRefreshed);
   }
-}
\ No newline at end of file
+}

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/svd/SVDRecommender.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/svd/SVDRecommender.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/svd/SVDRecommender.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/recommender/svd/SVDRecommender.java Sun Oct  3 20:53:07 2010
@@ -45,6 +45,8 @@ import org.apache.mahout.common.RandomUt
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * A {@link org.apache.mahout.cf.taste.recommender.Recommender} which uses Single Value Decomposition
@@ -182,19 +184,16 @@ public final class SVDRecommender extend
   
   @Override
   public List<RecommendedItem> recommend(long userID, int howMany, IDRescorer rescorer) throws TasteException {
-    if (howMany < 1) {
-      throw new IllegalArgumentException("howMany must be at least 1");
-    }
-    
+    Preconditions.checkArgument(howMany >= 1, "howMany must be at least 1");
     log.debug("Recommending items for user ID '{}'", userID);
-    
+
     FastIDSet possibleItemIDs = getAllOtherItems(userID);
-    
+
     TopItems.Estimator<Long> estimator = new Estimator(userID);
-    
+
     List<RecommendedItem> topItems = TopItems.getTopItems(howMany, possibleItemIDs.iterator(), rescorer,
       estimator);
-    
+
     log.debug("Recommendations are: {}", topItems);
     return topItems;
   }

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/AbstractSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/AbstractSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/AbstractSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/AbstractSimilarity.java Sun Oct  3 20:53:07 2010
@@ -32,6 +32,8 @@ import org.apache.mahout.cf.taste.simila
 import org.apache.mahout.cf.taste.transforms.PreferenceTransform;
 import org.apache.mahout.cf.taste.transforms.SimilarityTransform;
 
+import com.google.common.base.Preconditions;
+
 /** Abstract superclass encapsulating functionality that is common to most implementations in this package. */
 abstract class AbstractSimilarity implements UserSimilarity, ItemSimilarity {
   
@@ -51,9 +53,7 @@ abstract class AbstractSimilarity implem
    * </p>
    */
   AbstractSimilarity(final DataModel dataModel, Weighting weighting, boolean centerData) throws TasteException {
-    if (dataModel == null) {
-      throw new IllegalArgumentException("dataModel is null");
-    }
+    Preconditions.checkArgument(dataModel != null, "dataModel is null");
     this.dataModel = dataModel;
     this.weighted = weighting == Weighting.WEIGHTED;
     this.centerData = centerData;
@@ -80,9 +80,7 @@ abstract class AbstractSimilarity implem
   
   @Override
   public final void setPreferenceInferrer(PreferenceInferrer inferrer) {
-    if (inferrer == null) {
-      throw new IllegalArgumentException("inferrer is null");
-    }
+    Preconditions.checkArgument(inferrer != null, "inferrer is null");
     refreshHelper.addDependency(inferrer);
     refreshHelper.removeDependency(this.inferrer);
     this.inferrer = inferrer;

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingItemSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingItemSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingItemSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingItemSimilarity.java Sun Oct  3 20:53:07 2010
@@ -27,6 +27,7 @@ import org.apache.mahout.cf.taste.impl.c
 import org.apache.mahout.cf.taste.model.DataModel;
 import org.apache.mahout.cf.taste.similarity.ItemSimilarity;
 import org.apache.mahout.common.LongPair;
+import com.google.common.base.Preconditions;
 
 /** Caches the results from an underlying {@link ItemSimilarity} implementation. */
 public final class CachingItemSimilarity implements ItemSimilarity {
@@ -47,9 +48,7 @@ public final class CachingItemSimilarity
    * The cache size is capped by the given size.
    */
   public CachingItemSimilarity(ItemSimilarity similarity, int maxCacheSize) {
-    if (similarity == null) {
-      throw new IllegalArgumentException("similarity is null");
-    }
+    Preconditions.checkArgument(similarity != null, "similarity is null");
     this.similarity = similarity;
     this.similarityCache = new Cache<LongPair,Double>(new SimilarityRetriever(similarity), maxCacheSize);
   }
@@ -90,4 +89,4 @@ public final class CachingItemSimilarity
     }
   }
   
-}
\ No newline at end of file
+}

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/CachingUserSimilarity.java Sun Oct  3 20:53:07 2010
@@ -29,6 +29,8 @@ import org.apache.mahout.cf.taste.simila
 import org.apache.mahout.cf.taste.similarity.UserSimilarity;
 import org.apache.mahout.common.LongPair;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Caches the results from an underlying {@link org.apache.mahout.cf.taste.similarity.UserSimilarity}
  * implementation.
@@ -51,9 +53,7 @@ public final class CachingUserSimilarity
    * The cache size is capped by the given size.
    */
   public CachingUserSimilarity(UserSimilarity similarity, int maxCacheSize) {
-    if (similarity == null) {
-      throw new IllegalArgumentException("similarity is null");
-    }
+    Preconditions.checkArgument(similarity != null, "similarity is null");
     this.similarity = similarity;
     this.similarityCache = new Cache<LongPair,Double>(new SimilarityRetriever(similarity), maxCacheSize);
   }

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/EuclideanDistanceSimilarity.java Sun Oct  3 20:53:07 2010
@@ -21,6 +21,8 @@ import org.apache.mahout.cf.taste.common
 import org.apache.mahout.cf.taste.common.Weighting;
 import org.apache.mahout.cf.taste.model.DataModel;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * An implementation of a "similarity" based on the Euclidean "distance" between two users X and Y. Thinking
@@ -44,9 +46,7 @@ public final class EuclideanDistanceSimi
    */
   public EuclideanDistanceSimilarity(DataModel dataModel, Weighting weighting) throws TasteException {
     super(dataModel, weighting, false);
-    if (!dataModel.hasPreferenceValues()) {
-      throw new IllegalArgumentException("DataModel doesn't have preference values");
-    }
+    Preconditions.checkArgument(dataModel.hasPreferenceValues(), "DataModel doesn't have preference values");
   }
   
   @Override
@@ -55,4 +55,4 @@ public final class EuclideanDistanceSimi
     return n / (1.0 + Math.sqrt(sumXYdiff2));
   }
   
-}
\ No newline at end of file
+}

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericItemSimilarity.java Sun Oct  3 20:53:07 2010
@@ -31,6 +31,8 @@ import org.apache.mahout.common.RandomUt
 import org.apache.mahout.common.iterator.IteratorIterable;
 import org.apache.mahout.common.iterator.IteratorUtils;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * A "generic" {@link ItemSimilarity} which takes a static list of precomputed item similarities and bases its
@@ -240,9 +242,7 @@ public final class GenericItemSimilarity
      *           if value is NaN, less than -1.0 or greater than 1.0
      */
     public ItemItemSimilarity(long itemID1, long itemID2, double value) {
-      if (Double.isNaN(value) || (value < -1.0) || (value > 1.0)) {
-        throw new IllegalArgumentException("Illegal value: " + value);
-      }
+      Preconditions.checkArgument(value >= -1.0 && value <= 1.0, "Illegal value: %s", value);
       this.itemID1 = itemID1;
       this.itemID2 = itemID2;
       this.value = value;

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/GenericUserSimilarity.java Sun Oct  3 20:53:07 2010
@@ -32,6 +32,8 @@ import org.apache.mahout.common.RandomUt
 import org.apache.mahout.common.iterator.IteratorIterable;
 import org.apache.mahout.common.iterator.IteratorUtils;
 
+import com.google.common.base.Preconditions;
+
 public final class GenericUserSimilarity implements UserSimilarity {
   
   private final FastByIDMap<FastByIDMap<Double>> similarityMaps = new FastByIDMap<FastByIDMap<Double>>();
@@ -120,15 +122,13 @@ public final class GenericUserSimilarity
   }
   
   public static final class UserUserSimilarity implements Comparable<UserUserSimilarity> {
-    
+
     private final long userID1;
     private final long userID2;
     private final double value;
     
     public UserUserSimilarity(long userID1, long userID2, double value) {
-      if (Double.isNaN(value) || (value < -1.0) || (value > 1.0)) {
-        throw new IllegalArgumentException("Illegal value: " + value);
-      }
+      Preconditions.checkArgument(value >= -1.0 && value <= 1.0, "Illegal value: %s", value);
       this.userID1 = userID1;
       this.userID2 = userID2;
       this.value = value;
@@ -228,4 +228,4 @@ public final class GenericUserSimilarity
     
   }
   
-}
\ No newline at end of file
+}

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/PearsonCorrelationSimilarity.java Sun Oct  3 20:53:07 2010
@@ -21,6 +21,8 @@ import org.apache.mahout.cf.taste.common
 import org.apache.mahout.cf.taste.common.Weighting;
 import org.apache.mahout.cf.taste.model.DataModel;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * An implementation of the Pearson correlation. For users X and Y, the following values are calculated:
@@ -69,9 +71,7 @@ public final class PearsonCorrelationSim
    */
   public PearsonCorrelationSimilarity(DataModel dataModel, Weighting weighting) throws TasteException {
     super(dataModel, weighting, true);
-    if (!dataModel.hasPreferenceValues()) {
-      throw new IllegalArgumentException("DataModel doesn't have preference values");
-    }
+    Preconditions.checkArgument(dataModel.hasPreferenceValues(), "DataModel doesn't have preference values");
   }
   
   @Override

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/SpearmanCorrelationSimilarity.java Sun Oct  3 20:53:07 2010
@@ -27,6 +27,8 @@ import org.apache.mahout.cf.taste.model.
 import org.apache.mahout.cf.taste.similarity.PreferenceInferrer;
 import org.apache.mahout.cf.taste.similarity.UserSimilarity;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * Like {@link PearsonCorrelationSimilarity}, but compares relative ranking of preference values instead of
@@ -39,9 +41,7 @@ public final class SpearmanCorrelationSi
   private final DataModel dataModel;
   
   public SpearmanCorrelationSimilarity(DataModel dataModel) {
-    if (dataModel == null) {
-      throw new IllegalArgumentException("dataModel is null");
-    }
+    Preconditions.checkArgument(dataModel != null, "dataModel is null");
     this.dataModel = dataModel;
   }
   

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/UncenteredCosineSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/UncenteredCosineSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/UncenteredCosineSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/UncenteredCosineSimilarity.java Sun Oct  3 20:53:07 2010
@@ -21,6 +21,8 @@ import org.apache.mahout.cf.taste.common
 import org.apache.mahout.cf.taste.common.Weighting;
 import org.apache.mahout.cf.taste.model.DataModel;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * An implementation of the cosine similarity. The result is the cosine of the angle formed between
@@ -47,9 +49,7 @@ public final class UncenteredCosineSimil
    */
   public UncenteredCosineSimilarity(DataModel dataModel, Weighting weighting) throws TasteException {
     super(dataModel, weighting, false);
-    if (!dataModel.hasPreferenceValues()) {
-      throw new IllegalArgumentException("DataModel doesn't have preference values");
-    }
+    Preconditions.checkArgument(dataModel.hasPreferenceValues(), "DataModel doesn't have preference values");
   }
 
   @Override
@@ -66,4 +66,4 @@ public final class UncenteredCosineSimil
     return sumXY / denominator;
   }
 
-}
\ No newline at end of file
+}

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/file/FileItemSimilarity.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/file/FileItemSimilarity.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/file/FileItemSimilarity.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/similarity/file/FileItemSimilarity.java Sun Oct  3 20:53:07 2010
@@ -28,6 +28,8 @@ import org.apache.mahout.cf.taste.simila
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * An {@link ItemSimilarity} backed by a comma-delimited file. This class typically expects a file where each line
@@ -78,12 +80,9 @@ public class FileItemSimilarity implemen
    * @see #FileItemSimilarity(File)
    */
   public FileItemSimilarity(File dataFile, long minReloadIntervalMS) {
-    if (dataFile == null) {
-      throw new IllegalArgumentException("dataFile is null");
-    }
-    if (!dataFile.exists() || dataFile.isDirectory()) {
-      throw new IllegalArgumentException("dataFile is missing or a directory: " + dataFile);
-    }
+    Preconditions.checkArgument(dataFile != null, "dataFile is null");
+    Preconditions.checkArgument(dataFile.exists() && !dataFile.isDirectory(),
+      "dataFile is missing or a directory: %s", dataFile);
 
     log.info("Creating FileItemSimilarity for file {}", dataFile);
 

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/CaseAmplification.java Sun Oct  3 20:53:07 2010
@@ -22,6 +22,8 @@ import java.util.Collection;
 import org.apache.mahout.cf.taste.common.Refreshable;
 import org.apache.mahout.cf.taste.transforms.SimilarityTransform;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * Applies "case amplification" to similarities. This essentially makes big values bigger and small values
@@ -43,9 +45,7 @@ public final class CaseAmplification imp
    *           if factor is 0.0 or {@link Double#NaN}
    */
   public CaseAmplification(double factor) {
-    if (Double.isNaN(factor) || (factor == 0.0)) {
-      throw new IllegalArgumentException("factor is 0 or NaN");
-    }
+    Preconditions.checkArgument(factor != 0.0 && !Double.isNaN(factor), "factor is 0 or NaN");
     this.factor = factor;
   }
   

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/cf/taste/impl/transforms/InverseUserFrequency.java Sun Oct  3 20:53:07 2010
@@ -31,6 +31,8 @@ import org.apache.mahout.cf.taste.model.
 import org.apache.mahout.cf.taste.model.PreferenceArray;
 import org.apache.mahout.cf.taste.transforms.PreferenceTransform;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * Implements an "inverse user frequency" transformation, which boosts preference values for items for which
@@ -69,12 +71,8 @@ public final class InverseUserFrequency 
    *           if dataModel is <code>null</code> or logBase is {@link Double#NaN} or &lt;= 1.0
    */
   public InverseUserFrequency(DataModel dataModel, double logBase) throws TasteException {
-    if (dataModel == null) {
-      throw new IllegalArgumentException("dataModel is null");
-    }
-    if (Double.isNaN(logBase) || (logBase <= 1.0)) {
-      throw new IllegalArgumentException("logBase is NaN or <= 1.0");
-    }
+    Preconditions.checkArgument(dataModel != null, "dataModel is null");
+    Preconditions.checkArgument(logBase > 1.0, "logBase should be > 1.0");
     this.dataModel = dataModel;
     this.logBase = logBase;
     this.iufFactors = new FastByIDMap<Double>();

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/AbstractVectorClassifier.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/AbstractVectorClassifier.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/AbstractVectorClassifier.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/AbstractVectorClassifier.java Sun Oct  3 20:53:07 2010
@@ -22,6 +22,8 @@ import org.apache.mahout.math.DenseVecto
 import org.apache.mahout.math.Matrix;
 import org.apache.mahout.math.Vector;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Defines the interface for classifiers that take input as a vector.  This is implemented
  * as an abstract class so that it can implement a number of handy convenience methods
@@ -144,9 +146,7 @@ public abstract class AbstractVectorClas
    * @return A vector of scores, with one value per row of the input matrix.
    */
   public Vector classifyScalar(Matrix data) {
-    if (numCategories() != 2) {
-      throw new IllegalArgumentException("Can only call classifyScalar with two categories");
-    }
+    Preconditions.checkArgument(numCategories() == 2, "Can only call classifyScalar with two categories");
 
     Vector r = new DenseVector(data.numRows());
     for (int row = 0; row < data.numRows(); row++) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/ConfusionMatrix.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/ConfusionMatrix.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/ConfusionMatrix.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/ConfusionMatrix.java Sun Oct  3 20:53:07 2010
@@ -24,6 +24,8 @@ import java.util.Map;
 import org.apache.commons.lang.StringUtils;
 import org.apache.mahout.common.Summarizable;
 
+import com.google.common.base.Preconditions;
+
 /**
  * The ConfusionMatrix Class stores the result of Classification of a Test Dataset.
  * 
@@ -93,18 +95,20 @@ public class ConfusionMatrix implements 
   }
   
   public int getCount(String correctLabel, String classifiedLabel) {
-    if (labels.contains(correctLabel) && !(labels.contains(classifiedLabel) || defaultLabel.equals(classifiedLabel))) {
-      throw new IllegalArgumentException("Label not found " + correctLabel + ' ' + classifiedLabel);
-    }
+    Preconditions.checkArgument(!labels.contains(correctLabel)
+        || labels.contains(classifiedLabel)
+        || defaultLabel.equals(classifiedLabel),
+        "Label not found " + correctLabel + ' ' + classifiedLabel);
     int correctId = labelMap.get(correctLabel);
     int classifiedId = labelMap.get(classifiedLabel);
     return confusionMatrix[correctId][classifiedId];
   }
   
   public void putCount(String correctLabel, String classifiedLabel, int count) {
-    if (labels.contains(correctLabel) && !(labels.contains(classifiedLabel) || defaultLabel.equals(classifiedLabel))) {
-      throw new IllegalArgumentException("Label not found " + correctLabel + ' ' + classifiedLabel);
-    }
+    Preconditions.checkArgument(!labels.contains(correctLabel)
+        || labels.contains(classifiedLabel)
+        || defaultLabel.equals(classifiedLabel),
+        "Label not found " + correctLabel + ' ' + classifiedLabel);
     int correctId = labelMap.get(correctLabel);
     int classifiedId = labelMap.get(classifiedLabel);
     confusionMatrix[correctId][classifiedId] = count;
@@ -119,12 +123,7 @@ public class ConfusionMatrix implements 
   }
   
   public ConfusionMatrix merge(ConfusionMatrix b) {
-    if (labels.size() != b.getLabels().size()) {
-      throw new IllegalArgumentException("The Labels do not Match");
-    }
-    
-    // if (labels.containsAll(b.getLabels()))
-    // ;
+    Preconditions.checkArgument(labels.size() == b.getLabels().size(), "The label sizes do not match");
     for (String correctLabel : this.labels) {
       for (String classifiedLabel : this.labels) {
         incrementCount(correctLabel, classifiedLabel, b.getCount(correctLabel, classifiedLabel));
@@ -155,8 +154,8 @@ public class ConfusionMatrix implements 
         labelTotal += getCount(correctLabel, classifiedLabel);
       }
       returnString.append(" |  ").append(StringUtils.rightPad(String.valueOf(labelTotal), 6)).append('\t')
-          .append(StringUtils.rightPad(getSmallLabel(labelMap.get(correctLabel)), 5)).append(
-            " = ").append(correctLabel).append('\n');
+          .append(StringUtils.rightPad(getSmallLabel(labelMap.get(correctLabel)), 5))
+          .append(" = ").append(correctLabel).append('\n');
     }
     returnString.append("Default Category: ").append(defaultLabel).append(": ").append(
       labelMap.get(defaultLabel)).append('\n');
@@ -169,8 +168,7 @@ public class ConfusionMatrix implements 
     StringBuilder returnString = new StringBuilder();
     do {
       int n = val % 26;
-      int c = 'a';
-      returnString.insert(0, (char) (c + n));
+      returnString.insert(0, (char) ('a' + n));
       val /= 26;
     } while (val > 0);
     return returnString.toString();

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/BayesFeatureReducer.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/BayesFeatureReducer.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/BayesFeatureReducer.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/BayesFeatureReducer.java Sun Oct  3 20:53:07 2010
@@ -32,6 +32,8 @@ import org.apache.hadoop.mapred.Reporter
 import org.apache.mahout.common.Parameters;
 import org.apache.mahout.common.StringTuple;
 
+import com.google.common.base.Preconditions;
+
 /** Can also be used as a local Combiner. A simple summing reducer */
 public class BayesFeatureReducer extends MapReduceBase implements
     Reducer<StringTuple,DoubleWritable,StringTuple,DoubleWritable> {
@@ -66,9 +68,7 @@ public class BayesFeatureReducer extends
     }
     reporter.setStatus("Bayes Feature Reducer: " + key + " => " + sum);
 
-    if (key.length() < 2 || key.length() > 3) {
-      throw new IllegalArgumentException("StringTuple length out of bounds, not (2 < length < 3)");
-    }
+    Preconditions.checkArgument(key.length() >= 2 && key.length() <= 3, "StringTuple length out of bounds, not (2 < length < 3)");
     
     int featureIndex = key.length() == 2 ? 1 : 2;
     

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeatureLabelComparator.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeatureLabelComparator.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeatureLabelComparator.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeatureLabelComparator.java Sun Oct  3 20:53:07 2010
@@ -23,6 +23,8 @@ import org.apache.hadoop.io.WritableComp
 import org.apache.hadoop.io.WritableComparator;
 import org.apache.mahout.common.StringTuple;
 
+import com.google.common.base.Preconditions;
+
 import java.io.Serializable;
 
 public class FeatureLabelComparator extends WritableComparator implements Serializable {
@@ -35,11 +37,7 @@ public class FeatureLabelComparator exte
   public int compare(WritableComparable a, WritableComparable b) {
     StringTuple ta = (StringTuple) a;
     StringTuple tb = (StringTuple) b;
-
-    if (ta.length() < 2 || ta.length() > 3 || tb.length() < 2 || tb.length() > 3) {
-      throw new IllegalArgumentException("StringTuple length out of bounds");
-    }
-    
+    Preconditions.checkArgument(ta.length() >= 2 && ta.length() <= 3 && tb.length() >= 2 && tb.length() <= 3, "StringTuple length out of bounds");
     // token
     String tmpa = ta.length() == 2 ? ta.stringAt(1) : ta.stringAt(2);
     String tmpb = tb.length() == 2 ? tb.stringAt(1) : tb.stringAt(2);

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeaturePartitioner.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeaturePartitioner.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeaturePartitioner.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/bayes/mapreduce/common/FeaturePartitioner.java Sun Oct  3 20:53:07 2010
@@ -25,21 +25,18 @@ import org.apache.hadoop.mapred.JobConf;
 import org.apache.hadoop.mapred.Partitioner;
 import org.apache.mahout.common.StringTuple;
 
+import com.google.common.base.Preconditions;
+
 /**
  * ensure that features all make it into the same partition.
  */
 public class FeaturePartitioner implements Partitioner<StringTuple,DoubleWritable> {
   
   @Override
-  public int getPartition(StringTuple key, DoubleWritable value,
-      int numPartitions) {
-    
-    if (key.length() < 2 || key.length() > 3) {
-      throw new IllegalArgumentException("StringTuple length out of bounds");
-    }
-    
+  public int getPartition(StringTuple key, DoubleWritable value, int numPartitions) {
+    Preconditions.checkArgument(key.length() >= 2 && key.length() <= 3, "StringTuple length out of bounds");
     String feature = key.length() == 2 ? key.stringAt(1) : key.stringAt(2);
-    
+
     int length = feature.length();
     int right = 0;
     if (length > 0) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/evaluation/Auc.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/evaluation/Auc.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/evaluation/Auc.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/evaluation/Auc.java Sun Oct  3 20:53:07 2010
@@ -22,6 +22,8 @@ import org.apache.mahout.math.DenseMatri
 import org.apache.mahout.math.Matrix;
 import org.apache.mahout.math.list.DoubleArrayList;
 
+import com.google.common.base.Preconditions;
+
 import java.util.Random;
 
 /**
@@ -69,11 +71,8 @@ public class Auc {
    */
   public void add(int trueValue, double score) {
     hasScore = true;
-
-    if (trueValue != 0 && trueValue != 1) {
-      throw new IllegalArgumentException("True value must be 0 or 1");
-    }
-
+    Preconditions.checkArgument(trueValue == 0 || trueValue == 1, "True value must be 0 or 1" );
+    
     int predictedClass = (score > threshold) ? 1 : 0;
     confusion.set(trueValue, predictedClass, confusion.get(trueValue, predictedClass) + 1);
 
@@ -113,11 +112,7 @@ public class Auc {
 
   public void add(int trueValue, int predictedClass) {
     hasScore = false;
-
-    if (trueValue != 0 && trueValue != 1) {
-      throw new IllegalArgumentException("True value must be 0 or 1");
-    }
-
+    Preconditions.checkArgument(trueValue == 0 || trueValue == 1, "True value must be 0 or 1");
     confusion.set(trueValue, predictedClass, confusion.get(trueValue, predictedClass) + 1);
   }
 
@@ -128,10 +123,7 @@ public class Auc {
    * @return The value of the Area Under the receiver operating Curve.
    */
   public double auc() {
-    if (!hasScore) {
-      throw new IllegalArgumentException("Can't compute AUC for classifier without a score");
-    }
-
+    Preconditions.checkArgument(hasScore, "Can't compute AUC for classifier without a score");
     scores[0].sort();
     scores[1].sort();
 

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sequencelearning/hmm/HmmUtils.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sequencelearning/hmm/HmmUtils.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sequencelearning/hmm/HmmUtils.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sequencelearning/hmm/HmmUtils.java Sun Oct  3 20:53:07 2010
@@ -30,6 +30,8 @@ import org.apache.mahout.math.SparseMatr
 import org.apache.mahout.math.Vector;
 import org.uncommons.maths.Maths;
 
+import com.google.common.base.Preconditions;
+
 /**
  * A collection of utilities for handling HMMModel objects.
  */
@@ -143,75 +145,51 @@ public final class HmmUtils {
     /*
      * The number of hidden states is positive.
      */
-    if (model.getNrOfHiddenStates() <= 0) {
-      throw new IllegalArgumentException(
-          "Error: The number of hidden states has to be greater than 0!");
-    }
-
+    Preconditions.checkArgument(model.getNrOfHiddenStates() > 0,
+      "Error: The number of hidden states has to be greater than 0");
+    
     /*
      * The number of output states is positive.
      */
-    if (model.getNrOfOutputStates() <= 0) {
-      throw new IllegalArgumentException(
-          "Error: The number of output states has to be greater than 0!");
-    }
+    Preconditions.checkArgument(model.getNrOfOutputStates() > 0,
+      "Error: The number of output states has to be greater than 0!");
 
     /*
      * The size of the vector of initial probabilities is equal to the number of
      * the hidden states. Each initial probability is non-negative. The sum of
      * initial probabilities is equal to 1.
      */
-    if (model.getInitialProbabilities() == null) {
-      throw new IllegalArgumentException(
-          "Error: The vector of initial probabilities is not initialized!");
-    }
-    if (model.getInitialProbabilities().size() != model.getNrOfHiddenStates()) {
-      throw new IllegalArgumentException(
-          "Error: The vector of initial probabilities is not initialized!");
-    }
+    Preconditions.checkArgument(model.getInitialProbabilities() != null
+      && model.getInitialProbabilities().size() == model.getNrOfHiddenStates(),
+      "Error: The vector of initial probabilities is not initialized!");
+    
     double sum = 0;
     for (int i = 0; i < model.getInitialProbabilities().size(); i++) {
-      if (model.getInitialProbabilities().get(i) < 0) {
-        throw new IllegalArgumentException(
-            "Error: Initial probability of state " + i + " is negative!");
-      }
+      Preconditions.checkArgument(model.getInitialProbabilities().get(i) >= 0,
+        "Error: Initial probability of state %d is negative", i);
       sum += model.getInitialProbabilities().get(i);
     }
-    if (!Maths.approxEquals(sum, 1, 0.00001)) {
-      throw new IllegalArgumentException(
-          "Error: Initial probabilities do not add up to 1!");
-    }
-
+    Preconditions.checkArgument(Maths.approxEquals(sum, 1, 0.00001), "Error: Initial probabilities do not add up to 1");
     /*
      * The row size of the output matrix is equal to the number of the hidden
      * states. The column size is equal to the number of output states. Each
      * probability of the matrix is non-negative. The sum of each row is equal
      * to 1.
      */
-    if (model.getEmissionMatrix() == null) {
-      throw new IllegalArgumentException(
-          "Error: The output state matrix is not initialized!");
-    }
-    if (model.getEmissionMatrix().numRows() != model.getNrOfHiddenStates()
-        || model.getEmissionMatrix().numCols() != model.getNrOfOutputStates()) {
-      throw new IllegalArgumentException(
-          "Error: The output state matrix is not of the form nrOfHiddenStates x nrOfOutputStates!");
-    }
+    Preconditions.checkArgument(model.getEmissionMatrix() != null, "Error: The output state matrix is not initialized!");
+    Preconditions.checkArgument(model.getEmissionMatrix().numRows() == model.getNrOfHiddenStates()
+      && model.getEmissionMatrix().numCols() == model.getNrOfOutputStates(),
+      "Error: The output state matrix is not of the form nrOfHiddenStates x nrOfOutputStates");
     for (int i = 0; i < model.getEmissionMatrix().numRows(); i++) {
       sum = 0;
       for (int j = 0; j < model.getEmissionMatrix().numCols(); j++) {
-        if (model.getEmissionMatrix().get(i, j) < 0) {
-          throw new IllegalArgumentException(
-              "Error: The output state probability from hidden state " + i
-                  + " to output state " + j + " is negative!");
-        }
+        Preconditions.checkArgument(model.getEmissionMatrix().get(i, j) >= 0,
+          "Error: The output state probability from hidden state " + i +
+            " to output state " + j + " is negative");
         sum += model.getEmissionMatrix().get(i, j);
       }
-      if (!Maths.approxEquals(sum, 1, 0.00001)) {
-        throw new IllegalArgumentException(
-            "Error: The output state probabilities for hidden state " + i
-                + " don't add up to 1.");
-      }
+      Preconditions.checkArgument(Maths.approxEquals(sum, 1, 0.00001),
+        "Error: The output state probabilities for hidden state %d don't add up to 1", i);
     }
 
     /*
@@ -219,30 +197,21 @@ public final class HmmUtils {
      * number of the hidden states. Each probability of the matrix is
      * non-negative. The sum of each row in transition matrix is equal to 1.
      */
-    if (model.getTransitionMatrix() == null) {
-      throw new IllegalArgumentException(
-          "Error: The hidden state matrix is not initialized!");
-    }
-    if (model.getTransitionMatrix().numRows() != model.getNrOfHiddenStates()
-        || model.getTransitionMatrix().numCols() != model.getNrOfHiddenStates()) {
-      throw new IllegalArgumentException(
-          "Error: The output state matrix is not of the form nrOfHiddenStates x nrOfHiddenStates!");
-    }
+    Preconditions.checkArgument(model.getTransitionMatrix() != null,
+      "Error: The hidden state matrix is not initialized!");
+    Preconditions.checkArgument(model.getTransitionMatrix().numRows() == model.getNrOfHiddenStates()
+      && model.getTransitionMatrix().numCols() == model.getNrOfHiddenStates(),
+      "Error: The output state matrix is not of the form nrOfHiddenStates x nrOfHiddenStates");
     for (int i = 0; i < model.getTransitionMatrix().numRows(); i++) {
       sum = 0;
       for (int j = 0; j < model.getTransitionMatrix().numCols(); j++) {
-        if (model.getTransitionMatrix().get(i, j) < 0) {
-          throw new IllegalArgumentException(
-              "Error: The transition probability from hidden state " + i
-                  + " to hidden state " + j + " is negative!");
-        }
+        Preconditions.checkArgument(model.getTransitionMatrix().get(i, j) >= 0,
+          "Error: The transition probability from hidden state %d to hidden state %d is negative",
+          i, j);
         sum += model.getTransitionMatrix().get(i, j);
       }
-      if (!Maths.approxEquals(sum, 1, 0.00001)) {
-        throw new IllegalArgumentException(
-            "Error: The transition probabilities for hidden state " + i
-                + " don't add up to 1.");
-      }
+      Preconditions.checkArgument(Maths.approxEquals(sum, 1, 0.00001),
+        "Error: The transition probabilities for hidden state " + i + " don't add up to 1.");
     }
   }
 
@@ -393,4 +362,4 @@ public final class HmmUtils {
     // and return
     return sparseModel;
   }
-}
\ No newline at end of file
+}

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/AbstractOnlineLogisticRegression.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/AbstractOnlineLogisticRegression.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/AbstractOnlineLogisticRegression.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/AbstractOnlineLogisticRegression.java Sun Oct  3 20:53:07 2010
@@ -25,6 +25,8 @@ import org.apache.mahout.math.Vector;
 import org.apache.mahout.math.function.Functions;
 import org.apache.mahout.math.function.UnaryFunction;
 
+import com.google.common.base.Preconditions;
+
 import java.util.Iterator;
 
 /**
@@ -143,9 +145,7 @@ public abstract class AbstractOnlineLogi
    */
   @Override
   public double classifyScalar(Vector instance) {
-    if (numCategories() != 2) {
-      throw new IllegalArgumentException("Can only call classifyScalar with two categories");
-    }
+    Preconditions.checkArgument(numCategories() == 2, "Can only call classifyScalar with two categories");
 
     // apply pending regularization to whichever coefficients matter
     regularize(instance);
@@ -299,9 +299,7 @@ public abstract class AbstractOnlineLogi
 
   public void copyFrom(AbstractOnlineLogisticRegression other) {
     // number of categories we are classifying.  This should the number of rows of beta plus one.
-    if (numCategories != other.numCategories) {
-      throw new IllegalArgumentException("Can't copy unless number of target categories is the same");
-    }
+    Preconditions.checkArgument(numCategories == other.numCategories, "Can't copy unless number of target categories is the same");
 
     beta.assign(other.beta);
 

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/CsvRecordFactory.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/CsvRecordFactory.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/CsvRecordFactory.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/CsvRecordFactory.java Sun Oct  3 20:53:07 2010
@@ -19,6 +19,7 @@ package org.apache.mahout.classifier.sgd
 
 import com.google.common.base.CharMatcher;
 import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableMap;
@@ -115,11 +116,9 @@ public class CsvRecordFactory implements
    */
   @Override
   public void defineTargetCategories(List<String> values) {
-    if (values.size() > maxTargetValue) {
-      throw new IllegalArgumentException("Must have less than or equal to " + maxTargetValue
-        + " categories for target variable, but found " + values.size());
-    }
-
+    Preconditions.checkArgument(values.size() <= maxTargetValue,
+      "Must have less than or equal to " + maxTargetValue +
+        " categories for target variable, but found " + values.size());
     if (maxTargetValue == Integer.MAX_VALUE) {
       maxTargetValue = values.size();
     }
@@ -170,9 +169,7 @@ public class CsvRecordFactory implements
       @Override
       public Integer apply(String from) {
         Integer r = vars.get(from);
-        if (r == null) {
-          throw new IllegalArgumentException("Can't find variable " + from + ", only know about " + vars);
-        }
+        Preconditions.checkArgument(r != null, "Can't find variable %s, only know about %s", from, vars);
         return r;
       }
     }));
@@ -195,14 +192,10 @@ public class CsvRecordFactory implements
         c = typeDictionary.get(typeMap.get(name));
       }
       try {
-        if (c == null) {
-          throw new IllegalArgumentException("Invalid type of variable " + typeMap.get(name)
-            + " wanted one of " + typeDictionary.keySet());
-        }
+        Preconditions.checkArgument(c != null, "Invalid type of variable %s,  wanted one of %s",
+          typeMap.get(name), typeDictionary.keySet());
         Constructor<? extends FeatureVectorEncoder> constructor = c.getConstructor(String.class);
-        if (constructor == null) {
-          throw new IllegalArgumentException("Can't find correct constructor for " + typeMap.get(name));
-        }
+        Preconditions.checkArgument(constructor != null, "Can't find correct constructor for %s", typeMap.get(name));
         FeatureVectorEncoder encoder = constructor.newInstance(name);
         predictorEncoders.put(predictor, encoder);
         encoder.setTraceDictionary(traceDictionary);

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/MixedGradient.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/MixedGradient.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/MixedGradient.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/MixedGradient.java Sun Oct  3 20:53:07 2010
@@ -31,12 +31,11 @@ import java.util.Random;
  * See www.eecs.tufts.edu/~dsculley/papers/combined-ranking-and-regression.pdf
  */
 public class MixedGradient implements Gradient {
-  private double alpha;
 
-  private RankingGradient rank;
-  private Gradient basic;
-
-  Random random = RandomUtils.getRandom();
+  private final double alpha;
+  private final RankingGradient rank;
+  private final Gradient basic;
+  private final Random random = RandomUtils.getRandom();
 
   public MixedGradient(double alpha, int window) {
     this.alpha = alpha;

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/RankingGradient.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/RankingGradient.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/RankingGradient.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/classifier/sgd/RankingGradient.java Sun Oct  3 20:53:07 2010
@@ -38,7 +38,7 @@ public class RankingGradient implements 
 
   private int window = 10;
 
-  private List<Deque<Vector>> history = Lists.newArrayList();
+  private final List<Deque<Vector>> history = Lists.newArrayList();
 
   public RankingGradient(int window) {
     this.window = window;

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDADriver.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDADriver.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDADriver.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDADriver.java Sun Oct  3 20:53:07 2010
@@ -41,6 +41,8 @@ import org.apache.mahout.math.DenseMatri
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Estimates an LDA model from a corpus of documents, which are SparseVectors of word counts. At each phase,
  * it outputs a matrix of log probabilities of each topic.
@@ -99,22 +101,16 @@ public final class LDADriver extends Abs
         int word = key.getSecond();
         if (word == TOPIC_SUM_KEY) {
           logTotals[topic] = value.get();
-          if (Double.isInfinite(value.get())) {
-            throw new IllegalArgumentException();
-          }
+          Preconditions.checkArgument(!Double.isInfinite(value.get()));
         } else if (topic == LOG_LIKELIHOOD_KEY) {
           ll = value.get();
         } else {
-          if (!((topic >= 0) && (word >= 0))) {
-            throw new IllegalArgumentException(topic + " " + word);
-          }
-          if (pWgT.getQuick(topic, word) != 0.0) {
-            throw new IllegalArgumentException();
-          }
+          Preconditions.checkArgument(topic >= 0, "topic should be non-negative, not %d", topic);
+          Preconditions.checkArgument(word >= 0, "word should be non-negative not %d", word);
+          Preconditions.checkArgument(pWgT.getQuick(topic, word) == 0.0);
+
           pWgT.setQuick(topic, word, value.get());
-          if (Double.isInfinite(pWgT.getQuick(topic, word))) {
-            throw new IllegalArgumentException();
-          }
+          Preconditions.checkArgument(!Double.isInfinite(pWgT.getQuick(topic, word)));
         }
       }
       reader.close();

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDAReducer.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDAReducer.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDAReducer.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/clustering/lda/LDAReducer.java Sun Oct  3 20:53:07 2010
@@ -20,6 +20,8 @@ import org.apache.hadoop.io.DoubleWritab
 import org.apache.hadoop.mapreduce.Reducer;
 import org.apache.mahout.common.IntPairWritable;
 
+import com.google.common.base.Preconditions;
+
 /**
  * A very simple reducer which simply logSums the input doubles and outputs a new double for sufficient
  * statistics, and sums log likelihoods.
@@ -36,9 +38,7 @@ public class LDAReducer extends Reducer<
       double accum = 0.0;
       for (DoubleWritable vw : values) {
         double v = vw.get();
-        if (Double.isNaN(v)) {
-          throw new IllegalArgumentException(topicWord.getFirst() + " " + topicWord.getSecond());
-        }
+        Preconditions.checkArgument(!Double.isNaN(v), "Found NaN for topic=(%d,%d)", topicWord.getFirst(), topicWord.getSecond());
         accum += v;
       }
       context.write(topicWord, new DoubleWritable(accum));
@@ -46,17 +46,11 @@ public class LDAReducer extends Reducer<
       double accum = Double.NEGATIVE_INFINITY;
       for (DoubleWritable vw : values) {
         double v = vw.get();
-        if (Double.isNaN(v)) {
-          throw new IllegalArgumentException(topicWord.getFirst() + " " + topicWord.getSecond());
-        }
+        Preconditions.checkArgument(!Double.isNaN(v), "Found NaN for topic = (%d,%d)", topicWord.getFirst(), topicWord.getSecond());
         accum = LDAUtil.logSum(accum, v);
-        if (Double.isNaN(accum)) {
-          throw new IllegalArgumentException(topicWord.getFirst() + " " + topicWord.getSecond());
-        }
+        Preconditions.checkArgument(!Double.isNaN(accum), "Accumulated NaN for topic = (%d,%d)", topicWord.getFirst(), topicWord.getSecond());
       }
       context.write(topicWord, new DoubleWritable(accum));
     }
-    
   }
-  
 }

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/clustering/meanshift/MeanShiftCanopyCreatorMapper.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/clustering/meanshift/MeanShiftCanopyCreatorMapper.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/clustering/meanshift/MeanShiftCanopyCreatorMapper.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/clustering/meanshift/MeanShiftCanopyCreatorMapper.java Sun Oct  3 20:53:07 2010
@@ -20,6 +20,7 @@ package org.apache.mahout.clustering.mea
 import java.io.IOException;
 import java.util.regex.Pattern;
 
+import com.google.common.base.Preconditions;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.io.WritableComparable;
 import org.apache.hadoop.mapreduce.Mapper;
@@ -59,9 +60,10 @@ public class MeanShiftCanopyCreatorMappe
     if (nextCanopyId == -1) {
       String taskId = context.getConfiguration().get("mapred.task.id");
       String[] parts = UNDERSCORE_PATTERN.split(taskId);
-      if (parts.length != 6 || !"attempt".equals(parts[0]) || (!"m".equals(parts[3]) && !"r".equals(parts[3]))) {
-        throw new IllegalArgumentException("TaskAttemptId string : " + taskId + " is not properly formed");
-      }
+      Preconditions.checkArgument(parts.length == 6
+          && "attempt".equals(parts[0])
+          && ("m".equals(parts[3]) || "r".equals(parts[3])),
+          "TaskAttemptId string: %d is not properly formed", taskId);
       nextCanopyId = ((1 << 31) / 50000) * (Integer.parseInt(parts[4]));
       //each mapper has 42,949 ids to give.
     }

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/common/AbstractJob.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/common/AbstractJob.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/common/AbstractJob.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/common/AbstractJob.java Sun Oct  3 20:53:07 2010
@@ -47,6 +47,8 @@ import org.apache.mahout.common.commandl
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>Superclass of many Mahout Hadoop "jobs". A job drives configuration and launch of one or
  * more maps and reduces in order to accomplish some task.</p>
@@ -340,15 +342,10 @@ public abstract class AbstractJob extend
       this.outputPath = new Path(conf.get("mapred.output.dir"));
     }
 
-    if (inputOption != null && inputPath == null) {
-      throw new IllegalArgumentException("No input specified: " + inputOption.getPreferredName()
-          + " or -Dmapred.input.dir must be provided to specify input directory");
-    }
-
-    if (outputOption != null && outputPath == null) {
-      throw new IllegalArgumentException("No output specified: " + outputOption.getPreferredName()
-          + " or -Dmapred.output.dir must be provided to specify output directory");
-    }
+    Preconditions.checkArgument(inputOption == null || inputPath != null,
+        "No input specified or -Dmapred.input.dir must be provided to specify input directory");
+    Preconditions.checkArgument(outputOption == null || outputPath != null,
+        "No output specified:  or -Dmapred.output.dir must be provided to specify output directory" );
   }
 
   protected static void maybePut(Map<String, String> args, CommandLine cmdLine, Option... opt) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/common/distance/MahalanobisDistanceMeasure.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/common/distance/MahalanobisDistanceMeasure.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/common/distance/MahalanobisDistanceMeasure.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/common/distance/MahalanobisDistanceMeasure.java Sun Oct  3 20:53:07 2010
@@ -40,6 +40,7 @@ import org.apache.mahout.math.SingularVa
 import org.apache.mahout.math.VectorWritable;
 import org.apache.mahout.math.MatrixWritable;
 
+import com.google.common.base.Preconditions;
 
 //See http://en.wikipedia.org/wiki/Mahalanobis_distance for details
 public class MahalanobisDistanceMeasure implements DistanceMeasure {
@@ -136,11 +137,9 @@ public class MahalanobisDistanceMeasure 
    * @return Mahalanobis distance of a multivariate vector
    */
   public double distance(Vector v) {
-    if (meanVector == null || inverseCovarianceMatrix == null) {
-      throw new IllegalArgumentException("meanVector or inverseCovarianceMatrix not initialized");
-    }
-    
-    return Math.sqrt(v.minus(meanVector).dot(Algebra.mult(inverseCovarianceMatrix, v.minus(meanVector))));  
+    Preconditions.checkArgument(meanVector != null, "meanVector not initialized");
+    Preconditions.checkArgument(inverseCovarianceMatrix != null, "inverseCovarianceMatrix not initialized");
+    return Math.sqrt(v.minus(meanVector).dot(Algebra.mult(inverseCovarianceMatrix, v.minus(meanVector))));
   }
   
   @Override
@@ -148,10 +147,8 @@ public class MahalanobisDistanceMeasure 
     if (v1.size() != v2.size()) {
       throw new CardinalityException(v1.size(), v2.size());
     }
-    
-    if (meanVector == null || inverseCovarianceMatrix == null) {
-      throw new IllegalArgumentException("meanVector or inverseCovarianceMatrix not initialized");
-    }
+    Preconditions.checkArgument(meanVector != null, "meanVector not initialized");
+    Preconditions.checkArgument(inverseCovarianceMatrix != null, "inverseCovarianceMatrix not initialized");
     
     return Math.sqrt(v1.minus(v2).dot(Algebra.mult(inverseCovarianceMatrix, v1.minus(v2))));
   }
@@ -188,7 +185,7 @@ public class MahalanobisDistanceMeasure 
       if (diagElem > 0.0) {
         sInv.set(i, i, 1 / diagElem);
       } else {
-        throw new IllegalArgumentException("Eigen Value equals to 0 found.");
+        throw new IllegalStateException("Eigen Value equals to 0 found.");
       }
     }
     inverseCovarianceMatrix = svd.getU().times(sInv.times(svd.getU().transpose()));

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/ArrayIterator.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/ArrayIterator.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/ArrayIterator.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/ArrayIterator.java Sun Oct  3 20:53:07 2010
@@ -23,6 +23,8 @@ import java.util.NoSuchElementException;
 
 import org.apache.mahout.cf.taste.impl.common.SkippingIterator;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * Simple, fast {@link Iterator} for an array.
@@ -43,9 +45,8 @@ public final class ArrayIterator<T> impl
    *          array to iterate over
    */
   public ArrayIterator(T[] array) {
-    if (array == null) {
-      throw new IllegalArgumentException("array is null");
-    }
+    Preconditions.checkArgument(array != null, "array is null");
+
     this.array = array; // yeah, not going to copy the array here, for performance
     this.position = 0;
     this.max = array.length;

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/DelegatingIterator.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/DelegatingIterator.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/DelegatingIterator.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/DelegatingIterator.java Sun Oct  3 20:53:07 2010
@@ -19,6 +19,8 @@ package org.apache.mahout.common.iterato
 
 import java.util.Iterator;
 
+import com.google.common.base.Preconditions;
+
 /**
  * An iterator that delegates to another iterator.
  */
@@ -27,9 +29,7 @@ public abstract class DelegatingIterator
   private final Iterator<? extends T> delegate;
   
   protected DelegatingIterator(Iterator<T> delegate) {
-    if (delegate == null) {
-      throw new IllegalArgumentException("delegate is null");
-    }
+    Preconditions.checkArgument(delegate != null, "delegate is null");
     this.delegate = delegate;
   }
   

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorIterable.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorIterable.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorIterable.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorIterable.java Sun Oct  3 20:53:07 2010
@@ -19,6 +19,8 @@ package org.apache.mahout.common.iterato
 
 import java.util.Iterator;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * Simple utility class that makes an {@link Iterator} {@link Iterable} by returning the {@link Iterator}
@@ -38,9 +40,7 @@ public final class IteratorIterable<T> i
    *          {@link Iterator} on which to base this
    */
   public IteratorIterable(Iterator<T> iterator) {
-    if (iterator == null) {
-      throw new IllegalArgumentException("iterator is null");
-    }
+    Preconditions.checkArgument(iterator != null, "iterator is null");
     this.iterator = iterator;
   }
   

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorUtils.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorUtils.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorUtils.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/common/iterator/IteratorUtils.java Sun Oct  3 20:53:07 2010
@@ -25,6 +25,8 @@ import java.util.List;
 
 import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
 
+import com.google.common.base.Preconditions;
+
 /**
  * <p>
  * {@link java.util.Iterator}-related methods without a better home.
@@ -71,9 +73,7 @@ public final class IteratorUtils {
    *         according to the given {@link Comparator}
    */
   public static <K> List<K> iterableToList(Iterable<K> iterable, Comparator<K> comparator) {
-    if (iterable == null) {
-      throw new IllegalArgumentException("iterable is null");
-    }
+    Preconditions.checkArgument(iterable != null, "iterable is null");
     List<K> list;
     if (iterable instanceof Collection<?>) {
       if (iterable instanceof List<?>) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/DecisionForest.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/DecisionForest.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/DecisionForest.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/DecisionForest.java Sun Oct  3 20:53:07 2010
@@ -35,6 +35,8 @@ import org.apache.hadoop.fs.FSDataInputS
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.conf.Configuration;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Represents a forest of decision trees.
  */
@@ -47,10 +49,8 @@ public class DecisionForest implements W
   }
   
   public DecisionForest(List<Node> trees) {
-    if (!((trees != null) && !trees.isEmpty())) {
-      throw new IllegalArgumentException("trees argument must not be null or empty");
-    }
-    
+    Preconditions.checkArgument(trees != null && !trees.isEmpty(), "trees argument must not be null or empty");
+
     this.trees = trees;
   }
   
@@ -62,17 +62,15 @@ public class DecisionForest implements W
    * Classifies the data and calls callback for each classification
    */
   public void classify(Data data, PredictionCallback callback) {
-    if (callback == null) {
-      throw new IllegalArgumentException("callback must not be null");
-    }
-    
+    Preconditions.checkArgument(callback != null, "callback must not be null");
+
     if (data.isEmpty()) {
       return; // nothing to classify
     }
-    
+
     for (int treeId = 0; treeId < trees.size(); treeId++) {
       Node tree = trees.get(treeId);
-      
+
       for (int index = 0; index < data.size(); index++) {
         int prediction = tree.classify(data.get(index));
         callback.prediction(treeId, index, prediction);

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/ErrorEstimate.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/ErrorEstimate.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/ErrorEstimate.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/ErrorEstimate.java Sun Oct  3 20:53:07 2010
@@ -17,6 +17,8 @@
 
 package org.apache.mahout.df;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Various methods to compute from the output of a random forest
  */
@@ -26,25 +28,22 @@ public final class ErrorEstimate {
   }
   
   public static double errorRate(int[] labels, int[] predictions) {
-    if (labels.length != predictions.length) {
-      throw new IllegalArgumentException("labels.length != predictions.length");
-    }
-    
+    Preconditions.checkArgument(labels.length == predictions.length, "labels.length != predictions.length");
     double nberrors = 0; // number of instance that got bad predictions
     double datasize = 0; // number of classified instances
-    
+
     for (int index = 0; index < labels.length; index++) {
       if (predictions[index] == -1) {
         continue; // instance not classified
       }
-      
+
       if (predictions[index] != labels[index]) {
         nberrors++;
       }
-      
+
       datasize++;
     }
-    
+
     return nberrors / datasize;
   }
   
@@ -67,10 +66,8 @@ public final class ErrorEstimate {
    * Counts the number of instance that got bad predictions
    */
   public static int nbErrors(int[] labels, int[] predictions) {
-    if (labels.length != predictions.length) {
-      throw new IllegalArgumentException("labels.length != predictions.length");
-    }
-    
+    Preconditions.checkArgument(labels.length == predictions.length, "labels.length != predictions.length");
+
     int nberrors = 0;
     
     for (int index = 0; index < labels.length; index++) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/callback/SingleTreePredictions.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/callback/SingleTreePredictions.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/callback/SingleTreePredictions.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/callback/SingleTreePredictions.java Sun Oct  3 20:53:07 2010
@@ -19,6 +19,8 @@ package org.apache.mahout.df.callback;
 
 import java.util.Arrays;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Collects the predictions for a single tree
  */
@@ -40,9 +42,7 @@ public class SingleTreePredictions imple
     if (this.treeId == null) {
       this.treeId = treeId;
     } else {
-      if (this.treeId != treeId) {
-        throw new IllegalArgumentException("the predictions does not belong to the same tree");
-      }
+      Preconditions.checkArgument(this.treeId == treeId, "the predictions does not belong to the same tree");
     }
     
     predictions[instanceId] = prediction;

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataConverter.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataConverter.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataConverter.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataConverter.java Sun Oct  3 20:53:07 2010
@@ -25,6 +25,8 @@ import org.apache.mahout.math.DenseVecto
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Preconditions;
+
 /**
  * Converts String to Instance using a Dataset
  */
@@ -43,9 +45,7 @@ public class DataConverter {
     int nball = dataset.nbAttributes() + dataset.getIgnored().length + 1;
     
     StringTokenizer tokenizer = new StringTokenizer(string, ", ");
-    if (tokenizer.countTokens() != nball) {
-      throw new IllegalArgumentException("Wrong number of attributes in the string");
-    }
+    Preconditions.checkArgument(tokenizer.countTokens() == nball, "Wrong number of attributes in the string");
     
     int nbattrs = dataset.nbAttributes();
     DenseVector vector = new DenseVector(nbattrs);

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataLoader.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataLoader.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataLoader.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataLoader.java Sun Oct  3 20:53:07 2010
@@ -23,6 +23,7 @@ import java.util.List;
 import java.util.Scanner;
 import java.util.StringTokenizer;
 
+import com.google.common.base.Preconditions;
 import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
@@ -61,11 +62,8 @@ public final class DataLoader {
    */
   private static Instance parseString(int id, Attribute[] attrs, List<String>[] values, String string) {
     StringTokenizer tokenizer = new StringTokenizer(string, ", ");
-    if (tokenizer.countTokens() != attrs.length) {
-      log.error("{}: {}", id, string);
-      throw new IllegalArgumentException("Wrong number of attributes in the string");
-    }
-    
+    Preconditions.checkArgument(tokenizer.countTokens() == attrs.length, "Wrong number of attributes in the string");
+
     // extract tokens and check is there is any missing value
     String[] tokens = new String[attrs.length];
     for (int attr = 0; attr < attrs.length; attr++) {

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataUtils.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataUtils.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataUtils.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/data/DataUtils.java Sun Oct  3 20:53:07 2010
@@ -17,6 +17,8 @@
 
 package org.apache.mahout.df.data;
 
+import com.google.common.base.Preconditions;
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Random;
@@ -45,10 +47,7 @@ public final class DataUtils {
    * foreach i : array1[i] += array2[i]
    */
   public static void add(int[] array1, int[] array2) {
-    if (array1.length != array2.length) {
-      throw new IllegalArgumentException("array1.length != array2.length");
-    }
-    
+    Preconditions.checkArgument(array1.length == array2.length, "array1.length != array2.length");
     for (int index = 0; index < array1.length; index++) {
       array1[index] += array2[index];
     }
@@ -58,10 +57,7 @@ public final class DataUtils {
    * foreach i : array1[i] -= array2[i]
    */
   public static void dec(int[] array1, int[] array2) {
-    if (array1.length != array2.length) {
-      throw new IllegalArgumentException("array1.length != array2.length");
-    }
-    
+    Preconditions.checkArgument(array1.length == array2.length, "array1.length != array2.length");
     for (int index = 0; index < array1.length; index++) {
       array1[index] -= array2[index];
     }

Modified: mahout/trunk/core/src/main/java/org/apache/mahout/df/data/Dataset.java
URL: http://svn.apache.org/viewvc/mahout/trunk/core/src/main/java/org/apache/mahout/df/data/Dataset.java?rev=1004046&r1=1004045&r2=1004046&view=diff
==============================================================================
--- mahout/trunk/core/src/main/java/org/apache/mahout/df/data/Dataset.java (original)
+++ mahout/trunk/core/src/main/java/org/apache/mahout/df/data/Dataset.java Sun Oct  3 20:53:07 2010
@@ -23,6 +23,7 @@ import java.io.IOException;
 import java.util.Arrays;
 import java.util.List;
 
+import com.google.common.base.Preconditions;
 import org.apache.commons.lang.ArrayUtils;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FSDataInputStream;
@@ -176,13 +177,8 @@ public class Dataset implements Writable
    *          attribute's index
    */
   public int valueOf(int attr, String token) {
-    if (isNumerical(attr)) {
-      throw new IllegalArgumentException("Only for CATEGORICAL attributes");
-    }
-    if (values == null) {
-      throw new IllegalStateException("Values not found");
-    }
-    
+    Preconditions.checkArgument(!isNumerical(attr), "Only for CATEGORICAL attributes");
+    Preconditions.checkArgument(values != null, "Values not found");
     return ArrayUtils.indexOf(values[attr], token);
   }
   
@@ -209,16 +205,10 @@ public class Dataset implements Writable
   }
   
   private static void validateValues(Attribute[] attrs, List<String>[] values) {
-    if (attrs.length != values.length) {
-      throw new IllegalArgumentException("attrs.length != values.length");
-    }
-    
+    Preconditions.checkArgument(attrs.length == values.length,  "attrs.length != values.length");
     for (int attr = 0; attr < attrs.length; attr++) {
-      if (attrs[attr].isCategorical()) {
-        if (values[attr] == null) {
-          throw new IllegalArgumentException("values not found for attribute N° " + attr);
-        }
-      }
+      Preconditions.checkArgument(!attrs[attr].isCategorical() || values[attr] != null,
+          "values not found for attribute " + attr);
     }
   }