Matlab GA plot in nodisplay mode - linux

I'm using the matlab GA and the plot option 'gaplotrange'. But I'm running matlab on a Linux server through a terminal. So when I try to save the gaplot, I either keep getting an empty image (if I use saveas) or an error (if I use print, I get a message saying it is not supported in the current platform).
Is there any other way I could save the plot in the nodisplay mode?
Here is a piece of my code
opts = gaoptimset('PopulationSize', 256, 'EliteCount',1,'CrossoverFraction',0.8, ...
'Generation', 3, 'PenaltyFactor',80,'SelectionFcn',{#selectiontournament,4}, ...
'CrossoverFcn', #crossoverscattered ,'Vectorized','off', 'UseParallel','always',...
'OutputFcns',#pop_output,'MutationFcn',{#mutationuniform,0.002},'StallGenLimit',3,...
'TolFun', 1e-4,'PlotFcns',#gaplotbestf);
f = figure('vis','off');
[x,fval, exitflag, output, population, scores] = ga(#plate_fitness,16,[],[],[],[],vlb,vub,[],opts);
hgsave(f,'matlabga_range','png');

Matlab has a solution for this one posted here
hgsave('filename')
hgsave(h,'filename')
I don't have much experience with the genetic algorithms toolbox, but a quick glance at the docs shows this
To display a plot when calling ga from the command line, set the PlotFcns field of options to be a function handle to the plot function. For example, to display the best fitness plot, set options as follows
options = gaoptimset('PlotFcns', #gaplotbestf);
So if you're not passing 'PlotFcns' with a handle to the plotting function in, it looks like it won't generate the plot based on command line interaction. Add it in and see if it fixes your problem, more details here
Update:
Turns out the problem was that the ga method's plot was creating its own figure, so the save needed to be on the gcf, see the discussion below for more details.

Related

How to avoid Save Prompt During SendCommand on activex autocad api

I am trying to convert .dwg format to png/bmp.
when I use Plot in AutoCAD for converting dwg to png .
plot_command = "-PLOT yes base1\r\nPublishToWeb PNG.pc3\rSun Hi-Res (1600.00 x 1280.00 Pixels)\rP\rN\rE\rF\rC\rY\r.\rY\rN\rN\rN\r\n& 'D:/autocad_test/see.png'& \r\n"
doc.SendCommand(plot_command)
during this command Save prompt is coming. I need to override this and also save the file using this single command
I would suggest the following:
doc.SendCommand("_.filedia\n0\n_.-plot\n_Y\n\nPublishToWeb PNG.pc3\nSun Hi-Res (1600.00 x 1280.00 Pixels)\n_P\n_N\n_E\n_F\n_C\n_Y\n.\n_Y\n_N\n_N\n_N\nD:/autocad_test/see.png\n_N\n_Y\n_.filedia\n1\n")
Note that this assumes that the file does not already exist (otherwise there would be an additional prompt to consider - you may therefore wish to incorporate additional code to account for this scenario.

How to create TI-BASIC (TI-84+) input forms?

In the TI-BASIC programming language (Specifically TI-84+), how do you create input forms, such as the ones included in the default apps on the TI-84+.
The image included here shows an example of what I'm trying to create: A menu that you can scroll through and input multiple variables freely before executing a function
Additionally, is it possible to make this menu dynamically-updating as variables are entered?
You've set a rather tall order for TI-Basic to fill. user3932000 is correct; there is no built in function to create an input form of the type you request.
However, there is nothing stopping you from creating an interactive interface yourself. Creating it from scratch will be a time consuming and, it will consume a significant amount of memory on your calculator. There is no boilerplate code you plug your variables into to get the results you want, but you might have some luck modeling it after this quadratic solver I wrote.
ClrHome
a+bi
Output(1,1," QUADRATIC
Output(2,1," AX²+BX+C
Output(3,1,"ZEROS:
Output(6,1,"A=
Output(7,1,"B=
Output(8,1,"C=
DelVar YDelVar D
" →Str1
While Y≠105
getKey→Y
If Ans
Then
Output(X,4,Str1
Output(3,7,Str1+Str1+Str1+"
End
X+(Ans=34)-(Ans=25
If Ans<6:8
If Ans>8:6
Ans→X
Output(Ans,16,"◄
D(Y≠45→D
If Y=25 or Y=34
sum({A,B,C}(X={6,7,8→D
If Y=104:⁻D→D
10not(Y)+Y(102≠Y)-13int(Y/13(2>abs(5-abs(5-abs(Y-83
If Ans≤9
D10+Ans-2Ans(D<0→D
If X=6:D→A
If X=7:D→B
If X=8:D→C
If A
Then
2ˉ¹Aˉ¹(⁻B+{1,⁻1}√(B²-4AC
Else
If B
Then
⁻C/B
Else
If C
Then
"No Zeros
Else
"All Numbers
End
End
End
Output(3,7,Ans
Output(6,3,A
Output(7,3,B
Output(8,3,C
End
ClrHome
Ans
Here's a GIF of what it does for you.
With a little more work. This code could be used on the Graph screen instead of the home screen, giving more option in terms of layout and design.
In the TI-BASIC programming language (Specifically TI-84+), how do you create input forms, such as the ones included in the default apps on the TI-84+.
There are many ways to ask for input in your program:
Prompt: Asks for input and stores it in a variable. For example, Prompt A. Simplest way to ask for input, but not very visually appealing.
Input: Similar to the Prompt command, except that now you can include text within the input. For example, Input "What is your name?",A.
Menu(: Multiple choice input, and each choice is connected to a Lbl marker somewhere else in the script. Much like the error screen with the quit/goto choices that you've probably seen. For example, Menu("Are you a boy or a girl?","Boy",B,"Girl",G).
getKey: Checks if a certain key is pressed, and will output True (1) if that key is pressed. For example, getKey 105. See here for which numbers each key corresponds to.
The image included here shows an example of what I'm trying to create: A menu that you can scroll through and input multiple variables freely before executing a function http://imgur.com/ulthDRV
I'm afraid that's not possible in programs. You can either put in multiple inputs, or you might be interested in looking into making apps instead.
Additionally, is it possible to make this menu dynamically-updating as variables are entered?
If you're talking about the text on top of the screenshot, yes you can; just put a Disp command or something after each line of Input, so that it continuously overwrites the text above with new text after you input a variable.

Changing BUNIT in csh for a FITS file

I'm writing code in .csh, and I'm trying to change the bunit header for a FITS file from K (kelvin) to km/s. How can I do that?
I know in Python I would use new_fitsfile.header['BUNIT']='km/s', but that won't work in the current .csh code, and it's not an option to switch it to Python code.
If this is needed only once, call interactively fv or ds9, move to the header, edit the header card and save the result.
For generic batch jobs, one needs some online FITS editor like fmodhead fmodhead, fthedit, or my fedithead
sed "s:BUNIT = 'K ':BUNIT = 'km/s ':g" old.fits >new.fits
and be very careful to count the significant spaces.

Creating a graph with overlapping histograms and saving it to a single file

I am trying to write a Matlab script to analyze two specific sets of data, create histograms for them, and write them to a single file where you can see both histograms overlapped on one plot.
I created a functioning script that created the histogram for 1 set of data that basically went like this:
h1=figure;
hist(data,nbins:;
print(h1,'-dpng','hist.png)
Then I tried to simply add a second line of:
h2=figure;
and changed the print function to include h2. That obviously didn't work. I found that I couldn't have both an h1 and an h2 with the print function.
After searching the internet and looking for ways to get around this I decided to try to use saveas instead. I got to the following:
h=findobj(gca,'Type','patch');
hist(data1,nbins);
hold on;
hist(data2,nbins);
set(h(1),'FaceColor','r','EdgeColor','k');
set(h(2),'FaceColor','b','EdgeColor','k');
saveas(h,'-dpng','hist.png')
But this won't quite work either. I haven't found anything on the Mathworks website that helps me with this problem, and I haven't found anything on any other site either. I am using a Linux computer connecting to a different server via SSH so the only way that I can view plots that I make is by saving them to a file and then opening them. Please let me know if you have any suggestions to accomplish my task as outlined in my first paragraph. Thank you.
One way is to use different axes for different histogram. You can use SUBPLOT for this:
subplot(2,1,1)
hist(data1,nbins);
subplot(2,1,2)
hist(data2,nbins);
Another way is to find a common bins (x) and return the hist output to vectors. Then use BAR function for the plot.
nbins = 20;
x = linspace(min([data1(:);data2(:)]),max([data1(:);data2(:)]),nbins);
h1 = hist(data1, x);
h2 = hist(data2, x);
hb = bar(x,[h1(:),h2(:)],'hist');
% change colors and set x limits
set(hb(1),'FaceColor','r','EdgeColor','k');
set(hb(2),'FaceColor','b','EdgeColor','k');
gap = x(2)-x(1);
xlim([x(1)-gap x(end)+gap])

In MATLAB, how do I plot to an image and save the result without displaying it?

This question kind of starts where this question ends up. MATLAB has a powerful and flexible image display system which lets you use the imshow and plot commands to display complex images and then save the result. For example:
im = imread('image.tif');
f = figure, imshow(im, 'Border', 'tight');
rectangle('Position', [100, 100, 10, 10]);
print(f, '-r80', '-dtiff', 'image2.tif');
This works great.
The problem is that if you are doing a lot of image processing, it starts to be real drag to show every image you create - you mostly want to just save them. I know I could start directly writing to an image and then saving the result. But using plot/rectangle/imshow is so easy, so I'm hoping there is a command that can let me call plot, imshow etc, not display the results and then save what would have been displayed. Anyone know any quick solutions for this?
Alternatively, a quick way to put a spline onto a bitmap might work...
When you create the figure you set the Visibile property to Off.
f = figure('visible','off')
Which in your case would be
im = imread('image.tif');
f = figure('visible','off'), imshow(im, 'Border', 'tight');
rectangle('Position', [100, 100, 10, 10]);
print(f, '-r80', '-dtiff', 'image2.tif');
And if you want to view it again you can do
set(f,'visible','on')
The simple answer to your question is given by Bessi and Mr Fooz: set the 'Visible' setting for the figure to 'off'. Although it's very easy to use commands like IMSHOW and PRINT to generate figures, I'll summarize why I think it's not necessarily the best option:
As illustrated by Mr Fooz's answer, there are many other factors that come into play when trying to save figures as images. The type of output you get is going to be dependent on many figure and axes settings, thus increasing the likelihood that you will not get the output you want. This could be especially problematic if you have your figures set to be invisible, since you won't notice some discrepancy that could be caused by a change in a default setting for the figure or axes. In short, your output becomes highly sensitive to a number of settings that you would then have to add to your code to control your output, as Mr Fooz's example shows.
Even if you're not viewing the figures as they are made, you're still probably making MATLAB do more work than is really necessary. Graphics objects are still created, even if they are not rendered. If speed is a concern, generating images from figures doesn't seem like the ideal solution.
My suggestion is to actually modify the image data directly and save it using IMWRITE. It may not be as easy as using IMSHOW and other plotting solutions, but I think it is more efficient and gives more robust and consistent results that are not as sensitive to various plot settings. For the example you give, I believe the alternative code for creating a black rectangle would look something like this:
im = imread('image.tif');
[r,c,d] = size(im);
x0 = 100;
y0 = 100;
w = 10;
h = 10;
x = [x0:x0+w x0*ones(1,h+1) x0:x0+w (x0+w)*ones(1,h+1)];
y = [y0*ones(1,w+1) y0:y0+h (y0+h)*ones(1,w+1) y0:y0+h];
index = sub2ind([r c],y,x);
im(index) = 0;
im(index+r*c) = 0;
im(index+2*r*c) = 0;
imwrite(im,'image2.tif');
I'm expanding on Bessi's solution here a bit. I've found that it's very helpful to know how to have the image take up the whole figure and to be able to tightly control the output image size.
% prevent the figure window from appearing at all
f = figure('visible','off');
% alternative way of hiding an existing figure
set(f, 'visible','off'); % can use the GCF function instead
% If you start getting odd error messages or blank images,
% add in a DRAWNOW call. Sometimes it helps fix rendering
% bugs, especially in long-running scripts on Linux.
%drawnow;
% optional: have the axes take up the whole figure
subplot('position', [0 0 1 1]);
% show the image and rectangle
im = imread('peppers.png');
imshow(im, 'border','tight');
rectangle('Position', [100, 100, 10, 10]);
% Save the image, controlling exactly the output
% image size (in this case, making it equal to
% the input's).
[H,W,D] = size(im);
dpi = 100;
set(f, 'paperposition', [0 0 W/dpi H/dpi]);
set(f, 'papersize', [W/dpi H/dpi]);
print(f, sprintf('-r%d',dpi), '-dtiff', 'image2.tif');
If you'd like to render the figure to a matrix, type "help #avifile/addframe", then extract the subfunction called "getFrameForFigure". It's a Mathworks-supplied function that uses some (currently) undocumented ways of extracting data from figure.
Here is a completely different answer:
If you want an image file out, why not just save the image instead of the entire figure?
im = magic(10)
imwrite(im/max(im(:)),'magic.jpg')
Then prove that it worked.
imshow('magic.jpg')
This can be done for indexed and RGB also for different output formats.
You could use -noFigureWindows to disable all figures.

Resources