Octave axes limits change back to auto after plotting - octave

I am experimenting with octave animations and I have an issue with the following code:
clear
x = 0:pi/1000:2*pi;
y = sin(x);
y2 = sin(2*x);
y3 = sin(3*x);
figure
xlim("manual");
ylim("manual");
xlim([0 2*pi]);
ylim([-1 1]);
tic
for i = 1:2000
xlim ("mode")
plot(x(i),y(i),'b',x(i),y2(i),'r',x(i),y3(i),'g')
pause(1)
end
toc
At the output I get:
ans = manual
ans = auto
ans = auto
ans = auto
ans = auto
Why is the axis mode reverting to auto after plotting new data?

This is indeed intended behaviour. A good rationale for it being that there is no reason to assume that subsequent independent calls to the plot function should somehow be related, therefore octave chooses the best possible representation that fits the data. Therefore the fact that the calls to 'plot' in your case in your plotting strategy happen to be 'related' is inconsequential.
If you want to keep the previous axis settings etc within your loop, there are several options.
You may simply keep setting the limits at the end of each iteration, as you suggest
Rather than create a new axes object each time you call plot, you can hold on and plot things on the same axes; if you keep a record of the handle for each plot, you can delete the previous one as necessary leaving only the last one showing.
Plot only once, and within your loop simply replace the plot object's xdata and ydata fields, to update your plot.
Obviously the most straightforward thing to do is the first option; the last one might be something to consider if, e.g., computational efficiency is an issue.

The right way to make an animation is to update the 'XData' and 'YData' properties of the line created by plot. Something like this:
x = 0:pi/1000:2*pi;
y = sin(x);
y2 = sin(2*x);
y3 = sin(3*x);
cla
h = plot(x(1),y(1),'b',x(1),y2(1),'r',x(1),y3(1),'g');
xlim([0 2*pi]);
ylim([-1 1]);
for i = 2:2000
set(h(1),'XData',x(i),'YData',y(i))
set(h(2),'XData',x(i),'YData',y2(i))
set(h(3),'XData',x(i),'YData',y3(i))
pause(0.01)
end
If you want to preserve the previous dots, you can modify the set commands as follows:
set(h(1),'XData',x(1:i),'YData',y(1:i))
This way, a new point is added, rather than moving the existing point.

Related

Having issue with max_norm parameter of torch.nn.Embedding

I use torch.nn.Embedding to embed my model’s categorical input features, however, I face problems when I set the max_norm parameter to not None.
There is a note on the pytorch docs page that explains how to use max_norm parameter through the following example:
n, d, m = 3, 5, 7
embedding = nn.Embedding(n, d, max_norm=True)
W = torch.randn((m, d), requires_grad=True)
idx = torch.tensor(\[1, 2\])
a = embedding.weight.clone() # W.t() # weight must be cloned for this to be differentiable
b = embedding(idx) # W.t() # modifies weight in-place
out = (a.unsqueeze(0) + b.unsqueeze(1))
loss = out.sigmoid().prod()
loss.backward()
I can’t easily understand this example from the docs. What is the purpose of having both ‘a’ and ‘b’ and why ‘out’ is defined as, out = (a.unsqueeze(0) + b.unsqueeze(1))?
Do we need to first clone the entire embedding tensor as in ‘a’, and then finding the embeddings for our desired indices as in ‘b’? Then how do ‘a’ and ‘b’ need to be added?
In my code, I don’t have W explicitly, I am assuming that W is representative of the weights applied by the torch.nn.Linear layers. So, I just need to prepare the input (which includes the embeddings for categorical features) that goes into my network.
I greatly appreciate any instructions on this, as understanding this example would help me adapt my code accordingly.
Because W in the line computing a requires gradients, we must save embedding.weight to compute those gradients in the backward pass. However, in the line computing b, executing embedding(idx) will scale embedding.weight by max_norm - in place. So, without cloning it in line a, embedding.weight will be modified when line b is executed - changing what was saved for the backward pass to update W. Hence the requirement to clone embedding.weight - to save it before it gets scaled in line b.
If you don't use embedding.weight outside of the normal forward pass, you don't need to worry about all this.
If you get an error, post it (and your code).

Solving a steady flow in a subdomain of a mesh using FiPy

I'm fairly new to FiPy and I'm currently facing an issue of which I am sure can be solved easily: I want to solve a 3D steady flow of the form:
eq = ( DiffusionTerm(var=u) == -(1/mu) * dP + g_acc * (rho/mu) * ymax )
Where velocity u is in the y-direction and where du/dy = 0.
I would like to let the PDE solve within a subdomain of the entire 3D mesh, meaning that:
0 <= X < Boundary_1, u=0.
Boundary_1 <= X < Boundary_2, u = PDE solution
Boundary_2 <= X < Lx, u = 0.
Currently I have tried the following:
mesh = Grid3D(dx=dx, dy=dy, dz=dz, Lx=(Lx-0), Ly =(ymax-ymin), Lz=(zmax-zmin))
u = CellVariable(name = "velocity", mesh = mesh)
X, Y, Z = mesh.cellCenters
LeftWall = (X <= xBoundary_left)
RightWall = (X > xBoundary_right)
FrontWall = (mesh.facesFront)
BackWall = (mesh.facesBack)
u.constrain(0., where=LeftWall)
u.constrain(0., where=RightWall)
u.constrain(0., where=FrontWall)
u.constrain(0., where=BackWall)
Which leads to a solution of image 1 (see attached image). The boundary conditions for the X variable are not taken into account as I would like, as you can see in the example in image 2, where only the PDE domain is shown.
What I am looking for is a way to define the boundary conditions at the faces of the subdomain in such a way that it does not 'crop' the solution, but rather only solves the PDE for that subdomain. If it is possible to 'stitch' meshes together that include a Cellvariable u that has value 0 for two meshes and the value of the solved PDE for one mesh, that would be great as well!
I have tried working with inner boundary conditions in the form of an Implicit source, but that ended up in different errors.
Any help would be much appreciated!
FiPy constraints do not work on internal faces.
In our own work, rather than only solving an equation in a subdomain, we modify the coefficients to cause different behaviors to dominate in different subdomains. Conservation of momentum and conservation of mass don't suddenly stop being true; rather different conditions lead to, e.g., different Reynolds numbers.
It is possible to solve different equations on different meshes and communicate between them. See, e.g.,
https://www.mail-archive.com/search?q=how+to+set+up+data+transfer+between+two+adjacent+nonuniform+meshs&l=fipy%40nist.gov
How to extract a plane from a 3D variable in FiPy (3D to 2D)
https://www.mail-archive.com/search?l=fipy%40nist.gov&q=How+to+combine+scipy.interpolate.interp2d+with+fipy+variables&x=0&y=0
https://www.mail-archive.com/search?l=fipy%40nist.gov&q=Spline+interpolation+and+fipy+variable&x=18&y=9

A question regarding the nuances of functions within MatLab

When I run this piece of code:
dx = 4/(nx-1);
dy = 2/(ny-1);
phinew(2:ny-1,2:nx-1) = ((dy^2*(phiold(1:ny-2,2:nx-1)+phiold(3:ny,2:nx-1))+dx^2*(phiold(2:ny-1,1:nx-2)+phiold(2:ny-1,3:nx)))/(2*(dx^2+dy^2))-poissonf);
Within my code, the piece of code operates correctly, taking an input of an nx by ny matrix and outputting a nx by ny matrix. When I run the following code in the exact same position however:
phinew = Smoothing(phiold,poissonf,nx,ny)
Where the function "Smoothing" is defined as:
function [phinew,dx,dy] = Smoothing(phiold,poissonf,nx,ny)
dx = 4/(nx-1);
dy = 2/(ny-1);
phinew(2:ny-1,2:nx-1) = ((dy^2*(phiold(1:ny-2,2:nx-1)+phiold(3:ny,2:nx-1))+dx^2*(phiold(2:ny-1,1:nx-2)+phiold(2:ny-1,3:nx)))/(2*(dx^2+dy^2))-poissonf);
end
The function returns a nx-1 by ny-1 matrix for an nx by ny input.
I cannot wrap my head around why this is occurring at all. The output matrix is the exact same as it should be, except the last column and row are missing entirely. My code is iterative and so requires these to be of the same size, so I cannot move on until this issue is resolved.
Thank you for your time and your help. You people are life-savers.
When you run your code in the command window, phinew already exists. In your command window, do clear phinew before you pasting in those three lines, and you'll find that phinew is then nx-1 by ny-1, as you get from your function.
If you want to force your function to return nx by ny, put phinew = zeros(nx,ny); at the start of the function, or set the last column and row to whatever you want them to be.
EDIT: Responding you your comment "why [does the RHS of the main assignment output] a 48x48 matrix? Directly before the command is run phiold, phinew and poissonf are all 50x50."
I don't think poissonf is 50x50: that would lead to the error Matrix dimensions must agree, because poissonf is being added to the rest of the expression which is part of phiold, so I'll ignore poissonf in the following.
The RHS is always ny-2 by nx-2, even on the first iteration. You can see this by assigning the RHS to an intermediate variable, e.g. phipiece = ... and checking size(phipiece). The reason phinew (if created anew) is 49x49 is because it is assigned to (2:ny-1,2:nx-1), which will create a ny-1 by nx-1 matrix and leave the first row and column as zero.
If you use phinew = zeros(nx,ny); first, then the first and last rows and columns are left as zero.

In octave, error: for x^A, A must be a square matrix. Use .^ for elementwise power

In Octave I defined a function in a separate file square.m
function y = square(x)
y = x^2;
endfunction
In other file script.m I have
disp("Hello World 2");
fplot( #(x) square(x),[-1 1])
And I get
error: for x^A, A must be a square matrix. Use .^ for elementwise power.
Also if I try
y = x.^2;
inside the function I get the exact same message
The reason you're getting that error is because fplot is passing the range you specified all at once as a vector, treating your function as a vectorised function, expecting a vector input and returning a vector output.
You can confirm this by turning "debug on error" to true, by doing debug_on_error(true), run the offending line, and inspect x.
Therefore, inside your function, things go wrong, because you're trying to get the square of a vector, which is an illegal operation (mathematically speaking).
Converting your function to y = x.^2 should work in this case, because you'd be converting each element of the vector to its square, which is what you want. But obviously, simply changing ^ to .^ might not work for every problem.
In general, it's better to create your own 'range' and 'outputs' and plot them directly using plot; this gives you far more control, and you can inspect the inputs and outputs first to ensure you're plotting what you think you're plotting.
Welcome to StackOverflow!
I have just tried your code on https://octave-online.net/ (no need to create an account nor even the files).
The second version works "as expected": y = x .^ 2; inside the function.
Make sure you saved the file after the modification?

Finding the smallest distance in a set of points from the origin

I am to find the smallest distance between a given set of points and the origin. I have a matrix with 2 columns and 10 rows. Each row represents coordinates. One point consists of two coordinates and I would like to calculate the smallest distance between each point and to the origin. I would also like to determine which point gave this smallest distance.
In Octave, I calculate this distance by using norm and for each point in my set, I have a distance associated with them and the smallest distance is obviously the one I'm looking for. However, the code I wrote below isn't working the way it should.
function [dist,koor] = bonus4(S)
S= [-6.8667, -44.7967;
-38.0136, -35.5284;
14.4552, -27.1413;
8.4996, 31.7294;
-17.2183, 28.4815;
-37.5100, 14.1941;
-4.2664, -24.4428;
-18.6655, 26.9427;
-15.8828, 18.0170;
17.8440, -22.9164];
for i=1:size(S)
L=norm(S(i, :))
dist=norm(S(9, :));
koor=S(9, :) ;
end
i = 9 is the correct answer, but I need Octave to put that number in. How do I tell Octave that this is the number I want? Specifically:
dist=norm(S(9, :));
koor=S(9, :);
I cannot use any packages. I found the geometry package online but I am to solve the task without additional packages.
I'll work off of your original code. Firstly, you want to compute the norm of all of the points and store them as individual elements in an array. Your current code isn't doing that and is overwriting the variable L which is a single value at each iteration of the loop.
You'll want to make L an array and store the norms at each iteration of the loop. Once you do this, you'll want to find the location as well as the minimum distance itself. That can be done with one call to min where the first output gives you the minimum distance and the second output gives you the location of the minimum. You can use the second output to slice into your S array to retrieve the actual point.
Last but not least, you need to define S first before calling this function. You are defining S inside the function and that will probably give you unintended results if you want to change the input into this function at each invocation. Therefore, define S first, then call the function:
S= [-6.8667, -44.7967;
-38.0136, -35.5284;
14.4552, -27.1413;
8.4996, 31.7294;
-17.2183, 28.4815;
-37.5100, 14.1941;
-4.2664, -24.4428;
-18.6655, 26.9427;
-15.8828, 18.0170;
17.8440, -22.9164];
function [dist,koor] = bonus4(S)
%// New - Create an array to store the distances
L = zeros(size(S,1), 1);
%// Change to iterate over number of rows
for i=1:size(S,1)
L(i)=norm(S(i, :)); %// Change
end
[dist,ind] = min(L); %// Find the minimum distance
koor = S(ind,:); %// Get the actual point
end
Or, make sure you save the above function in a file called bonus4.m, then do this in the Octave command prompt:
octave:1> S= [-6.8667, -44.7967;
> -38.0136, -35.5284;
> 14.4552, -27.1413;
> 8.4996, 31.7294;
> -17.2183, 28.4815;
> -37.5100, 14.1941;
> -4.2664, -24.4428;
> -18.6655, 26.9427;
> -15.8828, 18.0170;
> 17.8440, -22.9164];
octave:2> [dist,koor] = bonus4(S);
Though this code works, I'll debate that it's slow as you're using a for loop. A faster way would be to do this completely vectorized. Because using norm for matrices is different than with vectors, you'll have to compute the distance yourself. Because you are measuring the distance from the origin, you can simply square each of the columns individually then add the columns of each row.
Therefore, you can just do this:
S= [-6.8667, -44.7967;
-38.0136, -35.5284;
14.4552, -27.1413;
8.4996, 31.7294;
-17.2183, 28.4815;
-37.5100, 14.1941;
-4.2664, -24.4428;
-18.6655, 26.9427;
-15.8828, 18.0170;
17.8440, -22.9164];
function [dist,koor] = bonus4(S)
%// New - Computes the norm of each point
L = sqrt(sum(S.^2, 2));
[dist,ind] = min(L); %// Find the minimum distance
koor = S(ind,:); %// Get the actual point
end
The function sum can be used to sum over a dimension independently. As such, by doing S.^2, you are squaring each term in the points matrix, then by using sum with the second parameter as 2, you are summing over all of the columns for each row. Taking the square root of this result computes the distance of each point to the origin, exactly the way the for loop functions. However, this (at least to me) is more readable and I daresay faster for larger sizes of points.