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
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