[Scipy-svn] r6917 - trunk/scipy/maxentropy

scipy-svn@scip... scipy-svn@scip...
Sat Nov 20 00:59:50 CST 2010


Author: warren.weckesser
Date: 2010-11-20 00:59:50 -0600 (Sat, 20 Nov 2010)
New Revision: 6917

Modified:
   trunk/scipy/maxentropy/maxentropy.py
   trunk/scipy/maxentropy/maxentutils.py
Log:
ENH: maxentropy: update 'raise' statements

Modified: trunk/scipy/maxentropy/maxentropy.py
===================================================================
--- trunk/scipy/maxentropy/maxentropy.py	2010-11-20 06:45:33 UTC (rev 6916)
+++ trunk/scipy/maxentropy/maxentropy.py	2010-11-20 06:59:50 UTC (rev 6917)
@@ -84,7 +84,7 @@
     def __init__(self):
         self.format = self.__class__.__name__[:4]
         if self.format == 'base':
-            raise ValueError, "this class cannot be instantiated directly"
+            raise ValueError("this class cannot be instantiated directly")
         self.verbose = False
 
         self.maxgtol = 1e-5
@@ -185,13 +185,13 @@
         if isinstance(self, bigmodel):
             # Ensure the sample matrix has been set
             if not hasattr(self, 'sampleF') and hasattr(self, 'samplelogprobs'):
-                raise AttributeError, "first specify a sample feature matrix" \
-                                      " using sampleFgen()"
+                raise AttributeError("first specify a sample feature matrix"
+                                      " using sampleFgen()")
         else:
             # Ensure the feature matrix for the sample space has been set
             if not hasattr(self, 'F'):
-                raise AttributeError, "first specify a feature matrix" \
-                                      " using setfeaturesandsamplespace()"
+                raise AttributeError("first specify a feature matrix"
+                                      " using setfeaturesandsamplespace()")
 
         # First convert K to a numpy array if necessary
         K = np.asarray(K, float)
@@ -226,9 +226,9 @@
 
         elif algorithm == 'LBFGSB':
             if callback is not None:
-                raise NotImplementedError, "L-BFGS-B optimization algorithm"\
-                        " does not yet support callback functions for"\
-                        " testing with an external sample"
+                raise NotImplementedError("L-BFGS-B optimization algorithm"
+                        " does not yet support callback functions for"
+                        " testing with an external sample")
             retval = optimize.fmin_l_bfgs_b(dual, oldparams, \
                         grad, args=(), bounds=self.bounds, pgtol=self.maxgtol,
                         maxfun=self.maxfun)
@@ -268,9 +268,9 @@
             (newparams, fopt, numiter, func_calls, warnflag) = retval
 
         else:
-            raise AttributeError, "the specified algorithm '" + str(algorithm) \
-                    + "' is unsupported.  Options are 'CG', 'LBFGSB', " \
-                    "'Nelder-Mead', 'Powell', and 'BFGS'"
+            raise AttributeError("the specified algorithm '" + str(algorithm)
+                    + "' is unsupported.  Options are 'CG', 'LBFGSB', "
+                    "'Nelder-Mead', 'Powell', and 'BFGS'")
 
         if np.any(self.params != newparams):
             self.setparams(newparams)
@@ -397,9 +397,9 @@
 
         if not self.callingback and self.external is None:
             if self.mindual > -np.inf and self.dual() < self.mindual:
-                raise DivergenceError, "dual is below the threshold 'mindual'" \
-                        " and may be diverging to -inf.  Fix the constraints" \
-                        " or lower the threshold!"
+                raise DivergenceError("dual is below the threshold 'mindual'"
+                        " and may be diverging to -inf.  Fix the constraints"
+                        " or lower the threshold!")
 
         self.iters += 1
 
@@ -543,7 +543,7 @@
             elif hasattr(self, 'K'):
                 m = len(self.K)
             else:
-                raise ValueError, "specify the number of features / parameters"
+                raise ValueError("specify the number of features / parameters")
 
         # Set parameters, clearing cache variables
         self.setparams(np.zeros(m, float))
@@ -596,7 +596,7 @@
 
         # Check whether the params are NaN
         if not np.all(self.params == self.params):
-            raise FloatingPointError, "some of the parameters are NaN"
+            raise FloatingPointError("some of the parameters are NaN")
 
         if self.verbose:
             print "Saving parameters ..."
@@ -642,8 +642,8 @@
         if f is not None and samplespace is not None:
             self.setfeaturesandsamplespace(f, samplespace)
         elif f is not None and samplespace is None:
-            raise ValueError, "not supported: specify both features and" \
-                    " sample space or neither"
+            raise ValueError("not supported: specify both features and"
+                    " sample space or neither")
 
 
     def setfeaturesandsamplespace(self, f, samplespace):
@@ -674,7 +674,7 @@
 
         # Has F = {f_i(x_j)} been precomputed?
         if not hasattr(self, 'F'):
-            raise AttributeError, "first create a feature matrix F"
+            raise AttributeError("first create a feature matrix F")
 
         # Good, assume the feature matrix exists
         log_p_dot = innerprodtranspose(self.F, self.params)
@@ -693,7 +693,7 @@
         """
         # For discrete models, use the representation E_p[f(X)] = p . F
         if not hasattr(self, 'F'):
-            raise AttributeError, "first set the feature matrix F"
+            raise AttributeError("first set the feature matrix F")
 
         # A pre-computed matrix of features exists
         p = self.pmf()
@@ -707,7 +707,7 @@
         """
         # Have the features already been computed and stored?
         if not hasattr(self, 'F'):
-            raise AttributeError, "first set the feature matrix F"
+            raise AttributeError("first set the feature matrix F")
 
         # Yes:
         # p(x) = exp(params.f(x)) / sum_y[exp params.f(y)]
@@ -763,8 +763,8 @@
             try:
                 f = self.f
             except AttributeError:
-                raise AttributeError, "either pass a list f of feature" \
-                           " functions or set this as a member variable self.f"
+                raise AttributeError("either pass a list f of feature"
+                           " functions or set this as a member variable self.f")
 
         # Do we have a prior distribution p_0?
         priorlogpmf = None
@@ -772,7 +772,7 @@
             try:
                 priorlogpmf = self.priorlogpmf
             except AttributeError:
-                raise AttributeError, "prior probability mass function not set"
+                raise AttributeError("prior probability mass function not set")
 
         def p(x):
             f_x = np.array([f[i](x) for i in range(len(f))], float)
@@ -887,9 +887,9 @@
                         # Try converting to a row vector
                         p_tilde = count.reshape((1, size))
                     except AttributeError:
-                        raise ValueError, "the 'counts' object needs to be a"\
-                            " row vector (1 x n) rank-2 array/matrix) or have"\
-                            " a .reshape method to convert it into one"
+                        raise ValueError("the 'counts' object needs to be a"
+                            " row vector (1 x n) rank-2 array/matrix) or have"
+                            " a .reshape method to convert it into one")
                 else:
                     p_tilde = counts
         # Make a copy -- don't modify 'counts'
@@ -927,7 +927,7 @@
         S = self.numsamplepoints
         # Has F = {f_i(x_j)} been precomputed?
         if not hasattr(self, 'F'):
-            raise AttributeError, "first create a feature matrix F"
+            raise AttributeError("first create a feature matrix F")
 
         # Good, assume F has been precomputed
 
@@ -1030,7 +1030,7 @@
         self.p_tilde_context[w].
         """
         if not hasattr(self, 'F'):
-            raise AttributeError, "need a pre-computed feature matrix F"
+            raise AttributeError("need a pre-computed feature matrix F")
 
         # A pre-computed matrix of features exists
 
@@ -1060,7 +1060,7 @@
         """
         # Have the features already been computed and stored?
         if not hasattr(self, 'F'):
-            raise AttributeError, "first set the feature matrix F"
+            raise AttributeError("first set the feature matrix F")
 
         # p(x | c) = exp(theta.f(x, c)) / sum_c[exp theta.f(x, c)]
         #      = exp[log p_dot(x) - logsumexp{log(p_dot(y))}]
@@ -1167,7 +1167,7 @@
         try:
             len(output)
         except TypeError:
-            raise ValueError, "output of sampleFgen.next() not recognized"
+            raise ValueError("output of sampleFgen.next() not recognized")
         if len(output) == 2:
             # Assume the format is (F, lp)
             (self.sampleF, self.samplelogprobs) = output
@@ -1175,7 +1175,7 @@
             # Assume the format is (F, lp, sample)
             (self.sampleF, self.samplelogprobs, self.sample) = output
         else:
-            raise ValueError, "output of sampleFgen.next() not recognized"
+            raise ValueError("output of sampleFgen.next() not recognized")
 
         # Check whether the number m of features is correct
         try:
@@ -1188,8 +1188,8 @@
             self.reset(m)
         else:
             if self.sampleF.shape[0] != m:
-                raise ValueError, "the sample feature generator returned" \
-                                  " a feature matrix of incorrect dimensions"
+                raise ValueError("the sample feature generator returned"
+                                  " a feature matrix of incorrect dimensions")
         if self.verbose >= 3:
             print "(done)"
 
@@ -1522,7 +1522,7 @@
         try:
             a_k = self.a_0
         except AttributeError:
-            raise AttributeError, "first define the initial step size a_0"
+            raise AttributeError("first define the initial step size a_0")
 
         avgparams = self.params
         if self.exacttest:

Modified: trunk/scipy/maxentropy/maxentutils.py
===================================================================
--- trunk/scipy/maxentropy/maxentutils.py	2010-11-20 06:45:33 UTC (rev 6916)
+++ trunk/scipy/maxentropy/maxentutils.py	2010-11-20 06:59:50 UTC (rev 6917)
@@ -261,7 +261,7 @@
     elif format in ('dok_matrix', 'csc_matrix', 'csr_matrix'):
         sparseF = sparse.dok_matrix((m, n))
     else:
-        raise ValueError, "sparse matrix format not recognized"
+        raise ValueError("sparse matrix format not recognized")
 
     for i in xrange(m):
         f_i = f[i]
@@ -327,7 +327,7 @@
     except ValueError:
         (p, q) = vshape
     if n != p:
-        raise TypeError, "matrix dimensions are incompatible"
+        raise TypeError("matrix dimensions are incompatible")
     if isinstance(v, ndarray):
         try:
             # See if A is sparse
@@ -348,7 +348,7 @@
     elif sparse.isspmatrix(v):
         return A * v
     else:
-        raise TypeError, "unsupported types for inner product"
+        raise TypeError("unsupported types for inner product")
 
 
 def innerprodtranspose(A,v):
@@ -374,8 +374,8 @@
             innerprod = numpy.empty(n, float)
             A.matvec_transp(v, innerprod)
         else:
-            raise TypeError, "innerprodtranspose(A,v) requires that v be " \
-                    "a vector (rank-1 dense array) if A is sparse."
+            raise TypeError("innerprodtranspose(A,v) requires that v be "
+                    "a vector (rank-1 dense array) if A is sparse.")
         return innerprod
     elif sparse.isspmatrix(A):
         return A.rmatvec(v).transpose()
@@ -396,7 +396,7 @@
                 x = numpy.dot(numpy.transpose(v), A)
                 return numpy.transpose(x)
         else:
-            raise TypeError, "unsupported types for inner product"
+            raise TypeError("unsupported types for inner product")
 
 
 def rowmeans(A):
@@ -421,8 +421,8 @@
         try:
             n = A.shape[1]
         except AttributeError:
-            raise TypeError, \
-                    "rowmeans() only works with sparse and dense arrays"
+            raise TypeError("rowmeans() only works with sparse and dense "
+                            "arrays")
         rowsum = innerprod(A, numpy.ones(n, float))
         return rowsum / float(n)
 
@@ -448,8 +448,8 @@
         try:
             m = A.shape[0]
         except AttributeError:
-            raise TypeError, \
-                    "columnmeans() only works with sparse and dense arrays"
+            raise TypeError("columnmeans() only works with sparse and dense "
+                            "arrays")
         columnsum = innerprodtranspose(A, numpy.ones(m, float))
         return columnsum / float(m)
 
@@ -475,8 +475,8 @@
         try:
             m = A.shape[0]
         except AttributeError:
-            raise TypeError, \
-                    "columnvariances() only works with sparse and dense arrays"
+            raise TypeError("columnvariances() only works with sparse "
+                            "and dense arrays")
         means = columnmeans(A)
         return columnmeans((A-means)**2) * (m/(m-1.0))
 



More information about the Scipy-svn mailing list