Calling Mathematica from OCaml program - ocaml

I am writing OCaml code. In part of it, I want to examine whether two arithmetic expression are equal (like x+2+y == x+2*y-y+2). Implemeting this in mathematica is straightforward, so all I want some help on executing Mathematica and get the result back in OCaml. My OS platform is Linux.
Cheers,
Z.

You may be able to use something along the lines of this:
let channel_to_mathematica, channel_from_mathematica = open_process "mathematica"
in
Printf.fprintf channel_to_mathematica "Tell me if this is equal ...\n";
let answer_from_mathematica = Scanf.fscanf channel_from_mathematica ...
in
...
Documentation of open_process here
Documentation of module Scanf here

A very general answer is to write a command-line Mathematica script that takes 2 expressions (either on the command line or stdin) and outputs whether they are equal.
Then in OCaml simply call that program with a system call.
As for writing such a command-line Mathematica script, I recommend MASH (disclosure: I made MASH):
Call a Mathematica program from the command line, with command-line args, stdin, stdout, and stderr

Related

Fortran: pipe to program

Is there any possibility to launch an external program from Fortran and write something to this programs standard input?
I know e.g. of gfortran's SYSTEM but there is no such option.
As you have noticed, GFortran does not have anything like the pipe()/fork()/exec() functions builtin.
If you're on Linux or some other Unix-like system you could do something like
execute_command_line("mkfifo /path/to/fifo")
The mkfifo command creates a named pipe, that is, a pipe that also has a name in the filesystem.
open(newunit=plot_unit, file="/path/to/fifo", access="stream", format="formatted")
execute_command_line("gnuplot < /path/to/fifo")
So the idea is that you can then open the FIFO like a normal external unit in GFortran, then execute gnuplot with standard input connected to the FIFO.
You might need to exchange the order of #2 and #3 in case this deadlocks. But some minor variation of the above should work (I've used it to connect to one Fortran program from another).
Firstly, if you're using a relatively recent compiler you should be able to use execute_command_line (part of the f2008 spec) instead of system (compiler extension). This launches a command using the C library's system call which uses the sh shell on nix and cmd.exe on Windows (see here). As such you can use standard input redirection type approaches to connect to stdin of the launched program, but it may not be suitable for more complicated use.
The following example shows a simple example
program stdIn
implicit none
character(len=20) :: cmd, args
character(len=50) :: fullcmd
cmd = "bc"
args = "1+2"
fullcmd = cmd//" <<< "//args
print*,"Running ",fullcmd
call execute_command_line(fullcmd)
end program stdIn
Which should output
Running bc <<< 1+2
3

Is it possible to execute another program using C++?

What I'd like to do is have my C++ code open up Mplus (statistical program that I've downloaded on my computer) and run it. Is it possible?
You may be able to do what you want with std::system() calls like:
std::system("program -e input_commands.txt"); // Assuming it accepts some sort of command line args
std::system("program < input_commands.txt"); // Assuming it responds to stdin
It depends on the program if this approach will work.

Differences when writing to / reading from the console between gfortran- and g77-compiled code

This one's going to take a bit of explaining. Please bear with me.
What I Have
I have in my possession some Fortran source code and some binaries that have been compiled from that code. I did not do the compilation, but there is a build script that suggests G77 was used to do it.
As well as the Fortran stuff, there is also some Java code that provides users with a GUI "wrapper" around the binaries. It passes information between itself and the binaries via their input/output/error pipes. The Java code is very messy, and this way of doing things adds a lot of boilerplate and redundancy, but it does the job and I know it works.
What I Need
Unfortunately, I'd like to make some changes:
I want to create a new Python wrapper for the binaries (or, more precisely, extend an existing Python program to become the new wrapper).
I want to be able to compile the Fortran code as part of this existing program's build process. I would like to use gfortran for this, since MinGW is used elsewhere in the build and so it will be readily available.
The Problem
When I compile the Fortran code myself using gfortran, I cannot get the resulting binaries to "talk" to either the current Java wrapper or my new Python wrapper.
Here are the various ways of printing to the console that I have tried in the Fortran code:
subroutine printA(message)
write(6,*) message
end
subroutine printB(message)
write(*,*) message
end
subroutine printC(message)
use iso_fortran_env
write(output_unit,*) message
end
There are also read commands as well, but the code doesn't even get a change to execute that part so I'm not worrying about it yet.
Extra Info
I have to call gfortran with the -ffixed-line-length-132 flag so that the code compiles, but apart from that I don't use anything else. I have tried using the -ff2c flag in the vague hope that it will make a difference. It doesn't.
This stackoverflow post is informative, but doesn't offer me anything that works.
The relavant manual page suggests that printA should work just fine.
I'm working on Windows, but will need this to be multi-platform.
Juse in case you're intested, the Java code uses Runtime.getRuntime().exec("prog.exe") to call the binaries and then the various "stream" methods of the resulting Process object to communicate with them. The Python code uses equivalents of this provided by the Popen object of the subprocess module.
I should also say that I am aware there are alternatives. Rewriting the code in Python (or something else like C++), or making amendments so that is it can be called via F2Py have been ruled out as options. Using g77 is also a no-go; we have enough dependencies as it is. I'd like to be able to write to / read from the console properly with gfortran, or know that it's just not possible.
Hard to say without seeing more details from your Fortran and Python codes. The following pair of code works for me (at least under Linux):
Fortran program repeating its input line by line prefixed with line number:
program test_communication
use iso_fortran_env, stdout => output_unit, stdin => input_unit
implicit none
character(100) :: buffer
integer :: ii
ii = 1
do while (.true.)
read(stdin, *) buffer
write(stdout, "(I0,A,A)") ii, "|", trim(buffer)
flush(stdout)
ii = ii + 1
end do
end program test_communication
Python program invoking the Fortran binary. You can feed it with arbitrary strings from the console.
import subprocess as sub
print "Starting child"
proc = sub.Popen("./a.out", stdin=sub.PIPE, stdout=sub.PIPE)
while True:
send = raw_input("Enter a string: ")
if not send:
print "Exiting loop"
break
proc.stdin.write(send)
proc.stdin.write("\n")
proc.stdin.flush()
print "Sent:", send
recv = proc.stdout.readline()
print "Received:", recv.rstrip()
print "Killing child"
proc.kill()

How to run a C++ program in another C++ program?

I have a simple C++ program that takes in inputs and outputs some string. Like this:
$ ./game
$ what kind of game? type r for regular, s for special.
$ r
$ choose a number from 1 - 10
$ 1
$ no try again
$ 2
$ no try again
$ 5
$ yes you WIN!
Now I want to write a c++ program can runs this c++ program and plays the game automatically without user input and then outputs it to a file or standard output.
Running it would look like this:
./program game r > outputfile
game is the game program, r for playing regular style.
How should I do this? The main reason I need this program is that I want to do automatic testing for a much bigger program.
You could use std::system from <cstdlib>:
std::system("game r > outputfile");
The return value is ./program's, the sole argument must be of type char const *.
There is no standard way to run a program and feed it standard input, though. Judging by your command line, you're on some Unix variant where popen from <stdio.h> should work:
FILE *sub = popen("game r > outputfile", "w");
then write to sub with the stdio functions and read outputfile afterwards.
(But for simple testing, I'd recommend implementing the core logic of your program as a set of functions/classes that can be run by a custom main function in a loop; or pick your favorite scripting language to handle this kind of thing.)
I'd be more efficient to add a caller function to your main source and have it control looping, logging, and feeding input. It would also not require system calls or other magic to pull off. Being a game programmer, we have our games play themselves as much as possible to help with debugging, and almost always this is done via internal code, not through external scripting or system calls. It makes it easier to feed viable input as well.
This scenario cries out for a "script", IMHO.
Bash, Perl, Python - you name it.
SIMPLEST CASE:
Just write a bash script to call ./program game r > outputfile.
Or ./program game r < test_input.txt > test_output.txt
For more advanced scenarios, you might want to look at "expect".
You might also want to look at "STAF", which might be a great way to "automate your automated tests":
http://staf.sourceforge.net/current/STAFFAQ.htm

Implementing "app.exe -instruction file" notation in C++

I have a project for my Data Structures class, which is a file compressor that works using Binary Trees and other stuff. We are required to "zip" and "unzip" any given file by using the following instructions in the command line:
For compressing: compressor.exe -zip file.whatever
For uncompressing: compressor.exe -unzip file.zip
We are programming in C++. I use the IDE Code::Blocks and compile using GCC in Windows.
My question is: How do you even implement that??!! How can you make your .exe receive those parameters in command line, and then execute them the way you want?
Also, anything special to have in mind if I want that implementation to compile in Linux?
Thanks for your help
You may want to look in your programming text for the signature of the main function, your program's entry point. That's where you'll be able to pull in those command line parameters.
I don't want to be more detailed than that because this is apparently a key point of the assignment, and if I ever find myself working with you, I'll expect you to be able to figure this sort of stuff out on your own once you've received an appropriate nudge. :)
Good luck!
As I recall, the Single UNIX Specification / POSIX defines getopt in unistd.h to handle the parsing of arguments for you. While this is a C function, it should also work in C++.
GNU GLIBC has this in addition to getopt_long (in getopt.h) to support GNU's extended --style .
Lo logré, I gotz it!!
I now have a basic understanding on how to use the argc and argv[ ] parameters on the main() function (I always wondered what they were good for...). For example, if I put in the command line:
compressor.exe -unzip file.zip
Then:
argc initializes in '3' (number of arguments in line)
argv[0] == "compressor.exe" (name of app.)
argv[1] == "-unzip"
argv[2] == "file.zip"
Greg (not 'Creg', sorry =P) and Bemrose, thank you guys for your help!! ^^