# Guy and Seth on Simulink

## Tracing Requirements to Models, Tests, and Generated Code

When I wrote a post about the R2013b new features, Fraser replied in a comment that one of his favorite new feature is the requirements linking to MATLAB code.

This made me realize that I never described on this blog how Simulink Verification and Validation allows the tracing of requirements to models, tests, and generated code:

To help readers not familiar with this topic, this week I give a quick overview of how Simulink Verification and Validation can facilitate maintaining and demonstrating traceability of high-level requirements to Simulink models and generated code.

The first step is to link requirements stored in an external document to blocks in your model. If I have requirements stored in a Microsoft® Word document, I can select the text I want to link:

Then I go to the model, right-click the block to be linked and select Link to Selection in Word:

In the model, the right-click menu of the block now contains a link that can be used to highlight the requirement in Word.

Requirements in the generated code

If you generate code for your model, you can choose to include the requirements as comments in the code. In the code generation report, you will see hyperlinks allowing you to navigate directly to the requirements document.

Traceability report

To get the big picture of the requirements in your model, you can generate a traceability report. Using Simulink Report Generator, you can configure the look of the report.

For the simple block in the example above, the default report looks like this:

Requirements Consistency Check

As your project evolves, you can run a set of Requirements Consistency Checks in the Model Advisor to ensure that the requirements links are still up-to-date and valid.

How do you navigate between your Simulink models and your requirements? Let us know by leaving a comment here.

## Hyperloop: Not so fast!

This week Matt Brauer is back to describe work he did to analyze the trajectory of the Hyperloop proposal. This is a key input to the Hyperloop Simulink models we are building.

Matt's conclusion is surprising:
From the perspective of geographic constraints and rider comfort, the 760 mph peak speed is not an issue. It’s the 300 mph section through the suburbs of San Francisco that requires closer consideration.

Where is the Hyperloop going?

As mentioned in a previous blog post, we’ve begun implementing Simulink models of the Hyperloop concept. To exercise those models, a core piece of information is the trajectory. We need to know where the Hyperloop is going and at what speed. I analyzed the proposal to derive this information, and what I found was interesting. From the perspective of geographic constraints and rider comfort, the 760 mph peak speed is not an issue. It’s the 300 mph section through the suburbs of San Francisco that requires closer consideration.

Potential Hyperloop route, including image from http://www.spacex.com/sites/spacex/files/hyperloop_alpha-20130812.pdf and Google Earth

The basic idea put forth in the proposal is to follow existing highways as much as possible. In order to limit lateral accelerations experienced by the passengers to 0.5g, there needs to be “minor deviations when the highway makes a sharp turn”. I remember from Freshmen Physics class that centripetal acceleration in a curve is proportional to the square of velocity. This means that increasing your velocity from 76 to 760 mph is actually a 100x multiplication of g forces.

Is it really possible to average 600 mph across the state of California on available land without making passengers nauseous? Or would a reasonable trajectory require wide loops, impeding on private citizens’ backyards? I put the technical computing power of MATLAB to work on answering these questions.

Technical Computing of a Route

I won’t go into all the details because this is a Simulink blog, but here is an overview of the steps I followed:

• First, I used Google Earth to get a set of longitude and latitude points along the California highways I-5 and I-580. After getting directions, saved a KML file with the data.
• I used the read_kml submission from the MATLAB Central File Exchange to import the data in MATLAB.
• It is possible to use functions like wmsfind, wmsupdate and wmsread from the Mapping Toolbox to add topography data to the route and surrounding area. However, I only used this information for plotting. For this first study, the derived route is only 2-dimensional.
• This gave me a set of discrete points along the highways, to which I associated a desired velocity based on the Hyperloop document.
• From these target points, I created a smoothed trajectory using the fit function from the Curve Fitting Toolbox.
• Using this smoothed trajectory, I wrote a simple script to calculate and plot the lateral acceleration along this trajectory.
• For the portions of the trajectory that were exceeding 0.5g's, I adjusted some target points to drive lateral accelerations below 0.5g’s while staying as close as possible to the original route.

In the end, I got the results below:

Velocity and Acceleration along derived Hyperloop route (created using the Mapping Toolbox)

You can see that the travel time is very close to the advertised 35 minutes. The accelerations were kept within reason, although it looks like a pretty dynamic ride.

How much does the Hyperloop need to deviate from the existing highways in order to achieve these results?

The red line shows the targeted highways. The yellow portions show sections of the derived Hyperloop route that deviate from the mean highway route by more than 50m. The yellow, "off-highway", portions account for 113 miles of the 347 mile trip.

To review in depth, I wrote the trajectory back to KML using kmlwriteline from the Mapping Toolbox. Now it's possible to view the derived route in Google Earth.

No major issues seen along I-5 (Image created using Google Earth)

Again, the red line is the mean highway route. Here, the yellow line shows the complete derived Hyperloop route. Upon reviewing the details, the route seems pretty reasonable up until I-580 outside of the bay area.

When I-580 turns west and starts going through the San Francisco suburbs, it becomes difficult to stay on the road. Here’s a snapshot of a particularly rough curve:

Re-routing along I-580 to avoid excessive g-forces (Image created using Google Earth)

Below is the route data for the area surrounding the above curve.

Despite the issues highlighted above, the final conclusion is quite positive. It seems that the first 295 miles of the route can be accomplished in about 27 minutes without excessive g’s on the passengers or encroaching on private property. “Landing” in the Bay Area may take a bit longer than originally advertised, but that seems like splitting hairs at this point. Further investigation is certainly warranted. So, let’s get those Simulink models running!

What do you think? Is the Hyperloop going in the right direction?

Given Elon Musk's statement that the Hyperloop should be an open design concept, would you be interested use Matt's trajectory and begin filling some of the boxes in our Hyperloop model architectures?

Let us know what you think by leaving a comment here.

## Motion Actuation in SimMechanics R2013b

In R2013b, it is possible to specify joint motion in SimMechanics Second Generation models. In this post, I will use a simple pendulum with internal friction and subject to gravity to highlight different ways to actuate a mechanism.

If you look at the dialog of a joint like the Revolute Joint, you will notice that each primitive now has two fields in the Actuation section: Torque and Motion.

The Torque field gives you 3 options: None, Provided by Input and Automatically Computed.

The Motion field two: Provided by Input and Automatically Computed.

This makes a total of 6 possible configurations for each joint primitive. In the Joint Actuation documentation page, you can find a description of all the modes into which a joint primitive can be actuated.

Passive: No torque and Automatically Computed Motion

This is the default setting, where the joint primitive is passive. For our example, the pendulum will simply fall under the effect of gravity.

Forward Dynamics: Torque Specified by Input and Automatically Computed Motion

A force or torque is specified for the joint primitive and the engine computes the resulting motion. For example, if we take the same pendulum as in the previous case and apply a constant torque, it will stabilize at an angle.

Inverse Dynamics: Motion specified by Input and Automatically Computed Torque

If you know how a joint should move and want to know the amount of torque or force necessary to make that happen, this mode is for you. For example, we can apply a sine wave motion to our pendulum and measure the torque required to generate this motion:

One important thing to note is that when specifying motion to a joint primitive, position, velocity and acceleration must be specified. To help with that, the Simulink-PS Converter gives the possibility to filter the desired motion and internally compute the first and second derivative of the input signal.

***Note: By default, the time constant in the Simulink-PS Converter block is 1e-3s. This value is appropriate for most Simscape domains, but for many SimMechanics models increasing it to 1e-2s can speed up the simulation without affecting the results significantly.

If filtering is not appropriate for your application, you can always turn it off and manually provide position, velocity and acceleration to the Simulink-PS Converter

Indirect Inverse Dynamics

This mode was not available in SimMechanics First Generation, and I decided to invent the expression indirect inverse Dynamics to describe it. As it is the case for Inverse Dynamics, the user specifies the motion of the mechanism. However the term Indirect means that SimMechanics automatically computes and applies the Forces and/or Torques necessary to produce the motion using joint primitives other than the ones where the motion is specified.

If we keep going with the same example, we can use the y-axis translational primitive of a Planar Joint to specify the translational motion of the pendulum extremity. SimMechanics can then compute the torque necessary at the pendulum base to generate this motion.

***Note that I included a Weld Joint in the previous model. In R2013b, SimMechanics Second Generation has a constraint that every kinematic loop must contain at least one joint with no motion actuation and no computed torque.

Indirect Inverse Dynamics... plus external forces

The last combination available is an extension of the previous. In addition to specifying the motion, it is possible to add an additional disturbance force or torque.

Try the new motion actuation in SimMechanics R2013b and let us know what you think by leaving a comment here.

## Hyperloop Model Architecture: We want your feedback!

We had some fun in our last post about the Hyperloop open source transportation system, but we didn't get much into the specifics. This week we begin to move things forward.

Before beginning to analyze the feasibility of individual components, we decided to think about how we would architect a Simulink model to simulate the Hyperloop. In my opinion, such a model should include:

• Componentization: It must be possible for a component to be used in isolation in test models, or as part of full system model
• Variants: For each component, it must be easy to switch between different levels of fidelity or content.
• Intuitive: If many engineers are going to participate in this project, it must be easy for them to understand the model.

With that in mind, Matt and I (Guy) built tentative architectures which we describe today. If you have experience creating models for collaborative development involving multiple engineers, we would really like to hear what you think in the comments.

Matt: Systems Approach

I really liked the way the hyperloop proposal partitioned the different systems. So, I followed their lead in my model architecture. I put six systems at the top level. Where applicable, the controls for that specific system reside with its model. This choice makes componentization more straight forward. I like to put images on a mask for each system to make their content clear.

click to enlarge

Each of these systems contains a referenced model. Those models become stand-alone environments for contributors to develop their own solutions for that system. Theoretically, these solutions could even depart from those put forth in the proposal. The developer is also free to utilize the modeling domain of their choice, be it Simulink, Simscape or integration of external tools.

It is possible to integrate different combinations of solutions and see how they work together. Variant selection can be parameterized as shown in the Block Parameter dialog below. Here, the variable varComp determines the active variant for the Compressor system.

The valid combinations could be managed through configuration sets within the Variant Manager. In the example below, there is a configuration for a Simulink version of the hyperloop proposal, a Simscape version of the same and a third configuration that utilizes a more conventional solution with hub motors and an independent suspension.

Since the interfaces between my components use Simulink signals, any toolbox or third party tool can be used to design the components. We can leverage advanced physical modeling tools and all users can reap the benefits.

From my perspective, the system-based hierarchy, combined with the images, makes an intuitive model. Using Model Reference means that there is a mechanism for variant control. Using Model Referencing with the right elements of the hierarchy provides the final ingredient; componentization. It’s all there.

Guy: Plant-Controller

To begin, I decided to go with an architecture I see often in Model-Based Design projects: a plant and a controller.

If you look inside the plant, you can find a layer where I convert signals between the ideal continuous plant and the discrete fixed-step controllers.

In the actual plant subsystem, you can see that I make intensive usage of our physical modeling toolboxes. I centered the design around one SimMechanics Solid block representing the center of mass of the capsule.

I also think we should use the Simscape electrical and pneumatic domains to model interactions between components.

To help identifying the data flow, I like to use a color code: green for Inports, red for Outports, blue for SimMechanics connections, etc...

Each component is a Variant Subsystem containing multiple versions of the component, with different implementations. The variants are stored in separate library files. By using a "one file per variant" approach, individual developers should be able to work in their own library file without modifying the rest of the model. This will also allow them to test their designs in smaller test models if needed.

With the central SimMechanics connection, each component can connect to the capsule to get information about its dynamics and apply forces or constraints to it. For example, the simplest model of air drag could look like the following, where I use a Transform Sensor to measure the capsule forward velocity and an External Force and Torque block to apply the drag.

For convenience, I packaged all my files in a Simulink Project. The startup script automatically sets the path and creates necessary variables as you open the project. I also defined shortcuts for common tasks, like opening the main model and plotting the final trajectory.

As you can see, our architectures are very different. We would really like to hear what you think. Do you prefer one, or the other, or something completely different? Tell us why by leaving a comment here.

## Don’t Engineer The Hyperloop in a Vacuum

Since it was released in August, the Hyperloop proposal by Elon Musk generated a lot of interest. Reactions were both positive and negative. As you can imagine, it also triggered a lot of discussions at Mathworks.

This week, we present you the synopsis of a discussion Seth, Matt and I recently had on this topic.

Seth: What do you think of the Hyperloop proposal from Elon Musk?

Matt: Who wouldn’t be interested in affordable, high-speed transportation that could get you the 350 miles from Los Angeles to San Francisco in 35 minutes? The technologies involved, electric motors, batteries, compressors, vehicle dynamics, seem to fit well with Simulink.

Guy: I can already image what such a Simulink model would look like, with all those components connected together.

Crowd-sourced Engineering Problems

Matt: Before we go too far, let’s look at what’s already been written.

Seth: Many media outlets and bloggers have posted articles about the hyperloop. Critics and proponents alike have highlighted difficulties in the proposal. Most, including The Economist, The NY Times and The Washington Post have questioned the proposed budget of $6 billion. These articles specifically question the costs of purchasing land and dealing with local community demands in building the infrastructure. Matt: Other sources have brought up more technical concerns. Scientific American questions how the air suspension would work at low speeds. The author also expresses concern about the cooling requirements to deal with air friction. There’s nearly a ton of water on board! I really like the summary from Gizmag. The author brings up inconsistency in the compressor design, motive power requirements and energy management for the pod and the tube. Guy: This is a perfect example of an application that needs simulation before building a prototype. Look at this image from the proposal: I can see SimMechanics being used along with the electrical and pneumatic Simscape domains to simulate such system. Matt: Here’s another interesting read. Pedestrian Observations expresses doubt about the capacity of the system in terms of trains and passengers per hour, given the limits of emergency braking. The author is pretty colorful in his concerns for the passengers’ comfort as well. G-forces may be unrealistic when traveling along existing highways. Seth: The Onion even gets involved. Constructively, they offer a novel solution for powering the system. Guy: Let’s be serious guys… I want to see that Simulink model ASAP! I'm not kidding... I don't always design Hyperloops, but when I do, I prefer Simulink. A Collaborative Environment for Engineering Solutions Seth: One thing that really intrigues me about the hyperloop is that it is “an open source transportation concept.” The authors want the engineering and scientific community to push the concept forward. Which problems would you solve with MATLAB and Simulink? Matt: Here are the engineering challenges I am interested in: • Air suspension control – maintaining trajectory and air gap while canting (rolling) for passenger comfort • Propulsion design and control – linear motor and power electronic sizing and control • Energy management for the vehicle - sizing of the energy storage • Energy management for the tube - solar/grid power requirements • Trajectory optimization – optimizing the route for cost while maintaining passenger comfort • Compression system design and control – pneumatic, hydraulic and thermal domains • Financial modeling - long term economic viability, including up-front and running costs Ideally, the environment will enable these problems to be solved in parallel, while leveraging the on-going development of each solution. Guy: Model referencing, variants and configuration management offered through Simulink Projects could provide such an environment. Seth: Wouldn’t it be great if there was a central repository for people to contribute to the ongoing development of the Hyperloop? Now it’s your turn Would you contribute to a massive collaborative project to simulate and evaluate the feasibility of the Hyperloop? Let us know by leaving a comment here. ## October 24th, 2013 ## Methods of the MATLAB System Block In the last post on MATLAB System block, I tried to provide a basic introduction to System Objects in MATLAB and Simulink environments. At the end, I finished with a quick example illustrating that System objects offer several methods to set up the properties of states and output signals of the system developed. This week, guest blogger Revathi Dukkipati will help us get a closer look at System object methods and the sequence in which they are implemented. Timing of methods in MATLAB When authoring System objects, one important thing to realize is that there are methods that you can call (for example step to process data), and the methods that you implement (for example stepImpl when you write your algorithm). To understand why there is a difference between the name of the method you call and the name of the method you implement, I recommend looking at the Methods Timing documentation page. You will find images like the following illustrating which methods you can call, and which methods you can or need to implement. For the step method, this looks like: The methods shown with a green background can be implemented by the user. Except for stepImpl which implements the algorithm, the other methods in green have an internal default implementation. You only need to implement them if the default is not appropriate for your application. The methods shown in white are completely controlled by MATLAB. Timing of Methods in Simulink When using a System object in Simulink through the MATLAB System block, it is important to know which methods are called during edit time, which methods are called during the model compilation and which methods are called every time step when the simulation runs. You can find an overview of this timing in the documentation page Simulink Engine Phases Mapped to System Object Methods: Let's look at those phases in more details with example.: Model Edit phase: This is where the object is created. Methods like getNumOutputsImpl and getNumInputsImpl need to be called for the Simulink editor to know the number of outputs and inputs of the block. Those methods are optional, you need to implement them only if your block has more than one input port and one output port. Here is an example System object with two inputs and three outputs: Model Compile phase: When simulating a model, before the simulation can start, Simulink needs to determine the dimensions and other properties of all signals. For the properties of its input ports, the MATLAB system block inherits them from the blocks connected to it. For the output ports, the Simulink engine can try to infer them from the input ports, or call the propagation methods of your System object. These methods are inherited from the base class matlab.system.mixin.Propagates and required when the output specifications cannot be inferred directly from the inputs. Even when output specifications can be inferred, adding the Propagation methods can improve the compilation time of your model since the time spent on inferring this data is saved. Here is an example where the output has a dimension of five: Model Execution phase: Once the model initialization is completed, the algorithm in stepImpl is called at every step. If the block contains states, I recommend separating the stepImpl into two functions: outputImpl where you compute the values of output signals, and updateImpl where you update the values of states internal to the block. Those two methods are provided by matlab.system.mixin.Nondirect class. Here is an example implementing an accumulator, using outputImpl and updateImpl Now it's your turn Have you tried the MATLAB System block? Let us know what you think of the MATLAB System block by leaving a comment here. ## October 16th, 2013 ## slLinearizer: Batch Linearization of Simulink Models This week I am happy to welcome guest bloggers Charu Fadnavis and Erman Korkut to introduce the new slLinearizer interface from Simulink Control Design. linearize vs. slLinearizer If you have used Simulink Control Design in the past, the first thing you might wonder is: Why a new interface to linearize Simulink models? If you compare the linearize function with the slLinearizer interface, you will realize that many linear analysis tasks can be accomplished by both. The main advantage of the slLinearizer interface is that it makes it easier to obtain multiple transfer functions without recompiling the model, also known as Batch Linearization. To get more details on the differences between those two approaches, we recommend going through the documentation page Choosing Batch Linearization Tools. The slLinearizer Interface Let's go through a simple example illustrating the basic of the slLinearizer Interface. For that, we will use a very simple model: The first step is to create a slLinearizer object for your model. Once the object is created, you want to add analysis points. One important difference when compared to the linearize workflow is that with the slLinearizer interface, the points that you specify are much more flexible. When adding points, you do not need to specify if they are input, output, open or closed loop, etc. To add points, you can use block name and port number, or signal names. For this example, let's add multiple points. We can now use any of the four get* methods to obtain transfer functions for the different points and loop openings: getIOTransfer, getLoopTransfer, getSensitivity, getCompSensitivity. For example, if I want to get the transfer function between the reference r and the output y: I use getIOTransfer: If I want the sensitivity at the control signal u: I use getSensitivity The important thing to note, is that the model will be compiled only the first time one of the get* method is called. Batch linearization In addition to linearizing for multiple analysis points and loop opening without recompiling the model, the slLinearizer interface makes it easy to obtain multiple linearizations for a set of operating points or parameter values. For the example above, let's say we want to obtain a series of transfer functions for different values of controller gain k, all you have to do is: and you obtain an array of transfer functions: If what you need to study is linearization at multiple operating points, it can also be done with the slLinearizer interface. For a detailed example of this workflow, see Vary Operating Points and Obtain Multiple Transfer Functions Using slLinearizer. Now It's Your Turn Check out the documentation for slLinearizer and try linearizing your model with it. We'd love to hear your thoughts! ## October 10th, 2013 ## From Symbolic to Simulink I am recently visited the MathWorks Japan office and learned about interesting work done by my colleague Hitoshi Takeshita. In his MATLAB Central submission Euler–Lagrange equation, Hitoshi shows how the Symbolic Math Toolbox can be used to easily obtain the equations of motion of a system by simply defining the energies involved. Once the equations of motion are obtained, he then uses the code generation capability of the Symbolic Math Toolbox to create a Simscape component and simulate the system in Simulink. I had never used this workflow before, but it can be very useful in applications like plant modeling and for engineering students learning systems dynamics. Let's look at an example using a double mass-spring system: Modeling a dynamic system in MuPAD MuPAD is the engine of the Symbolic Math Toolbox. If you never used it, I recommend going through the Getting Started section of the documentation, or read some of the posts in the Symbolic category of Loren's blog. In the MuPAD Notebook provided by Hitoshi, all you need to do is define the kinetic energy, potential energy and dissipation function: The rest of the notebook implements the Euler Lagrange equation: So all you need to do is evaluate the notebook: and you should obtain the equations of motion of the system: From MuPAD to Simulink Now that we have the equations of motion of the system, we want to bring them into Simulink. For that, we use the Simscape language. In the MuPAD notebook, it is possible to generate Simscape equations using the generate function: We can then copy and paste this code in the equations section of a Simscape file. We let you write the rest of the Simscape so you can integrate the equations the way you want. In my case, I created a component with two ports, keeping the motion of the middle mass internal to my component. I also modified the names of a few variables auto-generated by MuPAD: I can then execute ssc_build on this file and obtain a block that I can use in Simulink: Using the Simscape Simulation Results Explorer I can see that the two masses are moving as expected. Now it's your turn Using this method for a simple system like this one is probably not the most efficient way to quickly get a working simulation. However, I think this method can be very interesting for plant modelers analyzing complex systems and for engineering students trying to get familiar with Lagrange mechanics and equations of motion. Do you need to combine symbolic manipulations and Simulink? Is the approach highlighted here relevant for your applications? Let us know what you think by leaving a comment here. ## October 1st, 2013 ## 2013 Simulink Student Challenge – Win up to$1000!

• Have you done something super-cool in Simulink?
• Can you make a short video of it and share it on YouTube?
• Are you a student?
If you have answered yes to these questions, then you might be able to win your share of \$1000!

MathWorks announces the 2013 Simulink Student Challenge! I am looking for students to share videos about the cool stuff they are doing with Simulink. To enter all you need to do is create an original video, upload it to YouTube and tag it with Simulink2013

Check out the Simulink Student Challenge site for all the details. Submit your entry by December 10, 2013. Winners will be announced on January 6, 2014.

Need some inspiration?

What can you do with Simulink?

## The MATLAB System Block

In R2013b, you will notice a new block in the Simulink Library Browser: The MATLAB System block.

System Object

Before looking at the MATLAB System block, let's looks at the evolution of System objects.

In R2010a, System objects were introduced in the Signal Processing Blockset. In contrast to MATLAB functions, System objects are object-oriented implementations of algorithms that can automatically manage state information, data indexing, and buffering, which is particularly useful in digital signal processing.

In R2011a, System toolboxes were introduced. Built on System objects, those toolboxes give you the possibility to design (in MATLAB or Simulink) signal processing algorithms suitable for fast simulation, real-time prototyping, and embedded implementation.

Starting in R2011b, users can create custom System objects in MATLAB. To include those System objects in Simulink, the MATLAB Function block could be used, but it required some tricks (as shown in this post).

In R2013b the MATLAB System block makes it very easy to use custom System objects in Simulink.

A Simple Example

To illustrate the concept of using a System object in MATLAB and Simulink, I made a timesTwo System object based on the AddOne example included the documentation.

For that, all I need is to create a new class file, which inherits from the matlab.System class. Then I put the equations for my block in the stepImpl method:

I can use this System object in MATLAB with just two lines of code:

In Simulink, it is as simple a dragging the block, and specifying the name of the object:

Why do we need a MATLAB System block?

The previous example is too simple to highlight the power of the MATLAB System block. With System objects, you will find a large number of methods to setup the properties of states, output signals and input signals. You will even find methods to manage the MATLAB System block icon and dialog.

In the next weeks, I will follow up with a series of posts on the MATLAB System block to highlight more of its capabilities. For today, I will leave you with an example of a unit delay. When using the code below in the MATLAB System block, the input is marked as non-directfeedthrough. This makes it possible to use this block in loop without creating an algebraic loop.