How to realise the backflow from one volume to the upper volume by modelica language? - modelica

It is a simple idea that I Want to solve the same equations in a finite volume when the variable x of next volume is computed smaller than 0. Because the characteristic of the modelica language, it is really hard for me to realise the loop. I hope someone can help me with this. Thanks!
model Model
parameter Real L = 10;
parameter Real r = 5;
parameter Integer N = 20;
Real x[N](each start = 0);
equation
if noEvent(x[1] >= 0 and x[1] < L) then
der(x[1]) = r;
else
der(x[1]) = 0;
end if;
for i in 2:N loop
if noEvent(x[i - 1] >= L and x[i] >= 0 and x[i] < L) then
der(x[i]) = r - 1 * time;
elseif noEvent(x[i] < 0) then
der(x[i - 1]) = r - x[i - 1];
else
der(x[i]) = 0;
end if;
end for;
end model;
The code just can not dostep when time > 8s.
And the Mworks show the message:
...
Error: Failed to solve linear system at Time = 7.99999989157494
Error: Failed to solve linear system at Time = 7.99999989157489
Error: Failed to solve linear system at Time = 7.99999989157489

I have no Mworks, but Dymola. If we simulate your code in Dymola, we get the following error message:
Error: The following error was detected at time: 7.99999999711724
Error: Singular inconsistent scalar system for
der(x[2]) = ( -(if x[1] >= 10 and x[2] >= 0 and x[2] < 10 then 1*time-5 else (if x[2] < 0 then der(x[1])+x[1]-5 else 0.0)))/((if x[1] >= 10 and x[2] >= 0 and x[2] < 10 then 1.0 else (if x[2] < 0 then 0.0 else 1.0))) = -5/0
Looking in detail at the equation for x[2], we see that for x[2] < 0 we have
der(x[2]) = - (der(x[1])+x[1]-5) / 0
This originates from the elseif in your for loop, where you write:
elseif noEvent(x[i] < 0) then
der(x[i - 1]) = r - x[i - 1];
Here you only use the derivative of the previous vector element, while you are using der(x[i]) in the other if branches.
The modelica tool needs valid equations in all if branches.
My guess is, that it adds 0 * der(x[i]) to be able to create a solvable equation set.
So your equation in the elseif branch is extended by the tool to
0 * der(x[i]) + der(x[i - 1]) = r - x[i - 1]
And after causalization of the equations we get:
der(x[i]) := - (der(x[i - 1]) - r + x[i - 1]) / 0
To avoid the division by zero, you have to rewrite your for loop such that you are using der(x[i]) in every branch of the if statement. Here is an example how this could look like:
model Model2
parameter Real L = 10;
parameter Real r = 5;
parameter Integer N = 20;
Real x[N](each start = 0);
equation
if x[1] >= 0 and x[1] < L then
der(x[1]) = r;
else
der(x[1]) = 0;
end if;
for i in 2:N-1 loop
if x[i - 1] >= L and x[i] >= 0 and x[i] < L then
der(x[i]) = r - 1 * time;
elseif x[i+1] < 0 then
der(x[i]) = r - x[i];
else
der(x[i]) = 0;
end if;
end for;
if x[N - 1] >= L and x[N] >= 0 and x[N] < L then
der(x[N]) = r - 1 * time;
else
der(x[N]) = 0;
end if;
end Model2;
The elseif branch now looks ahead at the next element. This requries that the the last element of xis handled in seperate equations, like you already do with the first one.
This code now simulates beyond 8s, but there seem to be some troubles with your equations. Nothing is happening after 8s, because x[2] never reaches L. I guess you have to rethink the equation der(x[i]) = r - 1 * time (or the complete model) to solve that.
Note that I also removed all the noEvent() operators, because I expect your model to run better with state events.

Related

Matlab, k = 1.000000000000000 but k == 1 returns 0

I already read the other discussion here on SO but I still cannot understand why the code does not work as expected.
In my code I check that k is approximately equal to 1, but still it does not work:
if approx(k, 1, eps)
display('Approx equal');
else
k
k == 1
approx(k, 1, eps)
abs(k - 1) < eps
end
Instead of displaying the string, this is the result (I have enabled format long):
k = 1.000000000000000
ans = 0
ans = 0
ans = 0
This is baffling! I also tried to increase the error by k * 1e20 but the result is still 1e20... What to do here?
Note: although not really relevant to the question, here is the definition of approx:
function r = approx(a, b, tol)
r = a <= b + tol && a >= b - tol;
end
EDIT: I changed the approx function to avoid catastrophic cancellation:
function r = approx(a, b, tol)
r = a <= b + tol && a + tol >= b; % assumes tol is positive
end
Try displaying:
k - 1.000000000000000
I think you will find that there is a tiny but non-zero residual value.

Only allow fixed number of random points in each tile

Following up on a previous question, I have code that I think should limit the number of randomly generated points in each quadrant of the total tile; however, it is not working.
n = 4;
used = [];
k = 0;
a1_count = 0;
a2_count = 0;
a3_count = 0;
a4_count = 0;
min = 1;
max = 1;
while k<n
x = rand*2;
y = rand*2;
notvalid = 0;
if (0 <= x) && (x <= 1) && (0 <= y) && (y <= 1)
a1_count = a1_count + 1;
end
if (1 < x) && (x <= 2) && (0 <= y) && (y <= 1)
a2_count = a2_count + 1;
end
if (0 <= x) && (x <= 1) && (1 < y) && (y <= 2)
a3_count = a3_count + 1;
end
if (1 < x) && (x <= 2) && (1 < y) && (y <= 2)
a4_count = a4_count + 1;
end
%%%
if (min <= a1_count) && (a1_count <= max) && (min <= a2_count) && (a2_count <= max)...
&& (min <= a3_count) && (a3_count <= max) && (min <= a4_count) && (a4_count <= max)
notvalid=1;
end
if notvalid
continue
end
used(end+1,:) = [x;y];
k = k+1;
end
I wish to generate 4 random points, and have one in each quadrant of the total area. To do this, I have a maximum and minimum number of points in each quadrant (in this case 1), and an if statement to check that the count for each tile falls within the min and max. If it doesn't, then notvalid = 0 and the loop should begin again. This function doesn't seem to work however, as the loop finishes with 4 points total and is completely random (all the counts should = 1).
Can anyone spot where I'm going wrong?
I may be missing something, but the easiest approach would probably be something like
Select N random numbers within the x/y range of the first grid cell
Repeat for all grid cells
Here is some basic code that should create N random x/y points per grid cell
% Define the grid (for demonstration purposes)
dx = 1; dy = 1;
xrange = 0:dx:2;
yrange = 0:dy:2;
% Number of points per cell
N = 1;
[lowerx, lowery] = meshgrid(xrange(1:end-1), yrange(1:end-1));
% Store all those random numbers in a cell
data = cell(size(lowerx));
for k = 1:numel(lowerx);
% Generate 4 random points within the x/y range
xcoord = (rand(N, 1) * dx) + lowerx(k);
ycoord = (rand(N, 1) * dy) + lowery(k);
data{k} = [xcoord, ycoord];
end
disp(data)
data =
[1x2 double] [1x2 double]
[1x2 double] [1x2 double]
EDIT
To address your question directly using the code that you have provided, the logic in the code in your question is a little wonky. I have rewritten your while loop to be a little clearer so we can talk through it.
while k < n
x = rand * 2;
y = rand * 2;
if y >= 0 && y < 1
if x >= 0 && x < 1
a1_count = a1_count + 1;
else
a2_count = a2_count + 1;
end
else
if x >= 0 && x < 1
a3_count = a3_count + 1;
else
a4_count = a4_count + 1;
end
end
counts = [a1_count, a2_count, a3_count, a4_count];
notValid = all(counts >= minimum) && all(counts <= maximum);
if notValid
continue;
end
used(end+1,:) = [x;y];
k = k+1;
end
So the biggest thing is your notValid check. If you actually look at what you're checking (that all your *_count variables are within the pre-specified limits), I believe that if all of those conditions are true, then the current point is valid; however you state just the opposite.
Then you basically say, that if the current x y is valid, then add it to the used list. Well this logic is fine except that you define validity backwards as I stated before.
Ok so that aside, let's look at when you think that a point is not valid. Well, then you (correctly) go to the next iteration, but you never decrement the *_count variable. So say you had 1 point in quadrant 1 already and the second iteration through the loop it's in quadrant 1 again. Well you'd add 1 to a1_count and then see that it isn't valid (a1_count exceeds max) and go to the next loop, but a1_count stays at 2 despite really only having 1 because you just rejected it.
Now, all of that aside. Let's consider the first time through your loop and look at your validity check. Since you only add one point. Your validity check can never pass (if implemented correctly) because all *_count variables except the one that was just incremented will be less than the min.
So I think what happened is you probably did the validity check correctly at first, ended up with an infite while loop, and then negated that check, didn't get an infinite loop, but as a result got an incorrect solution.
The solution that you are getting currently, is literally the first 4 times through the while loop due to the incorrect logic.
If you really like your current approach, we can clean up the code to be correct.
n = 4;
used = zeros(0,2);
minimum = 1;
maximum = 1;
counts = [0 0 0 0];
while true
x = rand * 2;
y = rand * 2;
if y >= 0 && y < 1
if x >= 0 && x < 1
quadrant = 1;
else
quadrant = 2;
end
else
if x >= 0 && x < 1
quadrant = 3;
else
quadrant = 4;
end
end
% Check to see if we can even add this point
if counts(quadrant) + 1 > maximum
continue;
end
counts(quadrant) = counts(quadrant) + 1;
used = cat(1, used, [x, y]);
isComplete = all(counts >= minimum & counts <= maximum) && ...
size(used, 1) == n;
if isComplete
break
end
end

Gauss-Seidel code not converging on solution

I am unable to get converging values using a Gauss-Seidel algorithm
Here is the code:
A = [12 3 -5 2
1 6 3 1
3 7 13 -1
-1 2 -1 7];
b = [2
-3
10
-11];
ep = 1e-8;
[m, n] = size(A);
[n, p] = size(b);
x = zeros(n, 1001);
x(:, 1) = []
for k=0:1000
ka = k + 1;
if ka == 1001
break;
end
xnew = zeros(n,1);
for i=1:n
sum = 0;
j = 1;
while j < i
s1 = s1 + A(i,j) * x(j, ka + 1);
j = j + 1;
end
j = i + 1;
while j <= n
sum = sum + A(i,j) * x(j, ka);
j = j + 1;
end
xnew(i) = (b(i) - sum) / A(i, i);
% if result is within error bounds exit loop
if norm(b - A * xnew, 2) < ep * norm(b, 2)
'ending'
break
end
end
x(:,ka + 1) = xnew;
end
I cannot get the A * xnew to converge on b what am I doing wrong?
I have tried running this changing the syntax several times, but I keep getting values that are way off.
Thanks!
Gabe
You have basically two problems with your code:
(1) You are using two different variables "sum" and "s1". I replaced it by mySum. By the way, dont use "sum", since there is a matlab function with this name.
(2) I think there is also a problem in the update of x;
I solved this problem and I also tried to improve your code:
(1) You dont need to save all "x"s;
(2) It is better to use a "while" than a for when you dont know how many iterations you need.
(3) It is good to use "clear all" and "close all" in general in order to keep your workspace. Sometimes old computations may generate errors. For instance, when you use matrices with different sizes and the same name.
(4) It is better to use dot/comma to separate the lines of the matrices
You still can improve this code:
(1) You can test if A is square and if it satisfies the conditions necessary to use this numerical method: to be positive definite or to be diagonally dominant.
clear all
close all
A = [12 3 -5 2;
1 6 3 1;
3 7 13 -1;
-1 2 -1 7];
b = [2;
-3;
10;
-11];
ep = 1e-8;
n = length(b); % Note this method only works for A(n,n)
xNew=zeros(n,1);
xOld=zeros(n,1);
leave=false;
while(~leave)
xOld=xNew;
for i=1:n
mySum = 0;
j = i + 1;
while j <= n
mySum = mySum + A(i,j) * xOld(j,1);
j = j + 1;
end
j = 1;
while j < i
mySum = mySum + A(i,j) * xNew(j,1);
j = j + 1;
end
mySum=b(i,1)-mySum;
xNew(i,1) = mySum / A(i, i);
end
if (norm(b - A * xNew, 2) < ep * norm(b, 2))
disp('ending');
leave=true;
end
xOld = xNew;
end
xNew

Perceptron training in Matlab

I am trying to create a simple perceptron training function in MATLAB. I want to return the weights when no errors are found.
Here is the data I want to classify.
d = rand(10,2);
figure
labels = ones(10,1);
diff = d(:,1) + d(:,2) - 1;
labels( diff + 1 >= 1) = 2;
pathWidth = 0.05;
labels( abs(diff) < pathWidth) = [];
d(abs(diff) < pathWidth,:) = [];
plot(d(labels == 1,1),d(labels == 1,2),'k.','MarkerSize',10)
plot(d(labels == 2,1),d(labels == 2,2),'r.','MarkerSize',10)
It produces a labelled data set, where the division between the two classes (red, black) are more visible if you increase the number of points for d.
For my perceptron function I pass the data (d) and labels. I have 3 inputs, the x values, y values and bias which is one. Each input has a random weight between 0 and 1 assigned. Note that the dataset d I have named Z in the perceptron function.
I did use a sigmoid activation function but that would run once through the while loop and always return true after that, the sigmoid function also gave me values of either inf or 1. Below I am using just a threshold activation but it seems to continually loop and not returning my weights. I think the problem may lie in the if-statement below
if(v >= 0 && labels(i) == 1 || v < 0 && labels(i) == 2)
Perceptron function:
function perceptron(data,labels)
sizea = numel(data(:,1));
weights = rand(sizea,3);
Z = data(:,:)
eta = 0.5;
errors = 1;
count = 0;
while errors > 0
errors = 0;
v = sum((1*weights(1,1)) + (Z(:,1)*weights(1,2)) + (Z(:,2)*weights(1,3)));
if v >= 1
v = 1;
else
v = 0;
end
count = count + 1
for i = 1:sizea % for each object in dataset
if(v == 1 && labels(i) == 1 || v == 0 && labels(i) == 2)
errors = 1;
weights(1,1) = weights(1,1) - (2*v-1) * eta * 1;
weights(1,2) = weights(1,2) - (2*v-1) * eta * Z(i,1);
weights(1,3) = weights(1,3) - (2*v-1) * eta * Z(i,2);
v = sum((1*weights(1,1)) + (Z(:,1)*weights(1,2)) + (Z(:,2)*weights(1,3)));
if v >= 1
v = 1;
else
v = 0;
end
end
end
end
There are two major problems in your code:
You need to update v in your loop every time your weights vectors are updated.
It seems like you have 10 training set. So you have to update v sequentially in the loop instead of simultaneously. Keep iterating for every training set, update weights, then use the new weights to calculate the v for the next training set, so on and so forth, until there is no error (errors = 0 in your case).
Minor issue:
if(v >= 0 && labels(i) == 1 || v < 0 && labels(i) == 2)
should be
if(v == 1 && labels(i) == 1 || v == 0 && labels(i) == 2)
You may refer to this example to get more details of the algorithm.

Matlab error : Subscript indices must either be real positive integers or logicals

I have the following error in MATLAB:
??? Subscript indices must either be real positive integers or
logicals.
Error in ==> Lloyd_Max at 74 D(w_count) = mean((x -
centers(xq)).^2);
This is my code :
function [ xq,centers,D ] = Lloyd_Max( x,N,min_value,max_value )
%LLOYD_MAX Summary of this function goes here
% Detailed explanation goes here
x = x';
temp = (max_value - min_value)/2^N;
count=1;
for j=0:temp:((max_value - min_value)-temp),
centers(count) = (j + j + temp )/2;
count = count + 1;
end
for i=1:length(centers),
k(i) = centers(i);
end
w_count = 0;
while((w_count < 2) || (D(w_count) - D(w_count - 1) > 1e-6))
w_count = w_count + 1;
count1 = 2;
for i=2:(count-1),
T(i) = (k(i-1) + k(i))/2;
count1 = count1 +1 ;
end
T(1) = min_value;
T(count1) = max_value;
index = 1;
for j=2:count1,
tempc = 0;
tempk = 0;
for k=1:10000,
if(x(k) >= T(j-1) && x(k) < T(j))
tempk = tempk + x(k);
tempc = tempc + 1;
end
end
k(index) = tempk;
k_count(index) = tempc;
index = index + 1;
end
for i=1:length(k),
k(i) = k(i)/k_count(i);
end
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
for i=1:10000,
cnt = 1;
for l=2:count1,
if(xq(i) > T(l-1) && xq(i) <= T(l))
xq(i) = cnt;
end
cnt = cnt +1 ;
end
end
D(w_count) = mean((x - centers(xq)).^2);
end
end
and i call it and have these inputs :
M = 10000
t=(randn(M,1)+sqrt(-1)*randn(M,1))./sqrt(2);
A= abs(t).^2;
[xq,centers,D] = Lloyd_Max( A,2,0,4 );
I tried to comment the while and the D, Results :
I got the xq and the centers all normal, xq in the 1-4 range, centers 1-4 indexes and 0.5-3.5 range.
I dont know whats going wrong here...Please help me.
Thank in advance!
MYSTERY SOVLED!
Thank you all guys for your help!
I just putted out of the while the for loop :
for i=1:10000,
if (x(i) > max_value)
xq(i) = max_value;
elseif (x(i) < min_value)
xq(i) = min_value;
else
xq(i) = x(i);
end
end
and it worked like charm.... this loop was initilizing the array again. Sorry for that. Thank you again!
There is an assignment xq(i) = x(i) somewhere in the middle of your function, but you pass A as x from outside where you calculate A from t which is sampled by randn, so you can't promise xq is an integer.
I'm not sure exactly what you are aiming to do, but your vector xq does not contain integers, it contains doubles. If you want to use a vector of indices as you do with centers(xq), all elements of the vector need to be integers.
Upon a little inspection, it looks like xq are x values, you should find some way to map them to the integer of the closest cell to which they belong (i'm guessing 'centers' represents centers of cells?)