FlexSim Knowledge Base
Announcements, articles, and guides to help you take your simulations to the next level.
Sort by:
This article borrows from @jordan.johnson's original guide for deploying a distributed experiment/optimization with Amazon. Distributed Terminology Please be familiar with the terminology related to experiments and optimizations. Replication - a distinct model run. We'll use this term below for both replications (experimenter) and solutions (optimizer). Instance - a system, whether virtual or bare-metal, local or remote, meeting FlexSim's recommended requirements, and used for running distributed replications. Main PC - the system from which the user configures and initiates the distributed experiment or optimization. The Cloud - a shorthand term for remote servers/systems hosted in a data center, sometimes by a 3rd party such as Amazon, Microsoft, Google, or others. Background Concepts In discussing distributed experiments or optimization, you should start with a good understanding of both the Experimenter and the Optimizer. Please read and understand this user manual entry which includes explanations of key concepts that will be important as you continue. Other user manual articles provide additional guidance on configuring your own experiments or optimizations. Search the online user manual and this community if you have additional questions regarding experiments or optimizations, as needed. Using the experimenter requires a FlexSim license. The optimizer requires a license for the OptQuest add-on. Please contact your local distributor for more information or to request a test license for FlexSim and/or OptQuest. What are distributed experiments or optimizations? Experiments or optimizations can create dozens, hundreds, or even thousands of distinct model runs (or replications) to test various scenarios, build confidence intervals of the results, or zero-in on an optimal solution. A distributed experiment or optimization takes those individual model runs and assigns them (distributes them) to run across a group of computers. If you needed to run 1000 replications, and you have 4 computers available, each computer could run 250 replications, getting your results 4 times faster. When should you distribute? Using distributed replications can significantly reduce the required time to run an experiment if: The single-run time for your model is high (a couple minutes or more) You anticipate running a high number of replications If the time per replication is short, then the increased communication overhead may outweigh the benefit of using distributed replications. The communication overhead increases because all distributed replications still report results to a single FlexSim process on the Main PC, and that communication occurs over the network (local instances) or internet (remote instances), rather than on a single computer. If an experiment or optimization completes in an acceptable amount of time, you may not need to use distributed replications. Financial Costs 3rd party cloud providers such as Amazon, Microsoft, Google, and others, charge for their services. Your cost is usually based on the hardware you provision for your Windows instances, and the length of time those instances are live. Typically you only run your instances when running your experiment or optimization, and cancel or decommission your instances when your replications are complete. In this way you minimize the cost of your distributed experiment or optimization. The costs and process of decommissioning your provisioned instances differ based on which 3rd party cloud provider you use. You may have access to local computing resources that could be configured for use in your FlexSim experiments or optimizations. In this case you may avoid additional costs relating to 3rd party cloud providers by using your own on-premises computers. Licensing for distributed Windows instances Windows instances used solely for distributed replications DO NOT need an individual FlexSim license. Only the FlexSim installation on the Main PC must be licensed. System requirements for distributed Windows instances Graphics A Windows instance should meet or exceed FlexSim's recommended requirements. However, because replications run as background processes without graphics, they need not meet the graphics requirements and do not need hardware accelerated graphics. CPU An instance can run as many concurrent replications as it has CPU cores. If, for example, an instance has 32 CPU cores, it can run 32 replications of your model simultaneously. RAM For this example of a 32-CPU Windows instance, if you want FlexSim to run 32 replications simultaneously - one on each core - then the instance must also have enough RAM to handle 32 concurrent model runs. On your Main PC, use Windows Task Manager to watch a single model run's RAM usage to determine its peak RAM utilization. If your model's RAM utilization peaks at 3GB throughout the course of a model run, you should make sure your 32-CPU system has at least 32*3 = 96GB of RAM for replications alone, along with a good ~10% more for additional overhead used for the Webserver and the statistics gathering and reporting from all the replications (this number could be more or less, depending on the model's stats gathering). In addition, you must account for your system's baseline RAM utilization - how much RAM it uses just to run the operating system and all its background processes. You can find this baseline by checking the Task Manager at a moment when you're not running any simulations. Add all these together to see how much RAM would be necessary to run a replication on each core of the instance. If your instance doesn't have enough RAM to handle that many simultaneous replications, you'll need to limit the number of CPUs FlexSim will use when configuring your Cloud Computing settings from the Main PC. Disk Disk space is usually not an issue. However, if you are using the Store Data on Hard Drive option in the Statistics Collector, you will need to be sure that there is enough disk space to run the model to completion on the hard drive, multiplied by the number of cores. The amount of disk space on each instance may affect the total cost of using a 3rd party cloud provider. More information See the related sections in the article Recommended System Requirements for a more in-depth discussion of system components such as CPU and RAM, and how they relate to running your simulations and experiments. Provisioning distributed Windows instances The process of provisioning 3rd party cloud instances for running distributed FlexSim replications will differ from provider to provider. FlexSim has guides for the following cloud providers: Amazon Web Services Wherever you decide to host your instances, the important part is that eventually you end up with a group of Windows instances, each with a unique IPv4 address accessible from the Main PC. A custom Windows image Your 3rd party cloud provider probably allows you to save a custom Windows image that can include software and settings that you need for each Windows instance. Doing this once for a custom Windows image saves you time when starting new instances - each instance will start with the software and settings preconfigured for your purpose. On your custom image, do the following Download and install FlexSim. Use the same version of FlexSim as is licensed on the Main PC. Remember, you DO NOT need to activate a license. Run FlexSim. This creates a directory that is needed later. After FlexSim finishes its first start, close FlexSim. Download and install the FlexSim Webserver for your installed version of FlexSim. Edit the Webserver's configuration file appropriately for your situation. Default location is here: "C:\Program Files (x86)\FlexSim Web Server\flexsim webserver configuration.txt" Start the FlexSim Webserver from your Windows Start menu, or manually from the default location here: "C:\Program Files (x86)\FlexSim Web Server\flexsimserver.bat". The Webserver will download necessary files the first time it is run. Close the Webserver after it has completed its initial startup. Allow both FlexSim and node.js through the Windows Firewall. To do so, use Windows' Allow an App through the Windows Firewall tool. You will need to browse for both FlexSim and Node.js. Example locations (exact locations may vary by version): C:\Program Files\FlexSim 2023\program\flexsim.exe C:\Program Files\nodejs\node.exe If you are not familiar with the FlexSim Webserver, please review its documentation and test it out on a local machine to understand what it does, its configuration options, etc. If you cannot configure a custom Windows image, you will need to do the above on each instance individually. Initialize instances Launch your instances. On each instance, do the following: Log in to the instance with Remote Desktop or some other solution. Start the FlexSim Webserver from your Windows Start menu, or manually from the default location here: "C:\Program Files (x86)\FlexSim Web Server\flexsimserver.bat". Note the instance's IPv4 address. Once all instances are running the Webserver, you are ready to configure a distributed experiment or optimization from the Main PC. Author's Note: There is probably a way to make it so that when instances start up, they automatically run the Webserver, so that you don't have to manually connect to each one. I welcome any suggestions or steps for how to make that happen. Configuring a distributed experiment or optimization Once you have a list of running instances available, launch FlexSim on the Main PC. Open the experimenter interface from FlexSim's Main Menu > Statistics > Experimenter. Configure your experiment. As part of your configuration, under the Advanced tab, select the option to Use Distributed CPUs. Press the button to Configure Cloud Nodes. This will open the Global Preferences' Environment tab. Enter the IP addresses of your instances into FlexSim. Enter the port numbers you configured in their FlexSim Webservers. If your instances will max out RAM before CPUs, enter a CPU count representing the maximum number of concurrent replications your instance can handle. For more information on using remote computers for Experiment Jobs, see Running Jobs on the Cloud for more information.
View full article
In this article, you will learn how to export data from individual replications to an external database. This is an advanced tutorial, and assumes some exposure to databases and SQL. It also assumes that you are familiar with the Experimenter and/or Optimizer feature in FlexSim. This tutorial uses PostgreSQL, but should be compatible with the most popular SQL database engines. Model Description Let's assume you have a model with at least one Statistics Collector, as well as an experiment ready to go. The model used in this example is fairly simple: As the model runs, a Statistics Collector fills in a table. The table makes a new row for every item that goes into the Sink, recording the time, and the Type label of the item: For the experiment, we don't have any variables, but we do have one Performance Measure: Input of the Sink. Of course, an actual model would have many Variables, Scenarios, and Performance Measures, but this model leaves out those details. For reasons which come up later, this model also has two global variables, called g_scenario and g_replication. We will use these during the experiment phase. Connecting to the Database To connect to a database, you can use the Database Connector tool. Each Database Connector handles the connection to a single database. If you need to connect to more than one database, you will need more than one Database Connector. For this model, I have added a Database Connector, and configured the connection tab as follows: This configuration allows me to connect to a PostgreSQL database called "flexsim_test" running on my computer at port 9001. You can test the connection by clicking the "Test Connection" button. The test attempts to connect, as well as query the list of tables found in the database. Setting Up the Export Next, take a look at the Export tab: This tab specifies that we are exporting data from StatisticsCollector1 to the table called experiment_results in the database (this table should exist before you set up the export). The Append to Table box means that when the export occurs, the data will be added to the table. Otherwise, the data would be cleared from the target table. The other interesting thing here is that we are exporting more columns than the Statistics Collector has, namely the Scenario and Replication number. However, the expression in the From FlexSim Column column must be valid FlexQL (FlexSim's internal SQL language). Wrapping the values in Math.floor() leaves the values unchanged, and works well with FlexQL. Setting up the Experimenter Finally, let's take a look at just a little bit of code that makes the Experimenter dump data to a database. There is code in Start of Experiment, Start of Replication, and End of Replication: In the Start of Experiment, we need to clear the table. The code in this trigger connects to the database, runs the necessary query, and the closes the connection to the database. In the Start of Replication trigger, the code simply copies the replication and scenario values into the global variables we created for this purpose. In the End of Replication trigger, the code uses function_s to call "exportAll" on the database connector that we created. This uses the settings on the Export tab to dump the data from StatisticsCollector1 to the database table, including the replication and scenario columns. These same triggers run during an optimization, so the same logic will apply. Run the Experiment Finally, you can run the experiment. When each replication ends, the Statistics Collector data will be exported to the database. Databases can handle many connections simultaneously. This is important, because the child processes that run replications will all open individual connections to the database at the end of each replication. This leads to many concurrent connections, which most databases are designed to handle. But how can we tell that it worked? If you connect to the database with another tool, you can see the result table. Note that there are 1700 rows, and that data from Replication 5 is included. Additionally, you could use the Import tab to import all the data, or summary of the data data, into FlexSim. Conclusion Storing data in a database during an experiment is not difficult to do. There are many excellent tools for analyzing and visualizing database tables, which you could then use to further explore and understand your system. postgresqlexperimentdemo.fsm
View full article
Neste exemplo passo a passo iremos demonstrar como fazer uma otimização em seu modelo no FlexSim, utilizando o Optimizer, ferramenta OptQuest da OptTek, a qual é um add-in opcional no FlexSim. Com esta ferramenta você incorpora Metaheurísticas e orienta seu algoritmo para Otimizar, buscar as melhores soluções. Essa abordagem utiliza soluções funcionaram bem e as recombina em novas e melhores soluções. Vamos lá! Assista o vídeo em nosso canal do YouTube e acompanhe a montagem do modelo passo a passo abaixo: Modelo de Otimização Passo a Passo Para este tutorial, vamos examinar uma situação muito simples. Um único operador carrega o item de uma fonte para um processador. Depois que o item é processado o operador o carrega para um segundo processador que leva mais tempo para processar do que o primeiro. Após o segundo processador termina de processar o item, o operador leva-o para a saída. Agora vamos supor que queremos aumentar a Produção (que também está vinculado à receita) deste sistema, ajustando a posição dos processadores. Se cada processador pudesse ser movido até três metros à direita ou à esquerda, onde cada um deveria ser colocado? Seria muito difícil intuitivamente saber como colocar ambos os processadores para maximizar a produção. A fim de resolver este problema com precisão, vamos usar o Otimizador. Agora, obviamente este é um cenário drasticamente simplificado, mas muitas vezes na vida real você tem situações em que você quer ver como vários layouts afetam a Produção geral. Esta é uma implementação muito simplista de tal experiência. Passo 1: Construindo o Modelo Modelo Crie um novo modelo usando Segundos, Metros e Litros para unidades. Objetos Crie um Source, dois Processors, um Sink, um Dispatcher, e um Operator. Coloque esses objetos como mostrado abaixo e faça as conecções. Posições Defina a localização dos objetos de acordo com a tabela abaixo: Dispatcher e Operator não precisam estar em um lugar específico, mas não devem estar alinhados com o resto dos objetos. Lógica Defina a seguinte lógica: Selecione no Source1, Processor2, e Processor3 para usar transporte (Use Transport disponível no menu de propriedades rápidas (Quick Properties). Selecione o tempo de processo para o Processor2: normal(10, 2) (também disponível no disponível no menu Quick Properties). Selecione o tempo de processo para o Processor3: normal(12, 3). Defina a posicão inicial do Operator na sua posição atual. Passo 2: Definindo o Experimento O restante deste tutorial trata do uso do Experimenter, encontrado no menu Statistics. O Otimizador usa a maioria das funcionalidades já presentes no experimentador. Criando Variáveis Abra a janela Experimenter. Posicione a janela para que você possa ver os processadores no modelo, bem como a janela. Em seguida, para Processor1 e, em seguida, Processor2, siga estas etapas: Clique no processador na vista 3D. Clique no botão Referência de Posição nas Propriedades Rápidas e defina a referência de posição para Direct Spatials. Clique na seta para baixo ao lado do botão +. Selecione Sample no menu variables. Isso coloca o cursor no modo de Amostra. Selecione uma amostra do campo de posição X no menu Propriedades Rápidas clicando nele. Isso adiciona uma nova variável no Experimenter. Defina o valor para o Cenário 1 da nova variável clicando duas vezes na célula e digitando o novo valor. Defina o nome da variável clicando duas vezes no nome atual. Defina o nome sendo Proc1X para o Processor1 e Proc2X para o Processor2. Criando Performances de Medida Selecione a aba Performance Measures na janela do Experimenter, então: Clique no botão + para adicionar uma nova medida de desempenho. Nomeie a nova medida de desempenho Produção. Clique no botão e selecione a primeira opção Statistic by individual object. Selecione o Sink para o objeto e Input para a estatística. Para selecionar o objeto simplesmente digite "/Sink" (sem aspas) no campo do objeto ou faça o seguinte: Clique no botão +. Selecione o Sink através da lista de objetos do modelo. Após clique no botão Select quando você terminar. Otimização Além de utilizar o Experimenter para definir explicitamente cenários, você pode usar o Otimizador. O Optimizer criará automaticamente cenários e, em seguida, testará esses cenários, tentando encontrar um cenário que melhor atenda a um objetivo. Projetando a Otimização Vá para a guia Design do Optimizador na janela do Experimenter. Você verá que as duas variáveis criadas anteriormente estarão presentes; Isso ocorre porque o experimentador e o otimizador compartilham as mesmas variáveis. No entanto, o otimizador precisa de informações adicionais sobre essas variáveis. Especificamente, você deve especificar: Type - O tipo de uma variável determina quais tipos de valores são possíveis para uma determinada variável. Variáveis contínuas podem ter qualquer valor entre o limite superior e inferior. Lower Bound - O limite inferior especifica o menor valor possível que o otimizador pode definir para a variável. Upper Bound - O limite superior especifica o valor mais alto possível que o otimizador pode definir para a variável. Step - Para Variáveis Discretas e Design, o passo especifica a distância entre valores possíveis, começando pelo limite inferior. Group - Para as variáveis de permutação, o grupo especifica qual conjunto de variáveis de permutação essa variável particular pertence. Para esta otimização, queremos permitir que os processadores se movam três metros para cada lado. Como não estamos limitados a posições específicas dentro desse intervalo, ambas as variáveis de posição são Contínuas. No entanto, precisamos definir os limites inferior e superior de cada variável. Para editar valores na tabela, clique duas vezes na célula de interesse e insira o novo valor. Insira os valores mostrados abaixo: O passo final do projeto é definir a função objetivo. A função objetivo está presente, mas em branco. Edite seu nome para Faturamento. Em seguida, clique no campo da função de seta. Um botão aparecerá no lado direito. Clique neste botão para exibir uma lista de todas as variáveis e medidas de desempenho. A função objetivo é um valor derivado de qualquer um ou de todos esses valores. Selecionar Produção, Isso irá adicionar essa medida de desempenho para a função objetivo, e colocar o cursor para a direita e para o final. Adicione o texto * 500 para que a receita seja igual o [Produção] * 500. Deixe a direção em Maximize, porque queremos maximizar o Faturamento. Como temos apenas um objetivo, o modo de pesquisa pode permanecer em Single. Passo 3: Executando a Otimização Vá para a aba Optimizer Run na janela do Experimenter. Então: Defina Run Time sendo 10000. Este é o tempo que o otimizador executará cada configuração do modelo (potenciais soluções) para a avaliação. Defina o Wall Time sendo 0. Normalmente, isso significa quanto tempo o otimizador pode ser executado em tempo real. O valor 0 significa que não tem limite de tempo. Defina Max Solutions como 50. Isso significa que o otimizador tentará não mais de 50 soluções diferentes para encontrar a solução ideal. Clique no botão Optimize. A janela do Experimenter alternará automaticamente para a guia Resultados do Otimizador, Optimizer Results. O otimizador então começará a executar a seguinte sequência: Determinar valores para Proc1X e Proc2X. Executar um modelo com esses valores para 10000 segundos. Avaliar as variáveis e medidas de desempenho. Calcula a função objetivo. Classifique esta solução. Usa as informações desta solução para criar uma nova solução - novos valores para Proc1X e Proc2X. Repete novamente a partir do passo 2. O otimizador pode avaliar várias soluções ao mesmo tempo. À medida que a otimização progride, o gráfico de Resultados do Otimizador é atualizado e mostra o progresso do otimizador. Uma vez que o otimizador avalie 50 soluções, uma mensagem aparecerá indicando por que o otimizador parou. Neste caso, ele dirá que o otimizador atingiu o número máximo de soluções. Se algo der errado, a mensagem conterá informações sobre o erro. Passo 4: Analizando os Resultados Assim que a otimização for concluída, o gráfico de resultados do otimizador será semelhante a este: O Eixo Y é chamado de "Single Objective". Para este exemplo, é sinônimo de Faturamento. As melhores soluções são destacadas. Os círculos com uma borda mais clara ao seu redor representam melhores soluções. Para um único objetivo, as 10 melhores soluções são marcadas desta forma. Como a otimização progrediu, o otimizador ficou melhor e melhor na criação de boas soluções, de modo que as últimas 15 soluções foram todas muito boas. Isso é chamado de convergência, e é uma maneira de saber se uma otimização é concluída; Se o valor objetivo não tiver melhorado por um tempo, pode ser que ele não melhore com mais pesquisas, e a melhor solução atual deve ser usada. Respondendo à Pergunta Inicial O objetivo dessa otimização foi descobrir onde posicionar os dois processadores. Agora podemos encontrar a resposta a esta pergunta com muita facilidade. Passe o mouse sobre a melhor solução (o maior círculo azul) no gráfico; Uma pequena janela aparecerá. Clique nesta solução para selecioná-la. Agora, no painel Opções de gráfico, altere o Eixo Y para Proc1X e o Eixo X para Proc2X. A melhor solução (e todas as outras melhores soluções) é encontrada onde Proc1X é maior, e onde Proc2X é menor. Lembre-se que todas as 10 melhores soluções produziram os mesmos resultados; Neste caso, ter os dois processadores próximos um do outro é a melhor configuração para este modelo. Configurando o Modelo para a Melhor Solução Pode ser muito útil configurar o modelo para visualizar a melhor solução. Para fazer isso, clique no botão Export Scenarios. Este botão leva todas as soluções selecionadas e cria cenários para elas. Volte para a guia Scenarios na janela Experimenter para ver a nova solução. Agora, a partir do menu suspenso " Choose default reset scenario" na extrema direita, selecione o novo cenário. Em seguida, resete o modelo para aplicar esses valores ao modelo 3D. Segue o modelo referente ao artigo: modelo-optimizer.fsm Inscreva-se e acompanhe nosso canal de videos no YouTube FlexSim Brasil
View full article
Top Contributors