Is there any option of running an Anylogic simulator without opening any UI window? - simulation

I'm in a project in which I have to run an Anylogic simulator multiple times. I made an script to modify the input data, run the simulator and then store the output data just before the next simulation run.
The idea is to externally run the simulation (from a python file). The problem is that, when the simulation ends, the simulation window doesn't close automatically so the python file won't continue executing.
I´ve tried to run the simulator without showing the animation of the simulation but still opens a window so it doesn´t work for my purpose.
I don´t know if there is an option in Anylogic to export a model that automatically closes the window once the simulation is completed or if there is any way of creating a simulator that runs without opening any window.
Thank you.

Unfortunately there is no such solution. Even if you can run without UI in Linux, it will not automatically close once the run is complete. I use a workaround:
It is a Python script that scans the outputs folder every 5 seconds and if there are changes in the files, it closes the AnyLogic file. Use this as an inspiration::
from time import sleep
from utils.data.fileSystem import FileSystem
def sync_polling_folder(path, predicate, delay_sec):
print('checking under ' + path + ' folder')
beginning = FileSystem.stat(path)
old = beginning
new = beginning
def two_files_are_different():
return not predicate(str(old), str(new))
def the_process_has_not_begun():
return str(new) == str(beginning) or str(old) == str(beginning)
# if two folders are the same, quit (means no-changes = finished)
# but if they are equal because process never started, keep going
while two_files_are_different() or the_process_has_not_begun():
print('[sleeping] because files are not written yet.')
sleep(delay_sec) # main thread waiting
old = new
new = FileSystem.stat(path)
print('[anylogic] ready to be killed')
return True

Related

why can't I get a checkpoint to flash with a script?

I am trying really hard to start with a simple skeleton on Roblox Studio, and then change one of the checkpoints (or all of them) so that they flash.
I thought to do that by using a script that I saw online that changes the transparency from 1 to 0 and back every 1 second.
So I tried this (I added this to all Checkpoints quite consistently in the same way):
and this (for this one I just added the part at the bottom):
but whenever I played in the Studio to test it I always got static checkpoints:
It is either the script is not running, or transparency is not the right way to go or what?
The "Checkpoints" folder has many objects in it that are called "Checkpoint". If you want to flash a particular one from its child script, you could do this instead:
while (true) do
script.Parent.Transparency = 1
wait(1)
script.Parent.Transparency = 0
wait(1)
end
it will only flash its parent (the Checkpoint).

Displaying calculated data on simulation main window

after running my simulation model, I have results that are printed on the console. instead of printing on the console, is there a way i can display results on simulation main. i mean once we run the model the simulation window pops up and we push the run button where the simulation main closes and the main window starts running, instead of that once the run button is pushed the simulation main window stays until the simulation is ended and the output is displayed later on simulation main window
Sure. First, untick this box in your sim experiment properties:
Next, drag in a button to your experiment and give it this code:
if ( getState() == IDLE ){
run();
getExperimentHost().setPresentable( this);
}
This starts the model but you stay at the experiment.
To display data, you use the code box below in the experiment using the root keyword to access Main:
NOTE: This only updates after the model run. If you want to see data updates during the run, you need to display it on Main directly (this is what it is for)

Dash - Run callback in server side

Good morning,
I have created a callback in Dash that makes the job of a scheduler.
Every 10 minutes (with the help of an interval component), my callback is running to fetch the data from a server and to update the csv file that I use in my app.
The problem is that my callback is called only when I have the webpage opened. As soon as I close the page, the scheduler stops and runs again when I open the page again.
As the data process of updating data can be long sometimes, I want the scheduler to always run and fetch the data every 10 minutes.
I assume that a callback is a client side process right? So how can I make it run in server side?
Thank you,
Dash is probably not the right solution for this. I think it would make more sense to set up the Python code you need for this job in a simple .py script file, and set a cron job to run that script every 10 min.
Thank you #coralvanda for the help.
I finally did a python script in my container A that calls the container B every 10 minutes. The container B is fetching the data.
It makes the job.
import schedule
import time
import docker
def worker_restart():
client = docker.from_env()
container = client.containers.get('container_worker')
container.restart()
schedule.every(10).minutes.do(worker_restart)
while True:
schedule.run_pending()
time.sleep(1)

wxPython window randomly freezes on RPi and acts weird afterwards

This Problem occurs on the RPi (3B+, Raspbian Buster) only. I run the program on my Mac without any problems.
Short description of my program:
After entering the mainloop, the program enters a second thread with another loop (call it requestloop) when the designated button is pressed. The requestloop can be left by pressing the button again. This requestloop requests a xml table via url every 10 seconds which is then parsed with ElementTree, sorted and displayed in a wx.grid.Grid. I use grid.ForceRefresh to make sure the grid is updated.
I hope the following snippet helps to understand the above:
def on_btnrun(self, event):
global run
if self.btnrun.Label == "Start":
run = True
thrupt = threading.Thread(target=self.thrupdate)
thrupt.start()
self.btnrun.SetLabel("Ende")
elif self.btnrun.Label == "Ende":
run = False
self.btnrun.SetLabel("Start")
def thrupdate(self):
while run is True:
reset()
self.grid.ClearGrid()
update(self.grid)
self.grid.ForceRefresh()
time.sleep(10)
Problem:
Now as mentioned in the title the whole wx Window freezes after passing the requestloop between roughly 5 and 20 times. This happens completely randomly, I could not find any regularities. The program keeps running though, for it still prints the output in the terminal every cycle (I added this function for testing).
When I now open another window (eg. menu dropwdown) which lays over the wx Window it will be copied onto the wx Window and stay there after I closed it.
Here are some Images to better understand what I mean (ignore all other widgets that I didn't mention, they are just nonfunctional placeholders).
Image of the wx Window before it freezes
Image of the wx Window after it freezes
Image of the wx Window after opening and closing the dropdown menu
Extra-Info: while building wxPython on the RPi I got some warnings and everytime I run the program I get the following one (it says the actual time instead of time):
(program.py:1666): Gtk-Critical **: time: gtk_distribute_natural_allocation: assertion ‚extra_space >= 0‘ failed
Question:
I have no idea why any of this happens. Is wxPython not stable on Raspbian? Or did the build partly fail? Or is the RPi not having enough rendering capacity?
Solved it by using wx.CallAfter in the details of the update() method.

Output to command-line if started from command line

I'm writing an application that can be started either as a standard WinForms app or in unattended mode from the command-line. The application was built using the VS 2k5 standard WinForms template.
When the application is executed from the command-line, I want it to output information that can be captured by the script executing the application. When I do this directly from Console.WriteLine(), the output does not appear, although it can be captured by piping to a file.
On the other hand, I can force the application to pop up a second console by doing a P/Invoke on AllocConsole() from kernel32. This is not what I want, though. I want the output to appear in the same window the application was called from.
This is the salient code that allows me to pop up a console from the command line:
<STAThread()> Public Shared Sub Main()
If My.Application.CommandLineArgs.Count = 0 Then
Dim frm As New ISECMMParamUtilForm()
frm.ShowDialog()
Else
Try
ConsoleControl.AllocConsole()
Dim exMan As New UnattendedExecutionManager(ConvertArgs())
IsInConsoleMode = True
OutputMessage("Application started.")
If Not exMan.SetSettings() Then
OutputMessage("Execution failed.")
End If
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
ConsoleControl.FreeConsole()
End Try
End If
End Sub
Public Shared Sub OutputMessage(ByVal msg As String, Optional ByVal isError As Boolean = False)
Trace.WriteLine(msg)
If IsInConsoleMode Then
Console.WriteLine(msg)
End If
If isError Then
EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Error)
Else
EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Information)
End If
End Sub
Raymond Chen recently posted (a month after the question was posted here on SO) a short article about this:
How do I write a program that can be run either as a console or a GUI application?
You can't, but you can try to fake it.
Each PE application contains a field
in its header that specifies which
subsystem it was designed to run
under. You can say
IMAGE_SUBSYSTEM_WINDOWS_GUI to mark
yourself as a Windows GUI application,
or you can say
IMAGE_SUBSYSTEM_WINDOWS_CUI to say
that you are a console application. If
you are GUI application, then the
program will run without a console.
The subsystem determines how the
kernel prepares the execution
environment for the program. If the
program is marked as running in the
console subsystem, then the kernel
will connect the program's console to
the console of its parent, creating a
new console if the parent doesn't have
a console. (This is an incomplete
description, but the details aren't
relevant to the discussion.) On the
other hand, if the program is marked
as running as a GUI application, then
the kernel will run the program
without any console at all.
In that article he points to another by Junfeng Zhang that discusses how a couple of programs (Visual Studio and ildasm) implement this behavior:
How to make an application as both GUI and Console application?
In VisualStudio case, there are actually two binaries: devenv.com and devenv.exe. Devenv.com is a Console app. Devenv.exe is a GUI app. When you type devenv, because of the Win32 probing rule, devenv.com is executed. If there is no input, devenv.com launches devenv.exe, and exits itself. If there are inputs, devenv.com handles them as normal Console app.
In ildasm case, there is only one binary: ildasm.exe. It is first compiled as a GUI application. Later editbin.exe is used to mark it as console subsystem. In its main method it determines if it needs to be run as console mode or GUI mode. If need to run as GUI mode, it relaunches itself as a GUI app.
In the comments to Raymond Chen's article, laonianren has this to add to Junfeng Zhang's brief description of how Visual Studio works:
devenv.com is a general purpose console-mode stub application. When it runs it creates three pipes to redirect the console's stdin, stdout and stderr. It then finds its own name (usually devenv.com), replaces the ".com" with ".exe" and launches the new app (i.e. devenv.exe) using the read end of the stdin pipe and the write ends of the stdout and stderr pipes as the standard handles. Then it just sits and waits for devenv.exe to exit and copies data between the console and the pipes.
Thus even though devenv.exe is a gui app it can read and write the "parent" console using its standard handles.
And you could use devenv.com yourself for myapp.exe by renaming it to myapp.com. But you can't in practise because it belongs to MS.
Update 1:
As said in Michael Burr answer, Raymond Chen recently posted a short article about this. I am happy to see that my guess was not totally wrong.
Update 0:
Disclaimer: This "answer" is mostly speculation. I post it only because enough time has passed to establish that not many people have the answer to what look like a fundamental question.
I think that the "decision" if the application is gui or console is made at compile time and not at runtime. So if you compile your application as gui application, even if you don't display the gui, its still a gui application and doesn't have console. If you choose to compile it as console application then at minimum you will have a console windows flashing before moving to gui "mode". And I don't know if it is possible in managed code.
The problem is fundamental, I think, Because a console application has to take "control" of the calling console application. And it has to do so before the code of the child application is running.
If you want to check if your app is started from the command line in .NET, you can use Console.GetCursorPosition().
The reason that this works is that when you start it from the command line, the cursor moves away from the initial point ((0, 0)) because you typed something in the terminal (the name of the app).
You can do this with an equality check (code in C#):
class Program
{
public static void Main
{
if (Console.GetCursorPosition() == (0, 0))
{
//something GUI
}
else
{
//something not GUI
}
}
}
Note: You must set the output type to Console Application as other output types will make Console.GetCursorPosition() throw an exception.