Example #1
0
    def _compute_linear_coeff_sparse(self):
        """Compute M, K and C matrices of the Lagrangian DS
        K = Omega^2
        C = 2.Gamma
        """
        mass = sk.SimpleMatrix(self.ndof, self.ndof, sk.SPARSE, self.ndof)
        for i in range(self.ndof):
            mass.setValue(i, i, 1.)
        indices = np.arange(self.ndof)
        # --- Omega^2 matrix ---
        omega = npw.asrealarray(
            [1. + self.stiffness_coeff * j**2 for j in range(self.ndof)])
        coeff = (indices * math.pi * self.c0 / self.length)**2
        omega *= coeff
        stiffness_mat = sk.SimpleMatrix(self.ndof, self.ndof, sk.SPARSE,
                                        self.ndof)
        for i in range(self.ndof):
            stiffness_mat.setValue(i, i, omega[i])

        # 2.S.Gamma.S-1
        sigma = self.compute_damping(np.sqrt(omega) / (2. * math.pi))
        damping_mat = sk.SimpleMatrix(self.ndof, self.ndof, sk.SPARSE,
                                      self.ndof)
        for i in range(self.ndof):
            damping_mat.setValue(i, i, 2. * sigma[i])
        return mass, stiffness_mat, damping_mat
Example #2
0
    def __init__(self, string, position=None, restitution_coeff=1.):
        """"
        """
        # siconos relation
        self.position = position[1] * npw.ones(1)
        self.contact_index = position[0]
        if string.modal_form:
            coeff = 1.  # string.length / string._N
            if string.use_sparse:
                hmat = sk.SimpleMatrix(1, string.ndof, sk.SPARSE, string.ndof)
                for i in xrange(string.ndof):
                    val = coeff * string.s_mat[self.contact_index, i]
                    hmat.setValue(0, i, val)
            else:
                hmat = npw.zeros((1, string.ndof))
                hmat[...] = string.s_mat[self.contact_index, :]
                hmat *= coeff
        else:
            hmat = npw.zeros((1, string.ndof))
            hmat[0, self.contact_index] = 1.

        e = restitution_coeff
        nslaw = sk.NewtonImpactNSL(e)
        relation = sk.LagrangianLinearTIR(hmat, -self.position)
        super(Fret, self).__init__(nslaw, relation)
Example #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()
Example #4
0
 def initialize(self, io):
     self.nsds = io._model.nonSmoothDynamicalSystem()
     self.topo = self.nsds.topology()
     self.joint1_inter = self.topo.getInteraction('joint1')
     self.joint1 = Mechanics.joints.cast_NewtonEulerJointR(
         self.joint1_inter.relation())
     self.bar = self.topo.getDynamicalSystem('bar')
     self.post = self.topo.getDynamicalSystem('post')
     self.y = Kernel.SiconosVector(5)
     self.yDoF = Kernel.SiconosVector(1)
     self.jachq = Kernel.SimpleMatrix(1, 14)
Example #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.")
Example #6
0
def test_matrix_bracket_operator():
    M = sk.SimpleMatrix(10,10)
    M.zero()
    M_nparray = np.zeros((10,10))
    print(M_nparray)
    def fill_matrix(M, M_nparray):
        for i in range(M.size(0)):
            for j in range(M.size(1)):
                M[i,j] = float(i+j)
                M_nparray[i,j] = float(i+j)
                
        return
    fill_matrix(M,M_nparray)
    
    #print(M, type(M))
    #print(M_nparray, type(M_nparray))
    for i in range(M.size(0)):
        for j in range(M.size(1)):
            if M[i,j] != i+j :
                return False
            
    #assert((M == M_nparray).all())

            
    M[0,1]=266.0
    if M[0,1] != 266.0:
        return (M[0,1]== 266.0)
    
    try:
        # Slice indexing for SimpleMatrix is not yet implemented.
        M[0:1]= [0,2]
    except Exception as e:
        print(e)

    try:
        M[1.0,1]= 4.0
        # SiconosMatrix must be indexed by integer
    except Exception as e:
        print(e)
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)
Example #8
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()
Example #9
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)