octave runs ok but plot is not displayed? - octave

HI there
I am using Octave 2.3.4 with a plot command. I am new at Octave. This plot does not display for some reason. Here is my M file sample:
1;
clear all;
%%%%%%%%% parameters setting %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
r=0.01; %risk free rate
S0=50; %underlying price 1
%create an implied volatiltiy surface using below parameters:
basevol=0.25; %implied volatility at time t=0 and in center of strike axis
skewT=-0.001; %icrease in vol for one unit increase in maturity
v1=0.1; %defines how much a smile is raised at left end from base vol
v3=0.2; %defines how much a smile is raised at right end from base vol
nK=100; %no. of strike steps
nT=10; %no. of time steps
Tmax=1; %maximum value in time axis
Kmin=1; %minimum value in strike price axis
Kmax=150; %maximum value of strike price axis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dt=Tmax/(nT-1);
Tvec=0:dt:1;
dk=(Kmax-Kmin)/(nK-1);
Kvec=Kmin:dk:Kmax;
Tvec=Tvec';
Kvec=Kvec';
nK=size(Kvec,1);
nT=size(Tvec,1);
dvolT=ones(nK,nT)*(skewT*dt);
dvolT=cumsum(dvolT,2);
SmileVec=GetSmile(Kvec,v1,0,v3);
dvolK=ones(nK,nT);
dvolK=repmat(SmileVec,1,nT);
ImpliedVolSurface=ones(nK,nT)*basevol+dvolT+dvolK;
%use formula mentioned by John Elder in "Hedging for Financial Derivatives"
%this formula gives local volatility using implied volatility
function ret=GetLocalVolSurface(ImpliedVolSurface, S, r, Kvec, Tvec)
[m,n]=size(ImpliedVolSurface);
LocalVolSurface=zeros(m,n);
dk=Kvec(2)-Kvec(1);
dt=Tvec(2)-Tvec(1);
x=ImpliedVolSurface;
for i=3:m-2, %loop over strikes
for j=1:n-1, %loop over time steps
dv_dk=(x(i+1,j)-x(i-1,j))/(2*dk);
dv2_dk2=(x(i-1,j)-2*x(i,j)+x(i+1,j))/(dk*dk);
dv_dt=(x(i,j+1)-x(i,j))/dt;
K=Kvec(i);
T=Tvec(j+1);
rT=T^0.5;
sig=x(i,j);
h1=(log(S/K)+r*T+0.5*sig*sig*T)/(sig*rT);
numer=sig*sig + 2*T*sig*dv_dt + 2*r*K*T*sig*dv_dk;
denom=(1+K*h1*rT*dv_dk)^2 + K*K*T*sig*sig*(dv2_dk2-h1*dv_dk*dv_dk*rT);
LocalVolSurface(i,j)=(numer/denom)^0.5;
end
end
ret=LocalVolSurface;
endfunction
LocalVol_Surface=GetLocalVolSurface(ImpliedVolSurface,S0,r,Kvec,Tvec);
AsyImplVols=zeros(nK,1);
T=Tvec(nT-1);
F=S0*exp(r*T);
for i=3:nK-2,
% use formula sigBS(F,K)=sigLoc( (F+K)/2 )
K=Kvec(i);
lookupK=(F+K)/2;
kdiff=abs(Kvec-lookupK); %try to find nearest point in grid
kidx=min(find(kdiff==min(kdiff)));
if ( (kidx > 3) && (kidx < nK-2) ),
AsyImplVols(i)=LocalVol_Surface(kidx);
else
AsyImplVols(i) = NaN;
end
end
figure(1);
plot(Kvec(3:nK-2),[ImpliedVolSurface(3:nK-2,nT-1) LocalVol_Surface(3:nK-2,nT-1) AsyImplVols(3:nK-2)]);
When I run in Octave with no error, the plot is never displayed. It does include gnuplot 1.0.1 which I understand does the graph? Is there something I am not doing or missing? I am also running this on Windows 2003 Server.
Thanks

I got the answer here. Octave by default uses fltk for plotting etc, which is failing to work, using gnuplot works here. Just add below lines to .octaverc file in your home directory.
graphics_toolkit("gnuplot")
So that every time octave starts it will set the default package for plotting to gnuplot

I do know that's an old question but since I ran into quite the same error yesterday, maybe this can help someone else, too:
According to the Octave wiki pages, there seems to be a problem with plotting and the "oct2mat"-library. For me, the problem was solved after I ran this at the octave command prompt:
pkg rebuild -noauto oct2mat
and restarted octave. When you need to use "oct2mat", type:
pkg load oct2mat
Hope that helps!

I get the same problem installing on a windows 7 64 bit laptop (HP 630) with intel graphics. Every time you plot, it fails to do anything, but if you plot again, it shows up. It's some kind of refresh bug. It's annoying, but if you plot twice, the second time it works.
I am wondering if it is some kind of double buffering bug, because it works correctly on my own laptop running windows 7 with a dedicated graphics card.
In any case, try plotting twice in a row, I'll bet it works, and please let me know what the machine and video card are, because I've reported this to octave development.

Related

Octave Change UIControl Position

The following is example code from Matlab. It doesn't run in Octave. The code is:
f = figure;
b = uicontrol(f,'Style','pushbutton');
b.Position = [100 100 50 20];
It is from the online documentation: https://www.mathworks.com/help/matlab/ref/matlab.ui.control.uicontrol-properties.html
In Octave, I get: error: scalar cannot be indexed with .
What change must be made to make this run in Octave?
MATLAB introduced the second version of the handle graphics system (HG2) a couple of years ago. Octave still uses the old system.
Every time you see handle.propery, you are dealing with HG2. In the original system, we used get(handle,'property') and set(handle,'property',newvalue). Note that MATLAB will not deprecate this original syntax any time soon, it is perfectly valid to use both forms with the newer versions of MATLAB. Thus, the set and get functions are to be preferred for compatibility reasons.
So you can replace
b.Position = [100 100 50 20];
with
set(b,'Position',[100 100 50 20]);

OpenAI gym: How to get pixels in CartPole-v0

I would like to access the raw pixels in the OpenAI gym CartPole-v0 environment without opening a render window. How do I do this?
Example code:
import gym
env = gym.make("CartPole-v0")
env.reset()
img = env.render(mode='rgb_array', close=True) # Returns None
print(img)
img = env.render(mode='rgb_array', close=False)
# Opens annoying window, but gives me the array that I want
print(img.shape)
PS. I am having a hard time finding good documentation for OpenAI gym. Is it just me, or does it simply not exist?
Edit: I don't need to ever open the render video.
I was curious about same so I started looking into the source code and this is what I found.
Open AI uses pyglet for displaying the window and animations.
For showing the animation everything is drawn on to window and then rendered.
And then pyglet stores what is being displayed on to a buffer.
Dummy version of how code is written in open AI
import pyglet
from pyglet.gl import *
import numpy as np
display = pyglet.canvas.get_display()
screen = display.get_screens()
config = screen[0].get_best_config()
pyglet.window.Window(width=500, height=500, display=display, config=config)
# draw what ever you want
#get image from the buffer
buffer = pyglet.image.get_buffer_manager().get_color_buffer()
image_data=buffer.get_image_data()
arr = np.frombuffer(image_data.get_data(),dtype=np.uint8)
print(arr)
print(arr.shape)
output:
[0 0 0 ... 0 0 0]
(1000000,)
so basically every image we get is from buffer of what is being displayed on the window.
So if we don't draw anything on window we get no image so that window is required to get the image.
so you need to find a way such that windows is not displayed but its values are stored in buffer.
I know its not what you wanted but I hope it might lead you to a solution.
I've just gone through half of the gym source code line by line, and I can tell you that 1, the observation space of cartpole is digits to the ai, not pixels. eg, from their cartpole env py file...
Observation:
Type: Box(4)
Num Observation Min Max
0 Cart Position -2.4 2.4
1 Cart Velocity -Inf Inf
2 Pole Angle -0.209 rad (-12 deg) 0.209 rad (12 deg)
3 Pole Angular Velocity -Inf Inf
So, the pixels are for you at this point. And 2, if your goal is to teach the ai on pixels, you will need to render images from your data-in array, then pass them THROUGH the observation space as a pixel array, like Maunish Dave shows. OpenAI's Atari version does this.
If you want a better guide, don't read the OpenAI Docs, read the Stable Baseline docs here: https://stable-baselines.readthedocs.io/
Someone offers an answer here:
https://github.com/openai/gym/issues/374
"The atari and doom environments give pixels in their observations (ie, the return value from step). I don't think any other ones do.
render produces different results on different OSes, so they're not part of any official environment for benchmarking purposes. But if you want to create a new environment where the observation is in pixels, you could implement it by wrapping an existing environment and calling render."
I'm also working on getting raw pixels as well and I'm trying to find a way to see if what has been returned is what I expect it is.
The documentation can be found:
https://gym.openai.com/docs
And a forum for discussing OpenAI:
discuss.openai.com
Although its not very lively.
I have faced the similar problem:
This is how fixed it, in rendering.py file at /gym/envs/classic_control find the following line in the Viewer class:
self.window = pyglet.window.Window(width=width, height=height, display=display)
Change this line to:
self.window = pyglet.window.Window(width=width, height=height, display=display, visible=False)
Hope it helps!!

SYS(3050) is throwing Function argument value,type or count is invalid error

Earlier i had an issue of not enough memory for file mapping.
Then as advised by few experts I used following code in my main program and that solves the issue and worked fine.
SYS(3050,1,MIN(536870912,VAL(SYS(3050,1,0))))
SYS(3050,2,MIN(536870912,VAL(SYS(3050,1,0))))
But recently one of client's machine is upgraded to Windows 7 64 bit from XP 32 bit. After that when the system is starting
it is throwing an error of Function argument value, type or count is invalid at SYS(3050) line.
If I omit this and continues then not enough memory for file mapping is occurs.
Can anybody advise what i should do to overcome this issue? Is it because of 64 bit OS of Windows 7 (because other two machines with Windows 7 and 32 bit are working properly)
As Alan B said, the problems with 'not enough memory for file mapping' tend to go away when switching to VFP9 SP2 (it's the one fly in the ointment when using VFP8 SP1 which is otherwise the most solid of the lot).
If switching to VFP9 is not an option then I would suggest factoring out the nested SYS(3050,1,0) calls and sanitising the result before feeding it into VAL(). At the very least it would pinpoint more accurately the place where the problem occurs, to guide further investigation with the aid of a debugger or a tool like IDA.
The original code already caps the parameter at 536870912, which is well below the threshold of 2^31 at which SYS(3050) throws a range error. However, the parameter must be strictly positive, which requires adding a MAX() term:
local nLimit
nLimit = max(1, min(536870912, val(sys(3050, 1))))
sys(3050, 1, m.nLimit)
sys(3050, 2, m.nLimit)
Background: calling the function with a limit parameter of 0 is the same as calling it without a limit (i.e. it gets the limit instead of setting it). Calling the function with a negative parameter causes it to blow with a range error.

Octave specgram generates two diffent answers

I have a project where I have to recognize the frequency from an audio file. For this I use a single tone of 10 kHz to see if I can get it working.
Since I am pretty new to Octave, I tried this example with my own audio file.
I tried to understand what happens by doing some research to all functions.
My question here is; if I let specgram plot the figure when I do not specify it's output:
specgram(y,fftn,Fs,hanning(window),step);
it gives a line at 10kHz which is what I want.
But if I specify the output for the specgram function
[S,f,t]= specgram(y,fftn,Fs,hanning(window),step);
and let it plot, it plots the line at 18 kHz.
I figured it have to be in the inputs for the figure and I tried modifying these a bit, but every time I do that Octave gives an error.
I need the frequency as an given output, since I have to do some calculations with it, I figured I need to specify the frequency output.
This is the part of the code that specify the plot for the spectrogram:
step= fix(5*Fs/1000); % stepsize of the window
window= fix(90*Fs/1000); % window size
fftn =2^nextpow2(window); % Size of the FFT block
[S,f,t]= specgram(y,fftn,Fs,hanning(window),step);
S= abs(S(2:fftn*12000/Fs,:)); % Normalize the phase
S= S/max(S(:)); % Normalize the Energy
S= max(S, 10^(-40/10)); % Throw out values below -40 dB and above -3dB
S= min(S, 10^(-3/10));
figure
imagesc(t,f,(log(S)));
Can anyone help me here how to gain the frequency data from the audio file so I can use it in some calculations?
I have searched for answers already in the Octave manual for help and I tried it with various matlab sites. Also checked already many posts here such as:
How does Octave spectrogram 'specgram' from signal work?
Methodology of FFT for Matlab spectrogram / short time Fourier transform functions
P.S. Sorry for my bad English, it's not my native language
I found the answer myself, it turns out it is in this line of code:
S= abs(S(2:fftn*12000/Fs,:));
if I delete this line, the lines are placed on the right frequency in the figure. To me it looks like this line just takes a small space of the fft and replaces it with other frequencies but I'm not shure about that.

Clock function in Stata 9

I am using an old version of Stata, Stata 9, and I am trying to use the clock() function to convert some dates.
gen double Sgytime = clock (surgerystartdatetime, "dmyhm").
Stata says clock not found. Help please.
The function clock() was introduced in Stata 10. That is documented for all to see at http://www.stata.com/help.cgi?whatsnew9to10
Your options are to find a version of Stata that is 10 or higher, to write your own commands (not functions) to handle date-time data, or to use the user-written command ntimeofday published in the Stata Journal. search ntimeofday will indicate a download source. Note that the latter command does not work as clock() does, and in general Stata 9 just does not recognise date-time variables as such.
A larger question is that you are evidently getting ideas from material written for later versions of Stata, but the help and manuals for Stata 9 are the only completely reliable guide to what functions are available to you.
I think you may have an extra space between clock and the first parenthesis:
. display %tc clock("5-12-1998 11:15", "MDY hm")
12may1998 11:15:00
. display %tc clock ("5-12-1998 11:15", "MDY hm")
clock not found
I am assuming that in the search for lost time you have already verified that Stata (and not STATA) 9 has the clock function by looking at the documentation.