Author Topic: C Programming. Plotting/Visualizing. Seeking recommended direction(s)  (Read 4588 times)

0 Members and 1 Guest are viewing this topic.

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9941
  • Country: us
I have recently gotten involved with Applied Mathematics as a result of my grandson changing majors.  They will focus on two tools:
Python with its various libraries and
R and RStudio for statistics.

Attached is an example from the text: "Data Science Using Python and R" by Larose and Larose
https://www.amazon.com/gp/product/1119526817

The script is over on the left, the print output is on the right, underneath the graph.

There is nothing interactive about it but I must say, the libraries for Python are terrific.  And it's free...

And that is a very expensive book.  Expensive but worth every dime!

Writing something in C# wouldn't be my first choice for visualization although buttons, knobs and dials should be fairly easy.  I'm firmly of the opinion that MATLAB or Octave is the way to go.  For knobs and dials, MATLAB/Simulink or even MATLAB/Arduino.  I can set up a physical model with real knobs and real output and drive it from the Arduino.  I haven't done it but I suspect it would be possible to use MATLAB inside a control loop and tweak the settings in real time.
 

Offline wizard69

  • Super Contributor
  • ***
  • Posts: 1184
  • Country: us
The easy way to visualize data is to write the data to a file and plot it with a good plotting program.   I can't remember the lat one I used but it was just a plot from a scope download that could be saved as a JPeg to include in some mail.   Since plotting programs can often be had for free, everybody should have one of more installed.

If you are into C++ then what you probably should look into is ROOT: https://root.cern.ch/.   This huge package and has visualization elements in it.   There is plenty of documentation, some of it CERN specific, but enough to get you started.   This is probably not the best place to go if you want a quick graph of some static data.

One option I never have actually used is VTK: https://vtk.org/about/#overview.   Seems to be popular though.

The last bit of programming I did was via Python with Matplotlib: (https://matplotlib.org) in Jupyter.   That is actually an interesting way to program and has a pleasant ease of use.   What I was plotting was Archimedean spirals, to learn Matplotlib and Jupyter; code of which I promptly lost due to a self inflicted error.   If you are conversant in Python (who isn't) Python and Matplotlib might be a good solution.   Jupyter has a nice that might not work for you but it could be worth looking into.   The good thing is neither matplolib nor Python actually need Jupyter.

In the past I've tired Excel and it frankly sucked for what I was trying to accomplish.   Spreadsheets in general don't seem to understand plotting outside of the financial world.

You indicate that you only know C++, this might be a good time to explore Python and the world of scripting.   Python and matplotlib can be extremely powerful, and quick to use.   I can't say I'm an expert but it is hard to beat Python for quick correct programs.   If I was to suggest a package to anybody with modest needs it would be to go matplotlib and Python.   By the way matplotlib is not the only Python way to turn data into charts or graphs.

I'm working with pointers to pointers and structures, so I know some C programming. I don't know anything about other languages. I want to visualize/plot some code/graphs, for example, my A* algorithm, and Charging and Discharging Equations for Capacitors and the Voltage and Current of Inductors, developing my programs and skills and electrical engineering projects.
I did some searching and was not excited by what I saw (Xlib and gnu), although I saw a .java visualization of A* and it was pretty. Again, I don't know anything about other languages. I wonder if I could link my C code to a .java code. So that's what I am interested in.
Please let me know anything you know. Thanks.  :)
 

Offline RenThraysk

  • Regular Contributor
  • *
  • Posts: 107
  • Country: gb
If wanting interactive visualisations then might want to consider javascript.

In particular Mike Bostock's D3.

Gallery of examples
 
Some of the algorithms visualizations are impressive/
Visualizing Algorithms
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9941
  • Country: us
I'm pretty confident with MATLAB but wxMaxima is another package that is free.  Again, it won't support interactive control.

Attached is a plot and the Fortran source to create it just as I did plots back in the early '70s on an IBM 1130 with CalComp drum plotter.  It is tedious!

But, for a young fellow working through college, I was one of the only students with unlimited access to a real computer.

I did this as an example for my grandson when he took Algebra a few years ago.  I have an FPGA version of the IBM1130 which runs all of the factory code unchanged.  The Fortran to create the plot is mine and it uses the plotter library provided by IBM.

If I wasn't in a hurry, I would use this approach for just about all of my plotting needs.  Retro is cool!  Not recommended if productivity is a factor but cool nevertheless.

« Last Edit: June 20, 2020, 11:19:54 pm by rstofer »
 

Online Nominal Animal

  • Super Contributor
  • ***
  • Posts: 7004
  • Country: fi
    • My home page and email address
One reason why I love to use Graphviz and Gnuplot as external plotters, is that they support a huge number of different output formats – including PS, EPS, PDF, and SVG, the most important vector formats.  (You might be surprised to see SVG in that list, but being able to get a publication-quality output in SVG format, then edit/finesse it in Inkscape, and finally save as a rather small EPS/PDF, is actually a known-reliable, known-good-output workflow.)

In case you think gnuplot produces crude or ugly output, take a look at the examples.

When you want your program to generate the graphs, it is best to save the output to a file with a fixed name, and put the gnuplot script needed to generate the desired graphs in a separate file, and in the C program, just run system("gnuplot < script.gp") to have gnuplot generate the corresponding files.  That way, you can finesse the plots without having to recompile your program.

Generally, I use a Makefile to organize my projects.  I make all the default target (by defining it very first), and it'll clean, build, run, and plot the data.  The plotting part runs gnuplot either directly (redirecting input from a script), or via a shell script (if it generates a large number of plots).

During development, it is useful to run gnuplot (it then acts like a shell of a sort).  The plot window is then interactive, and you can zoom into details (and rotate 3D plots).  You can run scripts from the gnuplot "shell" using the load "script" command.  Also, gnuplot supports quite complex functions and least squares fitting of univariate data to arbitrary functions, making it way more than just a plotting toolkit.
 

Offline gcewing

  • Regular Contributor
  • *
  • Posts: 203
  • Country: nz
Another possibility is the Geogebra Graphing Calculator:

https://www.geogebra.org/graphing

You can use it to set up interactive graphs with input sliders. Free and multi-platform. Browser and offline versions are available.
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9941
  • Country: us
It is my understanding that wxMaxima is the solver of choice at CERN.  In any event, they are deeply involved with the design and implementation.

Here is a simple RC charging program and plot.  Note the call to gnuplot!

Code: [Select]
(%i7) R:6.8*10^3$         /* 6.8k resistor            */
C:10*10^-6$         /* 10 microfarad capacitor  */
Tau:R*C;            /* time constant Tau=R*C    */
SixTau:6*Tau;
Vapplied:100$       /* applied voltage is 100 to make
                       % scale on graph         */
                    /* equation for Vout(t)     */
Vout(t):=Vapplied*(1-%e^(-(t/Tau)))$
t(tau):= tau * Tau$ /* graph x axis is in units of Tau
                       convert to units of t for calculation */
(Tau) 0.068
(SixTau) 0.408
(%i8) plot2d([Vout(t(x))], [x,0,6], [y,0,Vapplied],
[xlabel,"Tau" ],[ylabel,"% Charge"],
[gnuplot_postamble, "set grid;
set title 'Capacitor Voltage';"])$

« Last Edit: June 21, 2020, 03:47:02 pm by rstofer »
 

Offline orolo

  • Frequent Contributor
  • **
  • Posts: 352
  • Country: es
Lots of good suggestions in the thread.

I've been through quite a lot of iterations: BASIC in high school; FORTRAN-77 and Mathematica in college; C & gnupplot, tikz & LaTeX (with some batch processing), maxima, maple and Python afterwards. All of them could work, but IMO some of them are more productive than others.

I wouldn't use C for general scientific computing. Too low level, and memory allocation and pointers make things difficult. You need to be a competent C programmer (most people aren't, me included) to write good numerical C. I think the mess with the Imperial College pandemic code is a recent and illustrative example. I've seen things like that before, e.g. choosing bisection as equation solving algorithm because the programmer couldn't, for the life of him, implement Newton-Raphson without random crashes or inconsistent output. Yes, there are good numerical libraries available in C, but that takes us to the next point.

I currently use Python + Numpy + Scipy + Matplotlib when I need numerical work done. Just install Python and then install these libraries following the instructions in the webpages (typically, use pip from the command line). There are also portable scientific pythons ready for download, with all the packages bundled.

Python works well. For example, a couple of weeks ago I wanted to do a quick check on period doubling. I implemented the Rössler attractor in a few minutes, just modifying an example for a simple dynamical system I found with a search engine. The result:

Code: [Select]
# Parámetros de Rössler.
a = 0.2
b = 0.2
c = 5.7

# Derivada.
def model(v, t):
    xp = -v[1] - v[2]
    yp = v[0] + a * v[1]
    zp = b + v[2] * (v[0] - c)
    return [xp, yp, zp]

# Construir solución completa:
def flujo(v0, t):
    v = odeint(model, v0, t)

    x = np.zeros(len(v))
    y = np.zeros(len(v))
    z = np.zeros(len(v))

    for k in range(0, len(v)):
        x[k] = v[k][0]
        y[k] = v[k][1]
        z[k] = v[k][2]

    return [x, y, z]

t = np.linspace(t0, t1, N)  # tiempo

a = 0.2
s2 = flujo([-6,-2,0] , t)

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(s2[0], s2[1], s2[2], label='a=0.2')
ax.legend()
plt.show()

The output (can be freely rotated and magnified, and saved to disk):

1005542-0

Note how the odeint command in Python uses a very customizable and high performance low level library to integrate the ODE. Python just does the gluing.

I've also used Arduino + Python + serial interface + matplotlib to plot, in real time, the output of a 24-bit ADC. Here is a link to a youtuber who does something similar with arduino's 10- ADC:



It's quite easy to do. Python also runs under window, linux and embedded systems, like raspberry pi and friends. You can mix matplotlib graphs and LaTeX if you want high quality formulas in your graphs.

Another  example: I've recently used Python to load a .wav sound file captured with a microphone, and analyzed its spectrum for a simple Doppler effect experiment. Just a few lines of code.

And you don't need to be a Python wizard. I'm neither a competent python programmer.

« Last Edit: June 21, 2020, 05:02:52 pm by orolo »
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 9941
  • Country: us
Part of the criteria was 'interactive'.  It seems to me that most of these methods could produce a family of curves whether written in Python, MATLAB, or any of the others.  Just keep looping until the user gets bored.

In the case where the program creates the dataset, it's really easy to plot a family of curves.  It is only slightly more complex when the data is coming in from a file.

Today, Python is probably the best way to go if the cost of MATLAB is an issue.  Heck, for simple math, Python is probably the better solution.  Integrating with Simulink is a separate issue and applies only to MATLAB.
 

Offline wizard69

  • Super Contributor
  • ***
  • Posts: 1184
  • Country: us
One of the reasons I like Python is that with my sporadic programming I can come back to code written days ago or years ago and understand the program without spending a lot of time parsing the code.   I even have a good chance of understanding somebody else code fairly quickly.    With languages like C or C++ you can run into a lot of cryptic code that requires studying at best to understand.   Of course that is often the fault of the guy that wrote the code.

From my perspective, at this point in time, just about any engineer or technician should have Python in their tools set.    I call it a tool because it basically is.
 

Offline orolo

  • Frequent Contributor
  • **
  • Posts: 352
  • Country: es
Part of the criteria was 'interactive'.  It seems to me that most of these methods could produce a family of curves whether written in Python, MATLAB, or any of the others.  Just keep looping until the user gets bored.
You are right, I got a bit off-topic. Thank you.

With respect to interactivity, you can integrate matplotlib into Tkinter, which is a de-facto standard multiplataform window environmet, quite easy to use. In this link there is a programmer who visualizes real-time bitcoin data with matplotlib+tkinter. Just as easily you can implement some sliders in your tkinter app, and update the matplotlib graph interactively. I've used tkinter rather often and it's easy; never needed to use it together with matplotlib, though.


Another part of the criteria was easy interactivity with code already written in C. It's very easy to interface your own C code from Python, here is the link to the C FFI in Python 3.8. I've done this before, but some years ago (in the times of Python 2.6), and I remember it being easy.
« Last Edit: June 21, 2020, 07:14:50 pm by orolo »
 

Offline nuclearcat

  • Supporter
  • ****
  • Posts: 382
  • Country: lb
Unlikely simple plain-C library exist, but for C++ there is some.Sure if it is possible to convert your project from C to C++.

https://github.com/lferry007/LargeVis
VTK https://lorensen.github.io/VTKExamples/site/Cxx/
Also C++ header only library for mathlib plotting https://github.com/lava/matplotlib-cpp
 

Offline ebclr

  • Super Contributor
  • ***
  • Posts: 2331
  • Country: 00
 

Offline Aman12011

  • Newbie
  • Posts: 1
  • Country: in
update the matplotlib graph interactively. I've used tkinter rather often and it's easy; never needed to use it together with matplotlib, though.
sad shayari

« Last Edit: July 12, 2020, 11:11:52 am by Aman12011 »
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf