Changeset 13461


Ignore:
Timestamp:
Sep 12, 2019 12:49:34 PM (3 months ago)
Author:
randersson
Message:

#5819 Performed 2to3 on the entire src/Python directory in order to make the code compatible. I've not reviewed all changes while doing this commit but will do while starting to run the tests. I'm not sure everything is converted correctly, for example the change in test_casadi_collocation row 1610.

Location:
branches/dev-5819/Python
Files:
70 edited

Legend:

Unmodified
Added
Removed
  • branches/dev-5819/Python/setup.py

    r683 r13461  
    4040    modified = False
    4141    hi_rev = -1
    42     lo_rev = sys.maxint
     42    lo_rev = sys.maxsize
    4343    for s in status:
    4444        if s.is_versioned and s.entry:
     
    7575    if not package_dir:
    7676        if path:
    77             return apply(os.path.join, path)
     77            return os.path.join(*path)
    7878        else:
    7979            return ''
     
    8888            else:
    8989                tail.insert(0, pdir)
    90                 return apply(os.path.join, tail)
     90                return os.path.join(*tail)
    9191        else:
    9292            # Oops, got all the way through 'path' without finding a
     
    102102
    103103            if tail:
    104                 return apply(os.path.join, tail)
     104                return os.path.join(*tail)
    105105            else:
    106106                return ''
  • branches/dev-5819/Python/src/pyjmi/__init__.py

    r9809 r13461  
    4949try:
    5050    _f = os.path.join(os.environ['JMODELICA_HOME'],'startup.py')
    51     execfile(_f)
     51    exec(compile(open(_f, "rb").read(), _f, 'exec'))
    5252except IOError:
    5353    logging.warning('Startup script ''%s'' not found. Environment may be corrupt'
     
    8080        modelicacasadi_present = False
    8181    if modelicacasadi_present:
    82         from casadi_interface import (OptimizationProblem,
     82        from .casadi_interface import (OptimizationProblem,
    8383                                      transfer_to_casadi_interface,
    8484                                      transfer_optimization_problem,
  • branches/dev-5819/Python/src/pyjmi/casadi_interface.py

    r11370 r13461  
    335335        mx_zero = casadi.MX(0.)
    336336        for par in mvar_par:
    337             for i in xrange(dae.numel()):
     337            for i in range(dae.numel()):
    338338                eq = mx_zero
    339339                for vk in var_kinds:
     
    351351        # Add sensitivity initial equations
    352352        for par in mvar_par:
    353             for i in xrange(init.numel()):
     353            for i in range(init.numel()):
    354354                init_eq = mx_zero
    355355                for vk in var_kinds:
     
    497497                i.
    498498        """
    499         time_points = map(casadi.MX, time_points)
     499        time_points = list(map(casadi.MX, time_points))
    500500        sensitivities = N.array([[self.getVariable('d%s/d%s' % (var, par)) for par in parameters] for var in outputs])
    501501        timed_mx_vars = [N.array([[casadi.MX.sym(sens.getName() + "(%s)" % tp.getValue()) for sens in sensitivities[i]]
    502                                   for i in xrange(len(outputs))]) for tp in time_points]
     502                                  for i in range(len(outputs))]) for tp in time_points]
    503503        timed_sens = []
    504         for i in xrange(len(time_points)):
     504        for i in range(len(time_points)):
    505505            timed_sens_i = []
    506             for j in xrange(len(outputs)):
     506            for j in range(len(outputs)):
    507507                timed_sens_ij = []
    508                 for k in xrange(len(parameters)):
     508                for k in range(len(parameters)):
    509509                    tv = ci.TimedVariable(self, timed_mx_vars[i][j, k], sensitivities[j, k], time_points[i])
    510510                    self.addTimedVariable(tv)
     
    551551        # Create sensitivity and Fisher matrices
    552552        Q = []
    553         for j in xrange(len(outputs)):
     553        for j in range(len(outputs)):
    554554            Q.append(casadi.vertcat([casadi.horzcat([s.getVar() for s in timed_sens[i][j]])
    555                                      for i in xrange(len(time_points))]))
    556         Fisher = sum([sigma[i, j] * casadi.mul(Q[i].T, Q[j]) for i in xrange(len(outputs))
    557                       for j in xrange(len(outputs))])
     555                                     for i in range(len(time_points))]))
     556        Fisher = sum([sigma[i, j] * casadi.mul(Q[i].T, Q[j]) for i in range(len(outputs))
     557                      for j in range(len(outputs))])
    558558
    559559        # Define the objective
  • branches/dev-5819/Python/src/pyjmi/examples/bounds_kinsol.py

    r5126 r13461  
    4646    try:
    4747        m.initialize()
    48         print 'Initialized OK'
     48        print('Initialized OK')
    4949    except:
    50         print 'Error in initialize'
     50        print('Error in initialize')
    5151   
    5252    # Parse the entire XML log
     
    5656    solves = gather_solves(log)
    5757   
    58     print 'Number of iterations in solver without bounds:',\
    59             len(solves[0].block_solves[0].iterations), '+', len(solves[0].block_solves[1].iterations)
     58    print('Number of iterations in solver without bounds:',\
     59            len(solves[0].block_solves[0].iterations), '+', len(solves[0].block_solves[1].iterations))
    6060   
    61     print 'Solution: x_1=', m.get('x_1'),' x_2=', m.get('x_2')
     61    print('Solution: x_1=', m.get('x_1'),' x_2=', m.get('x_2'))
    6262   
    6363    nbr_iterations = len(solves[0].block_solves[0].iterations)
    6464    iteration_points = numpy.zeros(shape=(nbr_iterations,2))
    6565   
    66     for i in xrange(nbr_iterations):
     66    for i in range(nbr_iterations):
    6767        iteration_points[i] = solves[0].block_solves[0].iterations[i].ivs
    6868   
     
    8787    try:
    8888        m.initialize()
    89         print 'Initialized OK'
     89        print('Initialized OK')
    9090    except:
    91         print 'Error in initialize'
     91        print('Error in initialize')
    9292   
    9393    # Parse the entire XML log
     
    9797    solves = gather_solves(log)
    9898   
    99     print 'Number of iterations in solver with bounds:',\
    100             len(solves[0].block_solves[0].iterations), '+', len(solves[0].block_solves[1].iterations)
     99    print('Number of iterations in solver with bounds:',\
     100            len(solves[0].block_solves[0].iterations), '+', len(solves[0].block_solves[1].iterations))
    101101   
    102     print 'Solution: x_1=', m.get('x_1'),' x_2=', m.get('x_2')
     102    print('Solution: x_1=', m.get('x_1'),' x_2=', m.get('x_2'))
    103103   
    104104    nbr_iterations = len(solves[0].block_solves[0].iterations)
    105105    iteration_points = numpy.zeros(shape=(nbr_iterations,2))
    106106   
    107     for i in xrange(nbr_iterations):
     107    for i in range(nbr_iterations):
    108108        iteration_points[i] = solves[0].block_solves[0].iterations[i].ivs
    109109   
     
    127127        X,Y = meshgrid(x, y)
    128128        Z = (X**2 + Y**2 - 25)**2 + ((X - 5)**2 + (Y - 2)**2 - 4)**2
    129         contour_levels = [4**n for n in xrange(1,6)]
     129        contour_levels = [4**n for n in range(1,6)]
    130130        contour(X,Y,Z, contour_levels, colors='b')
    131131        show()
  • branches/dev-5819/Python/src/pyjmi/examples/ccpp_elimination.py

    r10316 r13461  
    116116    eliminables = op.getEliminableVariables()
    117117    algebraics = op.getVariables(op.REAL_ALGEBRAIC)
    118     print "Number of algebraics:  ",len(algebraics)
    119 
    120     print "Eliminating variables!"
     118    print("Number of algebraics:  ",len(algebraics))
     119
     120    print("Eliminating variables!")
    121121   
    122122    eliminable_algebraics = [a for a in algebraics if a in eliminables]
     
    139139    #op.eliminateAlgebraics()   
    140140   
    141     print "Done with elimination"
     141    print("Done with elimination")
    142142    eliminated_vars = op.getEliminatedVariables()
    143     print "Number of variables that were eliminated: ", len(eliminated_vars)   
     143    print("Number of variables that were eliminated: ", len(eliminated_vars))   
    144144   
    145145   
  • branches/dev-5819/Python/src/pyjmi/examples/cstr_casadi.py

    r9053 r13461  
    9090    # Print some data for stationary point A
    9191    print(' *** Stationary point A ***')
    92     print('Tc = %f' % Tc_0_A)
    93     print('c = %f' % c_0_A)
    94     print('T = %f' % T_0_A)
     92    print(('Tc = %f' % Tc_0_A))
     93    print(('c = %f' % c_0_A))
     94    print(('T = %f' % T_0_A))
    9595   
    9696    # Set inputs for Stationary point B
     
    107107    # Print some data for stationary point B
    108108    print(' *** Stationary point B ***')
    109     print('Tc = %f' % Tc_0_B)
    110     print('c = %f' % c_0_B)
    111     print('T = %f' % T_0_B)
     109    print(('Tc = %f' % Tc_0_B))
     110    print(('c = %f' % c_0_B))
     111    print(('T = %f' % T_0_B))
    112112   
    113113    ### 2. Compute initial guess trajectories by means of simulation
  • branches/dev-5819/Python/src/pyjmi/examples/cstr_constrained_mhe_example.py

    r7612 r13461  
    156156        unconstr_x_est_t = unconstr_MHE_object.step(u_t, y_t)
    157157        #Add the results to x_est
    158         for key in constr_x_est.keys():
     158        for key in list(constr_x_est.keys()):
    159159            constr_x_est[key].append(constr_x_est_t[key])
    160         for key in unconstr_x_est.keys():
     160        for key in list(unconstr_x_est.keys()):
    161161            unconstr_x_est[key].append(unconstr_x_est_t[key])
    162162        ###Prepare the simulation
     
    166166       
    167167        #Set the initial values of the states
    168         for (key, list)in x.items():
     168        for (key, list)in list(x.items()):
    169169            model.set('_start_' + key, list[-1])
    170170       
     
    176176   
    177177        #Extract the state values from the result object
    178         for key in x.keys():
     178        for key in list(x.keys()):
    179179            x[key].append(res[key][-1])
    180180        #reset the FMU
  • branches/dev-5819/Python/src/pyjmi/examples/cstr_mhe_example.py

    r7612 r13461  
    158158       
    159159        #Add the results to x_est
    160         for key in x_est.keys():
     160        for key in list(x_est.keys()):
    161161            x_est[key].append(x_est_t[key])
    162162       
     
    167167       
    168168        #Set the initial values of the states
    169         for (key, list)in x.items():
     169        for (key, list)in list(x.items()):
    170170            model.set('_start_' + key, list[-1])
    171171       
     
    176176   
    177177        #Extract the state values from the result object
    178         for key in x.keys():
     178        for key in list(x.keys()):
    179179            x[key].append(res[key][-1])
    180180        #reset the FMU
  • branches/dev-5819/Python/src/pyjmi/examples/cstr_mpc_casadi.py

    r8187 r13461  
    156156        # the next sample period with the optimal input u_k
    157157        sim_model.reset()
    158         sim_model.set(x_k.keys(), x_k.values())
     158        sim_model.set(list(x_k.keys()), list(x_k.values()))
    159159        sim_res = sim_model.simulate(start_time=k*sample_period,
    160160                                     final_time=(k+1)*sample_period,
  • branches/dev-5819/Python/src/pyjmi/examples/distillation1_fmu.py

    r4051 r13461  
    5353    t   = res['time']
    5454   
    55     print "t = ", repr(N.array(t))
    56     print "x16 = ", repr(N.array(x16))
    57     print "x32 = ", repr(N.array(x32))
    58     print "y16 = ", repr(N.array(y16))
    59     print "y32 = ", repr(N.array(y32))
     55    print("t = ", repr(N.array(t)))
     56    print("x16 = ", repr(N.array(x16)))
     57    print("x32 = ", repr(N.array(x32)))
     58    print("y16 = ", repr(N.array(y16)))
     59    print("y32 = ", repr(N.array(y32)))
    6060
    6161    if with_plots:
  • branches/dev-5819/Python/src/pyjmi/examples/distillation2_fmu.py

    r4051 r13461  
    4545    t   = res['time']
    4646   
    47     print "t = ", repr(N.array(t))
    48     print "x16 = ", repr(N.array(x16))
    49     print "x32 = ", repr(N.array(x32))
     47    print("t = ", repr(N.array(t)))
     48    print("x16 = ", repr(N.array(x16)))
     49    print("x32 = ", repr(N.array(x32)))
    5050
    5151    if with_plots:
  • branches/dev-5819/Python/src/pyjmi/examples/distillation4_fmu.py

    r6608 r13461  
    5454    t   = res['time']
    5555   
    56     print "t = ", repr(N.array(t))
    57     print "x20 = ", repr(N.array(x20))
    58     print "x40 = ", repr(N.array(x40))
     56    print("t = ", repr(N.array(t)))
     57    print("x20 = ", repr(N.array(x20)))
     58    print("x40 = ", repr(N.array(x40)))
    5959   
    60     print "T20 = ", repr(N.array(T20))
    61     print "T40 = ", repr(N.array(T40))
     60    print("T20 = ", repr(N.array(T20)))
     61    print("T40 = ", repr(N.array(T40)))
    6262
    63     print "V20 = ", repr(N.array(V20))
    64     print "V40 = ", repr(N.array(V40))
     63    print("V20 = ", repr(N.array(V20)))
     64    print("V40 = ", repr(N.array(V40)))
    6565   
    6666    if with_plots:
  • branches/dev-5819/Python/src/pyjmi/examples/distillation4_opt.py

    r10316 r13461  
    9292    Q_fac = 1e-3
    9393
    94     print('T_14_ref: %.6f' % T_14_ref)
    95     print('T_28_ref: %.6f' % T_28_ref)
     94    print(('T_14_ref: %.6f' % T_14_ref))
     95    print(('T_28_ref: %.6f' % T_28_ref))
    9696
    9797    # Plot simulation
     
    205205        plt.figure(2)
    206206        plt.hold(True)
    207         for i in xrange(1, 43):
    208             temperature = (ss_res.final('Temp[' + `i` + ']') +
     207        for i in range(1, 43):
     208            temperature = (ss_res.final('Temp[' + repr(i) + ']') +
    209209                           ss_res.initial('absolute_zero'))
    210210            plt.plot(temperature, 43 - i, 'ko')
     
    225225    break_model.set('Q_elec_ref', Q_ref)
    226226    break_model.set('Vdot_L1_ref', L_vol_ref)
    227     for i in xrange(1, 43):
     227    for i in range(1, 43):
    228228        break_model.set('xA_init[%d]' % i, ss_res.final('xA[%d]' % i))
    229229
     
    256256    ref_model.set('Q_elec_ref', Q_ref)
    257257    ref_model.set('Vdot_L1_ref', L_vol_ref)
    258     for i in xrange(1, 43):
    259         ref_model.set('xA_init[' + `i` + ']',
    260                       break_res.final('xA[' + `i` + ']'))
     258    for i in range(1, 43):
     259        ref_model.set('xA_init[' + repr(i) + ']',
     260                      break_res.final('xA[' + repr(i) + ']'))
    261261
    262262    # Simulate
     
    286286    op.set('Q_elec_ref', Q_ref)
    287287    op.set('Vdot_L1_ref', L_vol_ref)
    288     for i in xrange(1, 43):
    289         op.set('xA_init[' + `i` + ']', break_res.final('xA[' + `i` + ']'))
     288    for i in range(1, 43):
     289        op.set('xA_init[' + repr(i) + ']', break_res.final('xA[' + repr(i) + ']'))
    290290
    291291    # Set optimization options and solve
     
    325325    verif_model.set('Q_elec_ref', Q_ref)
    326326    verif_model.set('Vdot_L1_ref', L_vol_ref)
    327     for i in xrange(1, 43):
    328         verif_model.set('xA_init[' + `i` + ']',
    329                         break_res.final('xA[' + `i` + ']'))
     327    for i in range(1, 43):
     328        verif_model.set('xA_init[' + repr(i) + ']',
     329                        break_res.final('xA[' + repr(i) + ']'))
    330330
    331331    # Simulate with optimal input
  • branches/dev-5819/Python/src/pyjmi/examples/furuta_dfo.py

    r10190 r13461  
    124124   
    125125    # Print optimal parameter values and optimal function value
    126     print 'Optimal parameter values:'
    127     print 'arm friction coefficient = ' + str(armFrictionCoefficient_opt)
    128     print 'pendulum friction coefficient = ' + str(pendulumFrictionCoefficient_opt)
    129     print 'Optimal function value: ' + str(f_opt)
    130     print ' '
     126    print('Optimal parameter values:')
     127    print('arm friction coefficient = ' + str(armFrictionCoefficient_opt))
     128    print('pendulum friction coefficient = ' + str(pendulumFrictionCoefficient_opt))
     129    print('Optimal function value: ' + str(f_opt))
     130    print(' ')
    131131   
    132132    # Load model
  • branches/dev-5819/Python/src/pyjmi/examples/logger_example.py

    r6169 r13461  
    4545    m.set('u1',3)
    4646
    47     print 'u1' + str(m.get('u1'))
    48     print 'x1' + str(m.get('x1'))
    49     print 'y1' + str(m.get('y1'))
    50     print 'z1' + str(m.get('z1'))
     47    print('u1' + str(m.get('u1')))
     48    print('x1' + str(m.get('x1')))
     49    print('y1' + str(m.get('y1')))
     50    print('z1' + str(m.get('z1')))
    5151
    5252    m.set('y1',0.)
     
    5454    m.initialize()
    5555
    56     print "model initialized"
     56    print("model initialized")
    5757
    58     print 'u1' + str(m.get('u1'))
    59     print 'x1' + str(m.get('x1'))
    60     print 'y1' + str(m.get('y1'))
    61     print 'z1' + str(m.get('z1'))
     58    print('u1' + str(m.get('u1')))
     59    print('x1' + str(m.get('x1')))
     60    print('y1' + str(m.get('y1')))
     61    print('z1' + str(m.get('z1')))
    6262
    6363    m.set('u1',4)
    6464
    65     print "Input set"
     65    print("Input set")
    6666
    67     print 'u1' + str(m.get('u1'))
    68     print 'x1' + str(m.get('x1'))
    69     print 'y1' + str(m.get('y1'))
    70     print 'z1' + str(m.get('z1'))
     67    print('u1' + str(m.get('u1')))
     68    print('x1' + str(m.get('x1')))
     69    print('y1' + str(m.get('y1')))
     70    print('z1' + str(m.get('z1')))
    7171
    7272    m.get_derivatives()
     
    7474    m.set('y1',0.5)
    7575
    76     print "Set initial value of y1"
     76    print("Set initial value of y1")
    7777
    78     print 'x1' + str(m.get('x1'))
    79     print 'y1' + str(m.get('y1'))
    80     print 'z1' + str(m.get('z1'))
     78    print('x1' + str(m.get('x1')))
     79    print('y1' + str(m.get('y1')))
     80    print('z1' + str(m.get('z1')))
    8181
    8282    m.set('p',0.5)
    8383
    84     print "Set initial value of p"
     84    print("Set initial value of p")
    8585
    86     print 'x1' + str(m.get('x1'))
    87     print 'y1' + str(m.get('y1'))
    88     print 'z1' + str(m.get('z1'))
     86    print('x1' + str(m.get('x1')))
     87    print('y1' + str(m.get('y1')))
     88    print('z1' + str(m.get('z1')))
    8989
    9090    # Parse the log file and print some of its contents
     
    9797    log = parse_jmi_log(log_file_name)
    9898
    99     print
    100     print 'Top log node:        log =', log
    101     print 'Unnamed sub nodes:   log.nodes = ['
     99    print()
     100    print('Top log node:        log =', log)
     101    print('Unnamed sub nodes:   log.nodes = [')
    102102    for node in log.nodes:
    103         print '   ', node, ','
    104     print ']'
     103        print('   ', node, ',')
     104    print(']')
    105105
    106106    # Gather information pertaining to equation solves
    107107    solves = gather_solves(log)
    108108
    109     print
    110     print 'Number of solver invocations:',                      len(solves)
    111     print 'Time of first solve:',                               solves[0].t
    112     print 'Number of block solves in first solver invocation:', len(solves[0].block_solves)
    113     print 'Names of iteration variables in first block solve:', solves[0].block_solves[0].variables
    114     print 'Min bounds in first block solve:',                   solves[0].block_solves[0].min
    115     print 'Max bounds in first block solve:',                   solves[0].block_solves[0].max
    116     print 'Initial residual scaling in first block solve:',     solves[0].block_solves[0].initial_residual_scaling
    117     print 'Number of iterations in first block solve:',         len(solves[0].block_solves[0].iterations)
    118     print
    119     print 'First iteration in first block solve: '
    120     print '  Iteration variables:',              solves[0].block_solves[0].iterations[0].ivs
    121     print '  Scaled residuals:',                 solves[0].block_solves[0].iterations[0].scaled_residuals
    122     print '  Jacobian:\n',                       solves[0].block_solves[0].iterations[0].jacobian
    123     print '  Jacobian updated in iteration:',    solves[0].block_solves[0].iterations[0].jacobian_updated
    124     print '  Residual scaling factors:',         solves[0].block_solves[0].iterations[0].residual_scaling
    125     print '  Residual scaling factors_updated:', solves[0].block_solves[0].iterations[0].residual_scaling_updated
    126     print '  Scaled residual norm:',             solves[0].block_solves[0].iterations[0].scaled_residual_norm
     109    print()
     110    print('Number of solver invocations:',                      len(solves))
     111    print('Time of first solve:',                               solves[0].t)
     112    print('Number of block solves in first solver invocation:', len(solves[0].block_solves))
     113    print('Names of iteration variables in first block solve:', solves[0].block_solves[0].variables)
     114    print('Min bounds in first block solve:',                   solves[0].block_solves[0].min)
     115    print('Max bounds in first block solve:',                   solves[0].block_solves[0].max)
     116    print('Initial residual scaling in first block solve:',     solves[0].block_solves[0].initial_residual_scaling)
     117    print('Number of iterations in first block solve:',         len(solves[0].block_solves[0].iterations))
     118    print()
     119    print('First iteration in first block solve: ')
     120    print('  Iteration variables:',              solves[0].block_solves[0].iterations[0].ivs)
     121    print('  Scaled residuals:',                 solves[0].block_solves[0].iterations[0].scaled_residuals)
     122    print('  Jacobian:\n',                       solves[0].block_solves[0].iterations[0].jacobian)
     123    print('  Jacobian updated in iteration:',    solves[0].block_solves[0].iterations[0].jacobian_updated)
     124    print('  Residual scaling factors:',         solves[0].block_solves[0].iterations[0].residual_scaling)
     125    print('  Residual scaling factors_updated:', solves[0].block_solves[0].iterations[0].residual_scaling_updated)
     126    print('  Scaled residual norm:',             solves[0].block_solves[0].iterations[0].scaled_residual_norm)
    127127
    128128if __name__ == "__main__":
  • branches/dev-5819/Python/src/pyjmi/examples/planar_pendulum.py

    r4921 r13461  
    5757
    5858    if maxerr > 1e-6:
    59         print "Maximum error: ", maxerr
     59        print("Maximum error: ", maxerr)
    6060        assert maxerr < 1e-4
    6161   
  • branches/dev-5819/Python/src/pyjmi/examples/qt_par_est_casadi.py

    r7194 r13461  
    166166
    167167    # Print and assert estimated parameter values
    168     print('a1: ' + str(a1_opt*1e4) + 'cm^2')
    169     print('a2: ' + str(a2_opt*1e4) + 'cm^2')
     168    print(('a1: ' + str(a1_opt*1e4) + 'cm^2'))
     169    print(('a2: ' + str(a2_opt*1e4) + 'cm^2'))
    170170    a_ref = [0.02656702, 0.02713898]
    171171    N.testing.assert_allclose(1e4 * N.array([a1_opt, a2_opt]),
  • branches/dev-5819/Python/src/pyjmi/examples/qt_par_est_dfo.py

    r4657 r13461  
    182182
    183183    # Print optimal parameter values and optimal function value
    184     print 'Optimal parameter values:'
    185     print 'a1 = ' + str(a1_opt*1e4) + ' cm^2'
    186     print 'a2 = ' + str(a2_opt*1e4) + ' cm^2'
    187     print 'Optimal function value: ' + str(f_opt)
    188     print ' '
     184    print('Optimal parameter values:')
     185    print('a1 = ' + str(a1_opt*1e4) + ' cm^2')
     186    print('a2 = ' + str(a2_opt*1e4) + ' cm^2')
     187    print('Optimal function value: ' + str(f_opt))
     188    print(' ')
    189189
    190190    model = load_fmu(fmu_name)
     
    288288
    289289    # Print optimal parameters and function value
    290     print 'Optimal parameter values:'
    291     print 'a1 = ' + str(a1_opt*1e4) + ' cm^2'
    292     print 'a2 = ' + str(a2_opt*1e4) + ' cm^2'
    293     print 'a3 = ' + str(a3_opt*1e4) + ' cm^2'
    294     print 'a4 = ' + str(a4_opt*1e4) + ' cm^2'
    295     print 'Optimal function value: ' + str(f_opt)
    296     print ' '
     290    print('Optimal parameter values:')
     291    print('a1 = ' + str(a1_opt*1e4) + ' cm^2')
     292    print('a2 = ' + str(a2_opt*1e4) + ' cm^2')
     293    print('a3 = ' + str(a3_opt*1e4) + ' cm^2')
     294    print('a4 = ' + str(a4_opt*1e4) + ' cm^2')
     295    print('Optimal function value: ' + str(f_opt))
     296    print(' ')
    297297
    298298    model = load_fmu(fmu_name)
  • branches/dev-5819/Python/src/pyjmi/examples/ukf_vdp.py

    r7828 r13461  
    128128    MSEx2 = N.sum(((N.array(x2_estimate) - N.array(x2_process))**2))/len(x2_estimate)
    129129   
    130     print
    131     print 'Mean square error x1: '+str(MSEx1)
    132     print 'Mean square error x2: '+str(MSEx2)
    133     print
     130    print()
     131    print('Mean square error x1: '+str(MSEx1))
     132    print('Mean square error x2: '+str(MSEx2))
     133    print()
    134134
    135135    #Plot simulation results
  • branches/dev-5819/Python/src/pyjmi/jmi.py

    r11370 r13461  
    4646
    4747from pyjmi.common.io import VariableNotFoundError as jmiVariableNotFoundError
     48from functools import reduce
    4849
    4950#Check to see if pyfmi is installed so that we also catch the error generated
  • branches/dev-5819/Python/src/pyjmi/jmi_algorithm_drivers.py

    r9821 r13461  
    247247                warm_start = False
    248248            if not warm_start:
    249                 print("Warning: The provided initial guess for the dual " +
     249                print(("Warning: The provided initial guess for the dual " +
    250250                      "variables will not be used since warm start is not " +
    251                       "enabled for IPOPT.")
     251                      "enabled for IPOPT."))
    252252
    253253        # Check validity of blocking_factors
     
    259259                            "match the number of collocation elements.")
    260260            elif isinstance(self.blocking_factors, BlockingFactors):
    261                 for (name, facs) in self.blocking_factors.factors.iteritems():
     261                for (name, facs) in self.blocking_factors.factors.items():
    262262                    var = self.op.getVariable(name)
    263263                    if var is None:
     
    308308       
    309309        # Check validity of nominal_traj_mode
    310         for name in self.nominal_traj_mode.keys():
     310        for name in list(self.nominal_traj_mode.keys()):
    311311            if name != "_default_mode":
    312312                var = self.op.getVariable(name)
     
    344344        Helper function that sets options for the solver.
    345345        """
    346         for (k, v) in self.solver_options.iteritems():
     346        for (k, v) in self.solver_options.items():
    347347            self.nlp.set_solver_option(k, v)
    348348           
     
    812812             
    813813        #Print times
    814         print("\nTotal time for %s samples (average time in parenthesis)."
    815                 %(nbr_samp))
    816         print("\nInitialization time: %.2f seconds" %times['init'])
    817         print("\nTotal time: %.2f seconds             (%.3f)" % (times['tot'],
    818                 times['tot']/(nbr_samp)))
    819         print("Pre-processing time: %.2f seconds    (%.3f)" % (times['update'],
    820                 times['update']/(nbr_samp)))
    821         print("Solution time: %.2f seconds          (%.3f)" % (times['sol'],
    822                 times['sol']/(nbr_samp)))
    823         print("Post-processing time: %.2f seconds   (%.3f)" %
    824                 (times['post_processing'], times['post_processing']/(nbr_samp)))
    825         print("\nLargest total time for one sample (nbr %s): %.2f seconds" %
    826                 (times['maxSample'], times['maxTime']))
    827         print("The sample period is %.2f seconds\n" %sample_period)
     814        print(("\nTotal time for %s samples (average time in parenthesis)."
     815                %(nbr_samp)))
     816        print(("\nInitialization time: %.2f seconds" %times['init']))
     817        print(("\nTotal time: %.2f seconds             (%.3f)" % (times['tot'],
     818                times['tot']/(nbr_samp))))
     819        print(("Pre-processing time: %.2f seconds    (%.3f)" % (times['update'],
     820                times['update']/(nbr_samp))))
     821        print(("Solution time: %.2f seconds          (%.3f)" % (times['sol'],
     822                times['sol']/(nbr_samp))))
     823        print(("Post-processing time: %.2f seconds   (%.3f)" %
     824                (times['post_processing'], times['post_processing']/(nbr_samp))))
     825        print(("\nLargest total time for one sample (nbr %s): %.2f seconds" %
     826                (times['maxSample'], times['maxTime'])))
     827        print(("The sample period is %.2f seconds\n" %sample_period))
  • branches/dev-5819/Python/src/pyjmi/jmi_io.py

    r9809 r13461  
    2525import scipy.io
    2626
    27 import jmi
     27from . import jmi
    2828from pyjmi.common.io import ResultWriter
    2929from pyjmi.common import xmlparser
     
    592592        #Write the point
    593593        str_text = (" %.14E" % data[0])
    594         for j in xrange(self._nvariables_without_sens-1):
     594        for j in range(self._nvariables_without_sens-1):
    595595            if rescale:
    596596                str_text = str_text + (" %.14E" %(data[1+j]*sc[j+n_parameters]))
     
    598598                str_text = str_text + (" %.14E" % data[1+j])
    599599
    600         for j in xrange(self._nvariables_total-self._nvariables_without_sens):
     600        for j in range(self._nvariables_total-self._nvariables_without_sens):
    601601            if rescale:
    602602                str_text = str_text + (" %.14E" %(data[j+self._nvariables_without_sens]*sens_sc[j]))
  • branches/dev-5819/Python/src/pyjmi/linearization.py

    r9809 r13461  
    2525import pyjmi.jmi as jmi
    2626from pyjmi.common.core import TrajectoryLinearInterpolation
     27from functools import reduce
    2728
    2829int = N.int32
     
    226227   
    227228    # Substitute named variables with vector variables in expressions
    228     named_vars = reduce(list.__add__, named_mvar_struct.values())
     229    named_vars = reduce(list.__add__, list(named_mvar_struct.values()))
    229230    mvar_struct = OrderedDict()
    230231    mvar_struct["time"] = casadi.MX.sym("time")
     
    281282    #Sort Values for reference point
    282283    stop=False
    283     for vt in z0.keys():
     284    for vt in list(z0.keys()):
    284285        RefPoint[vt] = N.zeros(n_var[vt])
    285286        passed_indices = list()
     
    304305               
    305306    missing_types = [vt for vt in var_kinds \
    306                      if vt not in z0.keys() and n_var[vt]!=0]
     307                     if vt not in list(z0.keys()) and n_var[vt]!=0]
    307308    if len(missing_types) !=0:
    308309        sys.stderr.write("Error: Please provide the following types in z0:\n")
     
    474475   
    475476    # Substitute named variables with vector variables in expressions
    476     named_vars = reduce(list.__add__, named_mvar_struct.values())
     477    named_vars = reduce(list.__add__, list(named_mvar_struct.values()))
    477478    mvar_struct = OrderedDict()
    478479    mvar_struct["time"] = casadi.MX.sym("time")
     
    532533                data = sim_result.result_data.get_variable_data(name)
    533534            except (pyfmi.common.io.VariableNotFoundError, pyjmi.common.io.VariableNotFoundError):
    534                 print("Warning: Could not find initial " +
     535                print(("Warning: Could not find initial " +
    535536                      "trajectory for variable " + name +
    536537                      ". Using initialGuess attribute value " +
    537                       "instead.")
     538                      "instead."))
    538539                ordinates = N.array([[
    539540                    op.get_attr(var, "initialGuess")]])
  • branches/dev-5819/Python/src/pyjmi/log/__init__.py

    r6917 r13461  
    2020"""
    2121
    22 from parser import parse_xml_log, parse_jmi_log, extract_jmi_log
    23 from jmi_log import gather_solves
    24 from prettyprinter import prettyprint_to_file
     22from .parser import parse_xml_log, parse_jmi_log, extract_jmi_log
     23from .jmi_log import gather_solves
     24from .prettyprinter import prettyprint_to_file
    2525
    2626__all__=['parser','tree','jmi_log','prettyprinter']
  • branches/dev-5819/Python/src/pyjmi/log/parser.py

    r6917 r13461  
    2222import re
    2323import numpy as np
    24 from tree import *
     24from .tree import *
    2525
    2626
     
    155155    except sax.SAXException as e:
    156156        if accept_errors:
    157             print 'Warning: Failure during parsing of XML JMI log:\n', e
    158             print 'Parsed log will be incomplete.'
     157            print('Warning: Failure during parsing of XML JMI log:\n', e)
     158            print('Parsed log will be incomplete.')
    159159        else:
    160160            raise Exception('Failed to parse XML JMI log:\n' + repr(e))
     
    180180    except sax.SAXException as e:
    181181        if accept_errors:
    182             print 'Warning: Failure during parsing of XML JMI log:\n', e
    183             print 'Parsed log will be incomplete'
     182            print('Warning: Failure during parsing of XML JMI log:\n', e)
     183            print('Parsed log will be incomplete')
    184184        else:
    185185            raise Exception('Failed to parse XML JMI log:\n' + repr(e))
  • branches/dev-5819/Python/src/pyjmi/log/prettyprinter.py

    r6917 r13461  
    2020
    2121from numpy import ndarray
    22 from tree import *
     22from .tree import *
    2323
    2424def prettyprint(write, node):
  • branches/dev-5819/Python/src/pyjmi/log/tree.py

    r6917 r13461  
    2828    """
    2929    def __init__(self, text):
    30         assert isinstance(text, basestring)
     30        assert isinstance(text, str)
    3131        self.text = text
    3232
     
    4343
    4444    def __init__(self, type):
    45         assert isinstance(type, basestring)
     45        assert isinstance(type, str)
    4646        self.type  = type
    4747        self.nodes = []
     
    6262    def __repr__(self):
    6363        return ('<' + self.type + ' node with ' + repr(len(self.nodes))
    64                 + ' subnodes, and named subnodes ' + repr(self.dict.keys()) + '>')
     64                + ' subnodes, and named subnodes ' + repr(list(self.dict.keys())) + '>')
    6565
    6666
     
    8686        types may be a string or list of strings.
    8787        """
    88         if isinstance(types, basestring):
     88        if isinstance(types, str):
    8989            types = [types]
    9090
  • branches/dev-5819/Python/src/pyjmi/optimization/assimulo_shooting.py

    r6917 r13461  
    2828    from openopt import NLP
    2929except ImportError:
    30     print "Could not load OpenOpt."
     30    print("Could not load OpenOpt.")
    3131   
    3232
     
    165165       
    166166        if self.verbosity >= Multiple_Shooting.SCREAM:
    167             print 'Calculating cost...'
    168             print 'Input u:', u[-1]
    169             print 'Input y: ', y[-1,:-1]
     167            print('Calculating cost...')
     168            print('Input u:', u[-1])
     169            print('Input y: ', y[-1,:-1])
    170170       
    171171        start_time = (self.final_time-self.start_time)/self.gridsize*(self.gridsize-1)
     
    189189       
    190190        if  self.verbosity >= Multiple_Shooting.WHISPER:
    191             print 'Evaluating cost:', cost
     191            print('Evaluating cost:', cost)
    192192        #if  self.verbosity >= Multiple_Shooting.SCREAM:
    193193        #    print 'Evaluating cost: (u, y) = ', u[-1], ys[-1]
     
    203203       
    204204        if self.verbosity >= Multiple_Shooting.SCREAM:
    205             print 'Calculating constraints...'
    206             print 'Input u:', u
    207             print 'Input y: ', y
     205            print('Calculating constraints...')
     206            print('Input u:', u)
     207            print('Input y: ', y)
    208208       
    209209        y_calc = N.array([])
     
    229229           
    230230        if self.verbosity >= Multiple_Shooting.SCREAM:
    231             print 'Equility constraints: ', cons.sum()
     231            print('Equility constraints: ', cons.sum())
    232232
    233233        return cons
     
    252252       
    253253        if self.verbosity >= Multiple_Shooting.NORMAL:
    254             print 'Initial parameter vector: '
    255             print p0
    256             print 'Lower bound:', len(lbound)
    257             print 'Upper bound:', len(ubound)
     254            print('Initial parameter vector: ')
     255            print(p0)
     256            print('Lower bound:', len(lbound))
     257            print('Upper bound:', len(ubound))
    258258
    259259        # Get OpenOPT handler
  • branches/dev-5819/Python/src/pyjmi/optimization/casadi_collocation.py

    r9326 r13461  
    3434from collections import OrderedDict, Iterable
    3535from scipy.sparse import csc_matrix, csr_matrix
     36from functools import reduce
    3637
    3738try:
     
    467468        cnt = 0
    468469        var_indices = self.get_var_indices()
    469         for i in xrange(1, self.n_e + 1):
    470             for k in self.time_points[i].keys():
     470        for i in range(1, self.n_e + 1):
     471            for k in list(self.time_points[i].keys()):
    471472                dx_opt[cnt, :] = self.primal_opt[var_indices[i][k]['dx']][:, 0]
    472473                x_opt[cnt, :] = self.primal_opt[var_indices[i][k]['x']][:, 0]
     
    494495        # Consider: do we actually need to save _xi, _ti, and _hi in self?
    495496        if self.hs == "free":
    496             self._hi = map(lambda h: self.horizon * h, self.h_opt)
     497            self._hi = [self.horizon * h for h in self.h_opt]
    497498        else:
    498             self._hi = map(lambda h: self.horizon * h, self.h)
     499            self._hi = [self.horizon * h for h in self.h]
    499500        self._xi = self._u_opt[1:].reshape(self.n_e, self.n_cp, self.model.n_u)
    500501        self._ti = N.cumsum([self.t0] + self._hi[1:])
     
    508509
    509510            x = 0
    510             for k in xrange(self.n_cp):
     511            for k in range(self.n_cp):
    511512                x += xi[i - 1, k, :] * self.pol.eval_basis(k + 1, tau, False)
    512513            return x
     
    781782        quad_pen = copy.deepcopy(quad_pen)
    782783        for variable_list in [eliminated, constr_quad_pen, quad_pen]:
    783             for (name, data) in variable_list.items():
     784            for (name, data) in list(variable_list.items()):
    784785                variable_list[name] = _create_trajectory_function(data)
    785786
     
    896897        """
    897898        # Check that factors exist for variables with bounds and penalties
    898         for name in du_bounds.keys():
    899             if name not in factors.keys():
     899        for name in list(du_bounds.keys()):
     900            if name not in list(factors.keys()):
    900901                raise ValueError('Bound provided for variable %s' % name +
    901902                                 'but no factors.')
    902         for name in du_quad_pen.keys():
    903             if name not in factors.keys():
     903        for name in list(du_quad_pen.keys()):
     904            if name not in list(factors.keys()):
    904905                raise ValueError('Penalty weight provided for variable ' +
    905906                                 '%s but no factors.' % name)
     
    10831084            new_constr_quad_pen = OrderedDict()
    10841085            new_variable_lists = [new_eliminated, new_quad_pen, new_constr_quad_pen]
    1085             for i in xrange(3):
    1086                 for name in variable_lists[i].keys():
     1086            for i in range(3):
     1087                for name in list(variable_lists[i].keys()):
    10871088                    var = op.getVariable(name)
    10881089                    if var is None:
     
    11051106        else:
    11061107            input_names = [u.getName() for u in mvar_vectors['u']]
    1107             elim_names = self.external_data.eliminated.keys()
     1108            elim_names = list(self.external_data.eliminated.keys())
    11081109            elim_vars = [op.getModelVariable(elim_name)
    11091110                         for elim_name in elim_names]
     
    11321133            for (vk, source) in (('constr_u', self.external_data.constr_quad_pen),
    11331134                                 ('quad_pen', self.external_data.quad_pen)):
    1134                 mvar_vectors[vk] = [op.getVariable(name) for (name, data) in source.iteritems()]
     1135                mvar_vectors[vk] = [op.getVariable(name) for (name, data) in source.items()]
    11351136                n_var[vk] = len(mvar_vectors[vk])
    11361137        else:
     
    11431144                                 ('constr_u', self.external_data.constr_quad_pen),
    11441145                                 ('quad_pen', self.external_data.quad_pen)):
    1145                 for (j, name) in enumerate(source.iterkeys()):
     1146                for (j, name) in enumerate(source.keys()):
    11461147                    self.external_data_name_map[name] = (j, vk)
    11471148
     
    12001201
    12011202        # Append name of variables into a list
    1202         named_vars = reduce(list.__add__, named_mvar_struct.values() +
     1203        named_vars = reduce(list.__add__, list(named_mvar_struct.values()) +
    12031204                            [named_mvar_struct_dx])           
    12041205
     
    12451246        # Create BlockingFactors from self.blocking_factors
    12461247        if isinstance(self.blocking_factors, Iterable):
    1247             factors = dict(zip(
     1248            factors = dict(list(zip(
    12481249                    [var.getName() for var in mvar_vectors['unelim_u']],
    1249                     n_var['unelim_u'] * [self.blocking_factors]))
     1250                    n_var['unelim_u'] * [self.blocking_factors])))
    12501251            self.blocking_factors = BlockingFactors(factors)
    12511252
     
    13661367                self.var_indices[varType][i] = dict()
    13671368                self.var_map[varType][i]['all'] = xx[0:0]
    1368                 for k in xrange(n_discrete_points):
     1369                for k in range(n_discrete_points):
    13691370                    self.var_map[varType][i][k+move_zero] = dict()
    13701371                    self.var_indices[varType][i][k+move_zero] = list()
     
    14241425        # Count NLP variables
    14251426        n_xx = n_popt
    1426         n_xx += (1 + self.n_e * self.n_cp) * N.sum(nlp_n_var.values())
     1427        n_xx += (1 + self.n_e * self.n_cp) * N.sum(list(nlp_n_var.values()))
    14271428        if self.eliminate_der_var:
    14281429            n_xx += nlp_n_var['x'] # dx_1_0
    14291430        if self.blocking_factors is not None:
    14301431            n_xx += (1 + self.n_e * self.n_cp) * n_cont_u
    1431             for factors in self.blocking_factors.factors.values():
     1432            for factors in list(self.blocking_factors.factors.values()):
    14321433                n_xx += len(factors)
    14331434        if not self.eliminate_cont_var:
     
    14361437        if self.is_gauss:
    14371438            n_xx += (self.n_e - 1) * nlp_n_var['x'] # Mesh points
    1438             n_xx += N.sum(nlp_n_var.values()) # tf
     1439            n_xx += N.sum(list(nlp_n_var.values())) # tf
    14391440        if self.hs == "free":
    14401441            n_xx += self.n_e
     
    14901491                if self.blocking_factors is not None:
    14911492                    count_us=(1+self.n_e * self.n_cp) * n_cont_u
    1492                     for factors in self.blocking_factors.factors.values():
     1493                    for factors in list(self.blocking_factors.factors.values()):
    14931494                        count_us += len(factors)
    14941495                    global_split_indices.append(
     
    15721573                var for var in mvar_vectors['unelim_u']
    15731574                if var.getName() not in
    1574                 self.blocking_factors.factors.keys()]
     1575                list(self.blocking_factors.factors.keys())]
    15751576           
    15761577            var_indices['u_cont'] = dict()
    1577             for i in xrange(1, self.n_e + 1):
     1578            for i in range(1, self.n_e + 1):
    15781579                var_indices['u_cont'][i]=dict()
    1579                 for k in xrange(1, self.n_cp + 1):
     1580                for k in range(1, self.n_cp + 1):
    15801581                    new_index = counter_s + n_cont_u
    1581                     var_indices['u_cont'][i][k] = range(counter_s, new_index)
     1582                    var_indices['u_cont'][i][k] = list(range(counter_s, new_index))
    15821583                    counter_s = new_index
    15831584
     
    15871588            # Create index storage for inputs with blocking factors
    15881589            var_indices['u_bf'] = dict()
    1589             for i in xrange(1, self.n_e + 1):
     1590            for i in range(1, self.n_e + 1):
    15901591                var_indices['u_bf'][i] = dict()
    1591                 for k in xrange(1, self.n_cp + 1):
     1592                for k in range(1, self.n_cp + 1):
    15921593                    var_indices['u_bf'][i][k]= []
    15931594                   
    15941595                   
    15951596            # Index controls with blocking factors
    1596             for name in self.blocking_factors.factors.keys():
     1597            for name in list(self.blocking_factors.factors.keys()):
    15971598                var = self.op.getVariable(name)
    15981599                element = 1
    15991600                factors = self.blocking_factors.factors[name]
    16001601                for (factor_i, factor) in enumerate(factors):
    1601                     for i in xrange(element, element + factor):
    1602                         for k in xrange(1, self.n_cp + 1):
     1602                    for i in range(element, element + factor):
     1603                        for k in range(1, self.n_cp + 1):
    16031604                            var_indices['u_bf'][i][k].append(counter_s)
    16041605
     
    16091610                   
    16101611            # Weave indices for inputs with and without blocking factors
    1611             for i in xrange(1, self.n_e + 1):
     1612            for i in range(1, self.n_e + 1):
    16121613                var_indices[varType][i]=dict()
    1613                 for k in xrange(1, self.n_cp + 1):
     1614                for k in range(1, self.n_cp + 1):
    16141615                    i_cont = 0
    16151616                    i_bf = 0
     
    16301631           
    16311632            # Add inputs to variable map
    1632             for i in xrange(1, self.n_e + 1):
     1633            for i in range(1, self.n_e + 1):
    16331634                var_map[varType][i] = dict()
    1634                 for k in xrange(1, self.n_cp + 1):
     1635                for k in range(1, self.n_cp + 1):
    16351636                    var_map[varType][i][k] = \
    16361637                        global_split[split_map['unelim_u']][
    1637                             map(sub, var_indices[varType][i][k],
    1638                                 aux_list)]
     1638                            list(map(sub, var_indices[varType][i][k],
     1639                                aux_list))]
    16391640                   
    16401641            # Index initial controls separately if blocking_factors is not None       
     
    16611662            new_index = counter_s + n_cont_u
    16621663            var_indices['unelim_u'][1][0][cont_indices] = \
    1663                          range(counter_s, new_index)
     1664                         list(range(counter_s, new_index))
    16641665            var_indices['unelim_u'][1][0] = \
    16651666                         list(var_indices['unelim_u'][1][0])
     
    17411742        var_map['p_opt']['all'] = \
    17421743                  global_split[split_map['p_opt']]
    1743         var_indices['p_opt']=range(counter_s,counter_s+n_popt)
     1744        var_indices['p_opt']=list(range(counter_s,counter_s+n_popt))
    17441745        if n_popt!=0:
    17451746            tmp_split=casadi.vertsplit(var_map['p_opt']['all'])
     
    17571758        var_map['h']['all'] = \
    17581759                  global_split[split_map['h']]
    1759         var_indices['h']=range(counter_s,counter_s+n_freeh2)
     1760        var_indices['h']=list(range(counter_s,counter_s+n_freeh2))
    17601761        if n_freeh2!=0:
    17611762            tmp_split=casadi.vertsplit(var_map['h']['all'])
     
    18071808        else:
    18081809            inp_list = [inp.getName() for inp in self.mvar_vectors['unelim_u']
    1809                    if not self.blocking_factors.factors.has_key(inp.getName())]
     1810                   if inp.getName() not in self.blocking_factors.factors]
    18101811
    18111812        n_c_e += len(inp_list) # u_1_0
     
    19141915            self.pp_unvarying = pp_split[0]
    19151916
    1916             self.pp_split  = dict(zip(pp_kinds, pp_split))
    1917             self.pp_offset = dict(zip(pp_kinds, pp_offset))
     1917            self.pp_split  = dict(list(zip(pp_kinds, pp_split)))
     1918            self.pp_offset = dict(list(zip(pp_kinds, pp_offset)))
    19181919        else:
    19191920            self.pp_unvarying = self.pp
     
    19491950        self.var_map['p_fixed'] = dict()
    19501951        self.var_map['p_fixed']['all'] = self.pp_unvarying
    1951         self.var_indices['p_fixed']=range(0, self.n_var['p_fixed'])
     1952        self.var_indices['p_fixed']=list(range(0, self.n_var['p_fixed']))
    19521953        if self.n_var['p_fixed'] != 0:
    19531954            tmp_split=casadi.vertsplit(self.var_map['p_fixed']['all'])
     
    20392040        """
    20402041        z = []
    2041         for vk in self.mvar_struct.iterkeys(): #Dangerous need to verify that variable types are added in correct order
     2042        for vk in self.mvar_struct.keys(): #Dangerous need to verify that variable types are added in correct order
    20422043            if vk == 'time':
    20432044                if self._normalize_min_time:
     
    20832084        """
    20842085        z = []
    2085         for vk in self.mvar_struct.iterkeys():
     2086        for vk in self.mvar_struct.keys():
    20862087            if vk == 'time':
    20872088                times = [self.time_points[i][k] for k in range(1, self.n_cp+1)]
     
    21212122        self.element_times[0] = N.nan # element 0 is unused
    21222123        t = self.t0
    2123         for i in xrange(1, self.n_e + 1):
     2124        for i in range(1, self.n_e + 1):
    21242125            self.element_times[i] = t
    21252126            t = t + self.horizon * self.h[i]
     
    21372138        time = []
    21382139
    2139         for i in xrange(1, self.n_e + 1):
     2140        for i in range(1, self.n_e + 1):
    21402141            self.time_points[i] = {}
    21412142            k0 = 0 if i == 1 else 1
    21422143            k1 = self.n_cp + (2 if self.is_gauss and i == self.n_e else 1)
    2143             for k in xrange(k0, k1):
     2144            for k in range(k0, k1):
    21442145                t = self.get_point_time(i, k)
    21452146                self.time_points[i][k] = t
     
    22162217                else:
    22172218                    raise CasadiCollocatorException(
    2218                         "Constraint point " + `constraint_point` +
     2219                        "Constraint point " + repr(constraint_point) +
    22192220                        " does not coincide with a collocation point.")
    22202221            else:
     
    22982299                            if (var_init_guess in [0., 1.]):
    22992300                                if self.options['verbosity'] >= 2:
    2300                                     print("Warning: Could not find initial " +
     2301                                    print(("Warning: Could not find initial " +
    23012302                                          "guess for %s in initial " % t_name +
    23022303                                          "trajectories. Using end-point of " +
    2303                                           "provided time horizon instead.")
     2304                                          "provided time horizon instead."))
    23042305                                if t_name == "startTime":
    23052306                                    t_init[t_name] = intraj_gvd("time").t[0]
     
    23112312                            else:
    23122313                                if self.options['verbosity'] >= 2:
    2313                                     print("Warning: Could not find initial " +
     2314                                    print(("Warning: Could not find initial " +
    23142315                                          "guess for %s in initial " % t_name +
    23152316                                          "trajectories. Using initialGuess " +
    2316                                           "attribute value instead.")
     2317                                          "attribute value instead."))
    23172318                                t_init[t_name] = var_init_guess
    23182319                        else:
     
    23332334                            except VariableNotFoundError:
    23342335                                if self.options['verbosity'] >= 2:
    2335                                     print("Warning: Could not find nominal " +
     2336                                    print(("Warning: Could not find nominal " +
    23362337                                          "value for %s in nominal t" % t_name +
    23372338                                          "rajectories. Using end-point of " +
    2338                                           "provided time horizon instead.")
     2339                                          "provided time horizon instead."))
    23392340                                if t_name == "startTime":
    23402341                                    t_nom[t_name] = nomtraj_gvd("time").t[0]
     
    23872388                        # more efficiently, especially in the case of MX
    23882389                        if self.options['verbosity'] >= 2:
    2389                             print("Warning: Could not find nominal trajectory " +
     2390                            print(("Warning: Could not find nominal trajectory " +
    23902391                                  "for variable " + name + ". Using nominal " +
    2391                                   "attribute value instead.")
     2392                                  "attribute value instead."))
    23922393                        self.nominal_traj_mode[name] = "attribute"
    23932394                        abscissae = N.array([0])
     
    24012402                        if len(nonfinite_ind) > 0:
    24022403                            if self.options['verbosity'] >= 1:
    2403                                 print("Warning: Nominal trajectory for variable " + name +
     2404                                print(("Warning: Nominal trajectory for variable " + name +
    24042405                                      " contains nonfinite values. Using nominal attribute " +
    2405                                       "value for these instead.")
     2406                                      "value for these instead."))
    24062407                            ordinates[nonfinite_ind] = self.op.get_attr(var, "nominal")
    24072408                        ordinates = ordinates.reshape([-1, 1])
     
    24242425               
    24252426                #Setup struct
    2426                 for i in xrange(1, self.n_e + 1):
     2427                for i in range(1, self.n_e + 1):
    24272428                    var_sf_map[vt][i] = {}
    24282429                    for k in self.time_points[i]:
     
    24502451                   
    24512452                    #Setup struct
    2452                     for i in xrange(1, self.n_e + 1):
     2453                    for i in range(1, self.n_e + 1):
    24532454                        for k in self.time_points[i]:
    24542455                            var_sf_map[vt][i][k][var_index] = (2*var_sf_count, 2*var_sf_count+1)
     
    25062507            self._invariant_e = invariant_e
    25072508            self._name_idx_sf_map = name_idx_sf_map
    2508             for i in xrange(1, self.n_e + 1):
     2509            for i in range(1, self.n_e + 1):
    25092510                variant_sf[i] = {}
    25102511                for k in time_points[i]:
     
    25242525                        mode = self._var_sf_mode[name]
    25252526                        if self.options['verbosity'] >= 3:
    2526                             print("Warning: Could not do time-variant " +
     2527                            print(("Warning: Could not do time-variant " +
    25272528                                          "scaling for variable %s " % name +
    25282529                                          "due to that the original scaling was %s. " %mode +
    2529                                           "Doing %s scaling instead." %mode)
     2530                                          "Doing %s scaling instead." %mode))
    25302531                   
    25312532                    values = {}
     
    25332534                    traj_max = -N.inf
    25342535                    if mode not in ["attribute"]: #Compute min/max from nominal trajectories
    2535                         for i in xrange(1, self.n_e + 1):
     2536                        for i in range(1, self.n_e + 1):
    25362537                            values[i] = {}
    25372538                            for k in time_points[i]:
     
    25632564                                variant = False
    25642565                                if self.options['verbosity'] >= 3:
    2565                                     print("Warning: Could not do time-variant " +
     2566                                    print(("Warning: Could not do time-variant " +
    25662567                                          "scaling for variable %s. " % name +
    25672568                                          "Doing time-invariant affine scaling " +
    2568                                           "instead.")
     2569                                          "instead."))
    25692570                            else:
    25702571                                raise CasadiCollocatorException(
     
    25802581                        name_idx_sf_map[name] = n_variant_var
    25812582                        n_variant_var += 1
    2582                         for i in xrange(1, self.n_e + 1):
     2583                        for i in range(1, self.n_e + 1):
    25832584                            for k in time_points[i]:
    25842585                                variant_sf[i][k].append(N.abs(values[i][k]))
     
    25972598                                d = N.abs(self.op.get_attr(var, "nominal"))
    25982599                                if self.options['verbosity'] >= 3:
    2599                                     print("Warning: Nominal trajectory for " +
     2600                                    print(("Warning: Nominal trajectory for " +
    26002601                                          "variable %s is identically " % name +
    2601                                           "zero. Using nominal attribute instead.")
     2602                                          "zero. Using nominal attribute instead."))
    26022603                                if d == 0.0:
    26032604                                    raise CasadiCollocatorException(
     
    26102611                                    ["affine", "time-variant"]):
    26112612                                    if self.options['verbosity'] >= 3:
    2612                                         print("Warning: Could not do affine " +
     2613                                        print(("Warning: Could not do affine " +
    26132614                                              "scaling for variable %s. " % name +
    2614                                               "Doing linear scaling instead.")
     2615                                              "Doing linear scaling instead."))
    26152616                                else:
    26162617                                    raise CasadiCollocatorException(
     
    26202621                                if d == 0.:
    26212622                                    if self.options['verbosity'] >= 3:
    2622                                         print("Warning: Nominal trajectory for " +
     2623                                        print(("Warning: Nominal trajectory for " +
    26232624                                              "variable %s is " % name +
    26242625                                              "identically zero. Using nominal " +
    2625                                               "attribute instead.")
     2626                                              "attribute instead."))
    26262627                                    d = N.abs(self.op.get_attr(var, "nominal"))
    26272628                                    if d == 0.:
     
    26882689                            if N.allclose(d, 0.):
    26892690                                if self.options['verbosity'] >= 2:
    2690                                     print("Warning: Nominal value for %s is " % name +
    2691                                           "too small. Setting scaling factor to 1.")
     2691                                    print(("Warning: Nominal value for %s is " % name +
     2692                                          "too small. Setting scaling factor to 1."))
    26922693                                d = 1.
    26932694                        except VariableNotFoundError:
    26942695                            if self.options['verbosity'] >= 2:
    2695                                 print("Warning: Could not find nominal trajectory " +
     2696                                print(("Warning: Could not find nominal trajectory " +
    26962697                                      "for variable " + name + ". Using nominal " +
    2697                                       "attribute value instead.")
     2698                                      "attribute value instead."))
    26982699                            nom_val = self.op.get_attr(var, "nominal")
    26992700                            d = N.abs(nom_val)
     
    27172718
    27182719        # Sample collocation points
    2719         for i in xrange(1, self.n_e + 1):
    2720             for k in self.time_points[i].keys():
     2720        for i in range(1, self.n_e + 1):
     2721            for k in list(self.time_points[i].keys()):
    27212722                value = data.eval(self.time_points[i][k])[0, 0]
    27222723                if value < traj_min:
     
    27572758            for vk in ('elim_u', 'constr_u', 'quad_pen'):
    27582759                self.var_map[vk] = dict()
    2759                 for i in xrange(1, self.n_e + 1):
     2760                for i in range(1, self.n_e + 1):
    27602761                    self.var_map[vk][i]=dict()
    2761                     for k in self.time_points[i].keys():
     2762                    for k in list(self.time_points[i].keys()):
    27622763                        self.var_map[vk][i][k] = dict()
    27632764                        self.var_map[vk][i][k]['all'] = N.zeros(self.n_var[vk])
     
    28332834        s_sym_input = [self.mvar_struct["time"]]
    28342835        s_sym_input_no_der = [self.mvar_struct["time"]]
    2835         var_kinds_ordered =copy.copy(self.mvar_struct.keys())
     2836        var_kinds_ordered =copy.copy(list(self.mvar_struct.keys()))
    28362837        del var_kinds_ordered[0]
    28372838        for vk in var_kinds_ordered:
     
    28532854           
    28542855            if self.eliminate_der_var:
    2855                 print "TODO define input for no derivative mode daeresidual"
     2856                print("TODO define input for no derivative mode daeresidual")
    28562857                raise NotImplementedError("eliminate_der_ver not supported yet")
    28572858            else:
     
    29012902
    29022903                if self.eliminate_der_var:
    2903                     print "TODO collocation inlining derivative"
     2904                    print("TODO collocation inlining derivative")
    29042905                    raise NotImplementedError("eliminate_der_var not supported yet")
    29052906                else:
     
    29592960
    29602961            # Scale variables in expressions
    2961             scaled_timed_var = map(
     2962            scaled_timed_var = list(map(
    29622963                operator.add,
    2963                 map(operator.mul, timed_var_d, self._timed_variables),
    2964                 timed_var_e)
     2964                list(map(operator.mul, timed_var_d, self._timed_variables)),
     2965                timed_var_e))
    29652966
    29662967            s_scaled_z   = [sz_d["time"] * self.mvar_struct["time"] + sz_e["time"]]
     
    29852986            # Scale variables in expressions
    29862987            if self.eliminate_der_var:
    2987                 print "TODO scaling for the additional constraints elim_der_var"
     2988                print("TODO scaling for the additional constraints elim_der_var")
    29882989                raise NotImplementedError("eliminate_der_var not supported yet")               
    29892990
     
    29982999               
    29993000            if self.eliminate_der_var:
    3000                 print "TODO define input for function with no derivatives"
     3001                print("TODO define input for function with no derivatives")
    30013002                raise NotImplementedError("eliminate_der_var not supported yet")
    30023003            else:
     
    30273028        self.path_eq_orig = []
    30283029        self.path_ineq_orig = []
    3029         for (res, cnstr) in itertools.izip(self.path, self.op.getPathConstraints()):
     3030        for (res, cnstr) in zip(self.path, self.op.getPathConstraints()):
    30303031            if cnstr.getType() == cnstr.EQ:
    30313032                g_e.append(res)
     
    30413042        s_path_constraint_input = []
    30423043        if self.eliminate_der_var:
    3043             print "TODO define input for function with no derivatives"
     3044            print("TODO define input for function with no derivatives")
    30443045            raise NotImplementedError("named_vars not supported yet")
    30453046        else:
     
    30703071        self.point_eq_orig = []
    30713072        self.point_ineq_orig = []
    3072         for (res, cnstr) in itertools.izip(self.point,
     3073        for (res, cnstr) in zip(self.point,
    30733074                                           self.op.getPointConstraints()):
    30743075            if cnstr.getType() == cnstr.EQ:
     
    31363137            # Create function for evaluation of Lagrange integrand
    31373138            if self.eliminate_der_var:
    3138                 print "TODO lagrange input no derivative mode"
     3139                print("TODO lagrange input no derivative mode")
    31393140                raise NotImplementedError("eliminate_der_var not supported yet")               
    31403141            else:
     
    31963197        inputs_order_map["time"]=0
    31973198        inputs_order_map_no_der["time"]=0
    3198         var_kinds_ordered =copy.copy(l1_mvar_struct.keys())
     3199        var_kinds_ordered =copy.copy(list(l1_mvar_struct.keys()))
    31993200        del var_kinds_ordered[0]
    32003201        for vk in var_kinds_ordered:
     
    32643265        if not self.variable_scaling:
    32653266            if self.eliminate_der_var:
    3266                 print "TODO define input for no derivative mode daeresidual with check_point"
     3267                print("TODO define input for no derivative mode daeresidual with check_point")
    32673268                raise NotImplementedError("eliminate_der_ver not supported yet with check_point")
    32683269            else:
     
    33333334            sdx_sf_d_i = casadi.MX.sym("dx_i_sf_d", self.n_var["dx"]*self.n_cp)
    33343335            sdx_sf_e_i = casadi.MX.sym("dx_i_sf_e", self.n_var["dx"]*self.n_cp)
    3335             sdx_sf_d_col = map(list,casadi.vertsplit(sdx_sf_d_i, self.n_var["dx"])) if sdx_sf_d_i.shape[0]>0 else empty_list
     3336            sdx_sf_d_col = list(map(list,casadi.vertsplit(sdx_sf_d_i, self.n_var["dx"]))) if sdx_sf_d_i.shape[0]>0 else empty_list
    33363337            sdx_sf_d_col = [[casadi.vertcat(sdx_sf_d_col[k])] for k in range(self.n_cp)]             if sdx_sf_d_i.shape[0]>0 else sdx_sf_d_col
    3337             sdx_sf_e_col = map(list,casadi.vertsplit(sdx_sf_e_i, self.n_var["dx"])) if sdx_sf_e_i.shape[0]>0 else empty_list
     3338            sdx_sf_e_col = list(map(list,casadi.vertsplit(sdx_sf_e_i, self.n_var["dx"]))) if sdx_sf_e_i.shape[0]>0 else empty_list
    33383339            sdx_sf_e_col = [[casadi.vertcat(sdx_sf_e_col[k])] for k in range(self.n_cp)]             if sdx_sf_e_i.shape[0]>0 else sdx_sf_e_col
    33393340
    33403341            if self.eliminate_der_var:
    3341                 print "TODO define input for no derivative mode daeresidual"
     3342                print("TODO define input for no derivative mode daeresidual")
    33423343                raise NotImplementedError("eliminate_der_ver not supported yet")
    33433344            else:
     
    34793480        n = (j1-j0)//self.n_cp
    34803481        assert n*self.n_cp == j1-j0
    3481         for k in xrange(1, self.n_cp+1):
     3482        for k in range(1, self.n_cp+1):
    34823483            self._add_c('eq', eqtype, (j0+(k-1)*n, j0+k*n), i, k)
    34833484           
     
    34883489        if self.variable_scaling:
    34893490           
    3490             for i in xrange(1, self.n_e + 1):
     3491            for i in range(1, self.n_e + 1):
    34913492                coll_sf[i] = {}
    34923493                coll_sf[i]['x_d'] = []
     
    34943495                coll_sf[i]['dx_d'] = {}
    34953496                coll_sf[i]['dx_e'] = {}
    3496                 for k in xrange(1, self.n_cp + 1):
     3497                for k in range(1, self.n_cp + 1):
    34973498                    coll_sf[i]['dx_d'][k] = []
    34983499                    coll_sf[i]['dx_e'][k] = []
     
    35133514                coll_sf[i]['x_e'][-1].append(e)
    35143515               
    3515                 for k in xrange(1, self.n_cp + 1):
     3516                for k in range(1, self.n_cp + 1):
    35163517                    d, e = self._get_affine_scaling_symbols(x_name, i, k)
    35173518                    coll_sf[i]['x_d'][-1].append(d)
     
    35213522
    35223523                # Succeeding elements
    3523                 for i in xrange(2, self.n_e + 1):
     3524                for i in range(2, self.n_e + 1):
    35243525                    k = self.n_cp + self.is_gauss
    35253526                    coll_sf[i]['x_d'].append([])
     
    35303531                    coll_sf[i]['x_e'][-1].append(e)
    35313532                   
    3532                     for k in xrange(1, self.n_cp + 1):
     3533                    for k in range(1, self.n_cp + 1):
    35333534                        d, e = self._get_affine_scaling_symbols(x_name, i, k)
    35343535                        coll_sf[i]['x_d'][-1].append(d)
     
    35383539
    35393540                # State derivatives
    3540                 for i in xrange(1, self.n_e + 1):
    3541                     for k in xrange(1, self.n_cp + 1):
     3541                for i in range(1, self.n_e + 1):
     3542                    for k in range(1, self.n_cp + 1):
    35423543                        d, e = self._get_affine_scaling_symbols(dx_name, i, k)
    35433544                        coll_sf[i]['dx_d'][k].append(d)
     
    35523553        # Index collocation equation scale factors
    35533554        if self.variable_scaling:
    3554             for i in xrange(1, self.n_e + 1):
     3555            for i in range(1, self.n_e + 1):
    35553556                coll_l1_sf[i] = {}
    35563557                if i==1:
     
    35813582
    35823583            #level 1 scaling factor lists for Collocation equation
    3583             for k in xrange(1, self.n_cp + 1):
     3584            for k in range(1, self.n_cp + 1):
    35843585                for var in self.mvar_vectors['x']:
    35853586                    x_name = var.getName()
    35863587                    dx_name = var.getMyDerivativeVariable().getName()
    35873588                   
    3588                     for i in xrange(1, self.n_e + 1):
     3589                    for i in range(1, self.n_e + 1):
    35893590                        d, e = self._get_affine_scaling_symbols(x_name, i, k)
    35903591                        coll_l1_sf[i]['x_d'].append(d)
    35913592                        coll_l1_sf[i]['x_e'].append(e)
    35923593                       
    3593                     for i in xrange(1, self.n_e + 1):
     3594                    for i in range(1, self.n_e + 1):
    35943595                        d, e = self._get_affine_scaling_symbols(dx_name, i, k)
    35953596                        coll_l1_sf[i]['dx_d'].append(d)
     
    36093610        self.der_vals = der_vals
    36103611
    3611         for k in xrange(self.n_cp + 1):
     3612        for k in range(self.n_cp + 1):
    36123613            #Done like this because of casadi update. This can be improved
    36133614            der_vals_k = [self.pol.der_vals[:, k].T.reshape([1, self.n_cp + 1]).T]
     
    36193620        self.x_list = x_list       
    36203621
    3621         for i in xrange(1, self.n_e + 1):
    3622             x_i = [self.var_map['x'][i][k]['all'].T for k in xrange(self.n_cp + 1)]
     3622        for i in range(1, self.n_e + 1):
     3623            x_i = [self.var_map['x'][i][k]['all'].T for k in range(self.n_cp + 1)]
    36233624            x_i = [casadi.vertcat(x_i)]
    36243625            x_list.append(x_i)
     
    36413642        self.add_c_eq('initial', initial_constr, i, k)
    36423643        if self.eliminate_der_var:
    3643             print "Call the additional equations for no derivative mode"
     3644            print("Call the additional equations for no derivative mode")
    36443645            raise NotImplementedError("named_vars not supported yet")
    36453646        else:
     
    36513652        else:
    36523653            inp_list = [inp.getName() for inp in self.mvar_vectors['unelim_u']
    3653                    if not self.blocking_factors.factors.has_key(inp.getName())]
     3654                   if inp.getName() not in self.blocking_factors.factors]
    36543655
    36553656        for name in inp_list:
     
    36583659            input_index = self.name_map[name][0]
    36593660
    3660             for k in xrange(1, self.n_cp + 1):
     3661            for k in range(1, self.n_cp + 1):
    36613662                u_1_0 += (self.pol.eval_basis(k, 0, False) *
    36623663                          self.var_map['unelim_u'][1][k][input_index])
     
    36693670        if self.is_gauss:
    36703671            if self.quadrature_constraint:
    3671                 for i in xrange(1, self.n_e + 1):
     3672                for i in range(1, self.n_e + 1):
    36723673                    # Evaluate x_{i, n_cp + 1} based on quadrature
    36733674                    x_i_np1  = []
     
    36883689                        (ind_dx, _) = self.name_map[dx_name]
    36893690                   
    3690                         for k in xrange(1, self.n_cp + 1):
     3691                        for k in range(1, self.n_cp + 1):
    36913692                            if self.variable_scaling:
    36923693                                dx_i_np1[-1] += self.pol.w[k] * self._get_unscaled_expr_symbols(dx_name, i, k)
     
    37073708                    self.add_c_eq('continuity', quad_constr, i)
    37083709            else:
    3709                 for i in xrange(1, self.n_e + 1):
     3710                for i in range(1, self.n_e + 1):
    37103711                    # Evaluate x_{i, n_cp + 1} based on polynomial x_i
    37113712                    x_i_np1 = 0
    3712                     for k in xrange(self.n_cp + 1):
     3713                    for k in range(self.n_cp + 1):
    37133714                        x_i_np1 += self.var_map['x'][i][k]['all'] * self.pol.eval_basis(
    37143715                            k, 1, True)
     
    37233724                # Evaluate xx_{n_e, n_cp + 1} based on polynomial xx_{n_e}
    37243725                xx_ne_np1 = 0
    3725                 for k in xrange(1, self.n_cp + 1):
     3726                for k in range(1, self.n_cp + 1):
    37263727                    xx_ne_np1 += (self.var_map[var_type][self.n_e][k]['all'] *
    37273728                                  self.pol.eval_basis(k, 1, False))
     
    37343735                # Evaluate dx_{n_e, n_cp + 1} based on polynomial x_{n_e}
    37353736                dx_ne_np1 = 0
    3736                 for k in xrange(self.n_cp + 1):
     3737                for k in range(self.n_cp + 1):
    37373738                    x_ne_k = self.var_map['x'][self.n_e][k]['all']
    37383739                    dx_ne_np1 += (1. / (self.horizon * self.h[self.n_e]) *
     
    37503751           
    37513752        # Path constraints
    3752         for i in xrange(1, self.n_e + 1):
    3753             for k in self.time_points[i].keys():
     3753        for i in range(1, self.n_e + 1):
     3754            for k in list(self.time_points[i].keys()):
    37543755                s_fcn_input = []
    37553756                if self.eliminate_der_var:
    3756                     print "TODO path constraints eliminate derivative mode"
     3757                    print("TODO path constraints eliminate derivative mode")
    37573758                    raise NotImplementedError("eliminate_der_var not supported yet")
    37583759                else:
     
    37833784        # Check that only inputs are constrained or eliminated
    37843785        if self.external_data is not None:
    3785             for var_name in (self.external_data.eliminated.keys() +
    3786                              self.external_data.constr_quad_pen.keys()):
     3786            for var_name in (list(self.external_data.eliminated.keys()) +
     3787                             list(self.external_data.constr_quad_pen.keys())):
    37873788                (_, vt) = self.name_map[var_name]
    37883789                if vt not in ['elim_u', 'unelim_u']:
    3789                     if var_name in self.external_data.eliminated.keys():
     3790                    if var_name in list(self.external_data.eliminated.keys()):
    37903791                        msg = ("Eliminated variable " + var_name + " is " +
    37913792                               "either not an input or in the model at all.")
     
    37973798        # Equality constraints for constrained inputs
    37983799        if self.external_data is not None:
    3799             for i in xrange(1, self.n_e + 1):
    3800                 for k in xrange(1, self.n_cp + 1):
    3801                     for j in xrange(len(self.external_data.constr_quad_pen)):
     3800            for i in range(1, self.n_e + 1):
     3801                for k in range(1, self.n_cp + 1):
     3802                    for j in range(len(self.external_data.constr_quad_pen)):
    38023803                        # Retrieve variable and value
    3803                         name = self.external_data.constr_quad_pen.keys()[j]
     3804                        name = list(self.external_data.constr_quad_pen.keys())[j]
    38043805                        #constr_var = self._get_unscaled_expr(name, i, k)
    38053806                        constr_var = self._get_unscaled_expr_symbols(name, i, k)
     
    38213822                "Non-uniform element lengths are not supported with delayed feedback.")
    38223823           
    3823             for (u_name, (y_name, delay_n_e)) in self.delayed_feedback.iteritems():
     3824            for (u_name, (y_name, delay_n_e)) in self.delayed_feedback.items():
    38243825                u_dae_var = self.op.getVariable(u_name)
    3825                 for i in xrange(1, self.n_e + 1):
    3826                     for k in xrange(1, self.n_cp + 1):
     3826                for i in range(1, self.n_e + 1):
     3827                    for k in range(1, self.n_cp + 1):
    38273828                        u_var = self._get_unscaled_expr_symbols(u_name, i, k)
    38283829                        if i > delay_n_e:
     
    38683869       
    38693870        # Collocation and DAE constraints
    3870         for i in xrange(1, self.n_e + 1):
    3871             for k in xrange(1, self.n_cp + 1):
     3871        for i in range(1, self.n_e + 1):
     3872            for k in range(1, self.n_cp + 1):
    38723873                # Create function inputs
    38733874                if self.eliminate_der_var:
    3874                     print "TODO set input for no derivative mode collocation equation"
     3875                    print("TODO set input for no derivative mode collocation equation")
    38753876                    raise NotImplementedError("eliminate_der_var not supported yet")
    38763877                else:
     
    38853886                   
    38863887                    if self.eliminate_der_var:
    3887                         print "TODO set input for no derivative mode collocation equation"
     3888                        print("TODO set input for no derivative mode collocation equation")
    38883889                        raise NotImplementedError("eliminate_der_var not supported yet")                       
    38893890                    else:
     
    39083909        # CONSIDER: Should these be scaled incase of affine scaling?
    39093910        if not self.eliminate_cont_var:
    3910             for i in xrange(1, self.n_e):
     3911            for i in range(1, self.n_e):
    39113912                cont_constr = (self.var_map['x'][i][self.n_cp + self.is_gauss]['all'] -
    39123913                               self.var_map['x'][i + 1][0]['all'])
     
    39353936
    39363937            # Evaluate Lagrange cost
    3937             for i in xrange(1, self.n_e + 1):
    3938                 for k in xrange(1, self.n_cp + 1):
     3938            for i in range(1, self.n_e + 1):
     3939                for k in range(1, self.n_cp + 1):
    39393940                    if self.eliminate_der_var:
    3940                         print "TODO lagrange input no derivative mode"
     3941                        print("TODO lagrange input no derivative mode")
    39413942                        raise NotImplementedError("eliminate_der_var not supported yet")                         
    39423943                    else:
     
    39823983        # Create der_vals for all collocation points (level1 input)
    39833984        der_vals_l1=list()
    3984         for k in xrange(1, self.n_cp + 1):
     3985        for k in range(1, self.n_cp + 1):
    39853986            der_vals_k = self.pol.der_vals[:, k]
    39863987            for j in der_vals_k:
     
    40094010        h_no_free=casadi.MX(h_uniform*self.horizon)
    40104011        non_uniform_h=False
    4011         for i in xrange(2, self.n_e + 1):
     4012        for i in range(2, self.n_e + 1):
    40124013            if self.h[i]!=h_uniform:
    40134014                non_uniform_h=True
    40144015                break
    4015         for i in xrange(1, self.n_e + 1):
     4016        for i in range(1, self.n_e + 1):
    40164017            # Create function inputs
    40174018            if self.eliminate_der_var:
    4018                 print "TODO set input for no derivative mode collocation equation"
     4019                print("TODO set input for no derivative mode collocation equation")
    40194020                raise NotImplementedError("eliminate_der_var not supported yet")
    40204021            else:
     
    40474048        # Continuity constraints for x_{i, 0}
    40484049        if not self.eliminate_cont_var:
    4049             for i in xrange(1, self.n_e):
     4050            for i in range(1, self.n_e):
    40504051                cont_constr = (self.var_map['x'][i][self.n_cp + self.is_gauss]['all'] -
    40514052                               self.var_map['x'][i + 1][0]['all'])
     
    40754076            Gauss_w=casadi.MX(Gauss_w)
    40764077            if self.hs == "free" or non_uniform_h:
    4077                 for i in xrange(1, self.n_e + 1):
     4078                for i in range(1, self.n_e + 1):
    40784079                    if self.eliminate_der_var:
    4079                         print "TODO lagrange input no derivative mode"
     4080                        print("TODO lagrange input no derivative mode")
    40804081                        raise NotImplementedError("eliminate_der_var not supported yet")                         
    40814082                    else:
     
    40894090                                               e_lterm_val)
    40904091            else:
    4091                 for i in xrange(1, self.n_e + 1):
     4092                for i in range(1, self.n_e + 1):
    40924093                    if self.eliminate_der_var:
    4093                         print "TODO lagrange input no derivative mode"
     4094                        print("TODO lagrange input no derivative mode")
    40944095                        raise NotImplementedError("eliminate_der_var not supported yet")                         
    40954096                    else:
     
    44584459                    except VariableNotFoundError:
    44594460                        if self.options['verbosity'] >= 2:
    4460                             print("Warning: Could not find initial " +
     4461                            print(("Warning: Could not find initial " +
    44614462                                  "trajectory for variable " + name +
    44624463                                  ". Using initialGuess attribute value " +
    4463                                   "instead.")
     4464                                  "instead."))
    44644465                        ordinates = N.array([[
    44654466                            self.op.get_attr(var, "initialGuess")]])
     
    44714472                        if len(nonfinite_ind) > 0:
    44724473                            if self.options['verbosity'] >= 1:
    4473                                 print("Warning: Initial trajectory for variable " + name +
     4474                                print(("Warning: Initial trajectory for variable " + name +
    44744475                                      " contains nonfinite values. Using initialGuess attribute " +
    4475                                       "value for these instead.")
     4476                                      "value for these instead."))
    44764477                            ordinates[nonfinite_ind] = self.op.get_attr(var, "initialGuess")
    44774478                        ordinates = ordinates.reshape([-1, 1])
     
    45644565                        except VariableNotFoundError:
    45654566                            if self.options['verbosity'] >= 2:
    4566                                 print("Warning: Could not find initial " +
     4567                                print(("Warning: Could not find initial " +
    45674568                                      "trajectory for variable " + name +
    45684569                                      ". Using initialGuess attribute value " +
    4569                                       "instead.")
     4570                                      "instead."))
    45704571                            ordinates = N.array([[
    45714572                                op.get_attr(var, "initialGuess")]])
     
    45904591                (var_idx, _) = name_map[name]
    45914592               
    4592                 for i in xrange(1, self.n_e + 1):
    4593                     for k in self.time_points[i].keys():
     4593                for i in range(1, self.n_e + 1):
     4594                    for k in list(self.time_points[i].keys()):
    45944595                       
    45954596                        #Get scaling factors
     
    46114612            vt = 'x'
    46124613            k = self.n_cp + self.is_gauss
    4613             for i in xrange(2, self.n_e + 1):
     4614            for i in range(2, self.n_e + 1):
    46144615                xx_lb[self.var_indices[vt][i][0]]   = xx_lb[self.var_indices[vt][i - 1][k]]
    46154616                xx_ub[self.var_indices[vt][i][0]]   = xx_ub[self.var_indices[vt][i - 1][k]]
     
    46204621            h_0 = 1. / self.n_e
    46214622            h_bounds = self.free_element_lengths_data.bounds
    4622             for i in xrange(1, self.n_e + 1):
     4623            for i in range(1, self.n_e + 1):
    46234624                xx_lb[self.var_indices['h'][i]] = h_bounds[0] * h_0
    46244625                xx_ub[self.var_indices['h'][i]] = h_bounds[1] * h_0
     
    46424643        # Finalize and sort recorded tracking info
    46434644        for dests in (self.c_dests, self.xx_dests):
    4644             for dest in dests.itervalues():               
     4645            for dest in dests.values():               
    46454646                inds = N.vstack(dest['inds'])
    46464647                i = N.array(dest['i'], dtype=N.int)
     
    46614662        n_i = self.c_i.numel()
    46624663        if (n_e, n_i) != (self.n_c_e, self.n_c_i):
    4663             print "(n_e, self.n_c_e) =", (n_e, self.n_c_e)
    4664             print "(n_i, self.n_c_i) =", (n_i, self.n_c_i)
     4664            print("(n_e, self.n_c_e) =", (n_e, self.n_c_e))
     4665            print("(n_i, self.n_c_i) =", (n_i, self.n_c_i))
    46654666        assert n_e == self.n_c_e
    46664667        assert n_i == self.n_c_i
     
    46994700        self.xx_sources['k'].fill(-1)
    47004701
    4701         for (var, dest) in self.xx_dests.iteritems():
     4702        for (var, dest) in self.xx_dests.items():
    47024703            v_inds = dest['inds']
    47034704            self.xx_sources['var'][v_inds] = var
     
    47124713        if self.order != "default":
    47134714            if self.order == "reverse":
    4714                 self.eq_ordering = eq_ordering = range(constraints.numel()-1, -1, -1)
    4715                 self.var_ordering = var_ordering = range(self.n_xx-1, -1, -1)
     4715                self.eq_ordering = eq_ordering = list(range(constraints.numel()-1, -1, -1))
     4716                self.var_ordering = var_ordering = list(range(self.n_xx-1, -1, -1))
    47164717            elif self.order == "random":
    4717                 self.eq_ordering = eq_ordering = range(constraints.numel())
    4718                 self.var_ordering = var_ordering = range(self.n_xx)
     4718                self.eq_ordering = eq_ordering = list(range(constraints.numel()))
     4719                self.var_ordering = var_ordering = list(range(self.n_xx))
    47194720                N.random.shuffle(eq_ordering)
    47204721                N.random.shuffle(var_ordering)
     
    47734774        if self.mutable_external_data:
    47744775            elim_u = N.zeros(self.n_var['elim_u'])
    4775             for j in xrange(self.n_var['elim_u']):
     4776            for j in range(self.n_var['elim_u']):
    47764777                # consider: are those always consecutive indices?
    47774778                # If so, would be enough to index into _par_vals with a range
     
    48114812                t_opt = [t_start]
    48124813                for h in h_scaled[1:]:
    4813                     for k in xrange(1, self.n_cp + 1):
     4814                    for k in range(1, self.n_cp + 1):
    48144815                        t_opt.append(t_start + self.pol.p[k] * h)
    48154816                    t_start += h
     
    48244825        elif self.result_mode == "element_interpolation":
    48254826            t_opt = [self.t0]
    4826             for i in xrange(1, self.n_e + 1):
     4827            for i in range(1, self.n_e + 1):
    48274828                t_end = t_opt[-1] + h_scaled[i]
    48284829                t_i = N.linspace(t_opt[-1], t_end, self.n_eval_points)
     
    48644865        time_points = self.get_time_points()
    48654866        if self.variable_scaling and not self.write_scaled_result:
    4866             for i in xrange(1, self.n_e + 1):
     4867            for i in range(1, self.n_e + 1):
    48674868                for k in time_points[i]:
    48684869                    for var_type in var_types:
     
    49104911        if (self.variable_scaling and not self.eliminate_cont_var and
    49114912            not self.write_scaled_result):
    4912             for i in xrange(1, self.n_e):
     4913            for i in range(1, self.n_e):
    49134914                k = self.n_cp + self.is_gauss
    49144915                x_i_k = primal_opt[self.var_indices['x'][i][k]]
     
    49174918            not self.eliminate_cont_var and not self.write_scaled_result):
    49184919            if self.quadrature_constraint:
    4919                 for i in xrange(1, self.n_e + 1):
     4920                for i in range(1, self.n_e + 1):
    49204921                    # Evaluate x_{i, n_cp + 1} based on quadrature
    49214922                    x_i_np1 = 0
    4922                     for k in xrange(1, self.n_cp + 1):
     4923                    for k in range(1, self.n_cp + 1):
    49234924                        dx_i_k = primal_opt[self.var_indices['dx'][i][k]]
    49244925                        x_i_np1 += self.pol.w[k] * dx_i_k
     
    49294930                    primal_opt[self.var_indices['x'][i][self.n_cp + 1]] = x_i_np1
    49304931            else:
    4931                 for i in xrange(1, self.n_e + 1):
     4932                for i in range(1, self.n_e + 1):
    49324933                    # Evaluate x_{i, n_cp + 1} based on polynomial x_i
    49334934                    x_i_np1 = 0
    4934                     for k in xrange(self.n_cp + 1):
     4935                    for k in range(self.n_cp + 1):
    49354936                        x_i_k = primal_opt[self.var_indices['x'][i][k]]
    49364937                        x_i_np1 += x_i_k * self.pol.eval_basis(k, 1, True)
     
    49434944        t_index = 0
    49444945        if self.result_mode == "collocation_points":
    4945             for i in xrange(1, self.n_e + 1):
     4946            for i in range(1, self.n_e + 1):
    49464947                for k in time_points[i]:
    49474948                    for var_type in var_types:
     
    49604961
    49614962                # Collocation point derivatives
    4962                 for i in xrange(1, self.n_e + 1):
    4963                     for k in xrange(1, self.n_cp + 1):
     4963                for i in range(1, self.n_e + 1):
     4964                    for k in range(1, self.n_cp + 1):
    49644965                        dx_i_k = 0
    4965                         for l in xrange(self.n_cp + 1):
     4966                        for l in range(self.n_cp + 1):
    49664967                            x_i_l = primal_opt[self.var_indices['x'][i][l]]
    49674968                            dx_i_k += (1. / h_scaled[i] * x_i_l *
     
    49724973        elif self.result_mode == "element_interpolation":
    49734974            tau_arr = N.linspace(0, 1, self.n_eval_points)
    4974             for i in xrange(1, self.n_e + 1):
     4975            for i in range(1, self.n_e + 1):
    49754976                for tau in tau_arr:
    49764977                    # Non-derivatives and uneliminated inputs
     
    49784979                        # Evaluate xx_i_tau based on polynomial xx^i
    49794980                        xx_i_tau = 0
    4980                         for k in xrange(not cont[var_type], self.n_cp + 1):
     4981                        for k in range(not cont[var_type], self.n_cp + 1):
    49814982                            xx_i_k = primal_opt[self.var_indices[var_type][i][k]]
    49824983                            xx_i_tau += xx_i_k * self.pol.eval_basis(
     
    49864987                    # eliminated inputs
    49874988                    xx_i_tau = 0
    4988                     for k in xrange(not cont[var_type], self.n_cp + 1):
     4989                    for k in range(not cont[var_type], self.n_cp + 1):
    49894990                        xx_i_k = self._get_elim_u_result(i, k)
    49904991                        xx_i_tau += xx_i_k * self.pol.eval_basis(
     
    49944995                    # Derivatives
    49954996                    dx_i_tau = 0
    4996                     for k in xrange(self.n_cp + 1):
     4997                    for k in range(self.n_cp + 1):
    49974998                        x_i_k = primal_opt[self.var_indices['x'][i][k]]
    49984999                        dx_i_tau += (1. / h_scaled[i] * x_i_k *
     
    50155016            var_types.remove('x')
    50165017            if self.discr == "LGR":
    5017                 for i in xrange(1, self.n_e + 1):
     5018                for i in range(1, self.n_e + 1):
    50185019                    for var_type in var_types:
    50195020                        xx_i_k = primal_opt[self.var_indices[var_type][i][k]]
     
    50235024                    t_index += 1
    50245025            elif self.discr == "LG":
    5025                 for i in xrange(1, self.n_e + 1):
     5026                for i in range(1, self.n_e + 1):
    50265027                    for var_type in var_types:
    50275028                        # Evaluate xx_{i, n_cp + 1} based on polynomial xx_i
    50285029                        xx_i_k = 0
    5029                         for l in xrange(1, self.n_cp + 1):
     5030                        for l in range(1, self.n_cp + 1):
    50305031                            xx_i_l = primal_opt[self.var_indices[var_type][i][l]]
    50315032                            xx_i_k += xx_i_l * self.pol.eval_basis(l, 1, False)
     
    50335034                    # Evaluate u_{i, n_cp + 1} based on polynomial u_i
    50345035                    u_i_k = 0
    5035                     for l in xrange(1, self.n_cp + 1):
     5036                    for l in range(1, self.n_cp + 1):
    50365037                        u_i_l = self._get_elim_u_result(i, l)
    50375038                        u_i_k += u_i_l * self.pol.eval_basis(l, 1, False)
     
    50425043            # Handle states separately
    50435044            t_index = 1
    5044             for i in xrange(1, self.n_e + 1):
     5045            for i in range(1, self.n_e + 1):
    50455046                x_i_k = primal_opt[self.var_indices['x'][i][k]]
    50465047                var_opt['x'][t_index, :] = x_i_k.reshape(-1)
     
    50595060                # Mesh point state derivatives
    50605061                t_index = 1
    5061                 for i in xrange(1, self.n_e + 1):
     5062                for i in range(1, self.n_e + 1):
    50625063                    dx_i_k = 0
    5063                     for l in xrange(self.n_cp + 1):
     5064                    for l in range(self.n_cp + 1):
    50645065                        x_i_l = primal_opt[self.var_indices['x'][i][l]]
    50655066                        dx_i_k += (1. / h_scaled[i] * x_i_l *
     
    50855086            u_opt = N.empty([self.n_e * self.n_cp + 1 + self.is_gauss,
    50865087                             self.n_var['u']])
    5087             for i in xrange(1, self.n_e + 1):
     5088            for i in range(1, self.n_e + 1):
    50885089                for k in time_points[i]:
    50895090                    unelim_u_i_k = primal_opt[self.var_indices['unelim_u'][i][k]]
     
    51225123            # Compute eliminated variables
    51235124            t_index = 0
    5124             var_kinds_ordered =copy.copy(self.mvar_struct.keys())
     5125            var_kinds_ordered =copy.copy(list(self.mvar_struct.keys()))
    51255126            del var_kinds_ordered[0]
    51265127            for t in t_opt:
     
    53825383        # Consider: do we actually need to save _xi, _ti, and _hi in self?
    53835384        if self.hs == "free":
    5384             self._hi = map(lambda h: self.horizon * h, self.h_opt)
     5385            self._hi = [self.horizon * h for h in self.h_opt]
    53855386        else:
    5386             self._hi = map(lambda h: self.horizon * h, self.h)
     5387            self._hi = [self.horizon * h for h in self.h]
    53875388       
    53885389        xi = self._u_opt[1:self.n_e*self.n_cp+1]
     
    57235724        Get a list of all types of constraints that have mappings to the NLP
    57245725        """
    5725         return self.c_dests.keys()
     5726        return list(self.c_dests.keys())
    57265727
    57275728    def get_nlp_constraint_indices(self, eqtype):
     
    57945795
    57955796        """
    5796         if isinstance(var, basestring):
     5797        if isinstance(var, str):
    57975798            var = self.op.getVariable(var)
    57985799
     
    58865887        ext = '.so'
    58875888    if not use_existing:
    5888         print 'Generating code for', name
     5889        print('Generating code for', name)
    58895890        fcn.generateCode(name + '.c')
    58905891        _add_help_fcns(name + '.c')
     
    60466047        if times is not None and self.options['verbosity'] >= 1:
    60476048            # Print times
    6048             print("\nInitialization time: %.2f seconds" % times['init'])
     6049            print(("\nInitialization time: %.2f seconds" % times['init']))
    60496050           
    6050             print("\nTotal time: %.2f seconds" % times['tot'])
    6051             print("Pre-processing time: %.2f seconds" % times['update'])
    6052             print("Solution time: %.2f seconds" % times['sol'])
    6053             print("Post-processing time: %.2f seconds\n" %
    6054                   times['post_processing'])
     6051            print(("\nTotal time: %.2f seconds" % times['tot']))
     6052            print(("Pre-processing time: %.2f seconds" % times['update']))
     6053            print(("Solution time: %.2f seconds" % times['sol']))
     6054            print(("Post-processing time: %.2f seconds\n" %
     6055                  times['post_processing']))
    60556056
    60566057        # Print condition numbers
     
    60606061            KKT_init_cond = N.linalg.cond(solver.get_KKT("init"), scaled_residuals=self.op.equation_scaling)
    60616062            KKT_opt_cond = N.linalg.cond(solver.get_KKT("opt"), scaled_residuals=self.op.equation_scaling)
    6062             print("\nJacobian condition number at the initial guess: %.3g" %
    6063                   J_init_cond)
    6064             print("Jacobian condition number at the optimum: %.3g" %
    6065                   J_opt_cond)
    6066             print("KKT matrix condition number at the initial guess: %.3g" %
    6067                   KKT_init_cond)
    6068             print("KKT matrix condition number at the optimum: %.3g" %
    6069                   KKT_opt_cond)
     6063            print(("\nJacobian condition number at the initial guess: %.3g" %
     6064                  J_init_cond))
     6065            print(("Jacobian condition number at the optimum: %.3g" %
     6066                  J_opt_cond))
     6067            print(("KKT matrix condition number at the initial guess: %.3g" %
     6068                  KKT_init_cond))
     6069            print(("KKT matrix condition number at the optimum: %.3g" %
     6070                  KKT_opt_cond))
    60706071
    60716072    def get_opt_input(self):
     
    67536754        else:
    67546755            r = self.get_residuals(eqtype, point=point, scaled=scaled, tik=False)
    6755             for j in xrange(r.shape[1]):
     6756            for j in range(r.shape[1]):
    67566757                rnorm = N.linalg.norm(r[:,j], ord=ord)
    67576758                result.append((rnorm, j))
     
    67936794            if inv:
    67946795                r = 1/r
    6795             for j in xrange(r.shape[1]):
     6796            for j in range(r.shape[1]):
    67966797                rnorm = N.linalg.norm(r[:,j], ord=ord)
    67976798                result.append((rnorm, j))
     
    69716972                try:
    69726973                    eq = self.get_equations(eqtype)[eqind] # todo: faster lookup?
    6973                     print "\nEquation(%s):" % eqtype, eq
     6974                    print("\nEquation(%s):" % eqtype, eq)
    69746975                except (KeyError, IndexError):
    6975                     print "\nEquation: (%s, %i)" % (eqtype, eqind)
     6976                    print("\nEquation: (%s, %i)" % (eqtype, eqind))
    69766977
    69776978                last_eqtype, last_eqind = eqtype, eqind
    6978             print "wrt", var
     6979            print("wrt", var)
    69796980
    69806981    def print_nonfinite_jacobian_entries(self, point='opt'):
     
    69896990                Default: 'opt'
    69906991        """
    6991         print "Nonfinite Jacobian entries:"
    6992         print "---------------------------"
     6992        print("Nonfinite Jacobian entries:")
     6993        print("---------------------------")
    69936994        self.print_jacobian_entries(self.find_nonfinite_jacobian_entries(point))
    69946995   
  • branches/dev-5819/Python/src/pyjmi/optimization/dfo.py

    r6917 r13461  
    3030import os
    3131
    32 import thread_feval as tf
     32from . import thread_feval as tf
    3333
    3434try:
     
    172172    if ub is not None:  # "None" < everything
    173173        if N.any(lb >= ub):
    174             raise ValueError, 'Lower bound must be smaller than upper bound.'
     174            raise ValueError('Lower bound must be smaller than upper bound.')
    175175   
    176176    # Check that lb < xstart < ub
    177177    if N.any(xstart <= lb):
    178         raise ValueError, 'xstart must be larger than lb.'
     178        raise ValueError('xstart must be larger than lb.')
    179179    if ub is not None:  # "None" < everything
    180180        if N.any(xstart >= ub):
    181             raise ValueError, 'xstart must be smaller than ub.'
     181            raise ValueError('xstart must be smaller than ub.')
    182182   
    183183    if nbr_cores is None:
     
    228228    Ssize = []
    229229   
    230     print ' '
    231     print 'Running solver Nelder-Mead...'
    232     print ' Initial parameters: ', xstart
    233     print ' '
     230    print(' ')
     231    print('Running solver Nelder-Mead...')
     232    print(' Initial parameters: ', xstart)
     233    print(' ')
    234234   
    235235    if debug:   
     
    291291       
    292292        if k%10 == 1:
    293             print '  %s  %s        %s            %s          %s'%("iter", "fevals", "obj", "term_x", "term_f")
    294         print ' {:>5d} {:>7d} {:>15e} {:>15e} {:>15e}'.format(k, nbr_fevals, f_val[0], ssize, shiftfv)
     293            print('  %s  %s        %s            %s          %s'%("iter", "fevals", "obj", "term_x", "term_f"))
     294        print(' {:>5d} {:>7d} {:>15e} {:>15e} {:>15e}'.format(k, nbr_fevals, f_val[0], ssize, shiftfv))
    295295       
    296296        if term_x or term_f:
     
    402402    # Print convergence results
    403403    if disp:
    404         print " "
     404        print(" ")
    405405        if nbr_iters >= max_iters:
    406             print 'Warning: Maximum number of iterations has been exceeded.'
     406            print('Warning: Maximum number of iterations has been exceeded.')
    407407        elif nbr_fevals >= max_fevals:
    408             print 'Warning: Maximum number of function evaluations has been exceeded.'
     408            print('Warning: Maximum number of function evaluations has been exceeded.')
    409409        else:
    410             print 'Optimization terminated successfully.'
     410            print('Optimization terminated successfully.')
    411411            if term_x:
    412                 print 'Terminated due to sufficiently small simplex.'
     412                print('Terminated due to sufficiently small simplex.')
    413413            else:
    414                 print 'Terminated due to sufficiently close function values at the vertices of the simplex.'
    415             print 'Found parameters: ', x_opt
    416         print ' '
    417         print 'Total number of iterations: ' + str(nbr_iters)
    418         print 'Total number of function evaluations: ' + str(nbr_fevals)
    419         print 'Total execution time: ' + str(solve_time) + ' s'
    420         print ' '
     414                print('Terminated due to sufficiently close function values at the vertices of the simplex.')
     415            print('Found parameters: ', x_opt)
     416        print(' ')
     417        print('Total number of iterations: ' + str(nbr_iters))
     418        print('Total number of function evaluations: ' + str(nbr_fevals))
     419        print('Total execution time: ' + str(solve_time) + ' s')
     420        print(' ')
    421421
    422422    # Return results
     
    570570    if ub is not None:  # "None" < everything
    571571        if N.any(lb >= ub):
    572             raise ValueError, 'Lower bound must be smaller than upper bound.'
     572            raise ValueError('Lower bound must be smaller than upper bound.')
    573573   
    574574    # Check that lb < xstart < ub
    575575    if N.any(xstart <= lb):
    576         raise ValueError, 'xstart must be larger than lb.'
     576        raise ValueError('xstart must be larger than lb.')
    577577    if ub is not None:  # "None" < everything
    578578        if N.any(xstart >= ub):
    579             raise ValueError, 'xstart must be smaller than ub.'
     579            raise ValueError('xstart must be smaller than ub.')
    580580   
    581581    # Check that nbr of cores is provided if multithreading is to be used
    582582    if type(func).__name__ != 'function':
    583583        if nbr_cores is None:
    584             raise ValueError, 'The number of processor cores used must be provided.'
     584            raise ValueError('The number of processor cores used must be provided.')
    585585   
    586586    # Convert xstart to float type array and flatten it so that
     
    718718        t_temp = time.clock()
    719719        t_now = t_temp - t0
    720         print ' '
    721         print 'Number of iterations: ' + str(k)
    722         print 'Number of function evaluations: ' + str(nbr_fevals)
    723         print 'Current time: ' + str(t_now) + ' s'
    724         print ' '
    725         print 'Current x value: ' + str(X[0])
    726         print 'Current function value: ' + str(f_val[0])
    727         print ' '
     720        print(' ')
     721        print('Number of iterations: ' + str(k))
     722        print('Number of function evaluations: ' + str(nbr_fevals))
     723        print('Current time: ' + str(t_now) + ' s')
     724        print(' ')
     725        print('Current x value: ' + str(X[0]))
     726        print('Current function value: ' + str(f_val[0]))
     727        print(' ')
    728728           
    729729        if plot_sim:
     
    747747        term_f = shiftfv < f_tol
    748748       
    749         print 'Termination criterion for x: ' + str(ssize)
    750         print 'Termination criterion for the objective function: ' + str(shiftfv)
    751         print ' '
     749        print('Termination criterion for x: ' + str(ssize))
     750        print('Termination criterion for the objective function: ' + str(shiftfv))
     751        print(' ')
    752752       
    753753        if term_x or term_f:
     
    896896    # Plot convergence criteria
    897897    if plot_conv:
    898         iters = range(len(F_val))
     898        iters = list(range(len(F_val)))
    899899        # Plot shiftfv vs iterations
    900900        plt.figure()
     
    918918    # Print convergence results
    919919    if disp:
    920         print ' '
    921         print 'Solver: Nelder-Mead'
    922         print ' '
     920        print(' ')
     921        print('Solver: Nelder-Mead')
     922        print(' ')
    923923        if nbr_iters >= max_iters:
    924             print 'Warning: Maximum number of iterations has been exceeded.'
     924            print('Warning: Maximum number of iterations has been exceeded.')
    925925        elif nbr_fevals >= max_fevals:
    926             print 'Warning: Maximum number of function evaluations has been exceeded.'
     926            print('Warning: Maximum number of function evaluations has been exceeded.')
    927927        else:
    928             print 'Optimization terminated successfully.'
     928            print('Optimization terminated successfully.')
    929929            if term_x:
    930                 print 'Terminated due to sufficiently small simplex.'
     930                print('Terminated due to sufficiently small simplex.')
    931931            else:
    932                 print 'Terminated due to sufficiently close function values at the vertices of the simplex.'
    933         print ' '
    934         print 'Total number of iterations: ' + str(nbr_iters)
    935         print 'Total number of function evaluations: ' + str(nbr_fevals)
    936         print 'Total execution time: ' + str(solve_time) + ' s'
    937         print ' '
     932                print('Terminated due to sufficiently close function values at the vertices of the simplex.')
     933        print(' ')
     934        print('Total number of iterations: ' + str(nbr_iters))
     935        print('Total number of function evaluations: ' + str(nbr_fevals))
     936        print('Total execution time: ' + str(solve_time) + ' s')
     937        print(' ')
    938938
    939939    # Return results
     
    10371037    # If no bounds are given this function should not be used
    10381038    if lb is None and ub is None:
    1039         raise ValueError, 'No bounds given, use function nelme instead.'
     1039        raise ValueError('No bounds given, use function nelme instead.')
    10401040   
    10411041    # Check that lb < ub
    10421042    if ub is not None:  # "None" < everything
    10431043        if N.any(lb >= ub):
    1044             raise ValueError, 'Lower bound must be smaller than upper bound.'
     1044            raise ValueError('Lower bound must be smaller than upper bound.')
    10451045   
    10461046    # Check that lb < xstart < ub
    10471047    if N.any(xstart <= lb):
    1048         raise ValueError, 'xstart must be larger than lb.'
     1048        raise ValueError('xstart must be larger than lb.')
    10491049    if ub is not None:  # "None" < everything
    10501050        if N.any(xstart >= ub):
    1051             raise ValueError, 'xstart must be smaller than ub.'
     1051            raise ValueError('xstart must be smaller than ub.')
    10521052   
    10531053    # Convert xstart to float type array and flatten it so that
     
    11571157                    - N.log(x_grid-lb[0]) - N.log(y_grid-lb[1])
    11581158            Z = z + mu*b
    1159             print 'Z: ' + str(Z)
     1159            print('Z: ' + str(Z))
    11601160            plt.figure()
    11611161            plt.grid()
     
    12181218    # Print convergence results
    12191219    if disp:
    1220         print ' '
    1221         print 'Solver: Sequential barrier method with Nelder-Mead'
    1222         print ' '
     1220        print(' ')
     1221        print('Solver: Sequential barrier method with Nelder-Mead')
     1222        print(' ')
    12231223        if nbr_iters >= max_iters:
    1224             print 'Warning: Maximum number of iterations has been exceeded.'
     1224            print('Warning: Maximum number of iterations has been exceeded.')
    12251225        elif nbr_fevals >= max_fevals:
    1226             print 'Warning: Maximum number of function evaluations has been exceeded.'
     1226            print('Warning: Maximum number of function evaluations has been exceeded.')
    12271227        else:
    1228             print 'Optimization terminated successfully.'
     1228            print('Optimization terminated successfully.')
    12291229            if term_x:
    1230                 print 'Termination criteria for x was fulfilled.'
     1230                print('Termination criteria for x was fulfilled.')
    12311231            else:
    1232                 print 'Termination criteria for auxiliary function was fulfilled.'
    1233         print ' '
    1234         print 'Number of iterations: ' + str(nbr_iters)
    1235         print 'Number of function evaluations: ' + str(nbr_fevals)
    1236         print ' '
    1237         print 'Execution time: ' + str(solve_time) + ' s'
    1238         print ' '
     1232                print('Termination criteria for auxiliary function was fulfilled.')
     1233        print(' ')
     1234        print('Number of iterations: ' + str(nbr_iters))
     1235        print('Number of function evaluations: ' + str(nbr_fevals))
     1236        print(' ')
     1237        print('Execution time: ' + str(solve_time) + ' s')
     1238        print(' ')
    12391239   
    12401240    # Return results
     
    13221322    # Check that lb < ub
    13231323    if N.any(lb >= ub):
    1324         raise ValueError, 'Lower bound must be smaller than upper bound.'
     1324        raise ValueError('Lower bound must be smaller than upper bound.')
    13251325   
    13261326    if plot:
     
    13481348   
    13491349    if disp:
    1350         print ' '
    1351         print 'Solver: OpenOpt solver ' + solver
    1352         print ' '
    1353         print 'Number of iterations: ' + str(nbr_iters)
    1354         print 'Number of function evaluations: ' + str(nbr_fevals)
    1355         print ' '
    1356         print 'Execution time: ' + str(solve_time)
    1357         print ' '
     1350        print(' ')
     1351        print('Solver: OpenOpt solver ' + solver)
     1352        print(' ')
     1353        print('Number of iterations: ' + str(nbr_iters))
     1354        print('Number of function evaluations: ' + str(nbr_fevals))
     1355        print(' ')
     1356        print('Execution time: ' + str(solve_time))
     1357        print(' ')
    13581358   
    13591359    # Return results
     
    14401440    # Check that lb < ub
    14411441    if N.any(lb >= ub):
    1442         raise ValueError, 'Lower bound must be smaller than upper bound.'
     1442        raise ValueError('Lower bound must be smaller than upper bound.')
    14431443   
    14441444    if plot:
     
    14661466   
    14671467    if disp:
    1468         print ' '
    1469         print 'Solver: OpenOpt solver ' + solver
    1470         print ' '
    1471         print 'Number of iterations: ' + str(nbr_iters)
    1472         print 'Number of function evaluations: ' + str(nbr_fevals)
    1473         print ' '
    1474         print 'Execution time: ' + str(solve_time)
    1475         print ' '
     1468        print(' ')
     1469        print('Solver: OpenOpt solver ' + solver)
     1470        print(' ')
     1471        print('Number of iterations: ' + str(nbr_iters))
     1472        print('Number of function evaluations: ' + str(nbr_fevals))
     1473        print(' ')
     1474        print('Execution time: ' + str(solve_time))
     1475        print(' ')
    14761476   
    14771477    # Return results
     
    16561656    if lb is None and ub is None:
    16571657        if alg == 2:
    1658             raise ValueError, 'Method 2 can only be chosen if bounds are provided.'
     1658            raise ValueError('Method 2 can only be chosen if bounds are provided.')
    16591659        if alg == 3:
    1660             raise ValueError, 'Method 3 can only be chosen if bounds are provided.'
     1660            raise ValueError('Method 3 can only be chosen if bounds are provided.')
    16611661        if alg == 4:
    1662             raise ValueError, 'Method 4 can only be chosen if bounds are provided.'
     1662            raise ValueError('Method 4 can only be chosen if bounds are provided.')
    16631663    elif lb is None or ub is None:
    16641664        if alg == 3:
    1665             raise ValueError, 'Method 3 can only be chosen if both upper and lower bounds are provided.'
     1665            raise ValueError('Method 3 can only be chosen if both upper and lower bounds are provided.')
    16661666        if alg == 4:
    1667             raise ValueError, 'Method 4 can only be chosen if both upper and lower bounds are provided.'
     1667            raise ValueError('Method 4 can only be chosen if both upper and lower bounds are provided.')
    16681668                             
    16691669    # Check that xstart is given if alg = 1 or 2                         
    16701670    if alg == 1 or alg == 2:
    16711671        if xstart is None:
    1672             raise ValueError, 'Methods 1 and 2 require a starting point.'
     1672            raise ValueError('Methods 1 and 2 require a starting point.')
    16731673   
    16741674    if type(func).__name__ != 'function':
    16751675        if alg != 1:
    1676             raise ValueError, 'If other than the Nelder-Mead method is chosen, func must be of function type.'
     1676            raise ValueError('If other than the Nelder-Mead method is chosen, func must be of function type.')
    16771677   
    16781678    # Solve the problem
     
    18231823   
    18241824    if len(t_meas) != n1:
    1825         raise ValueError, 't_meas and y_meas must have the same length.'
     1825        raise ValueError('t_meas and y_meas must have the same length.')
    18261826   
    18271827    if len(t_sim) != n2:
    1828         raise ValueError, 't_sim and y_sim must have the same length.'
     1828        raise ValueError('t_sim and y_sim must have the same length.')
    18291829   
    18301830    if m1 != m2:
    1831         raise ValueError, 'y_meas and y_sim must have the same number of rows.'
     1831        raise ValueError('y_meas and y_sim must have the same number of rows.')
    18321832   
    18331833    if not N.all(N.diff(t_sim) >= 0):
    1834         raise ValueError, 't_sim must be increasing.'
     1834        raise ValueError('t_sim must be increasing.')
    18351835   
    18361836    if w is None:
     
    18421842        if dim1 == 1:
    18431843            if N.ndim(w) != 0:
    1844                 raise ValueError, 'w must be a scalar since y_meas and y_sim only have one dimension.'
     1844                raise ValueError('w must be a scalar since y_meas and y_sim only have one dimension.')
    18451845        else:
    18461846            if N.ndim(w) != 1:
    1847                 raise ValueError, 'w must be a 1-dimensional array since y_meas and y_sim are 2-dimensional.'
     1847                raise ValueError('w must be a 1-dimensional array since y_meas and y_sim are 2-dimensional.')
    18481848            if (len(w) != m1):
    1849                 raise ValueError, 'w must have the same length as the number of rows in y_meas and y_sim.'
     1849                raise ValueError('w must have the same length as the number of rows in y_meas and y_sim.')
    18501850           
    18511851    # The number of measurement points
  • branches/dev-5819/Python/src/pyjmi/optimization/func_eval.py

    r6917 r13461  
    4242# Execute the file containing the definition of the function to be evaluated
    4343func_file_name = sys.argv[-2]
    44 execfile(func_file_name)
     44exec(compile(open(func_file_name, "rb").read(), func_file_name, 'exec'))
    4545
    4646# Get the actual function
  • branches/dev-5819/Python/src/pyjmi/optimization/gen_nice_qt_plot.py

    r6917 r13461  
    5050shooter.h(N.array(opt_vals))
    5151print('z')
    52 print(model._m.getZ())
     52print((model._m.getZ()))
    5353
    5454interval = [0., 5.]
  • branches/dev-5819/Python/src/pyjmi/optimization/greybox.py

    r8200 r13461  
    2626from pyjmi import get_files_path
    2727from casadi import MX
    28 import cPickle as pickle
     28import pickle as pickle
    2929import modelicacasadi_wrapper as mc
    3030from scipy.stats import chi2
     
    156156            self.weight = options['n_e']/(self.tf-self.t0)
    157157           
    158             for var in measurements.keys():
     158            for var in list(measurements.keys()):
    159159                # Add parameter for noise convariance, set initial guess to base nominal squared
    160160                r = self._add_real_parameter(self.prefix+'r_'+var)
     
    181181            # add parameters for noise convariance of measured variables
    182182            # add timed variable for each variable and measurementpoint
    183             for var in measurements.keys():
     183            for var in list(measurements.keys()):
    184184               
    185185                # Add parameter for noise convariance, set initial guess to base nominal squared
     
    218218        # add external data for measured variables
    219219        if self.costType == "integral":
    220             for (name, data) in self.measurements.items():
     220            for (name, data) in list(self.measurements.items()):
    221221                dictionary[self.prefix+'measured_'+name] = np.vstack([self.time,data])
    222222       
    223223        # add external data for inputs   
    224         for (name, data) in self.inputs.items():
     224        for (name, data) in list(self.inputs.items()):
    225225            dictionary[name] = np.vstack([self.time,data])
    226226   
     
    319319        # print currently free parameters
    320320        print ('Identifying with free parameters:')
    321         print self.free_parameters
     321        print(self.free_parameters)
    322322        res = self.op.optimize(options=self.options)
    323323       
     
    545545            for par in additionalFree:
    546546                print(par)
    547             print("Cost: %f" % obj.cost)
     547            print(("Cost: %f" % obj.cost))
    548548            costred = self.cost-obj.cost
    549             print("Cost reduction: %f" % costred)
     549            print(("Cost reduction: %f" % costred))
    550550            risk= self.calculate_risk(costred, dof, cases)
    551             print("Risk: %f" % risk )
     551            print(("Risk: %f" % risk ))
    552552            print("")
    553553
  • branches/dev-5819/Python/src/pyjmi/optimization/ipopt.py

    r9809 r13461  
    940940                        p_opt_data[i_pi_opt] = traj.x[0]
    941941                except VariableNotFoundError:
    942                     print "Warning: Could not find value for parameter " + name
     942                    print("Warning: Could not find value for parameter " + name)
    943943                   
    944944        #print(N.size(var_data))
     
    975975                dx_index = dx_index + 1
    976976                col_index = col_index + 1
    977                 print "Warning: Could not find trajectory for derivative variable " + name
     977                print("Warning: Could not find trajectory for derivative variable " + name)
    978978        for name in x_names:
    979979            try:
     
    990990                x_index = x_index + 1
    991991                col_index = col_index + 1
    992                 print "Warning: Could not find trajectory for state variable " + name
     992                print("Warning: Could not find trajectory for state variable " + name)
    993993
    994994        for name in u_names:
     
    10121012                u_index = u_index + 1
    10131013                col_index = col_index + 1
    1014                 print "Warning: Could not find trajectory for input variable " + name
     1014                print("Warning: Could not find trajectory for input variable " + name)
    10151015
    10161016        for name in w_names:
     
    10341034                w_index = w_index + 1
    10351035                col_index = col_index + 1
    1036                 print "Warning: Could not find trajectory for algebraic variable " + name
     1036                print("Warning: Could not find trajectory for algebraic variable " + name)
    10371037
    10381038        #print(var_data)
  • branches/dev-5819/Python/src/pyjmi/optimization/mhe/check_mhe_inputs.py

    r7612 r13461  
    338338    for (list, cov_matrix) in cov_list:
    339339        #Check if the list is a string
    340         if isinstance(list, basestring):
     340        if isinstance(list, str):
    341341            var = op.getVariable(list)
    342342            if var == None:
  • branches/dev-5819/Python/src/pyjmi/optimization/mhe/ekf_arrival_cost.py

    r7612 r13461  
    2020import sys
    2121import modelicacasadi_wrapper as mc
     22from functools import reduce
    2223
    2324
     
    171172
    172173        # Substitute named variables with vector variables in expressions
    173         named_vars = reduce(list.__add__, named_mvar_struct.values())
     174        named_vars = reduce(list.__add__, list(named_mvar_struct.values()))
    174175        self._mvar_struct = OrderedDict()
    175176        self._mvar_struct["time"] = casadi.MX.sym("time")
     
    359360        #Sort Values for reference point
    360361        stop=False
    361         for vt in z0.keys():
     362        for vt in list(z0.keys()):
    362363            RefPoint[vt] = N.zeros(self._nvar[vt])
    363364            passed_indices = list()
     
    383384     
    384385        missing_types = [vt for vt in var_kinds \
    385                          if vt not in z0.keys() and self._nvar[vt]!=0]
     386                         if vt not in list(z0.keys()) and self._nvar[vt]!=0]
    386387        if len(missing_types) !=0:
    387388            error_message = "Error: Please provide the " +\
     
    699700        for (list, cov_matrix) in cov_list:
    700701            #Check if the expected iterable object is instead a string
    701             if isinstance(list, basestring):
     702            if isinstance(list, str):
    702703                i = name_list.index(list)
    703704                matrix[i, i] = cov_matrix
  • branches/dev-5819/Python/src/pyjmi/optimization/mhe/mhe.py

    r8201 r13461  
    2222import modelicacasadi_wrapper as mc
    2323
    24 from ekf_arrival_cost import EKFArrivalCost
    25 import check_mhe_inputs as check
     24from .ekf_arrival_cost import EKFArrivalCost
     25from . import check_mhe_inputs as check
    2626
    2727
     
    139139   
    140140        self.x_est = N.zeros((self._size_dict['x'],1))
    141         for name, value in self._x_0_guess.items():
     141        for name, value in list(self._x_0_guess.items()):
    142142            row = self._variable_row_map[name]
    143143            self.x_est[row,0] = value
     
    201201                model.
    202202        """
    203         old_state_names = x_0_guess.keys()
     203        old_state_names = list(x_0_guess.keys())
    204204        corresponding_model_names = [self.op.getModelVariable(name).getName() \
    205205                                     for name in old_state_names]
    206         state_alias_dict = dict(zip(corresponding_model_names, old_state_names))
     206        state_alias_dict = dict(list(zip(corresponding_model_names, old_state_names)))
    207207        return state_alias_dict
    208208     
     
    284284        #Check x_0_guess and generate a new dict with the aliases replaced
    285285        x_0_guess_items = check.check_tuple_list(self.op,
    286                                                  self._x_0_guess.items(),
     286                                                 list(self._x_0_guess.items()),
    287287                                                 self._state_names,
    288288                                                 'x_0_guess')
     
    400400            var.setAttribute('free',True)
    401401       
    402         initial_value_dict = dict(zip(states, initial_value_pars))
     402        initial_value_dict = dict(list(zip(states, initial_value_pars)))
    403403        initial_value_pars = [initial_value_dict[name] \
    404404                              for name in self._state_names]
     
    612612        matrix_index_par_list = []
    613613        for (list, cov_matrix) in cov_list:
    614             if isinstance(list, basestring):
     614            if isinstance(list, str):
    615615                par_string = matrix_name + '_' + list
    616616                #Check if parameter already exists
  • branches/dev-5819/Python/src/pyjmi/optimization/mhe/mhe_initial_values.py

    r7612 r13461  
    2424import numpy as N
    2525from pyjmi.optimization.casadi_collocation import ExternalData
    26 import check_mhe_inputs as check
     26from . import check_mhe_inputs as check
    2727
    2828def optimize_for_initial_values(op, x_0_guess, u_0, MHE_opts):
     
    252252   
    253253    x_0_guess_items = check.check_tuple_list(op,
    254                                              x_0_guess.items(),
     254                                             list(x_0_guess.items()),
    255255                                             state_names,
    256256                                             'x_0_guess')
     
    258258   
    259259    u_0_items = check.check_tuple_list(op,
    260                                        u_0.items(),
     260                                       list(u_0.items()),
    261261                                       opts['input_names'],
    262262                                       'u_0')
  • branches/dev-5819/Python/src/pyjmi/optimization/mpc.py

    r8230 r13461  
    159159        # Check if nominal trajectories provided
    160160        if self.options['nominal_traj'] != None:
    161             print('Warning: Nominal trajectories will not work as intended '+\
     161            print(('Warning: Nominal trajectories will not work as intended '+\
    162162                 'with the MPC class. The trajectories will not shift with '+\
    163                  'the shifting optimization horizon.')
     163                 'the shifting optimization horizon.'))
    164164       
    165165        # Check if external data provided
    166166        if self.options['external_data'] != None:
    167             print('Warning: Using external_data to provide reference '+\
     167            print(('Warning: Using external_data to provide reference '+\
    168168                 'trajectories will not work as intended with the MPC class.'+\
    169169                 'The trajectories do not shift with the shifting '+\
    170                  'optimization horizon.')
     170                 'optimization horizon.'))
    171171                 
    172172        # Soften variable bounds and add u0-parameters for blockingfactors
     
    214214        bf = self.options['blocking_factors']
    215215        if bf is not None:
    216             for key in bf.du_quad_pen.keys():
     216            for key in list(bf.du_quad_pen.keys()):
    217217                var_par = casadi.MX.sym("%s_0" %key)
    218218                var =  ci.RealVariable(self.op, var_par, 2, 1)
     
    249249                pc.append(constr)
    250250
    251             for key in bf.du_bounds.keys():
     251            for key in list(bf.du_bounds.keys()):
    252252                # Find or create new _0 parameter
    253253                var_par = self.op.getVariable("%s_0" %key)
     
    327327
    328328        # Change bounds on variables to soft constraints
    329         for name in self.constr_viol_costs.keys():
     329        for name in list(self.constr_viol_costs.keys()):
    330330            var = self.op.getVariable(name)
    331331
     
    416416                                            " free element lengths.")
    417417            else:
    418                 bf = self.options['blocking_factors'].factors.values()[0]
     418                bf = list(self.options['blocking_factors'].factors.values())[0]
    419419                if bf[0] != self.n_e_s:
    420420                    raise ValueError("The first value in the blocking factor"+\
     
    430430            self.op.set('finalTime',self.op.get('startTime')+self.horizon_time)
    431431            #print("Warning: The final time has been changed to %s" % op.get('finalTime'))
    432         print("The prediction horizon is %s" % self.horizon_time)
     432        print(("The prediction horizon is %s" % self.horizon_time))
    433433
    434434    def _calculate_nbr_values_sample(self):
     
    492492                self.collocator.solver_object.setOption('print_level', 0)
    493493                                                   
    494             for key in self.warm_start_options.keys():
     494            for key in list(self.warm_start_options.keys()):
    495495                self.collocator.solver_object.setOption(key,\
    496496                                                self.warm_start_options[key])
     
    502502            self.collocator.solver_object.setOption('InitialLMest', False)
    503503           
    504             for key in self.warm_start_options.keys():
     504            for key in list(self.warm_start_options.keys()):
    505505                self.collocator.solver_object.setOption(key,\
    506506                                                self.warm_start_options[key])
     
    660660                        self.collocator.mvar_vectors['unelim_u']
    661661                        if var.getName() not in
    662                         self.options['blocking_factors'].factors.keys()]
     662                        list(self.options['blocking_factors'].factors.keys())]
    663663                   
    664664        n_cont_u = len(u_cont_names)
     
    677677        start_bf_u = end_cont_u
    678678
    679         for name in self.options['blocking_factors'].factors.keys():
     679        for name in list(self.options['blocking_factors'].factors.keys()):
    680680            factors = self.options['blocking_factors'].factors[name]
    681681
     
    761761
    762762        # Updates states
    763         for key in state_dict.keys():
    764             if not self.index.has_key(key):
     763        for key in list(state_dict.keys()):
     764            if key not in self.index:
    765765                raise ValueError("You are not allowed to change %s using this\
    766766                                method. Use MPC.set()-method instead." %key)
     
    831831                        self.collocator.xx_init = self.collocator.primal_opt
    832832                else:
    833                     print("Warning: A new initial guess for the primal " +\
    834                           "variables have not been specified for this sample.")
     833                    print(("Warning: A new initial guess for the primal " +\
     834                          "variables have not been specified for this sample."))
    835835       
    836836        # Initiate the warm start
     
    10461046        """
    10471047        for i, stat in enumerate(self.solver_stats):
    1048             print("%s: %s: %s iterations in %s seconds" %(i+1, stat[0], \
    1049                                                 stat[1], stat[3]))
     1048            print(("%s: %s: %s iterations in %s seconds" %(i+1, stat[0], \
     1049                                                stat[1], stat[3])))
    10501050    def get_solver_stats(self):
    10511051        """
  • branches/dev-5819/Python/src/pyjmi/optimization/polynomial.py

    r8119 r13461  
    3131        'Could not find CasADi package, aborting.')
    3232
    33 class LocalPol(object):
     33class LocalPol(object, metaclass=abc.ABCMeta):
    3434   
    3535    """
    3636    Abstract base class for Lagrange polynomials used for local collocation.
    3737    """
    38    
    39     __metaclass__ = abc.ABCMeta
    4038   
    4139    def __init__(self, n):
     
    6361        # Derivatives of all basis polynomials at all interpolation points
    6462        der_vals = casadi.DMatrix.ones(self.n + 1, self.n + 1)
    65         for j in xrange(self.n + 1):
    66             for k in xrange(self.n + 1):
     63        for j in range(self.n + 1):
     64            for k in range(self.n + 1):
    6765                der_vals[j, k] = lagrange_derivative_eval(self.p, j,
    6866                                                          self.p[k])
  • branches/dev-5819/Python/src/pyjmi/optimization/realtimecontrol.py

    r10313 r13461  
    8282     
    8383     
    84 class RealTimeBase(object):
    85    
    86     __metaclass__ = ABCMeta
     84class RealTimeBase(object, metaclass=ABCMeta):
    8785   
    8886    def __init__(self, dt, t_final, start_values, output_names,
     
    157155        self.wait_times.append(end_wait_time - start_wait_time)
    158156        if late_time > self.dt/10.0:
    159             print 'WARNING: Sample late by', late_time, 's.'
     157            print('WARNING: Sample late by', late_time, 's.')
    160158        return data
    161159       
     
    372370        op = transfer_optimization_problem(opt_name, file_path,
    373371                                           compiler_options = {'state_initial_equations' : True,"common_subexp_elim":False})
    374         op.set(par_values.keys(), par_values.values())
     372        op.set(list(par_values.keys()), list(par_values.values()))
    375373                                           
    376374        opt_opts = op.optimize_options()
     
    494492            new_pars = self.par_changes.get_new_pars(k*self.dt)
    495493            if new_pars != None:
    496                 self.solver.op.set(new_pars.keys(), new_pars.values())
     494                self.solver.op.set(list(new_pars.keys()), list(new_pars.values()))
    497495           
    498496            self.solver.update_state(x_k)
     
    506504                self.solve_times.append(solve_time)
    507505                if solve_time > self.dt*0.2:
    508                     print 'WARNING: Control signal late by', solve_time, 's'
     506                    print('WARNING: Control signal late by', solve_time, 's')
    509507            if self._ia:
    510508                self.send_control_signal(u_k_e)
     
    529527        self.ptime = time.clock()-time1
    530528        self.rtime = time.time()-time2
    531         print 'Processor time:', self.ptime, 's'
    532         print 'Real time:', self.rtime, 's'
     529        print('Processor time:', self.ptime, 's')
     530        print('Real time:', self.rtime, 's')
    533531       
    534532        if save:
     
    609607
    610608        t_total = total_times['t_mainloop']
    611         print 'Total times:'
     609        print('Total times:')
    612610        for name in stat_names:
    613             print("%19s: %6.4f s (%7.3f%%)" %(name, total_times[name], total_times[name]/t_total*100))
     611            print(("%19s: %6.4f s (%7.3f%%)" %(name, total_times[name], total_times[name]/t_total*100)))
    614612   
    615613    def save_results(self, filename=None):
     
    741739                              compiler_options = {'state_initial_equations' : True})
    742740        self.model = load_fmu(sim_fmu)
    743         self.model.set(start_values.keys(), start_values.values())
    744         self.model.set(par_values.keys(), par_values.values())
     741        self.model.set(list(start_values.keys()), list(start_values.values()))
     742        self.model.set(list(par_values.keys()), list(par_values.values()))
    745743        self.model.initialize()
    746744        self.t = 0
     
    940938            new_pars = self.par_changes.get_new_pars(k*self.dt)
    941939            if new_pars != None:
    942                 for name, value in new_pars.items():
     940                for name, value in list(new_pars.items()):
    943941                    ctrl_point[name] = value
    944942                   
    945             for name, value in ctrl_point.items():
     943            for name, value in list(ctrl_point.items()):
    946944                if name in self.outputs:
    947945                    x_k['_start_' + name] -= value
     
    950948            if len(self.inputs) == 1:
    951949                control_signal = [control_signal]
    952             for name, value in ctrl_point.items():
     950            for name, value in list(ctrl_point.items()):
    953951                if name in self.inputs:
    954952                    i = self.inputs.index(name)
     
    968966                self.solve_times.append(solve_time)
    969967                if solve_time > self.dt*0.2:
    970                     print 'WARNING: Control signal late by', solve_time, 's'
     968                    print('WARNING: Control signal late by', solve_time, 's')
    971969            if self._ia:
    972970                self.send_control_signal(u_k_e)
     
    990988        self.ptime = time.clock()-time1
    991989        self.rtime = time.time()-time2
    992         print 'Processor time:', self.ptime, 's'
    993         print 'Real time:', self.rtime, 's'
     990        print('Processor time:', self.ptime, 's')
     991        print('Real time:', self.rtime, 's')
    994992       
    995993        if save:
     
    11671165                              compiler_options = {'state_initial_equations' : True})
    11681166        self.model = load_fmu(sim_fmu)
    1169         self.model.set(start_values.keys(), start_values.values())
    1170         self.model.set(par_values.keys(), par_values.values())
     1167        self.model.set(list(start_values.keys()), list(start_values.values()))
     1168        self.model.set(list(par_values.keys()), list(par_values.values()))
    11711169        self.model.initialize()
    11721170        self.t = 0
     
    12221220   
    12231221    if filename is None:
    1224         filename = raw_input('Enter file name to save as: ')
     1222        filename = input('Enter file name to save as: ')
    12251223    if filename != '':
    12261224        if '.' not in filename:
     
    12471245   
    12481246    if filename is None:
    1249         filename = raw_input('Enter file name to load: ')
     1247        filename = input('Enter file name to load: ')
    12501248    if '.' not in filename:
    12511249        filename += '.pkl'
  • branches/dev-5819/Python/src/pyjmi/optimization/thread_feval.py

    r10348 r13461  
    8484        retval = th.retval
    8585        if retval != 0:
    86             raise OSError, 'Something went wrong with the function evaluation: os.system did not return 0.'
     86            raise OSError('Something went wrong with the function evaluation: os.system did not return 0.')
    8787        f_string = file(dir_name+'/f_value.txt').read()
    8888        fval = eval(f_string)
     
    106106            retval = threads[i].retval
    107107            if retval != 0:
    108                 raise OSError, 'Something went wrong with the function evaluation: os.system did not return 0.'
     108                raise OSError('Something went wrong with the function evaluation: os.system did not return 0.')
    109109            dir_name = 'dir_'+str(i+1)
    110110            f_string = file(dir_name+'/f_value.txt').read()
  • branches/dev-5819/Python/src/pyjmi/symbolic_elimination.py

    r9492 r13461  
    2727from pyjmi.common.core import ModelBase
    2828from pyjmi.common.algorithm_drivers import OptionBase
     29from functools import reduce
    2930
    3031class EliminationOptions(OptionBase):
     
    171172        pass
    172173
    173     def __nonzero__(self):
     174    def __bool__(self):
    174175        raise RuntimeError("BUG: Undefined Boolean value")
    175176
     
    221222    if deps is None:
    222223        deps = len(mx_vars) * [False]
    223     for i in xrange(expr.getNdeps()):
     224    for i in range(expr.getNdeps()):
    224225        dep = expr.getDep(i)
    225         deps = map(any, zip(deps, [casadi.isEqual(dep, var) for var in mx_vars]))
     226        deps = list(map(any, list(zip(deps, [casadi.isEqual(dep, var) for var in mx_vars]))))
    226227        deps = find_deps(dep, mx_vars, deps)
    227228    return deps
     
    322323        res_f.init()
    323324        is_linear = True
    324         for i in xrange(self.n):
    325             for j in xrange(self.n):
     325        for i in range(self.n):
     326            for j in range(self.n):
    326327                # Check if jac[i, j] depends on block unknowns
    327328                if casadi.dependsOn(res_f.jac(i, j), self.mx_vars):
     
    345346        print("Chosen causal variables: \n")
    346347        for var in self.block_causal_vars:
    347             print("\t%s" % var.name)
     348            print(("\t%s" % var.name))
    348349        print("\nChosen tearing variables: \n")
    349350        for var in self.block_tear_vars:
    350             print("\t%s" % var.name)
     351            print(("\t%s" % var.name))
    351352        print("\nChosen causal equations (ID: expression): \n")
    352353        for eq in self.block_causal_equations:
    353             print("\t%d: %s" % (eq.global_index, eq.string))
     354            print(("\t%d: %s" % (eq.global_index, eq.string)))
    354355        print("\nChosen tearing residuals: \n")
    355356        for eq in self.block_tear_res:
    356             print("\t%d: %s" % (eq.global_index, eq.string))
     357            print(("\t%d: %s" % (eq.global_index, eq.string)))
    357358
    358359    def create_lin_eq(self, known_vars, solved_vars, tear_vars):
     
    372373        # Create coefficient function
    373374        A = []
    374         for i in xrange(self.n):
     375        for i in range(self.n):
    375376            jac_f = res_f.jacobian(i)
    376377            jac_f.setOption("name", "block_jacobian")
     
    432433        # Update component indices
    433434        i = 0
    434         for (eq, var) in itertools.izip(causal_equations, causal_variables):
     435        for (eq, var) in zip(causal_equations, causal_variables):
    435436            eq.local_index = i
    436437            var.local_index = i
     
    525526        # Update component indices
    526527        i = 0
    527         for (eq, var) in itertools.izip(causal_equations, causal_variables):
     528        for (eq, var) in zip(causal_equations, causal_variables):
    528529            eq.local_index = i
    529530            var.local_index = i
     
    862863
    863864            # Plot vertices
    864             for i in xrange(i_star + 1):
     865            for i in range(i_star + 1):
    865866                if i % 2 == 0:
    866867                    for eq in L[i]:
     
    881882
    882883            # Plot edges
    883             for i in xrange(i_star):
     884            for i in range(i_star):
    884885                for (u, v) in E[i]:
    885886                    if i % 2 == 0:
     
    893894        # Compute vertex successors
    894895        successors = {}
    895         for i in xrange(i_star):
     896        for i in range(i_star):
    896897            for v in L[i+1]:
    897898                successors[v] = []
     
    919920                        del stack[0] # Remove source
    920921                        del stack[-1] # Remove sink
    921                         for i in xrange(len(stack)-1):
     922                        for i in range(len(stack)-1):
    922923                            if i % 2 == 0:
    923924                                path.append((stack[i+1], stack[i]))
     
    10031004            expr = equation.expression
    10041005            deps_incidence = np.array(find_deps(expr, mx_vars))
    1005             deps_equal = np.array(map(lambda mx_var: casadi.isEqual(expr, mx_var), mx_vars))
     1006            deps_equal = np.array([casadi.isEqual(expr, mx_var) for mx_var in mx_vars])
    10061007            deps = deps_incidence + deps_equal
    10071008            for (i, var) in enumerate(variables):
     
    11101111
    11111112        # Sort free/fixed parameters
    1112         fixed_pars = filter(lambda par: not model.get_attr(par, "free"), pars)
    1113         free_pars = filter(lambda par: model.get_attr(par, "free"), pars)
     1113        fixed_pars = [par for par in pars if not model.get_attr(par, "free")]
     1114        free_pars = [par for par in pars if model.get_attr(par, "free")]
    11141115        mvar_vectors['p_fixed'] = fixed_pars
    11151116        n_var['p_fixed'] = len(mvar_vectors['p_fixed'])
     
    11381139        i = 0
    11391140        for vk in ["dx", "w"]:
    1140             for (mvar, mx_var) in itertools.izip(mvar_vectors[vk], mx_var_struct[vk]):
     1141            for (mvar, mx_var) in zip(mvar_vectors[vk], mx_var_struct[vk]):
    11411142                if self.options['tearing'] and mvar.getTearing():
    11421143                    tearing = True
     
    11481149        # Create equations
    11491150        i = 0
    1150         for (named_res, named_eq) in itertools.izip(named_dae, named_dae_equations):
     1151        for (named_res, named_eq) in zip(named_dae, named_dae_equations):
    11511152            if self.options['tearing'] and named_eq.getTearing():
    11521153                tearing = True
     
    12041205        # Create list of named MX variables
    12051206        mx_var_struct = self._mx_var_struct
    1206         mx_vars = list(itertools.chain.from_iterable(mx_var_struct.values()))
     1207        mx_vars = list(itertools.chain.from_iterable(list(mx_var_struct.values())))
    12071208        time = mx_var_struct['time']
    12081209        dx = mx_var_struct['dx']
     
    15021503        # Find untorn dependencies, excluding block variable
    15031504        deps = []
    1504         for i in xrange(co.n):
     1505        for i in range(co.n):
    15051506            for vk in ['dx', 'x', 'u', 'w', 'p_opt']:
    15061507                for dae_var in self._mx_var_struct[vk]:
     
    15601561        n_alg_before = len([var for var in self._model.getVariables(self._model.REAL_ALGEBRAIC) if not var.isAlias()])
    15611562        n_alg_after = len([var for var in self.getVariables(self.REAL_ALGEBRAIC) if not var.isAlias()])
    1562         print('\nSystem has %d algebraic variables before elimination and %d after.' % (n_alg_before, n_alg_after))
     1563        print(('\nSystem has %d algebraic variables before elimination and %d after.' % (n_alg_before, n_alg_after)))
    15631564        n_blocks = len(self._graph.components)
    15641565        if n_blocks > 3:
    1565             print('The three largest BLT blocks have sizes %d, %d, and %d.\n' % tuple(block_sizes[-1:-4:-1]))
     1566            print(('The three largest BLT blocks have sizes %d, %d, and %d.\n' % tuple(block_sizes[-1:-4:-1])))
    15661567        else:
    1567             print('The system has %d BLT blocks of sizes: %s' % (n_blocks, block_sizes[::-1]))
     1568            print(('The system has %d BLT blocks of sizes: %s' % (n_blocks, block_sizes[::-1])))
    15681569
    15691570    def getVariables(self, vk):
     
    16951696        if n_path > 0:
    16961697            [path_lhs, path_rhs] = \
    1697                     map(list, zip(*[(constraint.getLhs(), constraint.getRhs()) for constraint in path_constraints]))
     1698                    list(map(list, list(zip(*[(constraint.getLhs(), constraint.getRhs()) for constraint in path_constraints]))))
    16981699        else:
    16991700            path_lhs = []
     
    17231724            self._objective_integrand = objective_integrand
    17241725        else:
    1725             for (path, lhs, rhs) in itertools.izip(path_constraints, path_lhs, path_rhs):
     1726            for (path, lhs, rhs) in zip(path_constraints, path_lhs, path_rhs):
    17261727                path.setLhs(lhs)
    17271728                path.setRhs(rhs)
     
    18231824                return self._op_res.get_solver_statistics()
    18241825        res = BLTResult(op_res)
    1825         for key in op_res.keys():
     1826        for key in list(op_res.keys()):
    18261827            res[key] = op_res[key]
    18271828
     
    18401841
    18411842            # Compute solved algebraics
    1842             for k in xrange(len(res['time'])):
     1843            for k in range(len(res['time'])):
    18431844                for (i, var) in enumerate(self._known_vars + self._explicit_unsolved_vars):
    18441845                    alg_sol_f.setInput(res[var.getName()][k], i)
  • branches/dev-5819/Python/src/pyjmi/ukf.py

    r10171 r13461  
    218218            P_sqrt = S.linalg.cholesky(P, lower = True)
    219219        except N.linalg.LinAlgError:
    220             print 'The covariance matrix was not positive definite:'
    221             print 'P = '
    222             print P
     220            print('The covariance matrix was not positive definite:')
     221            print('P = ')
     222            print(P)
    223223            raise
    224224   
     
    246246       
    247247        #Sort measurements alphabetically and extract values into scaled form
    248         y = collections.OrderedDict(sorted(y.items(), key = lambda t: t[0]))
     248        y = collections.OrderedDict(sorted(list(y.items()), key = lambda t: t[0]))
    249249        y_scaled = []
    250250        for measurement in self.mes:
     
    368368                opt['CVode_options']['atol'] = 1e-8
    369369                opt['CVode_options']['rtol'] = 1e-6
    370                 print 'Simulating sigma-point '+str(i+1)+' out of '+str(sigma.shape[1])+' :'
     370                print('Simulating sigma-point '+str(i+1)+' out of '+str(sigma.shape[1])+' :')
    371371                try:
    372372                    result = model.simulate(start_time = currTime, final_time = currTime + h, options = opt, input = u)
    373373                except (CVodeError, ValueError, FMUException) as e:
    374                     print e
     374                    print(e)
    375375                    retry = True
    376                     print 'Failed sigma point simulation'
     376                    print('Failed sigma point simulation')
    377377                    if k == 1:
    378                         if currTime in self.fails.keys():
     378                        if currTime in list(self.fails.keys()):
    379379                            self.fails[currTime] = self.fails[currTime] + 1
    380380                        else:
    381381                            self.fails[currTime] = 1
    382382                    if k == 10:
    383                         print 'Simulation failed 10 times, will use result from last sigma point instead'
     383                        print('Simulation failed 10 times, will use result from last sigma point instead')
    384384                        break
    385385                k = k + 1
     
    476476       
    477477        if (key == 'P_0' or key == 'P_v' or key == 'P_n') and type(value) == dict:
    478             for var in value.keys():
     478            for var in list(value.keys()):
    479479                if type(value[var]) == int:
    480480                    value[var] = float(value[var])
     
    493493       
    494494        #Check for invalid options and arguments
    495         keys = kw.keys()
     495        keys = list(kw.keys())
    496496        for key in keys:
    497497            value = kw[key]
     
    501501                value = float(value)
    502502            elif (key == 'P_0' or key == 'P_v' or key == 'P_n') and type(value) == dict:
    503                 for var in value.keys():
     503                for var in list(value.keys()):
    504504                    if type(value[var]) == int:
    505505                        value[var] = float(value[var])
  • branches/dev-5819/Python/src/pymodelica/__init__.py

    r9809 r13461  
    4949try:
    5050    _f = os.path.join(os.environ['JMODELICA_HOME'],'startup.py')
    51     execfile(_f)
     51    exec(compile(open(_f, "rb").read(), _f, 'exec'))
    5252except IOError:
    5353    logging.warning('Startup script ''%s'' not found. Environment may be corrupt'
     
    6363
    6464#Import the compile functions allowing for users to type: from pymodelica import compiler_*
    65 from compiler import compile_fmu, compile_fmux
     65from .compiler import compile_fmu, compile_fmux
  • branches/dev-5819/Python/src/pymodelica/compiler.py

    r13223 r13461  
    2828from subprocess import Popen, PIPE
    2929import subprocess
    30 from compiler_logging import CompilerLogHandler
    31 from compiler_exceptions import JError
    32 from compiler_exceptions import IllegalCompilerArgumentError
    33 from compiler_exceptions import IllegalLogStringError
     30from .compiler_logging import CompilerLogHandler
     31from .compiler_exceptions import JError
     32from .compiler_exceptions import IllegalCompilerArgumentError
     33from .compiler_exceptions import IllegalLogStringError
    3434
    3535import pymodelica as pym
     
    139139    """
    140140    #Remove in JModelica.org version 2.3
    141     if compiler_options.has_key("extra_lib_dirs"):
    142         print "Warning: The option 'extra_lib_dirs' has been deprecated and will be removed. Please use the 'file_name' to pass additional libraries."
     141    if "extra_lib_dirs" in compiler_options:
     142        print("Warning: The option 'extra_lib_dirs' has been deprecated and will be removed. Please use the 'file_name' to pass additional libraries.")
    143143   
    144144    if (target != "me" and target != "cs" and target != "me+cs"):
     
    228228    Helper function for compile_fmu and compile_fmux.
    229229    """
    230     for key, value in compiler_options.iteritems():
     230    for key, value in compiler_options.items():
    231231        if isinstance(value, list):
    232232            compiler_options[key] = list_to_string(value)
    233233   
    234     if isinstance(file_name, basestring):
     234    if isinstance(file_name, str):
    235235        file_name = [file_name]
    236236       
     
    384384    """
    385385    # Save in opts in the form: opt1:val1,opt2:val2
    386     opts = ','.join(['%s:%s' %(k, v) for k, v in compiler_options.iteritems()])
     386    opts = ','.join(['%s:%s' %(k, v) for k, v in compiler_options.items()])
    387387    # Convert all Python True/False to Java true/false
    388388    opts = opts.replace('True', 'true')
     
    453453
    454454def _get_compiler(files, selected_compiler='auto'):
    455     from compiler_wrappers import ModelicaCompiler, OptimicaCompiler
     455    from .compiler_wrappers import ModelicaCompiler, OptimicaCompiler
    456456   
    457457    comp = _which_compiler(files, selected_compiler)
  • branches/dev-5819/Python/src/pymodelica/compiler_interface.py

    r13252 r13461  
    3737        *_jvm_args)
    3838    org = jpype.JPackage('org')
    39     print "JVM started."
     39    print("JVM started.")
    4040
    4141
  • branches/dev-5819/Python/src/pymodelica/compiler_logging.py

    r13252 r13461  
    2020import xml.sax
    2121from threading import Thread
    22 from compiler_exceptions import *
     22from .compiler_exceptions import *
    2323import sys
    2424import traceback
     
    217217        try:
    218218            xml.sax.parse(self.stream, LogErrorParser(self.result))
    219         except xml.sax.SAXParseException, e:
     219        except xml.sax.SAXParseException as e:
    220220            self.result.problems.append(CompilationException('xml.sax.SAXParseException', self.stream.genErrorMsg(e),""))
    221221
     
    282282        """
    283283        if (self.loggerThread is None):
    284             print "Invalid call order!"
     284            print("Invalid call order!")
    285285        self.loggerThread.join()
    286286        problems = self.loggerThread.result.problems
     
    301301        if not exceptions:
    302302            if not errors:
    303                 from compiler import CompilerResult
     303                from .compiler import CompilerResult
    304304                return CompilerResult(name, warnings)
    305305            else:
  • branches/dev-5819/Python/src/pymodelica/compiler_wrappers.py

    r12127 r13461  
    2222
    2323import pymodelica as pym
    24 from compiler_interface import *
    25 from compiler_logging import CompilerLogHandler, LogHandlerThread
     24from .compiler_interface import *
     25from .compiler_logging import CompilerLogHandler, LogHandlerThread
    2626from pymodelica.common.core import list_to_string
    27 from compiler_exceptions import *
     27from .compiler_exceptions import *
    2828
    2929
     
    6565        """
    6666        # set compiler options
    67         for key, value in compiler_options.iteritems():
     67        for key, value in compiler_options.items():
    6868            if isinstance(value, bool):
    6969                self.set_boolean_option(key, value)
    70             elif isinstance(value, basestring):
     70            elif isinstance(value, str):
    7171                self.set_string_option(key,value)
    7272            elif isinstance(value, int):
     
    320320       
    321321    def set_target_platforms(self, platforms):
    322         if isinstance(platforms, basestring):
     322        if isinstance(platforms, str):
    323323            platforms = [platforms]
    324324        self._compiler.targetPlatforms = platforms
     
    363363        except jpype.JavaException as ex:
    364364            self._handle_exception(ex)
    365         from compiler import CompilerResult
     365        from .compiler import CompilerResult
    366366        return CompilerResult(unit, self.get_warnings())
    367367
     
    396396            Java classes.
    397397        """       
    398         if isinstance(model_file_name, basestring):
     398        if isinstance(model_file_name, str):
    399399            model_file_name = [model_file_name]
    400400        try:
     
    523523            warnings = []
    524524            while itr.hasNext():
    525                 problem = itr.next()
     525                problem = next(itr)
    526526                if str(problem.severity()).lower() == 'warning':
    527527                    warnings.append(CompilationWarning( \
  • branches/dev-5819/Python/src/pymodelica/doc/sphinx/source/conf.py

    r11373 r13461  
    4949
    5050# General information about the project.
    51 project = u'PyModelica'
    52 copyright = u'2018, Modelon AB'
    53 author = u'Modelon AB'
     51project = 'PyModelica'
     52copyright = '2018, Modelon AB'
     53author = 'Modelon AB'
    5454
    5555# The version info for the project you're documenting, acts as replacement for
     
    5858#
    5959# The short X.Y version.
    60 version = u''
     60version = ''
    6161# The full version, including alpha/beta/rc tags.
    62 release = u''
     62release = ''
    6363
    6464# The language for content autogenerated by Sphinx. Refer to documentation
     
    225225#  author, documentclass [howto, manual, or own class]).
    226226latex_documents = [
    227     (master_doc, 'PyModelica.tex', u'PyModelica Documentation',
    228      u'Modelon AB', 'manual'),
     227    (master_doc, 'PyModelica.tex', 'PyModelica Documentation',
     228     'Modelon AB', 'manual'),
    229229]
    230230
     
    255255# (source start file, name, description, authors, manual section).
    256256man_pages = [
    257     (master_doc, 'pymodelica', u'PyModelica Documentation',
     257    (master_doc, 'pymodelica', 'PyModelica Documentation',
    258258     [author], 1)
    259259]
     
    269269#  dir menu entry, description, category)
    270270texinfo_documents = [
    271     (master_doc, 'PyModelica', u'PyModelica Documentation',
     271    (master_doc, 'PyModelica', 'PyModelica Documentation',
    272272     author, 'PyModelica', 'One line description of project.',
    273273     'Miscellaneous'),
  • branches/dev-5819/Python/src/startup.py

    r9809 r13461  
    107107   
    108108try:
    109     execfile(os.path.join(_p,'.jmodelica.org','user_startup.py'))
     109    exec(compile(open(os.path.join(_p,'.jmodelica.org','user_startup.py'), "rb").read(), os.path.join(_p,'.jmodelica.org','user_startup.py'), 'exec'))
    110110except IOError:
    111111    None
  • branches/dev-5819/Python/src/tests_jmodelica/general/base_simul.py

    r10446 r13461  
    184184        # Remove values outside overlap
    185185        #time = filter((lambda t: t >= t1 and t <= t2), time) #This is not a good approach
    186         time = filter((lambda t: t >= t1 and t <= t2), res.t)
     186        time = list(filter((lambda t: t >= t1 and t <= t2), res.t))
    187187
    188188        # Check error for each time point
     
    347347    Selects method to use from the type of each value.
    348348    """
    349     for k, v in opts.iteritems():
     349    for k, v in opts.items():
    350350        if isinstance(v, int):
    351351            nlp.opt_coll_ipopt_set_int_option(k, v)
    352352        elif isinstance(v, float):
    353353            nlp.opt_coll_ipopt_set_num_option(k, v)
    354         elif isinstance(v, basestring):
     354        elif isinstance(v, str):
    355355            nlp.opt_coll_ipopt_set_string_option(k, v)
    356356
     
    361361    Selects method to use from the type of each value.
    362362    """
    363     for k, v in opts.iteritems():
     363    for k, v in opts.items():
    364364        if isinstance(v, bool):
    365365            cmp.set_boolean_option(k, v)
     
    368368        elif isinstance(v, float):
    369369            cmp.set_real_option(k, v)
    370         elif isinstance(v, basestring):
     370        elif isinstance(v, str):
    371371            cmp.set_string_option(k, v)
    372372
  • branches/dev-5819/Python/src/tests_jmodelica/general/test_extfunctions.py

    r11759 r13461  
    393393            self.run()
    394394            assert False, 'Simulation not stopped by failed assertions'
    395         except FMUException, e:
     395        except FMUException as e:
    396396            pass
    397397   
     
    413413            model.simulate(final_time = 3, options={"CVode_options":{"minh":1e-15}})
    414414            assert False, 'Simulation not stopped by calls to ModelicaError()'
    415         except CVodeError, e:
     415        except CVodeError as e:
    416416            assert abs(e.t - 2.0) < 0.01, 'Simulation stopped at wrong time'
    417417       
  • branches/dev-5819/Python/src/tests_jmodelica/general/test_operators.py

    r11351 r13461  
    471471            self.run(cvode_options={"minh":1e-15})
    472472            assert False, 'Simulation not stopped by failed assertions'
    473         except CVodeError, e:
     473        except CVodeError as e:
    474474            self.assert_equals('Simulation stopped at wrong time', e.t, 2.0)
    475475   
     
    491491            self.run()
    492492            assert False, 'Simulation not stopped by failed assertions'
    493         except FMUException, e:
     493        except FMUException as e:
    494494            self.assert_equals('Simulation stopped at wrong time', self.model.time, 2.0)
    495495       
     
    511511            self.run(cvode_options={"minh":1e-15})
    512512            assert False, 'Simulation not stopped by failed assertions'
    513         except CVodeError, e:
     513        except CVodeError as e:
    514514            self.assert_equals('Simulation stopped at wrong time', e.t, 2.0)
    515515
  • branches/dev-5819/Python/src/tests_jmodelica/initialization/test_KINsolver_options.py

    r12953 r13461  
    318318        log = parse_jmi_log(self.log_file_name)
    319319        solves = gather_solves(log)
    320         print solves
     320        print(solves)
    321321        nose.tools.assert_equals(len(solves), 2)
    322322   
  • branches/dev-5819/Python/src/tests_jmodelica/optimization/test_back_tracking.py

    r10318 r13461  
    3131   
    3232    xx_dests, xx_sources = coll.xx_dests, coll.xx_sources
    33     for (var, dest) in xx_dests.iteritems():
     33    for (var, dest) in xx_dests.items():
    3434        inds = dest['inds']
    3535        assert N.all(xx_sources['var'][inds] == var)
     
    208208    check_roundtrip(solver)
    209209
    210     for (eqtype, key) in eqkeys.iteritems():
     210    for (eqtype, key) in eqkeys.items():
    211211        eqs = solver.get_equations(eqtype)
    212212        assert len(eqs) == 1
  • branches/dev-5819/Python/src/tests_jmodelica/optimization/test_casadi_collocation.py

    r12770 r13461  
    104104                transfer_to_casadi_interface(
    105105                        class_path, vdp_file_path,
    106                         compiler_options=dict({"inline_functions": "none"}.items() + self.compiler_opts.items()))
     106                        compiler_options=dict(list({"inline_functions": "none"}.items()) + list(self.compiler_opts.items())))
    107107       
    108108        class_path = "VDP_pack.VDP_Opt_Function_global_constant"
     
    110110                transfer_to_casadi_interface(
    111111                        class_path, vdp_file_path,
    112                         compiler_options=dict({"inline_functions": "none"}.items() + self.compiler_opts.items()))
     112                        compiler_options=dict(list({"inline_functions": "none"}.items()) + list(self.compiler_opts.items())))
    113113       
    114114        cstr_file_path = os.path.join(get_files_path(), 'Modelica', 'CSTR.mop')
     
    247247        opts['discr'] = 'LG'
    248248        opts['result_mode'] = 'collocation_points'
    249         print 'LG + collocation_points'
     249        print('LG + collocation_points')
    250250        res = op.optimize(self.algorithm, opts)
    251251        assert_time(res)
     
    254254        opts['discr'] = 'LG'
    255255        opts['result_mode'] = 'element_interpolation'
    256         print 'LG + element_interpolation'
     256        print('LG + element_interpolation')
    257257        res = op.optimize(self.algorithm, opts)
    258258        N.testing.assert_allclose(res['time'][[0, -1]], [t0 + dt, tf + dt])
     
    262262        opts['discr'] = 'LG'
    263263        opts['result_mode'] = 'mesh_points'
    264         print 'LG + mesh_points'
     264        print('LG + mesh_points')
    265265        res = op.optimize(self.algorithm, opts)
    266266        assert_time(res)
     
    269269        opts['discr'] = 'LGR'
    270270        opts['result_mode'] = 'collocation_points'
    271         print 'LGR + collocation_points'
     271        print('LGR + collocation_points')
    272272        res = op.optimize(self.algorithm, opts)
    273273        assert_time(res)
     
    276276        opts['discr'] = 'LGR'
    277277        opts['result_mode'] = 'element_interpolation'
    278         print 'LGR + element_interpolation'
     278        print('LGR + element_interpolation')
    279279        res = op.optimize(self.algorithm, opts)
    280280        assert_time(res)
     
    283283        opts['discr'] = 'LGR'
    284284        opts['result_mode'] = 'mesh_points'
    285         print 'LGR + mesh_points'
     285        print('LGR + mesh_points')
    286286        res = op.optimize(self.algorithm, opts)
    287287        assert_time(res)
     
    16081608        res = op.optimize(self.algorithm, opts)
    16091609        assert_results(res, cost_ref, u_norm_ref)
    1610         indices = range(1, 4) + range(opts['n_e'] - 3, opts['n_e'])
     1610        indices = list(range(1, 4)) + list(range(opts['n_e'] - 3, opts['n_e']))
    16111611        values = N.array([0.5, 0.5, 0.5, 2.0, 2.0, 2.0])
    16121612        N.testing.assert_allclose(20. * res.h_opt[indices], values, 5e-3)
     
    22852285        # Set arbitrary non-zero guesses
    22862286        guesses = N.linspace(0.5, 1.8, len(op.getAllVariables()))
    2287         for (var, ig) in itertools.izip(op.getAllVariables(), guesses):
     2287        for (var, ig) in zip(op.getAllVariables(), guesses):
    22882288            var.setAttribute('initialGuess', ig)
    22892289
  • branches/dev-5819/Python/src/tests_jmodelica/optimization/test_delayed_feedback.py

    r10318 r13461  
    1818"""Tests optimization with delayed feedback."""
    1919
    20 from __future__ import division
     20
    2121
    2222import os
     
    5252
    5353    stepresults = []
    54     for step in xrange(2):   
     54    for step in range(2):   
    5555        opts = opt.optimize_options()
    5656        #    opts['variable_scaling'] = False
  • branches/dev-5819/Python/src/tests_jmodelica/optimization/test_greybox.py

    r10318 r13461  
    7474    ext_data = GB.options['external_data']
    7575    # input data
    76     for inp in inputs.keys():
     76    for inp in list(inputs.keys()):
    7777        evaluated_input = ext_data.eliminated[inp].eval(time)
    7878        N.array_equal(inputs[inp], evaluated_input)
    7979    # measurement data
    80     for meas in measurements.keys():
     80    for meas in list(measurements.keys()):
    8181        evaluated_meas = ext_data.eliminated['GreyBox_measured_'+meas].eval(time)
    8282        N.array_equal(measurements[meas], evaluated_meas)
     
    9898   
    9999    # Only use first 3 measurements
    100     for var in measurements.keys():
     100    for var in list(measurements.keys()):
    101101        measurements[var] = measurements[var][0:3]
    102102       
     
    123123    # Assert external data
    124124    ext_data = GB.options['external_data']
    125     for inp in inputs.keys():
     125    for inp in list(inputs.keys()):
    126126        evaluated_input = ext_data.eliminated[inp].eval(time)
    127127        N.array_equal(inputs[inp], evaluated_input)
     
    129129    # Assert objective and objective integrand
    130130    assert strnorm(GB.op.getObjectiveIntegrand().getDescription()) == strnorm('0')
    131     print strnorm(GB.op.getObjective().getDescription())
     131    print(strnorm(GB.op.getObjective().getDescription()))
    132132    assert strnorm(GB.op.getObjective().getDescription()) == strnorm('((((((((sq((E(0.000000)-133.837))/GreyBox_r_E)+(sq((E(2.004008)-132.493))/GreyBox_r_E))+(sq((E(4.008016)-129.124))/GreyBox_r_E))+(3*log(GreyBox_r_E)))+(sq((P(0.000000)-138))/GreyBox_r_P))+(sq((P(2.004008)-141.156))/GreyBox_r_P))+(sq((P(4.008016)-132.906))/GreyBox_r_P))+(3*log(GreyBox_r_P)))')
    133133
     
    195195   
    196196    # remove every third measurement to get nonuniform distribution of measurements
    197     for var in measurements.keys():
     197    for var in list(measurements.keys()):
    198198        measurements[var] = N.delete(measurements[var], slice(None, None, 3))
    199199   
  • branches/dev-5819/Python/src/tests_jmodelica/optimization/test_mhe.py

    r10318 r13461  
    831831                         self.CSTR_dx_0, self.CSTR_c_0, self.CSTR_MHE_opts)
    832832        #Get the names for the inputs and measured variables
    833         meas_names = y.keys()
    834         input_names = u.keys()
    835         state_names = res.keys()
     833        meas_names = list(y.keys())
     834        input_names = list(u.keys())
     835        state_names = list(res.keys())
    836836        #Tolerance
    837837        small = 1e-4
     
    891891                         self.VDP_dx_0, self.VDP_c_0, self.VDP_MHE_opts)
    892892        #Get the names for the inputs and measured variables
    893         meas_names = y.keys()
    894         input_names = u.keys()
    895         state_names = res.keys()
     893        meas_names = list(y.keys())
     894        input_names = list(u.keys())
     895        state_names = list(res.keys())
    896896        #Tolerance
    897897        small = 1e-4
     
    958958                         self.alg_dx_0, self.alg_c_0, self.alg_MHE_opts)
    959959        #Get the names for the inputs and measured variables
    960         meas_names = y.keys()
    961         input_names = u.keys()
    962         state_names = res.keys()
     960        meas_names = list(y.keys())
     961        input_names = list(u.keys())
     962        state_names = list(res.keys())
    963963        #Tolerance
    964964        small = 1e-4
     
    10121012       
    10131013        #Get the names for the inputs and measured variables
    1014         meas_names = res.keys()
    1015         input_names = u.keys()
     1014        meas_names = list(res.keys())
     1015        input_names = list(u.keys())
    10161016        #Define the time vector and sample_time
    10171017        nbr_of_points = 11
     
    11031103       
    11041104        #Get the names for the inputs and measured variables
    1105         meas_names = y.keys()
    1106         input_names = u.keys()
    1107         state_names = res.keys()
     1105        meas_names = list(y.keys())
     1106        input_names = list(u.keys())
     1107        state_names = list(res.keys())
    11081108        #Tolerance
    11091109        small = 1e-4
     
    11491149        c_0 = []
    11501150        #Get the names for the inputs and measured variables
    1151         meas_names = res.keys()
    1152         input_names = u.keys()
     1151        meas_names = list(res.keys())
     1152        input_names = list(u.keys())
    11531153        #Define the time vector and sample_time
    11541154        nbr_of_points = 11
  • branches/dev-5819/Python/src/tests_jmodelica/optimization/test_mpc.py

    r10318 r13461  
    183183            prev_value = value
    184184
    185         N.testing.assert_(largest_delta_quad<largest_delta)
     185        N.testing.assertTrue(largest_delta_quad<largest_delta)
    186186       
    187187    @testattr(casadi_base = True)
     
    231231            prev_value = value
    232232           
    233         N.testing.assert_(largest_delta<5)
     233        N.testing.assertTrue(largest_delta<5)
    234234       
    235235    @testattr(casadi_base = True)
     
    270270        MPC_object.update_state({'_start_c': self.c_0_A, '_start_T': 355})
    271271        MPC_object.sample()
    272         N.testing.assert_('Solve_Succeeded', MPC_object.collocator.
     272        N.testing.assertTrue('Solve_Succeeded', MPC_object.collocator.
    273273                                        solver_object.getStat('return_status'))
    274274
     
    357357        # Assert that problem was infeasible and that the returned input is
    358358        # the next input from the last succesful optimization
    359         N.testing.assert_('Infeasible_Problem_Detected', MPC_object.collocator.solver_object.getStat('return_status'))
     359        N.testing.assertTrue('Infeasible_Problem_Detected', MPC_object.collocator.solver_object.getStat('return_status'))
    360360 
    361361        N.testing.assert_almost_equal(u_k2[1](0)[0], result1['Tc'][4],decimal=10)
     
    365365        result2 = MPC_object.get_results_this_sample()
    366366
    367         N.testing.assert_(result1==result2)
     367        N.testing.assertTrue(result1==result2)
    368368       
    369369        # Assert that problem was infeasible yet again and that the returned
     
    371371        MPC_object.update_state({'_start_c': 900, '_start_T': 400})
    372372        u_k3 = MPC_object.sample()
    373         N.testing.assert_('Infeasible_Problem_Detected', MPC_object.collocator.
     373        N.testing.assertTrue('Infeasible_Problem_Detected', MPC_object.collocator.
    374374                                        solver_object.getStat('return_status'))
    375375 
     
    644644        u_k2 = MPC_object.sample()
    645645
    646         N.testing.assert_(MPC_object.collocator.warm_start)
     646        N.testing.assertTrue(MPC_object.collocator.warm_start)
    647647        wsip =\
    648648         MPC_object.collocator.solver_object.getOption('warm_start_init_point')
     
    650650        prl = MPC_object.collocator.solver_object.getOption('print_level')
    651651
    652         N.testing.assert_(wsip == 'yes')
     652        N.testing.assertTrue(wsip == 'yes')
    653653        N.testing.assert_equal(mu_init, 1e-3)
    654654        N.testing.assert_equal(prl,  0)
     
    726726            # the next sample period with the optimal input u_k
    727727            sim_model.reset()
    728             sim_model.set(x_k.keys(), x_k.values())
     728            sim_model.set(list(x_k.keys()), list(x_k.values()))
    729729            sim_res = sim_model.simulate(start_time=k*sample_period,
    730730                                         final_time=(k+1)*sample_period,
     
    765765            # the next sample period with the optimal input u_k
    766766            sim_model_elim.reset()
    767             sim_model_elim.set(x_k.keys(), x_k.values())
     767            sim_model_elim.set(list(x_k.keys()), list(x_k.values()))
    768768            sim_res = sim_model_elim.simulate(start_time=k*sample_period,
    769769                                         final_time=(k+1)*sample_period,
  • branches/dev-5819/Python/src/tests_jmodelica/simulation/test_assimulo_interface_fmi.py

    r11010 r13461  
    186186        model.initialize()
    187187        ev = model.get_event_info()
    188         print ev.nextEventTime
     188        print(ev.nextEventTime)
    189189        assert ev.nextEventTime == 1
    190190       
     
    194194        model.initialize()
    195195        ev = model.get_event_info()
    196         print ev.nextEventTime
     196        print(ev.nextEventTime)
    197197        assert ev.nextEventTime == 2
    198198        assert ev.nextEventTime == model.get("p")
     
    203203        model.initialize()
    204204        ev = model.get_event_info()
    205         print ev.nextEventTime
     205        print(ev.nextEventTime)
    206206        assert ev.nextEventTime == 1.5
    207207       
     
    227227        model.initialize()
    228228        ev = model.get_event_info()
    229         print ev.nextEventTime
     229        print(ev.nextEventTime)
    230230        assert ev.nextEventTime == 0.5
    231231       
    232232        model.simulate(options={"initialize":False})
    233233       
    234         print "i (should be 2): ", model.get("i")
     234        print("i (should be 2): ", model.get("i"))
    235235        assert model.get("i") == 2
    236236       
     
    240240        model.initialize()
    241241        ev = model.get_event_info()
    242         print ev.nextEventTime
     242        print(ev.nextEventTime)
    243243        assert ev.nextEventTime == 0.5
    244244       
    245245        model.simulate(options={"initialize":False})
    246246       
    247         print "i (should be 2): ", model.get("i")
     247        print("i (should be 2): ", model.get("i"))
    248248        assert model.get("i") == 2
    249249       
     
    253253        model.initialize()
    254254        ev = model.get_event_info()
    255         print ev.nextEventTime
     255        print(ev.nextEventTime)
    256256        assert ev.nextEventTime == 0.5
    257257       
    258258        model.simulate(options={"initialize":False})
    259259       
    260         print "i (should be 2): ", model.get("i")
    261         print "j (should be 1): ", model.get("j")
     260        print("i (should be 2): ", model.get("i"))
     261        print("j (should be 1): ", model.get("j"))
    262262        assert model.get("i") == 2
    263263        assert model.get("j") == 1
     
    268268        model.initialize()
    269269        ev = model.get_event_info()
    270         print ev.nextEventTime
     270        print(ev.nextEventTime)
    271271        assert ev.nextEventTime == 0.5
    272272       
    273273        model.simulate(options={"initialize":False})
    274274       
    275         print "i (should be 1): ", model.get("i")
    276         print "j (should be 1): ", model.get("j")
     275        print("i (should be 1): ", model.get("i"))
     276        print("j (should be 1): ", model.get("j"))
    277277        assert model.get("i") == 1
    278278        assert model.get("j") == 1
     
    283283        model.initialize()
    284284        ev = model.get_event_info()
    285         print ev.nextEventTime
     285        print(ev.nextEventTime)
    286286        assert ev.nextEventTime == 1.5
    287287       
    288288        res = model.simulate(final_time=4, options={"initialize":False})
    289289       
    290         print "x: ", res["x"]
    291         print "dx: ", res["der(x)"]
     290        print("x: ", res["x"])
     291        print("dx: ", res["der(x)"])
    292292       
    293293        assert res.solver.statistics["ntimeevents"] == 2
     
    422422        model.enter_continuous_time_mode()
    423423        ev = model.get_event_info()
    424         print ev.nextEventTime
     424        print(ev.nextEventTime)
    425425        assert ev.nextEventTime == 1
    426426       
     
    432432        model.enter_continuous_time_mode()
    433433        ev = model.get_event_info()
    434         print ev.nextEventTime
     434        print(ev.nextEventTime)
    435435        assert ev.nextEventTime == 2
    436436        assert ev.nextEventTime == model.get("p")
     
    443443        model.enter_continuous_time_mode()
    444444        ev = model.get_event_info()
    445         print ev.nextEventTime
     445        print(ev.nextEventTime)
    446446        assert ev.nextEventTime == 1.5
    447447       
     
    473473        model.enter_continuous_time_mode()
    474474        ev = model.get_event_info()
    475         print ev.nextEventTime
     475        print(ev.nextEventTime)
    476476        assert ev.nextEventTime == 0.5
    477477       
    478478        model.simulate(options={"initialize":False})
    479479       
    480         print "i (should be 2): ", model.get("i")
     480        print("i (should be 2): ", model.get("i"))
    481481        assert model.get("i") == 2
    482482       
     
    488488        model.enter_continuous_time_mode()
    489489        ev = model.get_event_info()
    490         print ev.nextEventTime
     490        print(ev.nextEventTime)
    491491        assert ev.nextEventTime == 0.5
    492492       
    493493        model.simulate(options={"initialize":False})
    494494       
    495         print "i (should be 2): ", model.get("i")
     495        print("i (should be 2): ", model.get("i"))
    496496        assert model.get("i") == 2
    497497       
     
    503503        model.enter_continuous_time_mode()
    504504        ev = model.get_event_info()
    505         print ev.nextEventTime
     505        print(ev.nextEventTime)
    506506        assert ev.nextEventTime == 0.5
    507507       
    508508        model.simulate(options={"initialize":False})
    509509       
    510         print "i (should be 2): ", model.get("i")
    511         print "j (should be 1): ", model.get("j")
     510        print("i (should be 2): ", model.get("i"))
     511        print("j (should be 1): ", model.get("j"))
    512512        assert model.get("i") == 2
    513513        assert model.get("j") == 1
     
    524524        model.simulate(options={"initialize":False})
    525525       
    526         print "i (should be 1): ", model.get("i")
    527         print "j (should be 1): ", model.get("j")
     526        print("i (should be 1): ", model.get("i"))
     527        print("j (should be 1): ", model.get("j"))
    528528        assert model.get("i") == 1
    529529        assert model.get("j") == 1
     
    536536        model.enter_continuous_time_mode()
    537537        ev = model.get_event_info()
    538         print ev.nextEventTime
     538        print(ev.nextEventTime)
    539539        assert ev.nextEventTime == 1.5
    540540       
    541541        res = model.simulate(final_time=4, options={"initialize":False})
    542542       
    543         print "x: ", res["x"]
    544         print "dx: ", res["der(x)"]
     543        print("x: ", res["x"])
     544        print("dx: ", res["der(x)"])
    545545       
    546546        assert res.solver.statistics["ntimeevents"] == 2
     
    15191519       
    15201520        res = model.simulate(final_time=1.5,options=opts)
    1521         print res.final("J1.w")
     1521        print(res.final("J1.w"))
    15221522        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
    15231523        assert res.solver.statistics["nfcnjacs"] > 0
     
    15271527   
    15281528        res = model.simulate(final_time=1.5,options=opts)
    1529         print res.final("J1.w")
     1529        print(res.final("J1.w"))
    15301530        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
    15311531        assert res.solver.statistics["nfcnjacs"] == 0
     
    15351535   
    15361536        res = model.simulate(final_time=1.5,options=opts)
    1537         print res.final("J1.w")
     1537        print(res.final("J1.w"))
    15381538        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
    15391539        assert res.solver.statistics["nfcnjacs"] > 0
     
    15431543   
    15441544        res = model.simulate(final_time=1.5,options=opts)
    1545         print res.final("J1.w")
     1545        print(res.final("J1.w"))
    15461546        assert (N.abs(res.final("J1.w") - 3.2450903041811698)) < 1e-4
    15471547        assert res.solver.statistics["nfcnjacs"] > 0
  • branches/dev-5819/Python/src/tests_jmodelica/test_casadiinterface_transfer.py

    r10318 r13461  
    371371        for var in model.getVariables(Model.REAL_PARAMETER_DEPENDENT):
    372372            actual += str(var) + "\n"
    373         print expected, "\n", actual
     373        print(expected, "\n", actual)
    374374        assert strnorm(actual) == strnorm(expected)
    375375
  • branches/dev-5819/Python/src/tests_jmodelica/test_casadiinterface_unittests.py

    r10318 r13461  
    513513    except:
    514514        errorString = sys.exc_info()[1].message
    515     print errorString
     515    print(errorString)
    516516    assert(strnorm(errorString) == strnorm("A Variable that is set as a derivative variable must be a DerivativeVariable"));
    517517   
     
    521521    except:
    522522        errorString = sys.exc_info()[1].message
    523     print errorString
     523    print(errorString)
    524524    assert(strnorm(errorString) == strnorm("A Variable that is set as a derivative variable must be a DerivativeVariable"));
    525525   
     
    538538    except:
    539539        errorString = sys.exc_info()[1].message
    540     print errorString
     540    print(errorString)
    541541    assert(strnorm(errorString) == strnorm("A RealVariable that is a state variable must have continuous variability, and may not be a derivative variable."));
    542542   
     
    987987                     "Start time = 0\nFinal time = 0\n\n\n" +
    988988                     "-- Objective integrand term --\n0\n-- Objective term --\n0")
    989     print simpleOptProblem
     989    print(simpleOptProblem)
    990990    assert( strnorm(simpleOptProblem) == strnorm(expectedPrint) )
    991991
     
    13681368                    " -- Initial equations -- \nnode3 = node4\n -- DAE equations -- \n" +
    13691369                    "node1 = node2\n\n")
    1370     print model, expectedPrint
     1370    print(model, expectedPrint)
    13711371    assert( strnorm(model) == strnorm(expectedPrint.rstrip()) )
  • branches/dev-5819/Python/src/tests_jmodelica/test_compiler.py

    r12127 r13461  
    241241        nose.tools.assert_equal(Test_Compiler.mc.get_string_option(option), setvalue)
    242242        # option should be of type str
    243         assert isinstance(Test_Compiler.mc.get_string_option(option),basestring)
     243        assert isinstance(Test_Compiler.mc.get_string_option(option),str)
    244244        # reset to original value
    245245        Test_Compiler.mc.set_string_option(option, default_value)
  • branches/dev-5819/Python/src/tests_jmodelica/test_delay.py

    r10318 r13461  
    277277    x_expected[inds]   = x_expected[inds-1]
    278278    x_expected[inds+1] = x_expected[inds+2]
    279     print x_expected+0
    280     print N.asarray(x, dtype=int)
    281     print t
     279    print(x_expected+0)
     280    print(N.asarray(x, dtype=int))
     281    print(t)
    282282    assert_close(x, x_expected, 1e-12)
    283283    assert_close(t[inds], N.array([0.43439307, 0.92808171, 1.0, 1.47239509,