예제 #1
0
파일: test_Kernel.py 프로젝트: xhub/siconos
def test_getMatrix():
    assert (K.getMatrix([[1,2,3]]) == np.array([[1,2,3]])).all()

    m = K.SimpleMatrix(1,3)

    m.setValue(0,0,1)

    m.setValue(0,1,2)

    m.setValue(0,2,3)

    assert (K.getMatrix(m) == np.array([[1,2,3]])).all()

    assert (K.getMatrix(m) != np.array([[1,0,3]])).any()
예제 #2
0
def test_getMatrix():
    assert (K.getMatrix([[1,2,3]]) == np.array([[1,2,3]])).all()

    m = K.SimpleMatrix(1,3)

    m.setValue(0,0,1)

    m.setValue(0,1,2)

    m.setValue(0,2,3)

    assert (K.getMatrix(m) == np.array([[1,2,3]])).all()

    assert (K.getMatrix(m) != np.array([[1,0,3]])).any()

    m1 = K.SimpleMatrix(((1,2,3), (4,5,6)))
    m2 = K.SimpleMatrix(np.array([[1,2,3],[4,5,6]]))
    assert (K.getMatrix(m1) == K.getMatrix(K.SimpleMatrix(m2))).all()
예제 #3
0
def test_getMatrix():
    assert (sk.getMatrix([[1, 2, 3]]) == np.array([[1, 2, 3]])).all()

    m = sk.SimpleMatrix(1, 3)

    m.setValue(0, 0, 1)

    m.setValue(0, 1, 2)

    m.setValue(0, 2, 3)

    assert (sk.getMatrix(m) == np.array([[1, 2, 3]])).all()

    assert (sk.getMatrix(m) != np.array([[1, 0, 3]])).any()

    m1 = sk.SimpleMatrix(((1, 2, 3), (4, 5, 6)))
    m2 = sk.SimpleMatrix(np.array([[1, 2, 3], [4, 5, 6]]))
    assert (sk.getMatrix(m1) == sk.getMatrix(sk.SimpleMatrix(m2))).all()
예제 #4
0
def compute_dt_matrices(A, B, h, TV=False):
    # variable declaration
    t0 = 0.0  # start time
    T = 1  # end time
    n, m = B.shape

    # Matrix declaration
    x0 = np.random.random(n)
    Csurface = np.random.random((m, n))

    # Declaration of the Dynamical System
    if TV:
        process_ds = SK.FirstOrderLinearDS(x0, A)
    else:
        process_ds = SK.FirstOrderLinearTIDS(x0, A)
    # Model
    process = SK.Model(t0, T)
    process.nonSmoothDynamicalSystem().insertDynamicalSystem(process_ds)
    # time discretisation
    process_time_discretisation = SK.TimeDiscretisation(t0, h)
    # Creation of the Simulation
    process_simu = SK.TimeStepping(process_time_discretisation, 0)
    process_simu.setName("plant simulation")
    # Declaration of the integrator
    process_integrator = SK.ZeroOrderHoldOSI()
    process_integrator.insertDynamicalSystem(process_ds)
    process_simu.insertIntegrator(process_integrator)

    rel = SK.FirstOrderLinearTIR(Csurface, B)
    nslaw = SK.RelayNSL(m)
    inter = SK.Interaction(m, nslaw, rel)

    #process.nonSmoothDynamicalSystem().insertInteraction(inter, True)
    process.nonSmoothDynamicalSystem().link(inter, process_ds)
    process.nonSmoothDynamicalSystem().setControlProperty(inter, True)
    # Initialization
    process.initialize(process_simu)

    # Main loop
    process_simu.computeOneStep()
    Ad = SK.getMatrix(process_integrator.Ad(process_ds)).copy()
    Bd = SK.getMatrix(process_integrator.Bd(process_ds)).copy()

    return (Ad, Bd)
예제 #5
0
def test_xml1():
    ''' the BouncingBall '''

    bouncingBall = buildModelXML(os.path.join(working_dir, 'data/BBallTS.xml'))
    # --- Get the simulation ---
    s = bouncingBall.simulation()

    dsN = SK.dynamicalSystems(
        bouncingBall.nonSmoothDynamicalSystem().topology().dSG(0))[0].number()
    ball = bouncingBall.nonSmoothDynamicalSystem().dynamicalSystem(dsN)

    N = 2000  # Number of time steps
    # saved in a matrix dataPlot

    outputSize = 4
    dataPlot = np.zeros((N + 1, outputSize))

    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)

    dataPlot[0, 0] = bouncingBall.t0()
    dataPlot[0, 1] = q[0]
    dataPlot[0, 2] = v[0]
    dataPlot[0, 3] = p[0]

    print("====> Start computation ...")
    # --- Time loop  ---
    k = 1
    while s.hasNextEvent():
        s.computeOneStep()
        # --- Get values to be plotted ---
        dataPlot[k, 0] = s.nextTime()
        dataPlot[k, 1] = q[0]
        dataPlot[k, 2] = v[0]
        dataPlot[k, 3] = p[0]
        s.nextStep()
        k += 1

    print("End of computation - Number of iterations done: {:}".format(k))
    print("====> Output file writing ...")
    dataPlot.resize(k, outputSize)
    np.savetxt("BBallTS.dat", dataPlot)

    # Comparison with a reference file
    dataPlotRef = SK.getMatrix(
        SK.SimpleMatrix(os.path.join(working_dir, 'data/BBallTSXML.ref')))
    if np.linalg.norm(dataPlot - dataPlotRef, ord=np.inf) > 1e-12:
        print(dataPlot - dataPlotRef)
        print("ERROR: The result is rather different from the reference file.")
예제 #6
0
def test_xml1():
    ''' the BouncingBall '''

    bouncingBall = buildModelXML(os.path.join(working_dir, 'data/BBallTS.xml'))
    # --- Get the simulation ---
    s = bouncingBall.simulation()

    dsN = SK.dynamicalSystems(bouncingBall.nonSmoothDynamicalSystem().topology().dSG(0))[0].number()
    ball = bouncingBall.nonSmoothDynamicalSystem().dynamicalSystem(dsN)

    N = 2000  # Number of time steps
    # saved in a matrix dataPlot

    outputSize = 4
    dataPlot = np.zeros((N + 1, outputSize))

    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)

    dataPlot[0, 0] = bouncingBall.t0()
    dataPlot[0, 1] = q[0]
    dataPlot[0, 2] = v[0]
    dataPlot[0, 3] = p[0]

    print("====> Start computation ...")
    # --- Time loop  ---
    k = 1
    while s.hasNextEvent():
        s.computeOneStep()
        # --- Get values to be plotted ---
        dataPlot[k, 0] = s.nextTime()
        dataPlot[k, 1] = q[0]
        dataPlot[k, 2] = v[0]
        dataPlot[k, 3] = p[0]
        s.nextStep()
        k += 1

    print("End of computation - Number of iterations done: {:}".format(k))
    print("====> Output file writing ...")
    dataPlot.resize(k, outputSize)
    np.savetxt("BBallTS.dat", dataPlot)

    # Comparison with a reference file
    dataPlotRef = SK.getMatrix(SK.SimpleMatrix(os.path.join(working_dir, 'data/BBallTSXML.ref')))
    if np.linalg.norm(dataPlot - dataPlotRef, ord=np.inf) > 1e-12:
        print(dataPlot - dataPlotRef)
        print("ERROR: The result is rather different from the reference file.")
    # diode R1 current
    dataPlot[k, 3] = y[0]
    # diode R1 voltage
    dataPlot[k, 4] = - lambda_[0]
    # diode F2 voltage
    dataPlot[k, 5] = - lambda_[1]
    # diode F1 current
    dataPlot[k, 6] = lambda_[2]
    k += 1
    aTS.nextStep()

# comparison with reference file
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("DiodeBridge.ref"))

error = norm(dataPlot[:,0:6] - ref[:,0:6])
print("error = " , error)

#assert (error < 1e-09)
withRef = True
if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    if (withRef):
        plot(ref[0:k - 1, 0], ref[0:k - 1, 1])
예제 #8
0
def test_bouncing_ball1():
    """Run a complete simulation (Bouncing ball example)
    LagrangianLinearTIDS,  no plugins.
    """

    t0 = 0.      # start time
    tend = 10.   # end time
    h = 0.005    # time step
    r = 0.1      # ball radius
    g = 9.81     # gravity
    m = 1        # ball mass
    e = 0.9      # restitution coeficient
    theta = 0.5  # theta scheme

    #
    # dynamical system
    #
    x = np.zeros(3, dtype=np.float64)
    x[0] = 1.
    v = np.zeros_like(x)
    # mass matrix
    mass = np.eye(3, dtype=np.float64)
    mass[2, 2] = 3. / 5 * r * r

    # the dynamical system
    ball = sk.LagrangianLinearTIDS(x, v, mass)

    # set external forces
    weight = np.zeros_like(x)
    weight[0] = -m * g
    ball.setFExtPtr(weight)

    #
    # Interactions
    #

    # ball-floor
    H = np.zeros((1, 3), dtype=np.float64)
    H[0, 0] = 1.

    nslaw = sk.NewtonImpactNSL(e)
    relation = sk.LagrangianLinearTIR(H)
    inter = sk.Interaction(nslaw, relation)

    #
    # NSDS
    #
    bouncing_ball = sk.NonSmoothDynamicalSystem(t0, tend)

    # add the dynamical system to the non smooth dynamical system
    bouncing_ball.insertDynamicalSystem(ball)

    # link the interaction and the dynamical system
    bouncing_ball.link(inter, ball)

    #
    # Simulation
    #

    # (1) OneStepIntegrators
    OSI = sk.MoreauJeanOSI(theta)

    # (2) Time discretisation --
    t = sk.TimeDiscretisation(t0, h)

    # (3) one step non smooth problem
    osnspb = sk.LCP()

    # (4) Simulation setup with (1) (2) (3)
    s = sk.TimeStepping(bouncing_ball,t, OSI, osnspb)

    # end of model definition

    #
    # computation
    #
    
    #
    # save and load data from xml and .dat
    #
    try:
        from siconos.io import save
        save(bouncing_ball, "bouncingBall.xml")
        save(bouncing_ball, "bouncingBall.bin")

    except:
        print("Warning : could not import save from siconos.io")

    # the number of time steps
    nb_time_steps = int((tend - t0) / h + 1)

    # Get the values to be plotted
    # ->saved in a matrix dataPlot

    data = np.empty((nb_time_steps, 5))

    #
    # numpy pointers on dense Siconos vectors
    #
    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)
    lambda_ = inter.lambda_(1)

    #
    # initial data
    #
    data[0, 0] = t0
    data[0, 1] = q[0]
    data[0, 2] = v[0]
    data[0, 3] = p[0]
    data[0, 4] = lambda_[0]

    k = 1

    # time loop
    while(s.hasNextEvent()):
        s.computeOneStep()

        data[k, 0] = s.nextTime()
        data[k, 1] = q[0]
        data[k, 2] = v[0]
        data[k, 3] = p[0]
        data[k, 4] = lambda_[0]

        k += 1
        #print(s.nextTime())
        s.nextStep()

    #
    # comparison with the reference file
    #

    ref = sk.getMatrix(sk.SimpleMatrix(
        os.path.join(working_dir, "data/result.ref")))
    assert (np.linalg.norm(data - ref) < 1e-12)
예제 #9
0
파일: CircuitRLCD.py 프로젝트: xhub/siconos
    #  inductor voltage
    dataPlot[k, 1] = x[0]
    # inductor current
    dataPlot[k, 2] = x[1]
    # diode  voltage
    dataPlot[k, 3] = - y[0]
    # diode  current
    dataPlot[k, 4] = lambda_[0]
    k += 1
    aTS.nextStep()

# comparison with reference file
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("CircuitRLCD.ref"))

assert (norm(dataPlot - ref) < 1e-10)

if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    grid()
    subplot(412)
    title('inductor current')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 2])
    grid()
예제 #10
0
    #  inductor voltage
    dataPlot[k, 1] = x[0]
    # inductor current
    dataPlot[k, 2] = x[1]
    # diode  voltage
    dataPlot[k, 3] = -y[0]
    # diode  current
    dataPlot[k, 4] = lambda_[0]
    k += 1
    aTS.nextStep()

# comparison with reference file
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("CircuitRLCD.ref"))

assert (norm(dataPlot - ref) < 1e-10)

if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    grid()
    subplot(412)
    title('inductor current')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 2])
    grid()
예제 #11
0
def test_diodebridge1():
    from siconos.kernel import FirstOrderLinearDS, FirstOrderLinearTIR, \
                               ComplementarityConditionNSL, Interaction,\
                               Model, EulerMoreauOSI, TimeDiscretisation, LCP,  \
                               TimeStepping
    from numpy import empty
    from siconos.kernel import SimpleMatrix, getMatrix
    from numpy.linalg import norm

    t0 = 0.0
    T = 5.0e-3       # Total simulation time
    h_step = 1.0e-6  # Time step
    Lvalue = 1e-2  # inductance
    Cvalue = 1e-6   # capacitance
    Rvalue = 1e3    # resistance
    Vinit = 10.0    # initial voltage
    Modeltitle = "DiodeBridge"

    #
    # dynamical system
    #

    init_state = [Vinit, 0]

    A = [[0,          -1.0/Cvalue],
         [1.0/Lvalue, 0          ]]

    LSDiodeBridge=FirstOrderLinearDS(init_state, A)

    #
    # Interactions
    #

    C = [[0.,   0.],
         [0,    0.],
         [-1.,  0.],
         [1.,   0.]]

    D = [[1./Rvalue, 1./Rvalue, -1.,  0.],
         [1./Rvalue, 1./Rvalue,  0., -1.],
         [1.,        0.,         0.,  0.],
         [0.,        1.,         0.,  0.]]

    B = [[0.,        0., -1./Cvalue, 1./Cvalue],
         [0.,        0.,  0.,        0.       ]]

    LTIRDiodeBridge=FirstOrderLinearTIR(C, B)
    LTIRDiodeBridge.setDPtr(D)

    LTIRDiodeBridge.display()
    nslaw=ComplementarityConditionNSL(4)
    InterDiodeBridge=Interaction(4, nslaw, LTIRDiodeBridge, 1)


    #
    # Model
    #
    DiodeBridge=Model(t0, T, Modeltitle)

    #   add the dynamical system in the non smooth dynamical system
    DiodeBridge.nonSmoothDynamicalSystem().insertDynamicalSystem(LSDiodeBridge)

    #   link the interaction and the dynamical system
    DiodeBridge.nonSmoothDynamicalSystem().link(InterDiodeBridge, LSDiodeBridge)

    #
    # Simulation
    #

    # (1) OneStepIntegrators
    theta = 0.5
    aOSI = EulerMoreauOSI(LSDiodeBridge, theta)

    # (2) Time discretisation
    aTiDisc = TimeDiscretisation(t0, h_step)

    # (3) Non smooth problem
    aLCP = LCP()

    # (4) Simulation setup with (1) (2) (3)
    aTS = TimeStepping(aTiDisc, aOSI, aLCP)

    # end of model definition

    #
    # computation
    #

    # simulation initialization
    DiodeBridge.initialize(aTS)

    k = 0
    h = aTS.timeStep()
    print("Timestep : ", h)
    # Number of time steps
    N = (T-t0)/h
    print("Number of steps : ", N)

    # Get the values to be plotted
    # ->saved in a matrix dataPlot

    dataPlot = empty([N, 8])

    x = LSDiodeBridge.x()
    print("Initial state : ", x)
    y = InterDiodeBridge.y(0)
    print("First y : ", y)
    lambda_ = InterDiodeBridge.lambda_(0)

    # For the initial time step:
    # time
    dataPlot[k, 0] = t0

    #  inductor voltage
    dataPlot[k, 1] = x[0]

    # inductor current
    dataPlot[k, 2] = x[1]

    # diode R1 current
    dataPlot[k, 3] = y[0]

    # diode R1 voltage
    dataPlot[k, 4] = - lambda_[0]

    # diode F2 voltage
    dataPlot[k, 5] = - lambda_[1]

    # diode F1 current
    dataPlot[k, 6] = lambda_[2]

    # resistor current
    dataPlot[k, 7] = y[0] + lambda_[2]

    k += 1
    while (k < N):
        aTS.computeOneStep()
        #aLCP.display()
        dataPlot[k, 0] = aTS.nextTime()
        #  inductor voltage
        dataPlot[k, 1] = x[0]
        # inductor current
        dataPlot[k, 2] = x[1]
        # diode R1 current
        dataPlot[k, 3] = y[0]
        # diode R1 voltage
        dataPlot[k, 4] = - lambda_[0]
        # diode F2 voltage
        dataPlot[k, 5] = - lambda_[1]
        # diode F1 current
        dataPlot[k, 6] = lambda_[2]
        # resistor current
        dataPlot[k, 7] = y[0] + lambda_[2]
        k += 1
        aTS.nextStep()

    #
    # comparison with the reference file
    #
    ref = getMatrix(SimpleMatrix(os.path.join(working_dir,"data/diode_bridge.ref")))

    print(norm(dataPlot - ref))
    assert (norm(dataPlot - ref) < 1e-12)
    return ref, dataPlot
예제 #12
0
    # diode R1 current
    dataPlot[k, 3] = y[0]
    # diode R1 voltage
    dataPlot[k, 4] = -lambda_[0]
    # diode F2 voltage
    dataPlot[k, 5] = -lambda_[1]
    # diode F1 current
    dataPlot[k, 6] = lambda_[2]
    k += 1
    aTS.nextStep()

# comparison with reference file
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("DiodeBridge.ref"))

error = norm(dataPlot[:, 0:6] - ref[:, 0:6])
print("error = ", error)

#assert (error < 1e-09)
withRef = True
if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    if (withRef):
        plot(ref[0:k - 1, 0], ref[0:k - 1, 1])
예제 #13
0
def test_diode_bridge():
    """Build diode bridge model"""
    # dynamical system
    bridge_ds = FirstOrderLinearDS(init_state, A)
    # interaction
    diode_bridge_relation = FirstOrderLinearTIR(C, B)
    diode_bridge_relation.setDPtr(D)

    nslaw = ComplementarityConditionNSL(4)
    bridge_interaction = Interaction(4, nslaw, diode_bridge_relation, 1)

    # Model
    diode_bridge = Model(t0, total_time, model_title)

    #  add the dynamical system in the non smooth dynamical system
    diode_bridge.nonSmoothDynamicalSystem().insertDynamicalSystem(bridge_ds)

    #   link the interaction and the dynamical system
    diode_bridge.nonSmoothDynamicalSystem().link(bridge_interaction, bridge_ds)

    # Simulation

    # (1) OneStepIntegrators
    theta = 0.5
    integrator = EulerMoreauOSI(theta)
    # (2) Time discretisation
    time_discretisation = TimeDiscretisation(t0, time_step)

    # (3) Non smooth problem
    non_smooth_problem = LCP()

    # (4) Simulation setup with (1) (2) (3)
    bridge_simulation = TimeStepping(time_discretisation,
                                     integrator, non_smooth_problem)

    # simulation initialization
    diode_bridge.setSimulation(bridge_simulation)
    diode_bridge.initialize()
    k = 0
    h = bridge_simulation.timeStep()
    # Number of time steps
    N = (total_time - t0) / h

    # Get the values to be plotted
    # ->saved in a matrix dataPlot
    data_plot = empty([N, 8])

    x = bridge_ds.x()
    print("Initial state : ", x)
    y = bridge_interaction.y(0)
    print("First y : ", y)
    lambda_ = bridge_interaction.lambda_(0)

    # For the initial time step:
    # time
    data_plot[k, 0] = t0

    #  inductor voltage
    data_plot[k, 1] = x[0]

    # inductor current
    data_plot[k, 2] = x[1]

    # diode R1 current
    data_plot[k, 3] = y[0]

    # diode R1 voltage
    data_plot[k, 4] = - lambda_[0]

    # diode F2 voltage
    data_plot[k, 5] = - lambda_[1]

    # diode F1 current
    data_plot[k, 6] = lambda_[2]

    # resistor current
    data_plot[k, 7] = y[0] + lambda_[2]

    k += 1
    while k < N:
        bridge_simulation.computeOneStep()
        #non_smooth_problem.display()
        data_plot[k, 0] = bridge_simulation.nextTime()
        #  inductor voltage
        data_plot[k, 1] = x[0]
        # inductor current
        data_plot[k, 2] = x[1]
        # diode R1 current
        data_plot[k, 3] = y[0]
        # diode R1 voltage
        data_plot[k, 4] = - lambda_[0]
        # diode F2 voltage
        data_plot[k, 5] = - lambda_[1]
        # diode F1 current
        data_plot[k, 6] = lambda_[2]
        # resistor current
        data_plot[k, 7] = y[0] + lambda_[2]
        k += 1
        bridge_simulation.nextStep()

    #
    # comparison with the reference file
    #
    ref = getMatrix(SimpleMatrix(os.path.join(working_dir,
                                              "data/diode_bridge.ref")))
    assert norm(data_plot - ref) < 1e-12
    return ref, data_plot
예제 #14
0
def test_bouncing_ball1():

    from siconos.kernel import LagrangianLinearTIDS, NewtonImpactNSL, \
        LagrangianLinearTIR, Interaction, Model, MoreauJeanOSI, TimeDiscretisation, LCP, TimeStepping

    from numpy import array, eye, empty

    t0 = 0       # start time
    T = 10       # end time
    h = 0.005    # time step
    r = 0.1      # ball radius
    g = 9.81     # gravity
    m = 1        # ball mass
    e = 0.9      # restitution coeficient
    theta = 0.5  # theta scheme

    #
    # dynamical system
    #
    x = array([1, 0, 0])  # initial position
    v = array([0, 0, 0])  # initial velocity
    mass = eye(3)         # mass matrix
    mass[2, 2] = 3./5 * r * r

    # the dynamical system
    ball = LagrangianLinearTIDS(x, v, mass)

    # set external forces
    weight = array([-m * g, 0, 0])
    ball.setFExtPtr(weight)

    #
    # Interactions
    #

    # ball-floor
    H = array([[1, 0, 0]])

    nslaw = NewtonImpactNSL(e)
    relation = LagrangianLinearTIR(H)
    inter = Interaction(1, nslaw, relation)

    #
    # Model
    #
    bouncingBall = Model(t0, T)

    # add the dynamical system to the non smooth dynamical system
    bouncingBall.nonSmoothDynamicalSystem().insertDynamicalSystem(ball)

    # link the interaction and the dynamical system
    bouncingBall.nonSmoothDynamicalSystem().link(inter, ball)

    #
    # Simulation
    #

    # (1) OneStepIntegrators
    OSI = MoreauJeanOSI(theta)
    OSI.insertDynamicalSystem(ball)

    # (2) Time discretisation --
    t = TimeDiscretisation(t0, h)

    # (3) one step non smooth problem
    osnspb = LCP()

    # (4) Simulation setup with (1) (2) (3)
    s = TimeStepping(t)
    s.insertIntegrator(OSI)
    s.insertNonSmoothProblem(osnspb)

    # end of model definition

    #
    # computation
    #

    # simulation initialization
    bouncingBall.initialize(s)

    #
    # save and load data from xml and .dat
    #
    try:
        from siconos.io import save
        save(bouncingBall, "bouncingBall.xml")
        save(bouncingBall, "bouncingBall.bin")

    except:
        print("Warning : could not import save from siconos.io")

    # the number of time steps
    N = (T-t0)/h+1

    # Get the values to be plotted
    # ->saved in a matrix dataPlot

    dataPlot = empty((N, 5))

    #
    # numpy pointers on dense Siconos vectors
    #
    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)
    lambda_ = inter.lambda_(1)

    #
    # initial data
    #
    dataPlot[0, 0] = t0
    dataPlot[0, 1] = q[0]
    dataPlot[0, 2] = v[0]
    dataPlot[0, 3] = p[0]
    dataPlot[0, 4] = lambda_[0]

    k = 1

    # time loop
    while(s.hasNextEvent()):
        s.computeOneStep()

        dataPlot[k, 0] = s.nextTime()
        dataPlot[k, 1] = q[0]
        dataPlot[k, 2] = v[0]
        dataPlot[k, 3] = p[0]
        dataPlot[k, 4] = lambda_[0]

        k += 1
        #print(s.nextTime())
        s.nextStep()

    #
    # comparison with the reference file
    #
    from siconos.kernel import SimpleMatrix, getMatrix
    from numpy.linalg import norm

    ref = getMatrix(SimpleMatrix(os.path.join(working_dir, "data/result.ref")))

    assert (norm(dataPlot - ref) < 1e-12)
예제 #15
0
sim.initialize()

# Run simulation
sim.run()

# Get data
dataPlot = sim.data()

# Save to disk
savetxt('SMCExampleImplicitOT2-noCplugin-sage-py.dat', dataPlot)
# Plot interesting data
subplot(411)
title('x1')
plot(dataPlot[:, 0], dataPlot[:, 1])
grid()
subplot(412)
title('x2')
plot(dataPlot[:, 0], dataPlot[:, 2])
grid()
subplot(413)
title('u')
plot(dataPlot[:, 0], dataPlot[:, 3])
savefig('ismcOT2_x_u.png')

# compare with the reference
ref = getMatrix(SimpleMatrix("SMCExampleImplicitOT2-py.ref"))
print("%19e" % norm(dataPlot - ref))
if (norm(dataPlot - ref) > 1e-12):
    print(dataPlot - ref)
    print("Warning. The result is rather different from the reference file.")
예제 #16
0
def test_xml5():
    ''' Bouncing Ball ED '''
    # --- buildModelXML loading from xml file ---
    bouncingBall = buildModelXML(os.path.join(working_dir, 'data/BBallED.xml'))

    # --- Get and initialize the simulation ---
    s = bouncingBall.simulation()
    dsN = SK.dynamicalSystems(bouncingBall.nonSmoothDynamicalSystem().topology().dSG(0))[0].number()
    ball = bouncingBall.nonSmoothDynamicalSystem().dynamicalSystem(dsN)

    # --- Get the values to be plotted ---
    # . saved in a matrix dataPlot

    N = 12368  # Number of saved points: depends on the number of events ...
    outputSize = 5
    dataPlot = np.zeros((N + 1, outputSize))

    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)
    f = ball.p(2)

    dataPlot[0, 0] = bouncingBall.t0()
    dataPlot[0, 1] = q[0]
    dataPlot[0, 2] = v[0]
    dataPlot[0, 3] = p[0]
    dataPlot[0, 4] = f[0]

    print("====> Start computation ... ")
    # --- Time loop  ---
    eventsManager = s.eventsManager()
    numberOfEvent = 0
    k = 0
    nonSmooth = False

    while s.hasNextEvent():
        k += 1

        s.advanceToEvent()
        if eventsManager.nextEvent().getType() == 2:
            nonSmooth = True

        s.processEvents()
        # If the treated event is non smooth, the pre-impact state has been solved in memory vectors during process.
        if nonSmooth:
            dataPlot[k, 0] = s.startingTime()
            dataPlot[k, 1] = ball.qMemory().getSiconosVector(1)[0]
            dataPlot[k, 2] = ball.velocityMemory().getSiconosVector(1)[0]
            k += 1
            nonSmooth = False
        dataPlot[k, 0] = s.startingTime()
        dataPlot[k, 1] = q[0]
        dataPlot[k, 2] = v[0]
        dataPlot[k, 3] = p[0]
        dataPlot[k, 4] = f[0]
        numberOfEvent += 1

    # --- Output files ---
    dataPlot.resize(k, outputSize)
    np.savetxt("BBallED.dat",  dataPlot)
    # Comparison with a reference file
    dataPlotRef = SK.getMatrix(SK.SimpleMatrix(os.path.join(working_dir, 'data/BouncingBallEDXml.ref')))

    if np.linalg.norm(dataPlot - dataPlotRef, ord=np.inf) > 1e-11:
        print("Warning. The results is rather different from the reference file.")
        print(np.linalg.norm(dataPlot - dataPlotRef, ord=np.inf))
        exit(1)
            index1 = sk.interactions(simulation.indexSet(1))
            if (len(index1) == 4):
                dataPlot[k, 3] = norm(index1[0].lambda_(1)) + \
                norm(index1[1].lambda_(1)) + norm(index1[2].lambda_(1)) + \
                norm(index1[3].lambda_(1))

    k += 1
    simulation.nextStep()

#
# comparison with the reference file
#
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("result_dynamic.ref"))

print("norm(dataPlot - ref) = {0}".format(norm(dataPlot - ref)))
if (norm(dataPlot - ref) > 1e-11):
    print("Warning. The result is rather different from the reference file.")


#
# plots
#

from matplotlib.pyplot import subplot, title, plot, grid, show

subplot(511)
title('position')
plot(dataPlot[0:k, 0], dataPlot[0:k, 1])
예제 #18
0
def test_diode_bridge():
    """Build diode bridge model"""
    # dynamical system
    bridge_ds = FirstOrderLinearDS(init_state, A)
    # interaction
    diode_bridge_relation = FirstOrderLinearTIR(C, B)
    diode_bridge_relation.setDPtr(D)

    nslaw = ComplementarityConditionNSL(4)
    bridge_interaction = Interaction(4, nslaw, diode_bridge_relation, 1)

    # Model
    diode_bridge = Model(t0, total_time, model_title)

    #  add the dynamical system in the non smooth dynamical system
    diode_bridge.nonSmoothDynamicalSystem().insertDynamicalSystem(bridge_ds)

    #   link the interaction and the dynamical system
    diode_bridge.nonSmoothDynamicalSystem().link(bridge_interaction, bridge_ds)

    # Simulation

    # (1) OneStepIntegrators
    theta = 0.5
    integrator = EulerMoreauOSI(theta)
    integrator.insertDynamicalSystem(bridge_ds)

    # (2) Time discretisation
    time_discretisation = TimeDiscretisation(t0, time_step)

    # (3) Non smooth problem
    non_smooth_problem = LCP()

    # (4) Simulation setup with (1) (2) (3)
    bridge_simulation = TimeStepping(time_discretisation, integrator,
                                     non_smooth_problem)

    # simulation initialization
    diode_bridge.initialize(bridge_simulation)
    k = 0
    h = bridge_simulation.timeStep()
    # Number of time steps
    N = (total_time - t0) / h

    # Get the values to be plotted
    # ->saved in a matrix dataPlot
    data_plot = empty([N, 8])

    x = bridge_ds.x()
    print("Initial state : ", x)
    y = bridge_interaction.y(0)
    print("First y : ", y)
    lambda_ = bridge_interaction.lambda_(0)

    # For the initial time step:
    # time
    data_plot[k, 0] = t0

    #  inductor voltage
    data_plot[k, 1] = x[0]

    # inductor current
    data_plot[k, 2] = x[1]

    # diode R1 current
    data_plot[k, 3] = y[0]

    # diode R1 voltage
    data_plot[k, 4] = -lambda_[0]

    # diode F2 voltage
    data_plot[k, 5] = -lambda_[1]

    # diode F1 current
    data_plot[k, 6] = lambda_[2]

    # resistor current
    data_plot[k, 7] = y[0] + lambda_[2]

    k += 1
    while k < N:
        bridge_simulation.computeOneStep()
        #non_smooth_problem.display()
        data_plot[k, 0] = bridge_simulation.nextTime()
        #  inductor voltage
        data_plot[k, 1] = x[0]
        # inductor current
        data_plot[k, 2] = x[1]
        # diode R1 current
        data_plot[k, 3] = y[0]
        # diode R1 voltage
        data_plot[k, 4] = -lambda_[0]
        # diode F2 voltage
        data_plot[k, 5] = -lambda_[1]
        # diode F1 current
        data_plot[k, 6] = lambda_[2]
        # resistor current
        data_plot[k, 7] = y[0] + lambda_[2]
        k += 1
        bridge_simulation.nextStep()

    #
    # comparison with the reference file
    #
    ref = getMatrix(
        SimpleMatrix(os.path.join(working_dir, "data/diode_bridge.ref")))
    assert norm(data_plot - ref) < 1e-12
    return ref, data_plot
예제 #19
0
    dataPlot[k, 0] = aTS.nextTime()
    #  inductor voltage
    dataPlot[k, 1] = x[0]
    # inductor current
    dataPlot[k, 2] = x[1]
    # diode  voltage
    dataPlot[k, 3] = -y[0]
    # diode  current
    dataPlot[k, 4] = lambda_[0]
    dataPlot[k, 5] = 0.
    k += 1
    aTS.nextStep()

# comparison with reference file

ref = sk.getMatrix(sk.SimpleMatrix("CircuitRLCD.ref"))

#assert (np.linalg.norm(dataPlot - ref) < 1e-10)

if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    grid()
    subplot(412)
    title('inductor current')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 2])
    grid()
예제 #20
0
while s.hasNextEvent():
    s.computeOneStep()

    dataPlot[k, 0] = s.nextTime()
    dataPlot[k, 1] = q[0]
    dataPlot[k, 2] = v[0]
    dataPlot[k, 3] = p[0]
    dataPlot[k, 4] = lambda_[0]

    k += 1
    s.nextStep()

#
# comparison with the reference file
#
ref = getMatrix(SimpleMatrix("BouncingBallTS.ref"))

if (norm(dataPlot - ref) > 1e-12):
    print("Warning. The result is rather different from the reference file.")
    print(norm(dataPlot - ref))

#
# plots
#
havedisplay = "DISPLAY" in os.environ
if not havedisplay:
    matplotlib.use('Agg')

plt.subplot(411)
plt.title('position')
plt.plot(dataPlot[:, 0], dataPlot[:, 1])
예제 #21
0
def test_serialization4():
    from siconos.kernel import LagrangianLinearTIDS, NewtonImpactNSL, \
        LagrangianLinearTIR, Interaction, Model, MoreauJeanOSI, TimeDiscretisation, LCP, TimeStepping

    from numpy import array, eye, empty

    t0 = 0       # start time
    T = 10       # end time
    h = 0.005    # time step
    r = 0.1      # ball radius
    g = 9.81     # gravity
    m = 1        # ball mass
    e = 0.9      # restitution coeficient
    theta = 0.5  # theta scheme

    #
    # dynamical system
    #
    x = array([1, 0, 0])  # initial position
    v = array([0, 0, 0])  # initial velocity
    mass = eye(3)         # mass matrix
    mass[2, 2] = 3./5 * r * r

    # the dynamical system
    ball = LagrangianLinearTIDS(x, v, mass)

    # set external forces
    weight = array([-m * g, 0, 0])
    ball.setFExtPtr(weight)

    #
    # Interactions
    #

    # ball-floor
    H = array([[1, 0, 0]])

    nslaw = NewtonImpactNSL(e)
    relation = LagrangianLinearTIR(H)
    inter = Interaction(1, nslaw, relation)

    #
    # Model
    #
    first_bouncingBall = Model(t0, T)

    # add the dynamical system to the non smooth dynamical system
    first_bouncingBall.nonSmoothDynamicalSystem().insertDynamicalSystem(ball)

    # link the interaction and the dynamical system
    first_bouncingBall.nonSmoothDynamicalSystem().link(inter, ball)

    #
    # Simulation
    #

    # (1) OneStepIntegrators
    OSI = MoreauJeanOSI(theta)

    # (2) Time discretisation --
    t = TimeDiscretisation(t0, h)

    # (3) one step non smooth problem
    osnspb = LCP()

    # (4) Simulation setup with (1) (2) (3)
    s = TimeStepping(t)
    s.insertIntegrator(OSI)
    s.insertNonSmoothProblem(osnspb)

    # end of model definition

    #
    # computation
    #

    # simulation initialization
    first_bouncingBall.setSimulation(s)
    first_bouncingBall.initialize()

    #
    # save and load data from xml and .dat
    #
    from siconos.io.io_base import save, load
    save(first_bouncingBall, "bouncingBall.xml")

    bouncingBall = load("bouncingBall.xml")

    # the number of time steps
    N = (T-t0)/h+1

    # Get the values to be plotted
    # ->saved in a matrix dataPlot

    dataPlot = empty((N, 5))

    #
    # numpy pointers on dense Siconos vectors
    #
    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)
    lambda_ = inter.lambda_(1)

    #
    # initial data
    #
    dataPlot[0, 0] = t0
    dataPlot[0, 1] = q[0]
    dataPlot[0, 2] = v[0]
    dataPlot[0, 3] = p[0]
    dataPlot[0, 4] = lambda_[0]

    k = 1

    # time loop
    while(s.hasNextEvent()):
        s.computeOneStep()

        dataPlot[k, 0] = s.nextTime()
        dataPlot[k, 1] = q[0]
        dataPlot[k, 2] = v[0]
        dataPlot[k, 3] = p[0]
        dataPlot[k, 4] = lambda_[0]

        k += 1
        print(s.nextTime())
        s.nextStep()

    #
    # comparison with the reference file
    #
    from siconos.kernel import SimpleMatrix, getMatrix
    from numpy.linalg import norm

    ref = getMatrix(SimpleMatrix(os.path.join(working_dir,
                                              "data/result.ref")))

    assert (norm(dataPlot - ref) < 1e-12)
예제 #22
0
subplot(411)
title('x1')
plot(dataPlot[:, 0], dataPlot[:, 1])
grid()
subplot(412)
title('x2')
plot(dataPlot[:, 0], dataPlot[:, 2])
grid()
subplot(413)
title('u')
plot(dataPlot[:, 0], dataPlot[:, 3])
grid()
savefig('ismcOT2_x_u')

subplot(211)
p1 = plot(dataPlot[:, 0], dataPlot[:, 2])
plt.ylabel('$\sigma$')
plt.xlabel('t')
grid()
subplot(212)
p2 = plot(dataPlot[:, 0], dataPlot[:, 3])
plt.ylabel('u')
plt.xlabel('t')
savefig('ismcOT2_sigma_u')

# TODO
# compare with the reference
ref = getMatrix(SimpleMatrix("SMCExampleImplicitOT2-py.ref"))
if (norm(dataPlot - ref) > 1e-12):
    print("Warning. The result is rather different from the reference file.")
예제 #23
0
    dataPlot[k, 10] = q[3]
    dataPlot[k, 11] = q[4]
    dataPlot[k, 12] = q[5]
    dataPlot[k, 13] = q[6]
    dataPlot[k, 14] = v[1]
    dataPlot[k, 15] = v[2]
    k = k + 1
    s.nextStep()

savetxt("result-py.dat", dataPlot)
#
# comparison with the reference file
#
from siconos.kernel import SimpleMatrix, getMatrix

ref = getMatrix(SimpleMatrix("resultNETS.ref"))
err = linalg.norm(dataPlot - ref)
print("error w.r.t reference file =", err)

if (err > 1e-12):
    print("Warning. The result is rather different from the reference file.")


#
# plots
#
from matplotlib.pyplot import subplot, title, plot, grid, show

subplot(411)
title('position')
plot(dataPlot[:, 0], dataPlot[:, 1])
            index1 = sk.interactions(simulation.indexSet(1))
            if (len(index1) == 4):
                dataPlot[k, 3] = norm(index1[0].lambda_(1)) + \
                norm(index1[1].lambda_(1)) + norm(index1[2].lambda_(1)) + \
                norm(index1[3].lambda_(1))

    k += 1
    simulation.nextStep()

#
# comparison with the reference file
#
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("result_dynamic.ref"))

print("norm(dataPlot - ref) = {0}".format(norm(dataPlot - ref)))
if (norm(dataPlot - ref) > 1e-11):
    print("Warning. The result is rather different from the reference file.")

#
# plots
#

if do_plot:
    subplot(511)
    title('position')
    plot(dataPlot[0:k, 0], dataPlot[0:k, 1])
    y = ylim()
    plot(ref[0:k, 0], ref[0:k, 1])
예제 #25
0
    # diode R1 current
    dataPlot[k, 3] = lambda_[0]
    # diode R1 voltage
    dataPlot[k, 4] = -y[0]
    # diode F2 voltage
    dataPlot[k, 5] = -lambda_[1]
    # diode F1 current
    dataPlot[k, 6] = lambda_[2]
    k += 1
    aTS.nextStep()

# comparison with reference file
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("DiodeBridgeCapFilter.ref"))

error = norm(dataPlot[:, 0:4] - ref[:, 0:4])
print("error = ", error)

assert (error < 1e-09)
withRef = False
if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    if (withRef):
        plot(ref[0:k - 1, 0], ref[0:k - 1, 1])
예제 #26
0
def test_bouncing_ball1():
    """Run a complete simulation (Bouncing ball example)
    LagrangianLinearTIDS,  no plugins.
    """

    t0 = 0.      # start time
    tend = 10.   # end time
    h = 0.005    # time step
    r = 0.1      # ball radius
    g = 9.81     # gravity
    m = 1        # ball mass
    e = 0.9      # restitution coeficient
    theta = 0.5  # theta scheme

    #
    # dynamical system
    #
    x = np.zeros(3, dtype=np.float64)
    x[0] = 1.
    v = np.zeros_like(x)
    # mass matrix
    mass = np.eye(3, dtype=np.float64)
    mass[2, 2] = 3. / 5 * r * r

    # the dynamical system
    ball = sk.LagrangianLinearTIDS(x, v, mass)

    # set external forces
    weight = np.zeros_like(x)
    weight[0] = -m * g
    ball.setFExtPtr(weight)

    #
    # Interactions
    #

    # ball-floor
    H = np.zeros((1, 3), dtype=np.float64)
    H[0, 0] = 1.

    nslaw = sk.NewtonImpactNSL(e)
    relation = sk.LagrangianLinearTIR(H)
    inter = sk.Interaction(nslaw, relation)

    #
    # NSDS
    #
    bouncing_ball = sk.NonSmoothDynamicalSystem(t0, tend)

    # add the dynamical system to the non smooth dynamical system
    bouncing_ball.insertDynamicalSystem(ball)

    # link the interaction and the dynamical system
    bouncing_ball.link(inter, ball)

    #
    # Simulation
    #

    # (1) OneStepIntegrators
    OSI = sk.MoreauJeanOSI(theta)

    # (2) Time discretisation --
    t = sk.TimeDiscretisation(t0, h)

    # (3) one step non smooth problem
    osnspb = sk.LCP()

    # (4) Simulation setup with (1) (2) (3)
    s = sk.TimeStepping(bouncing_ball,t, OSI, osnspb)

    # end of model definition

    #
    # computation
    #
    
    #
    # save and load data from xml and .dat
    #
    try:
        from siconos.io import save
        save(bouncing_ball, "bouncingBall.xml")
        save(bouncing_ball, "bouncingBall.bin")

    except:
        print("Warning : could not import save from siconos.io")

    # the number of time steps
    nb_time_steps = int((tend - t0) / h + 1)

    # Get the values to be plotted
    # ->saved in a matrix dataPlot

    data = np.empty((nb_time_steps, 5))

    #
    # numpy pointers on dense Siconos vectors
    #
    q = ball.q()
    v = ball.velocity()
    p = ball.p(1)
    lambda_ = inter.lambda_(1)

    #
    # initial data
    #
    data[0, 0] = t0
    data[0, 1] = q[0]
    data[0, 2] = v[0]
    data[0, 3] = p[0]
    data[0, 4] = lambda_[0]

    k = 1

    # time loop
    while(s.hasNextEvent()):
        s.computeOneStep()

        data[k, 0] = s.nextTime()
        data[k, 1] = q[0]
        data[k, 2] = v[0]
        data[k, 3] = p[0]
        data[k, 4] = lambda_[0]

        k += 1
        #print(s.nextTime())
        s.nextStep()

    #
    # comparison with the reference file
    #

    ref = sk.getMatrix(sk.SimpleMatrix(
        os.path.join(working_dir, "data/result.ref")))
    assert (np.linalg.norm(data - ref) < 1e-12)
    # diode R1 current
    dataPlot[k, 3] =    lambda_[0]
    # diode R1 voltage
    dataPlot[k, 4] = - y[0]
    # diode F2 voltage
    dataPlot[k, 5] = - lambda_[1]
    # diode F1 current
    dataPlot[k, 6] = lambda_[2]
    k += 1
    aTS.nextStep()

# comparison with reference file
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("DiodeBridgeCapFilter.ref"))

error = norm(dataPlot[:,0:6] - ref[:,0:6])
print "error = " , error

#assert (error < 1e-09)
withRef = False
if (withPlot):
    #
    # plots
    #
    subplot(411)
    title('inductor voltage')
    plot(dataPlot[0:k - 1, 0], dataPlot[0:k - 1, 1])
    if (withRef):
        plot(ref[0:k - 1, 0], ref[0:k - 1, 1])
예제 #28
0
    dataPlot[k, 0] = s.nextTime()
    dataPlot[k, 1] = q[0]
    dataPlot[k, 2] = v[0]
    dataPlot[k, 3] = p[0]
    dataPlot[k, 4] = lambda_[0]

    k += 1
    s.nextStep()

#
# comparison with the reference file
#
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm

ref = getMatrix(SimpleMatrix("result.ref"))

if (norm(dataPlot - ref) > 1e-12):
    print("Warning. The result is rather different from the reference file.")


#
# plots
#
import matplotlib,os
havedisplay = "DISPLAY" in os.environ
if not havedisplay:
    matplotlib.use('Agg')

import matplotlib.pyplot as plt
plt.subplot(411)
예제 #29
0
    dataPlot[k, 10] = q[3]
    dataPlot[k, 11] = q[4]
    dataPlot[k, 12] = q[5]
    dataPlot[k, 13] = q[6]
    dataPlot[k, 14] = v[1]
    dataPlot[k, 15] = v[2]
    k = k + 1
    s.nextStep()

savetxt("result-py.dat", dataPlot)
#
# comparison with the reference file
#
from siconos.kernel import SimpleMatrix, getMatrix

ref = getMatrix(SimpleMatrix("resultNETS.ref"))
err = linalg.norm(dataPlot - ref)
print("error w.r.t reference file =", err)

if (err > 1e-12):
    print("Warning. The result is rather different from the reference file.")

#
# plots
#
from matplotlib.pyplot import subplot, title, plot, grid, show

subplot(411)
title('position')
plot(dataPlot[:, 0], dataPlot[:, 1])
grid()