From 4b978b2bc0779add3085db8169cf58d56c49acac Mon Sep 17 00:00:00 2001 From: LIS Date: Sun, 14 Apr 2019 21:15:02 -0400 Subject: [PATCH 1/3] first pass at py3 support --- azure_tools/azurepool.py | 14 ++-- azure_tools/bo_wrapper.py | 7 +- azure_tools/common/helpers.py | 3 + ebo_core/bo.py | 8 ++- ebo_core/ebo.py | 32 +++++---- ebo_core/gibbs.py | 14 ++-- ebo_core/helper.py | 4 ++ ebo_core/mondrian.py | 12 ++-- ebo_core/mypool.py | 6 +- gp_tools/gp.py | 9 ++- gp_tools/representation.py | 14 ++-- gp_tools/test_gp_solvers.py | 101 ++++++++++++----------------- test_ebo.py | 10 ++- test_functions/push_function.py | 16 +++-- test_functions/push_utils.py | 6 +- test_functions/rover_function.py | 10 ++- test_functions/rover_utils.py | 12 ++-- test_functions/simple_functions.py | 6 +- 18 files changed, 163 insertions(+), 121 deletions(-) diff --git a/azure_tools/azurepool.py b/azure_tools/azurepool.py index 2a800e7..37ee165 100644 --- a/azure_tools/azurepool.py +++ b/azure_tools/azurepool.py @@ -1,9 +1,9 @@ -from __future__ import print_function + try: import configparser except ImportError: - import ConfigParser as configparser + import configparser as configparser import datetime import os @@ -12,11 +12,11 @@ import azure.batch.batch_auth as batchauth import azure.batch.models as batchmodels -import common.helpers +from . import common.helpers import time try: - import cPickle as pickle + import pickle as pickle except: import pickle import sys @@ -168,7 +168,7 @@ def map(self, parameters, job_id): job_id = common.helpers.generate_unique_resource_name( job_id) common.helpers.delete_blobs_from_container(block_blob_client, self.out) - input_file_names = [os.path.join(self.data_dir, str(i) + '.pk') for i in xrange(len(parameters))] + input_file_names = [os.path.join(self.data_dir, str(i) + '.pk') for i in range(len(parameters))] for i, p in enumerate(parameters): pickle.dump(p, open(input_file_names[i], 'wb')) # input_file_names = [os.path.realpath(fn) for fn in input_file_names] @@ -194,7 +194,7 @@ def map(self, parameters, job_id): # print(os.path.join(self.data_dir, str(0) + '_out.pk')) ret = [] - for i in xrange(len(parameters)): + for i in range(len(parameters)): fnm = os.path.join(self.data_dir, str(i) + '_out.pk') if os.path.isfile(fnm): ret.append(pickle.load(open(fnm))) @@ -312,7 +312,7 @@ def run_commands(batch_client, block_blob_client, job_id, pool_id): id="EBOTask-{}".format(i), command_line=common.helpers.wrap_commands_in_shell('linux', task_commands), user_identity=batchmodels.UserIdentity(auto_user=user)) \ - for i in xrange(len(nodes))] + for i in range(len(nodes))] batch_client.task.add_collection(job.id, tasks) logging.info('task created in seconds {}'.format(time.time() - start)) diff --git a/azure_tools/bo_wrapper.py b/azure_tools/bo_wrapper.py index 22954c8..831db37 100644 --- a/azure_tools/bo_wrapper.py +++ b/azure_tools/bo_wrapper.py @@ -1,10 +1,13 @@ +from __future__ import absolute_import +from __future__ import division from __future__ import print_function + import argparse import os import azure.storage.blob as azureblob try: - import cPickle as pickle + import pickle as pickle except: import pickle @@ -40,7 +43,7 @@ #print(res) pickle.dump(res, open(output_file, 'wb')) - + print("bo_wrapper.py listing files:") for item in os.listdir('.'): print(item) diff --git a/azure_tools/common/helpers.py b/azure_tools/common/helpers.py index 76b2fb5..81f5639 100644 --- a/azure_tools/common/helpers.py +++ b/azure_tools/common/helpers.py @@ -22,7 +22,10 @@ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. +from __future__ import absolute_import +from __future__ import division from __future__ import print_function + import datetime import io import os diff --git a/ebo_core/bo.py b/ebo_core/bo.py index 88b002f..255c78e 100644 --- a/ebo_core/bo.py +++ b/ebo_core/bo.py @@ -1,5 +1,9 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import numpy as np -from gibbs import GibbsSampler +from .gibbs import GibbsSampler from scipy.optimize import minimize @@ -63,7 +67,7 @@ def global_minimize(f, x_range, n, n_bo=1, n_bo_top_percent=1.0): ty = np.hstack((ty, res.fun)) inds = ty.argsort() thres = np.ceil(n_bo * n_bo_top_percent).astype(int) - inds_of_inds = np.hstack((range(thres), np.random.permutation(range(thres, len(inds))))) + inds_of_inds = np.hstack((list(range(thres)), np.random.permutation(list(range(thres, len(inds)))))) inds = inds[inds_of_inds[:n_bo]] return tx[inds, :] diff --git a/ebo_core/ebo.py b/ebo_core/ebo.py index 0c1633e..352a40d 100644 --- a/ebo_core/ebo.py +++ b/ebo_core/ebo.py @@ -1,13 +1,17 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import os import time -import helper +from . import helper import numpy as np -from mondrian import MondrianTree -from mypool import MyPool +from .mondrian import MondrianTree +from .mypool import MyPool try: - import cPickle as pickle + import pickle as pickle except: import pickle from gp_tools.representation import DenseL1Kernel @@ -50,8 +54,8 @@ def get_params(self): def run(self): x_range, T, B, dim_limit, min_leaf_size, max_n_leaves, n_bo, n_top = self.get_params() - tstart = self.X.shape[0] / B - for t in xrange(tstart, T): + tstart = self.X.shape[0] // B + for t in range(tstart, T): # search space partition ref = self.y.min() if self.y.shape[0] > 0 else None self.tree = MondrianTree(self.X, self.y, x_range, max_n_leaves, reference=ref) @@ -71,7 +75,7 @@ def run(self): self.timing.append((self.X.shape[0], elapsed)) # allocate worker budget - newX, newacf, z_all, k_all = zip(*res) + newX, newacf, z_all, k_all = list(zip(*res)) # sync hyper parameters if self.options['gibbs_iter'] != 0: @@ -99,13 +103,13 @@ def run(self): self.pause() def choose_newX(self, newX, newacf, n_top, B): - print + print() 'start choosing newX' start = time.time() inds = newacf.argsort() if 'heuristic' in self.options and self.options['heuristic']: n_top = np.ceil(B / 2.).astype(int) - inds_of_inds = np.hstack((range(n_top), np.random.permutation(range(n_top, len(inds))))) + inds_of_inds = np.hstack((list(range(n_top)), np.random.permutation(list(range(n_top, len(inds)))))) newX = newX[inds[inds_of_inds[:B]]] return newX @@ -143,7 +147,7 @@ def choose_newX(self, newX, newacf, n_top, B): all_candidates = all_candidates[all_candidates != jbest] next_ind += 1 rec.append(marginal) - print + print() 'finished choosing newX, eplased time = ', time.time() - start return newX[good_inds] @@ -163,9 +167,9 @@ def print_step(self, newX, t): if self.options['isplot']: plot_ebo(self.tree, newX, t) _, besty, cur = self.get_best() - print + print() 't=', t, ', bestid=', cur, ', besty=', besty - print + print() 'final z=', self.z, ' final k=', self.k def reload(self): @@ -173,7 +177,7 @@ def reload(self): if not os.path.isfile(fnm): return False self.X, self.y, self.z, self.k, self.timing = pickle.load(open(fnm)) - print + print() 'Successfully reloaded file.' # This will save the pool workers @@ -191,7 +195,7 @@ def save(self): if not os.path.exists(dirnm): os.makedirs(dirnm) pickle.dump([self.X, self.y, self.z, self.k, self.timing], open(fnm, 'wb')) - print + print() 'saving file... ', time.time() - start, ' seconds' diff --git a/ebo_core/gibbs.py b/ebo_core/gibbs.py index abccf0e..6fdbfd2 100644 --- a/ebo_core/gibbs.py +++ b/ebo_core/gibbs.py @@ -1,4 +1,8 @@ -import helper +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from . import helper import numpy as np import sklearn.random_projection as rp from gp_tools.gp import SparseFeatureGP, DenseFeatureGP, DenseKernelGP, SparseKernelGP @@ -71,7 +75,7 @@ def get_tilegp(self): all_cat = np.unique(self.z) if self.tilecap: hashing_mem = self.tilecap / len(all_cat) / nlayers - hashing = [rp.UNH(hashing_mem) for _ in xrange(len(all_cat))] + hashing = [rp.UNH(hashing_mem) for _ in range(len(all_cat))] for a in all_cat: inds = helper.find(self.z == a) indices.append(inds) @@ -109,10 +113,10 @@ def get_tilegp(self): # idea: can instead get log likelihood on different subset of data for gibbs def run(self, niter): - for i in xrange(niter): + for i in range(niter): # sample z w/ limit on size # random permute dimensions - for d in np.random.permutation(range(self.xdim)): + for d in np.random.permutation(list(range(self.xdim))): # sample z_d # initialize final_z = self.z.copy() @@ -130,7 +134,7 @@ def run(self, niter): other_cat = other_cat[np.logical_and(other_cat != zd_old, other_cat != -1)] # otherwise, need to remove z[d] and add one additional category if a_size > 0 and other_cat.size + 1 < self.n_add: - for a in xrange(self.n_add): + for a in range(self.n_add): if (a not in other_cat) and (a != zd_old): other_cat = np.append(other_cat, [a]) break diff --git a/ebo_core/helper.py b/ebo_core/helper.py index bbb2d69..b8077d2 100644 --- a/ebo_core/helper.py +++ b/ebo_core/helper.py @@ -1,4 +1,8 @@ #!/usr/bin/env python +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import numpy as np import scipy.cluster.hierarchy as hi diff --git a/ebo_core/mondrian.py b/ebo_core/mondrian.py index d2a2d52..85450e4 100644 --- a/ebo_core/mondrian.py +++ b/ebo_core/mondrian.py @@ -1,4 +1,8 @@ -import helper +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from . import helper import numpy as np @@ -63,7 +67,7 @@ def grow_tree(self, min_leaf_size): for node in leaves]) mask = np.maximum(prob[:, 1] - min_leaf_size, 0) if mask.sum() == 0: - print + print() 'Mondrian stopped at ', str(len(leaves)), ' number of leaves.' break @@ -90,7 +94,7 @@ def update_leaf_data(self, X, y, ref=None): def visualize(self): if self.leaves is None or self.X.shape[1] != 2: - print + print() 'error: x shape is wrong or leaves is none.' # visaulize 2d mondrians @@ -104,7 +108,7 @@ def visualize(self): mondrian_colors = mondrian_colors / 255.0 fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') - print('number of leaves = {}'.format(len(self.leaves))) + print(('number of leaves = {}'.format(len(self.leaves)))) for node in self.leaves: xy = node.x_range[0] xylen = node.x_range[1] - node.x_range[0] diff --git a/ebo_core/mypool.py b/ebo_core/mypool.py index f5b6e96..a12f810 100644 --- a/ebo_core/mypool.py +++ b/ebo_core/mypool.py @@ -1,4 +1,8 @@ -from bo import bo +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from .bo import bo class MyPool(object): diff --git a/gp_tools/gp.py b/gp_tools/gp.py index 167ffe8..272afdc 100644 --- a/gp_tools/gp.py +++ b/gp_tools/gp.py @@ -1,9 +1,16 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import numpy as np import scipy.linalg import scipy.sparse +try: + import sksparse.cholmod as spch +except ImportError: + pass -# import sksparse.cholmod as spch class SparseFeatureGP: def __init__(self, X, y, sigma, phi): self.X = X diff --git a/gp_tools/representation.py b/gp_tools/representation.py index dd783f2..cee3020 100644 --- a/gp_tools/representation.py +++ b/gp_tools/representation.py @@ -1,4 +1,8 @@ -from itertools import chain, izip +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from itertools import chain import numpy as np from scipy.sparse import csr_matrix @@ -463,7 +467,7 @@ def __init__(self, self.offset = offset if offset is None: self.offset = np.empty((ntiles.shape[1], ntilings)) - for i in xrange(ntiles.shape[0]): + for i in range(ntiles.shape[0]): self.offset[i, :] = -rnd_stream.random_sample(ntilings) / ntiles[0, i] if self.hashing == None: @@ -578,10 +582,10 @@ def __init__(self, self.tilings = [Tiling(in_index, nt, t, self.state_range, rnd_stream, offset=o, hashing=h) for in_index, nt, t, h, o in zip(input_indices, ntiles, ntilings, hashing, offsets)] - self.__size = sum(map(lambda x: x.size, self.tilings)) + self.__size = sum([x.size for x in self.tilings]) self.bias_term = bias_term self.index_offset = np.zeros(len(ntilings), dtype='int') - self.index_offset[1:] = np.cumsum(map(lambda x: x.size, self.tilings[:-1])) + self.index_offset[1:] = np.cumsum([x.size for x in self.tilings[:-1]]) self.index_offset = np.hstack([np.array([off] * t, dtype='int') for off, t in zip(self.index_offset, ntilings)]) @@ -759,7 +763,7 @@ def grid_of_points(state_range, num_centers): if isinstance(num_centers, int): num_centers = [num_centers] * state_range[0].shape[0] points = [np.linspace(start, stop, num, endpoint=True) - for start, stop, num in izip(state_range[0], + for start, stop, num in zip(state_range[0], state_range[1], num_centers)] diff --git a/gp_tools/test_gp_solvers.py b/gp_tools/test_gp_solvers.py index 09cc523..d627106 100644 --- a/gp_tools/test_gp_solvers.py +++ b/gp_tools/test_gp_solvers.py @@ -1,3 +1,7 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import numpy as np import sklearn.random_projection as rp from gp import SparseFeatureGP, DenseFeatureGP, DenseKernelGP, SparseKernelGP @@ -61,7 +65,7 @@ def generate_rp_tilecoding_gps(X, y, sigma, tilecoding, random_proj, include_spa ('Dense Kernel GP', dk_gp)] if include_sparse: sk_gp = SparseKernelGP(X, y, sigma=sigma, kern=sparsekern) - gps = gps + [('Sparse Feature GP', sf_gp), + gps = gps + [('Sparse Feature GP', sk_gp), ('Sparse Kernel GP', sk_gp)] return gps @@ -74,21 +78,19 @@ def compare_nll(gps): all_equal = nll_equal.all() errors = 0 if not all_equal: - for i in xrange(diff_nlls.shape[0]): - for j in xrange(i, diff_nlls.shape[1]): + for i in range(diff_nlls.shape[0]): + for j in range(i, diff_nlls.shape[1]): if not nll_equal[i, j]: errors = errors + 1 - print - 'ERROR: {0}, with nll {1}, differs beyond tolerance from {2}, with nll {3}'.format( - gps[i][0], nlls[i], gps[j][0], nlls[j]) + print('ERROR: {0}, with nll {1}, differs beyond tolerance from {2}, with nll {3}'.format( + gps[i][0], nlls[i], gps[j][0], nlls[j])) return errors def compare_mean_var(test_x, gps): results = [] for n, gp in gps: - print - "Evaluting {0}".format(n) + print("Evaluting {0}".format(n)) results.append(gp.predict(test_x)) # check variance estimates are positive @@ -96,8 +98,7 @@ def compare_mean_var(test_x, gps): for (mu, var), (n, gp) in zip(results, gps): if (var < 0).any(): errors = errors + 1 - print - 'ERROR: Negative variance estimate found in {0}'.format(n) + print('ERROR: Negative variance estimate found in {0}'.format(n)) all_mu = np.hstack([mu for mu, var in results]) all_var = np.hstack([var for mu, var in results]) @@ -106,37 +107,33 @@ def compare_mean_var(test_x, gps): mu_equals = np.isclose(diff_mu, np.zeros_like(diff_mu)) all_mu_equal = mu_equals.all() if not all_mu_equal: - for i in xrange(diff_mu.shape[0]): - for j in xrange(i, diff_mu.shape[1]): + for i in range(diff_mu.shape[0]): + for j in range(i, diff_mu.shape[1]): if not mu_equals[i, j]: errors = errors + 1 - print - 'ERROR: {0} and {1} mean prediction differs, found a max absolute difference of {2}'.format( - gps[i][0], gps[j][0], diff_mu[i, j]) + print('ERROR: {0} and {1} mean prediction differs, found a max absolute difference of {2}'.format( + gps[i][0], gps[j][0], diff_mu[i, j])) diff_var = np.abs(all_var[:, None, :] - all_var[:, :, None]).max(axis=0) var_equals = np.isclose(diff_var, np.zeros_like(diff_var)) all_var_equal = var_equals.all() if not all_var_equal: - for i in xrange(diff_var.shape[0]): - for j in xrange(i, diff_var.shape[1]): + for i in range(diff_var.shape[0]): + for j in range(i, diff_var.shape[1]): if not var_equals[i, j]: errors = errors + 1 - print - 'ERROR: {0} and {1} variance prediction differs, found a max absolute difference of {2}'.format( - gps[i][0], gps[j][0], diff_var[i, j]) + print('ERROR: {0} and {1} variance prediction differs, found a max absolute difference of {2}'.format( + gps[i][0], gps[j][0], diff_var[i, j])) return errors def fit_gps(test_name, gps): for n, gp in gps: try: - print - "Fitting {0} for test '{1}'".format(n, test_name) + print("Fitting {0} for test '{1}'".format(n, test_name)) gp.fit() except: - print - "Exception raise while fitting {0} in test '{1}'".format(n, test_name) + print("Exception raise while fitting {0} in test '{1}'".format(n, test_name)) raise @@ -154,10 +151,8 @@ def create_test_data1(rnd_stream): def test1(rnd_stream): test_name = 'test1' - print - '##########################################################' - print - "Starting test '{0}'".format(test_name) + print('##########################################################') + print("Starting test '{0}'".format(test_name)) t1_sigma = 0.1 t1_ntiles = 5 @@ -179,8 +174,7 @@ def test1(rnd_stream): errors = compare_nll(gps) errors = errors + compare_mean_var(test_x, gps) - print - "Ending test '{0}' with {1} errors".format(test_name, errors) + print("Ending test '{0}' with {1} errors".format(test_name, errors)) return errors @@ -205,10 +199,8 @@ def create_test_data2(rnd_stream): def test2(rnd_stream): test_name = 'test2' - print - '##########################################################' - print - "Starting test '{0}'".format(test_name) + print('##########################################################') + print("Starting test '{0}'".format(test_name)) t2_sigma = 0.1 t2_ntiles = 5 @@ -230,8 +222,7 @@ def test2(rnd_stream): errors = compare_nll(gps) errors = errors + compare_mean_var(test_x, gps) - print - "Ending test '{0}' with {1} errors".format(test_name, errors) + print("Ending test '{0}' with {1} errors".format(test_name, errors)) return errors @@ -256,10 +247,8 @@ def create_test_data3(rnd_stream): def test3(rnd_stream): test_name = 'test3' - print - '##########################################################' - print - "Starting test '{0}'".format(test_name) + print('##########################################################') + print("Starting test '{0}'".format(test_name)) t3_sigma = 0.1 t3_ntiles = 10 @@ -287,8 +276,7 @@ def test3(rnd_stream): errors = compare_nll(gps) errors = errors + compare_mean_var(test_x, gps) - print - "Ending test '{0}' with {1} errors".format(test_name, errors) + print("Ending test '{0}' with {1} errors".format(test_name, errors)) return errors @@ -313,10 +301,8 @@ def create_test_data4(rnd_stream): def test4(rnd_stream): test_name = 'test4' - print - '##########################################################' - print - "Starting test '{0}'".format(test_name) + print('##########################################################') + print("Starting test '{0}'".format(test_name)) t4_sigma = 0.1 t4_ntiles = 10 @@ -338,31 +324,24 @@ def test4(rnd_stream): errors = compare_nll(gps) errors = errors + compare_mean_var(test_x, gps) - print - "Ending test '{0}' with {1} errors".format(test_name, errors) + print("Ending test '{0}' with {1} errors".format(test_name, errors)) return errors -print -'Starting GP solver tests' +print('Starting GP solver tests') # for reproducibility, create a seed and use the corresponding pseudorandom generator seed = np.random.randint(np.iinfo(np.int32).max) rnd_stream = np.random.RandomState(seed) -print -'seed used was {0}'.format(seed) +print('seed used was {0}'.format(seed)) # run test and count errors -errors = sum([test1(rnd_stream), test2(rnd_stream)] +errors = sum([test1(rnd_stream), test2(rnd_stream)]) -print -'##########################################################' -print -'TEST COMPLETE' +print('##########################################################') +print('TEST COMPLETE') if errors > 0: - print -'TOTAL ERROR COUNT: {0}'.format(errors) + print('TOTAL ERROR COUNT: {0}'.format(errors)) else: -print -'No errors found' + print('No errors found') diff --git a/test_ebo.py b/test_ebo.py index 11b8bf7..2c09297 100644 --- a/test_ebo.py +++ b/test_ebo.py @@ -1,3 +1,7 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import numpy as np from ebo_core.ebo import ebo from test_functions.simple_functions import plot_f, SampledGpFunc, sample_z @@ -23,10 +27,10 @@ 'T':10, # number of iterations 'B':10, # number of candidates to be evaluated 'dim_limit':3, # max dimension of the input for each additive function component - 'isplot':1, # 1 if plotting the result; otherwise 0. + 'isplot':1, # 1 if plotting the result; otherwise 0. 'z':None, 'k':None, # group assignment and number of cuts in the Gibbs sampling subroutine 'alpha':1., # hyperparameter of the Gibbs sampling subroutine - 'beta':np.array([5.,2.]), + 'beta':np.array([5.,2.]), 'opt_n':1000, # points randomly sampled to start continuous optimization of acfun 'pid':'test3', # process ID for Azure 'datadir':'tmp_data/', # temporary data directory for Azure @@ -50,5 +54,5 @@ start = time.time() e.run() -print "elapsed time: ", time.time() - start +print("elapsed time: ", time.time() - start) diff --git a/test_functions/push_function.py b/test_functions/push_function.py index 67010ba..06dd0ec 100644 --- a/test_functions/push_function.py +++ b/test_functions/push_function.py @@ -1,4 +1,8 @@ -from push_utils import b2WorldInterface, make_base, create_body, end_effector, run_simulation +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from .push_utils import b2WorldInterface, make_base, create_body, end_effector, run_simulation import numpy as np @@ -26,7 +30,7 @@ def f_max(self): def dx(self): # dimension of the input return self._dx - + def __call__(self, argv): # returns the reward of pushing two objects with two robots rx = float(argv[0]) @@ -43,7 +47,7 @@ def __call__(self, argv): init_angle2 = float(argv[11]) rtor = float(argv[12]) rtor2 = float(argv[13]) - + initial_dist = self.f_max world = b2WorldInterface(True) @@ -61,14 +65,14 @@ def __call__(self, argv): ret1 = np.linalg.norm(np.array(self.gxy) - ret1) ret2 = np.linalg.norm(np.array(self.gxy2) - ret2) - return initial_dist - ret1 - ret2 + return initial_dist - ret1 - ret2 def main(): f = PushReward() x = np.random.uniform(f.xmin, f.xmax) - print('Input = {}'.format(x)) - print('Output = {}'.format(f(x))) + print(('Input = {}'.format(x))) + print(('Output = {}'.format(f(x)))) if __name__ == '__main__': diff --git a/test_functions/push_utils.py b/test_functions/push_utils.py index 41af467..796380f 100644 --- a/test_functions/push_utils.py +++ b/test_functions/push_utils.py @@ -1,3 +1,7 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import numpy as np import pygame from Box2D import * @@ -141,7 +145,7 @@ def get_state(self, verbose=False): list(self.hand.linearVelocity) + [self.hand.angularVelocity] if verbose: print_state = ["%.3f" % x for x in state] - print + print() "position, velocity: (%s), (%s) " % \ ((", ").join(print_state[:3]), (", ").join(print_state[3:])) diff --git a/test_functions/rover_function.py b/test_functions/rover_function.py index 88ecd19..c6a5aa8 100644 --- a/test_functions/rover_function.py +++ b/test_functions/rover_function.py @@ -1,4 +1,8 @@ -from rover_utils import RoverDomain, PointBSpline, ConstObstacleCost, NegGeom, AABoxes, UnionGeom, AdditiveCosts, \ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from .rover_utils import RoverDomain, PointBSpline, ConstObstacleCost, NegGeom, AABoxes, UnionGeom, AdditiveCosts, \ ConstCost import numpy as np @@ -245,8 +249,8 @@ def l2cost(x, point): x_range = f.get_range() x = np.random.uniform(x_range[0], x_range[1]) - print('Input = {}'.format(x)) - print('Output = {}'.format(f(x))) + print(('Input = {}'.format(x))) + print(('Output = {}'.format(f(x)))) if __name__ == "__main__": diff --git a/test_functions/rover_utils.py b/test_functions/rover_utils.py index 76b2c03..2812943 100644 --- a/test_functions/rover_utils.py +++ b/test_functions/rover_utils.py @@ -1,4 +1,6 @@ -from itertools import izip +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function import numpy as np import scipy.interpolate as si @@ -50,11 +52,11 @@ def set_params(self, params, start=None, goal=None): self.tck, u = si.splprep(points, k=3) if start is not None: - for a, sv in izip(self.tck[1], start): + for a, sv in zip(self.tck[1], start): a[0] = sv if goal is not None: - for a, gv in izip(self.tck[1], goal): + for a, gv in zip(self.tck[1], goal): a[-1] = gv def get_points(self, t): @@ -240,7 +242,7 @@ def plot_2d_rover(roverdomain, ngrid_points=100, ntraj_points=100, colormap='RdB # set title to be the total cost plt.title('traj cost: {0}'.format(traj_cost)) - print('traj cost: {0}'.format(traj_cost)) + print(('traj cost: {0}'.format(traj_cost))) # plot cost function cmesh = plt.pcolormesh(grid_points[0], grid_points[1], costs.reshape((ngrid_points, -1)), cmap=colormap) if draw_colorbar: @@ -297,7 +299,7 @@ def plot_3d_forest_rover(roverdomain, rectangles, ntraj_points=100): (roverdomain.start[2], roverdomain.goal[2]), c='k') # plot traj - seg = (zip(traj_points[:-1, :], traj_points[1:, :])) + seg = (list(zip(traj_points[:-1, :], traj_points[1:, :]))) ax.add_collection3d(Line3DCollection(seg, colors=[(0, 1., 0, 1.)] * len(seg))) # plot rectangles diff --git a/test_functions/simple_functions.py b/test_functions/simple_functions.py index bcbf74a..98f2d55 100644 --- a/test_functions/simple_functions.py +++ b/test_functions/simple_functions.py @@ -1,3 +1,7 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + import os import numpy as np @@ -79,7 +83,7 @@ def sample_z(dx): def save_sampled_gp_funcs(dx, n=50, nfunc=1, isplot=1, dirnm='mytests'): - import cPickle as pic + import pickle as pic for i in range(nfunc): sigma = 0.01 z = sample_z(dx) From 4ddfc87c8b95e924b509540a46cb90a76739ca01 Mon Sep 17 00:00:00 2001 From: LIS Date: Sun, 14 Apr 2019 21:18:12 -0400 Subject: [PATCH 2/3] reverted an automated change --- azure_tools/azurepool.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/azure_tools/azurepool.py b/azure_tools/azurepool.py index 37ee165..458bd06 100644 --- a/azure_tools/azurepool.py +++ b/azure_tools/azurepool.py @@ -1,9 +1,11 @@ - +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function try: import configparser except ImportError: - import configparser as configparser + import ConfigParser as configparser import datetime import os From 4cf1e83c64389ef42615c5a33c6e5f7b9fd5f341 Mon Sep 17 00:00:00 2001 From: LIS Date: Sun, 14 Apr 2019 21:19:49 -0400 Subject: [PATCH 3/3] reverted an automated change --- azure_tools/azurepool.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure_tools/azurepool.py b/azure_tools/azurepool.py index 458bd06..153433a 100644 --- a/azure_tools/azurepool.py +++ b/azure_tools/azurepool.py @@ -18,7 +18,7 @@ import time try: - import pickle as pickle + import cPickle as pickle except: import pickle import sys