def test_saveload_interval():
    """Test pickling for saving and loading 'Interval'"""

    m = Interval('test1', float, (-Inf, 1))
    s = Interval('a_singleton', float, 0.4)
    saveObjects([m, s], 'temp_objects.pkl', True)
    objs_ivals = loadObjects('temp_objects.pkl')
    assert objs_ivals[0].get(1) == 1

    # Try loading partial list from a larger file
    objs_part = loadObjects('temp_objects.pkl', ['a_singleton'])
    assert objs_part[0] == s
    os.remove('temp_objects.pkl')
def test_saveload_point_and_pointset():
    """Test pickling for saving and loading 'Point' and 'Pointset'"""

    x = Point(
        coorddict={
            'x0': [1.123456789],
            'x1': [-0.4],
            'x2': [4000]
        },
        coordtype=float64
    )

    v = Pointset(
        coorddict={
            'x0': 0.2,
            'x1': -1.2
        },
        indepvardict={'t': 0.01},
        coordtype=float,
        indepvartype=float
    )

    saveObjects([x, v], 'temp_objects.pkl', True)
    objs_pts = loadObjects('temp_objects.pkl')
    assert objs_pts[0] == x
    assert objs_pts[1] == v
    os.remove('temp_objects.pkl')
def test_saveload_implicitfngen():
    """Test pickling for saving and loading 'ImplicitFnGen'"""

    argsi = {
        'varspecs': {
            "y": "t*t+y*y-r*r",
            "x": "t"
        },
        'algparams': {'solvemethod': 'newton', 'atol': 1e-4},
        'xdomain': {'y': [-2, 2]},
        'ics': {'y': 0.75},
        'tdomain': [-2, 0],
        'pars': {'r': 2},
        'vars': ['y'],
        'checklevel': 2,
        'name': 'imptest',
    }

    testimp = ImplicitFnGen(argsi)
    traj1 = testimp.compute('traj1')
    saveObjects([testimp, traj1], 'temp_objects.pkl', True)
    objs_imp = loadObjects('temp_objects.pkl')
    assert objs_imp[0].xdomain['y'] == [-2, 2]
    assert traj1(-0.4) == objs_imp[1](-0.4)
    os.remove('temp_objects.pkl')
Example #4
0
def test_2D_example():
    """
    2D example: a quarter-sphere with linear constraint y = 3z,
    using MINPACK's fsolve
    """
    radius = 2.
    fvarspecs2d = {
        "y": "t*t+y*y+z*z-r*r",
        "z": "y-3.*z",
        "x": "t"
    }
    args2d = {
        'varspecs': fvarspecs2d,
        'algparams': {'solvemethod': 'fsolve', 'atol': 1e-3},
        'xdomain': {
            'y': [-2, 2],
            'z': [-2, 2]
        },
        'ics': {'y': 0.75, 'z': 0.9},
        'tdomain': [-2, 2],
        'pars': {'r': radius},
        'vars': ['y', 'z'],
        'checklevel': 1,
        'name': 'imptest2d'
    }
    testimp2d = ImplicitFnGen(args2d)

    traj2 = testimp2d.compute('traj2')
    p = traj2(1.5)
    assert allclose(norm(p), radius)
    assert allclose(p('y') - 3 * p('z'), 0)
    assert traj2.dimension == 3
    assert isparameterized(traj2)

    # Test bounds checking
    with pytest.raises(ValueError):
        traj2(3.)

    # Test saving and loading
    fname = 'temp_implicit2D.pkl'
    saveObjects([testimp2d, traj2], fname, force=True)
    impgen, imptraj = loadObjects(fname)
    assert impgen.xdomain['y'] == [-2, 2]
    assert allclose(imptraj(-0.4)['y'], 1.85903)

    impgen.set(pars={'r': 10.}, xdomain={'y': [-10, 10]})
    imptraj2 = impgen.compute('test2')

    with pytest.raises(PyDSTool_BoundsError):
        imptraj2(-0.4)

    impgen.set(xdomain={'z': [-5, 5]})
    imptraj2 = impgen.compute('test2')
    assert allclose(imptraj2(-0.4)['y'], 9.47924)

    os.remove(fname)
def test_saveload_interpolated_table_generator(interptable):
    """Test pickling for saving and loading 'InterpolateTable' Generator"""
    itabletraj = interptable.compute('itable')
    saveObjects(itabletraj, 'temp_objects.pkl', True)
    obj_itab = loadObjects('temp_objects.pkl')
    t = 0.1
    while t < 2.1:
        assert obj_itab[0](t) == itabletraj(t)
        t += 0.1
    os.remove('temp_objects.pkl')
def test_saveload_array():
    """Test pickling for saving and loading array"""
    a = array([1, Inf])
    b = [Inf, 0]

    saveObjects([a, b], 'temp_objects.pkl', True)
    loadedObjs = loadObjects('temp_objects.pkl')
    assert a[0] == loadedObjs[0][0]
    assert a[1] == loadedObjs[0][1]
    assert b[0] == loadedObjs[1][0]
    os.remove('temp_objects.pkl')
Example #7
0
def test_saveload_array(fname):
    """Test pickling for saving and loading array"""
    a = array([1, Inf])
    b = [Inf, 0]

    saveObjects([a, b], fname, True)
    loadedObjs = loadObjects(fname)
    assert a[0] == loadedObjs[0][0]
    assert a[1] == loadedObjs[0][1]
    assert b[0] == loadedObjs[1][0]
    os.remove(fname)
def test_saveload_variable():
    """Test pickling for saving and loading 'Variable'"""

    var1 = Variable(
        Pointset(
            coordarray=array(range(10), float) * 0.1,
            indepvararray=array(range(10), float) * 0.5
        ),
        name='v1'
    )
    saveObjects(var1, 'temp_objects.pkl', True)
    obj_var = loadObjects('temp_objects.pkl')[0]
    assert obj_var(1.5) == var1(1.5)
    os.remove('temp_objects.pkl')
def test_saveload_vode_odesystem(interptable):
    """Test pickling for saving and loading 'Vode_ODEsystem' Generator"""

    # Vode object with event and external input trajectory (defined earlier)
    fvarspecs = {
        "w": "k*w + a*itable + sin(t) + myauxfn1(t)*myauxfn2(w)",
        'aux_wdouble': 'w*2 + globalindepvar(t)',
        'aux_other': 'myauxfn1(2*t) + initcond(w)'
    }
    fnspecs = {
        'myauxfn1': (['t'], '2.5*cos(3*t)'),
        'myauxfn2': (['w'], 'w/2')
    }
    ev_args = {
        'name': 'threshold',
        'eventtol': 1e-4,
        'eventdelay': 1e-5,
        'starttime': 0,
        'term': True,
    }
    thresh_ev = Events.makePythonStateZeroCrossEvent('w', 20, 1, ev_args)
    DSargs = {
        'tdomain': [0.1, 2.1],
        'tdata': [0.11, 2.1],
        'ics': {'w': 3.0},
        'pars': {'k': 2, 'a': -0.5},
        'inputs': {'itable': interptable.variables['x1']},
        'auxvars': ['aux_wdouble', 'aux_other'],
        'algparams': {'init_step': 0.01, 'strict': False},
        'events': thresh_ev,
        'checklevel': 2,
        'name': 'ODEtest',
        'fnspecs': fnspecs,
        'varspecs': fvarspecs
    }
    testODE = Vode_ODEsystem(DSargs)
    odetraj = testODE.compute('testode')
    saveObjects([odetraj, testODE], 'temp_objects.pkl', True)
    objs_ode = loadObjects('temp_objects.pkl')
    objs_ode[1].diagnostics.clearWarnings()
    assert len(objs_ode[1].diagnostics.warnings) == 0
    odetraj2 = objs_ode[1].compute('testode2')
    assert odetraj2(0.6) == odetraj(0.6)
    assert len(objs_ode[1].diagnostics.warnings) == 1
    os.remove('temp_objects.pkl')
Example #10
0
def test_saveload_explicitfngen():
    """Test pickling for saving and loading 'ExplicitFnGen'"""

    args = {
        'tdomain': [-50, 50],
        'pars': {'speed': 1},
        'xdomain': {'s': [-1., 1.]},
        'name': 'sine',
        'globalt0': 0.4,
        'pdomain': {'speed': [0, 200]},
        'varspecs': {'s': "sin(globalindepvar(t)*speed)"}
    }
    sin_gen = ExplicitFnGen(args)
    sintraj1 = sin_gen.compute('sine1')
    sin_gen.set(pars={'speed': 2})
    sintraj2 = sin_gen.compute('sine2')
    saveObjects([sin_gen, sintraj1, sintraj2], 'temp_objects.pkl', True)
    objs_sin = loadObjects('temp_objects.pkl')
    assert sintraj1(0.55) == objs_sin[1](0.55)
    assert sintraj2(0.55) == objs_sin[2](0.55)
    os.remove('temp_objects.pkl')
Example #11
0
def test_saveload_trajectory():
    """Test pickling for saving and loading 'Trajectory'"""

    var1 = Variable(
        Pointset(
            coordarray=array(range(10), float) * 0.1,
            indepvararray=array(range(10), float) * 0.5
        ),
        name='v1'
    )
    var2 = Variable(
        Pointset(
            coordarray=array(range(10), float) * 0.25 + 1.0,
            indepvararray=array(range(10), float) * 0.5
        ),
        name='v2'
    )
    traj = Trajectory('traj1', [var1, var2])
    saveObjects(traj, 'temp_objects.pkl', True)
    traj_loaded = loadObjects('temp_objects.pkl')[0]
    assert traj_loaded(2.0) == traj(2.0)
    os.remove('temp_objects.pkl')
Example #12
0
def prep_boxplots(data, xlabel_str, figname='', fignum=1, do_legend=1,
                  means=1, xlegoff=0, ylegstep=1, ylegoff=0, spacing=None):
    spacing_actual = {
        'width': 0.1,
        'wgapfac': 0.75,
        'markersize': 12,
        'off_fac': 0.7,
        'x_step': 0.9,   # 9 * width
        'x_off': 0,
        'box_to_marker': 1.1,
        'notch_size': 0.2}
    if spacing is not None:
        spacing_actual.update(spacing)
    width = spacing_actual['width']
    wgapfac = spacing_actual['wgapfac']
    markersize = spacing_actual['markersize']
    off_fac = spacing_actual['off_fac']
    x_step = spacing_actual['x_step']
    x_off = spacing_actual['x_off']
    box_to_marker = spacing_actual['box_to_marker']
    notch_size = spacing_actual['notch_size']

    n = len(data)
    x_min = -width*3.8 #3.75
    x_max = (n-1)*x_step+width*4.5 #3.75
    if n > 1:
        halfticks = arange(1,n)*x_step-x_step/2
    figure(fignum)
    # work out ordering of data from 'pos' key
    order = {}
    # `pos` position runs from 1 to n, `ns` runs from 0 to n-1
    ns = []
    for k, v in data.iteritems():
        order[v['pos']] = k
        ns.append(v['pos']-1)
    ns.sort()
    assert ns == range(n)
    maxD = 0
    max_dimval_markers = 0
    labels = []
    for pos in range(n):
        name = order[pos+1]
        pde_name = 'PD_E-'+name
        if 'known_dim' in data[name]:
            if n == 1:
                kdx1 = x_min
                kdx2 = x_max
            else:
                if pos == 0:
                    kdx1 = x_min
                    kdx2 = halfticks[0]
                elif pos == n-1:
                    kdx1 = halfticks[n-2]
                    kdx2 = x_max
                else:
                    kdx1 = halfticks[pos-1]
                    kdx2 = halfticks[pos]
            plot([[kdx1], [kdx2]],
                 [data[name]['known_dim'],data[name]['known_dim']],
                 'k', linewidth=1, zorder=0)
        slope_data = loadObjects(pde_name)[2]
        ds_mins = array(slope_data[:,0])#,shape=(len(slope_data),1))
        ds_mins.shape=(len(slope_data),1)
        ds_maxs = array(slope_data[:,1])#,shape=(len(slope_data),1))
        ds_maxs.shape=(len(slope_data),1)
        max_ds = max([max(ds_mins[:,0]),max(ds_maxs[:,0])])
        if max_ds > maxD:
            maxD = max_ds
        # limits args are ineffective here
        boxplot(ds_mins,positions=[pos*x_step-width*wgapfac+x_off],whis=100,
                means=means,monochrome=True,notch=2,notchsize=notch_size,
                limits=(),widths=width,fill=1)
        boxplot(ds_maxs,positions=[pos*x_step+width*wgapfac+x_off],whis=100,
                means=means,monochrome=True,notch=2,notchsize=notch_size,
                limits=(),widths=width,fill=1)
        if pos == 0:
            fa = figure(fignum).axes[0]
            fa.hold(True)
        if means:
            ds_all_mean = (mean(ds_mins[:,0])+mean(ds_maxs[:,0]))/2
            plot([pos*x_step+x_off], [ds_all_mean], 'k^',
                 markersize=markersize-2)
        pca_x = pos*x_step-width*(wgapfac+box_to_marker)+x_off
        isomap_x = pos*x_step+width*(wgapfac+box_to_marker)+x_off
        pca_ds = {}
        isomap_ds = {}
        try:
            pca_data = data[name]['pca']
        except KeyError:
            pca_data = []
        pca_ds, max_dimval_pca, pca_used = plot_markers(pca_data,
                                          pca_x, 'PCA',
                                          symbol_map['pca'], -1,
                                          width, off_fac, markersize)
        if max_dimval_pca > maxD:
            maxD = max_dimval_pca
        if max_dimval_pca > max_dimval_markers:
            max_dimval_markers = max_dimval_pca
        try:
            isomap_data = data[name]['isomap']
        except KeyError:
            isomap_data = []
        isomap_ds, max_dimval_iso, isomap_used = plot_markers(isomap_data,
                                             isomap_x, 'Isomap',
                                             symbol_map['isomap'], 1,
                                             width, off_fac, markersize)
        if max_dimval_iso > maxD:
            maxD = max_dimval_iso
        if max_dimval_iso > max_dimval_markers:
            max_dimval_markers = max_dimval_iso
        labels.append(data[name]['label'])
    ## legend
    if do_legend:
        font = FontProperties()
        font.set_family('sans-serif')
        font.set_size(11)
        x_legend = x_min + 3*width/4 + xlegoff
        y_legend = maxD+ylegoff
        # pca legend
        for k, s in pca_used:
            plot_markers([(k,s,y_legend)], x_legend, 'Legend', symbol_map['pca'],
                     1, width, off_fac, markersize)
            if k == 'var':
                legstr = "%s=%d%%"%(k,s)
            else:
                legstr = "%s=%d"%(k,s)
            text(x_legend+3*width/4, y_legend-width*2., legstr,
                 fontproperties=font)
            y_legend -= ylegstep
        # isomap legend
        isomap_leg_data = []
        for k, s in isomap_used:
            if y_legend-width*2. <= max_dimval_markers + 2:
                y_legend = maxD+ylegoff
                x_legend += x_step #-width*.75
            plot_markers([(k,s,y_legend)], x_legend, 'Legend', symbol_map['isomap'],
                      1, width, off_fac, markersize)
##        if k == 'eps':
##            kstr = '\\epsilon'
##        else:
##            kstr = k
            text(x_legend+3*width/4, y_legend-width*2., "%s=%d"%(k,s),
                 fontproperties=font)
            y_legend -= ylegstep
    ## tidy up axes, etc.
    fa.set_xticks(arange(n)*x_step)
    if n>1:
        for h in range(n-1):
            plot([halfticks[h], halfticks[h]], [0,maxD+1+ylegoff], 'k:')
    fa.set_xticklabels(labels)
    fa.set_position([0.07, 0.11, 0.9, 0.85])
    fa.set_xlim(x_min,x_max)
    fa.set_ylim(0,maxD+1+ylegoff)
    if xlabel_str != '':
        xlabel(r'$\rm{'+xlabel_str+r'}$',args(fontsize=20,fontname='Times'))
    ylabel(r'$\rm{Dimension}$',args(fontsize=20,fontname='Times'))
    draw()
    if figname != '':
        save_fig(fignum, figname)