Running system commands and redirecting IO in julia

All languages have the means to call system commands, which means that the programs that you write can interact with and use other programs on your computer.

I like gnuplot, it is a powerful yet lightweight (and free) program for making very high quality graphs. Julia has several libraries or modules that interact with gnuplot, such as Gaston and Winston, but you can write your own using interprocess communication.

Lets generate some data and pipe it into gnuplot using julia. We will open gnuplot with a switch “-persistent” so that our plot does not disappear the instant that it is completed, it will stay open until we physically close it. We also need to pass it an option string for the plot, and create an IO stream to pipe the data points into it

x=[0.05*j for j in 1:100]
y=sin.(x)
str="plot \'-\'  with points pointtype 5 ps 1"
println(str) 


open(`gnuplot -persistent`, "w", stdout) do io
 println(io,str)
 for i = 1:length(x)
  println(io, x[i], " ", y[i])
  end
 println(io,"e")
end

That’s it, no need to call Gaston or any other plotting library.

I also like gnu plotutils and its command line program ode which is a filter that will read a file of commands in a very simple language, and apply fourth order Runge Kutta integration with adaptive step-size to integrate the EOMs that the file describes. We will open a pipeline to ode and squirt the descriptor file to it as a string, and open a second stream to redirect the sdout that ode produces to a file (julia 1.7 will have true pipes so we won’t need the fileĀ  step in the future but I am running julia 1.6). We then read the file into vectors and plot with Gaston:

str="g=9.8
L=3
w=0.2
x'=p
y'=q
p'=-(g/L)*x+2*w*q
q'=-(g/L)*y-2*w*p
p=0
q=0
x=1
y=1
print x,y
step 0,10
."

open("/tmp/stdout", "w") do io1
redirect_stdout(io1) do
open(`ode`, "w", stdout) do io
 println(io,str)
end
end
end

using DelimitedFiles,Gaston,DataFrames
myarray=open(readdlm,"/tmp/stdout")
dat=DataFrame(x=vec(myarray[:,1]),y=vec(myarray[:,2]))
plot(dat.x,dat.y)

As Red Green says, “It’s just that easy”.

See you next time. Keep your stick on the ice.

Home 2.0
error: Content is protected !!