├── sample_cache.mat ├── util ├── rotate_cov.m ├── mix_gaussians_neg_log_pdf.m ├── mix_gaussians_pdf.m ├── mix_gaussians_draw.m ├── mix_mix_gaussians_pdf.m ├── mog_gibbs.m ├── logsumexp.m ├── colorbrew.m ├── logmvnpdf.m ├── mix_gaussians_log_pdf.m ├── mog_conditional.m ├── subaxis.m └── parseArgs.m ├── mog_mh.m ├── exportfig ├── copyfig.m ├── license.txt ├── pdf2eps.m ├── user_string.m ├── pdftops.m ├── isolate_axes.m ├── ghostscript.m ├── eps2pdf.m ├── fix_lines.m ├── print2array.m ├── print2eps.m └── export_fig.m ├── README.md ├── hmc.m ├── harlemshake.m └── license.txt /sample_cache.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/duvenaud/harlemcmc-shake/HEAD/sample_cache.mat -------------------------------------------------------------------------------- /util/rotate_cov.m: -------------------------------------------------------------------------------- 1 | function covs = rotate_cov( lengths, angle ) 2 | % Tamara Broderick 3 | % David Duvenaud 4 | % 5 | % March 2013 6 | 7 | unrotated = diag(lengths); 8 | rotation = [cos(angle) -sin(angle); sin(angle) cos(angle)]; 9 | 10 | covs = rotation' * unrotated * rotation; 11 | -------------------------------------------------------------------------------- /util/mix_gaussians_neg_log_pdf.m: -------------------------------------------------------------------------------- 1 | function [nll, dnll] = mix_gaussians_neg_log_pdf( x, mix ) 2 | % Tamara Broderick 3 | % David Duvenaud 4 | % 5 | % March 2013 6 | 7 | [ll, dll] = mix_gaussians_log_pdf( x, mix ); 8 | nll = -ll; 9 | dnll = -dll; 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /util/mix_gaussians_pdf.m: -------------------------------------------------------------------------------- 1 | function vals = mix_gaussians_pdf( x, mix ) 2 | % Evaluate a mixture of Guassians at specified locations. 3 | % 4 | % Tamara Broderick 5 | % David Duvenaud 6 | % 7 | % March 2013 8 | 9 | vals = zeros(size(x, 1), 1); 10 | for k = 1:size(mix.means, 1); 11 | vals = vals + mix.weights(k) .* mvnpdf( x, mix.means(k, :), mix.covs(:, :, k)); 12 | end 13 | -------------------------------------------------------------------------------- /util/mix_gaussians_draw.m: -------------------------------------------------------------------------------- 1 | function vals = mix_gaussians_draw( mix, N ) 2 | % Generate random draws from a mixture of Gaussians. 3 | % 4 | % Tamara Broderick 5 | % David Duvenaud 6 | % 7 | % March 2013 8 | 9 | vals = NaN(N, size(mix.means,2)); 10 | 11 | for i = 1:N; 12 | cur_component = find(mnrnd( 1, mix.weights )); 13 | vals(i, :) = mvnrnd( mix.means(cur_component, :), ... 14 | mix.covs(:, :, cur_component)); 15 | end 16 | -------------------------------------------------------------------------------- /util/mix_mix_gaussians_pdf.m: -------------------------------------------------------------------------------- 1 | function vals = mix_mix_gaussians_pdf( x, mixes ) 2 | % Evaluate a mixutre of mixtures of Guassians at specified locations. 3 | % 4 | % Tamara Broderick 5 | % David Duvenaud 6 | % 7 | % March 2013 8 | 9 | vals = zeros(size(x, 1), 1); 10 | for n = 1:numel(mixes) 11 | mix = mixes{n} 12 | for k = 1:size(mix.means, 1); 13 | vals = vals + mix.weights(k) .* mvnpdf( x, mix.means(k, :), mix.covs(:, :, k)); 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /util/mog_gibbs.m: -------------------------------------------------------------------------------- 1 | function sample = mog_gibbs( mix, x ) 2 | 3 | % Returns a sample from a mixture of Gaussians, conditioned on one of its 4 | % dimensions being fixed. 5 | % 6 | % David Duvenaud 7 | % Tamara Broderick 8 | % 9 | % March 2012 10 | 11 | D = numel(x); 12 | 13 | % Choose a dimension to sample. 14 | dim = randi(D); 15 | fixed = 1:D; 16 | fixed(dim) = []; 17 | 18 | % Find the conditional pdf. 19 | cond_mix = mog_conditional( mix, x(fixed), fixed); 20 | 21 | % Now sample from this distribution: 22 | x(dim) = mix_gaussians_draw( cond_mix, 1 ); 23 | 24 | sample = x; 25 | -------------------------------------------------------------------------------- /mog_mh.m: -------------------------------------------------------------------------------- 1 | function sample = mog_mh( mix, cur_pt, proposal_cov ) 2 | % 3 | % Metropolis-Hastings sampling in a mixture of Gaussians. 4 | % 5 | % Tamara Broderick 6 | % David Duvenaud 7 | % March 2013 8 | 9 | % Compute MH proposal. 10 | proposal = mvnrnd( cur_pt, proposal_cov ); 11 | proposal_ll = mix_gaussians_log_pdf(proposal, mix); 12 | cur_ll = mix_gaussians_log_pdf(cur_pt, mix); 13 | 14 | % Possibly take a MH step. 15 | ratio = exp(proposal_ll - cur_ll); 16 | if ratio > rand 17 | sample = proposal; % Accept. :) 18 | else 19 | sample = cur_pt; % Reject. :( 20 | end 21 | -------------------------------------------------------------------------------- /util/logsumexp.m: -------------------------------------------------------------------------------- 1 | function s = logsumexp(a, dim) 2 | % Returns log(sum(exp(a),dim)) while avoiding numerical underflow. 3 | % Default is dim = 1 (rows) or dim=2 for a row vector 4 | % logsumexp(a, 2) will sum across columns instead of rows 5 | 6 | % Written by Tom Minka, modified by Kevin Murphy 7 | 8 | if nargin < 2 9 | dim = 1; 10 | if ndims(a) <= 2 & size(a,1)==1 11 | dim = 2; 12 | end 13 | end 14 | 15 | % subtract the largest in each column 16 | [y, i] = max(a,[],dim); 17 | dims = ones(1,ndims(a)); 18 | dims(dim) = size(a,dim); 19 | a = a - repmat(y, dims); 20 | s = y + log(sum(exp(a),dim)); 21 | %i = find(~finite(y)); 22 | %if ~isempty(i) 23 | % s(i) = y(i); 24 | %end 25 | -------------------------------------------------------------------------------- /util/colorbrew.m: -------------------------------------------------------------------------------- 1 | function c = colorbrew( i ) 2 | % 3 | % Nice colors taken from 4 | % http://colorbrewer2.org/ 5 | % 6 | % David Duvenaud 7 | % March 2012 8 | 9 | c_array(1, :) = [ 228, 26, 28 ]; % red 10 | c_array(2, :) = [ 55, 126, 184 ]; % blue 11 | c_array(3, :) = [ 77, 175, 74 ]; % green 12 | c_array(4, :) = [ 152, 78, 163 ]; % purple 13 | c_array(5, :) = [ 255, 127, 0 ]; % orange 14 | c_array(6, :) = [ 255, 255, 51 ]; % yellow 15 | c_array(7, :) = [ 166, 86, 40 ]; % brown 16 | c_array(8, :) = [ 247, 129, 191 ]; % pink 17 | c_array(9, :) = [ 153, 153, 153]; % grey 18 | c_array(10, :) = [ 0, 0, 0]; % black 19 | 20 | c = c_array( mod(i - 1, 10) + 1, : ) ./ 255; 21 | end 22 | -------------------------------------------------------------------------------- /util/logmvnpdf.m: -------------------------------------------------------------------------------- 1 | function [logp, dlopg] = logmvnpdf(x,mu,Sigma) 2 | % Log of multivariate normal pdf. 3 | % 4 | % Tamara Broderick 5 | % David Duvenaud 6 | % 7 | % March 2013 8 | 9 | dim = length(mu); 10 | logdetcov = logdet(Sigma); 11 | a = bsxfun(@minus, x, mu); 12 | logp = (-dim/2)*log(2*pi) + (-.5)*logdetcov +... 13 | (-.5.*sum(bsxfun( @times, a / Sigma, a), 2)); % Evaluate for multiple inputs. 14 | 15 | if nargout > 1 16 | % Compute Gradients w.r.t. x. 17 | % Output dimension will be N x D. 18 | dlopg = -( x - mu ) / Sigma; 19 | end 20 | end 21 | 22 | function ld = logdet(K) 23 | % returns the log-determinant of posdef matrix K. 24 | 25 | % This is probably horribly slow. 26 | ld = NaN; 27 | try 28 | ld = 2*sum(log(diag(chol(K)))); 29 | catch e 30 | e; 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /exportfig/copyfig.m: -------------------------------------------------------------------------------- 1 | %COPYFIG Create a copy of a figure, without changing the figure 2 | % 3 | % Examples: 4 | % fh_new = copyfig(fh_old) 5 | % 6 | % This function will create a copy of a figure, but not change the figure, 7 | % as copyobj sometimes does, e.g. by changing legends. 8 | % 9 | % IN: 10 | % fh_old - The handle of the figure to be copied. Default: gcf. 11 | % 12 | % OUT: 13 | % fh_new - The handle of the created figure. 14 | 15 | % Copyright (C) Oliver Woodford 2012 16 | 17 | function fh = copyfig(fh) 18 | % Set the default 19 | if nargin == 0 20 | fh = gcf; 21 | end 22 | % Is there a legend? 23 | if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend')) 24 | % Safe to copy using copyobj 25 | fh = copyobj(fh, 0); 26 | else 27 | % copyobj will change the figure, so save and then load it instead 28 | tmp_nam = [tempname '.fig']; 29 | hgsave(fh, tmp_nam); 30 | fh = hgload(tmp_nam); 31 | delete(tmp_nam); 32 | end 33 | return -------------------------------------------------------------------------------- /util/mix_gaussians_log_pdf.m: -------------------------------------------------------------------------------- 1 | function [ll, dll] = mix_gaussians_log_pdf( x, mix ) 2 | % Evaluate a mixture of Guassians at specified locations. 3 | % 4 | % x is N x D 5 | % mix.weights is k x 1 6 | % mix.means is k x D 7 | % 8 | % Tamara Broderick 9 | % David Duvenaud 10 | % 11 | % March 2013 12 | 13 | % vals is going to be summed over the elements of mixture. 14 | [K, D] = size(mix.means); 15 | [N, D] = size(x); 16 | 17 | log_pdfs = NaN(N, K); 18 | log_mix_weights = log(mix.weights); 19 | 20 | for k = 1:K 21 | log_pdfs(:, k) = log_mix_weights(k) + logmvnpdf( x, mix.means(k, :), mix.covs(:, :, k)); 22 | end 23 | ll = logsumexp( log_pdfs ); 24 | 25 | if nargout > 1 26 | d_log_pdfs = NaN(N, K, D); 27 | for k = 1:K 28 | [log_pdfs(:, k), d_log_pdfs(:, k, :)] = logmvnpdf( x, mix.means(k, :), mix.covs(:, :, k)); 29 | d_log_pdfs(:, k, :) = d_log_pdfs(:, k, :) * mix.weights(k) * exp(log_pdfs(:, k)); 30 | end 31 | 32 | dll = NaN( N, D); 33 | for d = 1:D 34 | dll(:, d) = sum( squeeze(d_log_pdfs( :, :, d)), 2) ./ exp(ll); 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /util/mog_conditional.m: -------------------------------------------------------------------------------- 1 | function cond_mix = mog_conditional( mix, x, fixed) 2 | % Returns a mixture of Gaussians, conditioned on some of its 3 | % dimensions being fixed to the value x. 4 | % 5 | % Tamara Broderick 6 | % David Duvenaud 7 | % 8 | % March 2013 9 | 10 | D = size(mix.means, 2); 11 | notfixed = 1:D; 12 | notfixed(fixed) = []; 13 | 14 | cond_mix.weights = NaN(size(mix.weights, 1), 1); 15 | cond_mix.means = NaN(size(mix.weights, 1), numel(notfixed)); 16 | cond_mix.covs = NaN(size(mix.weights, 1), numel(notfixed), numel(notfixed)); 17 | 18 | for k = 1:size(mix.means, 1); 19 | prec_all = inv(mix.covs(:,:,k)); 20 | mu_a = mix.means(notfixed); 21 | mu_b = mix.means(fixed); 22 | prec_aa = prec_all(notfixed, notfixed, k); 23 | prec_ab = prec_all(notfixed, fixed, k); 24 | 25 | cond_mix.means(k) = mu_a - prec_aa \ prec_ab * ( x - mu_b); 26 | cond_mix.covs(k) = inv(prec_aa); 27 | evs = mvnpdf( x, mix.means(fixed), mix.covs(fixed, fixed, k)); % Evidences. 28 | end 29 | 30 | % Renormalize: 31 | cond_mix.weights = mix.weights .* evs; 32 | cond_mix.weights = cond_mix.weights ./ sum(cond_mix.weights); 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | harlemcmc-shake 2 | =============== 3 | 4 | This code generates two short animations illustrate the differences between a Metropolis-Hastings (MH) sampler and a Hamiltonian Monte Carlo (HMC) sampler. 5 | 6 | The animations can be seen at 7 | https://www.youtube.com/watch?v=Vv3f0QNWvWQ 8 | 9 | We test the samplers on nine mixtures of Gaussians, ranging from a mixture of four elongated Gaussians in the upper right-hand corner, to a single spherical Gaussian in the middle, to a mixture of 100 spherical Gaussians in the lower lefthand corner. We plot the contours of these distributions in white and the last 10 samples in red. 10 | 11 | In the MH case, the samples are connected in sequential order by yellow lines. In the HMC case, the samples are connected (in yellow) by the Hamiltonian evolution sequence generated during the proposal of the next (accepted) sample. The MH proposals are set to spherical Gaussians with relatively small variance in the outer eight target Gaussian mixtures and relatively large variance for the central spherical Gaussian target distribution. 12 | 13 | Authors: 14 | Tamara Broderick (UC Berkeley) 15 | http://www.stat.berkeley.edu/~tab/ 16 | 17 | David Duvenaud (University of Cambridge) 18 | http://mlg.eng.cam.ac.uk/duvenaud/ 19 | 20 | 21 | Enjoy! 22 | 23 | -------------------------------------------------------------------------------- /exportfig/license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012, Oliver Woodford 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in 12 | the documentation and/or other materials provided with the distribution 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 18 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /exportfig/pdf2eps.m: -------------------------------------------------------------------------------- 1 | %PDF2EPS Convert a pdf file to eps format using pdftops 2 | % 3 | % Examples: 4 | % pdf2eps source dest 5 | % 6 | % This function converts a pdf file to eps format. 7 | % 8 | % This function requires that you have pdftops, from the Xpdf suite of 9 | % functions, installed on your system. This can be downloaded from: 10 | % http://www.foolabs.com/xpdf 11 | % 12 | %IN: 13 | % source - filename of the source pdf file to convert. The filename is 14 | % assumed to already have the extension ".pdf". 15 | % dest - filename of the destination eps file. The filename is assumed to 16 | % already have the extension ".eps". 17 | 18 | % Copyright (C) Oliver Woodford 2009-2010 19 | 20 | % Thanks to Aldebaro Klautau for reporting a bug when saving to 21 | % non-existant directories. 22 | 23 | function pdf2eps(source, dest) 24 | % Construct the options string for pdftops 25 | options = ['-q -paper match -eps -level2 "' source '" "' dest '"']; 26 | % Convert to eps using pdftops 27 | [status message] = pdftops(options); 28 | % Check for error 29 | if status 30 | % Report error 31 | if isempty(message) 32 | error('Unable to generate eps. Check destination directory is writable.'); 33 | else 34 | error(message); 35 | end 36 | end 37 | % Fix the DSC error created by pdftops 38 | fid = fopen(dest, 'r+'); 39 | if fid == -1 40 | % Cannot open the file 41 | return 42 | end 43 | fgetl(fid); % Get the first line 44 | str = fgetl(fid); % Get the second line 45 | if strcmp(str(1:min(13, end)), '% Produced by') 46 | fseek(fid, -numel(str)-1, 'cof'); 47 | fwrite(fid, '%'); % Turn ' ' into '%' 48 | end 49 | fclose(fid); 50 | return 51 | 52 | -------------------------------------------------------------------------------- /hmc.m: -------------------------------------------------------------------------------- 1 | function [params, nll, arate, tail] = hmc(likefunc, x, options, varargin) 2 | % Hamiltonian Monte Carlo - copied from David Mackay's book. 3 | % 4 | % Tomoharu Iwata 5 | % Tamara Broderick 6 | % David Duvenaud 7 | % 8 | % March 2013 9 | % 10 | % likefunc returns nll, dnll 11 | % 12 | % options.Tau is the number of leapfrog steps. 13 | % options.epsilon is step length 14 | 15 | 16 | silent = true; 17 | 18 | arate = 0; %acceptance rate 19 | L = options.num_iters; 20 | 21 | [E, g] = likefunc( x, varargin{:}); 22 | 23 | 24 | 25 | for l = 1:L 26 | p = randn( size( x ) ); 27 | H = p' * p / 2 + E; 28 | 29 | xnew = x; gnew = g; 30 | 31 | % Randomize step length and number of steps. 32 | %cur_tau = randi(options.Tau); 33 | %cur_eps = rand * options.epsilon; 34 | 35 | cur_tau = options.Tau; 36 | cur_eps = options.epsilon; 37 | 38 | tail = NaN(cur_tau+1, size(x,2)); 39 | tail(1,:) = x; 40 | 41 | for tau = 1:cur_tau 42 | p = p - cur_eps * gnew / 2; 43 | xnew = xnew + cur_eps * p; 44 | tail(tau+1, :) = xnew; 45 | [ignore, gnew] = likefunc( xnew, varargin{:}); 46 | 47 | p = p - cur_eps * gnew / 2; 48 | end 49 | 50 | [Enew, ignore] = likefunc( xnew, varargin{:}); 51 | Hnew = p' * p / 2 + Enew; 52 | dh = Hnew - H; 53 | 54 | if dh < 0 55 | accept = 1; 56 | if ~silent; fprintf('a'); end 57 | else 58 | if rand() < exp(-dh) 59 | accept = 1; 60 | if ~silent; fprintf('A'); end 61 | else 62 | accept = 0; 63 | if ~silent; fprintf('r'); end 64 | end 65 | end 66 | 67 | if accept 68 | g = gnew; 69 | x = xnew; 70 | E = Enew; 71 | arate = arate+1; 72 | else 73 | tail = []; 74 | end 75 | end 76 | 77 | arate = arate/L; 78 | params = x; 79 | nll = E; 80 | -------------------------------------------------------------------------------- /exportfig/user_string.m: -------------------------------------------------------------------------------- 1 | %USER_STRING Get/set a user specific string 2 | % 3 | % Examples: 4 | % string = user_string(string_name) 5 | % saved = user_string(string_name, new_string) 6 | % 7 | % Function to get and set a string in a system or user specific file. This 8 | % enables, for example, system specific paths to binaries to be saved. 9 | % 10 | % IN: 11 | % string_name - String containing the name of the string required. The 12 | % string is extracted from a file called (string_name).txt, 13 | % stored in the same directory as user_string.m. 14 | % new_string - The new string to be saved under the name given by 15 | % string_name. 16 | % 17 | % OUT: 18 | % string - The currently saved string. Default: ''. 19 | % saved - Boolean indicating whether the save was succesful 20 | 21 | % Copyright (C) Oliver Woodford 2011 22 | 23 | % This method of saving paths avoids changing .m files which might be in a 24 | % version control system. Instead it saves the user dependent paths in 25 | % separate files with a .txt extension, which need not be checked in to 26 | % the version control system. Thank you to Jonas Dorn for suggesting this 27 | % approach. 28 | 29 | function string = user_string(string_name, string) 30 | if ~ischar(string_name) 31 | error('string_name must be a string.'); 32 | end 33 | % Create the full filename 34 | string_name = fullfile(fileparts(mfilename('fullpath')), '.ignore', [string_name '.txt']); 35 | if nargin > 1 36 | % Set string 37 | if ~ischar(string) 38 | error('new_string must be a string.'); 39 | end 40 | % Make sure the save directory exists 41 | dname = fileparts(string_name); 42 | if ~exist(dname, 'dir') 43 | % Create the directory 44 | try 45 | if ~mkdir(dname) 46 | string = false; 47 | return 48 | end 49 | catch 50 | string = false; 51 | return 52 | end 53 | % Make it hidden 54 | try 55 | fileattrib(dname, '+h'); 56 | catch 57 | end 58 | end 59 | % Write the file 60 | fid = fopen(string_name, 'w'); 61 | if fid == -1 62 | string = false; 63 | return 64 | end 65 | try 66 | fwrite(fid, string, '*char'); 67 | catch 68 | fclose(fid); 69 | string = false; 70 | return 71 | end 72 | fclose(fid); 73 | string = true; 74 | else 75 | % Get string 76 | fid = fopen(string_name, 'r'); 77 | if fid == -1 78 | string = ''; 79 | return 80 | end 81 | string = fread(fid, '*char')'; 82 | fclose(fid); 83 | end 84 | return -------------------------------------------------------------------------------- /exportfig/pdftops.m: -------------------------------------------------------------------------------- 1 | function varargout = pdftops(cmd) 2 | %PDFTOPS Calls a local pdftops executable with the input command 3 | % 4 | % Example: 5 | % [status result] = pdftops(cmd) 6 | % 7 | % Attempts to locate a pdftops executable, finally asking the user to 8 | % specify the directory pdftops was installed into. The resulting path is 9 | % stored for future reference. 10 | % 11 | % Once found, the executable is called with the input command string. 12 | % 13 | % This function requires that you have pdftops (from the Xpdf package) 14 | % installed on your system. You can download this from: 15 | % http://www.foolabs.com/xpdf 16 | % 17 | % IN: 18 | % cmd - Command string to be passed into pdftops. 19 | % 20 | % OUT: 21 | % status - 0 iff command ran without problem. 22 | % result - Output from pdftops. 23 | 24 | % Copyright: Oliver Woodford, 2009-2010 25 | 26 | % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on 27 | % Mac OS. 28 | % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path 29 | % under linux. 30 | 31 | % Call pdftops 32 | [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd)); 33 | return 34 | 35 | function path_ = xpdf_path 36 | % Return a valid path 37 | % Start with the currently set path 38 | path_ = user_string('pdftops'); 39 | % Check the path works 40 | if check_xpdf_path(path_) 41 | return 42 | end 43 | % Check whether the binary is on the path 44 | if ispc 45 | bin = 'pdftops.exe'; 46 | else 47 | bin = 'pdftops'; 48 | end 49 | if check_store_xpdf_path(bin) 50 | path_ = bin; 51 | return 52 | end 53 | % Search the obvious places 54 | if ispc 55 | path_ = 'C:\Program Files\xpdf\pdftops.exe'; 56 | else 57 | path_ = '/usr/local/bin/pdftops'; 58 | end 59 | if check_store_xpdf_path(path_) 60 | return 61 | end 62 | % Ask the user to enter the path 63 | while 1 64 | if strncmp(computer,'MAC',3) % Is a Mac 65 | % Give separate warning as the uigetdir dialogue box doesn't have a 66 | % title 67 | uiwait(warndlg('Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.')) 68 | end 69 | base = uigetdir('/', 'Pdftops not found. Please locate the program.'); 70 | if isequal(base, 0) 71 | % User hit cancel or closed window 72 | break; 73 | end 74 | base = [base filesep]; 75 | bin_dir = {'', ['bin' filesep], ['lib' filesep]}; 76 | for a = 1:numel(bin_dir) 77 | path_ = [base bin_dir{a} bin]; 78 | if exist(path_, 'file') == 2 79 | break; 80 | end 81 | end 82 | if check_store_xpdf_path(path_) 83 | return 84 | end 85 | end 86 | error('pdftops executable not found.'); 87 | 88 | function good = check_store_xpdf_path(path_) 89 | % Check the path is valid 90 | good = check_xpdf_path(path_); 91 | if ~good 92 | return 93 | end 94 | % Update the current default path to the path found 95 | if ~user_string('pdftops', path_) 96 | warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.'); 97 | return 98 | end 99 | return 100 | 101 | function good = check_xpdf_path(path_) 102 | % Check the path is valid 103 | [good message] = system(sprintf('"%s" -h', path_)); 104 | % system returns good = 1 even when the command runs 105 | % Look for something distinct in the help text 106 | good = ~isempty(strfind(message, 'PostScript')); 107 | return -------------------------------------------------------------------------------- /util/subaxis.m: -------------------------------------------------------------------------------- 1 | function h=subaxis(varargin) 2 | %SUBAXIS Create axes in tiled positions. (just like subplot) 3 | % Usage: 4 | % h=subaxis(rows,cols,cellno[,settings]) 5 | % h=subaxis(rows,cols,cellx,celly[,settings]) 6 | % h=subaxis(rows,cols,cellx,celly,spanx,spany[,settings]) 7 | % 8 | % SETTINGS: Spacing,SpacingHoriz,SpacingVert 9 | % Padding,PaddingRight,PaddingLeft,PaddingTop,PaddingBottom 10 | % Margin,MarginRight,MarginLeft,MarginTop,MarginBottom 11 | % Holdaxis 12 | % 13 | % all units are relative (e.g from 0 to 1) 14 | % 15 | % Abbreviations of parameters can be used.. (Eg MR instead of MarginRight) 16 | % (holdaxis means that it wont delete any axes below.) 17 | % 18 | % 19 | % Example: 20 | % 21 | % >> subaxis(2,1,1,'SpacingVert',0,'MR',0); 22 | % >> imagesc(magic(3)) 23 | % >> subaxis(2,'p',.02); 24 | % >> imagesc(magic(4)) 25 | % 26 | % 2001 / Aslak Grinsted (Feel free to modify this code.) 27 | f=gcf; 28 | 29 | 30 | Args=[]; 31 | UserDataArgsOK=0; 32 | Args=get(f,'UserData'); 33 | if isstruct(Args) 34 | UserDataArgsOK=isfield(Args,'SpacingHorizontal')&isfield(Args,'Holdaxis')&isfield(Args,'rows')&isfield(Args,'cols'); 35 | end 36 | OKToStoreArgs=isempty(Args)|UserDataArgsOK; 37 | 38 | if isempty(Args)&(~UserDataArgsOK) 39 | Args=struct('Holdaxis',0, ... 40 | 'SpacingVertical',0.05,'SpacingHorizontal',0.05, ... 41 | 'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ... 42 | 'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ... 43 | 'rows',[],'cols',[]); 44 | end 45 | Args=parseArgs(varargin,Args,{'Holdaxis'},{'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}}); 46 | 47 | if (length(Args.NumericArguments)>1) 48 | Args.rows=Args.NumericArguments{1}; 49 | Args.cols=Args.NumericArguments{2}; 50 | %remove these 2 numerical arguments 51 | Args.NumericArguments={Args.NumericArguments{3:end}}; 52 | end 53 | 54 | if OKToStoreArgs 55 | set(f,'UserData',Args); 56 | end 57 | 58 | 59 | 60 | 61 | switch length(Args.NumericArguments) 62 | case 0 63 | return % no arguments but rows/cols.... 64 | case 1 65 | x1=mod((Args.NumericArguments{1}-1),Args.cols)+1; x2=x1; 66 | y1=floor((Args.NumericArguments{1}-1)/Args.cols)+1; y2=y1; 67 | case 2 68 | x1=Args.NumericArguments{1};x2=x1; 69 | y1=Args.NumericArguments{2};y2=y1; 70 | case 4 71 | x1=Args.NumericArguments{1};x2=x1+Args.NumericArguments{3}-1; 72 | y1=Args.NumericArguments{2};y2=y1+Args.NumericArguments{4}-1; 73 | otherwise 74 | error('subaxis argument error') 75 | end 76 | 77 | 78 | cellwidth=((1-Args.MarginLeft-Args.MarginRight)-(Args.cols-1)*Args.SpacingHorizontal)/Args.cols; 79 | cellheight=((1-Args.MarginTop-Args.MarginBottom)-(Args.rows-1)*Args.SpacingVertical)/Args.rows; 80 | xpos1=Args.MarginLeft+Args.PaddingLeft+cellwidth*(x1-1)+Args.SpacingHorizontal*(x1-1); 81 | xpos2=Args.MarginLeft-Args.PaddingRight+cellwidth*x2+Args.SpacingHorizontal*(x2-1); 82 | ypos1=Args.MarginTop+Args.PaddingTop+cellheight*(y1-1)+Args.SpacingVertical*(y1-1); 83 | ypos2=Args.MarginTop-Args.PaddingBottom+cellheight*y2+Args.SpacingVertical*(y2-1); 84 | 85 | if Args.Holdaxis 86 | h=axes('position',[xpos1 1-ypos2 xpos2-xpos1 ypos2-ypos1]); 87 | else 88 | h=subplot('position',[xpos1 1-ypos2 xpos2-xpos1 ypos2-ypos1]); 89 | end 90 | 91 | 92 | set(h,'box','on'); 93 | %h=axes('position',[x1 1-y2 x2-x1 y2-y1]); 94 | set(h,'units',get(gcf,'defaultaxesunits')); 95 | set(h,'tag','subaxis'); 96 | 97 | 98 | 99 | if (nargout==0) clear h; end; 100 | 101 | -------------------------------------------------------------------------------- /exportfig/isolate_axes.m: -------------------------------------------------------------------------------- 1 | %ISOLATE_AXES Isolate the specified axes in a figure on their own 2 | % 3 | % Examples: 4 | % fh = isolate_axes(ah) 5 | % fh = isolate_axes(ah, vis) 6 | % 7 | % This function will create a new figure containing the axes/uipanels 8 | % specified, and also their associated legends and colorbars. The objects 9 | % specified must all be in the same figure, but they will generally only be 10 | % a subset of the objects in the figure. 11 | % 12 | % IN: 13 | % ah - An array of axes and uipanel handles, which must come from the 14 | % same figure. 15 | % vis - A boolean indicating whether the new figure should be visible. 16 | % Default: false. 17 | % 18 | % OUT: 19 | % fh - The handle of the created figure. 20 | 21 | % Copyright (C) Oliver Woodford 2011-2012 22 | 23 | % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs 24 | % 16/3/2012 Moved copyfig to its own function. Thanks to Bob Fratantonio 25 | % for pointing out that the function is also used in export_fig.m. 26 | % 12/12/12 - Add support for isolating uipanels. Thanks to michael for 27 | % suggesting it. 28 | 29 | function fh = isolate_axes(ah, vis) 30 | % Make sure we have an array of handles 31 | if ~all(ishandle(ah)) 32 | error('ah must be an array of handles'); 33 | end 34 | % Check that the handles are all for axes or uipanels, and are all in the same figure 35 | fh = ancestor(ah(1), 'figure'); 36 | nAx = numel(ah); 37 | for a = 1:nAx 38 | if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'}) 39 | error('All handles must be axes or uipanel handles.'); 40 | end 41 | if ~isequal(ancestor(ah(a), 'figure'), fh) 42 | error('Axes must all come from the same figure.'); 43 | end 44 | end 45 | % Tag the objects so we can find them in the copy 46 | old_tag = get(ah, 'Tag'); 47 | if nAx == 1 48 | old_tag = {old_tag}; 49 | end 50 | set(ah, 'Tag', 'ObjectToCopy'); 51 | % Create a new figure exactly the same as the old one 52 | fh = copyfig(fh); %copyobj(fh, 0); 53 | if nargin < 2 || ~vis 54 | set(fh, 'Visible', 'off'); 55 | end 56 | % Reset the object tags 57 | for a = 1:nAx 58 | set(ah(a), 'Tag', old_tag{a}); 59 | end 60 | % Find the objects to save 61 | ah = findall(fh, 'Tag', 'ObjectToCopy'); 62 | if numel(ah) ~= nAx 63 | close(fh); 64 | error('Incorrect number of objects found.'); 65 | end 66 | % Set the axes tags to what they should be 67 | for a = 1:nAx 68 | set(ah(a), 'Tag', old_tag{a}); 69 | end 70 | % Keep any legends and colorbars which overlap the subplots 71 | lh = findall(fh, 'Type', 'axes', '-and', {'Tag', 'legend', '-or', 'Tag', 'Colorbar'}); 72 | nLeg = numel(lh); 73 | if nLeg > 0 74 | ax_pos = get(ah, 'OuterPosition'); 75 | if nAx > 1 76 | ax_pos = cell2mat(ax_pos(:)); 77 | end 78 | ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2); 79 | leg_pos = get(lh, 'OuterPosition'); 80 | if nLeg > 1; 81 | leg_pos = cell2mat(leg_pos); 82 | end 83 | leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2); 84 | for a = 1:nAx 85 | % Overlap test 86 | ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &... 87 | leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))]; 88 | end 89 | end 90 | % Get all the objects in the figure 91 | axs = findall(fh); 92 | % Delete everything except for the input objects and associated items 93 | delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)]))); 94 | return 95 | 96 | function ah = allchildren(ah) 97 | ah = allchild(ah); 98 | if iscell(ah) 99 | ah = cell2mat(ah); 100 | end 101 | ah = ah(:); 102 | return 103 | 104 | function ph = allancestors(ah) 105 | ph = []; 106 | for a = 1:numel(ah) 107 | h = get(ah(a), 'parent'); 108 | while h ~= 0 109 | ph = [ph; h]; 110 | h = get(h, 'parent'); 111 | end 112 | end 113 | return -------------------------------------------------------------------------------- /exportfig/ghostscript.m: -------------------------------------------------------------------------------- 1 | %GHOSTSCRIPT Calls a local GhostScript executable with the input command 2 | % 3 | % Example: 4 | % [status result] = ghostscript(cmd) 5 | % 6 | % Attempts to locate a ghostscript executable, finally asking the user to 7 | % specify the directory ghostcript was installed into. The resulting path 8 | % is stored for future reference. 9 | % 10 | % Once found, the executable is called with the input command string. 11 | % 12 | % This function requires that you have Ghostscript installed on your 13 | % system. You can download this from: http://www.ghostscript.com 14 | % 15 | % IN: 16 | % cmd - Command string to be passed into ghostscript. 17 | % 18 | % OUT: 19 | % status - 0 iff command ran without problem. 20 | % result - Output from ghostscript. 21 | 22 | % Copyright: Oliver Woodford, 2009-2010 23 | 24 | % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on 25 | % Mac OS. 26 | % Thanks to Nathan Childress for the fix to the default location on 64-bit 27 | % Windows systems. 28 | % 27/4/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and 29 | % Shaun Kline for pointing out the issue 30 | % 4/5/11 - Thanks to David Chorlian for pointing out an alternative 31 | % location for gs on linux. 32 | % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish 33 | % Punnoose for highlighting the issue. 34 | 35 | function varargout = ghostscript(cmd) 36 | % Call ghostscript 37 | [varargout{1:nargout}] = system(sprintf('"%s" %s', gs_path, cmd)); 38 | return 39 | 40 | function path_ = gs_path 41 | % Return a valid path 42 | % Start with the currently set path 43 | path_ = user_string('ghostscript'); 44 | % Check the path works 45 | if check_gs_path(path_) 46 | return 47 | end 48 | % Check whether the binary is on the path 49 | if ispc 50 | bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'}; 51 | else 52 | bin = {'gs'}; 53 | end 54 | for a = 1:numel(bin) 55 | path_ = bin{a}; 56 | if check_store_gs_path(path_) 57 | return 58 | end 59 | end 60 | % Search the obvious places 61 | if ispc 62 | default_location = 'C:\Program Files\gs\'; 63 | dir_list = dir(default_location); 64 | if isempty(dir_list) 65 | default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems 66 | dir_list = dir(default_location); 67 | end 68 | executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'}; 69 | ver_num = 0; 70 | % If there are multiple versions, use the newest 71 | for a = 1:numel(dir_list) 72 | ver_num2 = sscanf(dir_list(a).name, 'gs%g'); 73 | if ~isempty(ver_num2) && ver_num2 > ver_num 74 | for b = 1:numel(executable) 75 | path2 = [default_location dir_list(a).name executable{b}]; 76 | if exist(path2, 'file') == 2 77 | path_ = path2; 78 | ver_num = ver_num2; 79 | end 80 | end 81 | end 82 | end 83 | if check_store_gs_path(path_) 84 | return 85 | end 86 | else 87 | bin = {'/usr/bin/gs', '/usr/local/bin/gs'}; 88 | for a = 1:numel(bin) 89 | path_ = bin{a}; 90 | if check_store_gs_path(path_) 91 | return 92 | end 93 | end 94 | end 95 | % Ask the user to enter the path 96 | while 1 97 | if strncmp(computer, 'MAC', 3) % Is a Mac 98 | % Give separate warning as the uigetdir dialogue box doesn't have a 99 | % title 100 | uiwait(warndlg('Ghostscript not found. Please locate the program.')) 101 | end 102 | base = uigetdir('/', 'Ghostcript not found. Please locate the program.'); 103 | if isequal(base, 0) 104 | % User hit cancel or closed window 105 | break; 106 | end 107 | base = [base filesep]; 108 | bin_dir = {'', ['bin' filesep], ['lib' filesep]}; 109 | for a = 1:numel(bin_dir) 110 | for b = 1:numel(bin) 111 | path_ = [base bin_dir{a} bin{b}]; 112 | if exist(path_, 'file') == 2 113 | if check_store_gs_path(path_) 114 | return 115 | end 116 | end 117 | end 118 | end 119 | end 120 | error('Ghostscript not found. Have you installed it from www.ghostscript.com?'); 121 | 122 | function good = check_store_gs_path(path_) 123 | % Check the path is valid 124 | good = check_gs_path(path_); 125 | if ~good 126 | return 127 | end 128 | % Update the current default path to the path found 129 | if ~user_string('ghostscript', path_) 130 | warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.'); 131 | return 132 | end 133 | return 134 | 135 | function good = check_gs_path(path_) 136 | % Check the path is valid 137 | [good, message] = system(sprintf('"%s" -h', path_)); 138 | good = good == 0; 139 | return -------------------------------------------------------------------------------- /util/parseArgs.m: -------------------------------------------------------------------------------- 1 | function ArgStruct=parseArgs(args,ArgStruct,varargin) 2 | % Helper function for parsing varargin. 3 | % 4 | % 5 | % ArgStruct=parseArgs(varargin,ArgStruct[,FlagtypeParams[,Aliases]]) 6 | % 7 | % * ArgStruct is the structure full of named arguments with default values. 8 | % * Flagtype params is params that don't require a value. (the value will be set to 1 if it is present) 9 | % * Aliases can be used to map one argument-name to several argstruct fields 10 | % 11 | % 12 | % example usage: 13 | % -------------- 14 | % function parseargtest(varargin) 15 | % 16 | % %define the acceptable named arguments and assign default values 17 | % Args=struct('Holdaxis',0, ... 18 | % 'SpacingVertical',0.05,'SpacingHorizontal',0.05, ... 19 | % 'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ... 20 | % 'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ... 21 | % 'rows',[],'cols',[]); 22 | % 23 | % %The capital letters define abrreviations. 24 | % % Eg. parseargtest('spacingvertical',0) is equivalent to parseargtest('sv',0) 25 | % 26 | % Args=parseArgs(varargin,Args, ... % fill the arg-struct with values entered by the user 27 | % {'Holdaxis'}, ... %this argument has no value (flag-type) 28 | % {'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}}); 29 | % 30 | % disp(Args) 31 | % 32 | % 33 | % 34 | % 35 | % % Aslak Grinsted 2003 36 | 37 | Aliases={}; 38 | FlagTypeParams=''; 39 | 40 | if (length(varargin)>0) 41 | FlagTypeParams=strvcat(varargin{1}); 42 | if length(varargin)>1 43 | Aliases=varargin{2}; 44 | end 45 | end 46 | 47 | 48 | %---------------Get "numeric" arguments 49 | NumArgCount=1; 50 | while (NumArgCount<=size(args,2))&(~ischar(args{NumArgCount})) 51 | NumArgCount=NumArgCount+1; 52 | end 53 | NumArgCount=NumArgCount-1; 54 | if (NumArgCount>0) 55 | ArgStruct.NumericArguments={args{1:NumArgCount}}; 56 | else 57 | ArgStruct.NumericArguments={}; 58 | end 59 | 60 | 61 | %--------------Make an accepted fieldname matrix (case insensitive) 62 | Fnames=fieldnames(ArgStruct); 63 | for i=1:length(Fnames) 64 | name=lower(Fnames{i,1}); 65 | Fnames{i,2}=name; %col2=lower 66 | AbbrevIdx=find(Fnames{i,1}~=name); 67 | Fnames{i,3}=[name(AbbrevIdx) ' ']; %col3=abreviation letters (those that are uppercase in the ArgStruct) e.g. SpacingHoriz->sh 68 | %the space prevents strvcat from removing empty lines 69 | Fnames{i,4}=isempty(strmatch(Fnames{i,2},FlagTypeParams)); %Does this parameter have a value? (e.g. not flagtype) 70 | end 71 | FnamesFull=strvcat(Fnames{:,2}); 72 | FnamesAbbr=strvcat(Fnames{:,3}); 73 | 74 | if length(Aliases)>0 75 | for i=1:length(Aliases) 76 | name=lower(Aliases{i,1}); 77 | FieldIdx=strmatch(name,FnamesAbbr,'exact'); %try abbreviations (must be exact) 78 | if isempty(FieldIdx) 79 | FieldIdx=strmatch(name,FnamesFull); %&??????? exact or not? 80 | end 81 | Aliases{i,2}=FieldIdx; 82 | AbbrevIdx=find(Aliases{i,1}~=name); 83 | Aliases{i,3}=[name(AbbrevIdx) ' ']; %the space prevents strvcat from removing empty lines 84 | Aliases{i,1}=name; %dont need the name in uppercase anymore for aliases 85 | end 86 | %Append aliases to the end of FnamesFull and FnamesAbbr 87 | FnamesFull=strvcat(FnamesFull,strvcat(Aliases{:,1})); 88 | FnamesAbbr=strvcat(FnamesAbbr,strvcat(Aliases{:,3})); 89 | end 90 | 91 | %--------------get parameters-------------------- 92 | l=NumArgCount+1; 93 | while (l<=length(args)) 94 | a=args{l}; 95 | if ischar(a) 96 | paramHasValue=1; % assume that the parameter has is of type 'param',value 97 | a=lower(a); 98 | FieldIdx=strmatch(a,FnamesAbbr,'exact'); %try abbreviations (must be exact) 99 | if isempty(FieldIdx) 100 | FieldIdx=strmatch(a,FnamesFull); 101 | end 102 | if (length(FieldIdx)>1) %shortest fieldname should win 103 | [mx,mxi]=max(sum(FnamesFull(FieldIdx,:)==' ',2)); 104 | FieldIdx=FieldIdx(mxi); 105 | end 106 | if FieldIdx>length(Fnames) %then it's an alias type. 107 | FieldIdx=Aliases{FieldIdx-length(Fnames),2}; 108 | end 109 | 110 | if isempty(FieldIdx) 111 | error(['Unknown named parameter: ' a]) 112 | end 113 | for curField=FieldIdx' %if it is an alias it could be more than one. 114 | if (Fnames{curField,4}) 115 | val=args{l+1}; 116 | else 117 | val=1; %parameter is of flag type and is set (1=true).... 118 | end 119 | ArgStruct.(Fnames{curField,1})=val; 120 | end 121 | l=l+1+Fnames{FieldIdx(1),4}; %if a wildcard matches more than one 122 | else 123 | error(['Expected a named parameter: ' num2str(a)]) 124 | end 125 | end 126 | 127 | -------------------------------------------------------------------------------- /exportfig/eps2pdf.m: -------------------------------------------------------------------------------- 1 | %EPS2PDF Convert an eps file to pdf format using ghostscript 2 | % 3 | % Examples: 4 | % eps2pdf source dest 5 | % eps2pdf(source, dest, crop) 6 | % eps2pdf(source, dest, crop, append) 7 | % eps2pdf(source, dest, crop, append, gray) 8 | % eps2pdf(source, dest, crop, append, gray, quality) 9 | % 10 | % This function converts an eps file to pdf format. The output can be 11 | % optionally cropped and also converted to grayscale. If the output pdf 12 | % file already exists then the eps file can optionally be appended as a new 13 | % page on the end of the eps file. The level of bitmap compression can also 14 | % optionally be set. 15 | % 16 | % This function requires that you have ghostscript installed on your 17 | % system. Ghostscript can be downloaded from: http://www.ghostscript.com 18 | % 19 | %IN: 20 | % source - filename of the source eps file to convert. The filename is 21 | % assumed to already have the extension ".eps". 22 | % dest - filename of the destination pdf file. The filename is assumed to 23 | % already have the extension ".pdf". 24 | % crop - boolean indicating whether to crop the borders off the pdf. 25 | % Default: true. 26 | % append - boolean indicating whether the eps should be appended to the 27 | % end of the pdf as a new page (if the pdf exists already). 28 | % Default: false. 29 | % gray - boolean indicating whether the output pdf should be grayscale or 30 | % not. Default: false. 31 | % quality - scalar indicating the level of image bitmap quality to 32 | % output. A larger value gives a higher quality. quality > 100 33 | % gives lossless output. Default: ghostscript prepress default. 34 | 35 | % Copyright (C) Oliver Woodford 2009-2011 36 | 37 | % Suggestion of appending pdf files provided by Matt C at: 38 | % http://www.mathworks.com/matlabcentral/fileexchange/23629 39 | 40 | % Thank you to Fabio Viola for pointing out compression artifacts, leading 41 | % to the quality setting. 42 | % Thank you to Scott for pointing out the subsampling of very small images, 43 | % which was fixed for lossless compression settings. 44 | 45 | % 9/12/2011 Pass font path to ghostscript. 46 | 47 | function eps2pdf(source, dest, crop, append, gray, quality) 48 | % Intialise the options string for ghostscript 49 | options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"']; 50 | % Set crop option 51 | if nargin < 3 || crop 52 | options = [options ' -dEPSCrop']; 53 | end 54 | % Set the font path 55 | fp = font_path(); 56 | if ~isempty(fp) 57 | options = [options ' -sFONTPATH="' fp '"']; 58 | end 59 | % Set the grayscale option 60 | if nargin > 4 && gray 61 | options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray']; 62 | end 63 | % Set the bitmap quality 64 | if nargin > 5 && ~isempty(quality) 65 | options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false']; 66 | if quality > 100 67 | options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"']; 68 | else 69 | options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode']; 70 | v = 1 + (quality < 80); 71 | quality = 1 - quality / 100; 72 | s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v); 73 | options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s); 74 | end 75 | end 76 | % Check if the output file exists 77 | if nargin > 3 && append && exist(dest, 'file') == 2 78 | % File exists - append current figure to the end 79 | tmp_nam = tempname; 80 | % Copy the file 81 | copyfile(dest, tmp_nam); 82 | % Add the output file names 83 | options = [options ' -f "' tmp_nam '" "' source '"']; 84 | try 85 | % Convert to pdf using ghostscript 86 | [status message] = ghostscript(options); 87 | catch 88 | % Delete the intermediate file 89 | delete(tmp_nam); 90 | rethrow(lasterror); 91 | end 92 | % Delete the intermediate file 93 | delete(tmp_nam); 94 | else 95 | % File doesn't exist or should be over-written 96 | % Add the output file names 97 | options = [options ' -f "' source '"']; 98 | % Convert to pdf using ghostscript 99 | [status message] = ghostscript(options); 100 | end 101 | % Check for error 102 | if status 103 | % Report error 104 | if isempty(message) 105 | error('Unable to generate pdf. Check destination directory is writable.'); 106 | else 107 | error(message); 108 | end 109 | end 110 | return 111 | 112 | % Function to return (and create, where necessary) the font path 113 | function fp = font_path() 114 | fp = user_string('gs_font_path'); 115 | if ~isempty(fp) 116 | return 117 | end 118 | % Create the path 119 | % Start with the default path 120 | fp = getenv('GS_FONTPATH'); 121 | % Add on the typical directories for a given OS 122 | if ispc 123 | if ~isempty(fp) 124 | fp = [fp ';']; 125 | end 126 | fp = [fp getenv('WINDIR') filesep 'Fonts']; 127 | else 128 | if ~isempty(fp) 129 | fp = [fp ':']; 130 | end 131 | fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; 132 | end 133 | user_string('gs_font_path', fp); 134 | return 135 | -------------------------------------------------------------------------------- /exportfig/fix_lines.m: -------------------------------------------------------------------------------- 1 | function fix_lines(fname, fname2) 2 | %FIX_LINES Improves the line style of eps files generated by print 3 | % 4 | % Examples: 5 | % fix_lines fname 6 | % fix_lines fname fname2 7 | % 8 | % This function improves the style of lines in eps files generated by 9 | % MATLAB's print function, making them more similar to those seen on 10 | % screen. Grid lines are also changed from a dashed style to a dotted 11 | % style, for greater differentiation from dashed lines. 12 | % 13 | % The function also places embedded fonts after the postscript header, in 14 | % versions of MATLAB which place the fonts first (R2006b and earlier), in 15 | % order to allow programs such as Ghostscript to find the bounding box 16 | % information. 17 | % 18 | % IN: 19 | % fname - Name or path of source eps file. 20 | % fname2 - Name or path of destination eps file. Default: same as fname. 21 | 22 | % Copyright: (C) Oliver Woodford, 2008-2010 23 | 24 | % The idea of editing the EPS file to change line styles comes from Jiro 25 | % Doke's FIXPSLINESTYLE (fex id: 17928) 26 | % The idea of changing dash length with line width came from comments on 27 | % fex id: 5743, but the implementation is mine :) 28 | 29 | % Thank you to Sylvain Favrot for bringing the embedded font/bounding box 30 | % interaction in older versions of MATLAB to my attention. 31 | % Thank you to D Ko for bringing an error with eps files with tiff previews 32 | % to my attention. 33 | % Thank you to Laurence K for suggesting the check to see if the file was 34 | % opened. 35 | 36 | % Read in the file 37 | fh = fopen(fname, 'r'); 38 | if fh == -1 39 | error('File %s not found.', fname); 40 | end 41 | try 42 | fstrm = fread(fh, '*char')'; 43 | catch ex 44 | fclose(fh); 45 | rethrow(ex); 46 | end 47 | fclose(fh); 48 | 49 | % Move any embedded fonts after the postscript header 50 | if strcmp(fstrm(1:15), '%!PS-AdobeFont-') 51 | % Find the start and end of the header 52 | ind = regexp(fstrm, '[\n\r]%!PS-Adobe-'); 53 | [ind2 ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+'); 54 | % Put the header first 55 | if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1) 56 | fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]); 57 | end 58 | end 59 | 60 | % Make sure all line width commands come before the line style definitions, 61 | % so that dash lengths can be based on the correct widths 62 | % Find all line style sections 63 | ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes! 64 | regexp(fstrm, '[\n\r]DO[\n\r]'),... 65 | regexp(fstrm, '[\n\r]DA[\n\r]'),... 66 | regexp(fstrm, '[\n\r]DD[\n\r]')]; 67 | ind = sort(ind); 68 | % Find line width commands 69 | [ind2 ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]'); 70 | % Go through each line style section and swap with any line width commands 71 | % near by 72 | b = 1; 73 | m = numel(ind); 74 | n = numel(ind2); 75 | for a = 1:m 76 | % Go forwards width commands until we pass the current line style 77 | while b <= n && ind2(b) < ind(a) 78 | b = b + 1; 79 | end 80 | if b > n 81 | % No more width commands 82 | break; 83 | end 84 | % Check we haven't gone past another line style (including SO!) 85 | if a < m && ind2(b) > ind(a+1) 86 | continue; 87 | end 88 | % Are the commands close enough to be confident we can swap them? 89 | if (ind2(b) - ind(a)) > 8 90 | continue; 91 | end 92 | % Move the line style command below the line width command 93 | fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)]; 94 | b = b + 1; 95 | end 96 | 97 | % Find any grid line definitions and change to GR format 98 | % Find the DO sections again as they may have moved 99 | ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]')); 100 | if ~isempty(ind) 101 | % Find all occurrences of what are believed to be axes and grid lines 102 | ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]')); 103 | if ~isempty(ind2) 104 | % Now see which DO sections come just before axes and grid lines 105 | ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]); 106 | ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right 107 | ind = ind(ind2); 108 | % Change any regions we believe to be grid lines to GR 109 | fstrm(ind+1) = 'G'; 110 | fstrm(ind+2) = 'R'; 111 | end 112 | end 113 | 114 | % Isolate line style definition section 115 | first_sec = strfind(fstrm, '% line types:'); 116 | [second_sec remaining] = strtok(fstrm(first_sec+1:end), '/'); 117 | [remaining remaining] = strtok(remaining, '%'); 118 | 119 | % Define the new styles, including the new GR format 120 | % Dot and dash lengths have two parts: a constant amount plus a line width 121 | % variable amount. The constant amount comes after dpi2point, and the 122 | % variable amount comes after currentlinewidth. If you want to change 123 | % dot/dash lengths for a one particular line style only, edit the numbers 124 | % in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and 125 | % /GR (grid lines) lines for the style you want to change. 126 | new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width 127 | '/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width 128 | '/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines 129 | '/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines 130 | '/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines 131 | '/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines 132 | '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant 133 | 134 | if nargin < 2 135 | % Overwrite the input file 136 | fname2 = fname; 137 | end 138 | 139 | % Save the file with the section replaced 140 | fh = fopen(fname2, 'w'); 141 | if fh == -1 142 | error('Unable to open %s for writing.', fname2); 143 | end 144 | try 145 | fwrite(fh, fstrm(1:first_sec), 'char*1'); 146 | fwrite(fh, second_sec, 'char*1'); 147 | fprintf(fh, '%s\r', new_style{:}); 148 | fwrite(fh, remaining, 'char*1'); 149 | catch ex 150 | fclose(fh); 151 | rethrow(ex); 152 | end 153 | fclose(fh); 154 | return -------------------------------------------------------------------------------- /exportfig/print2array.m: -------------------------------------------------------------------------------- 1 | %PRINT2ARRAY Exports a figure to an image array 2 | % 3 | % Examples: 4 | % A = print2array 5 | % A = print2array(figure_handle) 6 | % A = print2array(figure_handle, resolution) 7 | % A = print2array(figure_handle, resolution, renderer) 8 | % [A bcol] = print2array(...) 9 | % 10 | % This function outputs a bitmap image of the given figure, at the desired 11 | % resolution. 12 | % 13 | % If renderer is '-painters' then ghostcript needs to be installed. This 14 | % can be downloaded from: http://www.ghostscript.com 15 | % 16 | % IN: 17 | % figure_handle - The handle of the figure to be exported. Default: gcf. 18 | % resolution - Resolution of the output, as a factor of screen 19 | % resolution. Default: 1. 20 | % renderer - string containing the renderer paramater to be passed to 21 | % print. Default: '-opengl'. 22 | % 23 | % OUT: 24 | % A - MxNx3 uint8 image of the figure. 25 | % bcol - 1x3 uint8 vector of the background color 26 | 27 | % Copyright (C) Oliver Woodford 2008-2012 28 | 29 | % 05/09/11: Set EraseModes to normal when using opengl or zbuffer 30 | % renderers. Thanks to Pawel Kocieniewski for reporting the 31 | % issue. 32 | % 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting 33 | % the issue. 34 | % 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure 35 | % size and erasemode settings. Makes it a bit slower, but more 36 | % reliable. Thanks to Phil Trinh and Meelis Lootus for reporting 37 | % the issues. 38 | % 09/12/11: Pass font path to ghostscript. 39 | % 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to 40 | % Ken Campbell for reporting it. 41 | % 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting 42 | % it. 43 | % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for 44 | % reporting the issue. 45 | 46 | function [A, bcol] = print2array(fig, res, renderer) 47 | % Generate default input arguments, if needed 48 | if nargin < 2 49 | res = 1; 50 | if nargin < 1 51 | fig = gcf; 52 | end 53 | end 54 | % Warn if output is large 55 | old_mode = get(fig, 'Units'); 56 | set(fig, 'Units', 'pixels'); 57 | px = get(fig, 'Position'); 58 | set(fig, 'Units', old_mode); 59 | npx = prod(px(3:4)*res)/1e6; 60 | if npx > 30 61 | % 30M pixels or larger! 62 | warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx); 63 | end 64 | % Retrieve the background colour 65 | bcol = get(fig, 'Color'); 66 | % Set the resolution parameter 67 | res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))]; 68 | % Generate temporary file name 69 | tmp_nam = [tempname '.tif']; 70 | if nargin > 2 && strcmp(renderer, '-painters') 71 | % Print to eps file 72 | tmp_eps = [tempname '.eps']; 73 | print2eps(tmp_eps, fig, renderer, '-loose'); 74 | try 75 | % Initialize the command to export to tiff using ghostscript 76 | cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc']; 77 | % Set the font path 78 | fp = font_path(); 79 | if ~isempty(fp) 80 | cmd_str = [cmd_str ' -sFONTPATH="' fp '"']; 81 | end 82 | % Add the filenames 83 | cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"']; 84 | % Execute the ghostscript command 85 | ghostscript(cmd_str); 86 | catch me 87 | % Delete the intermediate file 88 | delete(tmp_eps); 89 | rethrow(me); 90 | end 91 | % Delete the intermediate file 92 | delete(tmp_eps); 93 | % Read in the generated bitmap 94 | A = imread(tmp_nam); 95 | % Delete the temporary bitmap file 96 | delete(tmp_nam); 97 | % Set border pixels to the correct colour 98 | if isequal(bcol, 'none') 99 | bcol = []; 100 | elseif isequal(bcol, [1 1 1]) 101 | bcol = uint8([255 255 255]); 102 | else 103 | for l = 1:size(A, 2) 104 | if ~all(reshape(A(:,l,:) == 255, [], 1)) 105 | break; 106 | end 107 | end 108 | for r = size(A, 2):-1:l 109 | if ~all(reshape(A(:,r,:) == 255, [], 1)) 110 | break; 111 | end 112 | end 113 | for t = 1:size(A, 1) 114 | if ~all(reshape(A(t,:,:) == 255, [], 1)) 115 | break; 116 | end 117 | end 118 | for b = size(A, 1):-1:t 119 | if ~all(reshape(A(b,:,:) == 255, [], 1)) 120 | break; 121 | end 122 | end 123 | bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1)); 124 | for c = 1:size(A, 3) 125 | A(:,[1:l-1, r+1:end],c) = bcol(c); 126 | A([1:t-1, b+1:end],:,c) = bcol(c); 127 | end 128 | end 129 | else 130 | if nargin < 3 131 | renderer = '-opengl'; 132 | end 133 | err = false; 134 | % Set paper size 135 | old_pos_mode = get(fig, 'PaperPositionMode'); 136 | old_orientation = get(fig, 'PaperOrientation'); 137 | set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); 138 | try 139 | % Print to tiff file 140 | print(fig, renderer, res_str, '-dtiff', tmp_nam); 141 | % Read in the printed file 142 | A = imread(tmp_nam); 143 | % Delete the temporary file 144 | delete(tmp_nam); 145 | catch ex 146 | err = true; 147 | end 148 | % Reset paper size 149 | set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); 150 | % Throw any error that occurred 151 | if err 152 | rethrow(ex); 153 | end 154 | % Set the background color 155 | if isequal(bcol, 'none') 156 | bcol = []; 157 | else 158 | bcol = bcol * 255; 159 | if isequal(bcol, round(bcol)) 160 | bcol = uint8(bcol); 161 | else 162 | bcol = squeeze(A(1,1,:)); 163 | end 164 | end 165 | end 166 | % Check the output size is correct 167 | if isequal(res, round(res)) 168 | px = [px([4 3])*res 3]; 169 | if ~isequal(size(A), px) 170 | % Correct the output size 171 | A = A(1:min(end,px(1)),1:min(end,px(2)),:); 172 | end 173 | end 174 | return 175 | 176 | % Function to return (and create, where necessary) the font path 177 | function fp = font_path() 178 | fp = user_string('gs_font_path'); 179 | if ~isempty(fp) 180 | return 181 | end 182 | % Create the path 183 | % Start with the default path 184 | fp = getenv('GS_FONTPATH'); 185 | % Add on the typical directories for a given OS 186 | if ispc 187 | if ~isempty(fp) 188 | fp = [fp ';']; 189 | end 190 | fp = [fp getenv('WINDIR') filesep 'Fonts']; 191 | else 192 | if ~isempty(fp) 193 | fp = [fp ':']; 194 | end 195 | fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype']; 196 | end 197 | user_string('gs_font_path', fp); 198 | return 199 | -------------------------------------------------------------------------------- /exportfig/print2eps.m: -------------------------------------------------------------------------------- 1 | %PRINT2EPS Prints figures to eps with improved line styles 2 | % 3 | % Examples: 4 | % print2eps filename 5 | % print2eps(filename, fig_handle) 6 | % print2eps(filename, fig_handle, options) 7 | % 8 | % This function saves a figure as an eps file, with two improvements over 9 | % MATLAB's print command. First, it improves the line style, making dashed 10 | % lines more like those on screen and giving grid lines their own dotted 11 | % style. Secondly, it substitutes original font names back into the eps 12 | % file, where these have been changed by MATLAB, for up to 11 different 13 | % fonts. 14 | % 15 | %IN: 16 | % filename - string containing the name (optionally including full or 17 | % relative path) of the file the figure is to be saved as. A 18 | % ".eps" extension is added if not there already. If a path is 19 | % not specified, the figure is saved in the current directory. 20 | % fig_handle - The handle of the figure to be saved. Default: gcf. 21 | % options - Additional parameter strings to be passed to print. 22 | 23 | % Copyright (C) Oliver Woodford 2008-2012 24 | 25 | % The idea of editing the EPS file to change line styles comes from Jiro 26 | % Doke's FIXPSLINESTYLE (fex id: 17928) 27 | % The idea of changing dash length with line width came from comments on 28 | % fex id: 5743, but the implementation is mine :) 29 | 30 | % 14/11/2011: Fix a MATLAB bug rendering black or white text incorrectly. 31 | % Thanks to Mathieu Morlighem for reporting the issue and 32 | % obtaining a fix from TMW. 33 | % 08/12/11: Added ability to correct fonts. Several people have requested 34 | % this at one time or another, and also pointed me to printeps 35 | % (fex id: 7501), so thank you to them. My implementation (which 36 | % was not inspired by printeps - I'd already had the idea for my 37 | % approach) goes slightly further in that it allows multiple 38 | % fonts to be swapped. 39 | % 14/12/11: Fix bug affecting font names containing spaces. Thanks to David 40 | % Szwer for reporting the issue. 41 | % 25/01/12: Add a font not to be swapped. Thanks to Anna Rafferty and Adam 42 | % Jackson for reporting the issue. Also fix a bug whereby using a 43 | % font alias can lead to another font being swapped in. 44 | % 10/04/12: Make the font swapping case insensitive. 45 | % 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for 46 | % reporting the issue. 47 | % 26/10/12: Fix issue to do with swapping fonts changing other fonts and 48 | % sizes we don't want, due to listeners. Thanks to Malcolm Hudson 49 | % for reporting the issue. 50 | 51 | function print2eps(name, fig, varargin) 52 | options = {'-depsc2'}; 53 | if nargin < 2 54 | fig = gcf; 55 | elseif nargin > 2 56 | options = [options varargin]; 57 | end 58 | % Construct the filename 59 | if numel(name) < 5 || ~strcmpi(name(end-3:end), '.eps') 60 | name = [name '.eps']; % Add the missing extension 61 | end 62 | % Find all the used fonts in the figure 63 | font_handles = findobj(fig, '-property', 'FontName'); 64 | fonts = get(font_handles, 'FontName'); 65 | if ~iscell(fonts) 66 | fonts = {fonts}; 67 | end 68 | % Map supported font aliases onto the correct name 69 | fontsl = lower(fonts); 70 | for a = 1:numel(fonts) 71 | f = fontsl{a}; 72 | f(f==' ') = []; 73 | switch f 74 | case {'times', 'timesnewroman', 'times-roman'} 75 | fontsl{a} = 'times-roman'; 76 | case {'arial', 'helvetica'} 77 | fontsl{a} = 'helvetica'; 78 | case {'newcenturyschoolbook', 'newcenturyschlbk'} 79 | fontsl{a} = 'newcenturyschlbk'; 80 | otherwise 81 | end 82 | end 83 | fontslu = unique(fontsl); 84 | % Determine the font swap table 85 | matlab_fonts = {'Helvetica', 'Times-Roman', 'Palatino', 'Bookman', 'Helvetica-Narrow', 'Symbol', ... 86 | 'AvantGarde', 'NewCenturySchlbk', 'Courier', 'ZapfChancery', 'ZapfDingbats'}; 87 | matlab_fontsl = lower(matlab_fonts); 88 | require_swap = find(~ismember(fontslu, matlab_fontsl)); 89 | unused_fonts = find(~ismember(matlab_fontsl, fontslu)); 90 | font_swap = cell(3, min(numel(require_swap), numel(unused_fonts))); 91 | fonts_new = fonts; 92 | for a = 1:size(font_swap, 2) 93 | font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl)); 94 | font_swap{2,a} = matlab_fonts{unused_fonts(a)}; 95 | font_swap{3,a} = fonts{font_swap{1,end}(1)}; 96 | fonts_new(font_swap{1,a}) = {font_swap{2,a}}; 97 | end 98 | % Swap the fonts 99 | if ~isempty(font_swap) 100 | fonts_size = get(font_handles, 'FontSize'); 101 | if iscell(fonts_size) 102 | fonts_size = cell2mat(fonts_size); 103 | end 104 | M = false(size(font_handles)); 105 | % Loop because some changes may not stick first time, due to listeners 106 | c = 0; 107 | update = zeros(1000, 1); 108 | for b = 1:10 % Limit number of loops to avoid infinite loop case 109 | for a = 1:numel(M) 110 | M(a) = ~isequal(get(font_handles(a), 'FontName'), fonts_new{a}) || ~isequal(get(font_handles(a), 'FontSize'), fonts_size(a)); 111 | if M(a) 112 | set(font_handles(a), 'FontName', fonts_new{a}, 'FontSize', fonts_size(a)); 113 | c = c + 1; 114 | update(c) = a; 115 | end 116 | end 117 | if ~any(M) 118 | break; 119 | end 120 | end 121 | % Compute the order to revert fonts later, without the need of a loop 122 | [update, M] = unique(update(1:c)); 123 | [M, M] = sort(M); 124 | update = reshape(update(M), 1, []); 125 | end 126 | % Set paper size 127 | old_pos_mode = get(fig, 'PaperPositionMode'); 128 | old_orientation = get(fig, 'PaperOrientation'); 129 | set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait'); 130 | % MATLAB bug fix - black and white text can come out inverted sometimes 131 | % Find the white and black text 132 | white_text_handles = findobj(fig, 'Type', 'text'); 133 | M = get(white_text_handles, 'Color'); 134 | if iscell(M) 135 | M = cell2mat(M); 136 | end 137 | M = sum(M, 2); 138 | black_text_handles = white_text_handles(M == 0); 139 | white_text_handles = white_text_handles(M == 3); 140 | % Set the font colors slightly off their correct values 141 | set(black_text_handles, 'Color', [0 0 0] + eps); 142 | set(white_text_handles, 'Color', [1 1 1] - eps); 143 | % Print to eps file 144 | print(fig, options{:}, name); 145 | % Reset the font colors 146 | set(black_text_handles, 'Color', [0 0 0]); 147 | set(white_text_handles, 'Color', [1 1 1]); 148 | % Reset paper size 149 | set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation); 150 | % Correct the fonts 151 | if ~isempty(font_swap) 152 | % Reset the font names in the figure 153 | for a = update 154 | set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a)); 155 | end 156 | % Replace the font names in the eps file 157 | font_swap = font_swap(2:3,:); 158 | try 159 | swap_fonts(name, font_swap{:}); 160 | catch 161 | warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.'); 162 | return 163 | end 164 | end 165 | % Fix the line styles 166 | try 167 | fix_lines(name); 168 | catch 169 | warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.'); 170 | end 171 | return 172 | 173 | function swap_fonts(fname, varargin) 174 | % Read in the file 175 | fh = fopen(fname, 'r'); 176 | if fh == -1 177 | error('File %s not found.', fname); 178 | end 179 | try 180 | fstrm = fread(fh, '*char')'; 181 | catch ex 182 | fclose(fh); 183 | rethrow(ex); 184 | end 185 | fclose(fh); 186 | 187 | % Replace the font names 188 | for a = 1:2:numel(varargin) 189 | fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1}))); 190 | end 191 | 192 | % Write out the updated file 193 | fh = fopen(fname, 'w'); 194 | if fh == -1 195 | error('Unable to open %s for writing.', fname2); 196 | end 197 | try 198 | fwrite(fh, fstrm, 'char*1'); 199 | catch ex 200 | fclose(fh); 201 | rethrow(ex); 202 | end 203 | fclose(fh); 204 | return 205 | -------------------------------------------------------------------------------- /harlemshake.m: -------------------------------------------------------------------------------- 1 | function harlem_shake( save_pngs_flag ) 2 | % Harlem shake - MCMC version. 3 | % 4 | % Tamara Broderick 5 | % David Duvenaud 6 | % 7 | % Current available at: 8 | % http://github.com/duvenaud/harlemcmc-shake 9 | % 10 | % March 2013 11 | 12 | 13 | addpath('exportfig'); 14 | addpath('util'); 15 | 16 | 17 | mh_time = 16; % Seconds of buildup part. 18 | hmc_time = 23; % Seconds of crazy part. 19 | framerate = 14; % Hz. 20 | n_mh_frames = mh_time * framerate; 21 | n_hmc_frames = hmc_time * framerate; 22 | 23 | % Check for previously cached samples. 24 | cache_filename = 'sample_cache.mat'; 25 | if exist(cache_filename, 'file') 26 | load(cache_filename); 27 | else 28 | mh_proposal_cov = [ 0.005 0; 0 0.005 ]; 29 | mh_proposal_middle_cov = [ 0.5 0; 0 0.5 ]; 30 | 31 | % Set up some mixtures of Gaussians. 32 | mixes = define_mixes(); 33 | num_mixes = numel(mixes); 34 | 35 | % Fix the seed of the random generators. 36 | seed=0; 37 | randn('state',seed); 38 | rand('state',seed); 39 | 40 | % Start with samples from these dists. 41 | x = cell(num_mixes, 1); 42 | for n = 1:num_mixes 43 | x{n} = mix_gaussians_draw( mixes{n}, 1 ); 44 | end 45 | 46 | % Run M-H. 47 | fprintf('\nComputing MH samples'); 48 | for m = 1:num_mixes 49 | samples{m} = NaN(n_mh_frames, 2); 50 | samples{m}(1,:) = x{m}; 51 | 52 | if m == 5 % The central Gaussian gets its own proposal distribution. 53 | cur_cov = mh_proposal_middle_cov; 54 | else 55 | cur_cov = mh_proposal_cov; 56 | end 57 | for n = 2:n_mh_frames 58 | samples{m}(n,:) = mog_mh( mixes{m}, samples{m}(n - 1,:), cur_cov ); 59 | end 60 | fprintf('.'); 61 | end 62 | 63 | % Fix the seed of the random generators. 64 | randn('state',seed); 65 | rand('state',seed); 66 | 67 | fprintf('\nComputing HMC samples'); 68 | for m = 1:num_mixes 69 | 70 | if 0 71 | % NUTS. 72 | Madapt = 250; 73 | loglikefunc = @(t) mix_gaussians_log_pdf( t, mixes{m} ); 74 | lambda = 0.1; 75 | [samples{m}, epsilon] = hmc_da(loglikefunc, n_frames, Madapt, x{m}, lambda); 76 | else 77 | % Mackay brand HMC 78 | hmc_options.num_iters = 1; 79 | hmc_options.Tau = 20; % Number of steps. 80 | hmc_options.epsilon = 0.05; 81 | hmc_samples{m} = NaN(n_hmc_frames, 2); 82 | hmc_samples{m}(1,:) = x{m}; 83 | for n = 2:n_hmc_frames 84 | loglikefunc = @(t) mix_gaussians_neg_log_pdf( t, mixes{m} ); 85 | [hmc_samples{m}(n,:), nll, arate, tail{m,n}] = hmc( loglikefunc, hmc_samples{m}(n - 1,:), hmc_options ); 86 | end 87 | end 88 | 89 | fprintf('.'); 90 | end 91 | save(cache_filename); 92 | end 93 | 94 | if nargin < 1 95 | save_pngs = false; 96 | else 97 | save_pngs = save_pngs_flag; 98 | end 99 | 100 | visual_framerate = framerate; 101 | plot_hmc_tails = true; 102 | 103 | 104 | figure(1); clf; 105 | set(gcf, 'Position',[1 1 1400 1050]); 106 | 107 | % Plot MH part. 108 | frame_number = 1; 109 | frame_number = plot_samples( samples, n_mh_frames, num_mixes, save_pngs, visual_framerate, frame_number, mixes, [], plot_hmc_tails ); 110 | 111 | fprintf('\n\nDO THE HARLEM SHAKE\n\n') 112 | 113 | % Plot HMC part. 114 | plot_samples( hmc_samples, n_hmc_frames, num_mixes, save_pngs, visual_framerate, frame_number, mixes, tail, plot_hmc_tails ); 115 | 116 | 117 | % Compile the video. 118 | if save_pngs 119 | system('ffmpeg -r 14 -i frames/hs_%04d.png -vcodec huffyuv hs_movie_v7.avi'); 120 | end 121 | 122 | end 123 | 124 | 125 | function frame_number = plot_samples( samples, n_frames, num_mixes, ... 126 | save_pngs, framerate, frame_number, mixes, tail, plot_hmc_tails ) 127 | 128 | history = 10; 129 | num_hmc_tails = 9; 130 | col_change_frames = 6; 131 | 132 | 133 | in_hmc = numel(tail) > 0; 134 | if in_hmc 135 | ls = 'none'; 136 | else 137 | ls = '-'; 138 | end 139 | 140 | % Cache contours. 141 | for m = 1:num_mixes 142 | margin = 0.01; 143 | h_axes(m) = subaxis(3,3,m,'Spacing',0.01, 'MR',0.01, 'Holdaxis', true, ... 144 | 'MarginLeft',margin,'MarginRight',margin, ... 145 | 'MarginTop',margin,'MarginBottom',margin); 146 | 147 | plot_one_contour(mixes{m}); hold on; 148 | set(gca, 'LooseInset', [0,0,0,0]); 149 | end 150 | 151 | col_ix = 2; 152 | c_array(1, :) = [ 55, 126, 184 ]; % blue 153 | c_array(2, :) = [ 255, 127, 1 ]; % orange 154 | c_array(3, :) = [ 77, 175, 74 ]; % green 155 | c_array(4, :) = [ 250, 60, 80 ]; % red 156 | c_array(5, :) = [ 152, 78, 163 ]; % purple 157 | c_array(6, :) = [ 200, 255, 51 ]; % yellow 158 | 159 | 160 | for n = 1: n_frames 161 | 162 | % Change the background color if we're in the HMC phase. 163 | if in_hmc && (mod(n, col_change_frames) == 1) 164 | set(gcf, 'color', c_array(mod(col_ix, 6) + 1, :) ./255); 165 | col_ix = col_ix + 1; 166 | end 167 | 168 | cur_range = max(1, n - history):n; 169 | cur_tail_range = max(1, n - num_hmc_tails):n; 170 | 171 | % Plot Gibbs samplers running. 172 | for m = 1:num_mixes 173 | % Plot the sample. 174 | if plot_hmc_tails && in_hmc 175 | % Show HMC tail. 176 | for t_ix = cur_tail_range 177 | if numel(tail{m,t_ix}) > 0 178 | h_tail{m, t_ix} = plot(h_axes(m), tail{m,t_ix}(:,1), tail{m,t_ix}(:,2), ... 179 | 'c-', 'LineWidth', 5, 'Color', colorbrew(6)); 180 | end 181 | end 182 | end 183 | 184 | h{m} = plot(h_axes(m), samples{m}(cur_range,1), samples{m}(cur_range,2), ... 185 | '-', 'LineWidth', 7, 'Marker', 'o', 'MarkerSize', 15, ... 186 | 'LineStyle', ls, 'MarkerFaceColor', 'r', 'Color', colorbrew(6), ... 187 | 'MarkerEdgeColor', 'r'); 188 | end 189 | 190 | pause(1/framerate); 191 | 192 | if save_pngs 193 | set(gcf, 'Position',[1 1 1024 768]); 194 | export_fig('-nocrop', sprintf('frames/hs_%04d.png', frame_number)); 195 | end 196 | frame_number = frame_number + 1; 197 | 198 | % Erase old dots. 199 | for m = 1:num_mixes 200 | delete(h{m}); 201 | if plot_hmc_tails && in_hmc 202 | for t_ix = cur_tail_range 203 | if numel(tail{m,t_ix}) > 0 204 | delete(h_tail{m, t_ix}); 205 | end 206 | end 207 | end 208 | end 209 | end 210 | 211 | end 212 | 213 | 214 | 215 | function dist_vals = plot_one_contour(mix, dist_vals) 216 | % Plot the contours. 217 | length = 2; 218 | range = [ -length, length; -length length]; 219 | N_1d = 100; 220 | ncontours = 4; 221 | 222 | xrange = linspace( range(1,1), range(1,2), N_1d); % Choose a set of x locations. 223 | yrange = linspace( range(2,1), range(2,2), N_1d); % Choose a set of x locations. 224 | [xvals, yvals] = meshgrid( xrange, yrange); 225 | gridvals = [xvals(:) yvals(:)]; 226 | 227 | if nargin < 2 228 | dist_vals = mix_gaussians_pdf(gridvals, mix ); 229 | end 230 | 231 | %colormap('Gray'); 232 | %map = [0 0 0; 1 1 1]; 233 | %sc = 0.5; ec = 1; 234 | %gradient = linspace( sc, ec, 100)'.^1; 235 | %map = [gradient, gradient, gradient]; 236 | map = [1 1 1]; 237 | colormap(map); 238 | 239 | dh = contour( xvals, yvals, reshape(dist_vals .^ 0.6, N_1d, N_1d ), ncontours, ... 240 | 'LineWidth', 1); hold on; 241 | 242 | % Make plot prettier. 243 | set(gcf, 'color', 'white'); 244 | set(gca, 'color', 'black'); 245 | set(gca, 'YGrid', 'off'); 246 | set(gca, 'Xtick', []); 247 | set(gca, 'Ytick', []); 248 | %axis off 249 | end 250 | 251 | 252 | 253 | function mixes = define_mixes() 254 | 255 | mixes = cell(0); 256 | 257 | % H. 258 | if 1 259 | skinny = 0.01; 260 | really_skinny = 0.005; 261 | fat = 0.6; 262 | vert_cov = [really_skinny 0; 0 fat]; 263 | horz_cov = [fat 0; 0 skinny]; 264 | mix.means = [ -1.5 0; 0 0; 1.5 0]; 265 | mix.covs(:,:,1) = vert_cov; 266 | mix.covs(:,:,2) = horz_cov; 267 | mix.covs(:,:,3) = vert_cov; 268 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 269 | mixes{end + 1} = mix; 270 | end 271 | 272 | % A. 273 | if 1 274 | skinny = 0.01; 275 | fat = 0.45; 276 | horz_cov = [fat 0; 0 skinny]; 277 | mix.means = [ 0 -1; -0.9 0; 0.9 0]; 278 | mix.covs(:,:,1) = horz_cov; 279 | lengths = [0.01 1.2]; 280 | mix.covs(:,:,2) = rotate_cov( lengths, pi/8 ); 281 | mix.covs(:,:,3) = rotate_cov( lengths, -pi/8 ); 282 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 283 | mixes{end + 1} = mix; 284 | end 285 | 286 | 287 | % R. 288 | if 1 289 | skinny = 0.01; 290 | fat = 0.75; 291 | vert_cov = [skinny 0; 0 fat]; 292 | mix.means = [ -1.5 0; 0.25 1.25; 0.25 0.5; 0.25 -0.9 ]; 293 | mix.covs(:,:,1) = vert_cov; 294 | lengths = [1.2 0.01]; 295 | mix.covs(:,:,2) = rotate_cov( lengths, pi/12 ); 296 | mix.covs(:,:,3) = rotate_cov( lengths, -pi/12 ); 297 | mix.covs(:,:,4) = rotate_cov( lengths, pi/8 ); 298 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 299 | mixes{end + 1} = mix; 300 | end 301 | 302 | % L. 303 | if 1 304 | skinny = 0.01; 305 | fat = 0.6; 306 | vert_cov = [skinny 0; 0 fat]; 307 | horz_cov = [fat 0; 0 skinny]; 308 | mix.means = [ -1.5 0; 0 -1.5]; 309 | mix.covs(:,:,1) = vert_cov; 310 | mix.covs(:,:,2) = horz_cov; 311 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 312 | mixes{end + 1} = mix; 313 | end 314 | 315 | % Spherical Gaussian. 316 | mix.weights = 1; 317 | mix.means = [ 0 0]; 318 | mix.covs = [ 1 0; 0 1]; 319 | mixes{end + 1} = mix; 320 | 321 | 322 | % M. 323 | if 1 324 | skinny = 0.01; 325 | really_skinny = 0.005; 326 | fat = 0.6; 327 | vert_cov = [really_skinny 0; 0 fat]; 328 | mix.means = [ -1.5 0; 1.5 0; -0.7 0.2; 0.7 0.2 ]; 329 | mix.covs(:,:,1) = vert_cov; 330 | mix.covs(:,:,2) = vert_cov; 331 | lengths = [0.01 1]; 332 | mix.covs(:,:,3) = rotate_cov( lengths, -pi/6 ); 333 | mix.covs(:,:,4) = rotate_cov( lengths, pi/6 ); 334 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 335 | mixes{end + 1} = mix; 336 | end 337 | 338 | %S 339 | if 1 340 | num_circle = 50; 341 | angles = linspace( -pi/2, pi, num_circle) + pi/2; 342 | mix.means = [cos( angles').*1.75 - 1, sin(angles').*0.9] + 0.9; 343 | mix.means = [mix.means; -mix.means]; 344 | mix.covs = repmat( [ 1 0; 0 1], [1, 1, num_circle*2]) .* 0.01; 345 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 346 | mixes{end + 1} = mix; 347 | end 348 | 349 | % H. 350 | if 1 351 | skinny = 0.1; 352 | really_skinny = 0.005; 353 | fat1 = 1.2; 354 | fat2 = 0.6; 355 | vert_cov = [really_skinny 0; 0 fat1]; 356 | horz_cov = [fat2 0; 0 skinny]; 357 | mix.means = [ -1.5 0; 0 0; 1.5 0]; 358 | mix.covs(:,:,1) = vert_cov; 359 | mix.covs(:,:,2) = horz_cov; 360 | mix.covs(:,:,3) = vert_cov; 361 | %mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 362 | mix.weights = [0.1 0.8 0.1]; 363 | mixes{end + 1} = mix; 364 | end 365 | 366 | 367 | % K. 368 | if 1 369 | skinny = 0.01; 370 | fat = 0.75; 371 | vert_cov = [skinny 0; 0 fat]; 372 | mix.means = [ -1.5 0; -0.1 -0.8; -0.1 0.8 ]; 373 | mix.covs(:,:,1) = vert_cov; 374 | lengths = [1.2 0.01]; 375 | mix.covs(:,:,2) = rotate_cov( lengths, pi/6 ); 376 | mix.covs(:,:,3) = rotate_cov( lengths, -pi/6 ); 377 | mix.weights = ones(size(mix.means,1),1) ./ size(mix.means,1); 378 | mixes{end + 1} = mix; 379 | end 380 | 381 | end 382 | 383 | 384 | 385 | 386 | -------------------------------------------------------------------------------- /exportfig/export_fig.m: -------------------------------------------------------------------------------- 1 | %EXPORT_FIG Exports figures suitable for publication 2 | % 3 | % Examples: 4 | % im = export_fig 5 | % [im alpha] = export_fig 6 | % export_fig filename 7 | % export_fig filename -format1 -format2 8 | % export_fig ... -nocrop 9 | % export_fig ... -transparent 10 | % export_fig ... -native 11 | % export_fig ... -m 12 | % export_fig ... -r 13 | % export_fig ... -a 14 | % export_fig ... -q 15 | % export_fig ... - 16 | % export_fig ... - 17 | % export_fig ... -append 18 | % export_fig ... -bookmark 19 | % export_fig(..., handle) 20 | % 21 | % This function saves a figure or single axes to one or more vector and/or 22 | % bitmap file formats, and/or outputs a rasterized version to the 23 | % workspace, with the following properties: 24 | % - Figure/axes reproduced as it appears on screen 25 | % - Cropped borders (optional) 26 | % - Embedded fonts (vector formats) 27 | % - Improved line and grid line styles 28 | % - Anti-aliased graphics (bitmap formats) 29 | % - Render images at native resolution (optional for bitmap formats) 30 | % - Transparent background supported (pdf, eps, png) 31 | % - Semi-transparent patch objects supported (png only) 32 | % - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff) 33 | % - Variable image compression, including lossless (pdf, eps, jpg) 34 | % - Optionally append to file (pdf, tiff) 35 | % - Vector formats: pdf, eps 36 | % - Bitmap formats: png, tiff, jpg, bmp, export to workspace 37 | % 38 | % This function is especially suited to exporting figures for use in 39 | % publications and presentations, because of the high quality and 40 | % portability of media produced. 41 | % 42 | % Note that the background color and figure dimensions are reproduced 43 | % (the latter approximately, and ignoring cropping & magnification) in the 44 | % output file. For transparent background (and semi-transparent patch 45 | % objects), use the -transparent option or set the figure 'Color' property 46 | % to 'none'. To make axes transparent set the axes 'Color' property to 47 | % 'none'. Pdf, eps and png are the only file formats to support a 48 | % transparent background, whilst the png format alone supports transparency 49 | % of patch objects. 50 | % 51 | % The choice of renderer (opengl, zbuffer or painters) has a large impact 52 | % on the quality of output. Whilst the default value (opengl for bitmaps, 53 | % painters for vector formats) generally gives good results, if you aren't 54 | % satisfied then try another renderer. Notes: 1) For vector formats (eps, 55 | % pdf), only painters generates vector graphics. 2) For bitmaps, only 56 | % opengl can render transparent patch objects correctly. 3) For bitmaps, 57 | % only painters will correctly scale line dash and dot lengths when 58 | % magnifying or anti-aliasing. 4) Fonts may be substitued with Courier when 59 | % using painters. 60 | % 61 | % When exporting to vector format (pdf & eps) and bitmap format using the 62 | % painters renderer, this function requires that ghostscript is installed 63 | % on your system. You can download this from: 64 | % http://www.ghostscript.com 65 | % When exporting to eps it additionally requires pdftops, from the Xpdf 66 | % suite of functions. You can download this from: 67 | % http://www.foolabs.com/xpdf 68 | % 69 | %IN: 70 | % filename - string containing the name (optionally including full or 71 | % relative path) of the file the figure is to be saved as. If 72 | % a path is not specified, the figure is saved in the current 73 | % directory. If no name and no output arguments are specified, 74 | % the default name, 'export_fig_out', is used. If neither a 75 | % file extension nor a format are specified, a ".png" is added 76 | % and the figure saved in that format. 77 | % -format1, -format2, etc. - strings containing the extensions of the 78 | % file formats the figure is to be saved as. 79 | % Valid options are: '-pdf', '-eps', '-png', 80 | % '-tif', '-jpg' and '-bmp'. All combinations 81 | % of formats are valid. 82 | % -nocrop - option indicating that the borders of the output are not to 83 | % be cropped. 84 | % -transparent - option indicating that the figure background is to be 85 | % made transparent (png, pdf and eps output only). 86 | % -m - option where val indicates the factor to magnify the 87 | % on-screen figure dimensions by when generating bitmap 88 | % outputs. Default: '-m1'. 89 | % -r - option val indicates the resolution (in pixels per inch) to 90 | % export bitmap outputs at, keeping the dimensions of the 91 | % on-screen figure. Default: sprintf('-r%g', get(0, 92 | % 'ScreenPixelsPerInch')). Note that the -m and -r options 93 | % change the same property. 94 | % -native - option indicating that the output resolution (when outputting 95 | % a bitmap format) should be such that the vertical resolution 96 | % of the first suitable image found in the figure is at the 97 | % native resolution of that image. To specify a particular 98 | % image to use, give it the tag 'export_fig_native'. Notes: 99 | % This overrides any value set with the -m and -r options. It 100 | % also assumes that the image is displayed front-to-parallel 101 | % with the screen. The output resolution is approximate and 102 | % should not be relied upon. Anti-aliasing can have adverse 103 | % effects on image quality (disable with the -a1 option). 104 | % -a1, -a2, -a3, -a4 - option indicating the amount of anti-aliasing to 105 | % use for bitmap outputs. '-a1' means no anti- 106 | % aliasing; '-a4' is the maximum amount (default). 107 | % - - option to force a particular renderer (painters, opengl 108 | % or zbuffer) to be used over the default: opengl for 109 | % bitmaps; painters for vector formats. 110 | % - - option indicating which colorspace color figures should 111 | % be saved in: RGB (default), CMYK or gray. CMYK is only 112 | % supported in pdf, eps and tiff output. 113 | % -q - option to vary bitmap image quality (in pdf, eps and jpg 114 | % files only). Larger val, in the range 0-100, gives higher 115 | % quality/lower compression. val > 100 gives lossless 116 | % compression. Default: '-q95' for jpg, ghostscript prepress 117 | % default for pdf & eps. Note: lossless compression can 118 | % sometimes give a smaller file size than the default lossy 119 | % compression, depending on the type of images. 120 | % -append - option indicating that if the file (pdfs only) already 121 | % exists, the figure is to be appended as a new page, instead 122 | % of being overwritten (default). 123 | % -bookmark - option to indicate that a bookmark with the name of the 124 | % figure is to be created in the output file (pdf only). 125 | % handle - The handle of the figure, axes or uipanels (can be an array of 126 | % handles, but the objects must be in the same figure) to be 127 | % saved. Default: gcf. 128 | % 129 | %OUT: 130 | % im - MxNxC uint8 image array of the figure. 131 | % alpha - MxN single array of alphamatte values in range [0,1], for the 132 | % case when the background is transparent. 133 | % 134 | % Some helpful examples and tips can be found at: 135 | % http://sites.google.com/site/oliverwoodford/software/export_fig 136 | % 137 | % See also PRINT, SAVEAS. 138 | 139 | % Copyright (C) Oliver Woodford 2008-2012 140 | 141 | % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG 142 | % (fex id: 10889) which is itself inspired by EPS2PDF (fex id: 5782). 143 | % The idea for using pdftops came from the MATLAB newsgroup (id: 168171). 144 | % The idea of editing the EPS file to change line styles comes from Jiro 145 | % Doke's FIXPSLINESTYLE (fex id: 17928). 146 | % The idea of changing dash length with line width came from comments on 147 | % fex id: 5743, but the implementation is mine :) 148 | % The idea of anti-aliasing bitmaps came from Anders Brun's MYAA (fex id: 149 | % 20979). 150 | % The idea of appending figures in pdfs came from Matt C in comments on the 151 | % FEX (id: 23629) 152 | 153 | % Thanks to Roland Martin for pointing out the colour MATLAB 154 | % bug/feature with colorbar axes and transparent backgrounds. 155 | % Thanks also to Andrew Matthews for describing a bug to do with the figure 156 | % size changing in -nodisplay mode. I couldn't reproduce it, but included a 157 | % fix anyway. 158 | % Thanks to Tammy Threadgill for reporting a bug where an axes is not 159 | % isolated from gui objects. 160 | 161 | % 23/02/12: Ensure that axes limits don't change during printing 162 | % 14/03/12: Fix bug in fixing the axes limits (thanks to Tobias Lamour for 163 | % reporting it). 164 | % 02/05/12: Incorporate patch of Petr Nechaev (many thanks), enabling 165 | % bookmarking of figures in pdf files. 166 | % 09/05/12: Incorporate patch of Arcelia Arrieta (many thanks), to keep 167 | % tick marks fixed. 168 | % 12/12/12: Add support for isolating uipanels. Thanks to michael for 169 | % suggesting it. 170 | 171 | function [im, alpha] = export_fig(varargin) 172 | % Make sure the figure is rendered correctly _now_ so that properties like 173 | % axes limits are up-to-date. 174 | drawnow; 175 | % Parse the input arguments 176 | [fig, options] = parse_args(nargout, varargin{:}); 177 | % Isolate the subplot, if it is one 178 | cls = all(ismember(get(fig, 'Type'), {'axes', 'uipanel'})); 179 | if cls 180 | % Given handles of one or more axes, so isolate them from the rest 181 | fig = isolate_axes(fig); 182 | else 183 | % Check we have a figure 184 | if ~isequal(get(fig, 'Type'), 'figure'); 185 | error('Handle must be that of a figure, axes or uipanel'); 186 | end 187 | % Get the old InvertHardcopy mode 188 | old_mode = get(fig, 'InvertHardcopy'); 189 | end 190 | % Hack the font units where necessary (due to a font rendering bug in 191 | % print?). This may not work perfectly in all cases. Also it can change the 192 | % figure layout if reverted, so use a copy. 193 | magnify = options.magnify * options.aa_factor; 194 | if isbitmap(options) && magnify ~= 1 195 | fontu = findobj(fig, 'FontUnits', 'normalized'); 196 | if ~isempty(fontu) 197 | % Some normalized font units found 198 | if ~cls 199 | fig = copyfig(fig); 200 | set(fig, 'Visible', 'off'); 201 | fontu = findobj(fig, 'FontUnits', 'normalized'); 202 | cls = true; 203 | end 204 | set(fontu, 'FontUnits', 'points'); 205 | end 206 | end 207 | % MATLAB "feature": axes limits and tick marks can change when printing 208 | Hlims = findall(fig, 'Type', 'axes'); 209 | if ~cls 210 | % Record the old axes limit and tick modes 211 | Xlims = make_cell(get(Hlims, 'XLimMode')); 212 | Ylims = make_cell(get(Hlims, 'YLimMode')); 213 | Zlims = make_cell(get(Hlims, 'ZLimMode')); 214 | Xtick = make_cell(get(Hlims, 'XTickMode')); 215 | Ytick = make_cell(get(Hlims, 'YTickMode')); 216 | Ztick = make_cell(get(Hlims, 'ZTickMode')); 217 | end 218 | % Set all axes limit and tick modes to manual, so the limits and ticks can't change 219 | set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual'); 220 | % Set to print exactly what is there 221 | set(fig, 'InvertHardcopy', 'off'); 222 | % Set the renderer 223 | switch options.renderer 224 | case 1 225 | renderer = '-opengl'; 226 | case 2 227 | renderer = '-zbuffer'; 228 | case 3 229 | renderer = '-painters'; 230 | otherwise 231 | renderer = '-opengl'; % Default for bitmaps 232 | end 233 | % Do the bitmap formats first 234 | if isbitmap(options) 235 | % Get the background colour 236 | if options.transparent && (options.png || options.alpha) 237 | % Get out an alpha channel 238 | % MATLAB "feature": black colorbar axes can change to white and vice versa! 239 | hCB = findobj(fig, 'Type', 'axes', 'Tag', 'Colorbar'); 240 | if isempty(hCB) 241 | yCol = []; 242 | xCol = []; 243 | else 244 | yCol = get(hCB, 'YColor'); 245 | xCol = get(hCB, 'XColor'); 246 | if iscell(yCol) 247 | yCol = cell2mat(yCol); 248 | xCol = cell2mat(xCol); 249 | end 250 | yCol = sum(yCol, 2); 251 | xCol = sum(xCol, 2); 252 | end 253 | % MATLAB "feature": apparently figure size can change when changing 254 | % colour in -nodisplay mode 255 | pos = get(fig, 'Position'); 256 | % Set the background colour to black, and set size in case it was 257 | % changed internally 258 | tcol = get(fig, 'Color'); 259 | set(fig, 'Color', 'k', 'Position', pos); 260 | % Correct the colorbar axes colours 261 | set(hCB(yCol==0), 'YColor', [0 0 0]); 262 | set(hCB(xCol==0), 'XColor', [0 0 0]); 263 | % Print large version to array 264 | B = print2array(fig, magnify, renderer); 265 | % Downscale the image 266 | B = downsize(single(B), options.aa_factor); 267 | % Set background to white (and set size) 268 | set(fig, 'Color', 'w', 'Position', pos); 269 | % Correct the colorbar axes colours 270 | set(hCB(yCol==3), 'YColor', [1 1 1]); 271 | set(hCB(xCol==3), 'XColor', [1 1 1]); 272 | % Print large version to array 273 | A = print2array(fig, magnify, renderer); 274 | % Downscale the image 275 | A = downsize(single(A), options.aa_factor); 276 | % Set the background colour (and size) back to normal 277 | set(fig, 'Color', tcol, 'Position', pos); 278 | % Compute the alpha map 279 | alpha = round(sum(B - A, 3)) / (255 * 3) + 1; 280 | A = alpha; 281 | A(A==0) = 1; 282 | A = B ./ A(:,:,[1 1 1]); 283 | clear B 284 | % Convert to greyscale 285 | if options.colourspace == 2 286 | A = rgb2grey(A); 287 | end 288 | A = uint8(A); 289 | % Crop the background 290 | if options.crop 291 | [alpha, v] = crop_background(alpha, 0); 292 | A = A(v(1):v(2),v(3):v(4),:); 293 | end 294 | if options.png 295 | % Compute the resolution 296 | res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; 297 | % Save the png 298 | imwrite(A, [options.name '.png'], 'Alpha', double(alpha), 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); 299 | % Clear the png bit 300 | options.png = false; 301 | end 302 | % Return only one channel for greyscale 303 | if isbitmap(options) 304 | A = check_greyscale(A); 305 | end 306 | if options.alpha 307 | % Store the image 308 | im = A; 309 | % Clear the alpha bit 310 | options.alpha = false; 311 | end 312 | % Get the non-alpha image 313 | if isbitmap(options) 314 | alph = alpha(:,:,ones(1, size(A, 3))); 315 | A = uint8(single(A) .* alph + 255 * (1 - alph)); 316 | clear alph 317 | end 318 | if options.im 319 | % Store the new image 320 | im = A; 321 | end 322 | else 323 | % Print large version to array 324 | if options.transparent 325 | % MATLAB "feature": apparently figure size can change when changing 326 | % colour in -nodisplay mode 327 | pos = get(fig, 'Position'); 328 | tcol = get(fig, 'Color'); 329 | set(fig, 'Color', 'w', 'Position', pos); 330 | A = print2array(fig, magnify, renderer); 331 | set(fig, 'Color', tcol, 'Position', pos); 332 | tcol = 255; 333 | else 334 | [A, tcol] = print2array(fig, magnify, renderer); 335 | end 336 | % Crop the background 337 | if options.crop 338 | A = crop_background(A, tcol); 339 | end 340 | % Downscale the image 341 | A = downsize(A, options.aa_factor); 342 | if options.colourspace == 2 343 | % Convert to greyscale 344 | A = rgb2grey(A); 345 | else 346 | % Return only one channel for greyscale 347 | A = check_greyscale(A); 348 | end 349 | % Outputs 350 | if options.im 351 | im = A; 352 | end 353 | if options.alpha 354 | im = A; 355 | alpha = zeros(size(A, 1), size(A, 2), 'single'); 356 | end 357 | end 358 | % Save the images 359 | if options.png 360 | res = options.magnify * get(0, 'ScreenPixelsPerInch') / 25.4e-3; 361 | imwrite(A, [options.name '.png'], 'ResolutionUnit', 'meter', 'XResolution', res, 'YResolution', res); 362 | end 363 | if options.bmp 364 | imwrite(A, [options.name '.bmp']); 365 | end 366 | % Save jpeg with given quality 367 | if options.jpg 368 | quality = options.quality; 369 | if isempty(quality) 370 | quality = 95; 371 | end 372 | if quality > 100 373 | imwrite(A, [options.name '.jpg'], 'Mode', 'lossless'); 374 | else 375 | imwrite(A, [options.name '.jpg'], 'Quality', quality); 376 | end 377 | end 378 | % Save tif images in cmyk if wanted (and possible) 379 | if options.tif 380 | if options.colourspace == 1 && size(A, 3) == 3 381 | A = double(255 - A); 382 | K = min(A, [], 3); 383 | K_ = 255 ./ max(255 - K, 1); 384 | C = (A(:,:,1) - K) .* K_; 385 | M = (A(:,:,2) - K) .* K_; 386 | Y = (A(:,:,3) - K) .* K_; 387 | A = uint8(cat(3, C, M, Y, K)); 388 | clear C M Y K K_ 389 | end 390 | append_mode = {'overwrite', 'append'}; 391 | imwrite(A, [options.name '.tif'], 'Resolution', options.magnify*get(0, 'ScreenPixelsPerInch'), 'WriteMode', append_mode{options.append+1}); 392 | end 393 | end 394 | % Now do the vector formats 395 | if isvector(options) 396 | % Set the default renderer to painters 397 | if ~options.renderer 398 | renderer = '-painters'; 399 | end 400 | % Generate some filenames 401 | tmp_nam = [tempname '.eps']; 402 | if options.pdf 403 | pdf_nam = [options.name '.pdf']; 404 | else 405 | pdf_nam = [tempname '.pdf']; 406 | end 407 | % Generate the options for print 408 | p2eArgs = {renderer}; 409 | if options.colourspace == 1 410 | p2eArgs = [p2eArgs {'-cmyk'}]; 411 | end 412 | if ~options.crop 413 | p2eArgs = [p2eArgs {'-loose'}]; 414 | end 415 | try 416 | % Generate an eps 417 | print2eps(tmp_nam, fig, p2eArgs{:}); 418 | % Remove the background, if desired 419 | if options.transparent && ~isequal(get(fig, 'Color'), 'none') 420 | eps_remove_background(tmp_nam); 421 | end 422 | % Add a bookmark to the PDF if desired 423 | if options.bookmark 424 | fig_nam = get(fig, 'Name'); 425 | if isempty(fig_nam) 426 | warning('export_fig:EmptyBookmark', 'Bookmark requested for figure with no name. Bookmark will be empty.'); 427 | end 428 | add_bookmark(tmp_nam, fig_nam); 429 | end 430 | % Generate a pdf 431 | eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality); 432 | catch ex 433 | % Delete the eps 434 | delete(tmp_nam); 435 | rethrow(ex); 436 | end 437 | % Delete the eps 438 | delete(tmp_nam); 439 | if options.eps 440 | try 441 | % Generate an eps from the pdf 442 | pdf2eps(pdf_nam, [options.name '.eps']); 443 | catch ex 444 | if ~options.pdf 445 | % Delete the pdf 446 | delete(pdf_nam); 447 | end 448 | rethrow(ex); 449 | end 450 | if ~options.pdf 451 | % Delete the pdf 452 | delete(pdf_nam); 453 | end 454 | end 455 | end 456 | if cls 457 | % Close the created figure 458 | close(fig); 459 | else 460 | % Reset the hardcopy mode 461 | set(fig, 'InvertHardcopy', old_mode); 462 | % Reset the axes limit and tick modes 463 | for a = 1:numel(Hlims) 464 | set(Hlims(a), 'XLimMode', Xlims{a}, 'YLimMode', Ylims{a}, 'ZLimMode', Zlims{a}, 'XTickMode', Xtick{a}, 'YTickMode', Ytick{a}, 'ZTickMode', Ztick{a}); 465 | end 466 | end 467 | return 468 | 469 | function [fig, options] = parse_args(nout, varargin) 470 | % Parse the input arguments 471 | % Set the defaults 472 | fig = get(0, 'CurrentFigure'); 473 | options = struct('name', 'export_fig_out', ... 474 | 'crop', true, ... 475 | 'transparent', false, ... 476 | 'renderer', 0, ... % 0: default, 1: OpenGL, 2: ZBuffer, 3: Painters 477 | 'pdf', false, ... 478 | 'eps', false, ... 479 | 'png', false, ... 480 | 'tif', false, ... 481 | 'jpg', false, ... 482 | 'bmp', false, ... 483 | 'colourspace', 0, ... % 0: RGB/gray, 1: CMYK, 2: gray 484 | 'append', false, ... 485 | 'im', nout == 1, ... 486 | 'alpha', nout == 2, ... 487 | 'aa_factor', 3, ... 488 | 'magnify', 1, ... 489 | 'bookmark', false, ... 490 | 'quality', []); 491 | native = false; % Set resolution to native of an image 492 | 493 | % Go through the other arguments 494 | for a = 1:nargin-1 495 | if all(ishandle(varargin{a})) 496 | fig = varargin{a}; 497 | elseif ischar(varargin{a}) && ~isempty(varargin{a}) 498 | if varargin{a}(1) == '-' 499 | switch lower(varargin{a}(2:end)) 500 | case 'nocrop' 501 | options.crop = false; 502 | case {'trans', 'transparent'} 503 | options.transparent = true; 504 | case 'opengl' 505 | options.renderer = 1; 506 | case 'zbuffer' 507 | options.renderer = 2; 508 | case 'painters' 509 | options.renderer = 3; 510 | case 'pdf' 511 | options.pdf = true; 512 | case 'eps' 513 | options.eps = true; 514 | case 'png' 515 | options.png = true; 516 | case {'tif', 'tiff'} 517 | options.tif = true; 518 | case {'jpg', 'jpeg'} 519 | options.jpg = true; 520 | case 'bmp' 521 | options.bmp = true; 522 | case 'rgb' 523 | options.colourspace = 0; 524 | case 'cmyk' 525 | options.colourspace = 1; 526 | case {'gray', 'grey'} 527 | options.colourspace = 2; 528 | case {'a1', 'a2', 'a3', 'a4'} 529 | options.aa_factor = str2double(varargin{a}(3)); 530 | case 'append' 531 | options.append = true; 532 | case 'bookmark' 533 | options.bookmark = true; 534 | case 'native' 535 | native = true; 536 | otherwise 537 | val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match')); 538 | if ~isscalar(val) 539 | error('option %s not recognised', varargin{a}); 540 | end 541 | switch lower(varargin{a}(2)) 542 | case 'm' 543 | options.magnify = val; 544 | case 'r' 545 | options.magnify = val ./ get(0, 'ScreenPixelsPerInch'); 546 | case 'q' 547 | options.quality = max(val, 0); 548 | end 549 | end 550 | else 551 | [p, options.name, ext] = fileparts(varargin{a}); 552 | if ~isempty(p) 553 | options.name = [p filesep options.name]; 554 | end 555 | switch lower(ext) 556 | case {'.tif', '.tiff'} 557 | options.tif = true; 558 | case {'.jpg', '.jpeg'} 559 | options.jpg = true; 560 | case '.png' 561 | options.png = true; 562 | case '.bmp' 563 | options.bmp = true; 564 | case '.eps' 565 | options.eps = true; 566 | case '.pdf' 567 | options.pdf = true; 568 | otherwise 569 | options.name = varargin{a}; 570 | end 571 | end 572 | end 573 | end 574 | 575 | % Check we have a figure handle 576 | if isempty(fig) 577 | error('No figure found'); 578 | end 579 | 580 | % Set the default format 581 | if ~isvector(options) && ~isbitmap(options) 582 | options.png = true; 583 | end 584 | 585 | % Check whether transparent background is wanted (old way) 586 | if isequal(get(ancestor(fig, 'figure'), 'Color'), 'none') 587 | options.transparent = true; 588 | end 589 | 590 | % If requested, set the resolution to the native vertical resolution of the 591 | % first suitable image found 592 | if native && isbitmap(options) 593 | % Find a suitable image 594 | list = findobj(fig, 'Type', 'image', 'Tag', 'export_fig_native'); 595 | if isempty(list) 596 | list = findobj(fig, 'Type', 'image', 'Visible', 'on'); 597 | end 598 | for hIm = list(:)' 599 | % Check height is >= 2 600 | height = size(get(hIm, 'CData'), 1); 601 | if height < 2 602 | continue 603 | end 604 | % Account for the image filling only part of the axes, or vice 605 | % versa 606 | yl = get(hIm, 'YData'); 607 | if isscalar(yl) 608 | yl = [yl(1)-0.5 yl(1)+height+0.5]; 609 | else 610 | if ~diff(yl) 611 | continue 612 | end 613 | yl = yl + [-0.5 0.5] * (diff(yl) / (height - 1)); 614 | end 615 | hAx = get(hIm, 'Parent'); 616 | yl2 = get(hAx, 'YLim'); 617 | % Find the pixel height of the axes 618 | oldUnits = get(hAx, 'Units'); 619 | set(hAx, 'Units', 'pixels'); 620 | pos = get(hAx, 'Position'); 621 | set(hAx, 'Units', oldUnits); 622 | if ~pos(4) 623 | continue 624 | end 625 | % Found a suitable image 626 | % Account for stretch-to-fill being disabled 627 | pbar = get(hAx, 'PlotBoxAspectRatio'); 628 | pos = min(pos(4), pbar(2)*pos(3)/pbar(1)); 629 | % Set the magnification to give native resolution 630 | options.magnify = (height * diff(yl2)) / (pos * diff(yl)); 631 | break 632 | end 633 | end 634 | return 635 | 636 | function A = downsize(A, factor) 637 | % Downsample an image 638 | if factor == 1 639 | % Nothing to do 640 | return 641 | end 642 | try 643 | % Faster, but requires image processing toolbox 644 | A = imresize(A, 1/factor, 'bilinear'); 645 | catch 646 | % No image processing toolbox - resize manually 647 | % Lowpass filter - use Gaussian as is separable, so faster 648 | % Compute the 1d Gaussian filter 649 | filt = (-factor-1:factor+1) / (factor * 0.6); 650 | filt = exp(-filt .* filt); 651 | % Normalize the filter 652 | filt = single(filt / sum(filt)); 653 | % Filter the image 654 | padding = floor(numel(filt) / 2); 655 | for a = 1:size(A, 3) 656 | A(:,:,a) = conv2(filt, filt', single(A([ones(1, padding) 1:end repmat(end, 1, padding)],[ones(1, padding) 1:end repmat(end, 1, padding)],a)), 'valid'); 657 | end 658 | % Subsample 659 | A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:); 660 | end 661 | return 662 | 663 | function A = rgb2grey(A) 664 | A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A)); 665 | return 666 | 667 | function A = check_greyscale(A) 668 | % Check if the image is greyscale 669 | if size(A, 3) == 3 && ... 670 | all(reshape(A(:,:,1) == A(:,:,2), [], 1)) && ... 671 | all(reshape(A(:,:,2) == A(:,:,3), [], 1)) 672 | A = A(:,:,1); % Save only one channel for 8-bit output 673 | end 674 | return 675 | 676 | function [A, v] = crop_background(A, bcol) 677 | % Map the foreground pixels 678 | [h, w, c] = size(A); 679 | if isscalar(bcol) && c > 1 680 | bcol = bcol(ones(1, c)); 681 | end 682 | bail = false; 683 | for l = 1:w 684 | for a = 1:c 685 | if ~all(A(:,l,a) == bcol(a)) 686 | bail = true; 687 | break; 688 | end 689 | end 690 | if bail 691 | break; 692 | end 693 | end 694 | bail = false; 695 | for r = w:-1:l 696 | for a = 1:c 697 | if ~all(A(:,r,a) == bcol(a)) 698 | bail = true; 699 | break; 700 | end 701 | end 702 | if bail 703 | break; 704 | end 705 | end 706 | bail = false; 707 | for t = 1:h 708 | for a = 1:c 709 | if ~all(A(t,:,a) == bcol(a)) 710 | bail = true; 711 | break; 712 | end 713 | end 714 | if bail 715 | break; 716 | end 717 | end 718 | bail = false; 719 | for b = h:-1:t 720 | for a = 1:c 721 | if ~all(A(b,:,a) == bcol(a)) 722 | bail = true; 723 | break; 724 | end 725 | end 726 | if bail 727 | break; 728 | end 729 | end 730 | % Crop the background, leaving one boundary pixel to avoid bleeding on 731 | % resize 732 | v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)]; 733 | A = A(v(1):v(2),v(3):v(4),:); 734 | return 735 | 736 | function eps_remove_background(fname) 737 | % Remove the background of an eps file 738 | % Open the file 739 | fh = fopen(fname, 'r+'); 740 | if fh == -1 741 | error('Not able to open file %s.', fname); 742 | end 743 | % Read the file line by line 744 | while true 745 | % Get the next line 746 | l = fgets(fh); 747 | if isequal(l, -1) 748 | break; % Quit, no rectangle found 749 | end 750 | % Check if the line contains the background rectangle 751 | if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1) 752 | % Set the line to whitespace and quit 753 | l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' '; 754 | fseek(fh, -numel(l), 0); 755 | fprintf(fh, l); 756 | break; 757 | end 758 | end 759 | % Close the file 760 | fclose(fh); 761 | return 762 | 763 | function b = isvector(options) 764 | b = options.pdf || options.eps; 765 | return 766 | 767 | function b = isbitmap(options) 768 | b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha; 769 | return 770 | 771 | % Helper function 772 | function A = make_cell(A) 773 | if ~iscell(A) 774 | A = {A}; 775 | end 776 | return 777 | 778 | function add_bookmark(fname, bookmark_text) 779 | % Adds a bookmark to the temporary EPS file after %%EndPageSetup 780 | % Read in the file 781 | fh = fopen(fname, 'r'); 782 | if fh == -1 783 | error('File %s not found.', fname); 784 | end 785 | try 786 | fstrm = fread(fh, '*char')'; 787 | catch ex 788 | fclose(fh); 789 | rethrow(ex); 790 | end 791 | fclose(fh); 792 | 793 | % Include standard pdfmark prolog to maximize compatibility 794 | fstrm = strrep(fstrm, '%%BeginProlog', sprintf('%%%%BeginProlog\n/pdfmark where {pop} {userdict /pdfmark /cleartomark load put} ifelse')); 795 | % Add page bookmark 796 | fstrm = strrep(fstrm, '%%EndPageSetup', sprintf('%%%%EndPageSetup\n[ /Title (%s) /OUT pdfmark',bookmark_text)); 797 | 798 | % Write out the updated file 799 | fh = fopen(fname, 'w'); 800 | if fh == -1 801 | error('Unable to open %s for writing.', fname); 802 | end 803 | try 804 | fwrite(fh, fstrm, 'char*1'); 805 | catch ex 806 | fclose(fh); 807 | rethrow(ex); 808 | end 809 | fclose(fh); 810 | return -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------