how to communicate with uci protocol using matlab - matlab

I'm looking for a method to communicate with a chess engine with uci protocol using matlab.
The chess engine is rybka and its an exe file. When I run the rybka.exe, I can communicate via dos command prompt but I want do that via matlab.
I think I have to use streampipe and stdin and stdout but I don't know how use it.
I found this code in Python and it works fine but I'm looking for a matlab version:
import subprocess, time
engine = subprocess.Popen(
'a.exe',
universal_newlines=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
def put(command):
print('\nyou:\n\t'+command)
engine.stdin.write(command+'\n')
def get():
# using the 'isready' command (engine has to answer 'readyok')
# to indicate current last line of stdout
engine.stdin.write('isready\n')
print('\nengine:')
while True:
text = engine.stdout.readline().strip()
if text == 'readyok':
break
if text !='':
print('\t'+text)

If it's just a case of using the exe file and capturing the output you can use the system command to capture the output. For example I can run the system's dir command in the following way:
>> [~, output] = system('dir')
output =
ant ant.cmd antRun.bat antenv.cmd envset.cmd runant.pl
ant.bat antRun antRun.pl complete-ant-cmd.pl lcp.bat runant.py
Documentation: http://www.mathworks.com/help/matlab/ref/system.html
See also: Running C program's executable from Matlab and getting the output

Related

Matlab is not running a .exe external program on Windows

I'm trying to run .exe code inside Matlab terminal (R2018a) but I'm encountering some problems.
My .exe code runs normally on Windows cmd with the following generic command (an expected output file is created)
code.exe < input
In Matlab I tried 4 approaches:
system('code.exe < input');
dos('code.exe < input');
system('code.exe < input', '-echo');
system('set path=%path:C:\Program Files\MATLAB\R2018a\bin\win64;=% & code.exe < input');
They are returning the line below and no output file is created.
ans = -1.0737e+09
Adding the "&" character at the end of the line of attempt 1, as sugested by ref and many others, Matlab opens the Windows cmd in the correct folder but does not execute the .exe code properly (no processes are running in task manager), no output file is created, e.g.:
system('code.exe < input &');
I also tried the suggestion of this reference .exe run in matlab does not create two output files like it does when run in command prompt but I was not successful. This reference suggestion is also returning and no output file is created: "ans = -1.0737e+09"
Edit:
According to this link, user Walter Roberson says "-1073741511 is hex C0000139 which appears to correspond to the Windows error code for "Entry point not found". That indicates that you either tried to execute something that was inherently not properly created (such as if you tried to directly execute the DLL that did not have a main program), or else that the program you executed tried to use a DLL that could not be found."
Any insights on how to resolve this? Thanks.
The answer from this link solved my problem.
Basically, You will have to create a batch file similar to the one below and change the Matlab path according to your version.
fid = fopen('myBatchFile.bat','w')
fprintf(fid,'%s\n','set path=%path:C:\Program Files\MATLAB\R2018a\bin\win64;=%');
fprintf(fid,'%s\n','code.exe < input')
fclose(fid)
system('myBatchFile.bat')

How to send commands to command window programmatically in MATLAB?

In matlab I can change to another shell by the bang (!) Notation.
Example:
I enter a conda Environment in MATLAB by the following command:
!cmd '"%windir%\System32\cmd.exe" /K ""C:\Program Files\Anaconda3\Scripts\activate_<conda-env-name>.bat" "C:\Program Files\Anaconda3""'
My MATLAB Command window then Displays following:
(<conda-env-name>) U:\some_starting_path>
Now, is there a way to send commands to this newly entered shell in a programmatic way, so that that command is evaluated in that very shell's syntax and not as a MATLAB-command?
For example, how can I write code that will execute a Python command without needing to enter it manually into the command line?
Not using the ! command or system(). Those are "one and done" functions.
But you can use Java's java.lang.Process API from within Matlab to control and interact with an ongoing process.
function control_another_process
pb = java.lang.ProcessBuilder(["myCommand", "myArg1", "myArg2"]);
proc = pb.start; % now proc is a java.lang.Process object
stdin = proc.getOutputStream; % Here's how you send commands to the process
stdout = proc.getInputStream; % And here's how you get its output
stderr = proc.getErrorStream;
% ... now do stuff with the process ...
end
You can use this with a shell, with python, or any other command.
Here's a Matlab class that wraps up the Java code to make it convenient to work with in Matlab: https://github.com/apjanke/janklab/blob/master/Mcode/classes/%2Bjl/%2Butil/Process.m

How can I execute a simulink diagram running in external mode from a Matlab script?

Matlab provides the sim command that can be used in a Matlab script to call and execute a Simulink model. But the function seems to be restricted to models that only run in Normal mode. When I try to call a Simulink model that runs in External mode, Matlab halts the script and flags it as an error. Besides being a nuisance it seems to me an unnecessary restriction on what could be a very useful application.
In any event is there a work around, perhaps a different command that I can use to run the Simulink diagram in External mode from the Matlab script?
I did try using the Matlab DOS shell command (using !) but it requires opening another instance of Matlab.
External Mode doesn't run a simulation, rather it is a mechanism for using the Simulink model's front end as a way of changing and viewing data that is running elsewhere (e.g. an executable running on the same machine as the model, or code running on an external processor).
To do that from the command line (or within code) you need to use a combination of the following commands:
>> set_param(gcs,'SimulationMode','external') % put model into External Mode
>> set_param(gcs,'SimulationCommand','connect') % connect to the executable
>> set_param(gcs,'SimulationCommand','start') % Start the executable
>> set_param(gcs,'SimulationCommand','stop') % Stop the executable

Running a MATLAB script from Notepad++

Is there a way of running a MATLAB script from Notepad++?
Obviously I have MATLAB installed on my computer. I know you can set a path for Notepad++to run when you hit F5, but when I set this path to my MATLAB.exe file, it simply opens another instance of MATLAB.
This is not what I want, I want the actual script in Notepad++ to be executed in the already open and running instance of MATLAB.
I'm afraid I'm not on my home computer at the moment to test this out, so the following is just a suggestion for you to try.
If you take a look at the NppExec plugin for Notepad++, you'll see that with it you can specify a command to be run when you hit F6 (like an enhanced version of hitting F5 in the regular Notepad++). You can also give it variables such as the path to the current file, and the name of the current file.
MATLAB (on Windows at least - I assume you're on Windows) makes available an API over ActiveX/COM. If you search in the MATLAB documentation for details, it's under External Interfaces -> MATLAB COM Automation Server. By running (in MATLAB) the command enableservice('AutomationServer') you will set up your running instance of MATLAB to receive instructions over this API.
You should be able to write a small script (perhaps in VBScript or something similar) that will take as input arguments the path and filename of the current file in Notepad++, and will then connect to a running instance of MATLAB over the COM API and execute the file's contents.
Set this script to be executed in NppExec when you hit F6, and it should then run the current file in the open instance of MATLAB.
As I say, the above is just speculation as I can't test it out right now, but I think it should work. Good luck!
Use NppExec add-on and press F6, copy paste the following and save the script:
NPP_SAVE
set local MATPATH=C:\Program Files\MATLAB\R2015a\bin\matlab.exe
cd "$(CURRENT_DIRECTORY)"
"$(MATPATH)" -nodisplay -nosplash -nodesktop -r "try, run('$(FILE_NAME)'),
catch me, fprintf('%s / %s\n',me.identifier,me.message), end"
then run (press F6; enter). Matlab Console and Plot windows still open and stay open. Error messages will be displayed in opening Matlab command window. Adding
, exit"
to the last command will make it quit and close again. If you want to run an automated application with crontabs or the like, check Matlab external interface reference for automation.
matlab.exe -automation ...
Also works in cmd terminal, but you have to fill in the paths yourself.
This is a usable implementation upon Sam's idea. First, execute MATLAB in automation mode like this.
matlab.exe -automation
Next, compile and execute this following VB in NppExec plugin. (which is to use MATLAB automation API)
'open_matlab.vb
Imports System
Module open_matlab
' connect to a opened matlab session
Sub Main()
Dim h As Object
Dim res As String
Dim matcmd As String
h = GetObject(, "Matlab.Application")
Console.WriteLine("MATLAB & Notepad++")
Console.WriteLine(" ")
'mainLoop
while True
Console.Write(">> ")
matcmd = Console.ReadLine()
' How you exit this app
if matcmd.Equals("!!") then
Exit while
End if
res=h.Execute(matcmd)
Console.WriteLine(res)
End while
End Sub
End Module
Then you'll get a matlab-like terminal below your editor. You can then code above and execute below. type !! to exit the terminal.
What it looks like
Tips: don't use ctrl+c to interrupt the MATLAB command, because it will kill the whole process instead.

How to avoid manual entering of input file, when .exe file is run from Matlab?

I am using a trans.exe file, which when run asks for a parameter (=input) file. If I run trans.exe using Matlab, then how can I directly give the parameter file inside the program without being prompted by Matlab to type it manually each time trans.exe is run?
If your executable doesn't have the ability to accept command-line parameters, then your only option is to invoke a call which pipes stuff to the stdin of your executable (under Linux, this would be something like !echo "blah blah blah" | my_executable). I don't know if this technique works from Matlab, though.
system('"C:\path_name\trans.exe" < "C:\path_name\input_trans_parameter_file.txt"');
The following command line used in above system function directly uses the name of the input file stored in input_trans_parameter_file.txt.
< "C:\path_name\input_trans_parameter_file.txt"