How to refresh graph after change of parameter value in Scilab application? - scilab

I tried to make a simple application which solves ode for given starting value y_0.
For example we can have:
dy/dt = -2ty
Using some tutorials (scilab site and a youtube tutorial) I arrive at current version:
function dy = f(t,y)
dy = -2*t*y;
endfunction
function updatePlot()
clf(right)
y0 = get(y0CONTROL,"value");
t0 = 0;
t = 0:0.1:10
solution = ode(y0,t0,t,f);
plot(solution, right)
endfunction
gui = figure();
gui.visible = "on";
gui.immediate_drawing = "on";
left = uicontrol(gui,...
'style','frame',...
'layout','gridbag',...
'constraints', createConstraints('border', 'left',))
right = uicontrol(gui,...
'style','frame',...
'layout','border',...
'constraints', createConstraints('border', 'center'))
y0CONTROL = uicontrol(left, ...
'style','slider', ...
'max', 10, ...
'min', -10, ...
'value',-1,...
'callback', 'updatePlot')
updatePlot()
As one can see I attempted to use clf(right) to clear previous graph and plot(solution,right) to plot in now presumably empty right frame.
And yet this attempt fails - old lines stay on the graph after movement of the slider.
Please tell me how to correct this.

a more smooth solution is just to change the curve data:
function updatePlot()
y0CONTROL;
y0 = y0CONTROL.value
curve=y0CONTROL.user_data
t0 = 0;
t = 0:0.1:10
solution = ode(y0,t0,t,f);
if curve==[] then //first call
plot(t,solution)
curve=gce().children(1); //the handle on the curve
y0CONTROL.user_data=curve;
else //other calls
ax=gca();
ax.data_bounds(:,2)=[min(solution);max(solution)];
curve.data(:,2)=solution.';
end
endfunction
gui = figure();
ax=gca();
gui.visible = "on";
gui.immediate_drawing = "on";
y0CONTROL = uicontrol(gui, ...
'style','slider', ...
'position',[20 20 100 20],...
'max', 10, ...
'min', -10, ...
'value',-1,...
'callback', 'updatePlot()',...
'user_data',[])
ax.background=-2;
updatePlot()

It turns out that refreshing effect can be achieved by substituting
clf(right)
with
current_axes = gca()
delete(current_axes)
This was useful.

Related

scilab, passing parameters to the function and changing variable type

I'm trying to build a GUI to output plots for control system design when input parameters of transfer function.I got some problems on passing parameters to the function and changing variable type.
I've got a stucture with examples of simulation parameters:
param = [];
param.parameter = "s";
param.dom = "c"; //domain(c for continuous, d for discrete)
param.num = 1; //numerator of transfer function
param.den = "(s+1)^3"; //denominator
param.fmin = 0.01; //min freq of the plot
param.fmax = 100; //max freq
and a function to plot the graphs:
// display function
function displayProblem(param)
parameter = param.parameter;
dom = param.dom;
num = param.num;
den = param.den;
fmin = param.fmin;
fmax = param.fmax;
s = poly(0,parameter.string);
h = syslin(dom.string,num,den);
// Plotting of model data
delete(gca());
//bode(h,fmin1,fmax1);
gain_axes = newaxes();
gain_axes.title.font_size = 3;
gainplot(h,fmin,fmax);
gain_axes.axes_bounds = [1/3,0,1/3,1/2];
gain_axes.title.text = "Gain Plot";
phase_axes = newaxes();
gain_axes.title.font_size = 3;
phaseplot(h,fmin,fmax);
phase_axes.axes_bounds = [1/3,1/2,1/3,1/2];
phase_axes.title.text = "Phase Plot";
phase_axes = newaxes();
gain_axes.title.font_size = 3;
nyquist(h);
phase_axes.axes_bounds = [2/3,0,1/3,1/2];
phase_axes.title.text = "Nyquist Plot";
endfunction
There's something wrong when passing numerator and denominator to the function. The variable type doesn't match what syslin required. If I replace 'num' and 'den' with '1' and '(s+1)^3', everything worked quite well. Also if I try this line-by-line in control panel, it works, but not in SciNotes. What's the proper way to deal with this? Any suggestion will be greatly appreaciated.
There are 3 errors in your code: Replace
param.den = "(s+1)^3"; //denominator
with
param.den = (%s+1)^3;
Indeed, Scilab has a built-in polynomial type. Polynomials are not defined as a string nor as a vector of coefficients. The predefined constant %s is the monomial s.
In addition,
s = poly(0,parameter.string);
is useless (and incorrect: parameter would work, while parameter.string won't since parameter has no string field: It IS the string). Just remove the line.
As well, replace
h = syslin(dom.string,num,den);
with simply
h = syslin(dom, num,den);
Finally, although the figure's layout is not simple, you can use bode() in the function in the following way:
// delete(gca());
subplot(1,3,2)
bode(h, fmin, fmax)
subplot(2,3,3)
nyquist(h)
gcf().children.title.text=["Nyquist Plot" "Phase Plot" "Gain Plot"]
All in one, the code of your function may resume to
function displayProblem(param)
[dom, num, den] = (param.dom, param.num, param.den);
[fmin, fmax] = (param.fmin, param.fmax);
h = syslin(dom, num,den);
// Plotting of model data
subplot(1,3,2)
bode(h,fmin,fmax);
subplot(2,3,3)
nyquist(h);
gcf().children.title.text=["Nyquist Plot" "Phase Plot" "Gain Plot"];
endfunction
Best regards

How to put background image to the plot in Rust plotters lib

I'm trying to draw car trips on a plane. I'm using Plotters library.
Here is some code example of trips' drawing procedure:
pub fn save_trips_as_a_pic<'a>(trips: &CarTrips, resolution: (u32, u32))
{
// Some initializing stuff
/// <...>
let root_area =
BitMapBackend::new("result.png", (resolution.0, resolution.1)).into_drawing_area();
root_area.fill(&WHITE).unwrap();
let root_area =
root_area.margin(10,10,10,10).titled("TITLE",
("sans-serif", 20).into_font()).unwrap();
let drawing_areas =
root_area.split_evenly((cells.1 as usize, cells.0 as usize));
for (index, trip) in trips.get_trips().iter().enumerate(){
let mut chart =
ChartBuilder::on(drawing_areas.get(index).unwrap())
.margin(5)
.set_all_label_area_size(50)
.build_ranged(50.0f32..54.0f32, 50.0f32..54.0f32).unwrap();
chart.configure_mesh().x_labels(20).y_labels(10)
.disable_mesh()
.x_label_formatter(&|v| format!("{:.1}", v))
.y_label_formatter(&|v| format!("{:.1}", v))
.draw().unwrap();
let coors = trip.get_points();
{
let draw_result =
chart.draw_series(series_from_coors(&coors, &BLACK)).unwrap();
draw_result.label(format!("TRIP {}",index + 1)).legend(
move |(x, y)|
PathElement::new(vec![(x, y), (x + 20, y)], &random_color));
}
{
// Here I put red dots to see exact nodes
chart.draw_series(points_series_from_trip(&coors, &RED));
}
chart.configure_series_labels().border_style(&BLACK).draw().unwrap();
}
}
What I got now on Rust Plotters:
So, after drawing it in the 'result.png' image file, I struggle to understand these "lines", because I don't see the map itself. I suppose, there is some way in this library to put a map "map.png" in the background of the plot. If I would use Python, this problem will be solved like this:
# here we got a map image;
img: Image.Image = Image.open("map-image.jpg")
img.putalpha(64)
imgplot = plt.imshow(img)
# let's pretend that we got our map size in pixels and coordinates
# just in right relation to each other.
scale = 1000
x_shift = 48.0
y_shift = 50.0
coor_a = Coordinate(49.1, 50.4)
coor_b = Coordinate(48.9, 51.0)
x_axis = [coor_a.x, coor_b.x]
x_axis = [(element-x_shift) * scale for element in x_axis]
y_axis = [coor_a.y, coor_b.y]
y_axis = [(element-y_shift) * scale for element in y_axis]
plt.plot(x_axis, y_axis, marker='o')
plt.show()
Desired result on Python
Well, that's easy on Python, but I got no idea, how to do similar thing on Rust.

(R) Error in optim - attempt to apply non-function, when function is defined

not sure what I'm doing wrong here. I'm trying to get a cross-validation score for a mixture-of-two-gammas model.
llikGammaMix2 = function(param, x) {
if (any(param < 0) || param["p1"] > 1) {
return(-Inf)
} else {
return(sum(log(
dgamma(x, shape = param["k1"], scale = param["theta1"]) *
param["p1"] + dgamma(x, shape = param["k2"], scale = param["theta2"]) *
1
(1 - param["p1"])
)))
}
}
initialParams = list(
theta1 = 1,
k1 = 1.1,
p1 = 0.5,
theta2 = 10,
k2 = 2
)
for (i in 1:nrow(cichlids)) {
SWS1_training <- cichlids$SWS1 - cichlids$SWS1[i]
SWS1_test <- cichlids$SWS1[i]
MLE_training2 <-
optim(
par = initialParams,
fn = llikGammaMix2,
x = SWS1_training,
control = list(fnscale = -1)
)$par
LL_test2 <-
optim(
par = MLE_training2,
fn = llikGammaMix2,
x = SWS1_test,
control = list(fnscale = -1)
)$value
}
print(LL_test2)
This runs until it gets to the first optim(), then spits out Error in fn(par, ...) : attempt to apply non-function.
My first thought was a silly spelling error somewhere, but that doesn't seem to be the case. Any help is appreciated.
I believe the issue is in the return statement. It's unclear if you meant to multiply or add the last quantity (1 - param["p1"])))) to the return value. Based on being a mixture, I'm guessing you mean for it to be multiplied. Instead it just hangs at the end which throws issues for the function:
return(sum(log(dgamma(x, shape = param["k1"], scale = param["theta1"]) *
param["p1"] +
dgamma(x, shape = param["k2"], scale = param["theta2"]) *
(1 - param["p1"])))) ## ISSUE HERE: Is this what you meant?
There could be other issues with the code. I would double check that the function you are optimizing is what you think it ought to be. It's also hard to tell unless you give a reproducible example we might be able to use. Try to clear up the above issue and let us know if there are still problems.

solve system of ODEs with read in external forcing

In Julia, I want to solve a system of ODEs with external forcings g1(t), g2(t) like
dx1(t) / dt = f1(x1, t) + g1(t)
dx2(t) / dt = f2(x1, x2, t) + g2(t)
with the forcings read in from a file.
I am using this study to learn Julia and the package DifferentialEquations, but I am having difficulties finding the correct approach.
I could imagine that using a callback could work, but that seems pretty cumbersome.
Do you have an idea of how to implement such an external forcing?
You can use functions inside of the integration function. So you can use something like Interpolations.jl to build an interpolating polynomial from the data in your file, and then do something like:
g1 = interpolate(data1, options...)
g2 = interpolate(data2, options...)
p = (g1,g2) # Localize these as parameters to the model
function f(du,u,p,t)
g1,g2 = p
du[1] = ... + g1[t] # Interpolations.jl interpolates via []
du[2] = ... + g2[t]
end
# Define u0 and tspan
ODEProblem(f,u0,tspan,p)
Thanks for a nice question and nice answer by #Chris Rackauckas.
Below a complete reproducible example of such a problem. Note that Interpolations.jl has changed the indexing to g1(t).
using Interpolations
using DifferentialEquations
using Plots
time_forcing = -1.:9.
data_forcing = [1,0,0,1,1,0,2,0,1, 0, 1]
g1_cst = interpolate((time_forcing, ), data_forcing, Gridded(Constant()))
g1_lin = scale(interpolate(data_forcing, BSpline(Linear())), time_forcing)
p_cst = (g1_cst) # Localize these as parameters to the model
p_lin = (g1_lin) # Localize these as parameters to the model
function f(du,u,p,t)
g1 = p
du[1] = -0.5 + g1(t) # Interpolations.jl interpolates via ()
end
# Define u0 and tspan
u0 = [0.]
tspan = (-1.,9.) # Note, that we would need to extrapolate beyond
ode_cst = ODEProblem(f,u0,tspan,p_cst)
ode_lin = ODEProblem(f,u0,tspan,p_lin)
# Solve and plot
sol_cst = solve(ode_cst)
sol_lin = solve(ode_lin)
# Plot
time_dense = -1.:0.1:9.
scatter(time_forcing, data_forcing, label = "discrete forcing")
plot!(time_dense, g1_cst(time_dense), label = "forcing1", line = (:dot, :red))
plot!(sol_cst, label = "solution1", line = (:solid, :red))
plot!(time_dense, g1_lin(time_dense), label = "forcing2", line = (:dot, :blue))
plot!(sol_lin, label = "solution2", line = (:solid, :blue))

Torch nn. Current error always is nan

I've wrote the following code:
require 'nn'
require 'cunn'
file = torch.DiskFile('train200.data', 'r')
size = file:readInt()
inputSize = file:readInt()
outputSize = file:readInt()
dataset = {}
function dataset:size() return size end;
for i=1,dataset:size() do
local input = torch.Tensor(inputSize)
for j=1,inputSize do
input[j] = file:readFloat()
end
local output = torch.Tensor(outputSize)
for j=1,outputSize do
output[j] = file:readFloat()
end
dataset[i] = {input:cuda(), output:cuda()}
end
net = nn.Sequential()
hiddenSize = inputSize * 2
net:add(nn.Linear(inputSize, hiddenSize))
net:add(nn.Tanh())
net:add(nn.Linear(hiddenSize, hiddenSize))
net:add(nn.Tanh())
net:add(nn.Linear(hiddenSize, outputSize))
criterion = nn.MSECriterion()
net = net:cuda()
criterion = criterion:cuda()
trainer = nn.StochasticGradient(net, criterion)
trainer.learningRate = 0.02
trainer.maxIteration = 100
trainer:train(dataset)
And it must works good (At least I think so), and it works correct when inputSize = 20. But when inputSize = 200 current error always is nan. At first I've thought that file reading part is incorrect. I've recheck it some times but it is working great. Also I found that sometimes too small or too big learning rate may affect on it. I've tried learning rate from 0.00001 up to 0.8, but still the same result. What I'm doing wrong?
Thanks,
Igor

Resources