How to plot data by c program? - c

I am a mechanical engineer who has only limited knowledge in C programming. I wrote some code in order to make simulations, and I want to visualize the simulation results. At the moment I am using Dev-C for writing my codes. With fopen and fprintf commands I generate a .dat file which includes the results. Then I open GNUPLOT program and import my .dat file to plot the results. This takes time and I have to wait till the end of the simulation. Is there an easy way to connect my plotter with Dev-C, so my plotter starts plotting data during the simulation? Any library or etc. ?

Since you already know gnuplot, the simplest thing to do may be to just call gnuplot from your program and pipe the data to it:
FILE *gnuplot = popen("gnuplot", "w");
fprintf(gnuplot, "plot '-'\n");
for (i = 0; i < count; i++)
fprintf(gnuplot, "%g %g\n", x[i], y[i]);
fprintf(gnuplot, "e\n");
fflush(gnuplot);

I've been using PLPlot for plotting from C and have found it both effective and easy. It's cross platform, open source, and supports a rich array of plot capabilities. I'd recommend having a look at the examples to get started.

OK, one solution, as you are writing out to a file, would be to just make a system() call when you write out to the file, and call gnuplot.
But, that means you should change the filename each time, but I fear if you do that that it won't look correct, since you are sending small amounts of data each time.
http://www.gnu.org/software/libc/manual/html_node/System-Calls.html
I have never used gnuplot, but if you look at this page (http://gnuplot-tricks.blogspot.com/) you may find some tricks that would enable this to work well.
But, I think, unless you are going to plot everything yourself, and skip gnuplot, then you may just need to wait, as you are.
You may find the C interface to gnuplot may help you:
http://ndevilla.free.fr/gnuplot/

pbPlots is very easy to use and works with all C compilers.
Download pbPlots.c/h and supportLib.c/h from the github page and include them in your build.
Here is a complete example that will produce a plot in a PNG-file.
#include "pbPlots.h"
#include "supportLib.h"
int main(){
double x [] = {-1, 0, 1, 2, 3, 4, 5, 6};
double y [] = {-5, -4, -3, -2, 1, 0, 1, 2};
RGBABitmapImageReference *imageRef = CreateRGBABitmapImageReference();
DrawScatterPlot(imageRef, 600, 400, x, 8, y, 8);
size_t length;
double *pngData = ConvertToPNG(&length, imageRef->image);
WriteToFile(pngData, length, "plot.png");
return 0;
}
There are a lot more options available, these are described on the github page.

There is a extensive library called DISLIN for scientific purpose. Avaliable even in Fortran language.
You can check examples in official website.
You can obtain it freely in DISLIN Homepage

I had a wee look around to see what other people have done regarding real-time plotting in gnuplot, and found this:
http://users.softlab.ntua.gr/~ttsiod/gnuplotStreaming.html
There's a little Perl script that can drive the plotting, and you just pipe your information in.
Since your data is being written to file, you may want to tail -f yourdata.dat and pipe that into the real-time plotter.
Also, because you're using the stdio file calls, you'd need to flush regularly (by calling fflush)
Obviously your simulation would be running in the background or in another shell. That way you could break out of the plotting at any time without interrupting the simulation.
Hope that's of some use to you.

Related

Creating an initialization file in pari-gp

This question is definitely a stupid question. But, coming from C; I'm having trouble adding header files or "an initialization" file to my pari-gp code. This is to mean; I have a 1hr compile of code to make one vector; and I can use that vector once initialized; but I want to make a file of this vector such that I can access it once it's compiled once.
Here's the code without a header file; which takes about an hour to compile (given the series precision/numerical precision which are set to 100).
\p 100
\ps 100
Phi_Inv(w,l,{n=100}) =
{
my(out = 0);
for(i=0,n,
out = w*exp(out)/(exp(l*(n+1-i))+w)
);
out;
}
beta_init(n) = {
beta_taylor = vector(100,i,polcoef(Phi_Inv(w,l,n),i-1,w));
print(beta_taylor);
}
Rather than the brutal assignment of beta_taylor; and the caveman like print(beta_taylor), how can I write this to an initialization file I can package with the script. That is; an X mb file with all the coefficients neatly packed together. And if the file is lost, just run the code (which will take an hour) to write the initialization file again.
I mean, how would I properly do #include test.h where test.h is just a very long list of Taylor series values. So that I can just include this file, and write beta_taylor[i] for the i'th function. Such that it's as simple as including variables, like in C. I know I'm missing something simple and it's frustrating--making me feel stupid.
I'm mostly just asking about the syntax to go about and do this. I think I know how; but I imagine it's not the best way.
Any help or suggestions are greatly (And I really mean it, Greatly) appreciated.
To make a long story short; how do I save beta_taylor as a file we load when we initialize the program, and if the file is deleted we can save the program again by running the code for an hour?
Regards
So you want to serialize your vector of numbers to a file and read it back in later?
writebin() to the rescue. Something like
beta_init(n) = {
beta_taylor = vector(100,i,polcoef(Phi_Inv(w,l,n),i-1,w));
writebin("beta_taylor.dat", beta_taylor);
}
Run the function in one gp session, and then in another session, beta_taylor=read("beta_taylor.dat").
Compiling your code first with gp2c before running it to calculate the numbers will speed things up if you're not already doing that, btw. gp2c-run makes it easy by compiling a file and starting a new gp session with the resulting shared library already loaded. You might also look into if the parallel operations can be used here to speed up the initial computation; reading the documentation for parvector() I don't think it can be, though, because of that mysterious l variables used in beta_init() that I don't see you define anywhere, but you might be able to re-phrase your equation with hardcoded constants or something.
An initialization for Pari/GP, at program start:
(file gprc.txt in directory of gp.exe)
lines = 25
colors = "brightfg"
histfile = "gp_history.txt"
breakloop = 0
help = "# perl\\perl gphelp.pl -detex -ch 10 -cb 11 -cu 12"
prompt = "gp >"
prompt_cont="gpc>"
datadir = "u://paritty/syntax/_v11/"
path = "u://paritty/syntax/_v11/"
primelimit = 100 000 000
parisizemax = 1 000 000 000
read "__init.gp"
echo = 0
The file __init.gp contains my generally used functions; commands to read precomputed data-vectors can of course be included there. If no path is indicated it will be searched in the directory given in the path= statement.

Parsing Testing Data into C Program

I'm developing a module that will be run on an Embedded ARM chip to run an attitude controller, which is written in C. We have a MATLAB simulation, with a bunch of low-level functions that I'd like to be able to make unit tests for with data generated by the MATLAB program.
Each function is reasonably complex, and I'd like to calculate the error between the Matlab output and the C output for validation purposes. Each function has the same Inputs and Outputs between the two implementations, so they should match (to an allowable tolerance).
Are there any good existing file formats that could be useful? The types of test data would be:
<Test Input 1> <Test Input 2> <Test input 3> <Expected Output 1> <Expected output 2>
Where inputs and outputs are arbitrary single floats, arrays or matrices. I have considered XML because there are some nice parsers, but thats about all i know.
Any suggestions or direction?
an easy way is to use CSV file format:
it is easy to handle from C. see here
use OpenOffice/Excel later by just changing the file suffix to *.csv
see more here about CSV files
It sounds like you want to run these unit tests from C? Have you considered running them in MATLAB instead? If so then you would be able to leverage the MATLAB Unit Test Framework and parameterized testing to encode the actual and expected values (using the "sequential" ParameterCombination attribute in your MATLAB test. This would require that you create MEX wrappers for your C code so that you can invoke them from MATLAB, but other than that extra step this could be quite seamless. Also, have you looked into using MATLAB Coder for this?
The MATLAB Unit Test would look something like this:
classdef Times2Test < matlab.unittest.TestCase
properties(TestParameter)
input = {1,2,3};
expectedResult = {2,4,6};
end
methods(Test, ParameterCombination='sequential')
function testMATLABSimulation(testCase, input, expectedResult)
actualResult = times2(input);
testCase.verifyEqual(actualResult, expectedResult, ...
'RelTol', 1e-6);
end
function testCAlgorithm(testCase, input, expectedResult)
% Must expose to MATLAB by compiling C code to Mex
actualResult = times2Mex(input);
testCase.verifyEqual(actualResult, expectedResult, ...
'RelTol', 1e-6);
end
end
end
Since each function has the same input, there is no reason not to create input files in the most simple form - just numbers!
You know exactly the type and amount of numbers you want to read, so just read them using fscanf
The file could look like:
12.3 100 200.3
1 2 3
4 5 6
7 8 9
The first row is the arbitrary float numbers, you read each one into a variable.
The next 9 are a matrix, so you read them in a loop into a 3x3 matrix, etc...
There is one bit in your question which is kind of an eyebrow raiser:
"inputs and outputs are arbitrary single floats, arrays or matrices". This is going to add some complexity but maybe there is no way around that.
An .Xml file format is a good choice because it gives you a lot of flexibility and you can import/export your tests in an editor to help you make sense of it.
But perhaps an even better choice is a .JSON file format. It offers the same flexibility as a xml files but is not as heavy weight. There are open source libraries available to work with them in C and I'm sure matlab can export data in this format as well.

Read a line of c code from file and execute in a c program

I have a C program which calculates f(x) for some x values (main.c). I need to get a line of c code from file and that code is my function to execute (function.dot). For example function.dot will contain:
pow((1-x), 0.333);
I need to read this file, get that function and execute in my code (main.c). How can I do that?
Basic steps would be:
Read the line from the file.
Generate a new source file which wraps the line of code inside appropriate code.
Invoke a compiler to compile that code into a shared object/dll.
Load the library.
Call the function in the library.
If the single line of code in the file could be any language, it would be far easier to use something like Lua that can be linked into your main executable.
I will provide some options:
Switch to another interpreted language including python, ruby, perl, ...
If you are working on small project, I recommend this option.
Implement your own interpreter in C.
Parse your input, analyze it, execute it. You might find open source implementations: one choice is slang
http://www.jedsoft.org/slang/doc/html/slang.html
Call C compiler and dynamically link it.
It depends on your operating system but system or exec functions help you to call your compiler to handle your input file. If you are using Linux, dlsym can open a shared-object compiled from your input file.
You might need to convert your input file into C program.
Very slow to compile but fastest to run.
You have several options I can think of:
1) Switch to any number of interpreted langauges (python, perl, etc.) which support this as an easy mechanism. (Example: in python
data = open("function.dot").read()
x = 5
eval(data) #note that this is unsafe if you can't trust data, and you might also need to play with environment
)
2) You could wrap the code in it's own c file... something like (but with more error checking etc... you probably don't want to do this)
void generate_c_program(char *line)
{
FILE *fp = fopen("myfile.c","wt");
fprintf(fp,"#include <math.h>\nint main(char *argv, int argc) {\n double x = atof(argv[1]); printf(\"%f\",(%s));}\n");",line); //this is also unsafe if you can't trust data
fclose(fp);
//now execute gcc myfile.c
//now execute a.out
//optionally cleanup by deleting a.out and myfile.c
}
3) Effectively write your own compiler / parser (which may be fairly easy IF you've done this before and the number of functions / operations you need to support is small or may be a much bigger deal and will rather not fit in this answer)... the extensible way would be to use LEX/YACC or similar)

Create a MATLAB MEX file for a C program

I'm an experienced MATLAB user but totally new to C and MEX files. I have a complex program written in C that I need to call from within MATLAB. The program consists of a few dozen files in a folder, including one called main.c that processes inputs from the command line passes the results to other classes that do the actual calculations.
Normally, to install this program from the command line, I would run ./configure, make at the UNIX command prompt. Then, to run the program, ./runMyProgram -f input_file.txt -p some_parameters. The program takes a text file consisting of a list of numbers as input and prints a table of results in the command window. I want to feed the program a MATLAB array (instead of a .txt file) and get back an array (instead of a printed table of results).
I have read the MEX documentation from The Mathworks (which I found rather opaque), as well as some other "tutorials", but I am totally lost - the examples are for very simple, single-file C programs and don't really discuss how to handle a larger and more complicated program. Is it enough to replace the main.c file with a MEX file that does the same things? Also, how do I compile the whole package within MATLAB?
I would be grateful for any plain-English advice on where to start with this, or pointers to any tutorials that deal with the subject in a comprehensible way.
Yes. Normally replacing a main.c file with MEX file is the process. In your case since you already have complex build setup, it might be easier to build a library and then build a separate mex file which just links against this library. This will be much easier than building the whole thing using mex command. If you export the function you need to call from your library, you can call it from your mexFunction. mexFunction can do all the creation and reading of mxArrays. A simple sample mexFunction can be,
#include "mex.h"
// Include headers for your library
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
void* x = mxGetData(prhs[0]); // Assume one input. Check nrhs
plhs[0] = mxCreateDoubleMatrix(10,10,mxREAL); // Create 10x10 double matrix for output
void* y = mxGetData(plhs[0]);
yourLibraryFunction(x, y); // Read from x and write to y. Pass sizes in if needed
}

Matlab system function with a C executable

I have written a Matlab GUI for my C program. I thought about using MEX, but there are too many C files and C program requires a DLL to run.
So, instead I have the Matlab System function calling the executable with inputs, something like [status results] = system('executable "input 1" "input 2"'), which runs well, but I want real time output. results is just a percent output of how complete the program is, and I want to use this output for a GUI progress bar in Matlab.
The output does get stored into results, but only after the program is complete. Thus, making the progress bar pointless.
Is it possible to get the executable to send outputs one at a time to Matlab, and then have Matlab update the progress bar, and return to the executable?
Edit: I'm looking for a solution in Windows.
I only see two options, and neither fits directly with your current implementation approach.
The first, is to just use sockets to communicate between the two. Here's a pure matlab socket implementation, but under the hood it's using C sockets. It's been 10 years since I've done C/Java socket comms, but I recall that at the time there were some issues.
http://www.mathworks.com/matlabcentral/fileexchange/21131-tcpip-socket-communications-in-matlab
Another option is to have your executable be accessible via a C DLL from matlab, and call the DLL directly from matlab (i.e. have matlab control your app). This is the way I've been doing most such interactions lately, and it works very well.
http://www.mathworks.com/help/techdoc/ref/loadlibrary.html
I found a solution. Credit goes to Richard Alcock at Matlab Central
Specifically, for my solution:
cmd = {'executable.exe', 'input 1', 'input 2'};
processBuilder = java.lang.ProcessBuilder(cmd);
cmdProcess = processBuilder.start();
% Set up a reader to read the output from the command prompt
reader =
java.io.BufferedReader(...
java.io.InputStreamReader(...
cmdProcess.getInputStream() ...
) ...
);
% Loop until there is some output
nextLine = char( reader.readLine );
while isempty(nextLine)
nextLine = char( reader.readLine );
end
% Then loop until there is no more output
while ~isempty(nextLine);
fprintf('Output: %s\n', nextLine);
nextLine = char( reader.readLine );
end
% Get the exit value of the process
exitValue = cmdProcess.exitValue
Note: this code does not hold up the executable. The executable must finish before this code finishes, otherwise this code crashes when it gets ahead of the executable.

Resources