├── discretization.pdf ├── Subroutines ├── GaussHermite.m ├── fclencurt.m ├── allcomb2.m └── legpts.m ├── Discretize VAR ├── unitaryConstraint.m ├── test_discreteAR.m ├── minVarTrace.m ├── polynomialMoment.m ├── test_discreteVAR.m ├── discreteAR.m └── discreteVAR.m ├── Discretize SV ├── test_discreteSV.m └── discreteSV.m ├── README.md ├── Nonparametric Gaussian quadrature ├── test_NPGQ.m └── NPGQ.m ├── Discretize Gaussian mixture AR ├── test_discreteGMAR.m ├── GaussianMixtureQuadrature.m └── discreteGMAR.m ├── Discretize CIR ├── CIRpdf.m ├── test_discreteCIR.m └── discreteCIR.m ├── Discretize nonparametric distribution ├── test_discreteNP.m └── discreteNP.m ├── Core functionalities ├── entropyObjective.m └── discreteApproximation.m └── LICENSE /discretization.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexisakira/discretization/HEAD/discretization.pdf -------------------------------------------------------------------------------- /Subroutines/GaussHermite.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexisakira/discretization/HEAD/Subroutines/GaussHermite.m -------------------------------------------------------------------------------- /Discretize VAR/unitaryConstraint.m: -------------------------------------------------------------------------------- 1 | function [c,ceq] = unitaryConstraint(X) 2 | 3 | c = []; 4 | ceq = X'*X-eye(size(X,2)); 5 | 6 | end 7 | 8 | -------------------------------------------------------------------------------- /Discretize VAR/test_discreteAR.m: -------------------------------------------------------------------------------- 1 | mu = 0; 2 | rho = 0.9; 3 | sigma = 0.1; 4 | nMoments = 4; 5 | Nm = 9; 6 | 7 | tic 8 | [P,X] = discreteAR(mu,rho,sigma,Nm,'even',nMoments); 9 | toc -------------------------------------------------------------------------------- /Discretize SV/test_discreteSV.m: -------------------------------------------------------------------------------- 1 | %% Stochastic volatility - example in Appendix B.2 of Farmer & Toda (2017) 2 | 3 | lambda = 0.95; 4 | rho = 0.9; 5 | sigmaU = 0.007; 6 | sigmaE = 0.06; 7 | Ny = 9; 8 | Nx = 5; 9 | 10 | tic 11 | [P,yxGrids] = discreteSV(lambda,rho,sigmaU,sigmaE,Ny,Nx); 12 | toc -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # discretization 2 | Matlab codes for discretizing non-Gaussian Markov processes 3 | based on "Discretizing Nonlinear, Non-Gaussian Markov Processes with Exact Conditional Moments", Quantitative Economics 8(2):651-683 (2017) 4 | https://doi.org/10.3982/QE737 5 | by Leland E. Farmer & Alexis Akira Toda 6 | 7 | Please read "discretization.pdf" for details. 8 | -------------------------------------------------------------------------------- /Nonparametric Gaussian quadrature/test_NPGQ.m: -------------------------------------------------------------------------------- 1 | I = 10000; % sample size 2 | 3 | mu = 0; 4 | sigma = 0.2; 5 | alpha = 2; 6 | beta = 1; 7 | U = rand(I,1); % uniform random variable 8 | Normal = normrnd(mu,sigma,[I,1]); % normal random variable 9 | p = alpha/(alpha+beta); 10 | Laplace = (U <= p).*exprnd(1/alpha,[I,1]) - (U > p).*exprnd(1/beta,[I,1]); % Laplace random variable 11 | data = Normal + Laplace; % normal-Laplace random variable 12 | 13 | histogram(data); 14 | 15 | N = 9; % number of grid points 16 | 17 | tic 18 | [x,w] = NPGQ(data,N); 19 | toc -------------------------------------------------------------------------------- /Discretize VAR/minVarTrace.m: -------------------------------------------------------------------------------- 1 | function [U,fval] = minVarTrace(A) 2 | % find a unitary matrix U such that the diagonal components of U'*AU is as 3 | % close to a multiple of identity matrix as possible 4 | warning off 5 | 6 | [s1,s2] = size(A); 7 | if s1 ~= s2 8 | error('input matrix must be square') 9 | end 10 | 11 | K = s1; % size of A 12 | d = trace(A)/K; % diagonal of U'*A*U should be closest to d 13 | obj =@(X)(norm(diag(X'*A*X)-d)); 14 | options = optimoptions(@fmincon,'Display','off'); 15 | [U,fval] = fmincon(obj,eye(K),[],[],[],[],[],[],@unitaryConstraint,options); 16 | 17 | warning on 18 | 19 | end 20 | 21 | -------------------------------------------------------------------------------- /Discretize VAR/polynomialMoment.m: -------------------------------------------------------------------------------- 1 | function T = polynomialMoment(X,mu,scalingFactor,nMoments) 2 | 3 | % Purpose: 4 | % Compute the moment defining function used in discreteApproximation 5 | % 6 | % Usage: 7 | % T = polynomialMoment(X,mu,scalingFactor,nMoment) 8 | % 9 | % Inputs: 10 | % X - (1 x N) vector of grid points 11 | % mu - location parameter (conditional mean) 12 | % scalingFactor - scaling factor for numerical stability (typically largest grid point) 13 | % nMoments - number of polynomial moments 14 | 15 | % Check that scaling factor is positive 16 | if isnan(scalingFactor) || (scalingFactor <= 0) 17 | error('sF must be a positive number') 18 | end 19 | 20 | Y = (X-mu)/scalingFactor; % standardized grid 21 | T = bsxfun(@power,Y,[1:nMoments]'); 22 | 23 | end 24 | 25 | -------------------------------------------------------------------------------- /Discretize Gaussian mixture AR/test_discreteGMAR.m: -------------------------------------------------------------------------------- 1 | Nm = 9; % number of points for discretization 2 | 3 | mu = 0.0555; 4 | A1 = 0.5854; 5 | A2 = [0.8959 -0.3990]; 6 | pC = [0.1628 0.8372]; 7 | muC = [-0.0039 0.0008]; 8 | sigmaC = [0.1293 0.0300]; 9 | 10 | nMoments = 2; 11 | tic 12 | [PEven1,XEven1] = discreteGMAR(mu,A1,pC,muC,sigmaC,Nm,nMoments,'even'); 13 | toc 14 | tic 15 | [PEven2,XEven2] = discreteGMAR(mu,A2,pC,muC,sigmaC,Nm,nMoments,'even'); 16 | toc 17 | 18 | tic 19 | [PGMQ1,XGMQ1] = discreteGMAR(mu,A1,pC,muC,sigmaC,Nm,nMoments,'GMQ'); 20 | toc 21 | tic 22 | [PGMQ2,XGMQ2] = discreteGMAR(mu,A2,pC,muC,sigmaC,Nm,nMoments,'GMQ'); 23 | toc 24 | 25 | [v,~] = eigs(PEven1',1,1); 26 | pi = v/sum(v); % stationary distribution 27 | 28 | figure 29 | plot(XEven1,pi) 30 | xlabel('x') 31 | ylabel('Stationary distribution') -------------------------------------------------------------------------------- /Discretize VAR/test_discreteVAR.m: -------------------------------------------------------------------------------- 1 | %% Gaussian AR(1) 2 | 3 | % Parameter initialization 4 | 5 | rho = 0.99; % persistence 6 | N = 9; % # of grid points 7 | nMoments = 2; % # of moments to match 8 | sigma2 = 0.1; % conditional variance 9 | 10 | tic 11 | [P1,D1] = discreteVAR(0,rho,sigma2,N,nMoments,'even'); 12 | % 'method' can be 'even', 'quantile', or 'quadrature'. 'quantile' is not 13 | % recommended. 14 | toc 15 | 16 | %% Gaussian 2-D VAR(1) - example in Appendix B.1 17 | 18 | % Set parameters 19 | 20 | A = [0.9809 0.0028; 0.0410 0.9648]; % lag matrix 21 | Sigma = [0.0087^2 0; 0 0.0262^2]; % conditional covariance matrix 22 | N = 9; % # of grid points 23 | nMoments = 2; % # of moments to match 24 | 25 | % Discretize VAR 26 | 27 | tic 28 | [P2,D2] = discreteVAR(zeros(2,1),A,Sigma,N,nMoments,'even'); 29 | toc -------------------------------------------------------------------------------- /Discretize CIR/CIRpdf.m: -------------------------------------------------------------------------------- 1 | function Out = CIRpdf(x,r,a,b,sigma,Delta) 2 | % transition probability density of Cox-Ingersoll-Ross model 3 | % x: vector of future interest rates 4 | % r: current interest rate 5 | % a, b, sigma: parameters of CIR model 6 | % Delta: time difference 7 | 8 | %% some error checking 9 | if any(x < 0) 10 | error('x must be a nonnegative vector') 11 | end 12 | if (r <= 0)||(a <= 0)||(b <= 0)||(sigma <= 0)||(Delta <= 0) 13 | error('r, a, b, sigma, Delta must be positive') 14 | end 15 | 16 | if 2*a*b - sigma^2 <= 0 17 | error('It must be sigma^2 < 2*a*b') 18 | end 19 | 20 | %% define parameters 21 | 22 | c = (2*a)/((1-exp(-a*Delta))*sigma^2); 23 | q = 2*a*b/sigma^2 - 1; 24 | u = c*r*exp(-a*Delta); 25 | v = c*x; 26 | 27 | %% compute density 28 | 29 | Z = 2*sqrt(u*v); 30 | Out = c*exp(-u-v).*(v/u).^(q/2).*besseli(q,Z); 31 | 32 | end 33 | 34 | -------------------------------------------------------------------------------- /Discretize nonparametric distribution/test_discreteNP.m: -------------------------------------------------------------------------------- 1 | %% figure formatting 2 | 3 | set(0,'DefaultTextInterpreter','latex') 4 | set(0,'DefaultAxesTickLabelInterpreter','latex'); 5 | set(0,'DefaultLegendInterpreter', 'latex') 6 | 7 | set(0,'DefaultTextFontSize', 14) 8 | set(0,'DefaultAxesFontSize', 14) 9 | set(0,'DefaultLineLineWidth',1) 10 | 11 | temp = get(gca,'ColorOrder'); 12 | c1 = temp(1,:); 13 | c2 = temp(2,:); 14 | clear temp 15 | close all 16 | 17 | 18 | N = 9; % number of grid points 19 | cMoments1 = [0, 1, 0, 3]; % Gaussian 20 | cMoments2 = [0, 1, 0, 5]; % some example 21 | 22 | tic 23 | [x1,p1] = discreteNP(N,cMoments1); 24 | [x2,p2] = discreteNP(N,cMoments2); 25 | toc 26 | 27 | figure 28 | plot(x1,p1); hold on 29 | plot(x2,p2) 30 | xlabel('$x$') 31 | ylabel('Probability mass') 32 | legend(['$E[X^4]=$' num2str(cMoments1(end))], ['$E[X^4]=$' num2str(cMoments2(end))]) -------------------------------------------------------------------------------- /Subroutines/fclencurt.m: -------------------------------------------------------------------------------- 1 | function [x,w]=fclencurt(N1,a,b) 2 | 3 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | % 5 | % fclencurt.m - Fast Clenshaw Curtis Quadrature 6 | % 7 | % Compute the N nodes and weights for Clenshaw-Curtis 8 | % Quadrature on the interval [a,b]. Unlike Gauss 9 | % quadratures, Clenshaw-Curtis is only exact for 10 | % polynomials up to order N, however, using the FFT 11 | % algorithm, the weights and nodes are computed in linear 12 | % time. This script will calculate for N=2^20+1 (1048577 13 | % points) in about 5 seconds on a normal laptop computer. 14 | % 15 | % Written by: Greg von Winckel - 02/12/2005 16 | % Contact: gregvw(at)chtm(dot)unm(dot)edu 17 | % 18 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 19 | 20 | N=N1-1; bma=b-a; 21 | c=zeros(N1,2); 22 | c(1:2:N1,1)=(2./[1 1-(2:2:N).^2 ])'; c(2,2)=1; 23 | f=real(ifft([c(1:N1,:);c(N:-1:2,:)])); 24 | w=bma*([f(1,1); 2*f(2:N,1); f(N1,1)])/2; 25 | x=0.5*((b+a)+N*bma*f(1:N1,2)); 26 | -------------------------------------------------------------------------------- /Discretize CIR/test_discreteCIR.m: -------------------------------------------------------------------------------- 1 | clear 2 | close all 3 | clc; 4 | 5 | % just pick some numbers 6 | b = 4*0.007; 7 | a = -log(0.58); 8 | sigma = 0.1; 9 | 10 | r = 0.04; 11 | Delta = 1/4; 12 | x = linspace(0,0.1,101); 13 | temp = CIRpdf(x,r,a,b,sigma,Delta); 14 | 15 | figure 16 | plot(x,CIRpdf(x,r,a,b,sigma,Delta)); 17 | 18 | N = 9; 19 | Coverage = 0.995; % coverage rate of the grid (optional) 20 | %method = 'even'; 21 | method = 'exponential'; % grid choice (optional) 22 | 23 | tic 24 | [P,X] = discreteCIR(a,b,sigma,Delta,N,Coverage,method); 25 | toc 26 | 27 | if strcmp(method,'even') 28 | h = X(2) - X(1); 29 | dX = ones(size(X))/h; 30 | elseif strcmp(method,'exponential') 31 | h = log(X(2)) - log(X(1)); % grid spacing in log 32 | dX = 1./(h*X); 33 | end 34 | 35 | figure 36 | plot(X,P(floor(N/4),:).*dX,X,P(floor(N/2),:).*dX,X,P(ceil(3*N/4),:).*dX) 37 | title('Transition probabilities (density scale)') 38 | 39 | [v,~] = eigs(P',1,1); 40 | pi = v'/sum(v); % stationary distribution 41 | 42 | figure 43 | plot(X,pi.*dX) 44 | title('Stationary distribution (density scale)') -------------------------------------------------------------------------------- /Discretize nonparametric distribution/discreteNP.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % discreteNP 3 | % (c) 2023 Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % discretize a nonparametric distribution given centered moments 7 | % Usage: 8 | % [x,p] = discreteNP(N,cMoments,q) 9 | % 10 | % Inputs: 11 | % N - number of grid points 12 | % cMoments - vector of centered moments 13 | % q - vector of initial probability (optional) 14 | % 15 | % Outputs: 16 | % x - grid points 17 | % p - probability 18 | % 19 | % Version 1.0: September 27, 2023 20 | % 21 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 22 | 23 | function [x,p] = discreteNP(N,cMoments,q) 24 | 25 | % some error checking 26 | L = length(cMoments); % number of moments to be matched 27 | if L < 2 28 | error('You need to provide at least two moments') 29 | end 30 | if L > N+1 31 | error('There are not enough points to match moments') 32 | end 33 | if cMoments(1) ~= 0 34 | error('Moments must be centered') 35 | end 36 | if cMoments(2) <= 0 37 | error('Second moment must be positive') 38 | end 39 | sigma = sqrt(cMoments(2)); % standard deviation 40 | x = linspace(-sigma*sqrt(2*N),sigma*sqrt(2*N),N); % grid points 41 | % using sqrt(2*N) times standard deviation recommended by Farmer-Toda 42 | 43 | if nargin < 3 44 | q = normpdf(x,0,sigma); 45 | q = q/sum(q); % if initial prior not provided, use Gaussian 46 | end 47 | if length(q) ~= N 48 | error('Length of q must equal N') 49 | end 50 | if size(cMoments,1) < size(cMoments,2) 51 | cMoments = cMoments'; % convert to column vector 52 | end 53 | 54 | T = @(x)bsxfun(@power,x,[1:L]'); % moment defining function 55 | p = discreteApproximation(x,T,cMoments,q); 56 | 57 | end -------------------------------------------------------------------------------- /Core functionalities/entropyObjective.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % entropyObjective 3 | % (c) 2016 Leland E. Farmer and Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Compute the maximum entropy objective function used in 7 | % discreteApproximation 8 | % 9 | % Usage: 10 | % obj = entropyObjective(lambda,Tx,TBar,q) 11 | % 12 | % Inputs: 13 | % lambda - (L x 1) vector of values of the dual problem variables 14 | % Tx - (L x N) matrix of moments evaluated at the grid points 15 | % specified in discreteApproximation 16 | % TBar - (L x 1) vector of moments of the underlying distribution 17 | % which should be matched 18 | % q - (1 X N) vector of prior weights for each point in the grid. 19 | % 20 | % Outputs: 21 | % obj - scalar value of objective function evaluated at lambda 22 | % Optional (useful for optimization routines): 23 | % gradObj - (L x 1) gradient vector of the objective function evaluated 24 | % at lambda 25 | % hessianObj- (L x L) hessian matrix of the objective function evaluated at 26 | % lambda 27 | % 28 | % Version 1.2: June 7, 2016 29 | % 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 31 | 32 | function [obj,gradObj,hessianObj] = entropyObjective(lambda,Tx,TBar,q) 33 | 34 | % Some error checking 35 | 36 | if nargin < 4 37 | error('You must provide 4 arguments to entropyObjective.') 38 | end 39 | 40 | [L,N] = size(Tx); 41 | 42 | if length(lambda) ~= L || length(TBar) ~= L || length(q) ~= N 43 | error('Dimensions of inputs are not compatible.') 44 | end 45 | 46 | % Compute objective function 47 | 48 | Tdiff = Tx-repmat(TBar,1,N); 49 | temp = q.*exp(lambda'*Tdiff); 50 | obj = sum(temp); 51 | 52 | % Compute gradient of objective function 53 | 54 | if nargout > 1 55 | temp2 = bsxfun(@times,temp,Tdiff); 56 | gradObj = sum(temp2,2); 57 | end 58 | 59 | % Compute hessian of objective function 60 | 61 | if nargout > 2 62 | hessianObj = temp2*Tdiff'; 63 | end 64 | 65 | end -------------------------------------------------------------------------------- /Nonparametric Gaussian quadrature/NPGQ.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % NPGQ 3 | % (c) 2019 Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Discretize a nonparametric distribution directly from data 7 | % 8 | % Usage: 9 | % [x,w] = NPGQ(data,N) 10 | % 11 | % Inputs: 12 | % - data: data (one dimensional). Because sufficiently high-order 13 | % moments need to exist, if you know data is positive, take the 14 | % logarithm before feeding in. Afterwards you can recover the grid by 15 | % computing exp(x) instead of x. 16 | % - N: number of grid points 17 | % 18 | % Outputs: 19 | % - x: nodes of nonparametric Gaussian quadrature 20 | % - w: weights (probability) of nonparametric Gaussian quadrature 21 | % 22 | % Version 1.1: May 27, 2019 23 | % 24 | function [x,w] = NPGQ(data,N) 25 | 26 | %% standardize data for numerical stability 27 | I = length(data); 28 | if I <= 1 29 | error('sample size must exceed 1') 30 | end 31 | 32 | if all(data > 0) 33 | warning('Your data is positive and may not have sufficiently high moments. Consider using log(data) instead of data') 34 | end 35 | 36 | mu = sum(data)/I; % sample mean 37 | sigma = sqrt(sum((data-mu).^2)/I); % sample standard deviation 38 | 39 | z = (data-mu)/sigma; % standardize data for numerical stability 40 | 41 | if size(z,1) > size(z,2) 42 | z = z'; % convert to row vector 43 | end 44 | 45 | %% Precompute polynomial moments of Gaussian mixture 46 | temp = bsxfun(@power,z,[0:2*N]'); % matrix that stores powers of data 47 | PolyMoments = sum(temp,2)/I; % column vector of polynomial moments 48 | 49 | %% Implement Golub-Welsch algorithm 50 | M = zeros(N+1); % matrix of moments 51 | for n = 1:N+1 52 | M(n,:) = PolyMoments(n:N+n); 53 | end 54 | R = chol(M); % Cholesky factorization 55 | temp0 = diag(R); 56 | temp0(end) = []; 57 | beta = temp0(2:N)./temp0(1:N-1); 58 | temp1 = diag(R,1); 59 | temp2 = temp1./temp0; 60 | alpha = temp2 - [0;temp2(1:N-1)]; 61 | 62 | T = diag(alpha) + diag(beta,-1) + diag(beta,1); 63 | [V,D] = eig(T); 64 | 65 | %% Compute nodes and weights of Gaussian quadrature 66 | x = diag(D)'; 67 | [x,ind] = sort(x); % sort nodes in ascending order 68 | 69 | w = zeros(1,N); 70 | for n = 1:N 71 | v = V(:,n); 72 | w(n) = v(1)^2/dot(v,v); 73 | end 74 | w = w(ind); 75 | 76 | %% convert back to original scale 77 | x = mu + sigma*x; 78 | 79 | end 80 | 81 | -------------------------------------------------------------------------------- /Discretize Gaussian mixture AR/GaussianMixtureQuadrature.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % GaussianMixtureQuadrature 3 | % (c) 2019 Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % compute the nodes and weights of Gaussian quadrature when the 7 | % weighting function is a Gaussian mixture 8 | % Usage: 9 | % [x,w] = GaussianMixtureQuadrature(Coeff, Mu, Sigma, N) 10 | % 11 | % Inputs: 12 | % Coeff - coefficients (proportions) of Gaussian mixture components 13 | % Mu - vector of means 14 | % Sigma - vector of standard deviations 15 | % N - number of nodes for Gaussian quadrature 16 | % 17 | % Outputs: 18 | % x - nodes of Gaussian quadrature 19 | % w - weights of Gaussian quadrature 20 | % 21 | % Version 1.2: May 24, 2019 22 | % 23 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 24 | 25 | function [x,w] = GaussianMixtureQuadrature(Coeff, Mu, Sigma, N) 26 | 27 | %% Some error checking 28 | if length(Coeff) ~= length(Mu) || length(Coeff) ~= length(Sigma) || length(Mu) ~= length(Sigma) 29 | error('Coeff, Mu, Sigma must be of same length'); 30 | end 31 | 32 | if size(Coeff,1) > size(Coeff,2) 33 | Coeff = Coeff'; % convert to row vector 34 | end 35 | if size(Mu,1) > size(Mu,2) 36 | Mu = Mu'; % convert to row vector 37 | end 38 | if size(Sigma,1) > size(Sigma,2) 39 | Sigma = Sigma'; % convert to row vector 40 | end 41 | 42 | %% Precompute polynomial moments of Gaussian mixture 43 | K = length(Coeff); % number of mixture components 44 | temp = zeros(2*N+1,K); % matrix that stores moments of each mixture component 45 | Sigma2 = Sigma.^2; % vector of variances 46 | temp(1,:) = 1; 47 | temp(2,:) = Mu; 48 | for n=2:2*N % n is the order of moments 49 | temp(n+1,:) = Mu.*temp(n,:) + (n-1)*Sigma2.*temp(n-1,:); 50 | end 51 | PolyMoments = temp*(Coeff'); % column vector of polynomial moments 52 | 53 | %% Implement Golub-Welsch algorithm 54 | M = zeros(N+1); % matrix of moments 55 | for n=1:N+1 56 | M(n,:) = PolyMoments(n:N+n); 57 | end 58 | R = chol(M); % Cholesky factorization 59 | temp0 = diag(R); 60 | temp0(end) = []; 61 | beta = temp0(2:N)./temp0(1:N-1); 62 | temp1 = diag(R,1); 63 | temp2 = temp1./temp0; 64 | alpha = temp2 - [0;temp2(1:N-1)]; 65 | 66 | T = diag(alpha) + diag(beta,-1) + diag(beta,1); 67 | [V,D] = eig(T); 68 | 69 | %% Compute nodes and weights of Gaussian quadrature 70 | x = diag(D)'; 71 | [x,ind] = sort(x); 72 | 73 | w = zeros(1,N); 74 | for n = 1 : N 75 | v = V(:,n); 76 | w(n) = sum(Coeff) * v(1)^2 / dot(v,v); 77 | end 78 | w = w(ind); 79 | 80 | end 81 | -------------------------------------------------------------------------------- /Discretize SV/discreteSV.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % discreteSV 3 | % (c) 2016 Leland E. Farmer and Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Discretize an AR(1) process with log AR(1) stochastic volatility 7 | % y_t = lambda*y_{t-1} + u_t 8 | % x_t = (1-rho)*mu + rho*x_{t-1} + epsilon_t 9 | % u_t ~ N(0,exp(x_t)); epsilon_t ~ N(0,sigma_e^2) 10 | % 11 | % Usage: 12 | % [P,yxGrids] = discreteSV(lambda,rho,sigmaU,sigmaE,Ny,Nx,method,nSigmaY) 13 | % 14 | % Inputs: 15 | % lambda - persistence of y process 16 | % rho - persistence of x process 17 | % sigmaU - unconditional standard deviation of u_t 18 | % sigmaE - standard deviation of epsilon_t 19 | % Ny - number of grid points for y process 20 | % Nx - number of grid points for x process 21 | % Optional: 22 | % method - quadrature method for x process (default = 'even') 23 | % nSigmaY - grid spacing parameter for y (default = sqrt((Ny-1)/2) 24 | % 25 | % Version 1.2: May 27, 2019 26 | % 27 | % - Added nSigmaY as optional input variable 28 | % - Avoided combvec function, which requires Deep Learning Toolbox 29 | % - Changed output grid name from xyGrids to yxGrids because order is y, x 30 | % - Changed kappa to 1e-8 31 | function [P,yxGrids] = discreteSV(lambda,rho,sigmaU,sigmaE,Ny,Nx,method,nSigmaY) 32 | 33 | if nargin <= 6 34 | method = 'even'; % default is evenly spaced grid 35 | end 36 | 37 | if nargin <= 7 38 | nSigmaY = sqrt((Ny-1)/2); % spacing parameter for Y process 39 | end 40 | 41 | %% Compute some uncondtional moments 42 | 43 | sigmaX = (sigmaE^2)/(1-rho^2); % unconditional variance of variance process 44 | xBar = 2*log(sigmaU)-sigmaX/2; % unconditional mean of variance process, targeted to match a mean standard deviation of sigmaU 45 | sigmaY = sqrt(exp(xBar+sigmaX/2)/(1-lambda^2)); % uncondtional standard deviation of technology shock 46 | 47 | %% Construct technology process approximation 48 | 49 | [Px,xGrid] = discreteVAR(xBar*(1-rho),rho,sigmaE^2,Nx,2,method); % discretization of variance process 50 | 51 | yGrid = linspace(-nSigmaY*sigmaY,nSigmaY*sigmaY,Ny); 52 | 53 | Nm = Nx*Ny; % total number of state variable pairs 54 | %yxGrids = flipud(combvec(xGrid,yGrid))'; 55 | temp1 = repmat(xGrid,1,Ny); 56 | temp2 = kron(yGrid,ones(1,Nx)); 57 | yxGrids = flipud([temp1; temp2])'; % avoid using combvec, which requires deep learning toolbox 58 | P = zeros(Nm); 59 | lambdaGuess = zeros(2,1); 60 | scalingFactor = max(abs(yGrid)); 61 | kappa = 1e-8; % small positive constant for numerical stability 62 | 63 | for ii = 1:Nm 64 | 65 | q = normpdf(yGrid,lambda*yxGrids(ii,1),sqrt(exp((1-rho)*xBar+rho*yxGrids(ii,2)+(sigmaE^2)/2))); 66 | if sum(q 0 67 | q(q 1e-5 72 | warning('Failed to match first 2 moments. Just matching 1.') 73 | p = discreteApproximation(yGrid,@(X) (X-lambda*yxGrids(ii,1))./scalingFactor,0,q,0); 74 | end 75 | P(ii,:) = kron(p,ones(1,Nx)); 76 | P(ii,:) = P(ii,:).*repmat(Px(mod(ii-1,Nx)+1,:),1,Ny); 77 | 78 | end 79 | yxGrids = yxGrids'; 80 | end -------------------------------------------------------------------------------- /Core functionalities/discreteApproximation.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % discreteApproximation 3 | % (c) 2016 Leland E. Farmer and Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Compute a discrete state approximation to a distribution with known 7 | % moments, using the maximum entropy procedure proposed in Tanaka and 8 | % Toda (2013) 9 | % 10 | % Usage: 11 | % [p,lambdaBar,momentError] = discreteApproximation(D,T,TBar,q,lambda0) 12 | % 13 | % Inputs: 14 | % D - (K x N) matrix of grid points. K is the dimension of the 15 | % domain. N is the number of points at which an approximation 16 | % is to be constructed. 17 | % T - A function handle which should accept arguments of dimension 18 | % (K x N) and return an (L x N) matrix of moments evaluated at 19 | % each grid point, where L is the number of moments to be 20 | % matched. 21 | % TBar - (L x 1) vector of moments of the underlying distribution 22 | % which should be matched 23 | % Optional: 24 | % q - (1 X N) vector of prior weights for each point in D. The 25 | % default is for each point to have an equal weight. 26 | % lambda0 - (L x 1) vector of initial guesses for the dual problem 27 | % variables. The default is a vector of zeros. 28 | % 29 | % Outputs: 30 | % p - (1 x N) vector of probabilties assigned to each grid point in 31 | % D. 32 | % lambdaBar - (L x 1) vector of dual problem variables which solve the 33 | % maximum entropy problem 34 | % momentError - (L x 1) vector of errors in moments (defined by moments of 35 | % discretization minus actual moments) 36 | % 37 | % Version 1.2: June 7, 2016 38 | % 39 | % Version 1.3: May 26, 2019 40 | % 41 | % Changed algorithm to 'trust-region' to use Hessian 42 | % 43 | % Version 1.4: September 27, 2023 44 | % 45 | % Changed fminunc option for Matlab 2023b 46 | % Display warning if moment error is large 47 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 48 | 49 | function [p,lambdaBar,momentError] = discreteApproximation(D,T,TBar,q,lambda0) 50 | 51 | % Input error checking 52 | 53 | if nargin < 3 54 | error('You must provide at least 3 arguments to discreteApproximation.') 55 | end 56 | 57 | N = size(D,2); 58 | 59 | Tx = T(D); 60 | L = size(Tx,1); 61 | 62 | if size(Tx,2) ~= N || length(TBar) ~= L 63 | error('Dimension mismatch') 64 | end 65 | 66 | % Set default parameters if not provided 67 | if nargin < 4 68 | q = ones(1,N)./N; % uniform distribution 69 | end 70 | if nargin < 5 71 | lambda0 = zeros(L,1); 72 | end 73 | 74 | % Compute maximum entropy discrete distribution 75 | 76 | %options = optimset('TolFun',1e-10,'TolX',1e-10,'Display','off','GradObj','on','Hessian','on'); 77 | %options = optimset('TolFun',1e-10,'TolX',1e-10,'Display','off','Algorithm','trust-region'); 78 | options = optimoptions('fminunc','TolFun',1e-10,'TolX',1e-10,'Display','off',... 79 | 'Algorithm','trust-region','SpecifyObjectiveGradient',true); 80 | 81 | % Sometimes the algorithm fails to converge if the initial guess is too far 82 | % away from the truth. If this occurs, the program tries an initial guess 83 | % of all zeros. 84 | try 85 | lambdaBar = fminunc(@(lambda) entropyObjective(lambda,Tx,TBar,q),lambda0,options); 86 | catch 87 | warning('Failed to find a solution from provided initial guess. Trying new initial guess.') 88 | lambdaBar = fminunc(@(lambda) entropyObjective(lambda,Tx,TBar,q),zeros(size(lambda0)),options); 89 | end 90 | 91 | % Compute final probability weights and moment errors 92 | [obj,gradObj] = entropyObjective(lambdaBar,Tx,TBar,q); 93 | Tdiff = Tx-repmat(TBar,1,N); 94 | p = (q.*exp(lambdaBar'*Tdiff))./obj; 95 | momentError = gradObj./obj; 96 | 97 | if norm(momentError) > 1e-5 98 | warning('Large moment error. Consider increasing number of points or expanding domain') 99 | 100 | end -------------------------------------------------------------------------------- /Discretize CIR/discreteCIR.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % discreteCIR 3 | % (c) 2019 Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Compute a finite-state Markov chain approximation to the 7 | % Cox-Ingersoll-Ross model 8 | % dr_t = a*(b-r_t)*dt + sigma*sqrt(r_t)*dW_t 9 | % 10 | % Usage: 11 | % [P,X] = discreteCIR(a,b,sigma,Delta,N,Coverage,method) 12 | % 13 | % Inputs: 14 | % a - mean reversion parameter 15 | % b - unconditional mean of interest rate 16 | % sigma - volatility parameter 17 | % Delta - length of one period; for example, if parameters a, b, sigma 18 | % are calibrated at annual frequency and you want to discretize 19 | % the model at quarterly frequency, set Delta = 1/4. 20 | % N - number of grid points 21 | % Optional: 22 | % Coverage - coverage probability of grid (default = 0.999) 23 | % method - grid specification ('even' or 'exponential' (default)) 24 | % 25 | % Outputs: 26 | % P - N x N transition probability matrix 27 | % X - 1 x N vector of grid 28 | % 29 | % Version 1.1, May 28, 2019 30 | % 31 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 32 | 33 | function [P,X] = discreteCIR(a,b,sigma,Delta,N,Coverage,method) 34 | 35 | %% some error checking 36 | % Make sure the correct number of arguments are provided 37 | if nargin < 5 38 | error('You must supply at least 5 arguments to discreteCIR') 39 | elseif nargin < 6 % Coverage not provided 40 | Coverage = 0.999; % cover 99.9% of state space 41 | elseif nargin < 7 % grid choice not provided 42 | method = 'exponential'; 43 | elseif nargin >= 7 44 | if ~strcmp(method,'even')&&~strcmp(method,'exponential') 45 | error('Method must be either even or exponential') 46 | end 47 | end 48 | 49 | if (a <= 0)||(b <= 0)||(sigma <= 0)||(Delta <= 0) 50 | error('a, b, sigma, Delta must be positive') 51 | end 52 | 53 | if 2*a*b - sigma^2 <= 0 54 | error('It must be sigma^2 < 2*a*b') 55 | end 56 | 57 | % Check that N is a valid number of grid points 58 | if ~isnumeric(N) || N < 2 || rem(N,1) ~= 0 59 | error('N must be a positive integer greater than 2') 60 | end 61 | 62 | if (Coverage <= 0)||(Coverage >= 1) 63 | error('coverage must be between 0 and 1') 64 | end 65 | 66 | %% construct the grid 67 | 68 | alpha = 2*a*b/sigma^2; 69 | beta = 2*a/sigma^2; 70 | 71 | p = [1-Coverage 1+Coverage]/2; 72 | pd = makedist('Gamma','a',alpha,'b',1/beta); 73 | quantiles = icdf(pd,p); 74 | 75 | if strcmp(method,'even') 76 | X = linspace(quantiles(1),quantiles(2),N); % evenly-spaced grid to cover coverage 77 | W = ones(size(X)); 78 | elseif strcmp(method,'exponential') 79 | X = exp(linspace(log(quantiles(1)),log(quantiles(2)),N)); % exponential grid 80 | W = X; % change of variable formula when using exponential grid 81 | end 82 | W = W/sum(W); % normalization (not necessary; just in case for numerical stability) 83 | 84 | P = NaN(N); 85 | scalingFactor = max(abs(X)); 86 | ea = exp(-a*Delta); % constant used in following calculation 87 | 88 | for ii = 1:N 89 | r = X(ii); % current interest rate 90 | condMean = r*ea + b*(1-ea); % conditional mean 91 | condVar = (sigma^2/a)*(1 - ea)*(r*ea + b/2); % conditional variance 92 | TBar = [0 condVar]'; % conditional first and second moments (centered) 93 | q = W.*CIRpdf(X,r,a,b,sigma,Delta); % weighted conditional pdf (prior) 94 | % do maximum entropy discretization 95 | [p,~,momentError] = discreteApproximation(X,@(x) [(x-condMean)./scalingFactor;... 96 | ((x-condMean)./scalingFactor).^2],TBar./(scalingFactor.^(1:2)'),q,zeros(2,1)); 97 | if norm(momentError) > 1e-5 % if 2 moments fail, then just match 1 moment 98 | warning('Failed to match first 2 moments. Just matching 1.') 99 | P(ii,:) = discreteApproximation(X,@(x)(x-condMean)/scalingFactor,0,q,0); 100 | else 101 | P(ii,:) = p; 102 | end 103 | end 104 | 105 | end -------------------------------------------------------------------------------- /Discretize VAR/discreteAR.m: -------------------------------------------------------------------------------- 1 | function [P,X] = discreteAR(mu,rho,sigma,Nm,method,nMoments,nSigmas) 2 | 3 | % discretize AR(1) process with Gaussian shocks and various grids 4 | % no need to use this because it is a special case of discreteGMAR.m 5 | 6 | % define conditional central moments 7 | T1 = 0; 8 | T2 = sigma^2; 9 | T3 = 0; 10 | T4 = 3*sigma^4; 11 | 12 | TBar = [T1 T2 T3 T4]'; % vector of conditional central moments 13 | 14 | % Default number of moments to match is 2 15 | if nargin == 4 16 | nMoments = 2; 17 | end 18 | 19 | % define grid spacing parameter if not provided 20 | if nargin < 7 21 | if abs(rho) <= 1-2/(Nm-1) 22 | nSigmas = sqrt(2*(Nm-1)); 23 | else 24 | nSigmas = sqrt(Nm-1); 25 | end 26 | end 27 | 28 | % Check that Nm is a valid number of grid points 29 | if ~isnumeric(Nm) || Nm < 3 || rem(Nm,1) ~= 0 30 | error('Nm must be a positive integer greater than 3') 31 | end 32 | 33 | % Check that nMoments is a valid number 34 | if ~isnumeric(nMoments) || nMoments < 1 || nMoments > 4 || ~((rem(nMoments,1) == 0) || (nMoments == 1)) 35 | error('nMoments must be either 1, 2, 3, 4') 36 | end 37 | 38 | sigmaX = sigma/sqrt(1-rho^2); % unconditional standard deviation 39 | 40 | switch method 41 | case 'even' 42 | X = linspace(mu-nSigmas*sigmaX,mu+nSigmas*sigmaX,Nm); 43 | W = ones(1,Nm); 44 | case 'gauss-legendre' 45 | [X,W] = legpts(Nm,[mu-nSigmas*sigmaX,mu+nSigmas*sigmaX]); 46 | X = X'; 47 | case 'clenshaw-curtis' 48 | [X,W] = fclencurt(Nm,mu-nSigmas*sigmaX,mu+nSigmas*sigmaX); 49 | X = fliplr(X'); 50 | W = fliplr(W'); 51 | case 'gauss-hermite' 52 | [X,W] = GaussHermite(Nm); 53 | X = mu+sqrt(2)*sigma*X'; 54 | W = W'./sqrt(pi); 55 | end 56 | 57 | P = NaN(Nm); 58 | scalingFactor = max(abs(X)); 59 | kappa = 1e-8; 60 | 61 | for ii = 1:Nm 62 | 63 | condMean = mu*(1-rho)+rho*X(ii); % conditional mean 64 | switch method % define prior probabilities 65 | case 'gauss-hermite' 66 | q = W; 67 | otherwise 68 | q = W.*normpdf(X,condMean,sigma); 69 | end 70 | 71 | if any(q < kappa) 72 | q(q < kappa) = kappa; % replace by small number for numerical stability 73 | end 74 | 75 | if nMoments == 1 % match only 1 moment 76 | P(ii,:) = discreteApproximation(X,@(x)(x-condMean)/scalingFactor,TBar(1)./scalingFactor,q,0); 77 | else % match 2 moments first 78 | [p,lambda,momentError] = discreteApproximation(X,@(x) [(x-condMean)./scalingFactor;... 79 | ((x-condMean)./scalingFactor).^2],... 80 | TBar(1:2)./(scalingFactor.^(1:2)'),q,zeros(2,1)); 81 | if norm(momentError) > 1e-5 % if 2 moments fail, then just match 1 moment 82 | warning('Failed to match first 2 moments. Just matching 1.') 83 | P(ii,:) = discreteApproximation(X,@(x)(x-condMean)/scalingFactor,0,q,0); 84 | elseif nMoments == 2 85 | P(ii,:) = p; 86 | elseif nMoments == 3 % 3 moments 87 | [pnew,~,momentError] = discreteApproximation(X,@(x) [(x-condMean)./scalingFactor;... 88 | ((x-condMean)./scalingFactor).^2;((x-condMean)./scalingFactor).^3],... 89 | TBar(1:3)./(scalingFactor.^(1:3)'),q,[lambda;0]); 90 | if norm(momentError) > 1e-5 91 | warning('Failed to match first 3 moments. Just matching 2.') 92 | P(ii,:) = p; 93 | else P(ii,:) = pnew; 94 | end 95 | else % 4 moments 96 | [pnew,~,momentError] = discreteApproximation(X,@(x) [(x-condMean)./scalingFactor;... 97 | ((x-condMean)./scalingFactor).^2; ((x-condMean)./scalingFactor).^3;... 98 | ((x-condMean)./scalingFactor).^4],TBar./(scalingFactor.^(1:4)'),q,[lambda;0;0]); 99 | if norm(momentError) > 1e-5 100 | %warning('Failed to match first 4 moments. Just matching 3.') 101 | [pnew,~,momentError] = discreteApproximation(X,@(x) [(x-condMean)./scalingFactor;... 102 | ((x-condMean)./scalingFactor).^2;((x-condMean)./scalingFactor).^3],... 103 | TBar(1:3)./(scalingFactor.^(1:3)'),q,[lambda;0]); 104 | if norm(momentError) > 1e-5 105 | warning('Failed to match first 3 moments. Just matching 2.') 106 | P(ii,:) = p; 107 | else P(ii,:) = pnew; 108 | warning('Failed to match first 4 moments. Just matching 3.') 109 | end 110 | else P(ii,:) = pnew; 111 | end 112 | end 113 | end 114 | 115 | end -------------------------------------------------------------------------------- /Subroutines/allcomb2.m: -------------------------------------------------------------------------------- 1 | function A = allcomb2(varargin) 2 | 3 | % Slightly modified version of allcomb 4 | % ALLCOMB - All combinations 5 | % B = ALLCOMB(A1,A2,A3,...,AN) returns all combinations of the elements 6 | % in the arrays A1, A2, ..., and AN. B is P-by-N matrix is which P is the product 7 | % of the number of elements of the N inputs. This functionality is also 8 | % known as the Cartesian Product. The arguments can be numerical and/or 9 | % characters, or they can be cell arrays. 10 | % 11 | % Examples: 12 | % allcomb([1 3 5],[-3 8],[0 1]) % numerical input: 13 | % % -> [ 1 -3 0 14 | % % 1 -3 1 15 | % % 1 8 0 16 | % % ... 17 | % % 5 -3 1 18 | % % 5 8 1 ] ; % a 12-by-3 array 19 | % 20 | % allcomb('abc','XY') % character arrays 21 | % % -> [ aX ; aY ; bX ; bY ; cX ; cY] % a 6-by-2 character array 22 | % 23 | % allcomb('xy',[65 66]) % a combination 24 | % % -> ['xA' ; 'xB' ; 'yA' ; 'yB'] % a 4-by-2 character array 25 | % 26 | % allcomb({'hello','Bye'},{'Joe', 10:12},{99999 []}) % all cell arrays 27 | % % -> { 'hello' 'Joe' [99999] 28 | % % 'hello' 'Joe' [] 29 | % % 'hello' [1x3 double] [99999] 30 | % % 'hello' [1x3 double] [] 31 | % % 'Bye' 'Joe' [99999] 32 | % % 'Bye' 'Joe' [] 33 | % % 'Bye' [1x3 double] [99999] 34 | % % 'Bye' [1x3 double] [] } ; % a 8-by-3 cell array 35 | % 36 | % ALLCOMB(..., 'matlab') causes the first column to change fastest which 37 | % is consistent with matlab indexing. Example: 38 | % allcomb(1:2,3:4,5:6,'matlab') 39 | % % -> [ 1 3 5 ; 1 4 5 ; 1 3 6 ; ... ; 2 4 6 ] 40 | % 41 | % If one of the arguments is empty, ALLCOMB returns a 0-by-N empty array. 42 | % 43 | % See also NCHOOSEK, PERMS, NDGRID 44 | % and NCHOOSE, COMBN, KTHCOMBN (Matlab Central FEX) 45 | 46 | % for Matlab R2011b 47 | % version 4.0 (feb 2014) 48 | % (c) Jos van der Geest 49 | % email: jos@jasen.nl 50 | 51 | % History 52 | % 1.1 (feb 2006), removed minor bug when entering empty cell arrays; 53 | % added option to let the first input run fastest (suggestion by JD) 54 | % 1.2 (jan 2010), using ii as an index on the left-hand for the multiple 55 | % output by NDGRID. Thanks to Jan Simon, for showing this little trick 56 | % 2.0 (dec 2010). Bruno Luong convinced me that an empty input should 57 | % return an empty output. 58 | % 2.1 (feb 2011). A cell as input argument caused the check on the last 59 | % argument (specifying the order) to crash. 60 | % 2.2 (jan 2012). removed a superfluous line of code (ischar(..)) 61 | % 3.0 (may 2012) removed check for doubles so character arrays are accepted 62 | % 4.0 (feb 2014) added support for cell arrays 63 | 64 | error(nargchk(1,Inf,nargin)) ; 65 | 66 | NC = size(varargin{1},1) ; 67 | A = cell(1,NC); 68 | temp = cell2mat(varargin); 69 | 70 | for ii = 1:NC 71 | 72 | A(ii) = {temp(ii,:)}; 73 | 74 | end 75 | varargin = A; 76 | 77 | % check if we should flip the order 78 | if ischar(varargin{end}) && (strcmpi(varargin{end},'matlab') || strcmpi(varargin{end},'john')), 79 | % based on a suggestion by JD on the FEX 80 | NC = NC-1 ; 81 | ii = 1:NC ; % now first argument will change fastest 82 | else 83 | % default: enter arguments backwards, so last one (AN) is changing fastest 84 | ii = NC:-1:1 ; 85 | end 86 | 87 | % check for empty inputs 88 | if any(cellfun('isempty',varargin(ii))), 89 | warning('ALLCOMB:EmptyInput','Empty inputs result in an empty output.') ; 90 | A = zeros(0,NC) ; 91 | elseif NC > 1 92 | isCellInput = cellfun(@iscell,varargin) ; 93 | if any(isCellInput) 94 | if ~all(isCellInput) 95 | error('ALLCOMB:InvalidCellInput', ... 96 | 'For cell input, all arguments should be cell arrays.') ; 97 | end 98 | % for cell input, we use to indices to get all combinations 99 | ix = cellfun(@(c) 1:numel(c), varargin,'un',0) ; 100 | 101 | % flip using ii if last column is changing fastest 102 | [ix{ii}] = ndgrid(ix{ii}) ; 103 | 104 | A = cell(numel(ix{1}),NC) ; % pre-allocate the output 105 | for k=1:NC, 106 | % combine 107 | A(:,k) = reshape(varargin{k}(ix{k}),[],1) ; 108 | end 109 | else 110 | % non-cell input, assuming all numerical values or strings 111 | % flip using ii if last column is changing fastest 112 | [A{ii}] = ndgrid(varargin{ii}) ; 113 | % concatenate 114 | A = reshape(cat(NC+1,A{:}),[],NC) ; 115 | end 116 | elseif NC==1, 117 | A = varargin{1}(:) ; % nothing to combine 118 | 119 | else % NC==0, there was only the 'matlab' flag argument 120 | A = zeros(0,0) ; % nothing 121 | end -------------------------------------------------------------------------------- /Discretize Gaussian mixture AR/discreteGMAR.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % discreteGMAR 3 | % (c) 2019 Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Discretize an AR(p) process with Gaussian mixture shocks 7 | % 8 | % Usage: 9 | % [P,X] = discreteGMAR(mu,A,pC,muC,sigmaC,Nm,nMoments,method,nSigmas) 10 | % 11 | % Inputs: 12 | % mu - unconditional mean 13 | % A - vector of coefficients of AR(p) 14 | % pC - vector of proportions of Gaussian mixtures 15 | % muC - vector of means of Gaussian mixtures 16 | % sigmaC - vector of standard deviations of Gaussian mixtures 17 | % Nm - number of grid points in one dimension 18 | % Optional: 19 | % nMoments - number of moments to match (default = 2) 20 | % method - quadrature method (default = 'even') 21 | % nSigmas - grid spacing when using even-spaced grid 22 | 23 | function [P,X] = discreteGMAR(mu,A,pC,muC,sigmaC,Nm,nMoments,method,nSigmas) 24 | 25 | %% some error checking 26 | if any(pC < 0) 27 | error('mixture proportions must be positive') 28 | end 29 | if any(sigmaC < 0) 30 | error('standard deviations must be positive') 31 | end 32 | if sum(pC) ~= 1 33 | error('mixture proportions must add up to 1') 34 | end 35 | 36 | if size(pC,1) < size(pC,2) 37 | pC = pC'; % convert to column vector 38 | end 39 | if size(muC,1) < size(muC,2) 40 | muC = muC'; % convert to column vector 41 | end 42 | if size(sigmaC,1) < size(sigmaC,2) 43 | sigmaC = sigmaC'; % convert to column vector 44 | end 45 | 46 | K = length(A); 47 | 48 | if size(A,1) > size(A,2) 49 | A = A'; % convert A to row vector 50 | end 51 | 52 | F = [A;eye(K-1,K)]; % matrix to represent AR(p) by VAR(1); 53 | rho = abs(eigs(F,1)); % spectral radius of F 54 | 55 | if rho >= 1 56 | error('spectral radius must be less than one') 57 | end 58 | 59 | % compute conditional moments 60 | sigmaC2 = sigmaC.^2; 61 | T1 = pC'*muC; % mean 62 | T2 = pC'*(muC.^2+sigmaC2); % uncentered second moment 63 | T3 = pC'*(muC.^3+3*muC.*sigmaC2); % uncentered third moment 64 | T4 = pC'*(muC.^4+6*(muC.^2).*sigmaC2+3*sigmaC2.^2); % uncentered fourth moment 65 | 66 | TBar = [T1 T2 T3 T4]'; 67 | 68 | nComp = length(pC); % number of mixture components 69 | temp = zeros(1,1,nComp); 70 | temp(1,1,:) = sigmaC2; 71 | gmObj = gmdistribution(muC,temp,pC); % define the Gaussian mixture object 72 | 73 | % Default number of moments is 2 74 | if nargin == 6 75 | nMoments = 2; 76 | end 77 | 78 | % Check that Nm is a valid number of grid points 79 | if ~isnumeric(Nm) || Nm < 3 || rem(Nm,1) ~= 0 80 | error('Nm must be a positive integer greater than 3') 81 | end 82 | 83 | % Check that nMoments is a valid number 84 | if ~isnumeric(nMoments) || nMoments < 1 || nMoments > 4 || ~((rem(nMoments,1) == 0) || (nMoments == 1)) 85 | error('nMoments must be either 1, 2, 3, 4') 86 | end 87 | 88 | % set default nSigmas if not supplied 89 | if nargin < 9 90 | if rho <= 1-2/(Nm-1) 91 | nSigmas = sqrt(2*(Nm-1)); 92 | else nSigmas = sqrt(Nm-1); 93 | end 94 | end 95 | 96 | sigma = sqrt(T2-T1^2); % conditional standard deviation 97 | temp = (eye(K^2)-kron(F,F))\eye(K^2); 98 | sigmaX = sigma*sqrt(temp(1,1)); % unconditional standard deviation 99 | 100 | % construct the one dimensional grid 101 | switch method 102 | case 'even' % evenly-spaced grid 103 | X1 = linspace(mu-nSigmas*sigmaX,mu+nSigmas*sigmaX,Nm); 104 | W = ones(1,Nm); 105 | case 'gauss-legendre' % Gauss-Legendre quadrature 106 | [X1,W] = legpts(Nm,[mu-nSigmas*sigmaX,mu+nSigmas*sigmaX]); 107 | X1 = X1'; 108 | case 'clenshaw-curtis' % Clenshaw-Curtis quadrature 109 | [X1,W] = fclencurt(Nm,mu-nSigmas*sigmaX,mu+nSigmas*sigmaX); 110 | X1 = fliplr(X1'); 111 | W = fliplr(W'); 112 | case 'gauss-hermite' % Gauss-Hermite quadrature 113 | if rho > 0.8 114 | warning('Model is persistent; even-spaced grid is recommended') 115 | end 116 | [X1,W] = GaussHermite(Nm); 117 | X1 = mu+sqrt(2)*sigma*X1'; 118 | W = W'./sqrt(pi); 119 | case 'GMQ' % Gaussian Mixture Quadrature 120 | if rho > 0.8 121 | warning('Model is persistent; even-spaced grid is recommended') 122 | end 123 | [X1,W] = GaussianMixtureQuadrature(pC,muC,sigmaC,Nm); 124 | X1 = X1 + mu; 125 | end 126 | 127 | X = allcomb2(ones(K,1)*X1)'; % K*Nm^K matrix of grid points 128 | 129 | P = NaN(Nm^K); % transition probability matrix 130 | P1 = NaN(Nm^K,Nm); % matrix to store transition probability 131 | P2 = kron(eye(Nm^(K-1)),ones(Nm,1)); % Nm^K * Nm^(K-1) matrix used to construct P 132 | scalingFactor = max(abs(X1)); 133 | kappa = 1e-8; 134 | 135 | for ii = 1:Nm^K 136 | 137 | condMean = mu*(1-sum(A))+A*X(:,ii); 138 | xPDF = (X1-condMean)'; 139 | switch method 140 | case 'gauss-hermite' 141 | q = W.*(pdf(gmObj,xPDF)./normpdf(xPDF,0,sigma))'; 142 | case 'GMQ' 143 | q = W.*(pdf(gmObj,xPDF)./pdf(gmObj,X1'))'; 144 | otherwise 145 | q = W.*(pdf(gmObj,xPDF))'; 146 | end 147 | 148 | if any(q < kappa) 149 | q(q < kappa) = kappa; 150 | end 151 | 152 | if nMoments == 1 % match only 1 moment 153 | P1(ii,:) = discreteApproximation(X1,@(x)(x-condMean)/scalingFactor,TBar(1)./scalingFactor,q,0); 154 | else % match 2 moments first 155 | [p,lambda,momentError] = discreteApproximation(X1,@(x) [(x-condMean)./scalingFactor;... 156 | ((x-condMean)./scalingFactor).^2],... 157 | TBar(1:2)./(scalingFactor.^(1:2)'),q,zeros(2,1)); 158 | if norm(momentError) > 1e-5 % if 2 moments fail, then just match 1 moment 159 | warning('Failed to match first 2 moments. Just matching 1.') 160 | P1(ii,:) = discreteApproximation(X1,@(x)(x-condMean)/scalingFactor,TBar(1)./scalingFactor,q,0); 161 | elseif nMoments == 2 162 | P1(ii,:) = p; 163 | elseif nMoments == 3 164 | [pnew,~,momentError] = discreteApproximation(X1,@(x) [(x-condMean)./scalingFactor;... 165 | ((x-condMean)./scalingFactor).^2;((x-condMean)./scalingFactor).^3],... 166 | TBar(1:3)./(scalingFactor.^(1:3)'),q,[lambda;0]); 167 | if norm(momentError) > 1e-5 168 | warning('Failed to match first 3 moments. Just matching 2.') 169 | P1(ii,:) = p; 170 | else P1(ii,:) = pnew; 171 | end 172 | else % 4 moments 173 | [pnew,~,momentError] = discreteApproximation(X1,@(x) [(x-condMean)./scalingFactor;... 174 | ((x-condMean)./scalingFactor).^2; ((x-condMean)./scalingFactor).^3;... 175 | ((x-condMean)./scalingFactor).^4],TBar./(scalingFactor.^(1:4)'),q,[lambda;0;0]); 176 | if norm(momentError) > 1e-5 177 | %warning('Failed to match first 4 moments. Just matching 3.') 178 | [pnew,~,momentError] = discreteApproximation(X1,@(x) [(x-condMean)./scalingFactor;... 179 | ((x-condMean)./scalingFactor).^2;((x-condMean)./scalingFactor).^3],... 180 | TBar(1:3)./(scalingFactor.^(1:3)'),q,[lambda;0]); 181 | if norm(momentError) > 1e-5 182 | warning('Failed to match first 3 moments. Just matching 2.') 183 | P1(ii,:) = p; 184 | else P1(ii,:) = pnew; 185 | warning('Failed to match first 4 moments. Just matching 3.') 186 | end 187 | else P1(ii,:) = pnew; 188 | end 189 | end 190 | P(ii,:) = kron(P1(ii,:),P2(ii,:)); 191 | end 192 | 193 | end -------------------------------------------------------------------------------- /Discretize VAR/discreteVAR.m: -------------------------------------------------------------------------------- 1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | % discreteVAR 3 | % (c) 2015 Leland E. Farmer and Alexis Akira Toda 4 | % 5 | % Purpose: 6 | % Compute a finite-state Markov chain approximation to a VAR(1) 7 | % process of the form 8 | % 9 | % y_(t+1) = b + B*y_(t) + Psi^(1/2)*epsilon_(t+1) 10 | % 11 | % where epsilon_(t+1) is an (M x 1) vector of independent standard 12 | % normal innovations 13 | % 14 | % Usage: 15 | % [P,X] = discreteVAR(b,B,Psi,Nm,nMoments,method,nSigmas) 16 | % 17 | % Inputs: 18 | % b - (M x 1) constant vector 19 | % B - (M x M) matrix of impact coefficients 20 | % Psi - (M x M) variance-covariance matrix of the innovations 21 | % Nm - Desired number of discrete points in each dimension 22 | % Optional: 23 | % nMoments - Desired number of moments to match. The default is 2. 24 | % method - String specifying the method used to determine the grid 25 | % points. Accepted inputs are 'even,' 'quantile,' and 26 | % 'quadrature.' The default option is 'even.' Please see the 27 | % paper for more details. 28 | % nSigmas - If the 'even' option is specified, nSigmas is used to 29 | % determine the number of unconditional standard deviations 30 | % used to set the endpoints of the grid. The default is 31 | % sqrt(Nm-1). 32 | % 33 | % Outputs: 34 | % P - (Nm^M x Nm^M) probability transition matrix. Each row 35 | % corresponds to a discrete conditional probability 36 | % distribution over the state M-tuples in X 37 | % X - (M x Nm^M) matrix of states. Each column corresponds to an 38 | % M-tuple of values which correspond to the state associated 39 | % with each row of P 40 | % 41 | % NOTES: 42 | % - discreteVAR only accepts non-singular variance-covariance matrices. 43 | % - discreteVAR only constructs tensor product grids where each dimension 44 | % contains the same number of points. For this reason it is recommended 45 | % that this code not be used for problems of more than about 4 or 5 46 | % dimensions due to curse of dimensionality issues. 47 | % Future updates will allow for singular variance-covariance matrices and 48 | % sparse grid specifications. 49 | % 50 | % Version 1.1: May 5, 2015 51 | % 52 | % Changed default spacing for even-grid method to sqrt((Nm-1)/2) 53 | % 54 | % Version 1.2: March 4, 2016 55 | % 56 | % - Changed default spacing for even-grid method to sqrt(Nm-1) 57 | % - Use alternative diagonalization method to make the variance of each VAR 58 | % component approximately equal 59 | % - Target arbitrarily many conditional moments up to 4 60 | % 61 | % Version 1.3: May 24, 2019 62 | % 63 | % - Added warning message for using 'quantile' method because it is poor 64 | % - Decreased warning threshold for 'quadrature' method to spectral radius 0.8 65 | % 66 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 67 | 68 | function [P,X] = discreteVAR(b,B,Psi,Nm,nMoments,method,nSigmas) 69 | 70 | %% Input error checks 71 | 72 | warning off MATLAB:singularMatrix % surpress inversion warnings 73 | 74 | % Make sure the correct number of arguments are provided 75 | if nargin < 4 76 | error('You must supply at least 4 arguments to discreteVAR') 77 | elseif nargin >= 6 78 | if ~strcmp(method,'quantile') && ~strcmp(method,'even') && ~strcmp(method,'quadrature') 79 | error('Method must be one of quantile, even, or quadrature') 80 | end 81 | if strcmp(method,'quantile') 82 | warning('quantile method is poor and not recommended') 83 | end 84 | end 85 | 86 | % Default number of moments is 2 87 | if nargin == 4 88 | nMoments = 2; 89 | end 90 | 91 | % Default method is 'even' 92 | if nargin <= 5 93 | method = 'even'; 94 | end 95 | 96 | bSize = size(B); 97 | M = bSize(1); 98 | % Check to see if user has provided an explicit spacing for the 'even' 99 | % method. If not, use default value. 100 | if strcmp(method,'even') && nargin < 7 101 | nSigmas = sqrt(Nm-1); 102 | end 103 | 104 | % Check size restrictions on matrices 105 | if bSize(1) ~= bSize(2) 106 | error('B must be a square matrix') 107 | end 108 | 109 | if size(b,2) ~= 1 110 | error('b must be a column vector') 111 | end 112 | 113 | if size(b,1) ~= bSize(1) 114 | error('b must have the same number of rows as B') 115 | end 116 | 117 | % Check that Psi is a valid covariance matrix 118 | [~,posDefCheck] = chol(Psi); 119 | if posDefCheck 120 | error('Psi must be a positive definite matrix') 121 | end 122 | 123 | % Check that Nm is a valid number of grid points 124 | if ~isnumeric(Nm) || Nm < 3 || rem(Nm,1) ~= 0 125 | error('Nm must be a positive integer greater than 3') 126 | end 127 | 128 | % Check that nMoments is a valid number 129 | if ~isnumeric(nMoments) || nMoments < 1 || ~((rem(nMoments,2) == 0) || (nMoments == 1)) 130 | error('nMoments must be either 1 or a positive even integer') 131 | %~isnumeric(nMoments) || nMoments < 1 || rem(nMoments,1) ~= 0 132 | % error('nMoments must be a positive integer') 133 | end 134 | 135 | % Warning about persistence for quadrature method 136 | if strcmp(method,'quadrature') && any(eig(B) > 0.8) 137 | warning('The quadrature method may perform poorly for persistent processes.') 138 | end 139 | 140 | %% Compute polynomial moments of standard normal distribution 141 | gaussianMoment = zeros(nMoments,1); 142 | c = 1; 143 | for k=1:floor(nMoments/2) 144 | c = (2*k-1)*c; 145 | gaussianMoment(2*k) = c; 146 | end 147 | 148 | %% Compute standardized VAR(1) representation (zero mean and diagonal covariance matrix) 149 | 150 | if M == 1 151 | 152 | C = sqrt(Psi); 153 | A = B; 154 | mu = b/(1-B); 155 | Sigma = 1/(1-B^2); 156 | 157 | else 158 | 159 | C1 = chol(Psi,'lower'); 160 | mu = ((eye(M)-B)\eye(M))*b; 161 | A1 = C1\(B*C1); 162 | Sigma1 = reshape(((eye(M^2)-kron(A1,A1))\eye(M^2))*reshape(eye(M),M^2,1),M,M); % unconditional variance 163 | U = minVarTrace(Sigma1); 164 | A = U'*A1*U; 165 | Sigma = U'*Sigma1*U; 166 | C = C1*U; 167 | 168 | end 169 | 170 | %% Construct 1-D grids 171 | 172 | sigmas = sqrt(diag(Sigma)); 173 | y1D = zeros(M,Nm); 174 | 175 | switch method 176 | case 'even' 177 | for ii = 1:M 178 | minSigmas = sqrt(min(eigs(Sigma))); 179 | y1D(ii,:) = linspace(-minSigmas*nSigmas,minSigmas*nSigmas,Nm); 180 | end 181 | case 'quantile' 182 | y1DBounds = zeros(M,Nm+1); 183 | for ii = 1:M 184 | y1D(ii,:) = norminv((2*(1:Nm)-1)./(2*Nm),0,sigmas(ii)); 185 | y1DBounds(ii,:) = [-Inf, norminv((1:Nm-1)./Nm,0,sigmas(ii)), Inf]; 186 | end 187 | case 'quadrature' 188 | [nodes,weights] = GaussHermite(Nm); 189 | for ii = 1:M 190 | y1D(ii,:) = sqrt(2)*nodes; 191 | end 192 | end 193 | 194 | % Construct all possible combinations of elements of the 1-D grids 195 | D = allcomb2(y1D)'; 196 | 197 | %% Construct finite-state Markov chain approximation 198 | 199 | condMean = A*D; % conditional mean of the VAR process at each grid point 200 | P = ones(Nm^M); % probability transition matrix 201 | scalingFactor = y1D(:,end); % normalizing constant for maximum entropy computations 202 | temp = zeros(M,Nm); % used to store some intermediate calculations 203 | lambdaBar = zeros(2*M,Nm^M); % store optimized values of lambda (2 moments) to improve initial guesses 204 | kappa = 1e-8; % small positive constant for numerical stability 205 | 206 | for ii = 1:(Nm^M) 207 | 208 | % Construct prior guesses for maximum entropy optimizations 209 | switch method 210 | case 'even' 211 | q = normpdf(y1D,repmat(condMean(:,ii),1,Nm),1); 212 | case 'quantile' 213 | q = normcdf(y1DBounds(:,2:end),repmat(condMean(:,ii),1,Nm),1)... 214 | - normcdf(y1DBounds(:,1:end-1),repmat(condMean(:,ii),1,Nm),1); 215 | case 'quadrature' 216 | q = bsxfun(@times,(normpdf(y1D,repmat(condMean(:,ii),1,Nm),1)./normpdf(y1D,0,1)),... 217 | (weights'./sqrt(pi))); 218 | end 219 | 220 | % Make sure all elements of the prior are stricly positive 221 | q(q 1e-5 % if 2 moments fail, then just match 1 moment 241 | warning('Failed to match first 2 moments. Just matching 1.') 242 | temp(jj,:) = discreteApproximation(y1D(jj,:),... 243 | @(X)(X-condMean(jj,ii))/scalingFactor(jj),0,q(jj,:),0); 244 | lambdaBar((jj-1)*2+1:jj*2,ii) = zeros(2,1); 245 | elseif nMoments == 2 246 | lambdaBar((jj-1)*2+1:jj*2,ii) = lambda; 247 | temp(jj,:) = p; 248 | else % solve maximum entropy problem sequentially from low order moments 249 | lambdaBar((jj-1)*2+1:jj*2,ii) = lambda; 250 | for mm = 4:2:nMoments 251 | lambdaGuess = [lambda;0;0]; % add zero to previous lambda 252 | [pnew,lambda,momentError] = discreteApproximation(y1D(jj,:),... 253 | @(X) polynomialMoment(X,condMean(jj,ii),scalingFactor(jj),mm),... 254 | gaussianMoment(1:mm)./(scalingFactor(jj).^(1:mm)'),q(jj,:),lambdaGuess); 255 | if norm(momentError) > 1e-5 256 | warning(sprintf('Failed to match first %d moments. Just matching %d.',mm,mm-2)) 257 | break; 258 | else 259 | p = pnew; 260 | end 261 | end 262 | temp(jj,:) = p; 263 | end 264 | end 265 | end 266 | 267 | P(ii,:) = prod(allcomb2(temp),2)'; 268 | 269 | end 270 | 271 | X = C*D + repmat(mu,1,Nm^M); % map grids back to original space 272 | 273 | warning on MATLAB:singularMatrix 274 | 275 | end -------------------------------------------------------------------------------- /Subroutines/legpts.m: -------------------------------------------------------------------------------- 1 | function [x w v] = legpts(n,int,meth) 2 | %LEGPTS Legendre points and Gauss Quadrature Weights. 3 | % LEGPTS(N) returns N Legendre points X in (-1,1). 4 | % 5 | % [X,W] = LEGPTS(N) returns also a row vector W of weights for Gauss quadrature. 6 | % 7 | % LEGPTS(N,D) scales the nodes and weights for the domain D. D can be 8 | % either a domain object or a vector with two components. If the interval 9 | % is infinite, the map is chosen to be the default 'unbounded map' with 10 | % mappref('parinf') = [1 0] and mappref('adaptinf') = 0. 11 | % 12 | % [X,W,V] = LEGPTS(N) returns additionally a column vector V of weights in 13 | % the barycentric formula corresponding to the points X. 14 | % 15 | % [X,W] = LEGPTS(N,METHOD) allows the user to select which method to use. 16 | % METHOD = 'FASTSMALL' uses the recurrence relation for the Legendre 17 | % polynomials and their derivatives to perform Newton iteration 18 | % on the WKB approximation to the roots. 19 | % METHOD = 'FAST' uses the Glaser-Liu-Rokhlin fast algorithm, which 20 | % is much faster for large N. 21 | % METHOD = 'GW' will use the traditional Golub-Welsch eigenvalue method, 22 | % which is maintained mostly for historical reasons. 23 | % By default LEGPTS uses 'FASTSMALL' when N<=256 and FAST when N>256 24 | % 25 | % See also chebpts and jacpts. 26 | 27 | % Copyright 2011 by The University of Oxford and The Chebfun Developers. 28 | % See http://www.maths.ox.ac.uk/chebfun/ for Chebfun information. 29 | 30 | % 'GW' by Nick Trefethen, March 2009 - algorithm adapted from [1]. 31 | % 'FAST' by Nick Hale, April 2009 - algorithm adapted from [2]. 32 | % 33 | % References: 34 | % [1] G. H. Golub and J. A. Welsch, "Calculation of Gauss quadrature 35 | % rules", Math. Comp. 23:221-230, 1969, 36 | % [2] A. Glaser, X. Liu and V. Rokhlin, "A fast algorithm for the 37 | % calculation of the roots of special functions", SIAM Journal 38 | % on Scientific Computing", 29(4):1420-1438:, 2007. 39 | 40 | % Defaults 41 | interval = [-1,1]; 42 | method = 'default'; 43 | 44 | if n < 0 45 | error('CHEBFUN:legpts:n','First input should be a positive number.'); 46 | end 47 | 48 | % Return empty vector if n == 0 49 | if n == 0 50 | x = []; w = []; v = []; return 51 | end 52 | 53 | % Check the inputs 54 | if nargin > 1 55 | if nargin == 3 56 | interval = int; method = meth; 57 | elseif nargin == 2 58 | if ischar(int), method = int; else interval = int; end 59 | end 60 | if ~any(strcmpi(method,{'default','GW','fast','fastsmall'})) 61 | error('CHEBFUN:legpts:inputs',['Unrecognised input string.', method]); 62 | end 63 | if isa(interval,'domain') 64 | interval = interval.endsandbreaks; 65 | end 66 | if numel(interval) > 2, 67 | warning('CHEBFUN:legpts:domain',... 68 | 'Piecewise intervals not supported and will be ignored.'); 69 | interval = interval([1 end]); 70 | end 71 | end 72 | 73 | % Decide to use GW or FAST 74 | if n == 1 75 | % Trivial case when N = 1 76 | x = 0; w = 2; v = 1; 77 | elseif strcmpi(method,'GW') 78 | % GW, see [1] 79 | beta = .5./sqrt(1-(2*(1:n-1)).^(-2)); % 3-term recurrence coeffs 80 | T = diag(beta,1) + diag(beta,-1); % Jacobi matrix 81 | [V,D] = eig(T); % Eigenvalue decomposition 82 | x = diag(D); [x,i] = sort(x); % Legendre points 83 | w = 2*V(1,i).^2; % Quadrature weights 84 | v = sqrt(1-x.^2).*abs(V(1,i))'; % Barycentric weights 85 | v = v./max(v); 86 | 87 | % Enforce symmetry 88 | ii = 1:floor(n/2); x = x(ii); w = w(ii); 89 | vmid = v(floor(n/2)+1); v = v(ii); 90 | if mod(n,2) 91 | x = [x ; 0 ; -x(end:-1:1)]; w = [w 2-sum(2*w) w(end:-1:1)]; 92 | v = [v ; vmid ; v(end:-1:1)]; 93 | else 94 | x = [x ; -x(end:-1:1)]; w = [w w(end:-1:1)]; 95 | v = [v ; v(end:-1:1)]; 96 | end 97 | v(2:2:n) = -v(2:2:end); 98 | elseif (n < 256 && ~strcmpi(method,'fast')) || strcmpi(method,'fastsmall') 99 | % Fastsmall 100 | [x ders] = fastsmall(n); % Nodes and P_n'(x) 101 | w = 2./((1-x.^2).*ders.^2)'; % Quadrature weights 102 | v = 1./ders; v = v./max(abs(v)); % Barycentric weights 103 | if ~mod(n,2), ii = (floor(n/2)+1):n; v(ii) = -v(ii); end 104 | else 105 | % Fast, see [2] 106 | [x ders] = alg0_Leg(n); % Nodes and P_n'(x) 107 | w = 2./((1-x.^2).*ders.^2)'; % Quadrature weights 108 | v = 1./ders; v = v./max(abs(v)); % Barycentric weights 109 | if ~mod(n,2), ii = (floor(n/2)+1):n; v(ii) = -v(ii); end 110 | end 111 | 112 | % Normalise so that sum(w) = 2 113 | w = (2/sum(w))*w; 114 | 115 | % Rescale to arbitrary interval 116 | if ~all(interval == [-1 1]) 117 | if ~any(isinf(interval)) 118 | % Finite interval 119 | dab = diff(interval); 120 | x = (x+1)/2*dab + interval(1); 121 | w = dab*w/2; 122 | else 123 | % Infinite interval 124 | m = maps(fun,{'unbounded'},interval); % use default map 125 | if nargout > 1 126 | w = w.*m.der(x.'); 127 | end 128 | x = m.for(x); 129 | x([1 end]) = interval([1 end]); 130 | end 131 | end 132 | 133 | % -------------------- Routines for FAST_SMALL algorithm ------------------ 134 | 135 | function [x PP] = fastsmall(n) 136 | 137 | % Asymptotic formula (WKB) - only positive x. 138 | if mod(n,2), s = 1; else s = 0; end 139 | k = (n+s)/2:-1:1; theta = pi*(4*k-1)/(4*n+2); 140 | x = (1-(n-1)/(8*n^3)-1/(384*n^4)*(39-28./sin(theta).^2)).*cos(theta); 141 | 142 | % Initialise 143 | Pm2 = 1; Pm1 = x; PPm2 = 0; PPm1 = 1; 144 | dx = inf; l = 0; 145 | 146 | % Loop until convergence 147 | while norm(dx,inf) > eps && l < 10 148 | l = l + 1; 149 | for k = 1:n-1, 150 | P = ((2*k+1)*Pm1.*x-k*Pm2)/(k+1); Pm2 = Pm1; Pm1 = P; 151 | PP = ((2*k+1)*(Pm2+x.*PPm1)-k*PPm2)/(k+1); PPm2 = PPm1; PPm1 = PP; 152 | end 153 | dx = -P./PP; x = x + dx; 154 | Pm2 = 1; Pm1 = x; PPm2 = 0; PPm1 = 1; 155 | end 156 | 157 | % Once more for derivatives 158 | for k = 1:n-1, 159 | P = ((2*k+1)*Pm1.*x-k*Pm2)/(k+1); Pm2 = Pm1; Pm1 = P; 160 | PP = ((2*k+1)*(Pm2+x.*PPm1)-k*PPm2)/(k+1); PPm2 = PPm1; PPm1 = PP; 161 | end 162 | 163 | % Reflect for negative values 164 | x = [-x(end:-1:1+s) x].'; 165 | PP = [PP(end:-1:1+s) PP].'; 166 | 167 | 168 | % -------------------- Routines for FAST algorithm ------------------------ 169 | 170 | function [roots ders] = alg0_Leg(n) % Driver for 'Fast'. 171 | 172 | % Compute coefficients of P_m(0), m = 0,..,N via recurrence relation. 173 | Pm2 = 0; Pm1 = 1; 174 | for k = 0:n-1, P = -k*Pm2/(k+1); Pm2 = Pm1; Pm1 = P; end 175 | 176 | % Get the first roots and derivative values to initialise. 177 | roots = zeros(n,1); ders = zeros(n,1); % Allocate storage 178 | if mod(n,2) % n is odd 179 | roots((n-1)/2) = 0; % Zero is a root 180 | ders((n+1)/2) = n*Pm2; % P'(0) 181 | else % n is even 182 | [roots(n/2+1) ders(n/2+1)] = alg2_Leg(P,n); % Find first root 183 | end 184 | 185 | [roots ders] = alg1_Leg(roots,ders); % Other roots and derivatives 186 | 187 | % ------------------------------------------------------------------------- 188 | 189 | function [roots ders] = alg1_Leg(roots,ders) % Main algorithm for 'Fast' 190 | n = length(roots); 191 | if mod(n,2), N = (n-1)/2; s = 1; else N = n/2; s = 0; end 192 | 193 | % Approximate roots via asymptotic formula. 194 | k = (n-2+s)/2:-1:1; theta = pi*(4*k-1)/(4*n+2); 195 | roots(((n+4-s)/2):end) = (1-(n-1)/(8*n^3)-1/(384*n^4)*(39-28./sin(theta).^2)).*cos(theta); 196 | x = roots(N+1); 197 | 198 | % Number of terms in Taylor expansion. 199 | m = 30; 200 | 201 | % Storage 202 | hh1 = ones(m+1,1); zz = zeros(m,1); u = zeros(1,m+1); up = zeros(1,m+1); 203 | 204 | % Loop over all the roots we want to find (using symmetry). 205 | for j = N+1:n-1 206 | % Distance to initial approx for next root (from asymptotic foruma). 207 | h = roots(j+1) - x; 208 | 209 | % Recurrence Taylor coefficients (scaled & incl factorial terms). 210 | M = 1/h; % Scaling 211 | c1 = 2*x/M; c2 = 1./(1-x^2); % Some constants 212 | % Note, terms are flipped for more accuracy in inner product calculation. 213 | u([m+1 m]) = [0 ders(j)/M]; up(m+1) = u(m); 214 | for k = 0:m-2 215 | up(m-k) = (c1*(k+1)*u(m-k)+(k-n*(n+1)/(k+1))*u(m-k+1)/M^2)*c2; 216 | u(m-(k+1)) = up(m-k)/(k+2); 217 | end 218 | up(1) = 0; 219 | 220 | % Newton iteration 221 | hh = hh1; step = inf; l = 0; 222 | while (abs(step) > eps) && (l < 10) 223 | l = l + 1; 224 | step = (u*hh)/(up*hh)/M; 225 | h = h - step; 226 | Mhzz = (M*h)+zz; 227 | hh = [1;cumprod(Mhzz)]; % Powers of h (This is the fastest way!) 228 | hh = hh(end:-1:1); % Flip for more accuracy in inner product 229 | end 230 | 231 | % Update 232 | x = x + h; 233 | roots(j+1) = x; 234 | ders(j+1) = M*(up*hh); 235 | 236 | end 237 | 238 | % Nodes are symmetric. 239 | roots(1:N+s) = -roots(n:-1:N+1); 240 | ders(1:N+s) = ders(n:-1:N+1); 241 | 242 | % ------------------------------------------------------------------------- 243 | 244 | function [x1 d1] = alg2_Leg(Pn0,n) % Find the first root (note P_n'(0)==0) 245 | % Approximate first root via asymptotic formula 246 | k = ceil(n/2); theta = pi*(4*k-1)/(4*n+2); 247 | x1 = (1-(n-1)/(8*n^3)-1/(384*n^4)*(39-28./sin(theta).^2)).*cos(theta); 248 | 249 | m = 30; % Number of terms in Taylor expansion. 250 | 251 | % Recurrence Taylor coefficients (scaled & incl factorial terms). 252 | M = 1/x1; % Scaling 253 | zz = zeros(m,1); u = [Pn0 zeros(1,m)]; up = zeros(1,m+1); % Allocate storage 254 | for k = 0:2:m-2 255 | up(k+2) = (k-n*(n+1)/(k+1))*u(k+1)/M^2; 256 | u(k+3) = up(k+2)/(k+2); 257 | end 258 | % Flip for more accuracy in inner product calculation. 259 | u = u(m+1:-1:1); up = up(m+1:-1:1); 260 | 261 | % % Note, terms are flipped for more accuracy in inner product calculation. 262 | % zz = zeros(m,1); u = [zeros(1,m) Pn0]; up = zeros(1,m+1); % Allocate storage 263 | % for k = 0:2:m-2 264 | % up(m-k) = (k-n*(n+1)/(k+1))*u(m-k+1)/M^2; 265 | % u(m-(k+1)) = up(m-k)/(k+2); 266 | % end 267 | 268 | % Newton iteration 269 | x1k = ones(m+1,1); step = inf; l = 0; 270 | while (abs(step) > eps) && (l < 10) 271 | l = l + 1; 272 | step = (u*x1k)/(up*x1k)/M; 273 | x1 = x1 - step; 274 | x1k = [1;cumprod(M*x1+zz)]; % Powers of h (This is the fastest way!) 275 | x1k = x1k(end:-1:1); % Flip for more accuracy in inner product 276 | end 277 | 278 | % Get the derivative at this root, i.e. P'(x1). 279 | d1 = M*(up*x1k); 280 | 281 | 282 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | 635 | Copyright (C) 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 | Copyright (C) 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 | --------------------------------------------------------------------------------