> For the complete documentation index, see [llms.txt](https://cctang.gitbook.io/softwarecrafting/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cctang.gitbook.io/softwarecrafting/seminars/2017-mathworks-advisory-board/day2.md).

# Day 2: Model-Based Design with Simulink: Modeling and Simulation

## Model-Based Design Keynote - Andy Grace

* Technology Trends
  * Mechanization of Everything
  * High-speed Wireless Everything
  * Autonomous Systems in the Age of Aritificial Intelligence
    * "AI can bring on a second industrial revolution" - Kevin Kelly, Wired Magazine
    * Deep Learning and Compute Power improvements are driving innovation in AI
* Leads to:
  * Simulation as an imperative
  * High levels of abstraction necessary
  * Rigorous processes for safety and security
* Model-Based Design
  * Systematic use of models *throughout* the development process
  * Scope: Electronic systems that interact with the *physical* world
  * Three major areas
    * Modeling & Simulation
      * Software components
        * High-level abstraction with Simulink, Stateflow, & MATLAB
      * Physical components
        * Provide a suite of tools that allow working at multiple levels of fidelity
      * Physical systems
        * One integrated simulation platform that support multiple tools, formalisms, and versions
      * Software systems
        * System architecture was the most requested breakout from last year's MAB survey
          * System composition
            * Interfaces
            * Variants
            * Run-time effects
            * Scheduling
        * Modeling requirements
          * Simulink Requirements (R2017b)
        * Goal: Top-down and bottom-up system design linked together into one workflow
      * Performance: Parallel Simulations (R2017a)
    * Code Generation
      * Ease of use
        * Reduced bus wiring (R2017a)
      * Unbeatable code efficiency
      * Automatic fixed point conversion
      * Goal: Support extensive hardware targets from student targets to the highest performing rapid prototyping systems
      * Vision: Efficient code that easily plugs into any software environment
    * Test & Verification
      * V\&V will be separated into three products (R2017b)
        * Simulink Requirements
        * Simulink Coverage
        * Simulink Check
      * Vision: Automate steps and provide assurance for designs
  * Deep Solutions
    * Wireless
      * Providing more communication standards
    * Autonomous Systems Technologies
      * Localization
      * Planning
      * Controls
      * Perception

## From Components to Systems

## Design Patterns for Bottom-Up Component Modeling - Mani Ramamurthy

* Traditional workflow bottom-up model-based design
* A recent trend toward emergence of the software framework
* Areas of need
  * Modeling abstractions for embedded frameworks
  * Modeling abstractions for communication middlewares
  * Modularity, reuse, portability
    * Continuous-integration
    * Agile development
* Mission: Enhance model-based design for component frameworks
* *Design Patterns*, Erich Gamma, Richard Helm
  * Maximizing reuse
    * Define components
    * Parameterize design
    * Parameterize structure
  * Effect interfaces
    * Rich interfaces
    * Interface management
      * Interface Objects
      * Use concepts such as ICDs
  * Partitioning and Scheduling
    * Behavior design patterns
      * Design Partitioning
        * Scheduling Editor
      * Composing
      * Simulating timing
        * Run-time environment modeling

### Maximizing Reuse - Mike Tocci

* Units of reuse
  * Libraries
    * Foundation for graphical reuse in Simulink
    * Dynamic Interface
    * Support for code reuse as an optimization
    * ideal for Simscape components
    * Libaries support Test Harnesses (R2016b)
  * Model References
    * Interface is locked
      * Incremental code generation
        * Only rebuild if changes are being made
    * Encapsulate design data
  * Simulink Variants
    * Structural Parameterization
    * Variant propagation (R2016b)
* How to start
  * Build a utility
  * Put utility into a library subsystem
* What is a componenent in Simulink
  * 1000s of blocks
  * Generate C/C++ code
  * Supports composition
* Design Data
  * Keep data definitions and usage as close as possible
  * Use Model Workspace for all local data
  * Scope global data using Data Dictionaries
  * Model Data Editor (R2016b)
  * Model Mask (R2017a)

### Effective Interfaces - Alphan Ulusoy

* Signal interfaces
  * Ports are not aligned between components
    * Often buses are used as a workaround
    * New highlight > create bus shortcut (R2017a)
    * Separation of interface from implementation (R2017a)
      * Called Bus Element blocks
      * Looks a lot like from/goto pattern
      * Accessible from bus creator hover-over options
* Function Interfaces
  * Multi-instance shared resources (R2017b)
    * Example of watchdog using a datastore and the startup pattern
* Function Ports for Composition
  * Client/Server pattern
    * Both use the same data dictionary

### Modeling Software Services - Nirmal Gunaseelan

* Driver Services (R2017b)
  * Example: NVM driver software
  * Uses software interface
  * Black-box approach: S-functions
  * White-box driver services is new feature
* Middle services in the software framework
  * Modeled with global Simulink functions
  * Visualization is available
  * Reference implementation for AutoSAR (R2017b)

### Partitioning and Scheduling - Alongkrit Chutinan

* Software integration problem
  * Multiple software components
  * Integrate components into top-level application
* Typical workflow
  * Create components
  * Reference components in top level
  * Buildin simulation environment around components
  * Generate code from individual component model
  * Collect entry point for functions for each component
  * OS has pre-defined entry point functions (partitions)
    * Integrate code into OS
  * Model styles
    * Export function model
      * The scheduling pattern
    * Rate-based model
      * Algebraic loops are
* Scheduling pattern with rate-based models (R2017b)
* Using scheduling pattern to simulate startup/shutdown
  * Available to export function models (R2016b)
  * Extended to rate-based models (R2017b)

### Automatic Partitioning for Multicore Execution - Katalin Popovici

### Scheduling Editor - Andrew Calcutt

### Advanced Run-Time Environment Modeling - Senthil Manickavasagam

### Complementary Patterns Using Stateflow (Enabing Effective Designs with Stateflow) - David Andrade

* Enabling patterns
  * Scheduling
  * Mode switching
    * Debouncing using a stateflow keyword called duration (R2017a)
  * State logic
    * MATLAB
      * Directly in the state, or in a function
    * Child stateflow charts
      * Atomic subcharts are available
      * Port mapping dialog (R2015a)
    * Simulink subsystems within Stateflow (R2017b)
      * Can initialize state within a SL subsystem before it's enabled

## Top-Down System Engineering

### Framework for Modeling System Architecture - Devdatt Lad

* Vision
  * Seamless model-based workflow all the way from high-level system architecture to detailed implemention
  * Model-based system engineering
* System structure
  * New canvas tool
    * Implementation agnostic pipes and connectors
      * Can specify as design progresses
    * Validate requirements
      * Parameterize
      * Evaluate feasible alternatives
      * Select optimal architecture
  * Architecture Tool speaks MATLAB
    * Plug in analysis algorithms into the diagram properties
  * Profiles
    * Allows customization of architecture semantics to the tool
* Behaviors
  * Capture operation scenarios as sequence diagrams
  * Capture function requirements as activity diagrams
  * Capture component behavior as state charts
* Possible to start with existing Simmulink models
  * Interface Connectivity View
    * Impact analysis
  * Deployment View
  * Software Architecture View
  * Custom-defined Views
* Boot-strapped implementation as you move from architecture to implementation

### Towards Software Architectures - Tunc Simsek

* Bring together bottom-up and top-down design
* Explict control over software interfaces and implementation (R2017b)
  * Control how data is shared
  * Control how functions are scoped
  * Hide implementaiton details through graphical encapsulation
* Simulate asynchronous messages and functions
  * Scheduability analysis of software architecture
* Continuous integration with software architecutre modeling

## Scaling Up Model-Based Design - Rob Aberg

* Size and Scope:
  * Past: 1 - 2 code generation targets in one model
* Simulink caches (R2017a)
* Simulink parsim (R2017a)
* Simulink is being enhanced to be a full integration platform

### Simulation Integration Platform - Haihua Feng

* Flexible, reliable, and scalable multi-platform integration
* Challenges
  * Interfaces available
    * Today: 100+ connection partner tools provide co-sim gateways to Simulink
    * Today: S-function
    * FMI Support Update
      * Functional Mockup Interface
        * FMI Import into Simulink
          * Available for download (R2017a)
          * Ships with Simulink (R2017b)
  * Numberical issues across co-simulation boundaries

### Large Model Performance: Simulate It and It Simulates! - Fu Zhang

* Multi-domain workflow
  * Modeling > Configuration > Simulation > Analysis > Feedback
* New Modeling Capabilities (R2017b)
  * Improved algebraic constraint handling
* Solver Configuration Simplification
  * Simulink will automatically pick solver (R2016a)
    * Pick a solver at the beginning of the simulation
* Large Scale Model Execution
  * Large scale models are usually assembled from components
    * Model references with local solvers
    * Benefits of white box co-simulation
      * Better communication among components
      * Easier debugging with the same tools
* Analysis: Using Solver Profiler (R2016a)

### Simplified Block Authoring Workflows - Kaustubha Govind

* Why custom blocks?
  * Create a new algorithm that doesn't exist
  * Custom code/simulation
  * Co-simulation gateway
  * Host-specific code
  * Hardware-specific code
  * Standardization across teams
* Block authoring process
  * Choose block type
  * Implement algorithm
    * S-Function builder, for example
  * Customize interface
    * Mask editor
      * Build rich dialogs
        * New widgets
  * Add to library
* Goal
  * Streamline
  * Mistake-proof
  * Simplify
* S-function Quality and Robustness Checking (R2017b)

### Faster Simulations, Bigger Models

#### Working Effectively with Field Data - Alex Trubitsyn

* Field Data
  * Fleet
  * Track
* Improved usability of Dataset Object
  * Integration with variable editor (R2017a)
* Working with big data for simulations
  * Stream directly to disk
    * Constant run-time memory use
* Accessing simulation data on disk (R2016a)
  * Simulink.SimulationData.DatasetRef
    * Read-only reference to object on disk
    * Analysis in MATLAB
    * Pass to another simulation
  * SimulationDatastore (R2017a)
    * Read from disk, so size in memory is minimal

#### Massive Parallel Simulations - Rahul Kumar

* `SimulationInput` (R2017a)
* `parsim` (R2017a)
  * Without PCT/MDCS, simulations run sequentially
  * Automatic management of build folders
  * Better error diagnostics
  * Progress display
* Monitoring multiple simulations with Simulation Manager (R2017b)

### Better Workflows for Bigger Teams - Gavin Walker

* Simulink Project increases your agility to try new workflows
  * Provides environment
    * Locations for generated files ("slprj") (R2017b)
* Tight integration with source control
  * Simulink Comparison & Merge tool has a new UI (R2017b)
* New workflows built on top of Simulink Project

## Editors and Visualization - Jay Torgerson

* Vision
  * Create the world's greatest graphical modeling experience
    * Most
      * epxressive
      * intuitive
      * powerful
      * extensible
      * fast
* Theme: Model-centered design
  * Dashboar blocks
  * Property inspector dock in canvas
    * TODO: Investigate this
  * Symbol viewer in Stateflow (R2016b)
  * Model data editor (R2015a)
  * Simulink Finder
* Handling complexity
  * Perspectives
    * Interface
    * Test harnesses
      * Unit test subsystems
      * TODO: Investigate this
    * Requirements (R2017b)

### Visualizing Simulation Results - George Quievryn

* Simulink Instrumentation
  * Data
    * Visualize, Analyze, Manage, Debug, Test, and Understand
    * Unified logging, spectograms, new comparisons (R2017a)
    * Stateflow streaming, triggers, more spectral views (R2017b)
  * Verifying model changes
    * Compare simulation results between runs
    * Compare results in simulation and hardware
  * Simulation dashboards
    * Shipped in R2015a

### Managing Model Dashboards - Rich Conlan

* Flight instruments (R2016a)
* Enhanced capabilities

### Annotating and Documenting Models - Simon Greenwold

* Types of annotation
  * Presentation
    * Emphasis on expressiveness
      * TODO: Investigate
  * Documentation
    * Contextual documentation
  * Commentary

### Searching and Navigating Large Models - Atul Suri

* Signal tracing navigation using arrow keys (R2017b)
* Search runs in the background (R2017b)

### Managing Model Data - Paul Jackson

* Model Data Editor (R2016b)
  * Logical organization of design/instrumentation/code properties
  * Spreadsheet within the canvas
  * Directly configure the codegen parameters of the outport
  * R2017b
    * Signal properties tab
    * Data Stores tab
    * States tab
    * Parameters tab
      * See referenced variables
    * Filter contents
    * Configure parameters in the model without variable in the base/model workspace
* Variable Navigation (R2015b)
  * Discoverable (R2017a)
* Restore Missing Variables (R2017b)

### Editing at the Speed of Thought - Dennis Wilkinson

* Smart editing
  * Keep you focused on your model
  * Bring the tools to you
  * Eliminate the busy work
  * Edit as fast as you can think
* Recent advances
  * Default names are automatically hidden (R2017b)
  * Create subsystem (R2017b)
    * Pick up signal names automatically when creating a subsystem
  * Format painter (R2017a)
    * Pop-up menu
  * Quick Insert Refinements (R2017a)
    * Single type and insert will still work
    * Double click and insert
      * Automatically differentiates between annotations and block search insert
    * Automatic port creating by dragging signal to a block
      * Automatic port naming with signal name
    * Suggested blocks in Stateflow when transitions are drawn
    * Stateflow automatically inserts keywords in actions, if forgotten (eg, entry)
    * Stateflow > Chart > Arrange automatically
      * Automatically arranges the Stateflow canvas to be more readable
  * Line routing
    * Channel router (R2017a)
    * Channel routing with smart actions integration (R2017b)

## Breakout Sessions

### Speeding Up Simulation - Rajesh Pavan Sunkari

#### Massive Parallel SImulations - Rahul Kumar

* New workflow
  * Setup > Run > Monitor > Inspect
  * `parsim` command
    * Strealined design-centric workflow
    * Create a simulation input object
      * Unclear how to rearchitect test harnesses that utilize input files
        * Rahul says it can handle input files
    * One unified interface for running parallel simulations
    * No need to explicitly set up parpool
    * No set\_param calls needed
    * Run in background option (R2017b)
  * SimulationInput Object (R2017a)
    * Specify a numerical array, timeseries, or dataset object
    * PreSimFcn
    * TODO: Ask Bao to create example
  * External Inputs
    * `DatasetRef`
    * `createInputDataset`
  * `PreSimFcn`
    * Once per simulation
    * Performed on the worker
    * Use PreSimFcn to offload parameter value computations to parallel workers
  * `PostSimFcn`
    * Offload post-processing to parallel workers and reduce the data to be returned back from workers
  * Benefits of using `parsim`
    * Mistake-proofing your workflow
    * Avoiding transparency violations
      * Use 'TransferBaseWorksapceVariables'
    * Model dependencies
      * Automatically picks up model dependencies and sends them to the parallel workers
        * Only for MDCS clusers, workers on local pool always has access to the host files
    * Management of build artifacts
    * Managing logged files
      * `parsim` automatically brings back logged files
        * Logging to file or to To File blocks
        * Makes the file names unique by appending the 'run id' to the file name
    * Error diagnostics
      * Alerts whenever a simulation failed
      * Simulation metadata is returned
        * Execution time
        * Any errors that get generated
        * Status of simulation termination
  * Simulation Manager (R2017b)
    * Monitoring multiple simulations

#### Scheduling for Multicore - Andrew Calcutt

* Parallelize one model for one run across multiple cores
  * Specify the order of partitions

#### Solver Technology (Simulation Performance Improvement) - Fu Zhang

* Fu's team is focused on the continuous time solvers
* Solver Profiler (R2017b)
  * Simulink will identify list of candidates to address solver execptions
  * Command-line interface is available

### Polyspace

* Polyspace Improvement - Simplicity
  * Full support of compilers
  * Unified user interface
    * Single configuration
    * Simplified workflow to launch
    * Results grouped by product
  * Auto-detection of concurrency configuration primatives
    * Removed need for manual configuration
    * Speeds-up project configuration for multi-tasking applications
      * POSIX, VxWorks, C++-11
* Polyspace Improvement - Completeness
  * Code Prover
    * Easy customization and automation for launching Polyspace and accessing its results with MATLAB API (R2017a)
    * Improved in-source Annotation workflow (R2017b)
    * Launch Polyscapce on code generated from MATLAB Coder (R2017b - must request option to expose)
    * Polyspace results API in MATLAB (R2017a)
      * Results are in MATLAB Table format
    * Improved traceability back to Simulink model (R2017a)
      * Adds a new way to navigate from Polyspace to Simulink
    * Improved in-source annotations workflow (R2017b)
      * `/* polyspace MISRA-C:13.2 */`
        * By default, Polyspace will mark it as "Not a defect: Justified"
      * Old syntax is still supported for compatibility
    * Improve Floating Points support
      * Detect Integers in Floating Points (R2017a)
        * Benefits
          * Provide more information to Polyspace users
          * Reduce oranges
    * Stack size computation (R2017b)
      * Provide a metric of estimation of stack size for each function
        * Only available to Code Prover
  * Bug Finder
    * MISRA Checker
      * MISRA-C:2012 Support (R2015b)
        * Amendment 1 for security (R2017a)
    * Security Standards
      * Full support of ISO-17961
      * Improved support of CERT-C
      * Cybersecurity - Industry Activities & Standards
        * Coding standards & practices
          * CERT-C
          * ISO/IEC TS 17961 (R2017b)
          * CWE - Common Weakness Enumeration
          * MISRA-C:2012 Amendment 1
    * Checkers
      * Add new checkers and improve existing ones
        * Additional programming and security checks (R2017b)
      * Review of race conditions and deadlocks
        * Identifying conflicting Read/Write accessess (R2016b)
* Polyspace Improvement - More Performant
  * 50% Code Prover improvement from R2016a -> R2016b, no appreciable changes in R2017a and R2017b
  * Incremental analysis when integrated into Eclipse
    * Closing results will release the Polyspace license

### Getting Data In and Out of Simulink - Alex Truitsyn; Stacey Gage; David Boissy

* Creating and Connecting Model Inputs
  * Create input signals for Simulink model
    * Signal Editor (R2017a)
      * Create data through a tabular form
      * Command-line API (R2017b)
      * Usability Improvements (R2018a)
  * Connect external inputs to Simulink model
  * Dataset Signal Plot (R2016b)
    * Initial release of creatInputDataset (R2017a)
    * Support for Timetables in plot (R2017b)
    * Additional data type and format support (R2018a)
  * Root inport mapper (R2014b)
    * Data input/output > connect input
    * Right from the inport block parameters > connect input
    * TODO: Investigate
    * Hetergenous mapping modes in Root Inport Mapper (R2016b)
    * Strong data typing with spreadsheets in Root Inport Mapper (R2017a)
  * Command line mapping of inputs (R2013b)
    * `getRootInportMap`
* Timetable will be replacing timeseries
  * Logging in timetable format (R2017a)
    * Dataset element format
  * Load timetable format (R2017b)
* Simulation Output as Big Data (R2016a)
  * Stream to .mat file on disk
  * Won't run out of memory
* SimulationDatastore (R2017a)

## Followups

* Simulation artifact sharing - Rob Aberg
  * Build once, everyone else on the same architecture can utilize them
* Location of Simulink Project configuration folder - Gavin Walker
* Requirements Perspective on canvas - Jay Torgerson
* External documentation link or storage so it doesn't get appended to model file - Simon Greenwold
* TODO: Investigate logic analyzer block
