FlexSim Knowledge Base
Announcements, articles, and guides to help you take your simulations to the next level.
Sort by:
Attached is a sample model that uses Google's OR-Tools python module to find optimal AGV dispatching solutions. I recently stumbled on Google's OR-Tools, which includes several classes for finding optimal solutions to things like vehicle routing, scheduling, bin packing, etc. Since FlexSim now has a mechanism for easy connection to python, I decided to try and see if/how it could be connected to FlexSim for testing AGV dispatching strategies. I threw together this model just to see how/if the connection can work. All source/destination locations are chosen at random, and work inter-arrival rates are random with a user-defined mean inter-arrival time. To get this model running on your side: Install a version of python Run the following from the command-line: python -m pip install ortools In FlexSim, make sure your preferences are configured for the correct version of python, and that python is part of your PATH environment variable. Open the model. In the Parameters table, set DispatchMode to 'VRP Solver'. This model uses the Vehicle Routing Problem solver to find optimal AGV assignment strategies. The main work generation logic is in the 'Work Generation' process flow. At random intervals, work requests arrive. They are assigned to random source and destination locations. Then, when dispatching in 'VRP Solver' mode, the logic calls the optimizeVRP() user command. This command packages the current state of the model into a valid vehicle routing problem, and then passes it to the py_optimizeVRP() user command, which is implemented in python, in the AGVVRP.py file. The command creates the VRP problem using the OR-Tools classes, and then calls the solver, returning the results. OptimizeVRP() then interprets the results and assigns AGVs as needed. Note that the VRP is re-solved every time new work arrives. You'll see little 'freezes' in the execution of the model, because it is solving the VRP at each work arrival. Note that the standard Vehicle Routing Problem is slightly different from the problem this model needs optimized: In an AGV model, there’s no depot. Instead AGVs may be currently located anywhere in the warehouse. There’s no ‘depot-loaded’ capacity of an AGV, and no ‘demand’ at customers. The standard VRP is a situation where trucks are loaded at the depot, and then depleted as they visit each customer in the route. This is not present with single-capacity AGVs. When an AGV picks up at an origin location, it must immediately deliver to the destination location. In order to wrangle the AGV problem into a valid vehicle routing problem that can be solved by OR-Tools, I constructed the problem as follows: I made each AGV’s ‘current location’ a node in the graph The distance from the depot to the AGV’s current location is 0 The distance from the depot to any other node in the graph is prohibitively large. This will cause vehicles to always go to their 'current location' first, with 0 cost. The distance from any node in the graph back to the depot is 0 A given AGV must visit its current location as part of its route. This can be added as a constraint to the problem in OR-Tools For immediate unload after loading, I initially tried adding this rule as a constraint, but the solver hung when solving. So, instead of graph nodes being locations in the facility, I made graph nodes represent ‘tasks’, i.e. visiting this node means picking up the item AND dropping it off. As such, the ‘cost’ of ‘visiting’ a ‘task’ node is the cost to travel from the ‘destination’ of the previous node to the ‘origin’ of this ‘task’ node, plus the cost to travel from the ‘origin’ of this task node to the destination of this ‘task’ node. Once I did this, OR-Tools was able to solve the problem 'optimally'. By optimally, I mean it was finding the AGV routing that minimized the maximum 'travel makespan', which is the maximum distance route of all of the AGVs. Once I had done this, I wanted to compared it with various heuristic-based scenarios. So I set up a 'Closest' dispatch mode. Here, when an AGV finishes a task, it will take up the next task whose pickup point is closest to its current position. I also created a 'FIFO' dispatching mode, which is that work will be dispatched to AGVs always in FIFO order. These three dispatching modes I compared with the experimenter. My initial experiments showed some interesting results. Most interesting was that in 'VRP Solver' mode, work task time-in-system was relatively high. This is because the objective function completely ignored time in system of the work, and was only optimizing for vehicle travel distance. So some work was being pushed off until much later because vehicles could get better travel distances by pushing it off. To account for this, I added a 'soft upper bound', which is kind of like a 'due date' for the work. Namely, work is due to be finished 800 'meters-of-agv-travel' after it arrives. This was a quick-and-dirty workaround and could certainly be improved, but it did serve to get the time in system for VRP Solver mode down. Below are some of the resulting experimenter results. AGVTaskTime - Time from starting a task to finishing it (i.e. a kind of takt time) The VRP solver performed the best across all scenarios here, and was especially better than the other strategies in low-demand scenarios. This intuitively makes sense. When there are a lot of under-utilized AGVs, the closest and FIFO strategies will always dispatch idle AGVs to do work, which could potentially make them travel long distances. However, the VRP solver can find opportunities to decrease travel distance by waiting to dispatch an AGV that will be near a task in the future, and leave other AGVs idle. Note that I think the 'closest' strategy only finds the 'closest' next task for an AGV that just finished a task, not the 'closest' idle AGV for an arriving task. Obviously that could be changed for a better performing 'closest' strategy. On the other hand, I think in this model all idle AGVs go back to the same park location, so such a change would require distributed park locations to take advantage of closer idle AGVs. AGVWorkStaytime - time-in-system for a given AGV task Here the 'closest' strategy actually performed better than the VRP. This would seem counter-intuitive at first, but upon further evaluation, it does make sense. The VRP, in its current form, only optimizes for total AGV travel distance. It completely ignores job time in system/due dates/etc. So the solver will always assign a route that is shorter even if that route pushes back jobs that have been in the queue for a long time. The solver also re-solves every time a new job arrives. So we may be having scenarios where some jobs are always 'better' to be pushed to the end of the route, and so they keep getting pushed back, resulting in poor time-in-system performance. The solver does include soft and hard job 'due dates', so we could make adjustments to the problem to make the VRP get better time-in-system results. AvgAGVUtilization AvgAGVUtilization is where the VRP especially shines in low-demand scenarios. It finds opportunities to leave AGVs parked because there will be opportunities for busy AGVs to take up jobs in the future with minimal extra travel overhead, whereas the 'FIFO' and 'Closest' strategies will always dispatch idle AGVs to unassigned jobs, causing extra unnecessary empty travel. I am still a bit perplexed by the high-demand scenarios though. Here the 'Closest' and 'FIFO' strategies both beat the VRP in the 120/hr and 102/hr scenarios. This probably would warrant further investigation as to why the other strategies do better here. It may be that, in these scenarios, the AGVs cannot keep up with demand. So there is a queue of jobs that is ever-increasing. The VRP solver is optimizing the full plan, meaning it is scheduling job assignments, and finding travel distance minimization opportunities, that are way out into the future. And it is not getting the opportunity to execute those optimized routes because the problem is being re-solved at each job arrival. With an increasing job queue, the 'closest' and 'fifo' strategies might be actually doing better specifically because they are short-sighted. Just take the closest job to you. On the other hand, if we have increasing job queues (i.e. the AGVs can't keep up), then the AGV utilization should be around 100% anyway, which it's not. Anyway, it's something still to churn on. ThroughputPerHour The throughput per hour indicator tells us whether the AGVs actually kept up with the jobs. If the AGVs were able to keep up with jobs, then the resulting means should be right around the scenario's throughput/hr number. It looks like FIFO got way behind on both the 120/hr and 102/hr scenarios. 'Closest' and VRP both got a little behind in the 120/hr scenarios. One exciting possibility of using this design is that the python script is not technically dependent on FlexSim. So you can use FlexSim to test your python-based optimization, and then you can deploy that python script in a live setting. AGVVehicleRoutingProblem.zip
View full article
This model is a proof-of-concept example for combining FlexSim's GIS features with the power of mixed integer programming in python. The model simulates a distribution network of 'factories' (red icons) and 'warehouses' (blue icons). The factories produce the product you are selling, and then distribute the product to various warehouses in the network. Every day, each warehouse generates a random demand for the product. Once demand from each warehouse is known, the 'demand dispatcher' must determine which factory should produce and ship how much of the product to each warehouse, fulfilling all warehouses' demands at minimum total cost. Each factory has a maximum daily capacity of production and a per-unit cost of production. In addition, shipping costs must be taken into account from each factory to each warehouse. Given these factors and constraints, the problem of optimal dispatching boils down to the well-known min cost flow problem in optimization. I've created a simple python script that uses cvxpy to solve this min cost flow problem as a mixed integer program. The MIP is not exactly the same as the standard min cost flow problem, since total factory capacity may be more than total warehouse demand, and I'm using integer instead of continuous variables. Nevertheless, it is sufficient to demonstrate the capability. The Warehouse process flow generates daily demand for each warehouse and pushes it to a shared Demand list. The DemandDispatcher then pulls demand from the list, and marshals capacity, demand, and cost data into parameters that can be passed to python. Then it evaluates getMinCostFlow label on the process flow, passing those parameters in. The label is configured to connect to the getMinCostFlow function defined in the MinCostFlow.py module. This function formulates the MIP with cvxpy, solves the program, and then returns the optimal shipping quantities for each factory-warehouse pair, returning control back to FlexSim. Once the shipping quantities have been resolved, the DemandDispatcher process flow creates and labels 'Trucks' that are sent to each warehouse. Note that this travel mechanism is purely for animation purposes, letting you visualize how much product is being sent from factories to warehouses each day. Potential additions to this model could use inventory management strategies, simulating randomized lead times, etc. I've added several dashboards that show the cumulative average breakout for each warehouse of which factories supply that warehouse, as well as the cumulative average breakout for each factory of which warehouses that factory supplies. I've also added costing measures for the warehouses and factories. Some interesting insights that can be gleaned from this model are how shipping vs. production costs affect the balance of which factories will ship to which warehouses. For example, if your shipping costs are low relative to your production costs, then the min cost flow algorithm will push production to factories that are the lowest cost to produce, even if they are far away from the destination warehouse. High production cost factories are consequently relegated to little if any production. However, if shipping costs are high, the algorithm will localize production to the factories nearest their respective warehouses. In order to run this model, you need python properly configured, including: Install one of these python versions: 3.7, 3.8, 3.9, 3.10 Install the cvxpy and cvxopt packages: python -m pip install cvxpy cvxopt Make sure the python directory is part of your PATH environment variable Configure your Global Preferences (the Code tab) to use the associated python version. This model was built in FlexSim 22.1. MinCostFlow.zip
View full article
This model is a proof-of-concept example demonstrating the integration of FlexSim with Python's Pyomo package to solve the Knapsack Problem. The model simulates a loading process of a logistic company. The truck has a weight capacity of 200 kg. The scenario includes 15 products, each with a specific weight and value. The product details are as follows: The objective is to determine which products to load onto the truck to maximize the total value of goods while ensuring the total weight does not exceed 200 kg. The ProductCreation Process Flow creates the products in a Queue. The General Process Flow has a Custom Code that creates a couple of Maps to store the products weights and values. It sets the capacity variable from the Parameters Table. These three parameters can be passed to python. Then it evaluates KnapsackProblem label on the Process Flow, passing those parameters in. The label is configured to connect to the KnapsackProblem function defined in the KnapsackProblem.py module. This function formulates the Knapsack Problem with Pyomo, solves the program, and then returns the optimal collection of products to be load onto the truck. Since the Decision Variables are binary, once the products are resolved, the values are stored in a Global Table, where 1 means that the product was selected. A Combiner uses this table to set the Component List. A forklift load the products and once completed, the truck leaves. When it enters the Sink a message is displayed showing the total weight and value loaded. Model Parameters There are two parameters that can be changed in this model. One is the Truck Capacity, which is the constraint of this problem. The value ranges from 100 to 300. There are three Global Tables in this model that store a different set of Weights and Values for each products. The table selected for the problem can also be changed using the GUI. Potential additions to this model could use priority for the products or include multiple trucks or constraints such as volume. Requirements to run the model In order to run this model, you need python properly configured, including: Install one of these python versions: 3.9, 3.10, 3.11 Install pyomo and highspy packages: python -m pip install pyomo highspy Make sure the python directory is part of your PATH environment variable. Configure your Global Preferences (the Code tab) to use the associated python version. This model was built in FlexSim 24.0 Knapsack_Problem.zip Troubleshooting If you are getting this error: exception: Code Binding Error: could not bind to function Node: /Tools/ProcessFlow/ProcessFlow>labels/KnapsackProblem Binding string: /**external python: */ /**/"KnapsackProblem"/**/ /** \nfunction name:*/ /**/"KnapsackProblem"/**/ Windows Error Code : 126 Check this post
View full article
MQTT is a communication protocol designed for IoT devices. Clients (the devices) connect to a Broker which allows them to publish (send) and subscribe (receive) messages. Each message is associated with a Topic. Each client can choose which topics to use for publishing and subscribing. Usually, the MQTT broker discards messages once they are sent to all subscribers. However, a publisher can mark a message as "retained." This means the broker will keep the last message for that topic and make it available to other subscribers. Only the most recent message is retained. When developing a digital twin, you may need to access these retained messages. This article describes how to do that using FlexSim's Python connection. This article is not meant as a comprehensive guide, but as a starting point, which you certainly will modify for your circumstances. Here are the python scripts and FlexSim model used in this example: MQTT.zip A quick note: since MQTT is a device communication protocol, support for MQTT in the Emulation module is in progress. This article describes how to import data from an MQTT broker like any other file/database/http server, rather than connecting for Emulation purposes. Step 1: Gaining Access to an MQTT Broker Your facility may already have an MQTT Broker running. In the end, your digital twin will need to connect to that broker to retrieve the latest retained messages. However, for testing, or if you don't have an MQTT Broker yet, you can easily get one. One possibility is to use Docker to run the EMQX Broker. However, there are dozens of brokers and installation steps You can download Docker Desktop here: https://www.docker.com/products/docker-desktop/ Once docker is running, you can use the following command in a terminal to download and run the EMQX Broker: docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8084:8084 -p 8883:8883 -p 18083:18083 emqx/emqx Note that this command runs a Linux container, so if Docker is in Windows mode, you'll need to switch before running this command. Step 2: Publishing Messages to an MQTT Broker A real facility will have many publishers and subscribers. However, for testing, it can be convenient to create publishers and subscribers that you control. Once your broker is running, you can use code like the following to create a publishing client: https://github.com/emqx/MQTT-Client-Examples/blob/master/mqtt-client-Python3/pub_sub_tcp.py For this example, I created two clients that publish tabular data: one that publishes a set of "raw materials" available for use in the process, and another that publishes a set of "finished goods" available to fulfill orders. To create some data, run the finished_goods_client.py and raw_materials_client.py files for a few seconds each. Note that both of these clients mark the messages to be retained, so FlexSim can access the latest message, even if neither client is actively running. Step 3: Writing a Python Script to Retrieve Messages This approach is demonstrated in fs_client.py, shown here: import paho.mqtt.subscribe as subscribe import json def get_retained_msgs(topics): auth = { 'username': 'emqx', 'password': 'public', } msgs = subscribe.simple( topics, qos=0, msg_count=len(topics), retained=True, hostname="localhost", port=1883, client_id=None, auth=auth, keepalive=5) if type(msgs) == list: return [json.loads(m.payload) for m in msgs] else: return [json.loads(msgs.payload)] if __name__ == "__main__": topics = ["python-mqtt/raw-materials", "python-mqtt/finished-goods"] print(get_retained_msgs(topics)) Run this script to verify that it returns the latest data from the two publishers. When FlexSim calls this function, FlexSim can convert python Lists and Dictionaries into FlexSim Arrays and Maps. So you can return complex data structures directly to FlexSim. Step 4: Writing a User Command to Call the Python Command In FlexSim, create a new user command, and edit the code. Be sure to toggle the node for external use, and set it to the following: /**external python: */ /**/"fs_client"/**/ /** \nfunction name:*/ /**/"get_retained_msgs"/**/ To use Python like this, you need python installed on the path. You also need the paho-mqtt package installed globally. Finally, you need to verify that your global preferences indicate the correct version of Python. For more information on connecting to python functions, see FlexSim's documentation: https://docs.flexsim.com/en/23.2/Reference/DeveloperAdvancedUser/ConnectingToExternalCode/ConnectingToExternalCode.html Step 5: Writing a User Command to Write Messages to Global Tables In this example, the messages we are interested in store tabular data, so it makes sense to store the data in Global Tables: Array tables = ; Array topics = ["python-mqtt/raw-materials", "python-mqtt/finished-goods" Array msgs = getRetainedMessages(topics); for (int m = 1; m <= msgs.length; m++) { Table fsTable = tables[m // header code elided; see example Array msgData = msgs .data; Table msgTable = Table(msgData); msgTable.cloneTo(fsTable); // header code elided; see example } If you run this new user command, you can see the latest data pulled in to FlexSim. Conclusion This example shows just one way you could import data from an MQTT broker into FlexSim. In addition, the kind of data you import or what you do with that data is up to you as the user.
View full article
Sometimes data exists in Google Sheets that needs to be brought in to FlexSim. There are multiple ways to do this, discussed in this article. Copy and Paste This is the easiest method to get data from Google Sheets into FlexSim. Here's how it works: Open the desired sheet in your browser Click the top-left corner to select everything. Copy the data (use ctrl-C) Open FlexSim Create a Global Table if you haven't already Ensure the number of rows and columns in the Global Table is large enough to hold the pasted data. Click on the column header for the first row in the Global Table. Paste the data (use ctrl-V) Pros: Quick, easy Cons: Need to resize the global table correctly beforehand, repeat entire process if data changes. Export/Import via CSV This is also any easy method to get data. Here are the steps: Download your sheet as a csv file. In FlexSim, use the importtable() command to dump the csv into the global table. For example: importtable(Table("GlobalTable1"), "data.csv", 1) You could add this code to your model's OnReset trigger if desired. Pros: Quick, table sized to csv data automatically Cons: Repeat downloading csv if the data changes. Export/Import via XLSX You can also download a google spreadsheet as an Excel file. Then you can use the Excel importer as normal. Pros: Quick, table sized to data automatically, many options for configuring Cons: Repeat downloading xlsx file if the data changes Import via Python This method is more advanced and requires some configuration for the model and your Google account. Once complete, however, changes can be pulled in automatically without any manual steps. Follow the Sheets quickstart for python found here: https://developers.google.com/sheets/api/quickstart/python Following this guide walk you through creating a Google Cloud Project and creating credentials for that project. In addition, consider using this modified python file instead. This file creates a get_values method that the model can call, and that method is also called from main(), so it's easy to test in a python debugger: import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = "----- add your sheet's ID here -------------" SAMPLE_RANGE_NAME = "A1:B" def get_values(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists("token.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( "credentials.json", SCOPES ) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open("token.json", "w") as token: token.write(creds.to_json()) try: service = build("sheets", "v4", credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = ( sheet.values() .get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME, valueRenderOption="UNFORMATTED_VALUE") .execute() ) values = result.get("values", []) return values except HttpError as err: return [] def main(): values = get_values() if not values: print("No data found.") return for row in values: print(row) if __name__ == "__main__": main() Save the above script next to your model. Create a user command in your model. Format the user command for python and enter the file name and method name. It might look something like this: /**external python: */ /**/"sheets"/**/ /** \nfunction name:*/ /**/"get_values"/**/ The return type of the command should be var which means any Variant type. Use code like the following to clone the data to a global table: Array values = getValues(); // call the user command. Array colHeaders = values.shift(); for (int i = 1; i <= values.length; i++) { Array row = values; row[0] = nullvar; } Table(values).cloneTo(Table("GlobalTable1")); Add the above code to a reset trigger. Pros: automatic once complete, easy to keep data up-to-date Cons: requires complicated setup, some python coding. The script could be adjusted to download additional ranges, and then return all data at once, but that requires some code ability. Import via HTTPS Google recommends you use a client library to access its APIs. However, it is entirely possible to use HTTPS requests instead. This could all be done from FlexScript, with no additional installations required. Pros: done all from FlexScript, no extra installs Cons: very technical Conclusion There are several ways to extract data from Google Sheets into FlexSim. Each has pros and cons. Choose the one that best fits your circumstances. Good luck!
View full article
Top Contributors