Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (2024)

Once you set up Jupyter Notebook, you can open and test sample projects created for server-side simulation using Jupyter. This chapter briefly describes the sample projects and explains how to execute them.

To access the sample projects

  1. Set up Jupyter Notebook if you have not already done so.
  2. Extract the <install_root>\plugins\com.nomagic.magicdraw.simulation\pyST.zip file. The sample projects are located in the samples directory.

Bouncing Ball sample

The Bouncing Ball sample project demonstrates server-side simulation with FMU. In addition, you can draw a chart based on the CSV data after the model execution.

Prerequisites

Add the Bouncing Ball sample project to the Teamwork Cloud server.


To run the Bouncing Ball sample and draw a chart based on the CSV data

  1. Run the Bouncing Ball project and get the CSV data.

    Request example for running the simulation

    result = client.simulate('BouncingBall", config='Run BouncingBall')csv = result['csvExports']['Bouncing Ball']
  2. Draw a chart based on the CSV data.

    Request example for drawing a chart based on the CSV data

    import numpy as npimport matplotlib.pyplot import figurefrom io import StringIOfigure(figsize=(16, 8), dpi=80x = np.loadtxt(StringIO(csv), dtype='double', delimiter=',', skiprows = 1, usecols = (0)) / 1000y = np.loadtxt(StringIO(csv), dtype='double', delimiter=',', skiprows = 1, usecols = (1))plt.xlabel('time (ms)')plt.ylabel('height')plt.title('Bouncing Ball', fontweight="bold", fontsize=20)plt.plot(x, y,)plt.grid()plt.show()

Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (1)

The Bouncing Ball chart drawn based on the CSV data.


Coffee Machine sample

The Coffee Machine sample project demonstrates server-side simulation with a specified HTML UI mockup. With this project, you can open the HTML UI window during model execution.

Prerequisites

  • Add the Coffee Machine sample project to the Teamwork Cloud server.
  • To open the HTML UI during server-side simulation, attach the HTML UI to the server project and commit the changes to the server.

To run the Coffee Machine sample and open the HTML UI window

  1. Run the Coffee Machine project.

    Request example for running the simulation

    client.run('CoffeeMachine', config='Coffee Machine Web'){'state': 'INITIALIZING', 'simulationId': '20a84d37-0aba-4e12-9f14-ca381a5952f4', 'project': 'CoffeeMachine', 'elapsedTime': 106}
  2. Check the simulation status.

    Request example for getting the simulation status

    client.get_status('20a84d37-0aba-4e12-9f14-ca381a5952f4'){'state': 'RUNNING', 'simulationId': '20a84d37-0aba-4e12-9f14-ca381a5952f4', 'simulationTime': '0 ms', 'ui': ['<server_address>/simulation/api/ui/20a84d37-0aba-4e12-9f14-ca381a5952f4/CoffeeMachine.html'], 'project': 'CoffeeMachine', 'config': 'Coffee Machine Web', 'elapsedTime': 72742}
  3. Click the UI URL in the response to the status request to open the HTML UI window.

Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (2)

The HTML UI window opened during the Coffee Machine project execution.


Spacecraft Mass Rollup sample

The Spacecraft Mass Rollup sample demonstrates server-side simulation with specified input and output parameters.

Prerequisites

Add the Spacecraft Mass Rollup sample project to the Teamwork Cloud server.

To run the Spacecraft Mass Rollup sample with input and output parameters

  1. Do one or both of the following:
    • Specify a set of input parameters with values to be provided for the simulation.
    • Specify a set of output parameters to be obtained after the simulation is complete. If no output parameters are specified, all initialized values are returned.

      Request example for running the simulation with input and output parameters

      parameters = { "inputs": { "propulsion.thruster.me":32 "telecom.amplifier.me":15 }, "outputs": [ "me", "propulsion.me", "propulsion.tank.me", "propulsion.thruster.me", "telecom.me", "telecom.antenna.me", "telecom.amplifier.me" ]}client.run('SpacecraftMassRollup', config='spacecraft mass analysis', data=json.dumps(parameters)){'state': 'INITIALIZING', 'simulationId': 'fc5fa7eb-761a-4d31-9201-2f51f1754675', 'project': 'SpacecraftMassRollup', 'elapsedTime': 187}
  2. Get the simulation results.

    Request example for getting simulation results

    client.get_result('fc5fa7eb-761a-4d31-9201-2f51f1754675'){'outputs': {'me': 104.0, 'telecom.me': 34.0, 'telecom.amplifier.me': 15.0, 'telecom.antenna.me': 19.0, 'propulsion.me': 70.0, 'propulsion.tank.me': 38.0 'propulsion.thruster.me': 32.0}, 'verification': [{'property': 'propulsion.thruster.me', 'status': 'fail', 'value': 32.0, 'requirements': [{'id': '1', 'text': 'Estimated mass shall be less than allocated mass', 'status': 'fail', 'timestamp': 0}], 'constraints': [{'constraint': 'me < ma', 'status': 'fail', 'timestamp': 0}]}, {'property': 'telecom.amplifier.me', 'status': 'fail', 'value': 15.0, 'requirements': [{'id': '1', 'text': 'Estimated mass shall be less than allocated mass', 'status': 'fail', 'timestamp': 0}], 'constraints': [{'constraint': 'me < ma', 'status': 'fail', 'timestamp': 0}]}]}


Car Braking Analysis sample

The Car Braking Analysis sample project demonstrates the server-side simulation that calculates stopping distance. You can use this project for the following scenarios:

  • Seeing the relationship between the vehicle mass and braking distance.
  • Calculating the stopping distance according to the car mass and speed.

Prerequisites

Add the Car Braking Analysis sample project to the Teamwork Cloud server.

To run the Car Braking Analysis sample to see the relationship between the vehicle mass and braking distance

  1. Run the Car Braking Analysis project while changing the mass of the car, e.g., by 20 kg.

    Request example for running the simulation with a changed mass

    mass = [0] * 10distance = [0] * 10for x in range(0, 5): mass[x] = 800 + 20 * x parameters = { "inputs": { "grossMass": mass[x] } } results = client.simulate('CarBrakingAnalysis_final', config='Vehicle Analysis no Matlab', commit_results=False, data=json.dumps(parameters)) distance[x] = results['outputs']['stoppingDistance'] print(mass[x], distance[x] )
  2. Draw a chart of the relationship between the vehicle mass and braking distance.

    Request example for drawing the chart

    import numpty as npimport matplotlib.pyplot as pltfrom matplotlib.pyplot import figurefrom io import StringIOfigure(figsize=(16, 8), dpi=80)plt.xlabel('mass (kg)')plt.ylabel('stopping distance (m)')plt.title('The relationship between vehicle mass and braking distance', fontweight="bold", fontsize=20)plt.plot(mass, distance)plt.grid()plt.show()

Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (3)

The chart showing the relationship between the vehicle mass and stopping distance.

To run the Car Braking Analysis sample to calculate the stopping distance

  1. Run the Car Braking Analysis sample to calculate the stopping distance according to the specified car mass and speed.

    Request example for running the simulation to calculate the stopping distance

    speed = input("Enter the car speed (km/h):")totalMass = input("Enter the car mass (kg):")parameters = { "inputs": { "grossMass": totalMass, "speed": speed }}results = client.simulate('CarBakingAnalysis', config='Vehicle Analysis no Matlab', data=json.dumps(parameters))distance = results['outputs']["stoppingDistance"]requiredDistance = results['outputs']["requiredStoppingDistance"]print("Stopping distance:", distance)print("Failed requirements:")print(json.dumps(results['verification'], indent=2))
  2. Draw a chart to show the car stopping distance with the threshold of the required maximum stopping distance.

    Request example for drawing the chart

    import matplotlib.pyplot as pltimport matplotlib as mplimport numpy as npimport pandas as pddata = pd.DataFrame( {"distance": [distance]})ax = data.plot(kind='bar' figsize=(10,7), color=['dodgerblue'], fontsize=13);plt.axhline(y=requiredDistance, linewidth=3, linestyle='--', color='r')ax.set_ylim([0, distance+50])plt.title("car Braking Analysis Chart", fontsize=18, weight="bold")plt.ylabel("Metre (m)", fontsize=15)plt.text(0, distance+2, round(distance, 4), ha = 'center', fontsize=14)ax.get_legend().remove()plt.xticks(np.arange(1), ["Stopping distance"], rotation="horizontal", fontsize=15);

Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (4)

The chart showing the car stopping distance with the threshold of the required maximum stopping distance.

Hinge Monte Carlo Analysis sample

The Hinge Monte Carlo sample project demonstrates a server-side simulation that runs the Monte Carlo analysis. In addition, you can draw a histogram chart based on the CSV data after the model execution.

Prerequisite

Add the Hinge Monte Carlo Analysis sample project to the Teamwork Cloud server.

To run the Hinge Monte Carlo Analysis and draw a histogram based on CSV data

  1. Run the Hinge Monte Carlo Analysis and get the CSV data.

    Request example for running the simulation

    result = client.simulate('HingeMonteCarloAnalysis_Jupyter', config='Monte Carlo Analysis')csv = result['csvExports']['clearance']
  2. Draw a histogram based on the CSV data.

    Request example for drawing a histogram based on the CSV data

    import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.pyplot import figurefrom io import StringIOx = np.loadtxt(StringIO(csv), dtype='double', delimiter=',', skiprows = 1, usecols = (0))numberOfBins = 30figure(figsize=(16, 8), dpi=80)plt.hist(x, bins = numberOfBins)plt.xlabel('hinge.clearance')plt.ylabel('Frequency')plt.title('Hinge Clearance Histogram', fontweight="bold", fontsize=20)plt.xticks(np.arange(min(x), max(x), 0.5))plt.grid()plt.show()

Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (5)

TheHinge Clearance Histogram drawn based on the CSV data.

Cruise Control Widgets sample

The Cruise Control Widgets sample project demonstrates server-side simulation with a specified HTML UI mockup that includes widgets. With this project, you can open the HTML UI window during model execution.

Prerequisite

  • Add the Cruise Control Widgets sample project to the Teamwork Cloud server.
  • To open the HTML UI during server-side simulation, attach the HTML UI to the server project and commit the changes to the server.

To run the Cruise Control Widgets project and get the status of the specified simulation

  1. Run the Cruise Control Widgets project.

    Request example for running the simulation

    result = client.run('CruiseControl_Widgets', config='Cruise Control with Widgets')simID = result['simulationId']
  2. To get the status of the specified simulation.

    Request example for getting the status of the specified simulation

    client.get_status(simID){'state': 'RUNNING', 'simulationId': '160e822a-5c22-4758-9f1d-d72a83351559','simulationTime': '0 ms', 'ui': ['<server_address>/simulation/api/ui/160e822a-5c22-4758-9f1d-d72a83351559/SimulationWithWidgets.html'], 'project': 'CruiseControl_Widgets', 'config': 'Cruise Control with Widgets', 'elapsedTime': 1657}
Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (6)The HTML UI window opened during the Cruise Control Widgets project execution.
Sample projects for simulation with Jupyter Notebook - Magic Collaboration Studio 2024x Refresh1 (2024)
Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 6342

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.