Auswertung Experiment

Database tüddelei
DBHanlder läuft gut für DIESE Datanbank struktur...
App begonnen aber weit entfernt von gutem Stand
This commit is contained in:
sioe
2024-11-15 16:51:37 +01:00
parent 553ed19b9f
commit 397cfa61dd
219 changed files with 584 additions and 854 deletions

45
Libs/boundedlines/.gitignore vendored Normal file
View File

@@ -0,0 +1,45 @@
# MATLAB #
##########
# Editor autosave files
*~
*.asv
# Compiled MEX binaries (all platforms)
*.mex*
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

View File

@@ -0,0 +1,37 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

View File

@@ -0,0 +1,161 @@
<html xmlns:mwsh="http://www.mathworks.com/namespace/mcode/v1/syntaxhighlight.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--
This HTML is auto-generated from an M-file.
To make changes, update the M-file and republish this document.
-->
<title>inpaint_nans_demo</title>
<meta name="generator" content="MATLAB 7.0.1">
<meta name="date" content="2006-06-28">
<meta name="m-file" content="inpaint_nans_demo"><style>
body {
background-color: white;
margin:10px;
}
h1 {
color: #990000;
font-size: x-large;
}
h2 {
color: #990000;
font-size: medium;
}
p.footer {
text-align: right;
font-size: xx-small;
font-weight: lighter;
font-style: italic;
color: gray;
}
pre.codeinput {
margin-left: 30px;
}
span.keyword {color: #0000FF}
span.comment {color: #228B22}
span.string {color: #A020F0}
span.untermstring {color: #B20000}
span.syscmd {color: #B28C00}
pre.showbuttons {
margin-left: 30px;
border: solid black 2px;
padding: 4px;
background: #EBEFF3;
}
pre.codeoutput {
color: gray;
font-style: italic;
}
pre.error {
color: red;
}
/* Make the text shrink to fit narrow windows, but not stretch too far in
wide windows. On Gecko-based browsers, the shrink-to-fit doesn't work. */
p,h1,h2,div {
/* for MATLAB's browser */
width: 600px;
/* for Mozilla, but the "width" tag overrides it anyway */
max-width: 600px;
/* for IE */
width:expression(document.body.clientWidth > 620 ? "600px": "auto" );
}
</style></head>
<body><pre class="codeinput"><span class="comment">% Surface fit artifact removal</span>
[x,y] = meshgrid(0:.01:1);
z0 = exp(x+y);
znan = z0;
znan(20:50,40:70) = NaN;
znan(30:90,5:10) = NaN;
znan(70:75,40:90) = NaN;
z = inpaint_nans(znan,3);
<span class="comment">% Comparison to griddata</span>
k = isnan(znan);
zk = griddata(x(~k),y(~k),z(~k),x(k),y(k));
zg = znan;
zg(k) = zk;
close <span class="string">all</span>
figure
surf(z0)
title <span class="string">'Original surface'</span>
figure
surf(znan)
title <span class="string">'Artifacts (large holes) in surface'</span>
figure
surf(zg)
title([<span class="string">'Griddata inpainting ('</span>,num2str(sum(isnan(zg(:)))),<span class="string">' NaNs remain)'</span>])
figure
surf(z)
title <span class="string">'Inpainted surface'</span>
figure
surf(zg-z0)
title <span class="string">'Griddata error surface'</span>
figure
surf(z-z0)
title <span class="string">'Inpainting error surface (Note z-axis scale)'</span>
</pre><img vspace="5" hspace="5" src="inpaint_nans_demo_01.png"> <img vspace="5" hspace="5" src="inpaint_nans_demo_02.png"> <img vspace="5" hspace="5" src="inpaint_nans_demo_03.png"> <img vspace="5" hspace="5" src="inpaint_nans_demo_04.png"> <img vspace="5" hspace="5" src="inpaint_nans_demo_05.png"> <img vspace="5" hspace="5" src="inpaint_nans_demo_06.png"> <p class="footer"><br>
Published with MATLAB&reg; 7.0.1<br></p>
<!--
##### SOURCE BEGIN #####
% Surface fit artifact removal
[x,y] = meshgrid(0:.01:1);
z0 = exp(x+y);
znan = z0;
znan(20:50,40:70) = NaN;
znan(30:90,5:10) = NaN;
znan(70:75,40:90) = NaN;
z = inpaint_nans(znan,3);
% Comparison to griddata
k = isnan(znan);
zk = griddata(x(~k),y(~k),z(~k),x(k),y(k));
zg = znan;
zg(k) = zk;
close all
figure
surf(z0)
title 'Original surface'
figure
surf(znan)
title 'Artifacts (large holes) in surface'
figure
surf(zg)
title(['Griddata inpainting (',num2str(sum(isnan(zg(:)))),' NaNs remain)'])
figure
surf(z)
title 'Inpainted surface'
figure
surf(zg-z0)
title 'Griddata error surface'
figure
surf(z-z0)
title 'Inpainting error surface (Note z-axis scale)'
##### SOURCE END #####
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

View File

@@ -0,0 +1,42 @@
% Surface fit artifact removal
[x,y] = meshgrid(0:.01:1);
z0 = exp(x+y);
znan = z0;
znan(20:50,40:70) = NaN;
znan(30:90,5:10) = NaN;
znan(70:75,40:90) = NaN;
z = inpaint_nans(znan,3);
% Comparison to griddata
k = isnan(znan);
zk = griddata(x(~k),y(~k),z(~k),x(k),y(k));
zg = znan;
zg(k) = zk;
close all
figure
surf(z0)
title 'Original surface'
figure
surf(znan)
title 'Artifacts (large holes) in surface'
figure
surf(zg)
title(['Griddata inpainting (',num2str(sum(isnan(zg(:)))),' NaNs remain)'])
figure
surf(z)
title 'Inpainted surface'
figure
surf(zg-z0)
title 'Griddata error surface'
figure
surf(z-z0)
title 'Inpainting error surface (Note z-axis scale)'

View File

@@ -0,0 +1,39 @@
{\rtf1\mac\ansicpg10000\cocoartf102
{\fonttbl\f0\fswiss\fcharset77 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10780\viewh13720\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural
\f0\fs24 \cf0 Nomination comments:\
\
Inpaint_nans fills a hole in matlab. (Yes, the pun was intentional.) But there\
is indeed a niche that inpaint_nans falls into.\
\
The alternative to inpaint_nans is griddata (interp1 can be used for the 1-d \
problems) but griddata fails to extrapolate well. Griddata also has serious\
problems when its data already lies on a grid, due to its use of a Delaunay \
triangulation. The other serious problem with the use of griddata is the\
triangulation itself. The shape of the hole to be filled can sometimes result\
in triangles with a poor aspect ratio (long, thin triangles) which are in turn\
poor for interpolation. In fact, Griddata can even leave interior points\
uninterpolated (see the tests.)\
\
A future plan for inpaint_nans is to add an option that will use a locally\
anisotropic membrane model. This will allow better modeling for certain\
classes of wavy surfaces. I'm also highly tempted to remove method 5.\
I've never really liked it, having put it in at the request of one user. It has\
no valid theory behind it in the context of inpaint_nans.\
\
In the interest of openness, I'll also say what inpaint_nans does not do. It\
does not handle non-uniform grids. It is limited by the amount of memory \
in the size of the arrays it can handle, although some of the methods were\
explicitly provided to be more memory efficient than others. Inpaint_nans\
also makes heavy use of sparse matrices, so surprisingly large problems\
are accessible.\
\
Finally, while inpaint_nans does work for 1-d problems, they are not my\
target. Interp1 (with 'spline' as the method) is as accurate, and should be\
faster in general.\
\
John\
}

View File

@@ -0,0 +1,187 @@
%{
The methods of inpaint_nans
Digital inpainting is the craft of replacing missing elements in an
"image" array. A Google search on the words "digita inpainting" will turn
up many hits. I just tried this search and found 18300 hits.
If you wish to do inpainting in matlab, one place to start is with my
inpaint_nans code. Inpaint_nans is on the file exchange:
http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=4551&objectType=file
It looks for NaN elements in an array (or vector) and attempts to interpolate
(or extrapolate) smoothly to replace those elements.
The name "inpainting" itself comes from the world of art restoration.
Damaged paintings are restored by an artist/craftsman skilled in matching
the style of the original artist to fill in any holes in the painting.
In digital inpainting, the goal is to interpolate in from the boundaries
of a hole to smoothly replace an artifact. Obviously, where the hole is
large the digitally inpainted repair may not be an accurate approximation
to the original.
Inpaint_nans itself is really only a boundary value solver. The basic idea
is to formulate a partial differential equation (PDE) that is assumed to
apply in the domain of the artifact to be inpainted. The perimeter of the
hole supplies boundary values for the PDE. Then the PDE is approximated
using finite difference methods (the array elements are assumed to be
equally spaced in each dimension) and then a large (and very sparse) linear
system of equations is solved for the NaN elements in the array.
I've chosen a variety of simple differental equation models the user can
specify to be solved. All the methods current use a basically elliptic
PDE. This means that the resulting linear system will generally be well
conditioned. It does mean that the solution will generally be fairly smooth,
and over large holes, it will tend towards an average of the boundary
elements. These are characteristics of the elliptic PDEs chosen. (My hope
is to expand these options in the future.)
%}
%%
% Lets formulate a simple problem, and see how we could solve it using
% some of these ideas.
A = [0 0 0 0;1 NaN NaN 4;2 3 5 8];
% Although we can't plot this matrix using the functions surf or mesh,
% surely we can visualize what the fudamental shape is.
% There are only two unknown elements, the artifacts that inpaint_nans
% would fill in: A(2,2) and A(2,3).
% For an equally spaced grid, the Laplacian equation (or Poisson's equation
% of heat conduction at steady state if you prefer. Or, for the fickle,
% Ficke's law of diffusion would apply.) All of these result in the PDE
%
% u_xx + u_yy = 0
%
% where u_xx is the second partial derivative of u with respect to x,
% and u_yy is the second partial with respect to y.
%
% Approximating this PDE using finite differences for the partial
% derivatives, implies that at any node in the grid, we could replace
% it by the average of its 4 neighbors. Thus the two NaN elements
% generate two linear equations:
%
% A(2,2) = (A(1,2) + A(3,2) + A(2,1) + A(2,3)) / 4
% A(2,3) = (A(1,3) + A(3,3) + A(2,2) + A(2,4)) / 4
%
% Since we know all the parameters but A(2,2) and A(2,3), substitute their
% known values.
%
% A(2,2) = (0 + 3 + 1 + A(2,3)) / 4
% A(2,3) = (0 + 5 + A(2,2) + 4) / 4
%
% Or,
%
% 4*A(2,2) - A(2,3) = 4
% -A(2,2) + 4*A(2,3) = 9
%
% We can solve for the unkowns now using
u = [4 -1;-1 4]\[4;9]
A(2,2) = u(1);
A(2,3) = u(2);
% and finally plot the surface
close
surf(A)
title 'A simply inpainted surface'
% Neat huh? For an arbitrary number of NaN elements in an array,
% the above scheme is all there is to method 2 of inpaint_nans,
% together with a very slick application of sparse linear algebra
% in Matlab.
% Method 0 is very similar, but I've optimized it to build as
% small a linear system as possible for those cases where an array
% has only a few NaN elements.
% Method 1 is another subtle variation on this scheme, but it
% tries to be slightly smoother at some cost of efficiency, while
% still not modifying the known (non-NaN) elements of the array.
% Method 5 of inpaint_nans is also very similar to method 2, except
% that it uses a simple average of all 8 neighbors of an element.
% Its not actually an approximation to our PDE.
% Method 3 is yet another variation on this theme, except the PDE
% model used is one more suited to a model of a thin plate than for
% heat diffusion. Here the governing PDE is:
%
% u_xxxx + 2*u_xxyy + u_yyyy = 0
%
% again discretized into a linear system of equations.
%%
% Finally, method 4 of inpaint_nans has a different underlying
% model. Pretend that each element in the array was connected to
% its immediate neighbors to the left, right, up, and down by
% "springs". They are also connected to their neighbors at 45
% degree angles by springs with a weaker spring constant. Since
% the potential energy stored in a spring is proportional to its
% extension, we can formulate this again as a linear system of
% equations to be solved. For the example above, we would generate
% the set of equations:
% A(2,2) - A(1,2) = 0
% A(2,2) - A(2,1) = 0
% A(2,2) - A(3,2) = 0
% A(2,2) - A(2,3) = 0
% (A(2,2) - A(1,1))/sqrt(2) = 0
% (A(2,2) - A(1,3))/sqrt(2) = 0
% (A(2,2) - A(3,1))/sqrt(2) = 0
% (A(2,2) - A(3,3))/sqrt(2) = 0
% A(2,3) - A(1,3) = 0
% A(2,3) - A(2,2) = 0
% A(2,3) - A(3,3) = 0
% A(2,3) - A(2,4) = 0
% (A(2,3) - A(1,2))/sqrt(2) = 0
% (A(2,3) - A(1,4))/sqrt(2) = 0
% (A(2,3) - A(3,2))/sqrt(2) = 0
% (A(2,3) - A(3,4))/sqrt(2) = 0
% Substitute for the known elements to get
% A(2,2) - 0 = 0
% A(2,2) - 1 = 0
% A(2,2) - 3 = 0
% A(2,2) - A(2,3) = 0
% (A(2,2) - 0)/sqrt(2) = 0
% (A(2,2) - 0)/sqrt(2) = 0
% (A(2,2) - 2)/sqrt(2) = 0
% (A(2,2) - 5)/sqrt(2) = 0
% A(2,3) - 0 = 0
% A(2,3) - A(2,2) = 0
% A(2,3) - 5 = 0
% A(2,3) - 4 = 0
% (A(2,3) - 0)/sqrt(2) = 0
% (A(2,3) - 0)/sqrt(2) = 0
% (A(2,3) - 3)/sqrt(2) = 0
% (A(2,3) - 8)/sqrt(2) = 0
% This system is also solvable now:
r2 = 1/sqrt(2);
M=[1 0;1 0;1 0;1 -1;r2 0;r2 0;r2 0;r2 0;0 1;-1 1;0 1;0 1;0 r2;0 r2;0 r2;0 r2];
v = M\[0 1 3 0 0 0 2*r2 5*r2 0 0 5 4 0 0 3*r2 8*r2]'
A(2,2) = v(1);
A(2,3) = v(2);
% and finally plot the surface
surf(A)
title 'A simply inpainted surface using a spring model'
%%
% Why did I provide this approach, based on a spring metaphor?
% As you should have observed, methods 2 and 4 are really quite close
% in what they do for internal NaN elements. Its on the perimeter that
% they differ significantly. The diffusion/Laplacian model will
% extrapolate smoothly, and as linearly as possible. The spring model
% will tend to extrapolate as a constant function.

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,43 @@
%% Surface Fit Artifact Removal
%% Construct the Surface
[x,y] = meshgrid(0:.01:1);
z0 = exp(x+y);
close all
figure
surf(z0)
title 'Original surface'
znan = z0;
znan(20:50,40:70) = NaN;
znan(30:90,5:10) = NaN;
znan(70:75,40:90) = NaN;
figure
surf(znan)
title 'Artifacts (large holes) in surface'
%% In-paint Over NaNs
z = inpaint_nans(znan,3);
figure
surf(z)
title 'Inpainted surface'
figure
surf(z-z0)
title 'Inpainting error surface (Note z-axis scale)'
%% Comapre to GRIDDATA
k = isnan(znan);
zk = griddata(x(~k),y(~k),z(~k),x(k),y(k));
zg = znan;
zg(k) = zk;
figure
surf(zg)
title(['Griddata inpainting (',num2str(sum(isnan(zg(:)))),' NaNs remain)'])
figure
surf(zg-z0)
title 'Griddata error surface'

View File

@@ -0,0 +1,24 @@
Copyright (c) 2009, John D'Errico
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

View File

@@ -0,0 +1,178 @@
%% Repair to an image with 50% random artifacts
% Garden at Sainte-Adresse (Monet, 1867)
garden = imread('monet_adresse.jpg');
G = double(garden);
G(rand(size(G))<0.50) = NaN;
Gnan = G;
G(:,:,1) = inpaint_nans(G(:,:,1),2);
G(:,:,2) = inpaint_nans(G(:,:,2),2);
G(:,:,3) = inpaint_nans(G(:,:,3),2);
figure
subplot(1,3,1)
image(garden)
title 'Garden at Sainte-Adresse (Monet)'
subplot(1,3,2)
image(uint8(Gnan))
title 'Corrupted - 50%'
subplot(1,3,3)
image(uint8(G))
title 'Inpainted Garden'
%% Surface fit artifact removal
[x,y] = meshgrid(0:.01:1);
z0 = exp(x+y);
znan = z0;
znan(20:50,40:70) = NaN;
znan(30:90,5:10) = NaN;
znan(70:75,40:90) = NaN;
tic,z = inpaint_nans(znan,3);toc
tic
k = isnan(znan);
zk = griddata(x(~k),y(~k),z(~k),x(k),y(k));
zg = znan;
zg(k) = zk;
toc
figure
surf(z0)
title 'Original surface'
figure
surf(znan)
title 'Artifacts (large holes) in surface'
figure
surf(zg)
title(['Griddata inpainting (',num2str(sum(isnan(zg(:)))),' NaNs remain)'])
figure
surf(z)
title 'Inpainted surface'
figure
surf(zg-z0)
title 'Griddata error surface'
figure
surf(z-z0)
title 'Inpainting error surface (Note z-axis scale)'
%% Comparison of methods
[x,y] = meshgrid(-1:.02:1);
r = sqrt(x.^2 + y.^2);
z = exp(-(x.^2+ y.^2));
z(r>=0.9) = NaN;
z((r<=.5) & (x<0)) = NaN;
figure
pcolor(z);
title 'Surface provided to inpaint_nans'
% Method 0
tic,z0 = inpaint_nans(z,0);toc
% Method 1
tic,z1 = inpaint_nans(z,1);toc
% Method 2
tic,z2 = inpaint_nans(z,2);toc
% Method 3
tic,z3 = inpaint_nans(z,3);toc
% Method 4
tic,z4 = inpaint_nans(z,4);toc
% Method 5
tic,z5 = inpaint_nans(z,5);toc
figure
surf(z0)
colormap copper
hold on
h = surf(z);
set(h,'facecolor','r')
hold off
title 'Method 0 (Red was provided)'
figure
surf(z1)
hold on
h = surf(z);
set(h,'facecolor','r')
hold off
title 'Method 1 (Red was provided)'
figure
surf(z2)
hold on
h = surf(z);
set(h,'facecolor','r')
hold off
title 'Method 2 (Red was provided) - least accurate, but fastest'
figure
surf(z3)
hold on
h = surf(z);
set(h,'facecolor','r')
hold off
title 'Method 3 (Red was provided) - Slow, but accurate'
figure
surf(z4)
hold on
h = surf(z);
set(h,'facecolor','r')
hold off
title 'Method 4 (Red was provided) - designed for constant extrapolation!'
figure
h = surf(z5);
set(h,'facecolor','y')
hold on
h = surf(z);
set(h,'facecolor','r')
hold off
title 'Method 5 (Red was provided)'
%% 1-d "inpainting" using interp1
x = linspace(0,3*pi,100);
y0 = sin(x);
y = y0;
% Drop out 2/3 of the data
y(1:3:end) = NaN;
y(2:3:end) = NaN;
% inpaint_nans
y_inpaint = inpaint_nans(y,1);
% interpolate using interp1
k = isnan(y);
y_interp1c = y;
y_interp1s = y;
y_interp1c(k) = interp1(x(~k),y(~k),x(k),'cubic');
y_interp1s(k) = interp1(x(~k),y(~k),x(k),'spline');
figure
plot(x,y,'ro',x,y_inpaint,'b+')
legend('sin(x), missing 2/3 points','inpaint-nans','Location','North')
figure
plot(x,y0-y_inpaint,'r-',x,y0-y_interp1c,'b--',x,y0-y_interp1s,'g--')
title 'Inpainting residuals'
legend('Inpaint-nans','Pchip','Spline','Location','North')

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2015 Kelly Kearney
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,377 @@
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--
This HTML was auto-generated from MATLAB code.
To make changes, update the MATLAB code and republish this document.
--><title>boundedline.m: line with shaded error/confidence bounds</title><meta name="generator" content="MATLAB 9.1"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2017-08-08"><meta name="DC.source" content="./readmeExtras/README.m"><style type="text/css">
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:'';content:none}:focus{outine:0}ins{text-decoration:none}del{text-decoration:line-through}table{border-collapse:collapse;border-spacing:0}
html { min-height:100%; margin-bottom:1px; }
html body { height:100%; margin:0px; font-family:Arial, Helvetica, sans-serif; font-size:10px; color:#000; line-height:140%; background:#fff none; overflow-y:scroll; }
html body td { vertical-align:top; text-align:left; }
h1 { padding:0px; margin:0px 0px 25px; font-family:Arial, Helvetica, sans-serif; font-size:1.5em; color:#d55000; line-height:100%; font-weight:normal; }
h2 { padding:0px; margin:0px 0px 8px; font-family:Arial, Helvetica, sans-serif; font-size:1.2em; color:#000; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }
h3 { padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:1.1em; color:#000; font-weight:bold; line-height:140%; }
a { color:#005fce; text-decoration:none; }
a:hover { color:#005fce; text-decoration:underline; }
a:visited { color:#004aa0; text-decoration:none; }
p { padding:0px; margin:0px 0px 20px; }
img { padding:0px; margin:0px 0px 20px; border:none; }
p img, pre img, tt img, li img, h1 img, h2 img { margin-bottom:0px; }
ul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }
ul li { padding:0px; margin:0px 0px 7px 0px; }
ul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }
ul li ol li { list-style:decimal; }
ol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }
ol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }
ol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }
ol li ol li { list-style-type:lower-alpha; }
ol li ul { padding-top:7px; }
ol li ul li { list-style:square; }
.content { font-size:1.2em; line-height:140%; padding: 20px; }
pre, code { font-size:12px; }
tt { font-size: 1.2em; }
pre { margin:0px 0px 20px; }
pre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }
pre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }
pre.error { color:red; }
@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }
span.keyword { color:#0000FF }
span.comment { color:#228B22 }
span.string { color:#A020F0 }
span.untermstring { color:#B20000 }
span.syscmd { color:#B28C00 }
.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }
.footer p { margin:0px; }
.footer a { color:#878787; }
.footer a:hover { color:#878787; text-decoration:underline; }
.footer a:visited { color:#878787; }
table th { padding:7px 5px; text-align:left; vertical-align:middle; border: 1px solid #d6d4d4; font-weight:bold; }
table td { padding:7px 5px; text-align:left; vertical-align:top; border:1px solid #d6d4d4; }
</style></head><body><div class="content"><h1><tt>boundedline.m</tt>: line with shaded error/confidence bounds</h1><!--introduction--><p>Author: Kelly Kearney</p><p>This repository includes the code for the <tt>boundedline.m</tt> Matlab function and the accompanying <tt>outlinebounds.m</tt> function, along with all dependent functions required to run them.</p><p>The <tt>boundedline</tt> function allows a user to easily plot and line with a shaded patch around it. Ths sort of plot is often used to indicate uncertainty intervals or error bounds around a line.</p><!--/introduction--><h2>Contents</h2><div><ul><li><a href="#1">Getting started</a></li><li><a href="#2">Syntax</a></li><li><a href="#3">Example 1: Plotting lines using various syntax options</a></li><li><a href="#7">Example 2: Filling gaps</a></li><li><a href="#12">Contributions</a></li></ul></div><h2 id="1">Getting started</h2><p><b>Prerequisites</b></p><p>This function requires Matlab R14 or later.</p><p><b>Downloading and installation</b></p><p>This code can be downloaded from <a href="https://github.com/kakearney/boundedline-pkg/">Github</a> or the <a href="http://www.mathworks.com/matlabcentral/fileexchange/27485-boundedline-m">MatlabCentral File Exchange</a>. The File Exchange entry is updated daily from the GitHub repository.</p><p><b>Matlab Search Path</b></p><p>The following folders need to be added to your Matlab Search path (via <tt>addpath</tt>, <tt>pathtool</tt>, etc.):</p><pre class="language-matlab">boundedline-pkg/Inpaint_nans
boundedline-pkg/boundedline
boundedline-pkg/catuneven
boundedline-pkg/singlepatch
</pre><h2 id="2">Syntax</h2><p><tt>boundedline(x, y, b)</tt> plots a line with coordinates given by <tt>x</tt> and <tt>y</tt>, surrounded by a patch extending a certain distance <tt>b</tt> above/below that line. The dimensions of the <tt>x</tt>, <tt>y</tt>, and <tt>b</tt> arrays can vary to allow for multiple lines to be plotted at once, and for patch bounds to be either constant or varying along the length of the line. See function header help for full details of these variations.</p><p><tt>boundedline(..., 'alpha')</tt> renders the bounded area patch using a partially-transparent patch the same color as the corresponding line(s). If not included, the bounded area will use a fully-opaque patch in a lighter shade of the corresponding line color.</p><p><tt>boundedline(..., 'transparency', transp)</tt> indicates the tranparency or intensity of the bounds patch, using a scalar between 0 and 1. Default is 0.2.</p><p><tt>boundedline(..., 'orientation', orient)</tt> indicates the orientation of the bounds. Orientation can be either <tt>'vert'</tt> for vertical (y-direction) bounds, or <tt>'horiz'</tt> for horizontal (x-direction) bounds. Default is <tt>'vert'</tt>.</p><p><tt>boundedline(..., 'nan', nanflag)</tt> indicates how the bounds patch should handle NaNs in the line coordinates or bounds values. Options are <tt>'fill'</tt>, to smooth over the gap using neighboring values, <tt>'gap'</tt> to leave a blank space in the patch at those points, or <tt>'remove'</tt> to drop the NaN-points entirely, leading to linear interpolation of the gap in the patch. See examples below for more details on these options.</p><p><tt>boundedline(..., 'cmap', cmap)</tt> colors the lines (in order of plotting) acording to the colors in this n x 3 colormap array, overriding any linespec or default colors.</p><p><tt>boundedline(..., ax)</tt> plots the bounded line to the axis indicated by handle <tt>ax</tt>. If not included, the current axis is used.</p><p><tt>[hl, hp] = boundedline(...)</tt> returns the handles the resulting line and patch object(s).</p><p><tt>hout = outlinebounds(hl, hp)</tt> adds an outline to the bounds patch generated by <tt>boundedline</tt>, returning the handle of the resulting line object in <tt>hout</tt>.</p><p>Full details of all input and output variables for both functions can be accessed via the <tt>help</tt> function.</p><h2 id="3">Example 1: Plotting lines using various syntax options</h2><p>This example builds the 4-panel example image used on the MatlabCentral File Exchange, which shows several different methods for supplying line coordinates, bounds coordinates, and shading options.</p><p>The first axis plots two lines using the LineSpec option for input, which allows yoy to set line color, line color, and marker type for each line. The bounds on the first line vary over x, while the bounds on the second line are constant for all x. An outline is added to the bounds so the overlapping region can be seen more clearly.</p><pre class="codeinput">x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
e1 = rand(size(y1))*.5+.5;
e2 = [.25 .5];
ax(1) = subplot(2,2,1);
[l,p] = boundedline(x, y1, e1, <span class="string">'-b*'</span>, x, y2, e2, <span class="string">'--ro'</span>);
outlinebounds(l,p);
title(<span class="string">'Opaque bounds, with outline'</span>);
axis <span class="string">tight</span>;
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_01.png" alt=""> <p>For our second axis, we use the same 2 lines, and this time assign x-varying bounds to both lines. Rather than using the LineSpec syntax, this example uses the default color order to assign the colors of the lines and patches. I also turn on the <tt>'alpha'</tt> option, which renders the patch wit partial transparency.</p><pre class="codeinput">ax(2) = subplot(2,2,2);
boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, <span class="string">'alpha'</span>);
title(<span class="string">'Transparent bounds'</span>);
axis <span class="string">tight</span>;
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_02.png" alt=""> <p>The bounds can also be assigned to a horizontal orientation, for a case where the x-axis represents the dependent variable. In this case, the scalar error bound value applies to both lines and both sides of the lines.</p><pre class="codeinput">ax(3) = subplot(2,2,3);
boundedline([y1;y2], x, e1(1), <span class="string">'orientation'</span>, <span class="string">'horiz'</span>)
title(<span class="string">'Horizontal bounds'</span>);
axis <span class="string">tight</span>;
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_03.png" alt=""> <p>Rather than use a LineSpec or the default color order, a colormap array can be used to assign colors. In this case, increasingly-narrower bounds are added on top of the same line.</p><pre class="codeinput">ax(4) = subplot(2,2,4);
boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), <span class="keyword">...</span>
<span class="string">'cmap'</span>, cool(4), <span class="keyword">...</span>
<span class="string">'transparency'</span>, 0.5);
title(<span class="string">'Multiple bounds using colormap'</span>);
set(ax([1 2 4]), <span class="string">'xlim'</span>, [0 2*pi]);
set(ax(3), <span class="string">'ylim'</span>, [0 2*pi]);
axis <span class="string">tight</span>;
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_04.png" alt=""> <h2 id="7">Example 2: Filling gaps</h2><p>If you plot a line with one or more NaNs in either the <tt>x</tt> or <tt>y</tt> vector, the NaN location is rendered as a missing marker with a gap in the line. However, the <tt>patch</tt> command does not handle NaNs gracefully; it simply fails to show the patch at all if any of the coordinates include NaNs.</p><p>Because of this, the expected behavior of the patch part of boundedline when confronted with a NaN in either the bounds array (<tt>b</tt>) or the x/y-coordinates of the line (which are used to calculate the patch coordinates) is ambiguous. I offer a few options.</p><p>Before I demonstrate the options, I'll create a dataset that has a few different types of gaps:</p><pre class="codeinput">x = linspace(0, 2*pi, 50);
y = sin(x);
b = [ones(size(y))*0.2; rand(size(y))*.5+.5]';
y(10) = NaN; <span class="comment">% NaN in the line but not bounds</span>
b(20,1) = NaN; <span class="comment">% NaN in lower bound but not line</span>
b(30,2) = NaN; <span class="comment">% NaN in upper bound but not line</span>
b(40,:) = NaN; <span class="comment">% NaN in both sides of bound but not line</span>
</pre><p>Here's what that looks like in an errorbar plot.</p><pre class="codeinput">figure;
he = errorbar(x,y,b(:,1), b(:,2), <span class="string">'-bo'</span>);
line([x([10 20 30 40]); x([10 20 30 40])], [ones(1,4)*-2;ones(1,4)*2], <span class="keyword">...</span>
<span class="string">'color'</span>, ones(1,3)*0.5, <span class="string">'linestyle'</span>, <span class="string">':'</span>);
text(x(10), sin(x(10))-0.2, {<span class="string">'\uparrow'</span>,<span class="string">'Line'</span>,<span class="string">'gap'</span>}, <span class="string">'vert'</span>, <span class="string">'top'</span>, <span class="string">'horiz'</span>, <span class="string">'center'</span>);
text(x(20), sin(x(20))-0.2, {<span class="string">'\uparrow'</span>,<span class="string">'Lower'</span>,<span class="string">'bound'</span>,<span class="string">'gap'</span>}, <span class="string">'vert'</span>, <span class="string">'top'</span>, <span class="string">'horiz'</span>, <span class="string">'center'</span>);
text(x(30), sin(x(30))-0.2, {<span class="string">'\uparrow'</span>,<span class="string">'Upper'</span>,<span class="string">'bound'</span>,<span class="string">'gap'</span>}, <span class="string">'vert'</span>, <span class="string">'top'</span>, <span class="string">'horiz'</span>, <span class="string">'center'</span>);
text(x(40), sin(x(40))-0.2, {<span class="string">'\uparrow'</span>,<span class="string">'Two-sided'</span>,<span class="string">'bound'</span>,<span class="string">'gap'</span>}, <span class="string">'vert'</span>, <span class="string">'top'</span>, <span class="string">'horiz'</span>, <span class="string">'center'</span>);
axis <span class="string">tight</span> <span class="string">equal</span>;
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_05.png" alt=""> <p>The default method for dealing with NaNs in boundedline is to leave the gap in the line, but smooth over the gap in the bounds based on the neighboring points. This option can be nice if you only have one or two missing points, and you're not interested in emphasizing those gaps in your plot:</p><pre class="codeinput">delete(he);
[hl,hp] = boundedline(x,y,b,<span class="string">'-bo'</span>, <span class="string">'nan'</span>, <span class="string">'fill'</span>);
ho = outlinebounds(hl,hp);
set(ho, <span class="string">'linestyle'</span>, <span class="string">':'</span>, <span class="string">'color'</span>, <span class="string">'r'</span>, <span class="string">'marker'</span>, <span class="string">'.'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_06.png" alt=""> <p>I've added bounds outlines in a contrasting color so you can see how I'm handling individual points.</p><p>The second option leaves a full gap in the patch for any NaN. I considered allowing one-sided gaps, but couldn't think of a good way to distinguish a gap from a zero-valued bound. I'm open to suggestions if you have any (email me).</p><pre class="codeinput">delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,<span class="string">'-bo'</span>, <span class="string">'nan'</span>, <span class="string">'gap'</span>);
ho = outlinebounds(hl,hp);
set(ho, <span class="string">'linestyle'</span>, <span class="string">':'</span>, <span class="string">'color'</span>, <span class="string">'r'</span>, <span class="string">'marker'</span>, <span class="string">'.'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_07.png" alt=""> <p>The final option removes points from the patch that are NaNs. The visual result is very similar to the fill option, but the missing points are apparent if you plot the bounds outlines.</p><pre class="codeinput">delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,<span class="string">'-bo'</span>, <span class="string">'nan'</span>, <span class="string">'remove'</span>);
ho = outlinebounds(hl,hp);
set(ho, <span class="string">'linestyle'</span>, <span class="string">':'</span>, <span class="string">'color'</span>, <span class="string">'r'</span>, <span class="string">'marker'</span>, <span class="string">'.'</span>);
</pre><img vspace="5" hspace="5" src="./readmeExtras/README_08.png" alt=""> <h2 id="12">Contributions</h2><p>Community contributions to this package are welcome!</p><p>To report bugs, please submit <a href="https://github.com/kakearney/boundedline-pkg/issues">an issue</a> on GitHub and include:</p><div><ul><li>your operating system</li><li>your version of Matlab and all relevant toolboxes (type <tt>ver</tt> at the Matlab command line to get this info)</li><li>code/data to reproduce the error or buggy behavior, and the full text of any error messages received</li></ul></div><p>Please also feel free to submit enhancement requests, or to send pull requests (via GitHub) for bug fixes or new features.</p><p>I do monitor the MatlabCentral FileExchange entry for any issues raised in the comments, but would prefer to track issues on GitHub.</p><p class="footer"><br><a href="http://www.mathworks.com/products/matlab/">Published with MATLAB&reg; R2016b</a><br></p></div><!--
##### SOURCE BEGIN #####
%% |boundedline.m|: line with shaded error/confidence bounds
% Author: Kelly Kearney
%
% This repository includes the code for the |boundedline.m| Matlab function
% and the accompanying |outlinebounds.m| function, along with all dependent
% functions required to run them.
%
% The |boundedline| function allows a user to easily plot and line with a
% shaded patch around it. Ths sort of plot is often used to indicate
% uncertainty intervals or error bounds around a line.
%
%% Getting started
%
% *Prerequisites*
%
% This function requires Matlab R14 or later.
%
% *Downloading and installation*
%
% This code can be downloaded from <https://github.com/kakearney/boundedline-pkg/ Github>
% or the
% <http://www.mathworks.com/matlabcentral/fileexchange/27485-boundedline-m
% MatlabCentral File Exchange>. The File Exchange entry is updated daily
% from the GitHub repository.
%
% *Matlab Search Path*
%
% The following folders need to be added to your Matlab Search path (via
% |addpath|, |pathtool|, etc.):
%
% boundedline-pkg/Inpaint_nans
% boundedline-pkg/boundedline
% boundedline-pkg/catuneven
% boundedline-pkg/singlepatch
%% Syntax
%
% |boundedline(x, y, b)| plots a line with coordinates given by
% |x| and |y|, surrounded by a patch extending a certain distance |b|
% above/below that line. The dimensions of the |x|, |y|, and |b| arrays
% can vary to allow for multiple lines to be plotted at once, and for
% patch bounds to be either constant or varying along the length of the
% line. See function header help for full details of these variations.
%
% |boundedline(..., 'alpha')| renders the bounded area patch using a
% partially-transparent patch the same color as the corresponding line(s).
% If not included, the bounded area will use a fully-opaque patch in a
% lighter shade of the corresponding line color.
%
% |boundedline(..., 'transparency', transp)| indicates the
% tranparency or intensity of the bounds patch, using a scalar between 0
% and 1. Default is 0.2.
%
% |boundedline(..., 'orientation', orient)| indicates the orientation of
% the bounds. Orientation can be either |'vert'| for vertical (y-direction)
% bounds, or |'horiz'| for horizontal (x-direction) bounds. Default is
% |'vert'|.
%
% |boundedline(..., 'nan', nanflag)| indicates how the bounds patch should
% handle NaNs in the line coordinates or bounds values. Options are
% |'fill'|, to smooth over the gap using neighboring values, |'gap'| to
% leave a blank space in the patch at those points, or |'remove'| to drop
% the NaN-points entirely, leading to linear interpolation of the gap in
% the patch. See examples below for more details on these options.
%
% |boundedline(..., 'cmap', cmap)| colors the lines (in order of plotting)
% acording to the colors in this n x 3 colormap array, overriding any
% linespec or default colors.
%
% |boundedline(..., ax)| plots the bounded line to the axis indicated by
% handle |ax|. If not included, the current axis is used.
%
% |[hl, hp] = boundedline(...)| returns the handles the resulting line
% and patch object(s).
%
% |hout = outlinebounds(hl, hp)| adds an outline to the bounds patch
% generated by |boundedline|, returning the handle of the resulting line
% object in |hout|.
%
% Full details of all input and output variables for both functions can be
% accessed via the |help| function.
%% Example 1: Plotting lines using various syntax options
%
% This example builds the 4-panel example image used on the MatlabCentral
% File Exchange, which shows several different methods for supplying line
% coordinates, bounds coordinates, and shading options.
%
% The first axis plots two lines using the LineSpec option for input, which
% allows yoy to set line color, line color, and marker type for each line.
% The bounds on the first line vary over x, while the bounds on the second
% line are constant for all x. An outline is added to the bounds so the
% overlapping region can be seen more clearly.
x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
e1 = rand(size(y1))*.5+.5;
e2 = [.25 .5];
ax(1) = subplot(2,2,1);
[l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, 'REPLACE_WITH_DASH_DASHro');
outlinebounds(l,p);
title('Opaque bounds, with outline');
axis tight;
%%
% For our second axis, we use the same 2 lines, and this time assign
% x-varying bounds to both lines. Rather than using the LineSpec syntax,
% this example uses the default color order to assign the colors of the
% lines and patches. I also turn on the |'alpha'| option, which renders
% the patch wit partial transparency.
ax(2) = subplot(2,2,2);
boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');
title('Transparent bounds');
axis tight;
%%
% The bounds can also be assigned to a horizontal orientation, for a case
% where the x-axis represents the dependent variable. In this case, the
% scalar error bound value applies to both lines and both sides of the
% lines.
ax(3) = subplot(2,2,3);
boundedline([y1;y2], x, e1(1), 'orientation', 'horiz')
title('Horizontal bounds');
axis tight;
%%
% Rather than use a LineSpec or the default color order, a colormap array
% can be used to assign colors. In this case, increasingly-narrower bounds
% are added on top of the same line.
ax(4) = subplot(2,2,4);
boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), ...
'cmap', cool(4), ...
'transparency', 0.5);
title('Multiple bounds using colormap');
set(ax([1 2 4]), 'xlim', [0 2*pi]);
set(ax(3), 'ylim', [0 2*pi]);
axis tight;
%% Example 2: Filling gaps
%
% If you plot a line with one or more NaNs in either the |x| or |y| vector,
% the NaN location is rendered as a missing marker with a gap in the line.
% However, the |patch| command does not handle NaNs gracefully; it simply
% fails to show the patch at all if any of the coordinates include NaNs.
%
% Because of this, the expected behavior of the patch part of boundedline
% when confronted with a NaN in either the bounds array (|b|) or the
% x/y-coordinates of the line (which are used to calculate the patch
% coordinates) is ambiguous. I offer a few options.
%
% Before I demonstrate the options, I'll create a dataset that has a few
% different types of gaps:
x = linspace(0, 2*pi, 50);
y = sin(x);
b = [ones(size(y))*0.2; rand(size(y))*.5+.5]';
y(10) = NaN; % NaN in the line but not bounds
b(20,1) = NaN; % NaN in lower bound but not line
b(30,2) = NaN; % NaN in upper bound but not line
b(40,:) = NaN; % NaN in both sides of bound but not line
%%
% Here's what that looks like in an errorbar plot.
figure;
he = errorbar(x,y,b(:,1), b(:,2), '-bo');
line([x([10 20 30 40]); x([10 20 30 40])], [ones(1,4)*-2;ones(1,4)*2], ...
'color', ones(1,3)*0.5, 'linestyle', ':');
text(x(10), sin(x(10))-0.2, {'\uparrow','Line','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(20), sin(x(20))-0.2, {'\uparrow','Lower','bound','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(30), sin(x(30))-0.2, {'\uparrow','Upper','bound','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(40), sin(x(40))-0.2, {'\uparrow','Two-sided','bound','gap'}, 'vert', 'top', 'horiz', 'center');
axis tight equal;
%%
% The default method for dealing with NaNs in boundedline is to leave the
% gap in the line, but smooth over the gap in the bounds based on the
% neighboring points. This option can be nice if you only have one or two
% missing points, and you're not interested in emphasizing those gaps in
% your plot:
delete(he);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'fill');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
%%
% I've added bounds outlines in a contrasting color so you can see how I'm
% handling individual points.
%
% The second option leaves a full gap in the patch for any NaN. I
% considered allowing one-sided gaps, but couldn't think of a good way to
% distinguish a gap from a zero-valued bound. I'm open to suggestions if
% you have any (email me).
delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'gap');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
%%
% The final option removes points from the patch that are NaNs. The visual
% result is very similar to the fill option, but the missing points are
% apparent if you plot the bounds outlines.
delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'remove');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
%% Contributions
%
% Community contributions to this package are welcome!
%
% To report bugs, please submit
% <https://github.com/kakearney/boundedline-pkg/issues an issue> on GitHub and
% include:
%
% * your operating system
% * your version of Matlab and all relevant toolboxes (type |ver| at the Matlab command line to get this info)
% * code/data to reproduce the error or buggy behavior, and the full text of any error messages received
%
% Please also feel free to submit enhancement requests, or to send pull
% requests (via GitHub) for bug fixes or new features.
%
% I do monitor the MatlabCentral FileExchange entry for any issues raised
% in the comments, but would prefer to track issues on GitHub.
%
##### SOURCE END #####
--></body></html>

240
Libs/boundedlines/README.m Normal file
View File

@@ -0,0 +1,240 @@
%% |boundedline.m|: line with shaded error/confidence bounds
% Author: Kelly Kearney
%
% This repository includes the code for the |boundedline.m| Matlab function
% and the accompanying |outlinebounds.m| function, along with all dependent
% functions required to run them.
%
% The |boundedline| function allows a user to easily plot and line with a
% shaded patch around it. Ths sort of plot is often used to indicate
% uncertainty intervals or error bounds around a line.
%
%% Getting started
%
% *Prerequisites*
%
% This function requires Matlab R14 or later.
%
% *Downloading and installation*
%
% This code can be downloaded from <https://github.com/kakearney/boundedline-pkg/ Github>
% or the
% <http://www.mathworks.com/matlabcentral/fileexchange/27485-boundedline-m
% MatlabCentral File Exchange>. The File Exchange entry is updated daily
% from the GitHub repository.
%
% *Matlab Search Path*
%
% The following folders need to be added to your Matlab Search path (via
% |addpath|, |pathtool|, etc.):
%
% boundedline-pkg/Inpaint_nans
% boundedline-pkg/boundedline
% boundedline-pkg/catuneven
% boundedline-pkg/singlepatch
%% Syntax
%
% |boundedline(x, y, b)| plots a line with coordinates given by
% |x| and |y|, surrounded by a patch extending a certain distance |b|
% above/below that line. The dimensions of the |x|, |y|, and |b| arrays
% can vary to allow for multiple lines to be plotted at once, and for
% patch bounds to be either constant or varying along the length of the
% line. See function header help for full details of these variations.
%
% |boundedline(..., 'alpha')| renders the bounded area patch using a
% partially-transparent patch the same color as the corresponding line(s).
% If not included, the bounded area will use a fully-opaque patch in a
% lighter shade of the corresponding line color.
%
% |boundedline(..., 'transparency', transp)| indicates the
% tranparency or intensity of the bounds patch, using a scalar between 0
% and 1. Default is 0.2.
%
% |boundedline(..., 'orientation', orient)| indicates the orientation of
% the bounds. Orientation can be either |'vert'| for vertical (y-direction)
% bounds, or |'horiz'| for horizontal (x-direction) bounds. Default is
% |'vert'|.
%
% |boundedline(..., 'nan', nanflag)| indicates how the bounds patch should
% handle NaNs in the line coordinates or bounds values. Options are
% |'fill'|, to smooth over the gap using neighboring values, |'gap'| to
% leave a blank space in the patch at those points, or |'remove'| to drop
% the NaN-points entirely, leading to linear interpolation of the gap in
% the patch. See examples below for more details on these options.
%
% |boundedline(..., 'cmap', cmap)| colors the lines (in order of plotting)
% acording to the colors in this n x 3 colormap array, overriding any
% linespec or default colors.
%
% |boundedline(..., ax)| plots the bounded line to the axis indicated by
% handle |ax|. If not included, the current axis is used.
%
% |[hl, hp] = boundedline(...)| returns the handles the resulting line
% and patch object(s).
%
% |hout = outlinebounds(hl, hp)| adds an outline to the bounds patch
% generated by |boundedline|, returning the handle of the resulting line
% object in |hout|.
%
% Full details of all input and output variables for both functions can be
% accessed via the |help| function.
%% Example 1: Plotting lines using various syntax options
%
% This example builds the 4-panel example image used on the MatlabCentral
% File Exchange, which shows several different methods for supplying line
% coordinates, bounds coordinates, and shading options.
%
% The first axis plots two lines using the LineSpec option for input, which
% allows yoy to set line color, line color, and marker type for each line.
% The bounds on the first line vary over x, while the bounds on the second
% line are constant for all x. An outline is added to the bounds so the
% overlapping region can be seen more clearly.
x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
e1 = rand(size(y1))*.5+.5;
e2 = [.25 .5];
ax(1) = subplot(2,2,1);
[l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');
outlinebounds(l,p);
title('Opaque bounds, with outline');
axis tight;
%%
% For our second axis, we use the same 2 lines, and this time assign
% x-varying bounds to both lines. Rather than using the LineSpec syntax,
% this example uses the default color order to assign the colors of the
% lines and patches. I also turn on the |'alpha'| option, which renders
% the patch with partial transparency.
ax(2) = subplot(2,2,2);
boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');
title('Transparent bounds');
axis tight;
%%
% The bounds can also be assigned to a horizontal orientation, for a case
% where the x-axis represents the dependent variable. In this case, the
% scalar error bound value applies to both lines and both sides of the
% lines.
ax(3) = subplot(2,2,3);
boundedline([y1;y2], x, e1(1), 'orientation', 'horiz')
title('Horizontal bounds');
axis tight;
%%
% Rather than use a LineSpec or the default color order, a colormap array
% can be used to assign colors. In this case, increasingly-narrower bounds
% are added on top of the same line.
ax(4) = subplot(2,2,4);
boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), ...
'cmap', cool(4), ...
'transparency', 0.5);
title('Multiple bounds using colormap');
set(ax([1 2 4]), 'xlim', [0 2*pi]);
set(ax(3), 'ylim', [0 2*pi]);
axis tight;
%% Example 2: Filling gaps
%
% If you plot a line with one or more NaNs in either the |x| or |y| vector,
% the NaN location is rendered as a missing marker with a gap in the line.
% However, the |patch| command does not handle NaNs gracefully; it simply
% fails to show the patch at all if any of the coordinates include NaNs.
%
% Because of this, the expected behavior of the patch part of boundedline
% when confronted with a NaN in either the bounds array (|b|) or the
% x/y-coordinates of the line (which are used to calculate the patch
% coordinates) is ambiguous. I offer a few options.
%
% Before I demonstrate the options, I'll create a dataset that has a few
% different types of gaps:
x = linspace(0, 2*pi, 50);
y = sin(x);
b = [ones(size(y))*0.2; rand(size(y))*.5+.5]';
y(10) = NaN; % NaN in the line but not bounds
b(20,1) = NaN; % NaN in lower bound but not line
b(30,2) = NaN; % NaN in upper bound but not line
b(40,:) = NaN; % NaN in both sides of bound but not line
%%
% Here's what that looks like in an errorbar plot.
figure;
he = errorbar(x,y,b(:,1), b(:,2), '-bo');
line([x([10 20 30 40]); x([10 20 30 40])], [ones(1,4)*-2;ones(1,4)*2], ...
'color', ones(1,3)*0.5, 'linestyle', ':');
text(x(10), sin(x(10))-0.2, {'\uparrow','Line','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(20), sin(x(20))-0.2, {'\uparrow','Lower','bound','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(30), sin(x(30))-0.2, {'\uparrow','Upper','bound','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(40), sin(x(40))-0.2, {'\uparrow','Two-sided','bound','gap'}, 'vert', 'top', 'horiz', 'center');
axis tight equal;
%%
% The default method for dealing with NaNs in boundedline is to leave the
% gap in the line, but smooth over the gap in the bounds based on the
% neighboring points. This option can be nice if you only have one or two
% missing points, and you're not interested in emphasizing those gaps in
% your plot:
delete(he);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'fill');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
%%
% I've added bounds outlines in a contrasting color so you can see how I'm
% handling individual points.
%
% The second option leaves a full gap in the patch for any NaN. I
% considered allowing one-sided gaps, but couldn't think of a good way to
% distinguish a gap from a zero-valued bound. I'm open to suggestions if
% you have any (email me).
delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'gap');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
%%
% The final option removes points from the patch that are NaNs. The visual
% result is very similar to the fill option, but the missing points are
% apparent if you plot the bounds outlines.
delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'remove');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
%% Contributions
%
% Community contributions to this package are welcome!
%
% To report bugs, please submit
% <https://github.com/kakearney/boundedline-pkg/issues an issue> on GitHub and
% include:
%
% * your operating system
% * your version of Matlab and all relevant toolboxes (type |ver| at the Matlab command line to get this info)
% * code/data to reproduce the error or buggy behavior, and the full text of any error messages received
%
% Please also feel free to submit enhancement requests, or to send pull
% requests (via GitHub) for bug fixes or new features.
%
% I do monitor the MatlabCentral FileExchange entry for any issues raised
% in the comments, but would prefer to track issues on GitHub.
%

279
Libs/boundedlines/README.md Normal file
View File

@@ -0,0 +1,279 @@
# boundedline.m: line with shaded error/confidence bounds
Author: Kelly Kearney
[![View boundedline.m on File Exchange](https://www.mathworks.com/matlabcentral/images/matlab-file-exchange.svg)](https://www.mathworks.com/matlabcentral/fileexchange/27485-boundedline-m)
This repository includes the code for the `boundedline.m` Matlab function and the accompanying `outlinebounds.m` function, along with all dependent functions required to run them.
The `boundedline` function allows a user to easily plot and line with a shaded patch around it. Ths sort of plot is often used to indicate uncertainty intervals or error bounds around a line.
## Contents
- Getting started
- Syntax
- Example 1: Plotting lines using various syntax options
- Example 2: Filling gaps
- Contributions
## Getting started
**Prerequisites**
This function requires Matlab R14 or later.
**Downloading and installation**
This code can be downloaded from [Github](https://github.com/kakearney/boundedline-pkg/) or the [MatlabCentral File Exchange](http://www.mathworks.com/matlabcentral/fileexchange/27485-boundedline-m). The File Exchange entry is updated daily from the GitHub repository.
**Matlab Search Path**
The following folders need to be added to your Matlab Search path (via `addpath`, `pathtool`, etc.):
```matlab
boundedline-pkg/Inpaint_nans
boundedline-pkg/boundedline
boundedline-pkg/catuneven
boundedline-pkg/singlepatch
```
## Syntax
`boundedline(x, y, b)` plots a line with coordinates given by `x` and `y`, surrounded by a patch extending a certain distance `b` above/below that line. The dimensions of the `x`, `y`, and `b` arrays can vary to allow for multiple lines to be plotted at once, and for patch bounds to be either constant or varying along the length of the line. See function header help for full details of these variations.
`boundedline(..., 'alpha')` renders the bounded area patch using a partially-transparent patch the same color as the corresponding line(s). If not included, the bounded area will use a fully-opaque patch in a lighter shade of the corresponding line color.
`boundedline(..., 'transparency', transp)` indicates the tranparency or intensity of the bounds patch, using a scalar between 0 and 1. Default is 0.2.
`boundedline(..., 'orientation', orient)` indicates the orientation of the bounds. Orientation can be either `'vert'` for vertical (y-direction) bounds, or `'horiz'` for horizontal (x-direction) bounds. Default is `'vert'`.
`boundedline(..., 'nan', nanflag)` indicates how the bounds patch should handle NaNs in the line coordinates or bounds values. Options are `'fill'`, to smooth over the gap using neighboring values, `'gap'` to leave a blank space in the patch at those points, or `'remove'` to drop the NaN-points entirely, leading to linear interpolation of the gap in the patch. See examples below for more details on these options.
`boundedline(..., 'cmap', cmap)` colors the lines (in order of plotting) acording to the colors in this n x 3 colormap array, overriding any linespec or default colors.
`boundedline(..., ax)` plots the bounded line to the axis indicated by handle `ax`. If not included, the current axis is used.
`[hl, hp] = boundedline(...)` returns the handles the resulting line and patch object(s).
`hout = outlinebounds(hl, hp)` adds an outline to the bounds patch generated by `boundedline`, returning the handle of the resulting line object in `hout`.
Full details of all input and output variables for both functions can be accessed via the `help` function.
## Example 1: Plotting lines using various syntax options
This example builds the 4-panel example image used on the MatlabCentral File Exchange, which shows several different methods for supplying line coordinates, bounds coordinates, and shading options.
The first axis plots two lines using the LineSpec option for input, which allows you to set line color, line color, and marker type for each line. The bounds on the first line vary over x, while the bounds on the second line are constant for all x. An outline is added to the bounds so the overlapping region can be seen more clearly.
```matlab
x = linspace(0, 2*pi, 50);
y1 = sin(x);
y2 = cos(x);
e1 = rand(size(y1))*.5+.5;
e2 = [.25 .5];
ax(1) = subplot(2,2,1);
[l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');
outlinebounds(l,p);
title('Opaque bounds, with outline');
axis tight;
```
![](./readmeExtras/README_01.png)
For our second axis, we use the same 2 lines, and this time assign x-varying bounds to both lines. Rather than using the LineSpec syntax, this example uses the default color order to assign the colors of the lines and patches. I also turn on the `'alpha'` option, which renders the patch with partial transparency.
```matlab
ax(2) = subplot(2,2,2);
boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');
title('Transparent bounds');
axis tight;
```
![](./readmeExtras/README_02.png)
The bounds can also be assigned to a horizontal orientation, for a case where the x-axis represents the dependent variable. In this case, the scalar error bound value applies to both lines and both sides of the lines.
```matlab
ax(3) = subplot(2,2,3);
boundedline([y1;y2], x, e1(1), 'orientation', 'horiz')
title('Horizontal bounds');
axis tight;
```
![](./readmeExtras/README_03.png)
Rather than use a LineSpec or the default color order, a colormap array can be used to assign colors. In this case, increasingly-narrower bounds are added on top of the same line.
```matlab
ax(4) = subplot(2,2,4);
boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), ...
'cmap', cool(4), ...
'transparency', 0.5);
title('Multiple bounds using colormap');
set(ax([1 2 4]), 'xlim', [0 2*pi]);
set(ax(3), 'ylim', [0 2*pi]);
axis tight;
```
![](./readmeExtras/README_04.png)
## Example 2: Filling gaps
If you plot a line with one or more NaNs in either the `x` or `y` vector, the NaN location is rendered as a missing marker with a gap in the line. However, the `patch` command does not handle NaNs gracefully; it simply fails to show the patch at all if any of the coordinates include NaNs.
Because of this, the expected behavior of the patch part of boundedline when confronted with a NaN in either the bounds array (`b`) or the x/y-coordinates of the line (which are used to calculate the patch coordinates) is ambiguous. I offer a few options.
Before I demonstrate the options, I'll create a dataset that has a few different types of gaps:
```matlab
x = linspace(0, 2*pi, 50);
y = sin(x);
b = [ones(size(y))*0.2; rand(size(y))*.5+.5]';
y(10) = NaN; % NaN in the line but not bounds
b(20,1) = NaN; % NaN in lower bound but not line
b(30,2) = NaN; % NaN in upper bound but not line
b(40,:) = NaN; % NaN in both sides of bound but not line
```
Here's what that looks like in an errorbar plot.
```matlab
figure;
he = errorbar(x,y,b(:,1), b(:,2), '-bo');
line([x([10 20 30 40]); x([10 20 30 40])], [ones(1,4)*-2;ones(1,4)*2], ...
'color', ones(1,3)*0.5, 'linestyle', ':');
text(x(10), sin(x(10))-0.2, {'\uparrow','Line','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(20), sin(x(20))-0.2, {'\uparrow','Lower','bound','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(30), sin(x(30))-0.2, {'\uparrow','Upper','bound','gap'}, 'vert', 'top', 'horiz', 'center');
text(x(40), sin(x(40))-0.2, {'\uparrow','Two-sided','bound','gap'}, 'vert', 'top', 'horiz', 'center');
axis tight equal;
```
![](./readmeExtras/README_05.png)
The default method for dealing with NaNs in boundedline is to leave the gap in the line, but smooth over the gap in the bounds based on the neighboring points. This option can be nice if you only have one or two missing points, and you're not interested in emphasizing those gaps in your plot:
```matlab
delete(he);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'fill');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
```
![](./readmeExtras/README_06.png)
I've added bounds outlines in a contrasting color so you can see how I'm handling individual points.
The second option leaves a full gap in the patch for any NaN. I considered allowing one-sided gaps, but couldn't think of a good way to distinguish a gap from a zero-valued bound. I'm open to suggestions if you have any (email me).
```matlab
delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'gap');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
```
![](./readmeExtras/README_07.png)
The final option removes points from the patch that are NaNs. The visual result is very similar to the fill option, but the missing points are apparent if you plot the bounds outlines.
```matlab
delete([hl hp ho]);
[hl,hp] = boundedline(x,y,b,'-bo', 'nan', 'remove');
ho = outlinebounds(hl,hp);
set(ho, 'linestyle', ':', 'color', 'r', 'marker', '.');
```
![](./readmeExtras/README_08.png)
## Contributions
Community contributions to this package are welcome!
To report bugs, please submit [an issue](https://github.com/kakearney/boundedline-pkg/issues) on GitHub and include:
- your operating system
- your version of Matlab and all relevant toolboxes (type `ver` at the Matlab command line to get this info)
- code/data to reproduce the error or buggy behavior, and the full text of any error messages received
Please also feel free to submit enhancement requests, or to send pull requests (via GitHub) for bug fixes or new features.
I do monitor the MatlabCentral FileExchange entry for any issues raised in the comments, but would prefer to track issues on GitHub.
<sub>[Published with MATLAB R2016b]("http://www.mathworks.com/products/matlab/")</sub>

View File

@@ -0,0 +1,37 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

View File

@@ -0,0 +1,501 @@
function varargout = boundedline(varargin)
%BOUNDEDLINE Plot a line with shaded error/confidence bounds
%
% [hl, hp] = boundedline(x, y, b)
% [hl, hp] = boundedline(x, y, b, linespec)
% [hl, hp] = boundedline(x1, y1, b1, linespec1, x2, y2, b2, linespec2)
% [hl, hp] = boundedline(..., 'alpha')
% [hl, hp] = boundedline(..., ax)
% [hl, hp] = boundedline(..., 'transparency', trans)
% [hl, hp] = boundedline(..., 'orientation', orient)
% [hl, hp] = boundedline(..., 'nan', nanflag)
% [hl, hp] = boundedline(..., 'cmap', cmap)
%
% Input variables:
%
% x, y: x and y values, either vectors of the same length, matrices
% of the same size, or vector/matrix pair where the row or
% column size of the array matches the length of the vector
% (same requirements as for plot function).
%
% b: npoint x nside x nline array. Distance from line to
% boundary, for each point along the line (dimension 1), for
% each side of the line (lower/upper or left/right, depending
% on orientation) (dimension 2), and for each plotted line
% described by the preceding x-y values (dimension 3). If
% size(b,1) == 1, the bounds will be the same for all points
% along the line. If size(b,2) == 1, the bounds will be
% symmetrical on both sides of the lines. If size(b,3) == 1,
% the same bounds will be applied to all lines described by
% the preceding x-y arrays (only applicable when either x or
% y is an array). Bounds cannot include Inf, -Inf, or NaN,
%
% linespec: line specification that determines line type, marker
% symbol, and color of the plotted lines for the preceding
% x-y values.
%
% 'alpha': if included, the bounded area will be rendered with a
% partially-transparent patch the same color as the
% corresponding line(s). If not included, the bounded area
% will be an opaque patch with a lighter shade of the
% corresponding line color.
%
% ax: handle of axis where lines will be plotted. If not
% included, the current axis will be used.
%
% transp: Scalar between 0 and 1 indicating with the transparency or
% intensity of color of the bounded area patch. Default is
% 0.2.
%
% orient: direction to add bounds
% 'vert': add bounds in vertical (y) direction (default)
% 'horiz': add bounds in horizontal (x) direction
%
% nanflag: Sets how NaNs in the boundedline patch should be handled
% 'fill': fill the value based on neighboring values,
% smoothing over the gap
% 'gap': leave a blank space over/below the line
% 'remove': drop NaNs from patches, creating a linear
% interpolation over the gap. Note that this
% applies only to the bounds; NaNs in the line will
% remain.
%
% cmap: n x 3 colormap array. If included, lines will be colored
% (in order of plotting) according to this colormap,
% overriding any linespec or default colors.
%
% Output variables:
%
% hl: handles to line objects
%
% hp: handles to patch objects
%
% Example:
%
% x = linspace(0, 2*pi, 50);
% y1 = sin(x);
% y2 = cos(x);
% e1 = rand(size(y1))*.5+.5;
% e2 = [.25 .5];
%
% ax(1) = subplot(2,2,1);
% [l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');
% outlinebounds(l,p);
% title('Opaque bounds, with outline');
%
% ax(2) = subplot(2,2,2);
% boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');
% title('Transparent bounds');
%
% ax(3) = subplot(2,2,3);
% boundedline([y1;y2], x, e1(1), 'orientation', 'horiz')
% title('Horizontal bounds');
%
% ax(4) = subplot(2,2,4);
% boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), ...
% 'cmap', cool(4), 'transparency', 0.5);
% title('Multiple bounds using colormap');
% Copyright 2010 Kelly Kearney
%--------------------
% Parse input
%--------------------
% Color and cmap are mechanically the same:
tmp = strncmpi(varargin,'color',3);
if any(tmp)
varargin{tmp} = 'cmap';
end
% Alpha flag
isalpha = cellfun(@(x) ischar(x) && strcmp(x, 'alpha'), varargin);
if any(isalpha)
usealpha = true;
varargin = varargin(~isalpha);
else
usealpha = false;
end
% Axis
isax = cellfun(@(x) isscalar(x) && ishandle(x) && strcmp('axes', get(x,'type')), varargin);
if any(isax)
hax = varargin{isax};
varargin = varargin(~isax);
else
hax = gca;
end
% Transparency
[found, trans, varargin] = parseparam(varargin, 'transparency');
if ~found
trans = 0.2;
end
if ~isscalar(trans) || trans < 0 || trans > 1
error('Transparency must be scalar between 0 and 1');
end
% Orientation
[found, orient, varargin] = parseparam(varargin, 'orientation');
if ~found
orient = 'vert';
end
if strcmp(orient, 'vert')
isvert = true;
elseif strcmp(orient, 'horiz')
isvert = false;
else
error('Orientation must be ''vert'' or ''horiz''');
end
% Colormap
[hascmap, cmap, varargin] = parseparam(varargin, 'cmap');
% NaN flag
[found, nanflag, varargin] = parseparam(varargin, 'nan');
if ~found
nanflag = 'fill';
end
if ~ismember(nanflag, {'fill', 'gap', 'remove'})
error('Nan flag must be ''fill'', ''gap'', or ''remove''');
end
[haslw, lwidth, varargin] = parseparam(varargin, 'linewidth');
if ~haslw
lwidth = get(0, 'DefaultLineLineWidth');
end
% X, Y, E triplets, and linespec
[x,y,err,linespec] = deal(cell(0));
while ~isempty(varargin)
if length(varargin) < 3
error('Unexpected input: should be x, y, bounds triplets');
end
if all(cellfun(@isnumeric, varargin(1:3)))
x = [x varargin(1)];
y = [y varargin(2)];
err = [err varargin(3)];
varargin(1:3) = [];
else
if any(cellfun(@(x) isa(x, 'datetime'), varargin(1:3)))
% Special error message for most likely culprit: datetimes
error('boundedline cannot support datetime input due to incompatibility between patches and datetime axes; please convert to datenumbers instead');
else
% Otherwise
error('Unexpected input: should be numeric x, y, bounds triplets');
end
end
if ~isempty(varargin) && ischar(varargin{1})
linespec = [linespec varargin(1)];
varargin(1) = [];
else
linespec = [linespec {[]}];
end
end
%--------------------
% Reformat x and y
% for line and patch
% plotting
%--------------------
% Calculate y values for bounding lines
plotdata = cell(0,7);
htemp = figure('visible', 'off');
for ix = 1:length(x)
% Get full x, y, and linespec data for each line (easier to let plot
% check for properly-sized x and y and expand values than to try to do
% it myself)
try
if isempty(linespec{ix})
hltemp = plot(x{ix}, y{ix});
else
hltemp = plot(x{ix}, y{ix}, linespec{ix});
end
catch
close(htemp);
error('X and Y matrices and/or linespec not appropriate for line plot');
end
linedata = get(hltemp, {'xdata', 'ydata', 'marker', 'linestyle', 'color'});
nline = size(linedata,1);
% Expand bounds matrix if necessary
if nline > 1
if ndims(err{ix}) == 3
err2 = squeeze(num2cell(err{ix},[1 2]));
else
err2 = repmat(err(ix),nline,1);
end
else
err2 = err(ix);
end
% Figure out upper and lower bounds
[lo, hi] = deal(cell(nline,1));
for iln = 1:nline
x2 = linedata{iln,1};
y2 = linedata{iln,2};
nx = length(x2);
if isvert
lineval = y2;
else
lineval = x2;
end
sz = size(err2{iln});
if isequal(sz, [nx 2])
lo{iln} = lineval - err2{iln}(:,1)';
hi{iln} = lineval + err2{iln}(:,2)';
elseif isequal(sz, [nx 1])
lo{iln} = lineval - err2{iln}';
hi{iln} = lineval + err2{iln}';
elseif isequal(sz, [1 2])
lo{iln} = lineval - err2{iln}(1);
hi{iln} = lineval + err2{iln}(2);
elseif isequal(sz, [1 1])
lo{iln} = lineval - err2{iln};
hi{iln} = lineval + err2{iln};
elseif isequal(sz, [2 nx]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln}(:,1);
hi{iln} = lineval + err2{iln}(:,2);
elseif isequal(sz, [1 nx]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln};
hi{iln} = lineval + err2{iln};
elseif isequal(sz, [2 1]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln}(1);
hi{iln} = lineval + err2{iln}(2);
else
error('Error bounds must be npt x nside x nline array');
end
end
% Combine all data (xline, yline, marker, linestyle, color, lower bound
% (x or y), upper bound (x or y)
plotdata = [plotdata; linedata lo hi];
end
close(htemp);
% Override colormap
if hascmap
nd = size(plotdata,1);
cmap = repmat(cmap, ceil(nd/size(cmap,1)), 1);
cmap = cmap(1:nd,:);
plotdata(:,5) = num2cell(cmap,2);
end
%--------------------
% Plot
%--------------------
% Setup of x and y, plus line and patch properties
nline = size(plotdata,1);
[xl, yl, xp, yp, marker, lnsty, lncol, ptchcol, alpha] = deal(cell(nline,1));
for iln = 1:nline
xl{iln} = plotdata{iln,1};
yl{iln} = plotdata{iln,2};
% if isvert
% xp{iln} = [plotdata{iln,1} fliplr(plotdata{iln,1})];
% yp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% else
% xp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% yp{iln} = [plotdata{iln,2} fliplr(plotdata{iln,2})];
% end
[xp{iln}, yp{iln}] = calcpatch(plotdata{iln,1}, plotdata{iln,2}, isvert, plotdata{iln,6}, plotdata{iln,7}, nanflag);
marker{iln} = plotdata{iln,3};
lnsty{iln} = plotdata{iln,4};
if usealpha
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = plotdata{iln,5};
alpha{iln} = trans;
else
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = interp1([0 1], [1 1 1; lncol{iln}], trans);
alpha{iln} = 1;
end
end
% Plot patches and lines
if verLessThan('matlab', '8.4.0')
[hp,hl] = deal(zeros(nline,1));
else
[hp,hl] = deal(gobjects(nline,1));
end
for iln = 1:nline
hp(iln) = patch(xp{iln}, yp{iln}, ptchcol{iln}, ...
'facealpha', alpha{iln}, ...
'edgecolor', 'none', ...
'parent', hax);
end
for iln = 1:nline
hl(iln) = line(xl{iln}, yl{iln}, ...
'marker', marker{iln}, ...
'linestyle', lnsty{iln}, ...
'color', lncol{iln}, ...
'linewidth', lwidth, ...
'parent', hax);
end
%--------------------
% Assign output
%--------------------
nargoutchk(0,2);
if nargout >= 1
varargout{1} = hl;
end
if nargout == 2
varargout{2} = hp;
end
%--------------------
% Parse optional
% parameters
%--------------------
function [found, val, vars] = parseparam(vars, param)
isvar = cellfun(@(x) ischar(x) && strcmpi(x, param), vars);
if sum(isvar) > 1
error('Parameters can only be passed once');
end
if any(isvar)
found = true;
idx = find(isvar);
val = vars{idx+1};
vars([idx idx+1]) = [];
else
found = false;
val = [];
end
%----------------------------
% Calculate patch coordinates
%----------------------------
function [xp, yp] = calcpatch(xl, yl, isvert, lo, hi, nanflag)
ismissing = isnan([xl;yl;lo;hi]);
% If gap method, split
if any(ismissing(:)) && strcmp(nanflag, 'gap')
tmp = [xl;yl;lo;hi];
idx = find(any(ismissing,1));
n = diff([0 idx length(xl)]);
tmp = mat2cell(tmp, 4, n);
isemp = cellfun('isempty', tmp);
tmp = tmp(~isemp);
tmp = cellfun(@(a) a(:,~any(isnan(a),1)), tmp, 'uni', 0);
isemp = cellfun('isempty', tmp);
tmp = tmp(~isemp);
xl = cellfun(@(a) a(1,:), tmp, 'uni', 0);
yl = cellfun(@(a) a(2,:), tmp, 'uni', 0);
lo = cellfun(@(a) a(3,:), tmp, 'uni', 0);
hi = cellfun(@(a) a(4,:), tmp, 'uni', 0);
else
xl = {xl};
yl = {yl};
lo = {lo};
hi = {hi};
end
[xp, yp] = deal(cell(size(xl)));
for ii = 1:length(xl)
iseq = ~verLessThan('matlab', '8.4.0') && isequal(lo{ii}, hi{ii}); % deal with zero-width bug in R2014b/R2015a
if isvert
if iseq
xp{ii} = [xl{ii} nan(size(xl{ii}))];
yp{ii} = [lo{ii} fliplr(hi{ii})];
else
xp{ii} = [xl{ii} fliplr(xl{ii})];
yp{ii} = [lo{ii} fliplr(hi{ii})];
end
else
if iseq
xp{ii} = [lo{ii} fliplr(hi{ii})];
yp{ii} = [yl{ii} nan(size(yl{ii}))];
else
xp{ii} = [lo{ii} fliplr(hi{ii})];
yp{ii} = [yl{ii} fliplr(yl{ii})];
end
end
if strcmp(nanflag, 'fill')
xp{ii} = inpaint_nans(xp{ii}', 4);
yp{ii} = inpaint_nans(yp{ii}', 4);
if iseq % need to maintain NaNs for zero-width bug
nx = length(xp{ii});
xp{ii}((nx/2)+1:end) = NaN;
end
elseif strcmp(nanflag, 'remove')
if iseq
nx = length(xp{ii});
keepnan = false(size(xp));
keepnan((nx/2)+1:end) = true;
isn = (isnan(xp{ii}) | isnan(yp{ii})) & ~keepnan;
else
isn = isnan(xp{ii}) | isnan(yp{ii});
end
xp{ii} = xp{ii}(~isn);
yp{ii} = yp{ii}(~isn);
end
end
if strcmp(nanflag, 'gap')
[xp, yp] = singlepatch(xp, yp);
else
xp = xp{1};
yp = yp{1};
end

View File

@@ -0,0 +1,43 @@
function hnew = outlinebounds(hl, hp)
%OUTLINEBOUNDS Outline the patch of a boundedline
%
% hnew = outlinebounds(hl, hp)
%
% This function adds an outline to the patch objects created by
% boundedline, matching the color of the central line associated with each
% patch.
%
% Input variables:
%
% hl: handles to line objects from boundedline
%
% hp: handles to patch objects from boundedline
%
% Output variables:
%
% hnew: handle to new line objects
% Copyright 2012 Kelly Kearney
hnew = zeros(size(hl));
for il = 1:numel(hp)
col = get(hl(il), 'color');
xy = get(hp(il), {'xdata','ydata'});
ax = ancestor(hl(il), 'axes');
nline = size(xy{1},2);
if mod(size(xy{1}, 1), 2) == 0
% Insert a NaN between upper and lower lines, so they're disconnected
L = size(xy{1}, 1) / 2;
xy{1} = [xy{1}(1:L, :); nan(1, nline); xy{1}(L+1:end, :)];
xy{2} = [xy{2}(1:L, :); nan(1, nline); xy{2}(L+1:end, :)];
end
if nline > 1
xy{1} = reshape([xy{1}; nan(1,nline)], [], 1);
xy{2} = reshape([xy{2}; nan(1,nline)], [], 1);
end
hnew(il) = line(xy{1}, xy{2}, 'parent', ax, 'linestyle', '-', 'color', col);
end

37
Libs/boundedlines/catuneven/.gitignore vendored Normal file
View File

@@ -0,0 +1,37 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

View File

@@ -0,0 +1,57 @@
function b = catuneven(dim, padval, varargin)
%CATUNEVEN Concatenate unequally-sized arrays, padding with a value
%
% This function is similar to cat, except it does not require the arrays to
% be equally-sized along non-concatenated dimensions. Instead, all arrays
% are padded to be equally-sized using the value specified.
%
% b = catuneven(dim, padval, a1, a2, ...)
%
% Input variables:
%
% dim: dimension along which to concatenate
%
% padval: value used as placeholder when arrays are expanded
%
% a#: arrays to be concatenated, numerical
%
% Output variables:
%
% b: concatenated array
% Copyright 2013 Kelly Kearney
ndim = max(cellfun(@ndims, varargin));
ndim = max(ndim, dim);
for ii = 1:ndim
sz(:,ii) = cellfun(@(x) size(x, ii), varargin);
end
maxsz = max(sz, [], 1);
nv = length(varargin);
val = cell(size(varargin));
for ii = 1:nv
sztmp = maxsz;
sztmp(dim) = sz(ii,dim);
idx = cell(ndim,1);
[idx{:}] = ind2sub(sz(ii,:), 1:numel(varargin{ii}));
idxnew = sub2ind(sztmp, idx{:});
try
val{ii} = ones(sztmp) * padval;
catch
val{ii} = repmat(padval, sztmp);
end
val{ii}(idxnew) = varargin{ii};
end
b = cat(dim, val{:});

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -0,0 +1,37 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db

View File

@@ -0,0 +1,65 @@
function varargout = singlepatch(varargin)
%SINGLEPATCH Concatenate patches to be plotted as one
%
% [xp, yp, zp, ...] = singlepatch(x, y, z, ...)
%
% Concatenates uneven vectors of x and y coordinates by replicating the
% last point in each polygon. This allows patches with different numbers
% of vertices to be plotted as one, which is often much, much more
% efficient than plotting lots of individual patches.
%
% Input variables:
%
% x: cell array, with each cell holding a vector of coordinates
% associates with a single patch. The input variables must all be
% of the same size, and usually will correspond to x, y, z, and c
% data for the patches.
%
% Output variables:
%
% xp: m x n array of coordinates, where m is the maximum length of the
% vectors in x and n is numel(x).
% Copyright 2015 Kelly Kearney
if nargin ~= nargout
error('Must supply the same number of input variables as output variables');
end
nv = nargin;
vars = varargin;
sz = cellfun(@size, vars{1}(:), 'uni', 0);
sz = cat(1, sz{:});
if all(sz(:,1) == 1)
for ii = 1:nv
vars{ii} = catuneven(1, NaN, vars{ii}{:})';
end
% x = catuneven(1, NaN, x{:})';
% y = catuneven(1, NaN, y{:})';
elseif all(sz(:,2) == 1)
for ii = 1:nv
vars{ii} = catuneven(2, NaN, vars{ii}{:});
end
% x = catuneven(2, NaN, x{:});
% y = catuneven(2, NaN, y{:});
else
error('Inputs must be cell arrays of vectors');
end
[ii,jj] = find(isnan(vars{1}));
ind = accumarray(jj, ii, [size(vars{1},2) 1], @min);
ij1 = [ii jj];
ij2 = [ind(jj)-1 jj];
idx1 = sub2ind(size(vars{1}), ij1(:,1), ij1(:,2));
idx2 = sub2ind(size(vars{1}), ij2(:,1), ij2(:,2));
for ii = 1:nv
vars{ii}(idx1) = vars{ii}(idx2);
end
varargout = vars;