Skip to content

Commit

Permalink
Python 3 compatibility (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
bqpd committed Dec 18, 2019
1 parent dabac42 commit 3affab1
Show file tree
Hide file tree
Showing 16 changed files with 90 additions and 68 deletions.
18 changes: 9 additions & 9 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../..'))
print sys.path
print(sys.path)

# -- General configuration ------------------------------------------------

Expand Down Expand Up @@ -48,8 +48,8 @@
master_doc = 'index'

# General information about the project.
project = u'GPfit'
copyright = u'2015, MIT Convex Optimization Group'
project = 'GPfit'
copyright = '2015, MIT Convex Optimization Group'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -201,8 +201,8 @@
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'GPfit.tex', u'GPfit Documentation',
u'MIT Convex Optimization Group', 'manual'),
('index', 'GPfit.tex', 'GPfit Documentation',
'MIT Convex Optimization Group', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -231,8 +231,8 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'gpfit', u'GPfit Documentation',
[u'MIT Convex Optimization Group'], 1)
('index', 'gpfit', 'GPfit Documentation',
['MIT Convex Optimization Group'], 1)
]

# If true, show URL addresses after external links.
Expand All @@ -245,8 +245,8 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'GPfit', u'GPfit Documentation',
u'MIT Convex Optimization Group', 'GPfit', 'One line description of project.',
('index', 'GPfit', 'GPfit Documentation',
'MIT Convex Optimization Group', 'GPfit', 'One line description of project.',
'Miscellaneous'),
]

Expand Down
7 changes: 4 additions & 3 deletions docs/source/examples/hoburgabbeel_ex6_1.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"Fits an example function"
from __future__ import division
from numpy import logspace, log, log10, random
from gpfit.fit import fit

Expand All @@ -15,6 +16,6 @@
cSMA, errorSMA = fit(x, y, K, "SMA")
cISMA, errorISMA = fit(x, y, K, "ISMA")

print "MA RMS Error: %.5g" % errorMA
print "SMA RMS Error: %.5g" % errorSMA
print "ISMA RMS Error: %.5g" % errorISMA
print("MA RMS Error: %.5g" % errorMA)
print("SMA RMS Error: %.5g" % errorSMA)
print("ISMA RMS Error: %.5g" % errorISMA)
11 changes: 7 additions & 4 deletions docs/source/examples/hoburgabbeel_ex6_1_output.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
MA fit from params
w = 0.807159 * (u_1)**-0.0703921
w = 0.995106 * (u_1)**-0.431386
w = 0.92288 * (u_1)**-0.247099
SMA fit from params
w**3.4411 = 0.422736 * (u_1)**-2.14843
+ 0.424169 * (u_1)**-2.14784
+ 0.15339 * (u_1)**0.584654
1 = (0.992648/w**0.35353) * (u_1)**-0.204093
+ (0.947302/w**0.0920266) * (u_1)**0.017725
+ (0.961409/w**0.11673) * (u_1)**-0.011164
ISMA fit from params
1 = (0.994797/w**0.238961) * (u_1)**-0.138389
+ (0.949519/w**0.0924504) * (u_1)**0.0165798
+ (0.967646/w**0.115505) * (u_1)**-0.0131876
MA RMS Error: 0.0023556
SMA RMS Error: 2.3856e-05
ISMA RMS Error: 8.0757e-07
ISMA RMS Error: 1.0765e-06
1 change: 1 addition & 0 deletions gpfit/ba_init.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"Implements ba_init"
from __future__ import print_function
from numpy import ones, hstack, zeros, tile, argmin
from numpy.linalg import lstsq, matrix_rank
from numpy.random import permutation as randperm
Expand Down
1 change: 1 addition & 0 deletions gpfit/examples/ex61setup.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import division
from numpy import linspace, logspace, log, exp, log10
from gpfit.fit import fit

Expand Down
2 changes: 1 addition & 1 deletion gpfit/fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def fit(xdata, ydata, K, ftype="ISMA"):
B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]

if ftype == "ISMA":
alpha = 1./params[range(-K, 0)]
alpha = 1./params[list(range(-K, 0))]
for k in range(K):
fitdata["c%d" % k] = exp(alpha[k]*B[k])
fitdata["a%d" % k] = alpha[k]
Expand Down
24 changes: 13 additions & 11 deletions gpfit/fit_constraintset.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
" fit constraint set "
from numpy import amax, array, hstack, where
from __future__ import print_function
from __future__ import division
from gpkit import ConstraintSet
from gpkit import Variable, NomialArray, NamedVariables, VectorVariable
from numpy import amax, array, hstack, where

# pylint: disable=too-many-instance-attributes, too-many-locals,
# pylint: disable=too-many-branches, no-member, import-error
Expand Down Expand Up @@ -41,7 +43,7 @@ def __init__(self, fitdata, ivar=None, dvars=None, name="",
monos = [fitdata["c%d" % k]*NomialArray(array(dvars).T**array(
[fitdata["e%d%d" % (k, i)] for i in
range(fitdata["d"])])).prod(NomialArray(dvars).ndim - 1)
for k in range(fitdata["K"])]
for k in range(fitdata["K"])]

if err_margin == "Max":
self.mfac = Variable("m_{fac-" + name + "-fit}",
Expand Down Expand Up @@ -101,8 +103,8 @@ def get_fitdata(self):
def get_dataframe(self):
" return a pandas DataFrame of fit parameters "
import pandas as pd
df = pd.DataFrame(self.fitdata.values()).transpose()
df.columns = self.fitdata.keys()
df = pd.DataFrame(list(self.fitdata.values())).transpose()
df.columns = list(self.fitdata.keys())
return df

def process_result(self, result):
Expand All @@ -112,9 +114,9 @@ def process_result(self, result):
super(FitCS, self).process_result(result)

if self.mfac not in result["sensitivities"]["constants"]:
return None
return
if amax([abs(result["sensitivities"]["constants"][self.mfac])]) < 1e-5:
return None
return

for dvar in self.dvars:
if isinstance(dvar, NomialArray):
Expand All @@ -135,7 +137,7 @@ def process_result(self, result):
+ " %s bound. Solution is %.4f but"
" bound is %.4f" %
(direct, amax([num]), bnd))
print "Warning: " + msg
print("Warning: " + msg)


class XfoilFit(FitCS):
Expand All @@ -162,11 +164,11 @@ def process_result(self, result):
super(XfoilFit, self).process_result(result)

if self.mfac not in result["sensitivities"]["constants"]:
return None
return
if amax([abs(result["sensitivities"]["constants"][self.mfac])]) < 1e-5:
return None
return
if not self.airfoil:
return None
return

from .xfoilWrapper import xfoil_comparison
cl, re = 0.0, 0.0
Expand All @@ -185,4 +187,4 @@ def process_result(self, result):
" Xfoil cd=%.6f, GP sol cd=%.6f" %
(", ".join(self.ivar.descr["models"]), err[i], re[i],
cl[i], cd[i], cdx[i]))
print "Warning: %s" % msg
print("Warning: %s" % msg)
3 changes: 2 additions & 1 deletion gpfit/implicit_softmax_affine.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"Implements ISMA residual function"
from __future__ import division
from numpy import ones, nan, inf, hstack, dot, tile
from .lse_implicit import lse_implicit

Expand Down Expand Up @@ -27,7 +28,7 @@ def implicit_softmax_affine(x, params):
"""

npt, dimx = x.shape
K = params.size/(dimx+2)
K = params.size//(dimx+2)
ba = params[0:-K]
alpha = params[-K:]
if any(alpha <= 0):
Expand Down
20 changes: 11 additions & 9 deletions gpfit/levenberg_marquardt.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"Implements LM"
from __future__ import print_function
from __future__ import division
from time import time
from sys import float_info
import numpy as np
Expand Down Expand Up @@ -29,7 +31,7 @@ def levenberg_marquardt(residfun, initparams,
initparams: np.array (1D)
Initial fit parameter guesses
verbose: bool
If true, print verbose output
If true, print(verbose output)
lambdainit: float
Initial value for step size penalty lambda
maxiter: int
Expand Down Expand Up @@ -92,19 +94,19 @@ def levenberg_marquardt(residfun, initparams,
'Norm of \n')
print('Iter Residual optimality Lambda'
' step Jwarp \n')
print formatstr1 % (itr, rms, maxgrad)
print(formatstr1 % (itr, rms, maxgrad))

# Main Loop
while True:

if itr == maxiter:
if verbose:
print 'Reached maximum number of iterations'
print('Reached maximum number of iterations')
break

elif time() - t > maxtime:
if verbose:
print 'Reached maxtime (%s seconds)' % maxtime
print('Reached maxtime (%s seconds)' % maxtime)
break
elif (itr >= 2 and
abs(RMStraj[itr] - RMStraj[itr-2]) <
Expand Down Expand Up @@ -155,23 +157,23 @@ def levenberg_marquardt(residfun, initparams,
# dsp here so that all grad info is for updated point,
# but lambda not yet updated
if verbose:
print formatstr % (itr, trialrms, maxgrad, lamb, norm(step),
max(diagJJ)/min(diagJJ))
print(formatstr % (itr, trialrms, maxgrad, lamb, norm(step),
max(diagJJ)/min(diagJJ)))

if maxgrad < tolgrad:
if verbose:
print('1st order optimality attained')
break

if prev_trial_accepted and itr > 1:
lamb = lamb/10
lamb = lamb/10.

prev_trial_accepted = True
params_updated = True
else:
if verbose:
print formatstr % (itr, trialrms, maxgrad, lamb, norm(step),
max(diagJJ)/min(diagJJ))
print(formatstr % (itr, trialrms, maxgrad, lamb, norm(step),
max(diagJJ)/min(diagJJ)))
lamb = lamb*10
prev_trial_accepted = False
params_updated = False
Expand Down
2 changes: 2 additions & 0 deletions gpfit/lse_implicit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"Implements lse_implicit"
from __future__ import print_function
from __future__ import division
from numpy import zeros, spacing, exp, log, tile


Expand Down
1 change: 1 addition & 0 deletions gpfit/lse_scaled.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"Implements lse_scaled"
from __future__ import division
from numpy import tile, exp, log


Expand Down
3 changes: 2 additions & 1 deletion gpfit/max_affine.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"Implements MA residual function"
from __future__ import division
import numpy as np


Expand Down Expand Up @@ -26,7 +27,7 @@ def max_affine(x, ba):
dydba
"""
npt, dimx = x.shape
K = ba.size/(dimx + 1)
K = ba.size//(dimx + 1)
ba = np.reshape(ba, (dimx + 1, K), order='F') # 'F' gives Fortran indexing

# augment data with column of ones
Expand Down
5 changes: 3 additions & 2 deletions gpfit/plot_fit.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"Fit plotting"
import matplotlib.pyplot as plt
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from gpfit.fit import fit
from gpfit.print_fit import print_MA, print_SMA

Expand All @@ -24,7 +25,7 @@ def plot_fit_1d(udata, wdata, K=1, fitclass='MA', plotspace='log'):

if fitclass == 'SMA':
wexps, = cstrt.left.exps
alpha, = wexps.values()
alpha, = list(wexps.values())
uvarkey, = cstrt.right.varkeys
A = [d[uvarkey]/alpha for d in cstrt.right.exps]
B = np.log(cstrt.right.cs) / alpha
Expand Down
20 changes: 12 additions & 8 deletions gpfit/print_fit.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
"Implements functions for raw fit printing from params"
from __future__ import print_function
from numpy import exp


# pylint: disable=invalid-name
def print_ISMA(A, B, alpha, d, K):
"print ISMA fit from params"
"prints ISMA fit from params"
print("ISMA fit from params")
stringList = [None]*K

printString = '1 = '
for k in range(K):
if k > 0:
print printString
print(printString)
printString = ' + '

printString += '({0:.6g}/w**{1:.6g})'.format(exp(alpha[k] * B[k]), alpha[k])
Expand All @@ -20,19 +22,20 @@ def print_ISMA(A, B, alpha, d, K):

stringList[k] = printString

print printString
print(printString)
return stringList


# pylint: disable=invalid-name
def print_SMA(A, B, alpha, d, K):
"print SMA fit from params"
"prints SMA fit from params"
print("SMA fit from params")
stringList = [None]*K

printString = 'w**{0:.6g} = '.format(alpha)
for k in range(K):
if k > 0:
print printString
print(printString)
printString = ' + '

printString += '{0:.6g}'.format(exp(alpha * B[k]))
Expand All @@ -42,13 +45,14 @@ def print_SMA(A, B, alpha, d, K):

stringList[k] = printString

print printString
print(printString)
return stringList


# pylint: disable=invalid-name
def print_MA(A, B, d, K):
"print MA fit from params"
"prints MA fit from params"
print("MA fit from params")
stringList = [None]*K

for k in range(K):
Expand All @@ -58,6 +62,6 @@ def print_MA(A, B, d, K):
printString += ' * (u_{0:d})**{1:.6g}'.format(i+1, A[d*k + i])

stringList[k] = printString
print printString
print(printString)

return stringList
3 changes: 2 additions & 1 deletion gpfit/softmax_affine.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"Implements SMA residual function"
from __future__ import division
from numpy import size, inf, nan, ones, hstack, dot, tile
from .lse_scaled import lse_scaled

Expand Down Expand Up @@ -31,7 +32,7 @@ def softmax_affine(x, params):
alpha = 1/softness
if alpha <= 0:
return inf*ones((npt, 1)), nan
K = size(ba)/(dimx+1)
K = size(ba)//(dimx+1)
ba = ba.reshape(dimx+1, K, order='F')

X = hstack((ones((npt, 1)), x)) # augment data with column of ones
Expand Down
Loading

0 comments on commit 3affab1

Please sign in to comment.