keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
2D | pillowlab/GLMspiketools | glmtools_spline/neglogli_tspline_poiss.m | .m | 1,247 | 49 | function [L,dL,ddL] = neglogli_tspline_poiss(prs,X,Y,g,dtbin)
% [L,dL,ddL] = neglogli_tspline_poiss(prs,X,Y,g,dtbin)
%
% Compute negative log-likelihood of data Y given rate g(X*prs).
%
% INPUT:
% prs [M x 1] - parameters
% X [N x M] - design matrix
% Y [N x 1] - observed Poisson random variables
% g - handle for transfer function
% dtbin [1 x 1] - size of time bins of Y
%
% OUTPUT:
% L [1 x 1] - negative log-likelihood
% dL [M x 1] - gradient
% ddL [M x M] - Hessian (2nd deriv matrix)
%
% Last modified: 25 May 2018 (JW Pillow)
% Project parameters onto design matrix
z = X*prs;
etol = 1e-100;
if nargout==1
% Compute neglogli
f = g(z);
f(f<etol)=etol;
L = -Y'*log(f) + sum(f)*dtbin;
elseif nargout == 2
% Compute neglogli & Gradient
[f,df] = g(z);
f(f<etol)=etol;
L = -Y'*log(f) + sum(f)*dtbin;
% grad
wts = (dtbin*df-(Y.*df./f));
dL = X'*wts;
elseif nargout == 3
% Compute neglogli, Gradient & Hessian
[f,df,ddf] = g(z);
f(f<etol)=etol;
L = -Y'*log(f) + sum(f)*dtbin;
% grad
wts = (dtbin*df-(Y.*df./f));
dL = X'*wts;
ww = dtbin*ddf-Y.*(ddf./f-(df./f).^2);
ddL = X'*bsxfun(@times,X,ww);
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/MLfit_splineNlin.m | .m | 985 | 30 | function [gg,negloglival,pp] = MLfit_splineNlin(gg,Stim)
% [gg,neglogli,pp] = MLfit_splineNlin(gg,Stim,optimargs)
%
% Fit a nonlinear function in an GLM neuron with a (positive) spline defined using a set of knots
% (discontinuities of a piecewise-polynomial function), using maximum likelihood
% loss
%
% Inputs:
% gg = glm param structure
% Stim = stimulus
%
% Outputs:
% fun - function pointer to nonlinearity (uses 'ppval')
% pp - piecewise polynomial structure
% Mspline - matrix for converting function params to spline coeffs
% splinePrs - coefs=Mspline*splinePrse
% Compute net GLM filter output
[~,~,~,Itot] = neglogli_GLM(gg,Stim);
Itot = Itot-gg.dc; % remove effect of dc
gg.dc = 0; % set dc to zero
% Do fitting
[fspline,pp,negloglival] = fit_tspline_poisson(Itot,gg.sps,gg.splineprs,gg.dtSp);
% Insert params into glm struct
gg.ppstruct = pp; % piecewise polynomial parameters
gg.nlfun = fspline; % insert nonlinearity
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/fminNewton.m | .m | 5,145 | 181 | function [prs,fval,H] = fminNewton(fptr,prs,opts)
% [prs,fval,H] = fminNewton(fptr,prs,opts)
%
% Simple mplementation of Newton's method for minimizing a function
%
% Inputs:
% fptr - function handle for loss function
% prs - initial value of parameters
% opts - struct with fields: 'tolX', 'tolFun', 'maxIter', 'verbose'.
% (verbose takes on values 0, 1 or 2)
%
% Outputs:
% prs - minimizer of function (or best guess)
% fval - value of function at minimizer
% H - Hessian at minimizer
%
% Derivation of Newton's method (refresher):
% ------------------------------
% f = f0 + f1(x-x0) + 1/2 (x-x0)^T H (x-x0) %% 2nd order Taylor expansion
% df = f1 + H(x-x0) %% derivative
% x = x0 - H^{-1} f1 %% solve for x (new point)
% ------------------------------
%
% $Id$
if nargin < 3
opts = [];
end
% set options to defaults, if necessary
if isfield(opts,'tolX'),tolX= opts.tolX; else tolX = 1e-8; end
if isfield(opts,'tolFun'),tolFun= opts.tolFun; else tolFun = 1e-8; end
if isfield(opts,'maxIter'),maxIter= opts.maxIter; else maxIter = 50; end
if isfield(opts,'verbose'),verbose= opts.verbose; else verbose = 0; end
% Initialize
dX = inf;
dF = inf;
iter = 0;
canDescend = true;
nprs = length(prs);
% % Change warning states so ill-conditioned matrix inverses aren't reported
% msgid1 = 'MATLAB:illConditionedMatrix';
% msgid2 = 'MATLAB:singularMatrix';
% msgid3 = 'MATLAB:nearlySingularMatrix';
% wstate = warning('off',msgid1);
% warning('off',msgid2);
% warning('off',msgid3);
% lastwarn('');
while (dX>tolX) && (dF>tolFun) && (iter < maxIter) && canDescend
% evaluate function, gradient & Hessian
[f,df,H] = fptr(prs);
if any(isinf(H)) | any(isnan(H))
error('fminNewton2: Infinity or Nan in user-supplied Hessian');
end
% Test for positive definite-ness
try chol(H); REG=0;
catch fprintf('[[not pos-def]]');REG=1;
end
% Check to see if H is ill-conditioned
if ~REG && (cond(H)<1e6)
% ---- Standard Newton's Method if well-conditioned ----
dprs = -H\df;
% % Check if it's a descent direction
% if dprs'*df > 0
% dprs = -dprs; % flip sign otherwise
% fprintf(1, 'FLIPPED\n');
% end
else
% ---- Regularize if ill-conditioned ----
if verbose>=2
fprintf('(regularizing H)');
end
% Compute eigenvalues of H
eigvals = eig(H); eigmin = min(eigvals);eigmax = max(eigvals);
if eigmin > 0
lam = eigmax/1e3;
else
%lam = max(eigmax/1e6,-2*eigmin);
lam = eigmax/1e3-eigmin;
end
dprs = -(H+lam*speye(nprs))\(df); % next attempt
% Make sure *this* is a descent direction (if not, something is wrong)
if dprs'*df > 0
error('Somehow we didn''t end up with a descent direction');
end
end
% Evaluate function at new value
fnew = fptr(prs+dprs);
if fnew < f
% Accept the position: update bookkeeping params
dX = norm(dprs);
dF = -(fnew-f);
% Update params
prs = prs+dprs;
else
% Line search in this search direction
% (Note: will give errs if loss func doesn't accept matrix inputs)
if verbose >= 2
fprintf('(line search 1)');
end
fracs = 3.^(-(1:5)); % fractions of gradient to move
fnewvec = fptr(bsxfun(@plus,prs,+dprs*fracs));
[fnew,imin] = nanmin(fnewvec);
if ~(fnew<f)
% try again with even smaller steps
if verbose >= 2
fprintf('(line search 2)');
end
fracs = 3.^(-(6:15)); % fractions of gradient to move
fnewvec = fptr(bsxfun(@plus,prs,+dprs*fracs));
[fnew,imin] = nanmin(fnewvec);
end
if isinf(fnew) || isnan(fnew)
error('fminNewton2: unavoidable infinity or Nan function value: try improving line search');
end
if ~(fnew<f)
canDescend = 0;
if verbose>=1
fprintf('fminNewton: can''t descend anymore; minimum possible\n');
end
else
% Accept the position: update bookkeeping params
dprs = dprs*fracs(imin);
dX = norm(dprs);
dF = -(fnew-f);
% Update params
prs = prs+dprs;
end
end
% Print out information if requested
if verbose>=2
fprintf('iter %d: fun=%.4f\n', iter,fnew);
end
iter = iter+1;
% % Check to make sure we're only decreasing function
% if canDescend && (dF<0)
% warning('error in fminNewton: function increased somehow!'); % for debugging
% keyboard;
% end
end
% If desired, Compute value and Hessian at final value
if nargout > 1
[fval,~,H] = fptr(prs);
end
% Report stopping condition, if verbose >= 1
if verbose >=1
if ~canDescend && iter>3
fprintf('fminNewton could not descend further (iter=%d): flat local minimum likely\n',iter);
elseif ~canDescend
fprintf('fminNewton could not descend (iter=%d): quadratic approx may be bad\n',iter);
fprintf('Try implementing a linesearch method or using better initialization\n');
elseif dX<tolX
fprintf('fminNewton finished (iter=%d): change in X less than tolX\n',iter);
elseif dF<tolFun
fprintf('fminNewton finished (iter=%d): change in fun less than tolFun\n',iter);
else
fprintf('fminNewton stopped: iter=%d exceeded maxIter',iter);
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/tsplinefun.m | .m | 483 | 24 | function [f,df,ddf] = tsplinefun(x,splfun,tfun)
% [f,df,ddf] = tsplinefun(x,splfun,tfun)
%
% Computes the function:
% f(x) = tfun(splfun(x)) and its first and second derivatives
% where tfun is a function handle
switch nargout
case 0,
f = tfun(splfun(x));
case 1,
f = tfun(splfun(x));
case 2,
[g,dg] = splfun(x);
[f,df] = tfun(g);
df = df.*dg;
case 3,
[g,dg,ddg] = splfun(x);
[f,dfg,ddfg] = tfun(g);
df = dfg.*dg;
ddf = ddfg.*dg.^2 + dfg.*ddg;
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/initializeGLMsplineNlin.m | .m | 1,847 | 45 | function [ggnew,negloglival] = initializeGLMsplineNlin(gg,Stim,prs)
% [ggnew,negloglival] = initializeGLMsplineNlin(gg,Stim,prs)
%
% Initializes parameters for a spline nonlinearity using GLM log-likelihood
%
% Inputs:
% gg = param struct
% Stim = stimulus
% spline_prs = structure parameters for spline nonlinearity
% ---- Fields: ----
% nknots = # of knots,
% epprob = [low,high] quantiles for first and last knots
% smoothness = 1+degree of smoothness (3 -> 2nd order continuous)
% extrapDeg = [lo,hi] degree of polynomials for extrapolation outside breaks
%
% Outputs:
% ggnew = new param struct (with ML params);
% negloglival = negative log-likelihood at ML estimate
% Compute net current output from GLM
[~,~,~,Itot] = neglogli_GLM(gg,Stim);
Itot = Itot-gg.dc; % remove DC from injected current
% Set knots and insert piece-wise linear nonlinearity.
knotrange = quantile(Itot,prs.epprob);
knots = linspace(knotrange(1),knotrange(2), prs.nknots);
prebreaks = ((prs.extrapDeg(1):1)-2)/10; % extra left breaks (spaced 0.1 apart)
postbreaks = (1:(2-prs.extrapDeg(2)))/10; % extra right breaks (spaced 0.1 apart)
breaks = [prebreaks+knots(1), knots, knots(end)+postbreaks];
% make spline structure
ss = struct('breaks',breaks, 'smoothness',prs.smoothness, 'extrapDeg',prs.extrapDeg,'tfun',@logexp1);
[fspline,pp,negloglival] = fit_tspline_poisson(Itot,gg.sps,ss,gg.dtSp);
% Insert params into glm struct
ggnew = gg; % initialize
ggnew.dc = 0; % set DC term to zero
ggnew.ppstruct = pp; % piecewise polynomial parameters
ggnew.splineprs = ss; % spline hyperparameters
ggnew.nlfun = fspline; % insert nonlinearity
% % Optional: make plot comparing old and new nonlinearity
% xx = linspace(min(II),max(II),100);
% plot(xx,fspline(xx),breaks,fspline(breaks),'o',xx,gg.nlfun(xx));
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/fit_tspline_poisson.m | .m | 2,410 | 66 | function [fun,pp,neglogli,splPrs,Mspline] = fit_tspline_poisson(x,y,ss,dtbin,prs0)
% [fun,pp,neglogli,splPrs,Mspline] = fit_tspline_poisson(x,y,ss,dtbin,prs0)
%
% Fit a function y = f(x) with a cubic spline, defined using a set of
% breaks, smoothness and extrapolation criteria, by maximizing Poisson
% likelihood: y ~ Poiss(g(spline(x))).
%
% Inputs:
% x [Nx1] - input variable
% y [Nx1] - output (count) variable
% ss [struct] - spline struct with fields:
% .breaks - breaks between polynomial pieces
% .smoothness - derivs of 1 less are continuous
% (e.g., smoothness=3 -> 2nd derivs are continuous)
% .extrapDeg - degree polynomial for extrapolation on ends
% .tfun - nonlinear transfer function (forcing positive outputs)
% dtbin [1x1]- time bin size (OPTIONAL; assumed 1 otherwise)
% prs0 [Mx1] - initial guess at spline params (OPTIONAL)
%
% Outputs:
% fun - function handle for nonlinearity (uses 'ppval')
% pp - piecewise polynomial structure
% neglogli - negative loglikelihood at parameter estimate
% splinePrs - vector x such that spline coeffs = Mspline*x
% Mspline - matrix for converting params to spline coeffs
%
% Note: the fitted nonlinearity can be evaluated via:
% y = ss.tfun(ppval(pp,xx));
%
% last updated: 26/03/2012 (JW Pillow)
if nargin<4
dtbin=1;
end
sortflag=1; % allow sorted design matrix (slightly faster)
% Compute design matrix
[Xdesign,Ysrt,Mspline] = mksplineDesignMat(x,y,ss,sortflag);
nprs = size(Xdesign,2);
if nargin<5
prs0 = randn(nprs,1)*.1;
end
% Set up loss function
floss = @(prs)neglogli_tspline_poiss(prs,Xdesign,Ysrt,ss.tfun,dtbin);
% HessCheck(floss,prs0); % Check that analytic grad and Hessian are correct
% minimize negative log-likelihood using Newton's method
[splPrs,neglogli] = fminNewton(floss,prs0);
% Create function handle for resulting tspline
[~,pp] = mksplinefun(ss.breaks, Mspline*splPrs);
splfun = @(x)ppfun(pp,x);
tfun = ss.tfun;
fun = @(x)tsplinefun(x,splfun,tfun);
% % -----------------------------------------
% % If desired, use Matlab's fminunc instead:
% opts = optimset('display','off','gradobj','on','Hessian','off','maxiter',5000,'maxfunevals',5000,'largescale','off');
% splinePrs2 = fminunc(floss,prs0,opts);
% [floss(splinePrs) floss(splinePrs2)] % Compare results
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/mksplinefun.m | .m | 544 | 19 | function [fun,pp] = mksplinefun(breaks,x)
% [fun,pp] = mksplinefun(breaks,x)
%
% Make spline function handle out of breaks (knots) and coefficients in vector x.
%
% Inputs:
% breaks - points of discontinuity
% x - vector that can be reshaped into N x 4 matrix of spline coefficients
% for each segment
%
% Outputs:
% fun - function pointer for spline function
% pp - matlab piecewise polynomial structure (evaluate with 'ppval').
coeffs = reshape(x,4,[])';
pp = mkpp(breaks, coeffs);
fun = @(x)ppval(pp,x);
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/logexp4.m | .m | 559 | 24 | function [f,df,ddf] = logexp4(x);
% [f,df,ddf] = logexp4(x);
%
% Implements the nonlinearity:
% f(x) = log(1+exp(x)).^4;
% plus first and second derivatives
%
% General formulas:
% f(x) = log(1+exp(x))^k
% f'(x) = k log(1+e^x)^(k-1) * e^x/(1+e^x);
% f"(x) = k(k-1) log(1+e^x)^(k-2) * (e^x/(1+e^x))^2
% + k log(1+e^x)^(k-1) * e^x/(1+e^x)^2
f0 = log(1+exp(x));
f = f0.^4;
if nargout > 1
df = 4*f0.^3.*exp(x)./(1+exp(x));
end
if nargout > 2
ddf = 12*f0.^2.*(exp(x)./(1+exp(x))).^2 + ...
4*f0.^3.*exp(x)./(1+exp(x)).^2;
end
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/logexp_pow.m | .m | 508 | 23 | function [f,df,ddf] = logexp_pow(x,pow);
% [f,df,ddf] = logexp_pow(x);
%
% Implements the nonlinearity:
% f(x) = log(1+exp(x)).^pow;
% plus first and second derivatives
f0 = log(1+exp(x));
f = f0.^pow;
if nargout > 1
df = pow*f0.^(pow-1).*exp(x)./(1+exp(x));
end
if nargout > 2
if pow == 1
ddf = pow*f0.^(pow-1).*exp(x)./(1+exp(x)).^2;
else
ddf = pow*f0.^(pow-1).*exp(x)./(1+exp(x)).^2 + ...
pow*(pow-1)*f0.^(pow-2).*(exp(x)./(1+exp(x))).^2;
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/logexp1.m | .m | 368 | 22 | function [f,df,ddf] = logexp1(x);
% [f,df,ddf] = logexp1(x);
%
% Implements the nonlinearity:
% f(x) = log(1+exp(x)).^pow;
% Where pow = 1;
% plus first and second derivatives
%
pow = 1;
f0 = log(1+exp(x));
f = f0.^pow;
if nargout > 1
df = pow*f0.^(pow-1).*exp(x)./(1+exp(x));
end
if nargout > 2
ddf = pow*f0.^(pow-1).*exp(x)./(1+exp(x)).^2;
end
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/logexp2.m | .m | 430 | 20 | function [f,df,ddf] = logexp2(x);
% [f,df,ddf] = logexp_pow(x);
%
% Implements the nonlinearity:
% f(x) = log(1+exp(x)).^pow;
% where pow=2,
% plus first and second derivatives
pow = 2;
f0 = log(1+exp(x));
f = f0.^pow;
if nargout > 1
df = pow*f0.^(pow-1).*exp(x)./(1+exp(x));
end
if nargout > 2
ddf = pow*f0.^(pow-1).*exp(x)./(1+exp(x)).^2 + ...
pow*(pow-1)*f0.^(pow-2).*(exp(x)./(1+exp(x))).^2;
end
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/logexp3.m | .m | 358 | 19 | function [f,df,ddf] = logexp3(x);
% [f,df,ddf] = logexp3(x);
%
% Implements the nonlinearity:
% f(x) = log(1+exp(x)).^3;
% plus first and second derivatives
f0 = log(1+exp(x));
f = f0.^3;
if nargout > 1
df = 3*f0.^2.*exp(x)./(1+exp(x));
end
if nargout > 2
ddf = 6*f0.*(exp(x)./(1+exp(x))).^2 + ...
3*f0.^2.*exp(x)./(1+exp(x)).^2;
end
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/expfun.m | .m | 166 | 9 | function [f,df,ddf] = expfun(x)
% [f,df,ddf] = expfun(x)
%
% replacement for 'exp' that returns 3 arguments (value, 1st & 2nd deriv)
f = exp(x);
df = f;
ddf = df;
| MATLAB |
2D | pillowlab/GLMspiketools | nlfuns/logexp5.m | .m | 559 | 24 | function [f,df,ddf] = logexp5(x);
% [f,df,ddf] = logexp4(x);
%
% Implements the nonlinearity:
% f(x) = log(1+exp(x)).^4;
% plus first and second derivatives
%
% General formulas:
% f(x) = log(1+exp(x))^k
% f'(x) = k log(1+e^x)^(k-1) * e^x/(1+e^x);
% f"(x) = k(k-1) log(1+e^x)^(k-2) * (e^x/(1+e^x))^2
% + k log(1+e^x)^(k-1) * e^x/(1+e^x)^2
f0 = log(1+exp(x));
f = f0.^5;
if nargout > 1
df = 5*f0.^4.*exp(x)./(1+exp(x));
end
if nargout > 2
ddf = 20*f0.^3.*(exp(x)./(1+exp(x))).^2 + ...
5*f0.^4.*exp(x)./(1+exp(x)).^2;
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/normalizecols.m | .m | 171 | 7 | function B = normalizecols(A);
%
% B = normalizecols(A);
%
% Normalizes the columns of a matrix, so each is a unit vector.
B = A./repmat(sqrt(sum(A.^2)), size(A,1), 1); | MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/spikefilt.m | .m | 697 | 24 | function Y = spikefilt(sps, H)
% Y = spikefilt(sps, H, twin)
%
% Causally filters spike train with spike indices spikeInds with filter matrix H.
%
% Inputs:
% sps [tlen x 1] - spike train vector
% H [n x m] - spike-history matrix (each column is a filter)
%
% Output:
% Y [tlen x m] - each column is the spike train filtered with the
% corresponding column of H
%
% Note: there is a faster 'mex' version of this function called spikefilt_mex,
% available in version 'v1'. It was removed in Jan 2016 to allow for
% mex-free code release.
[hlen,hwid] = size(H);
% Do convolution and remove extra bins
Y = conv2(sps,H,'full');
Y = [zeros(1,hwid); Y(1:end-hlen,:)];
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/makeStimRows.m | .m | 2,036 | 67 | function S = makeStimRows(Stim, nkt, flag)
% S = makeStimRows(Stim, nkt, flag);
%
% Converts spatio-temporal stimulus to a design matrix, where each row of
% the design matrix contains all space-time stimulus elements within a time
% window of "nkt" time bins.
%
% INPUT:
% Stim [N x M] - stimulus, first dimension is time, others are space
% nkt [1 x 1] - number of time bins to include in temporal kernel
% flag (optional)
% 'same' - padded w/ zeros to make S the same size (default)
% 'valid' - no padding with zeros: length(S) = length(Stim)-nkt+1.
% vector of indices - returns only stimuli corresponding to
% these time bins
%
% OUTPUT:
% S [N x M*nkt] or [Nsp x M*nkt ] - design matrix
%
% $Id$
% parse inputs
if nargin < 3
flag = 'same';
end
[n1,n2] = size(Stim);
if ischar(flag) % --- Form for all stimuli (with zero-padding of first bins) -----
if strcmp(flag,'same')
S = zeros(n1, n2*nkt);
Stim = [zeros(nkt-1,n2); Stim];
n1 = n1+nkt-1;
elseif strcmp(flag,'valid')
S = zeros(n1-nkt+1,n2*nkt);
else
error('Unknown flag');
end
% Form design matrix
for j=1:n2
% Loop over columns of original stimulus
S(:,(nkt*(j-1)+1):(nkt*j)) = ...
fliplr(toeplitz(Stim(nkt:n1, j), Stim(nkt:-1:1,j)));
end
else % ---- Form for spiking stimuli only ----------------------------------------
inds = flag; % indices to keep
if (min(inds) < 1) || (max(inds) > n1)
error('Spike indices outside allowed range');
end
S = zeros(length(inds), n2*nkt);
% Do for spinds < nkt
nsp1 = length(inds(inds<nkt));
for j = 1:nsp1
S(j,:) = reshape([zeros(nkt-inds(j), n2); Stim(1:inds(j),:)], 1, n2*nkt);
end
% Do for remaining indices
for j = nsp1 +1:length(inds)
S(j,:) = reshape(Stim(inds(j)-nkt+1:inds(j),:), 1, n2*nkt);
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/getFminOptsForVersion.m | .m | 736 | 18 | function opts = getFminOptsForVersion(v)
% opts = getFminOptsForVersion(v)
%
% Gets the options for fminunc needed for user's version of MATLAB
%
% Note of complaint: it's stupid that I had to write this function, but
% matlab has incompatible syntax for fminunc options for different versions
% (earlier versions of matlab will crash with options required by later
% versions). The cutoff point for my two versions was 9.1 vs. 9.3, but if
% you're getting warnings or crashes, please report to pillow@princeton.edu
% or make an issue report on github
if str2num(v(1:3))>9.2 % check if version is before V 9.2
opts = {'algorithm','trust-region','Gradobj','on','Hessian','on'};
else
opts = {'Gradobj','on','Hessian','on'};
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/in.m | .m | 461 | 22 | function [ii, nds] = in(v, rnge)
% [ii,nds] = in(v, rnge)
%
% returns indices of vector v within range rnge, inclusive of endpoints
if (nargout == 1)
if length(rnge) == 1;
ii = v(v<=vrnge);
else
ii = v((v>=rnge(1)) & (v<=rnge(2)));
end
else
if length(rnge) == 1;
nds = find(v<=vrnge);
ii = v(nds);
else
nds = find((v>=rnge(1)) & (v<=rnge(2)));
ii = v(nds);
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/simGLM.m | .m | 7,517 | 185 | function [tsp,sps,Itot,Istm] = simGLM(glmprs,Stim)
% [tsp,sps,Itot,Ispk] = simGLM(glmprs,Stim)
%
% Compute response of glm to stimulus Stim.
%
% Uses time rescaling instead of Bernouli approximation to conditionally
% Poisson process
%
% Dynamics: Filters the Stimulus with glmprs.k, passes this through a
% nonlinearity to obtain the point-process conditional intensity. Add a
% post-spike current to the linear input after every spike.
%
% Input:
% glmprs - struct with GLM params, has fields 'k', 'h','dc' for params
% and 'dtStim', 'dtSp' for discrete time bin size for stimulus
% and spike train (in s).
% Stim - stimulus matrix, with time running vertically and each
% column corresponding to a different pixel / regressor.
% Output:
% tsp - list of spike times (in s)
% sps - binary matrix with spike times (at resolution dtSp).
% Itot - summed filter outputs
% Istm - just the spike-history filter output
% Check nonlinearity (default is exponential)
if ~isfield(glmprs, 'nlfun'),
glmprs.nlfun = @exp;
end
upSampFactor = glmprs.dtStim/glmprs.dtSp; % number of spike bins per Stim bin
assert(mod(upSampFactor,1) == 0, 'dtStim / dtSp must be an integer');
% Determine which version to run
if size(glmprs.k,3) > 1 % Run "coupled" GLM model if multiple cells present
[tsp,sps,Itot,Istm] = simGLMcpl(glmprs,Stim,upSampFactor);
else % Single cell simulation
[tsp,sps,Itot,Istm] = simGLMsingle(glmprs,Stim,upSampFactor);
end
% ======================================================================
function [tsp,sps,Itot,Istm] = simGLMsingle(glmprs,Stim,upSampFactor)
% Sub-function within simGLM.m
%
% Simulates the GLM point process model for a single (uncoupled) neuron
% using time-rescaling
% --------------- Check Inputs ----------------------------------
nbinsPerEval = 100; % Default number of bins to update for each spike
dt = glmprs.dtSp; % bin size for simulation
slen = size(Stim,1); % length of stimulus
rlen = slen*upSampFactor; % length of binned spike response
hlen = size(glmprs.ih,1); % length of post-spike filter
% ------------- Compute filtered resp to signal ----------------
Istm = sameconv(Stim,glmprs.k); % filter stimulus with k
Istm = kron(Istm,ones(upSampFactor,1)) + glmprs.dc; % upsample stim current
Itot = Istm; % total filter output
% --------------- Set up simulation dynamics variables ---------------
nsp = 0; % number of spikes
sps = zeros(rlen,1); % sparse spike time matrix
jbin = 1; % current time bin
tspnext = exprnd(1); % time of next spike (in rescaled time)
rprev = 0; % Integrated rescaled time up to current point
% --------------- Run dynamics ---------------------------------------
while jbin <= rlen
iinxt = jbin:min(jbin+nbinsPerEval-1,rlen);
rrnxt = glmprs.nlfun(Itot(iinxt))*dt; % Cond Intensity
rrcum = cumsum(rrnxt)+rprev; % integrated cond intensity
if (tspnext >= rrcum(end)) % No spike in this window
jbin = iinxt(end)+1;
rprev = rrcum(end);
else % Spike!
ispk = iinxt(find(rrcum>=tspnext, 1, 'first')); % time bin where spike occurred
nsp = nsp+1;
sps(ispk) = 1; % spike time
mxi = min(rlen, ispk+hlen); % max time affected by post-spike kernel
iiPostSpk = ispk+1:mxi; % time bins affected by post-spike kernel
if ~isempty(iiPostSpk)
Itot(iiPostSpk) = Itot(iiPostSpk)+glmprs.ih(1:mxi-ispk);
end
tspnext = exprnd(1); % draw next spike time
rprev = 0; % reset integrated intensity
jbin = ispk+1; % Move to next bin
% -- Update # of samples per iter ---
muISI = jbin/nsp;
nbinsPerEval = max(20, round(1.5*muISI));
end
end
tsp = find(sps>0)*dt;
% ========================================================================
function [tsp,sps,Itot,Istm] = simGLMcpl(glmprs,Stim,upSampFactor)
% [tsp,sps,Itot,Istm] = simGLMcpl(glmprs,Stim,upSampFactor)
%
% Compute response of (multi-cell) coupled-glm to stimulus Stim.
%
% Uses time rescaling to sample conditionally Poisson process
%
% Dynamics: Filters the Stimulus with glmprs.k, passes this through a
% nonlinearity to obtain the point-process conditional intensity. Add a
% post-spike current to the linear input after every spike.
%
% Sub-function within simGLM.m
% --------------- Check Inputs ----------------------------------
ncells = size(glmprs.k,3);
nbinsPerEval = 100; % Default number of bins to update for each spike
dt = glmprs.dtSp;
% Check that dt evenly divides 1
if mod(1,dt) ~= 0
dt = 1/round(1/dt);
fprintf(1, 'glmrunmod: reset dtsim = %.3f\n', dt);
end
slen = size(Stim,1); % length of stimulus
rlen = slen*upSampFactor; % length of binned response
ih = permute(glmprs.ih,[1 3 2]); % permute so all outgoing filters in a single plane
hlen = size(ih,1); % length of h filter
% ------------- Compute filtered resp to signal ----------------
Istm = zeros(slen,ncells);
for jj = 1:ncells
Istm(:,jj) = sameconv(Stim,glmprs.k(:,:,jj)); % filter stimulus with k
end
Istm = bsxfun(@plus,Istm,glmprs.dc); % add DC term
% Compute finely sampled version
Istm = kron(Istm,ones(upSampFactor,1)); % upsample stim current
Itot = Istm; % total filter output
% --------------- Set up simulation dynamics variables ---------------
tsp(1,1:ncells) = {zeros(round(slen/25),1)}; % allocate space for spike times
nsp = zeros(1,ncells);
jbin = 1; % counter ?
tspnext = exprnd(1,1,ncells); % time of next spike (in rescaled time)
rprev = zeros(1,ncells); % Integrated rescaled time up to current point
% --------------- Run dynamics ---------------------------------------
while jbin <= rlen
iinxt = jbin:min(jbin+nbinsPerEval-1,rlen); % Bins to update in this iteration
nii = length(iinxt); % Number of bins
rrnxt = glmprs.nlfun(Itot(iinxt,:))*dt; % Cond Intensity
rrcum = cumsum(rrnxt+[rprev;zeros(nii-1,ncells)],1); % Cumulative intensity
if all(tspnext >= rrcum(end,:)) % No spike in this window
jbin = iinxt(end)+1;
rprev = rrcum(end,:);
else % Spike!
[ispks,jspks] = find(rrcum>=repmat(tspnext,nii,1));
spcells = unique(jspks(ispks == min(ispks))); % cell number(s)
ispk = iinxt(min(ispks)); % time bin of spike(s)
rprev = rrcum(min(ispks),:); % grab accumulated history to here
% Record this spike
mxi = min(rlen, ispk+hlen); % determine bins for adding h current
iiPostSpk = ispk+1:mxi;
for ic = 1:length(spcells)
icell = spcells(ic);
nsp(icell) = nsp(icell)+1;
tsp{icell}(nsp(icell),1) = ispk*dt;
if ~isempty(iiPostSpk)
Itot(iiPostSpk,:) = Itot(iiPostSpk,:)+ih(1:mxi-ispk,:,icell);
end
rprev(icell) = 0; % reset this cell's integral
tspnext(icell) = exprnd(1); % draw RV for next spike in this cell
end
jbin = ispk+1; % Move to next bin
% -- Update # of samples per iter ---
muISI = jbin/(sum(nsp));
nbinsPerEval = max(20, round(1.5*muISI));
end
end
% Remove any extra bins from tsp and compute binned spike train 'sps'
sps = zeros(rlen,ncells);
for jj = 1:ncells
tsp{jj} = tsp{jj}(1:nsp(jj));
if ~isempty(tsp{jj})
sps(round(tsp{jj}/dt),jj) = 1;
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/makeBasis_PostSpike.m | .m | 3,133 | 90 | function [iht, ihbas, ihbasis] = makeBasis_PostSpike(ihprs,dt)
% [iht, ihbas, ihbasis] = makeBasis_PostSpike(ihprs,dt)
%
% Make nonlinearly stretched basis consisting of raised cosines
% -------
% Inputs:
% prs = param structure with fields:
% ncols = # of basis vectors
% hpeaks = 2-vector containg [1st_peak last_peak], the peak
% location of first and last raised cosine basis vectors
% b = offset for nonlinear stretching of x axis: y = log(x+b)
% (larger b -> more nearly linear stretching)
% absref = absolute refractory period (optional). If specified,
% this param creates an additional "square" basis
% vector with support n [0,absref] (i.e., with a hard
% cutoff at absref)
%
% dt = grid of time points for representing basis
% --------
% Outputs: iht = time lattice on which basis is defined
% ihbas = orthogonalized basis
% ihbasis = original raised cosine (non-orthogonal) basis
%
% -------------
% Example call:
%
% ihbasprs.ncols = 5;
% ihbasprs.hpeaks = [.1 2];
% ihbasprs.b = .5;
% ihbasprs.absref = .1; %% (optional)
% [iht,ihbas,ihbasis] = makeBasis_PostSpike(ihprs,dt);
ncols = ihprs.ncols;
b = ihprs.b;
hpeaks = ihprs.hpeaks;
if isfield(ihprs, 'absref')
absref = ihprs.absref;
else
absref = 0;
end
% Check input values
if (hpeaks(1)+b) < 0
error('b + first peak location: must be greater than 0');
end
if absref >= dt % use one fewer "cosine-shaped basis vector
ncols = ncols-1;
elseif absref > 0
warning('Refractory period too small for time-bin sizes');
end
% nonlinearity for stretching x axis (and its inverse)
nlin = @(x)log(x+1e-20);
invnl = @(x)exp(x)-1e-20; % inverse nonlinearity
ff = @(x,c,dc)(cos(max(-pi,min(pi,(x-c)*pi/dc/2)))+1)/2; % raised cosine basis vector
% Generate basis of raised cosines
if ncols > 1
yrnge = nlin(hpeaks+b); % nonlinearly transformed first & last bumps
db = diff(yrnge)/(ncols-1); % spacing between cosine bump peaks
ctrs = yrnge(1):db:yrnge(2); % centers (peak locations) for basis vectors
else
% if only 1 basis function
if length(hpeaks)==1
hpeaks = [0 hpeaks]; % place imaginary 1st bump at 0
end
yrnge = nlin(hpeaks+b); % nonlinearly transformed first & last bumps
ncolseff = 3; % use 3 "effective" number of basis funcs, so left edge decays at 0
db = diff(yrnge)/(ncolseff-1); % spacing between cosine bump peaks
ctrs = yrnge(2); % centers (peak locations) for basis vectors
end
% Make basis
mxt = invnl(yrnge(2)+2*db)-b; % maximum time bin
iht = (dt:dt:mxt)';
nt = length(iht); % number of points in iht
ihbasis = ff(repmat(nlin(iht+b), 1, ncols), repmat(ctrs, nt, 1), db);
% create first basis vector as step-function for absolute refractory period
if absref >= dt
ii = find(iht<absref);
ih0 = zeros(size(ihbasis,1),1);
ih0(ii) = 1;
ihbasis(ii,:) = 0;
ihbasis = [ih0,ihbasis];
end
% compute orthogonalized basis
ihbas = orth(ihbasis);
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/makeBasis_StimKernel.m | .m | 2,344 | 61 | function [kbasorth,kbasis] = makeBasis_StimKernel(kbasprs, nkt);
% [kbasorth, kbasis] = makeBasis_StimKernel(kbasprs, nkt);
%
% Generates a basis consisting of raised cosines and several columns of
% identity matrix vectors for temporal structure of stimulus kernel
%
% Args: kbasprs = struct with fields:
% neye = number of identity basis vectors at front
% ncos = # of vectors that are raised cosines
% kpeaks = 2-vector, with peak position of 1st and last vector,
% relative to start of cosine basis vectors (e.g. [0 10])
% b = offset for nonlinear scaling. larger values -> more linear
% scaling of vectors. bk must be >= 0
% nkt = number of time samples in basis (optional)
%
% Output:
% kbasorth = orthogonal basis
% kbasis = standard raised cosine (non-orthongal) basis
neye = kbasprs.neye;
ncos = kbasprs.ncos;
kpeaks = kbasprs.kpeaks;
b = kbasprs.b;
kdt = 1; % spacing of x axis must be in units of 1
% nonlinearity for stretching x axis (and its inverse)
nlin = @(x)log(x+1e-20);
invnl = @(x)exp(x)-1e-20; % inverse nonlinearity
% Generate basis of raised cosines
yrnge = nlin(kpeaks+b);
db = diff(yrnge)/(ncos-1); % spacing between raised cosine peaks
ctrs = yrnge(1):db:yrnge(2); % centers for basis vectors
mxt = invnl(yrnge(2)+2*db)-b; % maximum time bin
kt0 = (0:kdt:mxt)';
nt = length(kt0); % number of points in iht
ff = @(x,c,dc)(cos(max(-pi,min(pi,(x-c)*pi/dc/2)))+1)/2; % raised cosine basis vector
kbasis0 = ff(repmat(nlin(kt0+b), 1, ncos), repmat(ctrs, nt, 1), db);
% Concatenate identity-vectors
nkt0 = size(kt0,1);
kbasis = [[eye(neye); zeros(nkt0,neye)] [zeros(neye, ncos); kbasis0]];
kbasis = flipud(kbasis); % flip so fine timescales are at the end.
nkt0 = size(kbasis,1);
if nargin > 1
if nkt0 < nkt
%fprintf('>>>> makeBasis_StimKernel: Padding basis with %d rows of zeros\n', nkt-nkt0);
kbasis = [zeros(nkt-nkt0,ncos+neye); kbasis];
elseif nkt0 > nkt
%fprintf('>>>> makeBasis_StimKernel: Removing %d rows from basis\n', nkt0-nkt);
kbasis = kbasis(end-nkt+1:end,:);
end
end
kbasis = bsxfun(@rdivide,kbasis,sqrt(sum(kbasis.^2))); % normalize columns to be unit vectors
kbasorth = orth(kbasis);
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/simpleSTC.m | .m | 6,243 | 171 | function [STA,STC,RawMu,RawCov] = simpleSTC(Stim,sp,nkt,maxsize)
% [STA,STC,RawMu,RawCov] = simpleSTC(Stim,sp,nkt,maxsize)
%
% Computes mean and covariance of spike-triggered (or response weighted)
% stimuli and raw stimuli
%
% INPUT:
% Stim [N x M] - stimulus matrix; 1st dimension = time, 2nd dimension = space
% sp [N x 1] - column vector of spike count in each time bin (can be sparse)
% [Nsp x 1] - or, vector of spike times
% nkt [1 x 1] - # time samples to consider to be part of the stimulus
% MaxSize [1 x 1] (optional) - max # of floats to store while computing cov
% (smaller = slower, but less memory required)
%
% OUTPUT:
% STA [nkt x M] - spike-triggered average (reshaped as matrix)
% STC [nkt*M x nkt*M] - spike-triggered covariance (covariance around the mean);
% RawMu [nkt*M x 1] - mean of raw stimulus ensemble
% RawCov [nkt*M x nkt*M] - covariance of raw stimulus ensemble
%
% Notes:
% (1) Ignores response before nkt bins
% (2) Faster if only 2 output arguments (raw mean and covariance not computed)
% (3) Reduce 'maxsize' if getting "out of memory" errors
% (4) If inputs are not spike times or counts, response-weighted covariance may be more appropriate.
% See "simpleRWC.m".
%
% --------
% Details:
% --------
% Let X = "valid" design matrix (from makeStimRows)
% Y = sp (spike train)
% nsp = sum(Y); % number of spikes (sum of responses)
% N = size(Stim,1); % number of stimuli
%
% then STA = X'*Y / nsp
% STC = X'*(X.*repmat(Y,1,ncols)))/(nsp-1) - STA*STA'*nsp/(nsp-1)
% RawMu = sum(X)/N;
% RawCov = X*X'/(N-1);
%
% Copyright 2010 Pillow Lab. All rights reserved.
% $Id$
%-------- Parse inputs ---------------------------
if nargin < 4
maxsize = 1e9; % max chunk size; decrease if getting "out of memory"
end
[slen,swid] = size(Stim); % stimulus size (# time bins x # spatial bins).
nsp = length(sp);
% Convert list of spike times to spike-count vector, if necessary
if (nsp ~= slen)
fprintf(1, 'simpleSTC: converting spike times to counts\n');
sp = hist(sp,1:slen)';
end
sp(1:nkt-1) = 0; % Remove spikes before time n
spsum = sum(sp); % Sum of spikes
if (spsum == 0)
spsum = 2;
end
nspnds = sum(sp~=0);
% ---------------------------------------------------
% 1. Compute only the spike-triggered STA and STC
if nargout <= 2
Msz = nspnds*swid*nkt; % size of design matrix for spiking stimuli
iisp = find(sp);
splen = length(iisp);
if Msz < maxsize % Compute in one chunk if small enough
SS = makeStimRows(Stim, nkt,iisp);
STA = (SS'*sp(iisp))/spsum;
if nargout > 1
STC = SS'*bsxfun(@times,SS,sp(iisp))/(spsum-1) - STA*STA'*spsum/(spsum-1);
end
else % Compute in multiple chunks if too large
nchunk = ceil(Msz/maxsize);
chunksize = ceil(length(iisp)/nchunk);
fprintf(1, 'simpleSTC: using %d chunks to compute STA/STC\n', nchunk);
% Initialize on 1st chunk
i0 = 1;
imx = chunksize;
SS = makeStimRows(Stim,nkt,iisp(i0:imx));
STA = (sp(iisp(i0:imx))'*SS)';
if nargout > 1
STC = SS'*bsxfun(@times,SS,sp(iisp(i0:imx)));
end
% Compute for remaining chunks
for j = 2:nchunk
i0 = chunksize*(j-1)+1;
imx = min(chunksize*j, splen);
SS = makeStimRows(Stim,nkt,iisp(i0:imx));
STA = STA + (sp(iisp(i0:imx))'*SS)';
if nargout > 1
STC = STC + SS'*bsxfun(@times,SS,sp(iisp(i0:imx)));
end
end
% normalize by number of samples
STA = STA/spsum;
if nargout > 1
STC = STC/(spsum-1) - STA*STA'*spsum/(spsum-1);
end
end
% -----------------------------------------------------------------------
% 2. Compute both the spike-triggered and raw stimulus means and covariances
else
sp = sp(nkt:end); % Ignore spikes before time bin nkt
slen = length(sp); % length of time indices for stim and spikes
Msz = slen*swid*nkt; % Size of full stimulus matrix
if Msz < maxsize % Check if stimulus is small enough to do in one chunk
SS = makeStimRows(Stim,nkt,'valid'); % Convert stimulus to matrix where each row is one stim
% Compute raw mean and covariance
RawMu = mean(SS)';
RawCov = (SS'*SS)/(slen-1)-RawMu*RawMu'*slen/(slen-1);
% Compute spike-triggered mean and covariance
iisp = find(sp>0);
spvec = sp(iisp);
STA = (spvec'*SS(iisp,:))'/spsum;
STC = SS(iisp,:)'*bsxfun(@times,SS(iisp,:),spvec)/(spsum-1) ...
- STA*(STA'*spsum/(spsum-1));
else % Compute Full Stim matrix in chunks, compute mean and cov on chunks
nchunk = ceil(Msz/maxsize);
chunksize = ceil(slen/nchunk);
fprintf(1, 'simpleSTC: using %d chunks to compute covariance\n', nchunk);
% Compute statistics on first chunk
SS = makeStimRows(Stim(1:chunksize+nkt-1,:),nkt,'valid'); % convert stimulus to "full" version
spvec = sp(1:chunksize);
iisp = find(spvec>0);
RawMu = sum(SS)';
RawCov = SS'*SS;
STA = (spvec(iisp)'*SS(iisp,:))';
STC = SS(iisp,:)'*bsxfun(@times,SS(iisp,:),spvec(iisp));
% add to mean and covariance for remaining chunks
for j = 2:nchunk;
i0 = chunksize*(j-1)+1; % starting index for chunk
imax = min(slen,chunksize*j); % ending index for chunk
SS = makeStimRows(Stim(i0:imax+nkt-1,:),nkt,'valid');
spvec = sp(i0:imax);
iisp = find(spvec);
RawMu = RawMu + sum(SS)';
RawCov = RawCov +SS'*SS;
STA = STA + (spvec(iisp)'*SS(iisp,:))';
STC = STC + SS(iisp,:)'*bsxfun(@times,SS(iisp,:),spvec(iisp));
end
% divide means and covariances by number of samples
RawMu = RawMu/slen;
RawCov = RawCov/(slen-1) - RawMu*RawMu'*slen/(slen-1);
STA = STA/spsum;
STC = STC/(spsum-1) - STA*STA'*spsum/(spsum-1);
end
end
STA = reshape(STA,[],swid); % reshape to have same width as stimulus
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/makeSimStruct_GLM.m | .m | 3,025 | 70 | function S = makeSimStruct_GLM(nkt,dtStim,dtSp)
% S = makeSimStruct_GLM(nkt,dtStim,dtSp);
%
% Creates a structure with default parameters for a GLM model
%
% Input: nkt = number of time bins for stimulus filter
% dtStim = bin size for sampling of stimulus kernel ('ih'), in s
% dtSp = bin size for sampling post-spike kernel ('k'), in s
% (should evenly divde dtStim)
%
% Struct fields (model params):
% 'filt' - stimulus filter
% 'nlfun' - nonlinearity (exponential by default)
% 'dc' - dc input to cell
% 'ih' - post-spike current
% 'ihbas' - basis for post-spike current
% 'iht' - time lattice for post-spike current
% 'dtsim' - default time bin size for simulation
% 'ihbasprs' - basis for post-spike current
% Check that stimulus bins bigger than spike bins
assert (dtStim>=dtSp, 'dtStim must be >= dtSp');
% Check that spike bin size evenly divides stimulus bin size
if mod(dtStim,dtSp)~=0
warning('makeSimStruct_GLM: dtSp doesn''t evenly divide dtStim: rounding dtSp to nearest even divisor');
dtSp = dtStim/round(dtStim/dtSp);
fprintf('dtSp reset to: %.3f\n', dtSp);
end
% Create a default (temporal) stimulus filter
tk = (0:nkt-1)'; % time indices for made-up filter
b1 = nkt/32; b2 = nkt/16;
k1 = 1/(gamma(6)*b1)*(tk/b1).^5 .* exp(-tk/b1); % Gamma pdfn
k2 = 1/(gamma(6)*b2)*(tk/b2).^5 .* exp(-tk/b2); % Gamma pdf
k = flipud(k1-k2./1.5+1e-5);
k = k./norm(k)/2;
% % ----- Represent this filter (approximately) in temporal basis -------
ktbasprs.neye = min(5,nkt); % Number of "identity" basis vectors near time of spike;
ktbasprs.ncos = min(5,nkt); % Number of raised-cosine vectors to use
ktbasprs.kpeaks = [0 ((nkt-ktbasprs.neye)/2)]; % Position of 1st and last bump
ktbasprs.b = 1; % Offset for nonlinear scaling (larger -> more linear)
ktbas = makeBasis_StimKernel(ktbasprs,nkt);
k = ktbas*(ktbas\k);
% -- Nonlinearity -------
nlinF = @expfun;
% Other natural choice: nlinF = @(x)log(1+exp(x));
% --- Make basis for post-spike (h) filter ------
ihbasprs.ncols = 5; % Number of basis vectors for post-spike kernel
ihbasprs.hpeaks = [dtSp dtSp*50]; % Peak location for first and last vectors
ihbasprs.b = dtSp*5; % Determines how nonlinear to make spacings
ihbasprs.absref = []; % absolute refractory period (optional)
[iht,~,ihbasis] = makeBasis_PostSpike(ihbasprs,dtSp);
ih = ihbasis*[-10 .5 1 .25 -1]'; % h current
% Place parameters in structure
S = struct(...
'k', 2*k, ... % stimulus filter
'nlfun', nlinF, ... % nonlinearity
'dc', 1.5, ... % dc input (constant)
'ih', ih, ... % post-spike current
'iht', iht, ... % time indices of aftercurrent
'dtStim', dtStim,... % time bin size for stimulus (s)
'dtSp', dtSp, ... % time bin size for spikes (s)
'ihbasprs', ihbasprs, ... % params for ih basis
'ktbasprs', ktbasprs); % params for k time-basis | MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/sameconv.m | .m | 1,679 | 58 | function Y = sameconv(X, F)
% SAMECONV - causally filters X with F and returns output of same height
%
% Y = sameconv(X, F)
%
% F is not "flipped", so first element of Y is last row of F dot product with
% first row of X.
%
% Inputs:
% X [NxM] - tall matrix
% F [RxM] - short matrix (same width as X)
%
% Output:
% Y [Nx1] - X filtered causally with F.
% (first element is F(end,:)*X(1,:)' )
%
% Attempts to use fastest method based on length and width of F.
% (i.e., using either matrix arithmetic or matlab's "conv2").
%
% ex) sameconv(+- 0 0 -+, +- 1 4 -+) --> +- 0 -+
% | 1 0 | | 2 5 | | 3 |
% | 0 0 | +- 3 6 -+ | 2 |
% | 0 0 | | 1 |
% | 0 0 | | 0 |
% | 0 1 | | 6 |
% +- 0 0 -+ +- 5 -+
%
% (updated: 14/03/2011 JW Pillow)
%
% Copyright 2011 Pillow Lab.
% $Id$
[nx, xwid] = size(X);
[nf, fwid] = size(F);
assert(xwid == fwid, 'X and F must have same second dimension');
% Decide which method to use based on size of F
if log2(nf)+3>2*log2(fwid)
% Use CONV2 if F is tall and skinny
% conv2 doesn't take sparse matrix
if issparse(X); X = full(X); end
if issparse(F); F = full(F); end
Y = conv2([zeros(nf-1,xwid); X], rot90(F,2), 'valid');
else
% Use Matrix Operations if F is short and fat.
ny = nx+nf-1; % # of columns in full convolution
Y = zeros(ny,1);
yy = X*F';
for j = 1:nf
Y(j:j+nx-1) = Y(j:j+nx-1) + yy(:,nf-j+1);
end
% Extract only the first part
Y = Y(1:nx,:);
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_misc/makeSimStruct_GLMcpl.m | .m | 2,094 | 89 | function S = makeSimStruct_GLMcpl(varargin);
% S = makeSimStruct_GLMcpl(gg1, gg2, gg3, ...);
%
% Creates a structure for simulating coupled GLM from multiple
% single-neuron GLMs.
%
% Input: structures params of glms to combine
ncells = nargin;
gg = varargin{1};
[klen,kwid] = size(gg.k);
kk = zeros(klen,kwid,ncells); % Stimulus filters
nh = length(gg.iht);
ih = zeros(nh,ncells,ncells); % post-spike & coupling kernels
ihflag = 0; % Check for spike-history kernel
if ~isempty(gg.ih), ihflag = 1; end
ih2flag = 0; % Check for presence of coupling kernels
if size(gg.ih,2)>1
ih2flag = 1; end
if isfield(gg, 'ih2'); if ~isempty(gg.ih2);
ih2flag = 1; end; end
ihbasflag = 0; % Basis for history kernel?
if isfield(gg, 'ihbas'); if ~isempty(gg.ihbas)
ihbasflag = 1; end; end
ihbas2flag=0; % Distinct basis for coupling kernels?
if isfield(gg, 'ihbas2'); if ~isempty(gg.ihbas2)
ihbas2flag = 1; end; end
% Add cells to single param structure
nltestvals = [0, 1, 2];
for j = 1:ncells
gg = varargin{j};
kk(:,:,j) = gg.k;
dc(j) = gg.dc;
if isfield(gg, 'nlfun')
nlfuns{j} = gg.nlfun;
else
nlfuns{j} = @exp;
end
NLtst(j,:) = nlfuns{j}(nltestvals);
if ihflag % Post-spike kernel
if ihbasflag
ih(:,j,j) = gg.ihbas*gg.ih(:,1);
else
ih(:,j,j) = gg.ih(:,1);
end
end
if ih2flag % Coupling kernels
if ihbas2flag
ih(:,setdiff(1:ncells,j),j) = gg.ihbas2*gg.ih2;
elseif ihbasflag
ih(:,setdiff(1:ncells,j),j) = gg.ihbas*gg.ih(:,2:end);
else
ih(:,setdiff(1:ncells,j),j) = gg.ih(:,2:end);
end
end
end
S.k = kk;
S.dc = dc;
S.ih = ih;
S.iht = varargin{1}.iht;
S.dtStim = varargin{1}.dtStim;
S.dtSp = varargin{1}.dtSp;
if all(min(NLtst)==max(NLtst))
S.nlfun = nlfuns{1};
else
S.nlfun = @(x)multiNLfun(x,nlfuns);
end
if isfield(gg,'ihbasprs')
S.ihbasprs = gg.ihbasprs;
end
if isfield(gg,'ihbasprs2')
S.ihbasprs2 = gg.ihbasprs2;
end
| MATLAB |
2D | pillowlab/GLMspiketools | demos/demo5_GLM_10CoupledNeurons.m | .m | 8,057 | 205 | % testscript3_GLM_coupled.m
%
% Demo script for simulating and fitting a coupled GLM (2 neurons).
%
% Notes:
% - Fitting code uses same functions as for single-cell responses.
% - Simulation code requires new structures / functions
% (due to the need to pass activity between neurons)
% Make sure paths are set (assumes this script called from 'demos' directory)
cd ..; setpaths_GLMspiketools; cd demos/
%% ===== 1. Set parameters for simulating a GLM ============ %
dtStim = .001; % Bin size for simulating model & computing likelihood (in units of stimulus frames)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
nkt = 1; % Number of time bins in stimulus filter k %% FIX THIS SO IT DOESN'T MAKE NAN
gg = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM struct with default params
%% Set up basis for coupling filters
% Make basis for self-coupling term
ihbasprs.ncols = 3; % number of basis vectors
ihbasprs.hpeaks = [.001, .005]; % peak of 1st and last basis vector
ihbasprs.b = .001; % scaling (smaller -> more logarithmic scaling)
ihbasprs.absref = []; % absolute refractory period basis vector (optional)
% Make basis
[iht,ihbas,ihbasis] = makeBasis_PostSpike(ihbasprs,dtSp);
nht = length(iht); % number of bins
% Make basis for cross-coupling term
ihbasprs2.ncols = 1; % number of basis vectors
ihbasprs2.hpeaks = [0.001,.005]; % put peak at 5ms and "effective" 1st peak at 0
ihbasprs2.b = .001; % smaller -> more logarithmic scaling
ihbasprs2.absref = []; % no abs-refracotry period for this one
% Make basis
[iht2,ihbas2,ihbasis2] = makeBasis_PostSpike(ihbasprs2,dtSp);
nht2 = length(iht2);
% pad to put them into the same time bins
if nht2>nht
% padd ih1 with zeros
iht = iht2; zz = zeros(nht2-nht,ihbasprs.ncols);
ihbas = [ihbas;zz]; ihbasis = [ihbasis;zz]; nht=nht2;
elseif nht2<nht
% padd ih1 with zeros
iht2 = iht; zz = zeros(nht-nht2,ihbasprs2.ncols);
ihbas2 = [ihbas2;zz]; ihbasis2 = [ihbasis2;zz]; nht2=nht;
end
% plot it
subplot(211);
plot(iht, ihbasis, ihbasprs.hpeaks, 1, '*', 'linewidth', 2);
xlabel('time after spike (ms)'); title('post-spike basis');
subplot(212);
plot(iht2, ihbasis2, ihbasprs2.hpeaks, 1, '*', 'linewidth', 2);
xlabel('time after spike (ms)'); title('coupling basis');
%% Set self-coupling filter shapes
wself = [-10; 3.2; -1]; % weights for self-coupling term
ihself = ihbasis*wself; % self-coupling filter
wcpl = 0.5; % weights for cross-coupling term
ihcpl = ihbasis2*wcpl; % cross-coupling filter
clf; plot(iht, exp(ihself), iht, exp(ihcpl), iht, iht*0+1, 'k--');
legend('self-coupling', 'cross-coupling');
xlabel('time lag (s)');
ylabel('gain (sp/s)');
%% Set up multi-neuron GLM
nneur = 10;
k = randn(10,1)*0.5; % stimulus weights
gg.k = permute(k,[2,3,1]); % stimulus weights
gg.dc = 2+(rand(1,nneur)-0.5);
% Generate random coupling strengths
WW = randn(nneur); % coupling strengths
WW = WW-diag(diag(WW)-1); % set diagonal to zero (for self-coupling)
gg.iht = iht;
gg.ih = zeros(nht,nneur,nneur);
% Insert coupling filters
for jj = 1:nneur
gg.ih(:,:,jj) = ihcpl*WW(jj,:); % cross-coupling input weights to neuron jj
gg.ih(:,jj,jj) = ihself*WW(jj,jj); % self-coupling weights
end
% Plot filters
lw = 2; % linewidth
subplot(131);
plot(gg.iht, gg.ih(:,:,1),gg.iht,gg.iht*0, 'k--', 'linewidth', lw);
title('incoming filters: cell 1');
subplot(132);
plot(gg.iht, gg.ih(:,:,2),gg.iht,gg.iht*0, 'k--', 'linewidth', lw);
title('incoming filters: cell 2');
subplot(133);
plot(gg.iht, gg.ih(:,:,3),gg.iht,gg.iht*0, 'k--', 'linewidth', lw);
%% ===== 2. Run short simulation for visualization purposes ========= %
slen = 200; % Stimulus length (frames) & width (# pixels)
swid = 1; % width of stimulus
stimsd = 1; % contrast of stimulus
Stim = stimsd*randn(slen,swid); % Gaussian white noise stimulus
[tsp,~,Itot,Istm] = simGLM(gg, Stim); % Simulate GLM response
Isp = Itot-Istm; % net spike-history output
% ==== Plot some traces of simulated response ========
tt = (dtSp:dtSp:slen*dtStim)';
subplot(131) % % ==== neuron 1 ===========
plot(tt, Istm(:,1), 'k', tt, Isp(:,1), 'r', tt, tt*0, 'k--', ...
tsp{1}, ones(size(tsp{1})), 'ro');
title('cell 1'); axis tight;
xlabel('time (s)'); ylabel('filter output');
legend('stim filter + dc', 'spike-hist filter');
subplot(132) % ==== neuron 2 ===========
plot(tt, Istm(:,2), 'k', tt, Isp(:,2), 'r', tt, tt*0, 'k--', ...
tsp{2}, ones(size(tsp{2})), 'ro');
title('cell 2'); axis tight;
xlabel('time (s)');
subplot(133) % ==== neuron 3 ===========
plot(tt, Istm(:,3), 'k', tt, Isp(:,3), 'r', tt, tt*0, 'k--', ...
tsp{3}, ones(size(tsp{3})), 'ro');
title('cell 3'); axis tight;
xlabel('time (s)');
%% ===== 3. Generate some training data =============================== %%
slen = 5e5; % Stimulus length (in bins);
Stim = stimsd*randn(slen,swid); % Gaussian white noise stimulus
[tsp,sps,Itot,ispk] = simGLM(gg,Stim); % run model
%% ===== 4. Do ML fitting for all neurons in a loop =================== %%
% Initialize param struct for fitting
ggInit = makeFittingStruct_GLM(dtStim,dtSp); % Initialize params for fitting struct
% Initialize fields (using h bases computed above)
ggInit.ktbas = 1; % k basis
ggInit.ihbas = ihbas; % h self-coupling basis
ggInit.ihbas2 = ihbas2; % h coupling-filter basis
nktbasis = 1; % number of basis vectors in k basis
nhbasis = size(ihbas,2); % number of basis vectors in h basis
nhbasis2 = size(ihbas2,nneur-1); % number of basis vectors in h basis
ggInit.kt = 1; % initial params from scaled-down sta
ggInit.k = 1; % initial setting of k filter
ggInit.ihw = zeros(nhbasis,1); % init params for self-coupling filter
ggInit.ihw2 = zeros(nhbasis2,nneur-1); % init params for cross-coupling filter
ggInit.ih = [ggInit.ihbas*ggInit.ihw ggInit.ihbas2*ggInit.ihw2];
ggInit.iht = iht;
ggInit.dc = 0; % Initialize dc term to zero
ggInit.sps = sps(:,1); % spikes from 1 cell
ggInit.sps2 = sps(:,2:nneur); % spikes from all
ggInit.couplednums = 2:nneur; % cell numbers of cells coupled to this one
ggfit(1:nneur) = ggInit; % initialize fitting struct
kfit = zeros(nneur,1);
dcfit = zeros(nneur,1);
for jj = 1:nneur
couplednums = setdiff(1:nneur,jj); % cell numbers of cells coupled to this one
% Set spike responses for cell 1 and coupled cell
ggInit.sps = sps(:,jj);
ggInit.sps2 = sps(:,couplednums);
ggInit.couplednums = couplednums; % number of cell coupled to this one (for clarity)
% Do ML fitting
fprintf('==== Fitting filters to neuron %d ==== \n', jj)
opts = {'display', 'iter', 'maxiter', 100};
ggfit(jj) = MLfit_GLM(ggInit,Stim,opts); % do ML fitting
kfit(jj) = ggfit(jj).k;
dcfit(jj) = ggfit(jj).dc;
end
%% ===== 5. Plot true and fitted params for first few cells ============================================= %%
clf reset; colors = get(gca,'colororder');
ncolrs = size(colors,1); % number of traces to plot for each cell
ymax = max(exp([ggfit(1).ih(:);ggfit(2).ih(:);ggfit(3).ih(:);gg.ih(:)])); % max of y range
for jj = 1:10
subplot(2,5,jj); % --Spike filters cell 1 % -------------
ccpl = setdiff(1:nneur,jj); % coupled cells
cnums = [jj, ccpl];
plot(gg.iht, exp(gg.ih(:,cnums(1:ncolrs),jj)), ggfit(jj).iht, exp(ggfit(jj).ih(:,1:ncolrs)), '--', 'linewidth', lw);
hold on; plot(gg.iht, gg.iht*0+1, 'k'); hold off;
title(sprintf('cell %d filters',jj)); axis tight; set(gca,'ylim',[0,ymax]);
if jj==1
ylabel('gain (sp/s)'); xlabel('time after spike (s)');
end
end
% Print true and recovered params:
fprintf('\n---------------------------------\n');
fprintf('k: true est | dc: true est\n');
fprintf('---------------------------------\n');
for jj = 1:nneur
fprintf(' %5.2f %5.2f %5.2f %5.2f\n', [gg.k(jj), kfit(jj), gg.dc(jj), dcfit(jj)]);
end
| MATLAB |
2D | pillowlab/GLMspiketools | demos/demo2_GLM_spatialStim.m | .m | 6,074 | 157 | % demo2_GLM_spatialStim.m
%
% Test code for simulating and fitting the GLM with a 2D stimulus filter
% (time x 1D space), with both traditional and bilinear parametrization
% of the stimulus kernel.
% Make sure paths are set (assumes this script called from 'demos' directory)
cd ..; setpaths_GLMspiketools; cd demos/
%% 1. Set parameters and display for GLM ============= %
dtStim = .01; % Bin size for stimulus (in seconds). (Equiv to 100Hz frame rate)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
% Make a temporal filter
nkt = 20; % Number of time bins in stimulus filter k
kt = (normpdf(1:nkt,3*nkt/4,1.5)-.5*normpdf(1:nkt,nkt/2,3))';
% Make a spatial filter;
nkx = 10;
xxk = (1:1:nkx)'; % pixel locations
ttk = dtStim*(-nkt+1:0)'; % time bins for filter
kx = 1./sqrt(2*pi*4).*exp(-(xxk-nkx/2).^2/5);
k = kt*kx'; % Make space-time separable filter
k = k./norm(k(:))/1.5;
% Insert into glm structure (created with default history filter)
ggsim = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM structure with default params
ggsim.k = k; % Insert into simulation struct
ggsim.dc = 2;
% === Make Fig: model params =======================
clf; subplot(3,3,[1 4]); % ------------------------------------------
plot(kt,ttk); axis tight;
set(gca, 'ydir', 'reverse'); ylabel('time (frames)');
subplot(3,3,[2 3 5 6]); % --------------------------------------
imagesc(xxk,ttk,ggsim.k);
colormap gray; axis off;
title('stimulus kernel k');
subplot(3,3,8:9); % ----------------------------------------
plot(xxk,kx); axis tight;
set(gca, 'xlim', [.5 nkx+.5]); xlabel('space (pixels)');
%% 2. Generate some training data ========================================
slen = 10000; % Stimulus length (frames); More samples gives better fit
Stim = round(rand(slen,nkx))*2-1; % Run model on long, binary stimulus
[tsp,sps,Itot,Istm] = simGLM(ggsim,Stim); % run model
nsp = length(tsp);
% --- Make plot of first 0.5 seconds of data --------
tlen = 0.5;
ttstim = dtStim:dtStim:tlen; iistim = 1:length(ttstim);
ttspk = dtSp:dtSp:tlen; iispk = 1:length(ttspk);
spinds = sps(iispk)>0;
subplot(311);
imagesc([0 tlen], [1 nkx], Stim(iistim,:)');
title('stimulus'); ylabel('pixel');
subplot(312);
semilogy(ttspk,exp(Itot(iispk)),ttspk(spinds), exp(Itot(spinds)), 'ko');
ylabel('spike rate (sp/s)');
title('conditional intensity (and spikes)');
subplot(313);
Isp = Itot-Istm; % total spike-history filter output
plot(ttspk,Istm(iispk), ttspk,Isp(iispk)); axis tight;
legend('k output', 'h output'); xlabel('time (s)');
ylabel('log intensity'); title('filter outputs');
%% 3. Fit GLM (traditional version) via max likelihood
% Compute the STA
sps_coarse = sum(reshape(sps,[],slen),1)'; % bin spikes in bins the size of stimulus
sta0 = simpleSTC(Stim,sps_coarse,nkt); % Compute STA
sta = reshape(sta0,nkt,[]); % reshape it to match dimensions of true filter
exptmask= []; % Not currently supported!
% Initialize params for fitting --------------
% Set params for fitting, including bases
nkbasis = 8; % number of basis vectors for representing k
nhbasis = 8; % number of basis vectors for representing h
hpeakFinal = .1; % time of peak of last basis vector for h
gg0 = makeFittingStruct_GLM(dtStim,dtSp,nkt,nkbasis,sta,nhbasis,hpeakFinal);
gg0.sps = sps; % Insert binned spike train into fitting struct
gg0.mask = exptmask; % insert mask (optional)
gg0.ihw = randn(size(gg0.ihw))*1; % initialize spike-history weights randomly
% Compute conditional intensity at initial parameters
[negloglival0,rr] = neglogli_GLM(gg0,Stim);
fprintf('Initial negative log-likelihood: %.5f\n', negloglival0);
% Do ML estimation of model params
opts = {'display', 'iter', 'maxiter', 100};
[gg1, negloglival1a] = MLfit_GLM(gg0,Stim,opts); % do ML (requires optimization toolbox)
%% 4. Fit GLM ("bilinear stim filter version") via max likelihood
% Initialize params for fitting --------------
k_rank = 1; % Number of column/row vector pairs to use
gg0b = makeFittingStruct_GLMbi(k_rank,dtStim,dtSp,nkt,nkbasis,sta,nhbasis,hpeakFinal);
gg0b.sps = sps;
gg0b.mask = exptmask;
logli0b = neglogli_GLM(gg0b,Stim); % Compute logli of initial params
fprintf('Initial value of negative log-li (GLMbi): %.3f\n', logli0b);
% Do ML estimation of model params
opts = {'display', 'iter'};
[gg2, negloglival2] = MLfit_GLMbi(gg0b,Stim,opts); % do ML (requires optimization toolbox)
%% 5. Plot results ====================
%figure(3);
subplot(231); % True filter % ---------------
imagesc(ggsim.k); colormap gray;
title('True Filter');ylabel('time');
subplot(232); % sta % ------------------------
imagesc(sta);
title('raw STA'); ylabel('time');
subplot(233); % sta-projection % ---------------
imagesc(gg0.k); title('low-rank STA');
subplot(234); % estimated filter % ---------------
imagesc(gg1.k); title('ML estimate: full filter'); xlabel('space'); ylabel('time');
subplot(235); % estimated filter % ---------------
imagesc(gg2.k); title('ML estimate: bilinear filter'); xlabel('space');
subplot(236); % ----------------------------------
plot(ggsim.iht,exp(ggsim.ih),'k', gg1.iht,exp(gg1.ihbas*gg1.ihw),'b',...
gg2.iht, exp(gg2.ihbas*gg2.ihw), 'r'); axis tight;
title('post-spike kernel'); xlabel('time after spike (s)');
legend('true','GLM','bilinear GLM');
% Errors in STA and ML estimate
ktmu = normalizecols([mean(ggsim.k,2),mean(gg1.k,2),mean(gg2.k,2)]);
kxmu = normalizecols([mean(ggsim.k)',mean(gg1.k)',mean(gg2.k)']);
msefun = @(k)(sum((k(:)-ggsim.k(:)).^2)); % error function
fprintf(['K-filter errors (GLM vs. GLMbilinear):\n', ...
'Temporal error: %.3f %.3f\n', ...
' Spatial error: %.3f %.3f\n', ...
' Total error: %.3f %.3f\n'], ...
subspace(ktmu(:,1),ktmu(:,2)), subspace(ktmu(:,1),ktmu(:,3)), ...
subspace(kxmu(:,1),kxmu(:,2)), subspace(kxmu(:,1),kxmu(:,3)), ...
msefun(gg1.k), msefun(gg2.k));
| MATLAB |
2D | pillowlab/GLMspiketools | demos/demo1_GLM_temporalStim.m | .m | 4,719 | 116 | % demo1_GLM_temporalStim.m
%
% Demo script for simulating and fitting a single-neuron GLM with 1D
% (temporal) filter with exponential nonlinearity
% Make sure paths are set (assumes this script called from 'demos' directory)
cd ..; setpaths_GLMspiketools; cd demos/
%% 1. Set parameters and display for GLM % =============================
dtStim = .01; % Bin size for stimulus (in seconds). (Equiv to 100Hz frame rate)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
nkt = 30; % Number of time bins in stimulus filter k
ggsim = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM structure with default params
% === Plot true model params =======================
clf;
ttk = dtStim*(-nkt+1:0)'; % time relative to spike of stim filter taps
subplot(221);plot(ttk, ggsim.k);
title('stimulus kernel'); xlabel('time (s)');
subplot(222); % --------
plot(ggsim.iht, ggsim.iht*0, 'k--', ggsim.iht, ggsim.ih);
title('post-spike kernel h'); axis tight;
xlabel('time after spike (s)');
set(gca, 'ylim',[min(ggsim.ih)*1.1 max(ggsim.ih)*1.5]);
subplot(224); % --------
[iht,ihbasOrthog,ihbasis] = makeBasis_PostSpike(ggsim.ihbasprs,dtSp);
plot(ggsim.iht, ihbasis); title('basis for h'); axis tight;
%% 2. Generate some training data %========================================
slen = 50000; % Stimulus length (frames); more samples gives better fit
swid = 1; % Stimulus width (pixels); must match # pixels in stim filter
% Make stimulus
Stim = rand(slen,swid)*2-1; % Stimulate model to long, unif-random stimulus
% Simulate model
[tsp,sps,Itot,Istm] = simGLM(ggsim,Stim); % run model
% --- Make plot of first 0.5 seconds of data --------
tlen = 0.5;
ttstim = dtStim:dtStim:tlen; iistim = 1:length(ttstim);
subplot(311);
plot(ttstim,Stim(iistim));
title('stimulus');
subplot(312);
ttspk = dtSp:dtSp:tlen; iispk = 1:length(ttspk);
spinds = sps(iispk)>0;
semilogy(ttspk,exp(Itot(iispk)),ttspk(spinds), exp(Itot(spinds)), 'ko');
ylabel('spike rate (sp/s)');
title('conditional intensity (and spikes)');
subplot(313);
Isp = Itot-Istm; % total spike-history filter output
plot(ttspk,Istm(iispk), ttspk,Isp(iispk)); axis tight;
legend('k output', 'h output'); xlabel('time (s)');
ylabel('log intensity'); title('filter outputs');
%% 3. Setup fitting params %===================================================
% Compute the STA
sps_coarse = sum(reshape(sps,[],slen),1)'; % bin spikes in bins the size of stimulus
sta = simpleSTC(Stim,sps_coarse,nkt); % Compute STA
sta = reshape(sta,nkt,[]); % reshape it to match dimensions of true filter
% Set mask (if desired)
exptmask= []; %[1 slen*dtStim]; % data range to use for fitting (in s).
% Set params for fitting, including bases
nkbasis = 8; % number of basis vectors for representing k
nhbasis = 8; % number of basis vectors for representing h
hpeakFinal = .1; % time of peak of last basis vector for h
gg0 = makeFittingStruct_GLM(dtStim,dtSp,nkt,nkbasis,sta,nhbasis,hpeakFinal);
gg0.sps = sps; % Insert binned spike train into fitting struct
gg0.mask = exptmask; % insert mask (optional)
gg0.ihw = randn(size(gg0.ihw))*1; % initialize spike-history weights randomly
% Compute conditional intensity at initial parameters
[negloglival0,rr] = neglogli_GLM(gg0,Stim);
fprintf('Initial negative log-likelihood: %.5f\n', negloglival0);
%% 4. Do ML fitting %=====================
opts = {'display', 'iter', 'maxiter', 100}; % options for fminunc
[gg1, negloglival] = MLfit_GLM(gg0,Stim,opts); % do ML (requires optimization toolbox)
%% 5. Plot results ======================================================
ttk = -nkt+1:0; % time bins for stimulus filter
subplot(221); % True filter
plot(ttk, ggsim.k, 'k', ttk, sta./norm(sta)*norm(ggsim.k), ttk, gg1.k, 'r');
title('Stim filters');
legend('k_{true}', 'k_{STA}', 'k_{ML}', 'location', 'northwest');
% ----------------------------------
subplot(222);
plot(ggsim.iht, ggsim.ih, gg1.iht, gg1.ih,'r', ggsim.iht, ggsim.iht*0, 'k--');
title('post-spike kernel');
axis tight;
legend('h_{true}', 'h_{ML}', 'location', 'southeast');
% ----------------------------------
subplot(224);
plot(ggsim.iht, exp(ggsim.ih), gg1.iht, exp(gg1.ih),'r', ggsim.iht,ggsim.iht*0+1,'k--');
title('exponentiated post-spike kernels');
xlabel('time since spike (s)');
ylabel('gain'); axis tight;
legend('h_{true}', 'h_{ML}', 'location', 'southeast');
% Errors in STA and ML estimate (subspace angle between true k and estimate)
fprintf('Filter estimation error (in radians)\n sta: %.3f\n ML: %.3f\n', ...
subspace(ggsim.k,sta), subspace(ggsim.k,gg1.k));
| MATLAB |
2D | pillowlab/GLMspiketools | demos/demo3_GLM_coupled.m | .m | 7,432 | 174 | % testscript3_GLM_coupled.m
%
% Demo script for simulating and fitting a coupled GLM (2 neurons).
%
% Notes:
% - Fitting code uses same functions as for single-cell responses.
% - Simulation code requires new structures / functions
% (due to the need to pass activity between neurons)
% Make sure paths are set (assumes this script called from 'demos' directory)
cd ..; setpaths_GLMspiketools; cd demos/
%% ===== 1. Set parameters and display for GLM ============ %
dtStim = .01; % Bin size for simulating model & computing likelihood (in units of stimulus frames)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
nkt = 20; % Number of time bins in stimulus filter k
ggsim1 = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM struct with default params
ggsim2 = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM struct with default params
% Change second neuron's stimulus filter
[ktbas,ktbasis] = makeBasis_StimKernel(ggsim2.ktbasprs,nkt);
ggsim2.k = ktbasis*[0 0 .1 .25 .5 .5 .25 -.25 -.5 -.25]'; % more delayed filter
ggsim = makeSimStruct_GLMcpl(ggsim1,ggsim2);
% Make some coupling kernels
[iht,ihbas,ihbasis] = makeBasis_PostSpike(ggsim.ihbasprs,dtSp);
hhcpl = ihbasis*[.25;.25;.125;0;0];
hhcpl(:,2) = ihbasis*[-2;-1;0;.25;.25];
ggsim.ih(:,2,1) = hhcpl(:,2); % 2nd cell coupling to first
ggsim.ih(:,1,2) = hhcpl(:,1); % 1st cell coupling to second
% === Make Fig: model params =======================
ttk = (-nkt+1:0)'*dtStim;
subplot(2,2,1); % -------------------------------
plot(ttk, ggsim.k(:,:,1));
title('neuron 1 stim kernel');
subplot(2,2,3); % -------------------------------
plot(ttk, ggsim.k(:,:,2));
title('neuron 2 stim kernel'); xlabel('time (frames)');
subplot(2,2,2); % --------------------------------
plot(ggsim.iht, exp(ggsim.ih(:,:,1)), ggsim.iht, ggsim.iht*0+1, 'k--');
title('spike kernels into Cell 1 (exponentiated)');
legend('from 1', 'from 2', 'location', 'northeast'); ylabel('gain');
subplot(2,2,4); % ---------------------------------
plot(ggsim.iht, exp(ggsim.ih(:,:,2)), ggsim.iht, ggsim.iht*0+1, 'k--');
title('spike kernels into Cell 2 (exponentiated)');
legend('from 1', 'from 2', 'location', 'northeast');
ylabel('gain'); xlabel('time after spike (frames)');
%% ===== 2. Run short simulation for visualization purposes ========= %
%
slen = 50; % Stimulus length (frames) & width (# pixels)
swid = size(ggsim.k,2); % stimulus width
Stim = 2*randn(slen,swid); % Gaussian white noise stimulus
[tsp,~,Itot,Istm] = simGLM(ggsim, Stim); % Simulate GLM response
Isp = Itot-Istm; % net spike-history output
% ==== Plot some traces of simulated response ========
tt = (dtSp:dtSp:slen*dtStim)';
subplot(321); %------------------------
plot(1:slen, Stim, 'k', 'linewidth', 2);
title('GWN stimulus'); axis tight;
subplot(3,2,3); %------------------------
plot(tt, Itot(:,1),'b',tsp{1}, max(Itot(:,1))*ones(size(tsp{1})), 'ro');
title('cell 1: net voltage + spikes');
axis([0 slen*dtStim, min(Itot(:,1)) max(Itot(:,1))*1.01]); ylabel('filter output');
subplot(3,2,4); %------------------------
plot(tt, Itot(:,2), 'b', tsp{2}, max(Itot(:,2))*ones(size(tsp{2})), 'ro');
title('cell 2: net voltage + spikes');
axis([0 slen*dtStim, min(Itot(:,2)) max(Itot(:,2))*1.01]);
subplot(325) % --------------------------
plot(tt, Istm(:,1), 'k', tt, Isp(:,1), 'r');
title('stim-induced & spike-induced currents'); axis tight;
xlabel('time (frames)'); ylabel('filter output');
subplot(326); %---------------------------
plot(tt, Istm(:,2), 'k', tt, Isp(:,2), 'r');
title('stim-induced & spike-induced currents');
axis tight; xlabel('time (frames)');
%% ===== 3. Generate some training data =============================== %%
slen = 20000; % Stimulus length (frames); More samples gives better fit
Stim = round(rand(slen,swid))-.5; % Run model on long, binary stimulus
[tsp,sps,Itot,ispk] = simGLM(ggsim,Stim); % run model
%% ===== 4. Fit cell #1 (with coupling from cell #2) =================== %%
% Compute Spike-triggered averages
sps1 = sum(reshape(sps(:,1),[],slen),1)'; % bin spikes in bins the size of stimulus
sta1 = simpleSTC(Stim,sps1,nkt); % Compute STA 1
sta1 = reshape(sta1,nkt,[]);
sps2 = sum(reshape(sps(:,2),[],slen),1)'; % rebinned spike train
sta2 = simpleSTC(Stim,sps2,nkt); % Compute STA 2
sta2 = reshape(sta2,nkt,[]);
% Initialize param struct for fitting
gg0 = makeFittingStruct_GLM(dtStim,dtSp); % Initialize params for fitting struct
% Initialize fields (using h and k bases computed above)
gg0.ktbas = ktbas; % k basis
gg0.ihbas = ihbas; % h self-coupling basis
gg0.ihbas2 = ihbas; % h coupling-filter basis
nktbasis = size(ktbas,2); % number of basis vectors in k basis
nhbasis = size(ihbas,2); % number of basis vectors in h basis
gg0.kt = 0.1*(ktbas\sta1); % initial params from scaled-down sta
gg0.k = gg0.ktbas*gg0.kt; % initial setting of k filter
gg0.ihw = zeros(nhbasis,1); % params for self-coupling filter
gg0.ihw2 = zeros(nhbasis,1); % params for cross-coupling filter
gg0.ih = [gg0.ihbas*gg0.ihw gg0.ihbas2*gg0.ihw2];
gg0.iht = iht;
gg0.dc = 0; % Initialize dc term to zero
gg0.couplednums = 2; % cell numbers of cells coupled to this one
% Set spike responses for cell 1 and coupled cell
gg0.sps = sps(:,1);
gg0.sps2 = sps(:,2);
% Compute initial value of negative log-likelihood (just to inspect)
[neglogli0,rr] = neglogli_GLM(gg0,Stim);
% Do ML fitting
fprintf('Fitting neuron 1: initial neglogli0 = %.3f\n', neglogli0);
opts = {'display', 'iter', 'maxiter', 100};
[gg1, neglogli1] = MLfit_GLM(gg0,Stim,opts); % do ML (requires optimization toolbox)
%% ===== 5. Fit cell #2 (with coupling from cell #1) ==================
gg0b = gg0; % initial parameters for fitting
gg0b.sps = sps(:,2); % cell 2 spikes
gg0b.sps2 = sps(:,1); % spike trains from coupled cells
gg0.kt = 0.1*(ktbas\sta2); % initial params from scaled-down sta
gg0b.k = gg0b.ktbas*gg0b.kt; % Project STA onto basis for fitting
gg0.couplednums = 1; % number of cell coupled to this one
% Compute initial value of negative log-likelihood (just to inspect)
[neglogli0b] = neglogli_GLM(gg0b,Stim); % initial value of negative logli
% Do ML fitting
fprintf('Fitting neuron 2: initial neglogli = %.3f\n', neglogli0b);
[gg2, neglogli2] = MLfit_GLM(gg0b,Stim,opts); % do ML (requires optimization toolbox)
%% ===== 6. Plot fits ============================================= %%
ttk = (-nkt+1:0)*dtStim; % time indices for k
subplot(221); % Stim filters cell 1 % ---------------
plot(ttk, ggsim1.k(:,1), 'k', ttk, gg1.k, 'r');
title('Cell 1: k filter');
legend('true', 'estim', 'location', 'northwest');
subplot(223); % Stim filters cell 2 % ---------------
plot(ttk, ggsim2.k, 'k', ttk, gg2.k, 'r');
title('Cell 2: k filter');
xlabel('time (s)')
subplot(222); % --Spike filters cell 1 % -------------
plot(ggsim.iht, (ggsim.ih(:,:,1)), gg1.iht, (gg1.ih), '--');
title('exponentiated incoming h filters');
legend('true h11', 'true h21', 'estim h11', 'estim h21');
axis tight;
subplot(224); % --Spike filters cell 2 % -------------
plot(ggsim.iht, (ggsim.ih(:,:,2)), gg2.iht, (gg2.ih), '--');
title('exponentiated incoming h filters');
axis tight; xlabel('time (s)')
legend('true h22', 'true h12', 'estim h22', 'estim h12');
| MATLAB |
2D | pillowlab/GLMspiketools | demos/demo2b_GLM_spatialStim_Regularized.m | .m | 8,074 | 224 | % demo2b_GLM_spatialStim_Regularized.m
%
% Test code for simulating and fitting the GLM with a 2D stimulus filter
% (time x 1D space), regularized with a Gaussian prior.
% Make sure paths are set (assumes this script called from 'demos' directory)
cd ..; setpaths_GLMspiketools; cd demos/
%% 1. Set parameters and display for GLM ============= %
dtStim = .01; % Bin size for stimulus (in seconds). (Equiv to 100Hz frame rate)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
% Make a temporal filter
nkt = 20; % Number of time bins in stimulus filter k
kt = (normpdf(1:nkt,3*nkt/4,1.5)-.5*normpdf(1:nkt,nkt/2,3))';
% Make a spatial filter;
nkx = 10;
xxk = (1:1:nkx)'; % pixel locations
ttk = dtStim*(-nkt+1:0)'; % time bins for filter
kx = 1./sqrt(2*pi*4).*exp(-(xxk-nkx/2).^2/5);
ktrue = kt*kx'; % Make space-time separable filter
ktrue = ktrue./norm(ktrue(:));
% Insert into glm structure (created with default history filter)
ggsim = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM structure with default params
ggsim.k = ktrue; % Insert into simulation struct
ggsim.dc = 3;
% === Make Fig: model params =======================
clf; subplot(3,3,[1 4]); % ------------------------------------------
plot(kt,ttk); axis tight;
set(gca, 'ydir', 'reverse'); ylabel('time (frames)');
subplot(3,3,[2 3 5 6]); % --------------------------------------
imagesc(xxk,ttk,ggsim.k);
colormap gray; axis off;
title('stimulus kernel k');
subplot(3,3,8:9); % ----------------------------------------
plot(xxk,kx); axis tight;
set(gca, 'xlim', [.5 nkx+.5]); xlabel('space (pixels)');
%% 2. Generate some training data ========================================
% generate stimulus
slen = 10000; % Stimulus length (frames); More samples gives better fit
gfilt = normpdf(-3:3, 0, .8);
Stim = conv2(randn(slen,nkx),gfilt,'same'); % convolve in space
Stim = conv2(Stim,gfilt','same'); % convolve in time
[tsp,sps,Itot,Istm] = simGLM(ggsim,Stim); % run model
nsp = length(tsp);
rlen = length(sps);
% --- Make plot of first 0.5 seconds of data --------
tlen = 0.5;
ttstim = dtStim:dtStim:tlen; iistim = 1:length(ttstim);
ttspk = dtSp:dtSp:tlen; iispk = 1:length(ttspk);
spinds = sps(iispk)>0;
subplot(311);
imagesc([0 tlen], [1 nkx], Stim(iistim,:)');
title('stimulus'); ylabel('pixel');
subplot(312);
semilogy(ttspk,exp(Itot(iispk)),ttspk(spinds), exp(Itot(spinds)), 'ko');
ylabel('spike rate (sp/s)');
title('conditional intensity (and spikes)');
subplot(313);
Isp = Itot-Istm; % total spike-history filter output
plot(ttspk,Istm(iispk), ttspk,Isp(iispk)); axis tight;
legend('k output', 'h output'); xlabel('time (s)');
ylabel('log intensity'); title('filter outputs');
%% 3. Fit GLM with max likelihood
% Compute the STA
sps_coarse = sum(reshape(sps,[],slen),1)'; % bin spikes in bins the size of stimulus
sta0 = simpleSTC(Stim,sps_coarse,nkt); % Compute STA
sta = reshape(sta0,nkt,[]); % reshape it to match dimensions of true filter
exptmask= []; % Not currently supported!
% Initialize params for fitting --------------
% Set params for fitting, including bases
nkbasis = 8; % number of basis vectors for representing k
nhbasis = 8; % number of basis vectors for representing h
hpeakFinal = .1; % time of peak of last basis vector for h
gg0 = makeFittingStruct_GLM(dtStim,dtSp,nkt,nkbasis,sta,nhbasis,hpeakFinal);
gg0.sps = sps; % Insert binned spike train into fitting struct
gg0.mask = exptmask; % insert mask (optional)
gg0.ihw = randn(size(gg0.ihw))*1; % initialize spike-history weights randomly
% Compute conditional intensity at initial parameters
[negloglival0,rr] = neglogli_GLM(gg0,Stim);
fprintf('Initial negative log-likelihood: %.5f\n', negloglival0);
% Do ML estimation of model params
opts = {'display', 'iter', 'maxiter', 1000};
[gg1, negloglival1] = MLfit_GLM(gg0,Stim,opts); % do ML (requires optimization toolbox)
%% 4. Fit GLM with iid Gaussian ("ridge regression") prior.
% Divide data into training and test
trainfrac = 0.8;
ntrain = ceil(trainfrac*slen);
ntrainsps = ceil(trainfrac*rlen);
stimtrain = Stim(1:ntrain,:); stimtest = Stim(ntrain+1:end,:);
spstrain = sps(1:ntrainsps); spstest = sps(ntrainsps+1:end);
% Set prior covariance matrix ---------------
nparams = numel(gg0.kt);
Ceye = speye(nparams);
% Make grid of lambda (ridge parameter) values -----
lamvals = 2.^(-1:10);
nlam = length(lamvals);
testlogli = zeros(nlam,1);
trainlogli = zeros(nlam,1);
ggridge = cell(nlam,1);
% Initialize params --------
gg0_train = gg0;
gg0_train.sps = spstrain;
% Find MAP estimate for each value of ridge parameter
fprintf('====Doing grid search for ridge parameter====\n');
for jj = 1:nlam
fprintf('lambda = %.1f\n',lamvals(jj));
Cinv = lamvals(jj)*Ceye; % inverse covariance of prior
% Do MAP estimation of model params
[ggridge{jj}, negloglival] = MAPfit_GLM(gg0_train,stimtrain,Cinv,opts); % do ML (requires optimization toolbox)
trainlogli(jj) = -negloglival;
% Compute test log-likelihood
gg2tst = ggridge{jj};
gg2tst.sps = spstest;
testlogli(jj) = -neglogli_GLM(gg2tst,stimtest);
end
% Plot test log likelihood
clf; semilogx(lamvals,testlogli, '-o');
xlabel('lambda'); ylabel('test log-likelihood'); title('ridge prior');
% Select best ridge param and fit on all data.
[~,imax] = max(testlogli);
[gg2,neglogli2] = MAPfit_GLM(gg1,Stim,lamvals(imax)*Cinv,opts);
%% 5. Fit GLM with smoothing prior.
% Make matrices to compute column and row pairwise differences
Dx = spdiags(ones(nkx,1)*[-1 1],0:1,nkx-1,nkx);
Dt = spdiags(ones(nkt,1)*[-1 1],0:1,nkt-1,nkt);
Dtbas = Dt*gg1.ktbas;
Mt = kron(speye(nkx),Dtbas'*Dtbas); % computes squared diffs along columns
Mx = kron(Dx,gg1.ktbas); % computes squared diffs along row
Mx = Mx'*Mx;
C0 = Mt + Mx; % default covariance matrix
% Make grid of lambda (smoothing parameter) values -----
lamvals_sm = 2.^(0:13);
nlam = length(lamvals_sm);
testlogli_sm = zeros(nlam,1);
trainlogli_sm = zeros(nlam,1);
ggsmooth = cell(nlam,1);
% Find MAP estimate for each value of ridge parameter
for jj = 1:nlam
Cinv = lamvals_sm(jj)*C0; % inverse covariance of prior
% Do MAP estimation of model params
[ggsmooth{jj}, negloglival] = MAPfit_GLM(gg0_train,stimtrain,Cinv,opts); % do ML (requires optimization toolbox)
trainlogli_sm(jj) = -negloglival;
% Compute test log-likelihood
gg3tst = ggsmooth{jj};
gg3tst.sps = spstest;
testlogli_sm(jj) = -neglogli_GLM(gg3tst,stimtest);
end
% Plot test log likelihood
clf; semilogx(lamvals_sm,testlogli_sm, '-o');
xlabel('lambda'); ylabel('test log-likelihood'); title('smoothing prior');
% Select best ridge param and fit on all data.
[~,imax] = max(testlogli_sm);
[gg3,neglogli3] = MAPfit_GLM(gg2,Stim,lamvals_sm(imax)*C0,opts);
%% 6. Plot results ====================
subplot(231); % True filter % ---------------
imagesc(ggsim.k); colormap gray;
title('True Filter');ylabel('time');
subplot(232); % sta % ------------------------
imagesc(gg1.k);
title('ML estimate'); ylabel('time');
subplot(234); % sta-projection % ---------------
imagesc(gg2.k); title('MAP: ridge prior'); xlabel('space'); ylabel('time');
subplot(235); % estimated filter % ---------------
imagesc(gg3.k); title('MAP: smoothing prior'); xlabel('space');
subplot(236); % ----------------------------------
plot(ggsim.iht,exp(ggsim.ih),'k--', gg1.iht,exp(gg1.ihbas*gg1.ihw),...
gg2.iht, exp(gg2.ihbas*gg2.ihw), ...
gg3.iht, exp(gg3.ihbas*gg3.ihw) ...
); axis tight;
title('post-spike kernel'); xlabel('time after spike (s)');
legend('true','ML','ridge','smooth');
r2fun = @(k)(1-sum((k(:)-ktrue(:)).^2)./sum(ktrue(:).^2)); % error function
fprintf('\nK filter R^2:\n ----------\n ML = %9.3f\n Ridge = %6.3f\n Smooth = %4.3f\n',...
r2fun(gg1.k), r2fun(gg2.k),r2fun(gg3.k));
| MATLAB |
2D | pillowlab/GLMspiketools | demos/demo4_GLM_3CoupledNeurons.m | .m | 9,026 | 220 | % testscript3_GLM_coupled.m
%
% Demo script for simulating and fitting a coupled GLM (2 neurons).
%
% Notes:
% - Fitting code uses same functions as for single-cell responses.
% - Simulation code requires new structures / functions
% (due to the need to pass activity between neurons)
% Make sure paths are set (assumes this script called from 'demos' directory)
cd ..; setpaths_GLMspiketools; cd demos/
%% ===== 1. Set parameters for simulating a GLM ============ %
dtStim = .001; % Bin size for simulating model & computing likelihood (in units of stimulus frames)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
nkt = 1; % Number of time bins in stimulus filter k %% FIX THIS SO IT DOESN'T MAKE NAN
gg = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM struct with default params
%% Set up basis for self-coupling filters
% Make basis for self-coupling term
ihbasprs.ncols = 3; % number of basis vectors
ihbasprs.hpeaks = [.002, .005]; % peak of 1st and last basis vector
ihbasprs.b = .001; % scaling (smaller -> more logarithmic scaling)
ihbasprs.absref = .002; % absolute refractory period basis vector (optional)
% Make basis
[iht,ihbas,ihbasis] = makeBasis_PostSpike(ihbasprs,dtSp);
nht = length(iht); % number of bins
% Make basis for cross-coupling term
ihbasprs2.ncols = 1; % number of basis vectors
ihbasprs2.hpeaks = [0.001,.005]; % put peak at 10ms and "effective" 1st peak at 0
ihbasprs2.b = .002; % smaller -> more logarithmic scaling
ihbasprs2.absref = []; % no abs-refracotry period for this one
% Make basis
[iht2,ihbas2,ihbasis2] = makeBasis_PostSpike(ihbasprs2,dtSp);
nht2 = length(iht2);
% pad to put them into the same time bins, if necessary
if nht2>nht
% padd ih1 with zeros
iht = iht2; zz = zeros(nht2-nht,ihbasprs.ncols);
ihbas = [ihbas;zz]; ihbasis = [ihbasis;zz]; nht=nht2;
elseif nht2<nht
% padd ih1 with zeros
iht2 = iht; zz = zeros(nht-nht2,ihbasprs2.ncols);
ihbas2 = [ihbas2;zz]; ihbasis2 = [ihbasis2;zz]; nht2=nht;
end
% plot it
subplot(211);
plot(iht, ihbasis, ihbasprs.hpeaks, 1, '*', 'linewidth', 2);
xlabel('time after spike (ms)'); title('post-spike basis');
subplot(212);
plot(iht2, ihbasis2, ihbasprs2.hpeaks, 1, '*', 'linewidth', 2);
xlabel('time after spike (ms)'); title('coupling basis');
%% Set self-coupling weights
wself = [-5; .2; -.15]; % weights for self-coupling term
ihself = ihbasis*wself; % self-coupling filter
wcpl = 0.5; % weights for cross-coupling term
ihcpl = ihbasis2*wcpl; % cross-coupling filter
clf; plot(iht, exp(ihself), iht, exp(ihcpl), iht, iht*0+1, 'k--');
legend('self-coupling', 'cross-coupling');
xlabel('time lag (s)');
ylabel('gain (sp/s)');
%% Set up multi-neuron GLM
nneur = 3;
k = [.85 .9 0.7]; % stimulus weights
gg.k = permute(k,[1,3,2]); % stimulus weights
gg.iht = iht;
gg.ih = zeros(nht,nneur,nneur);
gg.ih(:,:,1) = [ihself, 1.25*ihcpl, -1*ihcpl]; % input weights to neuron 1
gg.ih(:,:,2) = [1.8*ihcpl, 1.5*ihself, -.5*ihcpl]; % input weights to neuron 2
gg.ih(:,:,3) = [1.5*ihcpl, .5*ihcpl, ihself]; % input weights to neuron 3
%% ===== 2. Run short simulation for visualization purposes ========= %
slen = 50; % Stimulus length (frames) & width (# pixels)
swid = 1; % width of stimulus
stimsd = 1; % contrast of stimulus
Stim = stimsd*randn(slen,swid); % Gaussian white noise stimulus
[tsp,~,Itot,Istm] = simGLM(gg, Stim); % Simulate GLM response
Isp = Itot-Istm; % net spike-history output
% ==== Plot some traces of simulated response ========
tt = (dtSp:dtSp:slen*dtStim)';
subplot(131) % % ==== neuron 1 ===========
plot(tt, Istm(:,1), 'k', tt, Isp(:,1), 'r', tt, tt*0, 'k--', ...
tsp{1}, ones(size(tsp{1})), 'ro');
title('cell 1'); axis tight;
xlabel('time (s)'); ylabel('filter output');
legend('stim filter + dc', 'spike-hist filter');
subplot(132) % ==== neuron 2 ===========
plot(tt, Istm(:,2), 'k', tt, Isp(:,2), 'r', tt, tt*0, 'k--', ...
tsp{2}, ones(size(tsp{2})), 'ro');
title('cell 2'); axis tight;
xlabel('time (s)');
subplot(133) % ==== neuron 3 ===========
plot(tt, Istm(:,3), 'k', tt, Isp(:,3), 'r', tt, tt*0, 'k--', ...
tsp{3}, ones(size(tsp{3})), 'ro');
title('cell 3'); axis tight;
xlabel('time (s)');
%% ===== 3. Generate some training data =============================== %%
slen = 2e5; % Stimulus length (in bins);
Stim = stimsd*randn(slen,swid); % Gaussian white noise stimulus
[tsp,sps,Itot,ispk] = simGLM(gg,Stim); % run model
%% ===== 4. Fit cell #1 (with coupling from cell #2 and #3) =================== %%
% Initialize param struct for fitting
gg1in = makeFittingStruct_GLM(dtStim,dtSp); % Initialize params for fitting struct
% Initialize fields (using h bases computed above)
gg1in.ktbas = 1; % k basis
gg1in.ihbas = ihbas; % h self-coupling basis
gg1in.ihbas2 = ihbas2; % h coupling-filter basis
nktbasis = 1; % number of basis vectors in k basis
nhbasis = size(ihbas,2); % number of basis vectors in h basis
nhbasis2 = size(ihbas2,2); % number of basis vectors in h basis
gg1in.kt = 1; % initial params from scaled-down sta
gg1in.k = 1; % initial setting of k filter
gg1in.ihw = zeros(nhbasis,1); % init params for self-coupling filter
gg1in.ihw2 = zeros(nhbasis2,nneur-1); % init params for cross-coupling filter
gg1in.ih = [gg1in.ihbas*gg1in.ihw gg1in.ihbas2*gg1in.ihw2];
gg1in.iht = iht;
gg1in.dc = 0; % Initialize dc term to zero
% Set fields for fitting cell #1
couplednums = [2 3]; % the cells coupled to this one
gg1in.couplednums = couplednums; % cell numbers of cells coupled to this one
gg1in.sps = sps(:,1); % Set spike responses for cell 1
gg1in.sps2 = sps(:,couplednums); % spikes from coupled cells
% Compute initial value of negative log-likelihood (just to inspect)
[neglogli0,rr] = neglogli_GLM(gg1in,Stim);
% Do ML fitting
fprintf('Fitting neuron 1: initial neglogli0 = %.3f\n', neglogli0);
opts = {'display', 'iter', 'maxiter', 100};
[gg1, neglogli1] = MLfit_GLM(gg1in,Stim,opts); % do ML (requires optimization toolbox)
%% ===== 5. Fit cell #2 (with coupling from cell #1 and #3) ==================
cellnum = 2;
couplednums = setdiff(1:3, cellnum); % the cells coupled to this one
gg2in = gg1in; % initial parameters for fitting
gg2in.sps = sps(:,cellnum); % cell 2 spikes
gg2in.sps2 = sps(:,couplednums); % spike trains from coupled cells
gg2in.couplednums = couplednums; % cells coupled to this one
% Do ML fitting
fprintf('Fitting neuron 2\n');
[gg2, neglogli2] = MLfit_GLM(gg2in,Stim,opts); % do ML (requires optimization toolbox)
%% ===== 6. Fit cell #3 (with coupling from cell #1 and #2) ==================
cellnum = 3;
couplednums = setdiff(1:3, cellnum);
gg3in = gg1in; % initial parameters for fitting
gg3in.sps = sps(:,cellnum); % cell 3 spikes
gg3in.sps2 = sps(:,couplednums); % spike trains from coupled cells
gg3in.couplednums = couplednums; % cells coupled to this one
% Do ML fitting
fprintf('Fitting neuron 3\n');
[gg3, neglogli3] = MLfit_GLM(gg3in,Stim,opts); % do ML (requires optimization toolbox)
%% ===== 6. Plot fits ============================================= %%
colors = get(gca,'colororder');
set(gcf,'defaultAxesColorOrder',colors(1:3,:)); % use only 3 colors
lw = 2; % linewidth
ymax = max(exp([gg1.ih(:);gg2.ih(:);gg3.ih(:);gg.ih(:)])); % max of y range
subplot(131); % --Spike filters cell 1 % -------------
plot(gg.iht, exp(gg.ih(:,:,1)), gg1.iht, exp((gg1.ih)), '--', 'linewidth', lw);
hold on; plot(gg.iht, gg.iht*0+1, 'k'); hold off;
legend('true h11', 'true h21', 'true h31', 'estim h11', 'estim h21', 'estim h31', 'location', 'southeast');
title('incoming filters: cell 1'); axis tight; set(gca,'ylim',[0,ymax]);
ylabel('gain (sp/s)'); xlabel('time after spike (s)');
subplot(132); % --Spike filters cell 2 % -------------
plot(gg.iht, exp(gg.ih(:,[2 1 3],2)), gg2.iht, exp(gg2.ih), '--', 'linewidth', lw);
hold on; plot(gg.iht, gg.iht*0+1, 'k'); hold off;
legend('true h22', 'true h12', 'true h32', 'estim h22', 'estim h12', 'estim h32', 'location', 'southeast');
title('cell 2'); axis tight; set(gca,'ylim',[0,ymax]);
subplot(133); % --Spike filters cell 3 % -------------
plot(gg.iht, exp(gg.ih(:,[3 1 2],3)), gg3.iht, exp(gg3.ih), '--', 'linewidth', lw);
hold on; plot(gg.iht, gg.iht*0+1, 'k'); hold off;
legend('true h33', 'true h13', 'true h23', 'estim h22', 'estim h13', 'estim h23', 'location', 'southeast');
title('cell 3'); axis tight; set(gca,'ylim',[0,ymax]);
% Print out true and recovered params:
fprintf('\n------------------\n');
fprintf('True stim weights: %.2f, %.2f, %.2f\n', squeeze(gg.k));
fprintf(' Est stim weights: %.2f, %.2f, %.2f\n\n', gg1.k,gg2.k,gg3.k);
% Print out true and recovered params:
fprintf('True dc: %.2f, %.2f, %.2f\n', gg.dc*[1 1 1]);
fprintf(' Est dc: %.2f, %.2f, %.2f\n', gg1.dc,gg2.dc,gg3.dc);
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/MLfit_GLMbi.m | .m | 1,644 | 49 | function [gg,fval,H,Xstruct] = MLfit_GLMbi(gg,Stim,optimArgs)
% [gg,fval,H,Xstruct] = MLfit_GLMbi(gg,Stim,optimArgs);
%
% Computes the ML estimate for GLM params, using grad and hessians.
% Assumes bilinear parametrization of space-time filter.
%
% Inputs:
% gg = param struct
% Stim = stimulus
% optimArgs = cell array of optimization params (optional)
%
% Outputs:
% ggnew = new param struct (with ML params);
% fval = negative log-likelihood at ML estimate
% H = Hessian of negative log-likelihood at ML estimate
% Xstruct = structure with design matrices for spike-hist and stim terms
% Set optimization parameters
algopts = getFminOptsForVersion(version);
if nargin > 2, opts = optimset(algopts{:}, optimArgs{:});
else, opts = optimset(algopts{:});
end
% --- Create design matrix extract initial params from gg ----------------
[prs0,Xstruct] = setupfitting_GLM(gg,Stim);
% minimize negative log likelihood
lfunc = @(prs)Loss_GLMbi_logli(prs,Xstruct); % loss function for exponential nonlinearity
[prs,fval] = fminunc(lfunc,prs0,opts); % optimize negative log-likelihood for prs
% Compute Hessian at maximum, if requested
if nargout > 2
[fval,~,H] = Loss_GLMbi_logli(prs);
end
% Put returned vals back into param structure ------
gg = reinsertFitPrs_GLMbi(gg,prs,Xstruct);
% %----------------------------------------------------
% Optional debugging code
% %----------------------------------------------------
%
% % ------ Check analytic gradients, Hessians -------
% DerivCheck(lfunc,prs0,opts);
% HessCheck_Elts(lfunc, [1 12],prs0,opts);
% tic; [lival,J,H]=lfunc(prs0,Xstruct); toc;
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/MAPfit_GLMbi_coordascent.m | .m | 4,334 | 133 | function [gg,neglogli,H,neglogp] = MAPfit_GLMbi_coordascent(gg,Stim,Cxinv,Ctinv,maxiter,ftol,optimArgs)
% [gg,neglogli,H,neglogp] = MAPfit_GLMbi_coordascent(gg,Stim,Cxinv,Ctinv,maxiter,ftol,optimArgs)
%
% Computes the MAP estimate for GLM params, with gradient and hessians, via
% coordinate ascent, for bilinear (low rank) parametrization of space-time filter.
%
% Inputs:
% gg = param struct
% Stim = stimulus
% Cxinv = inverse covariance for spatial params
% Ctinv = inverse covariance for temporal params
% maxiter = maximum number of coordinate ascent steps
% ftol = tolerance for stopping based on function improvement
% optimArgs = cell array of optimization params (optional)
%
% Outputs:
% ggnew = new param struct (with ML params);
% fval = negative log-likelihood at ML estimate
% H = Hessian of negative log-likelihood at ML estimate
% Set maxiter if necessary
if (nargin <= 3) || isempty(maxiter)
maxiter = 50; % maximum number of coordinate ascent steps
end
if (nargin <=4) || isempty(ftol)
ftol = .001; % tolerance for stopping
end
% Set optimization parameters
if nargin < 6
optimArgs = [];
end
% create struct for spatial optimization
ggx = gg;
ggx.ktype = 'linear'; % set type to linear (from bilinear)
ggx.ktbas = 1; ggx.ktbasprs = []; % remove temporal basis
ggx.kt = gg.kx(:)';
ggx.k = ggx.kt;
% create struct for temporal optimization
ggt = gg;
ggt.ktype = 'linear'; % set type to linear (from bilinear)
ggt.kt = gg.kt;
ggt.k = ggt.ktbas*ggt.kt;
% Initialize spatial stimulus
[nt,nkx] = size(Stim);
krank = gg.krank;
xStim = zeros(nt,krank*nkx); % initialize spatial stimulus
% compute initial log-likelihood
neglogli0 = neglogli_GLM(gg,Stim); % Compute logli of initial params
dlogp = inf; % initialize change in log-posterior
jjiter = 0; % initialize counter
% compute initial penalties (negative log prior)
kt = gg.kt; % temporal params
kx = gg.kx; % spatial params
krank = size(kt,2); % rank
nlpx = .5*kx'*Cxinv*kx;
nlpt = .5*kt'*Ctinv*kt;
nlp = trace(nlpx*nlpt);
neglogp0 = neglogli0+nlp; % initial log-posterior
fprintf('Initial smoothing penalty: %.2f\n', nlp);
% Do coordinate ascent until STOP
while (jjiter<maxiter) && dlogp>ftol
% ---- Update temporal params -----
fprintf('Iter #%d: Updating t params\n', jjiter);
tStim = Stim*reshape(ggx.k',[],gg.krank);
ggt.dc = ggx.dc; % update dc param
[ggt,tneglogli] = MAPfit_GLM(ggt,tStim,kron(nlpx,Ctinv),optimArgs);
nlpt = .5*ggt.kt'*Ctinv*ggt.kt;
nlp = trace(nlpx*nlpt);
fprintf(' dlogp = %.4f (penalty=%.2f)\n', neglogp0-(tneglogli+nlp), nlp);
% Convolve stimulus with temporal filters
for irank = 1:krank
for icol = 1:nkx
xStim(:,icol+(irank-1)*nkx) = sameconv(Stim(:,icol),ggt.k(:,irank));
end
end
% ---- Update spatial params ----
fprintf('Iter #%d: Updating x params\n', jjiter);
ggx.dc = ggt.dc; % update dc param
[ggx,xneglogli] = MAPfit_GLM(ggx,xStim,kron(nlpt,Cxinv),optimArgs);
nlpx = .5*reshape(ggx.k,[],krank)'*Cxinv*reshape(ggx.k(:),[],krank);
nlp = trace(nlpx*nlpt);
neglogp = xneglogli+nlp;
fprintf(' dlogp = %.4f (penalty=%.2f)\n', neglogp0-neglogp,nlp);
% Update iters
jjiter = jjiter+1; % counter
dlogp = neglogp0-neglogp; % change in log-likelihood
neglogp0 = neglogp;
end
fprintf('Finished coordinate ascent: %d iterations (dlogp=%.6f)\n',jjiter,dlogp);
% Compute conditional Hessians, if desired
if nargout > 2
% Compute Hessian for time components
tStim = Stim*(ggx.k');
ggt.dc = ggx.dc; % update dc param
[ggt,~,Ht] = MAPfit_GLM(ggt,tStim,Ctinv,optimArgs);
nlpt = .5*ggt.kt(:)'*Ctinv*ggt.kt(:);
% Compute Hessian for space components
for irank = 1:krank
for icol = 1:nkx
xStim(:,icol+(irank-1)*nkx) = sameconv(Stim(:,icol),ggt.k(:,irank));
end
end
ggx.dc = ggt.dc; % update dc param
[ggx,xneglogli,Hx] = MAPfit_GLM(ggx,xStim,Cxinv,optimArgs);
nlpx = .5*ggx.k(:)'*Cxinv*ggx.k(:);
neglogp = xneglogli+nlpt+nlpx;
H = {Ht,Hx}; % Hessians for t and x components
end
% Update params of bilinear model
gg.dc = ggx.dc;
gg.kt = ggt.kt;
gg.kx = reshape(ggx.k',[],gg.krank);
gg.k = (gg.ktbas*gg.kt)*gg.kx';
neglogli = xneglogli;
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/reinsertFitPrs_GLMbi.m | .m | 759 | 30 | function gg = reinsertFitPrs_GLMbi(gg,prs,Xstruct)
% gg = reinsertFitPrs_GLMbi(gg,prs);
%
% After fitting, reinsert params into param structure
% Put returned vals back into param structure ------
krank = Xstruct.krank;
nktprs = Xstruct.nkt*krank;
nkxprs = Xstruct.nkx*krank;
nktot = nktprs+nkxprs;
nh = Xstruct.nh;
nh2 = Xstruct.nh2;
% Insert params into struct
gg.kt = reshape(prs(1:nktprs),[],krank);
gg.kx = reshape(prs(nktprs+1:nktprs+nkxprs),[],krank);
gg.dc = prs(nktot+1);
gg.ihw = reshape(prs(nktot+2:nktot+nh+1), nh,1);
gg.ihw2 = reshape(prs(nktot+nh+2:end), nh2, []);
gg.k = (gg.ktbas*gg.kt)*(gg.kxbas*gg.kx)';
if isempty(gg.ihw)
gg.ihbas = [];
end
if isempty(gg.ihw2)
gg.ihbas2 = [];
end
gg.ih = [gg.ihbas*gg.ihw, gg.ihbas2*gg.ihw2];
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/reinsertFitPrs_GLM.m | .m | 705 | 28 | function gg = reinsertFitPrs_GLM(gg,prs,Xstruct)
% gg = reinsertFitPrs_GLM(gg,prs,Xstruct)
%
% After fitting, reinsert params into GLM param structure
% Extract relevant size information
nkt = Xstruct.nkt;
nkx = Xstruct.nkx;
nktot = nkt*nkx;
nh = Xstruct.nh;
nh2 = Xstruct.nh2;
% Insert params
gg.kt = reshape(prs(1:nktot),nkt,nkx);
gg.k = gg.ktbas*gg.kt;
gg.dc = prs(nktot+1);
gg.ihw = reshape(prs(nktot+2:nktot+nh+1), nh,1);
gg.ihw2 = reshape(prs(nktot+nh+2:end), nh2, []);
% Ensure these bases are 'empty' if no spike history filters
if isempty(gg.ihw), gg.ihbas = [];
end
if isempty(gg.ihw2), gg.ihbas2 = [];
end
% Insert spike-history filters
gg.ih = [gg.ihbas*gg.ihw, gg.ihbas2*gg.ihw2];
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/initfit_stimDesignMat_bi.m | .m | 1,968 | 48 | function Xstruct = initfit_stimDesignMat_bi(gg,Stim)
% Xstruct = initfit_stimDesignMat_bi(gg,Stim)
%
% Initialize parameters relating to stimulus design matrix for bilinearly
% parametrized GLM
% ---- Set up filter and stim processing params -------------------
nkx = size(gg.kxbas,2); % # params per spatial vector
nkt = size(gg.ktbas,2); % # time params per stim pixel (# t params)
ncols = nkx*nkt; % number of columns in design matrix
[slen,swid] = size(Stim); % size of stimulus
upsampfactor = (gg.dtStim/gg.dtSp); % number of times by which spikes more finely sampled than stim
rlen = slen*upsampfactor; % length of spike train vector
% ---- Check size of filter and width of stimulus ----------
assert(nkx == swid,'Mismatch between stim width and kernel width');
% ---- Convolve stimulus with spatial and temporal bases -----
xfltStim = Stim*gg.kxbas; % stimulus filtered with spatial basis
% ---- Allocated space for design matrix ------
try Xstruct.Xstim = zeros(slen,ncols); %
catch
fprintf('\nERROR: Stimulus too for joint optimization!\n');
fprintf('Use ''MLfit_GLMbi_coordascent.m'' instead\n\n');
error('Out of Memory Error in initfit_stimDesignMat_bi.m');
end
% ---- Build stimulus design matrix -------------
for i = 1:nkx
for j = 1:nkt
Xstruct.Xstim(:,(i-1)*nkt+j) = sameconv(xfltStim(:,i),gg.ktbas(:,j));
end
end
% ---- Set up stim processing params ----------
Xstruct.nkx = nkx; % # stimulus spatial stimulus pixels
Xstruct.nkt = nkt; % # time bins in stim filter
Xstruct.krank = gg.krank; % stim filter rank
Xstruct.slen = slen; % Total stimulus length (coarse bins)
Xstruct.rlen = rlen; % Total spike-train bins (fine bins)
Xstruct.upsampfactor = upsampfactor; % rlen / slen
Xstruct.Minterp = kron(speye(slen),ones(upsampfactor,1)); % rlen x slen matrix for upsampling and downsampling
Xstruct.dtStim = gg.dtStim; % time bin size for stimulus
Xstruct.dtSp = gg.dtSp; % time bins size for spike train
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/neglogli_GLM.m | .m | 3,083 | 93 | function [neglogli,rr,tt,Itot,Istm,Ih,Icpl] = neglogli_GLM(gg,Stim)
% [neglogli,rr,tt,Itot,Istm,Ih,Icpl] = neglogli_GLM(gg,Stim)
%
% Compute glm model negative log-likelihood given the parameters in gg,
%
% Inputs: gg = param object
% fields: k - stimulus kernel
% ih - post-spike current
% dc - dc current injection
% nlfun - nonlinearity
% dt - time bin size
% Stim = stimulus
%
% Outputs:
% neglogli = negative log-likelihood of spike trains
% rr = conditional intensity (in expected spikes /sec)
% tt = time bins for for conditional intensity
% Itot = sum of all filter outputs
% Istm = sum of stim filter output and dc term
% Ih = output of neuron's own spike-history filter
% Icpl = matrix of coupling current inputs
% ---- Extract params from glm struct ---------------
k = gg.k;
dc = gg.dc;
ih = gg.ih;
dt = gg.dtSp; % time bin size for spikes
upsampfactor = gg.dtStim/dt; % number of spike bins per Stim bin
slen = size(Stim,1);
rlen = size(gg.sps,1);
% Check that upSampFactor is an integer
assert(mod(upsampfactor,1) == 0, 'dtStim / dtSp must be an integer');
% Check factor relating size of stim and binned spike train
assert(slen*upsampfactor==rlen,'Spike train length must be an even multiple of stim length');
% ---- Compute filtered resp to stimulus -----------------------------
I0 = sameconv(Stim,k);
Itot = kron(I0,ones(upsampfactor,1)) + dc;
% -------------- Compute net h current --------------------------------
% Check if post-spike filters are present
if isempty(gg.ihw), gg.ihbas = []; end
if isempty(gg.ihw2), gg.ihbas2 = []; end
% Compute convolution of post-spike filters with spike history
nCoupled = length(gg.couplednums); % # cells coupled to this one
if ~isempty(ih)
Itot = Itot + spikefilt(gg.sps,ih(:,1)); % self-coupling filter
for j = 1:nCoupled % coupling filters from other neurons
Itot = Itot + spikefilt(gg.sps2(:,j),ih(:,j+1));
end
end
rr = gg.nlfun(Itot); % Conditional intensity
% -- Compute negative log-likelihood from conditional intensity ------
bmask = initfit_mask(gg.mask,dt,rlen); % bins to use for likelihood calc
rrmask = rr(bmask); % rate only on timee bins in mask
trm1 = sum(rrmask)*dt; % non-spiking term
trm2 = -sum(log(rrmask(gg.sps(bmask)>0))); % Spiking term
neglogli = trm1 + trm2;
% ====== OPTIONAL OUTPUT ARGS ===================================
% time indices
if nargout > 2, tt = (1:rlen)'*dt;
end
% Stim filter output
if nargout > 4, Istm = kron(I0,ones(upsampfactor,1)) + dc;
end
% Spike-history filter output
if nargout > 5
Ih = zeros(length(Itot),1);
if ~isempty(ih), Ih = spikefilt(gg.sps,ih(:,1));
end
end
% Coupling filter outputs
if nargout > 6
Icpl = zeros(length(Itot),size(ih,2)-1);
if ~isempty(ih)
for j = 1:nCoupled
Icpl(:,j) = spikefilt(gg.sps2(:,j),ih(:,j+1));
end
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/Loss_GLMbi_logli.m | .m | 6,263 | 190 | function [logli, dL, H] = Loss_GLMbi_logli(prs,Xstruct)
% [logli, dL, H] = Loss_GLMbi_logli(prs,Xstruct)
%
% Compute negative log-likelXXspood of data undr the GLM model, with bilinear
% parametrization of the input current
%
% Uses arbitrary nonlinearity 'nlfun' instead of exponential
%
% Inputs:
% prs = [ktprs - weights for stimulus time kernel
% kxprs - weights for stim space kernel
% dc - dc current injection
% XXspprs - weights on post-spike current];
%
% Outputs:
% logli = negative log likelXXspood of spike train
% dL = gradient with respect to prs
% H = hessian
% Extract some size information from Xstruct
nkt = Xstruct.nkt; % # of basis vectors for spatial k basis
nkx = Xstruct.nkx; % # of basis vectors for spatial k basis
krank = Xstruct.krank; % rank of stim filter
nktprs = nkt*krank; % total # params for temporal filters
nkxprs = nkx*krank; % total # params for spatial filters
% Unpack GLM prs;
ktprs = prs(1:nktprs);
kxprs = prs(nktprs+1:nktprs+nkxprs);
dc = prs(nktprs+nkxprs+1);
XXspprs = prs(nktprs+nkxprs+2:end);
% Extract some other stuff we'll use a lot
XXstm = Xstruct.Xstim; % stimulus design matrix
XXsp = Xstruct.Xsp; % spike history design matrix
bsps = Xstruct.bsps; % binary spike vector
M = Xstruct.Minterp; % matrix for interpolating from stimulus bins to spike train bins
ihflag = Xstruct.ihflag; % flag
rlen = Xstruct.rlen; % number of bins in spike train vector
nsp = (sum(bsps)); % number of spikes
dt = Xstruct.dtSp; % absolute bin size for spike train (in sec)
% -- Make block-diag matrix containing nkt params -----
Mkt = kron(speye(nkx),reshape(ktprs,nkt,krank)); % block-diagonal matrix for kt params
inds = reshape((1:nkx*krank),krank,nkx)'; inds = inds(:);
Mkt = Mkt(:,inds); % turns out we need it reshaped this way
% -------- Compute bilinear stim filter reponse -----------------------
dSSdx = XXstm*Mkt; % stim filtered with temporal filter
ystm = dSSdx*kxprs;
% -------- Compute sum of filter reponses -----------------------
if ihflag
Itot = M*ystm + XXsp*XXspprs + dc; % stim-dependent + spikehist-dependent inputs
else
Itot = M*ystm + dc; % stim-dependent input only
end
% --------- Compute output of nonlinearity ------------------------
[rr,drr,ddrr] = Xstruct.nlfun(Itot);
% Check for (approximately) zero-values of rr
etol = 1e-100; % cutoff for small values of conditional intensity
iiz = find(rr <= etol);
rr(iiz) = etol; % Set value to small
drr(iiz) = 0; ddrr(iiz) = 0; % Set derivs here to 0
% --------- Compute log-likelXXspood ---------------------------------
Trm1 = sum(rr)*dt; % non-spike term
Trm2 = -sum(log(rr(bsps))); % spike term
logli = Trm1 + Trm2;
% =============================================
% --------- Compute Gradient -----------------
% =============================================
if (nargout > 1)
% Compute dSSdt - stim filtered with spatial kernel
Mkx = kron(speye(nkt), reshape(kxprs,nkx,krank));
inds = reshape((1:nkt*krank),krank,nkt)'; inds = inds(:);
Mkx = Mkx(:,inds);
inds = reshape((1:nkt*nkx),nkt,nkx)'; inds = inds(:);
dSSdt = XXstm(:,inds)*Mkx;
% Non-spiking terms (Term 1)
dqq = drr'*M;
dLdkx0 = (dqq*dSSdx)';
dLdkt0 = (dqq*dSSdt)';
dLdb0 = sum(drr);
if ihflag, dLdh0 = (drr'*XXsp)';
end
% Non-spiking terms (Term 2)
Msp = M(bsps,:); % interpolation matrix just for spike bins
frac1 = drr(bsps)./rr(bsps);
fracsp = frac1'*Msp;
dLdkx1 = (fracsp*dSSdx)';
dLdkt1 = (fracsp*dSSdt)';
dLdb1 = sum(frac1);
if ihflag, dLdh1 = (frac1'*XXsp(bsps,:))';
end
% Combine Term 1 and Term 2
dLdkx = dLdkx0*dt - dLdkx1;
dLdkt = dLdkt0*dt - dLdkt1;
dLdk = [dLdkt; dLdkx];
dLdb = dLdb0*dt - dLdb1;
if ihflag, dLdh = dLdh0*dt - dLdh1;
else dLdh = [];
end
dL = [dLdk; dLdb; dLdh];
end
% =============================================
% --------- Compute Hessian -----------------
% =============================================
if nargout > 2
% --- Non-spiking terms -----
% multiply each row of M with drr
ddrrdiag = spdiags(ddrr,0,rlen,rlen);
ddqqIntrp = ddrrdiag*M;
ddqq = M'*ddqqIntrp; % this is MUCH faster than using bsxfun, due to sparsity!
% Hx and Ht
Hkt = (dSSdt'*ddqq*dSSdt)*dt;
Hkx = (dSSdx'*ddqq*dSSdx)*dt;
% Hxt
Hktx0a= reshape((drr'*M)*XXstm,nkt,nkx);
Hktx0a = kron(speye(krank),Hktx0a);
Hktx = (dSSdx'*ddqq*dSSdt + Hktx0a')*dt;
% Hb
Hb = sum(ddrr)*dt;
% Hkb
sumqq = sum(ddqqIntrp,1);
Hxb = (sumqq*dSSdx)';
Htb = (sumqq*dSSdt)';
Hkb = [Htb;Hxb]*dt;
if ihflag
% Hh
Hh = (XXsp'*ddrrdiag*XXsp)*dt;
% Hhk
Hth = (XXsp'*ddqqIntrp)*dSSdt;
Hxh = (XXsp'*ddqqIntrp)*dSSdx;
Hkh = [Hth'; Hxh']*dt;
% Hb
Hhb = (ddrr'*XXsp)'*dt;
else
Hkh = []; Hhb=[]; Hh=[];
end
% --- Add in spiking terms ----
frac2 = (rr(bsps).*ddrr(bsps) - drr(bsps).^2)./rr(bsps).^2;
fr2diag = spdiags(frac2,0,nsp,nsp);
fr2Interp = fr2diag*Msp;
fr2ddqq = Msp'*fr2Interp;
% Spiking terms, Hxx and Htt
Hkt= Hkt - dSSdt'*fr2ddqq*dSSdt;
Hkx= Hkx - dSSdx'*fr2ddqq*dSSdx;
% Spiking terms, Hxt
Hktx1a= reshape(frac1'*Msp*XXstm,nkt,nkx)';
Hktx1a= kron(speye(krank),Hktx1a);
Hktx1b= dSSdx'*fr2ddqq*dSSdt;
Hktx1= Hktx1a+Hktx1b;
Hktx= Hktx - Hktx1;
% Const term
Hb = Hb-sum(frac2);
% Const by k
sumfr2 = sum(fr2Interp,1);
Hxb1 = sumfr2*dSSdx;
Htb1 = sumfr2*dSSdt;
Hkb = Hkb - [Htb1'; Hxb1'];
if ihflag
XXsprrsp = fr2diag*XXsp(bsps,:);
Hh= Hh - XXsp(bsps,:)'*XXsprrsp;
% Const by h
Hhb1 = sum(XXsprrsp,1)';
Hhb = Hhb - Hhb1;
% k by h term
Hth0 = XXsp(bsps,:)'*(fr2Interp*dSSdt);
Hxh0 = XXsp(bsps,:)'*(fr2Interp*dSSdx);
Hkh = Hkh-[Hth0';Hxh0'];
end
Hk = [[Hkt; Hktx] [Hktx'; Hkx]];
H = [[Hk Hkb Hkh]; [Hkb' Hb Hhb']; [Hkh' Hhb Hh]];
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/MAPfit_GLM.m | .m | 3,158 | 97 | function [gg,neglogli,H,Xstruct,neglogp] = MAPfit_GLM(gg,Stim,Cinv,optimArgs)
% [gg,neglogli,H,Xstruct,neglogp] = MAPfit_GLM(gg,C,Stim,optimArgs)
%
% Computes the MAP estimate for GLM params, using grad and hessians under
% a zero-mean Gaussian prior with inverse covariance Cinv.
%
% Minimizes negative log-likelihood plus a penalty of the form
% 0.5*x'*Cinv*x, where x is the parameter vector
%
% Assumes basis for temporal dimensions of stim filter
%
% Inputs:
% -------
% gg = param struct
% Stim = stimulus
% Cinv = inverse of prior covariance matrix (gives quadratic penalty)
% optimArgs = cell array of optimization params (optional)
%
% Outputs:
% -------
% ggnew = new param struct (with MAP params);
% neglogli = negative log-likelihood at MAP estimate
% H = Hessian of negative log-likelihood at MAP estimate
% Xstruct = structure with design matrices for spike-hist and stim terms
% neglogp = negative log-posterior at MAP estimate
% Set optimization parameters
algopts = getFminOptsForVersion(version);
if nargin > 3, opts = optimset(algopts{:}, optimArgs{:});
else, opts = optimset(algopts{:});
end
% --- Create design matrix extract initial params from gg ----------------
[prs0,Xstruct] = setupfitting_GLM(gg,Stim);
% --- Set log-likelihood function ----------------------------
if isequal(Xstruct.nlfun,@expfun) || isequal(Xstruct.nlfun,@exp)
% loss function for exponential nonlinearity
lfunc = @(prs)Loss_GLM_logli_exp(prs,Xstruct);
else
lfunc = @(prs)Loss_GLM_logli(prs,Xstruct);
% loss function for all other nonlinearities
end
% set log-posterior function
lpost = @(prs)(neglogpost(prs,lfunc,Cinv));
% --- minimize negative log posterior --------------------
[prsMAP,neglogp] = fminunc(lpost,prs0,opts); % find MAP estimate of params
% Compute Hessian of log-likelihood, if desired
if nargout > 1
[neglogli,~,H] = lfunc(prsMAP);
end
% Put returned vals back into param structure
gg = reinsertFitPrs_GLM(gg,prsMAP,Xstruct);
end
%% =================================================
function [negLP,dLP,H] = neglogpost(prs,lfunc,Cinv)
% Compute log-posterior by adding quadratic penalty to log-likelihood
nprs = size(Cinv,1); % number of parameters in C
preg = prs(1:nprs); % parameters being regularized.
switch nargout
case 1 % evaluate function
negLP = lfunc(prs) + .5*preg'*Cinv*preg;
case 2 % evaluate function and gradient
[negLP,dLP] = lfunc(prs);
negLP = negLP + .5*preg'*Cinv*preg;
dLP(1:nprs) = dLP(1:nprs) + Cinv*preg;
case 3 % evaluate function and gradient
[negLP,dLP,H] = lfunc(prs);
negLP = negLP + .5*preg'*Cinv*preg;
dLP(1:nprs) = dLP(1:nprs) + Cinv*preg;
H(1:nprs,1:nprs) = H(1:nprs,1:nprs) + Cinv;
end
end
% %----------------------------------------------------
% Optional debugging code
% %----------------------------------------------------
%
% % ------ Check analytic gradients and Hessians -------
% HessCheck(lfunc,prs0,opts);
% HessCheck_Elts(@Loss_GLM_logli, [1 12],prs0,opts);
% tic; [lival,J,H]=lfunc(prs0); toc;
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/MLfit_GLMbi_coordascent.m | .m | 3,484 | 113 | function [gg,fval,H] = MLfit_GLMbi_coordascent(gg,Stim,maxiter,ftol,optimArgs)
% [gg,fval,H] = MLfit_GLMbi_coordascent(gg,Stim,maxiter,ftol,optimArgs);
%
% Computes the ML estimate for GLM params, with gradient and hessians, via
% coordinate ascent, for bilinear (low rank) parametrization of space-time filter.
%
% Inputs:
% gg = param struct
% Stim = stimulus
% maxiter = maximum number of coordinate ascent steps
% ftol = tolerance for stopping based on function improvement
% optimArgs = cell array of optimization params (optional)
%
% Outputs:
% ggnew = new param struct (with ML params);
% fval = negative log-likelihood at ML estimate
% H = Hessian of negative log-likelihood at ML estimate
% Set maxiter if necessary
if (nargin <= 2) || isempty(maxiter)
maxiter = 50; % maximum number of coordinate ascent steps
end
if (nargin <=3) || isempty(ftol)
ftol = .001; % tolerance for stopping
end
% Set optimization parameters
if nargin < 5
optimArgs = [];
end
% create struct for spatial optimization
ggx = gg;
ggx.ktype = 'linear'; % set type to linear (from bilinear)
ggx.ktbas = 1; ggx.ktbasprs = []; % remove temporal basis
ggx.kt = gg.kx(:)';
ggx.k = ggx.kt;
% create struct for temporal optimization
ggt = gg;
ggt.ktype = 'linear'; % set type to linear (from bilinear)
ggt.kt = gg.kt;
ggt.k = ggt.ktbas*ggt.kt;
% Initialize spatial stimulus
[nt,nkx] = size(Stim);
krank = gg.krank;
xStim = zeros(nt,krank*nkx); % initialize spatial stimulus
% compute initial log-likelihood
neglogli0 = neglogli_GLM(gg,Stim); % Compute logli of initial params
dlogli = inf; % initialize change in logli
jjiter = 0; % initialize counter
while (jjiter<maxiter) && dlogli>ftol
% ---- Update temporal params -----
fprintf('Iter #%d: Updating temporal params\n', jjiter);
tStim = Stim*reshape(ggx.k',[],gg.krank);
ggt.dc = ggx.dc; % update dc param
[ggt,tneglogli] = MLfit_GLM(ggt,tStim,optimArgs);
fprintf(' dlogli = %.4f\n', neglogli0-tneglogli);
% Convolve stimulus with temporal filters
for irank = 1:krank
for icol = 1:nkx
xStim(:,icol+(irank-1)*nkx) = sameconv(Stim(:,icol),ggt.k(:,irank));
end
end
% ---- Update spatial params ----
fprintf('Iter #%d: Updating spatial params\n', jjiter);
ggx.dc = ggt.dc; % update dc param
[ggx,xneglogli] = MLfit_GLM(ggx,xStim,optimArgs);
fprintf(' dlogli = %.4f\n', neglogli0-xneglogli);
% Update iters
jjiter = jjiter+1; % counter
dlogli = neglogli0-xneglogli; % change in log-likelihood
neglogli0 = xneglogli;
end
fprintf('\nFinished coordinate ascent: %d iterations (dlogli=%.6f)\n',jjiter,dlogli);
% Compute conditional Hessians, if desired
if nargout > 2
% Compute Hessian for time components
tStim = Stim*(ggx.k');
ggt.dc = ggx.dc; % update dc param
[ggt,~,Ht] = MLfit_GLM(ggt,tStim,optimArgs);
% Compute Hessian for space components
for irank = 1:krank
for icol = 1:nkx
xStim(:,icol+(irank-1)*nkx) = sameconv(Stim(:,icol),ggt.k(:,irank));
end
end
ggx.dc = ggt.dc; % update dc param
[ggx,neglogli0,Hx] = MLfit_GLM(ggx,xStim,optimArgs);
H = {Ht,Hx}; % Hessians for t and x components
end
% Update params of bilinear model
gg.dc = ggx.dc;
gg.kt = ggt.kt;
gg.kx = reshape(ggx.k',[],gg.krank);
gg.k = (gg.ktbas*gg.kt)*gg.kx';
fval = neglogli0; % value of loglikelihood
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/initfit_mask.m | .m | 1,147 | 38 | function bmask = initfit_mask(mask,dtSp,rlen)
% bmask = initfit_mask(mask,dtSp,rlen)
%
% Compute binary mask for computing log-likelihood
%
% Input:
% ------
% mask [n x 2]: list of intervals to use for computing log-likelihood
% (ignore time bins outside these intervals)
% dtSp [1 x 1]: bin size for spike trains and conditional intensity
% rlen [1 x 1]: length of total conditional intensity vector
%
% Output:
% -------
% bmask [rlen x 1]: binary vector where (1 = use for LL), (0 = ignore).
if isempty(mask) % No mask
bmask = true(rlen,1); % keep all indices
else
% convert mask to discrete time bins
mask = round(mask/dtSp);
% Check that mask doesn't extend beyond stimulus window
if max(mask(:)) > rlen
warning('GLM:mask', 'Mask is too long for data segment: truncating...');
mask(:,2) = max(mask(:,2),rlen); % set maximum mask value to stim length
mask(diff(mask')'<0,:) = []; % remove rows with negative intervals
end
% Generate mask
bmask = false(rlen,1);
for j = 1:size(mask,1)
bmask(mask(j,1):mask(j,2)) = true;
end
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/makeFittingStruct_GLM.m | .m | 3,351 | 78 | function gg = makeFittingStruct_GLM(dtStim,dtSp,klength,nkbasis,k0,nhbasis,lasthpeak)
% gg = makeFittingStruct_GLM(dtStim,dtSp,klength,nkbasis,k0,nhbasis,lasthpeak)
%
% Initialize parameter structure for fitting GLM,
% with normal parametrization of stim kernel
%
% Inputs:
% dtStim = bin size of stimulus (in s)
% dtSp = bin size for spike train (in s)
% klength = temporal length of stimulus filter, in # of bins (optional)
% nkbasis = # temporal basis vectors for stim filter (optional)
% nhbasis = # temporal basis vectors for spike hist filter h (optional)
% lasthpeak = time of peak of last h basis vector, in s (optional)
% k0 = initial estimate of stimulus filter (optional)
%
% Outputs:
% gg = GLM-fitting param structure
% ---- Set up fitting structure -------------------------------
gg.k = []; % Actual stim filter k
gg.ih = []; % Actual post-spike filter ih
gg.dc = 0; % "dc" or constant input (determines baseline spike rate)
gg.ihw = []; % h filter weights
gg.iht = []; % h filter time points
gg.ihbas = []; % basis for h filter
gg.ihbasprs = []; % parameters for basis for h-filter
gg.kt = []; % basis weights for stimulus filter k
gg.ktbas = []; % temporal basis for stimulus filter k
gg.ktbasprs = []; % parameters for basis for k-filter
gg.nlfun = @expfun; % default nonlinearity: exponential
gg.sps = []; % spike times (in s)
gg.mask = []; % list of intervals to ignore when computing likelihood
gg.dtStim = dtStim; % time bin size for stimulus
gg.dtSp = dtSp; % time bin for spike train
gg.ihw2 = []; % weights for coupling filters
gg.ihbas2 = []; % basis for coupling filters
gg.ihbasprs2 = []; % parameters for coupling filter basis
gg.sps2 = []; % spike times of coupled neurons
gg.couplednums = []; % numbers of coupled cells
% % ----- Set up temporal basis for stimulus kernel -----------
if nargin > 2
assert((klength>nkbasis), 'klength should be bigger than number of temporal basis vectors');
ktbasprs.neye = 0; % number of "identity" basis vectors
ktbasprs.ncos = nkbasis; % Number of raised-cosine vectors to use
ktbasprs.kpeaks = [0 klength*(1 - 1.5/nkbasis)]; % Position of 1st and last bump
ktbasprs.b = 10; % Offset for nonlinear scaling (larger -> more linear)
[~,ktbasis] = makeBasis_StimKernel(ktbasprs,klength);
gg.ktbas = ktbasis;
gg.ktbasprs = ktbasprs;
end
if (nargin > 4) && (~isempty(k0))
% initialize k filter in this basis
gg.kt = (gg.ktbas'*gg.ktbas)\(gg.ktbas'*k0);
gg.k = gg.ktbas*gg.kt;
end
% ----- Set up basis for post-spike filter -----------------------
if (nargin > 5) && (nhbasis>0)
ihbasprs.ncols = nhbasis; % Number of basis vectors for post-spike kernel
ihbasprs.hpeaks = [dtSp lasthpeak]; % Peak location for first and last vectors
ihbasprs.b = lasthpeak/5; % How nonlinear to make spacings (rough heuristic)
ihbasprs.absref = []; % absolute refractory period (optional)
[iht,ihbas] = makeBasis_PostSpike(ihbasprs,dtSp);
gg.iht = iht;
gg.ihbas = ihbas;
gg.ihbasprs = ihbasprs;
gg.ihw = zeros(size(ihbas,2),1);
gg.ih = gg.ihbas*gg.ihw; % Set ih to be the current value of ihbas*ihw
end
% specify type of parametrization of filter ('linear' vs. 'bilinear')
gg.ktype = 'linear';
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/initfit_sphistDesignMat.m | .m | 1,390 | 48 | function Xstruct = initfit_sphistDesignMat(gg,Xstruct)
% Xstruct = initfit_sphistDesignMat(gg,Xstruct)
%
% Sets parameters relating to optimization of
% spike-filter terms in the point process GLM and inserts them into design
% matrix structure 'Xstruct'
% Determine # of parameters for self-coupling filter
if ~isempty(gg.ihw), nh=size(gg.ihbas,2);
else nh=0;
end
% Determine # of params for coupling filters
if ~isempty(gg.ihw2), nh2 = size(gg.ihbas2,2);
else nh2=0;
end
% Determine # of coupled neurons
nCoupled = length(gg.couplednums); % Number of coupled cells
% Set flag for existence of coupling filters
if (nh+nh2 == 0), Xstruct.ihflag = false;
else Xstruct.ihflag = 1;
end
% Vector of binary (0 or 1) spike counts
Xstruct.bsps = sparse(gg.sps>0);
% ---- Create Spike-history Design Matrix ------------------------
Xsp = zeros(Xstruct.rlen,nh+nh2*nCoupled); % allocate
% Design matrix for self-coupling filter
if nh>0
Xsp(:,1:nh) = spikefilt(full(double(gg.sps>0)),gg.ihbas);
end
% Design matrix for cross-coupling filters
for jcpl = 1:nCoupled
inds = nh+nh2*(jcpl-1)+1:nh+nh2*jcpl; % column indices
Xsp(:,inds) = spikefilt(full(double(gg.sps2(:,jcpl))),gg.ihbas2); % insert into design matrix
end
% ---- Set fields of Xstruct -------------------------------------
Xstruct.nh = nh;
Xstruct.nh2 = nh2;
Xstruct.nCoupled = nCoupled;
Xstruct.Xsp = Xsp; | MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/setupfitting_GLM.m | .m | 1,529 | 45 | function [prs0,Xstruct] = setupfitting_GLM(gg, Stim)
% [prs0,Xstruct] = setupfitting_GLM(gg, Stim)
%
% Set initial parameters and build design matrix structure for GLM fitting
%
% Inputs:
% gg = glm param structure
% Stim = stimulus (time along columns, other dims along rows)
% maxsize = maximum # floats to store in design matrix
% (Affects # of chunks used to compute likelihood)
% Output:
% prs0 = initial parameters extracted from gg
% Xstruct = struct with design matrix for stim and spike-history terms
% Initialize optimization param structure
% ---- Create struct and make stimulus design matrix ---------------------
if strcmp(gg.ktype, 'linear') % standard GLM
Xstruct = initfit_stimDesignMat(gg,Stim); % create design matrix structure
% extract parameter vector
prs0 = [gg.kt(:); gg.dc; gg.ihw(:); gg.ihw2(:)];
elseif strcmp(gg.ktype, 'bilinear') % bilinearly-parametrized stim filter
Xstruct = initfit_stimDesignMat_bi(gg,Stim); % create design matrix structure
% extract parameter vector
prs0 = [gg.kt(:); gg.kx(:); gg.dc; gg.ihw(:); gg.ihw2(:)];
else
error('unknown filter type (allowed types are ''linear'' or ''bilinear'')');
end
% ---- Make spike-history design matrix -----------------------------------
Xstruct = initfit_sphistDesignMat(gg,Xstruct);
% set nonlinearity
Xstruct.nlfun = gg.nlfun;
% compute mask (time bins to use for likelihood)
Xstruct.bmask = initfit_mask(gg.mask,Xstruct.dtSp,Xstruct.rlen);
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/Loss_GLM_logli.m | .m | 4,129 | 122 | function [logli, dL, H] = Loss_GLM_logli(prs,Xstruct)
% [logli, dL, H] = Loss_GLM_logli(prs,Xstruct)
%
% Compute negative log-likelihood of data undr the GLM model
% (with standard linear parametrization of stimulus kernel);
%
% Uses arbitrary nonlinearity 'nlfun' instead of exponential
%
% Inputs:
% prs = [kprs - weights for stimulus kernel
% dc - dc current injection
% ihprs - weights on post-spike current]
%
% Outputs:
% logli = negative log likelihood of spike train
% dL = gradient with respect to prs
% H = hessian
% Unpack GLM prs;
nktot = Xstruct.nkx*Xstruct.nkt; % total # params for k
kprs = prs(1:nktot);
dc = prs(nktot+1);
ihprs = prs(nktot+2:end);
% Extract some other stuff we'll use a lot
XXstm = Xstruct.Xstim; % stimulus design matrix
XXsp = Xstruct.Xsp; % spike history design matrix
bsps = Xstruct.bsps; % binary spike vector
M = Xstruct.Minterp; % matrix for interpolating from stimulus bins to spike train bins
ihflag = Xstruct.ihflag; % flag
rlen = Xstruct.rlen; % number of bins in spike train vector
nsp = (sum(bsps)); % number of spikes
dt = Xstruct.dtSp; % absolute bin size for spike train (in sec)
% -------- Compute sum of filter reponses -----------------------
if Xstruct.ihflag
Itot = M*(XXstm*kprs) + XXsp*ihprs + dc; % stim-dependent + spikehist-dependent inputs
else
Itot = M*(XXstm*kprs) + dc; % stim-dependent input only
end
% --------- Compute output of nonlinearity ------------------------
[rr,drr,ddrr] = Xstruct.nlfun(Itot);
% --------- Compute log-likelihood ---------------------------------
Trm1 = sum(rr)*dt; % non-spike term
Trm2 = -sum(log(rr(bsps))); % spike term
logli = Trm1 + Trm2;
% --------- Compute Gradient -----------------
if (nargout > 1)
% Non-spiking terms (Term 1)
dLdk0 = (drr'*M*XXstm)';
dLdb0 = sum(drr);
if ihflag, dLdh0 = (drr'*XXsp)';
end
% Spiking terms (Term 2)
Msp = M(bsps,:); % interpolation matrix just for spike bins
frac1 = drr(bsps)./rr(bsps);
dLdk1 = ((frac1'*Msp)*XXstm)';
dLdb1 = sum(frac1);
if ihflag, dLdh1 = (frac1'*XXsp(bsps,:))';
end
% Combine Term 1 and Term 2
dLdk = dLdk0*dt - dLdk1;
dLdb = dLdb0*dt - dLdb1;
if ihflag, dLdh = dLdh0*dt - dLdh1;
else dLdh = [];
end
dL = [dLdk; dLdb; dLdh];
end
% --------- Compute Hessian -----------------
if nargout > 2
% --- Non-spiking terms -----
% multiply each row of M with drr
ddrrdiag = spdiags(ddrr,0,rlen,rlen);
ddqqIntrp = ddrrdiag*M; % this is MUCH faster than using bsxfun, due to sparsity!
% k and b terms
Hk = (XXstm'*(M'*ddqqIntrp)*XXstm)*dt; % Hkk (k filter)
Hb = sum(ddrr)*dt; % Hbb (constant b)
Hkb = (sum(ddqqIntrp,1)*XXstm)'*dt; % Hkb (cross-term)
if ihflag % h terms
Hh = (XXsp'*(bsxfun(@times,XXsp,ddrr)))*dt; % Hh (h filter)
% (here bsxfun is faster than diagonal multiplication)
Hkh = ((XXsp'*ddqqIntrp)*XXstm*dt)'; % Hhk (cross-term)
Hhb = (ddrr'*XXsp)'*dt; % Hhb (cross-term)
else
Hkh=[]; Hhb=[]; Hh=[];
end
% --- Add in spiking terms ----
frac2 = (rr(bsps).*ddrr(bsps) - drr(bsps).^2)./rr(bsps).^2; % needed weights from derivation of Hessian
fr2Interp = spdiags(frac2,0,nsp,nsp)*Msp; % rows of Msp re-weighted by these weights
% Spiking terms, k and b
Hk= Hk - XXstm'*(Msp'*fr2Interp)*XXstm; % Hkk (k filter)
Hb = Hb-sum(frac2); % Hbb (constant b)
Hb1 = sum(fr2Interp,1)*XXstm; % Spiking term, k and const
Hkb = Hkb - Hb1';
if Xstruct.ihflag
XXrrsp = bsxfun(@times,XXsp(bsps,:),frac2);
Hh= Hh - XXsp(bsps,:)'*XXrrsp;
% Const by h
Hhb1 = sum(XXrrsp,1)';
Hhb = Hhb - Hhb1;
% k by h term
Hkh0 = XXsp(bsps,:)'*(fr2Interp*XXstm);
Hkh = Hkh-Hkh0';
end
H = [[Hk Hkb Hkh]; [Hkb' Hb Hhb']; [Hkh' Hhb Hh]];
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/initfit_stimDesignMat.m | .m | 1,536 | 36 | function Xstruct = initfit_stimDesignMat(gg,Stim)
% Xstruct = initfit_stimDesignMat(gg,Stim)
%
% Initialize parameters relating to stimulus design matrix
% ---- Set up filter and stim processing params -------------------
nkx = size(gg.k,2); % number stim pixels (# x params)
nkt = size(gg.ktbas,2); % # time params per stim pixel (# t params)
ncols = nkx*nkt; % total number of columns in stim design matrix
[slen,swid] = size(Stim); % size of stimulus
upsampfactor = (gg.dtStim/gg.dtSp); % number of times by which spikes more finely sampled than stim
rlen = slen*upsampfactor; % length of spike train vector
% ---- Check size of filter and width of stimulus ----------
assert(nkx == swid,'Mismatch between stim width and kernel width');
% ---- Convolve stimulus with spatial and temporal bases -----
Xstruct.Xstim = zeros(slen,ncols);
for i = 1:nkx
for j = 1:nkt
Xstruct.Xstim(:,(i-1)*nkt+j) = sameconv(Stim(:,i),gg.ktbas(:,j));
end
end
% ---- Set fields of Xstruct -------------------------------------
Xstruct.nkx = nkx; % # stimulus spatial stimulus pixels
Xstruct.nkt = nkt; % # time bins in stim filter
Xstruct.slen = slen; % Total stimulus length (coarse bins)
Xstruct.rlen = rlen; % Total spike-train bins (fine bins)
Xstruct.upsampfactor = upsampfactor; % rlen / slen
Xstruct.Minterp = kron(speye(slen),ones(upsampfactor,1)); % rlen x slen matrix for upsampling and downsampling
Xstruct.dtStim = gg.dtStim; % time bin size for stimulus
Xstruct.dtSp = gg.dtSp; % time bins size for spike train
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/makeFittingStruct_GLMbi.m | .m | 1,806 | 53 | function gg = makeFittingStruct_GLMbi(krank,varargin)
% gg = makeFittingStruct_GLM(krank,dtStim,dtSp,klength,nkbasis,k0,nhbasis,lasthpeak)
%
% Initialize parameter struct for fitting generalized linear model (GLM),
% with bilinear (i.e., low-rank) parametrization stimulus filter
%
% Inputs:
% krank = rank of stim filter
% dtStim = bin size of stimulus (in s)
% dtSp = bin size for spike train (in s)
% klength = temporal length of stimulus filter, in # of bins (optional)
% nkbasis = # temporal basis vectors for stim filter (optional)
% nhbasis = # temporal basis vectors for spike hist filter h (optional)
% lasthpeak = time of peak of last h basis vector, in s (optional)
% k0 = initial estimate of stimulus filter (optional)
%
% Outputs:
% gg = GLM-fitting param structure
% ====================================================================
% Set up structure
gg = makeFittingStruct_GLM(varargin{:});
% Set additional fields needed by bilinear GLM
gg.kx = [];
gg.kxbas=[];
gg.kbasprs = [];
gg.krank = krank;
gg.ktype = 'bilinear';
% if initial filter passed in, use svd to set up initial K params (bilinearly parametrized)
if (length(varargin)>4) && (~isempty(varargin{3}))
k0 = varargin{5};
[u,s,v] = svd(k0);
mux = mean(k0)';
nkt = size(gg.ktbas,2);
nkx = size(k0,2);
kt = zeros(nkt,krank);
kx = zeros(nkx,krank);
for j = 1:krank;
if v(:,j)'*mux < 0 % Flip sign if shape looks opposite to k0
u(:,j) = -u(:,j); v(:,j) = -v(:,j);
end
kt(:,j) = (gg.ktbas'*gg.ktbas)\(gg.ktbas'*(u(:,j)*s(j,j)));
kx(:,j) = v(:,j);
end
gg.kxbas = speye(nkx);
gg.kt = kt;
gg.kx = kx;
gg.k = (gg.ktbas*gg.kt)*(gg.kxbas*gg.kx)';
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/MLfit_GLM.m | .m | 1,912 | 53 | function [gg,neglogli,H,Xstruct] = MLfit_GLM(gg,Stim,optimArgs)
% [gg,neglogli,H,Xstruct] = MLfit_GLM(gg,Stim,optimArgs)
%
% Computes the ML estimate for GLM params, using grad and hessians.
% Assumes basis for temporal dimensions of stim filter
%
% Inputs:
% gg = param struct
% Stim = stimulus
% optimArgs = cell array of optimization params (optional)
%
% Outputs:
% ggnew = new param struct (with ML params);
% neglogli = negative log-likelihood at ML estimate
% H = Hessian of negative log-likelihood at ML estimate
% Xstruct = structure with design matrices for spike-hist and stim terms
% Set optimization parameters
algopts = getFminOptsForVersion(version);
if nargin > 2, opts = optimset(algopts{:}, optimArgs{:});
else, opts = optimset(algopts{:});
end
% --- Create design matrix extract initial params from gg ----------------
[prs0,Xstruct] = setupfitting_GLM(gg,Stim);
% --- Set loss function --------------------------------------------------
if isequal(Xstruct.nlfun,@expfun) || isequal(Xstruct.nlfun,@exp)
lfunc = @(prs)Loss_GLM_logli_exp(prs,Xstruct); % loss function for exponential nonlinearity
else
lfunc = @(prs)Loss_GLM_logli(prs,Xstruct); % loss function for all other nonlinearities
end
% --- minimize negative log likelihood --------------------
[prsML,neglogli] = fminunc(lfunc,prs0,opts); % find ML estimate of params
% Compute Hessian if desired
if nargout > 2
[neglogli,~,H] = Loss_GLM_logli(prsML,Xstruct);
end
% Put returned vals back into param structure ------
gg = reinsertFitPrs_GLM(gg,prsML,Xstruct);
% %----------------------------------------------------
% Optional debugging code
% %----------------------------------------------------
%
% % ------ Check analytic gradients and Hessians -------
% HessCheck(lfunc,prs0,opts);
% HessCheck_Elts(@Loss_GLM_logli, [1 12],prs0,opts);
% tic; [lival,J,H]=lfunc(prs0); toc;
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_fitting/Loss_GLM_logli_exp.m | .m | 3,269 | 100 | function [logli, dL, H] = Loss_GLM_logli_exp(prs,Xstruct)
% [neglogli, dL, H] = Loss_GLM_logli_exp(prs)
%
% Compute negative log-likelihood of data undr the GLM model with
% exponential nonlinearity (with standard linear parametrization of stim filter)
%
% Inputs:
% prs = [kprs - weights for stimulus kernel
% dc - dc current injection
% ihprs - weights on post-spike current];
% Outputs:
% logli = negative log likelihood of spike train
% dL = gradient with respect to prs
% H = hessian
% Extract some vals from Xstruct (Opt Prs);
nktot = Xstruct.nkx*Xstruct.nkt; % total # params for k
dt = Xstruct.dtSp; % absolute bin size for spike train (in sec)
% Unpack GLM prs;
kprs = prs(1:nktot);
dc = prs(nktot+1);
ihprs = prs(nktot+2:end);
% Extract some other stuff we'll use a lot
XXstm = Xstruct.Xstim; % stimulus design matrix
XXsp = Xstruct.Xsp; % spike history design matrix
bsps = Xstruct.bsps; % binary spike vector
M = Xstruct.Minterp; % matrix for interpolating from stimulus bins to spike train bins
ihflag = Xstruct.ihflag; % flag
rlen = Xstruct.rlen; % number of bins in spike train vector
nsp = sum(bsps); % number of spikes
% -------- Compute sum of filter reponses -----------------------
if Xstruct.ihflag
Itot = M*(XXstm*kprs) + XXsp*ihprs + dc; % stim-dependent + spikehist-dependent inputs
else
Itot = M*(XXstm*kprs) + dc; % stim-dependent input only
end
% --------- Compute output of nonlinearity ------------------------
rr = exp(Itot);
% --------- Compute log-likelihood ---------------------------------
Trm1 = sum(rr)*dt; % non-spike term
Trm2 = -sum(Itot(bsps)); % spike term
logli = Trm1 + Trm2;
% --------- Compute Gradient -----------------
if (nargout > 1)
% Non-spiking terms (Term 1)
dLdk0 = (rr'*M*XXstm)';
dLdb0 = sum(rr);
if ihflag, dLdh0 = (rr'*XXsp)';
end
% Spiking terms (Term 2)
Msp = M(bsps,:); % interpolation matrix just for spike bins
dLdk1 = (sum(Msp*XXstm))';
dLdb1 = nsp;
if ihflag, dLdh1 = sum(XXsp(bsps,:),1)';
end
% Combine terms
dLdk = dLdk0*dt - dLdk1;
dLdb = dLdb0*dt - dLdb1;
if ihflag, dLdh = dLdh0*dt - dLdh1;
else dLdh = [];
end
dL = [dLdk; dLdb; dLdh];
end
% --------- Compute Hessian -----------------
if nargout > 2
% --- Non-spiking terms -----
% multiply each row of M with drr
ddrrdiag = spdiags(rr,0,rlen,rlen);
ddqqIntrp = ddrrdiag*M; % this is MUCH faster than using bsxfun, due to sparsity!
% k and b terms
Hk = (XXstm'*(M'*ddqqIntrp)*XXstm)*dt; % Hkk (k filter)
Hb = dLdb0*dt; % Hbb (constant b)
Hkb = (sum(ddqqIntrp,1)*XXstm)'*dt; % Hkb (cross-term)
if ihflag % h terms
Hh = (XXsp'*(bsxfun(@times,XXsp,rr)))*dt; % Hh (h filter)
% (here bsxfun is faster than diagonal multiplication)
Hkh = ((XXsp'*ddqqIntrp)*XXstm*dt)'; % Hhk (cross-term)
Hhb = (rr'*XXsp)'*dt; % Hhb (cross-term)
else
Hkh=[]; Hhb=[]; Hh=[];
end
H = [[Hk Hkb Hkh]; [Hkb' Hb Hhb']; [Hkh' Hhb Hh]];
end
| MATLAB |
2D | pillowlab/GLMspiketools | unittests/unit_condIntensityConsistency_cpl.m | .m | 3,361 | 85 | % Unit test to check the consistency of conditional intensity computed
% during simulation and during fitting, using spikes from generated from a
% simulation of coupled neurons in demo3
% 1. First, run relevant section of demo3
dtStim = .01; % Bin size for simulating model & computing likelihood (in units of stimulus frames)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
nkt = 20; % Number of time bins in stimulus filter k
ggsim1 = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM struct with default params
ggsim2 = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM struct with default params
% Change second neuron's stimulus filter
[ktbas,ktbasis] = makeBasis_StimKernel(ggsim2.ktbasprs,nkt);
ggsim2.k = ktbasis*[0 0 .1 .25 .5 .5 .25 -.25 -.5 -.25]'; % more delayed filter
ggsim = makeSimStruct_GLMcpl(ggsim1,ggsim2);
% Make some coupling kernels
[iht,ihbas,ihbasis] = makeBasis_PostSpike(ggsim.ihbasprs,dtSp);
hhcpl = ihbasis*[.25;.25;.125;0;0];
hhcpl(:,2) = ihbasis*[-2;-1;0;.25;.25];
ggsim.ih(:,2,1) = hhcpl(:,2); % 2nd cell coupling to first
ggsim.ih(:,1,2) = hhcpl(:,1); % 1st cell coupling to second
% Run short simulation for visualization purposes
slen = 50; % Stimulus length (frames) & width (# pixels)
swid = size(ggsim.k,2); % stimulus width
Stim = 2*randn(slen,swid); % Gaussian white noise stimulus
[tsp,sps,Itot,Istm] = simGLM(ggsim, Stim); % Simulate GLM response
Isp = Itot-Istm; % net spike-history output
%% 2. compute conditional intensity again during log-likelihood evaluation
% Make param object with "true" params
ggTrue = makeFittingStruct_GLM(dtStim,dtSp);
ggTrue.k = ggsim.k(:,:,1); % % insert stimulus filter
ggTrue.dc = ggsim.dc(1); % insert dc value
ggTrue.ih = ggsim.ih(:,:,1); % insert spike-history filter
ggTrue.sps = sps(:,1); % spike times
ggTrue.sps2 = sps(:,2); % spike times of coupled neuron
ggTrue.couplednums = 2; % number of cell coupled to this one (for clarity)
[logliTrue2,rrT2,tt2,Itot2,Istm2,Ih2] = neglogli_GLM(ggTrue,Stim);
% ---- Unit tests -------
% On total log-conditional intensity
assert(max(abs(Itot(:,1)-Itot2))<1e-8,'Unit failed: log-conditional intensity consistency');
% On just the stimulus component of the conditional intensity
assert(max(abs(Istm(:,1)-Istm2))<1e-8,'Unit failed: spike-history filter output consistency');
%% 3. Do same for other neuron
% Make param object with "true" params
ggTrue = makeFittingStruct_GLM(dtStim,dtSp);
ggTrue.k = ggsim.k(:,:,2); % % insert stimulus filter
ggTrue.dc = ggsim.dc(2); % insert dc value
ggTrue.ih = fliplr(ggsim.ih(:,:,2)); % insert spike-history filter
ggTrue.sps = sps(:,2); % spike times
ggTrue.sps2 = sps(:,1); % spike times of coupled neuron
ggTrue.couplednums = 1; % number of cell coupled to this one (for clarity)
[logliTrue3,rrT3,tt3,Itot3,Istm3,Ih3] = neglogli_GLM(ggTrue,Stim);
% ---- Unit tests -------
% On total log-conditional intensity
assert(max(abs(Itot(:,2)-Itot3))<1e-8,'Unit failed: log-conditional intensity consistency');
% On just the stimulus component of the conditional intensity
assert(max(abs(Istm(:,2)-Istm3))<1e-8,'Unit failed: spike-history filter output consistency');
% ===================================
% Report if passed
% ===================================
fprintf('Unit passed: condIntensityConsistency_cpl\n');
| MATLAB |
2D | pillowlab/GLMspiketools | unittests/unit_condIntensityConsistency.m | .m | 1,954 | 51 | % Unit testing code to ensure that conditional intensity is computed the
% same way during simulation as during fitting
%% 1. Set parameters and display for a GLM % ==============================
dtStim = .01; % Bin size for stimulus (in seconds). (Equiv to 100Hz frame rate)
dtSp = .001; % Bin size for simulating model & computing likelihood (must evenly divide dtStim);
nkt = 30; % Number of time bins in stimulus filter k
ttk = dtStim*(-nkt+1:0)'; % time relative to spike of stim filter taps
ggsim = makeSimStruct_GLM(nkt,dtStim,dtSp); % Create GLM structure with default params
%% 2. Simulate model and compute conditional intensity ====================
slen = 5000; % Stimulus length (frames); More samples gives better fit
swid = 1;
Stim = randn(slen,swid); % Run model on long, binary stimulus
[tsp,sps,Itot,Istm] = simGLM(ggsim,Stim); % run model and return conditional intensity
nsp = length(tsp);
%% 3. Make param object with "true" params ================================
ggTrue = makeFittingStruct_GLM(dtStim,dtSp);
ggTrue.k = ggsim.k; % insert stimulus filter
ggTrue.dc = ggsim.dc; % insert dc value
ggTrue.ih = ggsim.ih; % insert spike-history filter
ggTrue.sps = sps; % spike times
ggTrue.mask = [];
%% 4. Compute intensity again (during computation of log-likelihood) ======
% (if desired, compare rrT computed here with vmem computed above).
% To make it fail if you want to:
% Stim(1) = Stim(1)+.1;
[logliTrue, rrT,tt,Itot2,Istm2,Ih2] = neglogli_GLM(ggTrue,Stim);
%% 5. Unit tests
% On total log-conditional intensity
assert(max(abs(Itot-Itot2))<1e-8,'Unit failed: log-conditional intensity consistency');
% On just the stimulus component of the conditional intensity
assert(max(abs(Istm-Istm2))<1e-8,'Unit failed: spike-history filter output consistency');
% ===================================
% Report if passed
% ===================================
fprintf('Unit passed: condIntensityConsistency\n');
| MATLAB |
2D | MRSRL/mridata-recon | recon_2d_fse.py | .py | 10,357 | 268 | """Basic recon for 2D FSE datasets on mridata.org."""
import numpy as np
import os
import ismrmrd
import argparse
import imageio
from tqdm import tqdm
from fileio import cfl
from mrirecon import fse
from mrirecon import fftc
def isrmrmd_user_param_to_dict(header):
"""
Store ISMRMRD header user parameters in a dictionary.
Parameter
---------
header : ismrmrd.xsd.ismrmrdHeader
ISMRMRD header object
Returns
-------
dict
Dictionary containing custom user parameters
"""
user_dict = {}
user_long = list(header.userParameters.userParameterLong)
user_double = list(header.userParameters.userParameterDouble)
user_string = list(header.userParameters.userParameterString)
user_base64 = list(header.userParameters.userParameterBase64)
for entry in user_long + user_double + user_string + user_base64:
user_dict[entry.name] = entry.value_
return user_dict
def load_ismrmrd_to_np(file_name, verbose=False):
"""
Load data from an ISMRMRD file to a numpy array.
Raw data from the ISMRMRD file is loaded into a numpy array. If the ISMRMRD file includes the array 'rec_std' that contains the standard deviation of the noise, this information is used to pre-whiten the k-space data. If applicable, a basic phase correction is performed on the loaded k-space data.
Parameters
----------
file_name : str
Name of ISMRMRD file
verbose : bool, optional
Turn on/off verbose print out
Returns
-------
np.array
k-space data in an np.array of dimensions [phase, echo, slice, coils, kz, ky, kx]
ismrmrd.xsd.ismrmrdHeader
ISMRMRD header object
"""
dataset = ismrmrd.Dataset(file_name, create_if_needed=False)
header = ismrmrd.xsd.CreateFromDocument(dataset.read_xml_header())
param_dict = isrmrmd_user_param_to_dict(header)
num_kx = header.encoding[0].encodedSpace.matrixSize.x
num_ky = header.encoding[0].encodingLimits.kspace_encoding_step_1.maximum + 1
num_kz = header.encoding[0].encodingLimits.kspace_encoding_step_2.maximum + 1
num_channels = header.acquisitionSystemInformation.receiverChannels
num_slices = header.encoding[0].encodingLimits.slice.maximum + 1
num_echoes = header.encoding[0].encodingLimits.contrast.maximum + 1
num_phases = header.encoding[0].encodingLimits.phase.maximum + 1
num_segments = header.encoding[0].encodingLimits.segment.maximum + 1
is_fse_with_calib = num_segments > 1
chop_y = 1 - int(param_dict.get('ChopY', 1))
chop_z = 1 - int(param_dict.get('ChopZ', 1))
try:
rec_std = dataset.read_array('rec_std', 0)
rec_weight = 1.0 / (rec_std ** 2)
rec_weight = np.sqrt(rec_weight / np.sum(rec_weight))
except Exception:
rec_weight = np.ones(num_channels)
opt_mat = np.diag(rec_weight)
if verbose:
print("Data dims: (%d, %d, %d, %d, %d, %d, %d)" % (num_kx, num_ky, num_kz,
num_channels, num_slices,
num_echoes, num_phases))
kspace = np.zeros([num_phases, num_echoes, num_slices, num_channels,
num_kz, num_ky, num_kx], dtype=np.complex64)
if is_fse_with_calib:
echo_train = np.zeros([num_phases, num_echoes, num_slices, 1, num_kz, num_ky, 1],
dtype=np.uint)
kspace_fse_cal = np.zeros([num_phases, num_echoes, num_slices, num_channels,
num_segments, num_kx], dtype=np.complex64)
echo_train_fse_cal = np.zeros([num_phases, num_echoes, num_slices, 1, num_segments, 1],
dtype=np.uint)
max_slice = 0
wrap = lambda x: x
if verbose:
print("Loading data...")
wrap = tqdm
try:
num_acq = dataset.number_of_acquisitions()
except:
print("Unable to determine number of acquisitions! Empty?")
return
for i in wrap(range(num_acq)):
acq = dataset.read_acquisition(i)
i_ky = acq.idx.kspace_encode_step_1 # pylint: disable=E1101
i_kz = acq.idx.kspace_encode_step_2 # pylint: disable=E1101
i_echo = acq.idx.contrast # pylint: disable=E1101
i_phase = acq.idx.phase # pylint: disable=E1101
i_slice = acq.idx.slice # pylint: disable=E1101
if i_slice > max_slice:
max_slice = i_slice
sign = (-1) ** (i_ky * chop_y + i_kz * chop_z)
data = np.matmul(opt_mat.T, acq.data) * sign
if i_kz < num_kz:
i_segment = acq.idx.segment # pylint: disable=E1101
if i_ky < num_ky:
kspace[i_phase, i_echo, i_slice, :, i_kz, i_ky, :] = data
if is_fse_with_calib:
echo_train[i_phase, i_echo, i_slice, 0, i_kz, i_ky, 0] = i_segment
elif is_fse_with_calib:
kspace_fse_cal[i_phase, i_echo, i_slice, :, i_ky - num_ky, :] = data
echo_train_fse_cal[i_phase, i_echo, i_slice, 0, i_ky - num_ky, 0] = i_segment
dataset.close()
max_slice += 1
if num_slices != max_slice:
if verbose:
print("Actual number of slices different: %d/%d" % (max_slice, num_slices))
kspace = kspace[:, :, :max_slice, :, :, :, :]
if is_fse_with_calib:
echo_train = echo_train[:, :, :max_slice, :, :, :, :]
kspace_fse_cal = kspace_fse_cal[:, :, :max_slice, :, :, :]
echo_train_fse_cal = echo_train_fse_cal[:, :, :max_slice, :, :, :]
if is_fse_with_calib:
if verbose:
print("FSE phase correction...")
if 0:
print("writing files for debugging...")
cfl.write("kspace", kspace)
cfl.write("echo_train", echo_train)
cfl.write("kspace_fse_cal", kspace_fse_cal)
cfl.write("echo_train_fse_cal", echo_train_fse_cal)
kspace_cor = fse.phase_correction(kspace, echo_train, kspace_fse_cal, echo_train_fse_cal)
# for debugging
if 0:
cfl.write("kspace_orig" , kspace)
kspace = kspace_cor
return kspace, header
def transform(kspace, header, verbose=False):
"""
Transform kspace data to image domain.
If needed, cropping is performed based on information in the header.
Parameters
----------
kspace : np.array
Data in k-space [phase, echo, slice, coils, z, ky, kx]
header : ismrmrd.xsd.ismrmrdHeader
ISMRMRD header object
verbose : bool, optional
Turn on/off print outs
Returns
-------
np.array
Data in image domain [phase, echo, slice, coils, z, y, x]
"""
image = fftc.ifft2c(kspace)
num_kx = header.encoding[0].encodedSpace.matrixSize.x
num_ky = header.encoding[0].encodingLimits.kspace_encoding_step_1.maximum + 1
num_x = header.encoding[0].reconSpace.matrixSize.x
num_y = header.encoding[0].reconSpace.matrixSize.y
if num_x < num_kx:
if verbose:
print("Cropping data in x (%d to %d)..." % (num_kx, num_x))
x0 = (num_kx - num_x) // 2
x1 = x0 + num_x
image = image[:, :, :, :, :, :, x0:x1]
if num_y < num_ky:
if verbose:
print("Cropping data in y (%d to %d)..." % (num_ky, num_y))
y0 = (num_ky - num_y) // 2
y1 = y0 + num_y
image = image[:, :, :, :, :, y0:y1, :]
return image
def dataset_to_cfl(dir_out, file_name, suffix="", file_png=None, verbose=False):
"""
Convert ISMRMRD to CFL files in specified directory.
Parameters
----------
dir_out : str
Output directory to write CFL files
file_name : str
Name of ISMRMRD file
suffix : str, optional
Suffix to attach to output file names
file_png : str, optional
If not None, a png file will be written out
verbose : bool, optional
Turn on/off verbose print outs
"""
kspace, header = load_ismrmrd_to_np(file_name, verbose=verbose)
if verbose:
print("Transforming k-space data to image domain...")
image = transform(kspace, header, verbose=verbose)
num_phases = kspace.shape[0]
num_echoes = kspace.shape[1]
if verbose:
print("Writing files...")
for i_phase in range(num_phases):
for i_echo in range(num_echoes):
suffix_i = suffix
if num_echoes > 1:
suffix_i = "_" + ("echo%02d" % i_echo) + suffix_i
if num_phases > 1:
suffix_i = "_" + ("phase%02d" % i_phase) + suffix_i
cfl.write(os.path.join(dir_out, "kspace" + suffix_i),
kspace[i_phase, i_echo, :, :, :, :, :])
cfl.write(os.path.join(dir_out, "image" + suffix_i),
image[i_phase, i_echo, :, :, :, :, :])
if file_png is not None:
if os.path.splitext(file_png)[1] != ".png":
file_png += ".png"
if verbose:
print("Writing example png ({})...".format(file_png))
energy = np.sum(np.abs(kspace) ** 2, axis=(-1, -2, -4))
i_phase, i_echo, i_slice, i_z = np.where(energy == energy.max())
image_out = image[i_phase[0], i_echo[0], i_slice[0], :, i_z[0], :, :]
image_out = np.sqrt(np.sum(np.abs(image_out) ** 2, axis=0))
image_out = image_out / np.max(image_out) * np.iinfo(np.uint8).max
imageio.imwrite(file_png, image_out.astype(np.uint8))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process ISMRMRD files")
parser.add_argument("input", action="store",
help="raw data in ISMRMRD format")
parser.add_argument("-o", "--output", default="./",
help="output directory (default: ./)")
parser.add_argument("-p", "--png", default=None,
help="png file name (default: None)")
parser.add_argument("-s", "--suffix", default="",
help="suffix to file output")
parser.add_argument("-v", "--verbose", action="store_true",
help="verbose printing (default: False)")
args = parser.parse_args()
dataset_to_cfl(args.output, args.input, suffix=args.suffix,
file_png=args.png, verbose=args.verbose)
| Python |
2D | MRSRL/mridata-recon | fileio/__init__.py | .py | 0 | 0 | null | Python |
2D | MRSRL/mridata-recon | fileio/cfl.py | .py | 1,764 | 72 | """Read/write files for BART"""
# This file is slightly modified from the file:
# https://github.com/mrirecon/bart/blob/master/python/cfl.py
# Copyright 2013-2015. The Regents of the University of California.
# All rights reserved. Use of this source code is governed by
# a BSD-style license which can be found in the LICENSE file.
#
# Authors:
# 2013 Martin Uecker <uecker@eecs.berkeley.edu>
# 2015 Jonathan Tamir <jtamir@eecs.berkeley.edu>
import numpy as np
def read_hdr(name, order='C'):
"""Read hdr file."""
# get dims from .hdr
h = open(name + ".hdr", "r")
h.readline() # skip line
l = h.readline()
h.close()
dims = [int(i) for i in l.split()]
if order == 'C':
dims.reverse()
return dims
def read(name, order='C'):
dims = read_hdr(name, order)
# remove singleton dimensions from the end
n = np.prod(dims)
# dims_prod = np.cumprod(dims)
# dims = dims[:np.searchsorted(dims_prod, n)+1]
# load data and reshape into dims
d = open(name + ".cfl", "r")
a = np.fromfile(d, dtype=np.complex64, count=n)
d.close()
return a.reshape(dims, order=order)
def readcfl(name):
return read(name, order='F')
def write(name, array, order='C'):
h = open(name + ".hdr", "w")
h.write('# Dimensions\n')
if order=='C':
for i in array.shape[::-1]:
h.write("%d " % i)
else:
for i in (array.shape):
h.write("%d " % i)
h.write('\n')
h.close()
d = open(name + ".cfl", "w")
if order=='C':
array.astype(np.complex64).tofile(d)
else:
# tranpose for column-major order
array.T.astype(np.complex64).tofile(d)
d.close()
def writecfl(name, array):
write(name, array, order='F')
| Python |
2D | MRSRL/mridata-recon | mrirecon/fse.py | .py | 2,670 | 73 | """General recon functions for FSE datasets."""
import numpy as np
from mrirecon import fftc
def _compute_coefficients_ahncho(kscalib):
"""Compute correction coefficients for FSE using Ahn-Cho method.
kscalib: [..., channels, segments, kx]
"""
# offset start and end to avoid effects from fft wrap
istart = 5
iend = -5
kscalib_shape = kscalib.shape
num_segments = kscalib_shape[-2]
num_kx = kscalib_shape[-1]
kscalib = np.reshape(kscalib, [-1, num_segments, num_kx])
imcalib = fftc.ifftc(kscalib, axis=-1)
imcalib_ref = np.conj(imcalib) * imcalib[:, :1, :]
p1_calc = np.angle(np.mean(imcalib_ref[:, :, istart:iend]
* np.conj(imcalib_ref[:, :, (istart+1):(iend+1)]), axis=-1))
p1_calc = np.expand_dims(p1_calc, axis=-1)
x = np.arange(num_kx * 1.0)
x = np.reshape(x, [1, 1, num_kx])
imcalib_cor1 = imcalib_ref * np.exp(1j * x * p1_calc)
p0_calc = np.angle(np.mean(imcalib_cor1, axis=-1))
p1_calc = np.reshape(p1_calc, kscalib_shape[:-2] + p1_calc.shape[-2:])
p0_calc = np.reshape(p0_calc, kscalib_shape[:-2] + p0_calc.shape[-1:] + (1,))
return p0_calc, -p1_calc
def phase_correction(kspace, echo_train, kspace_fse_calib, echo_train_fse_calib):
"""Perform linear phase correction for FSE scans
kspace: [phases, echoes, slices, channels, kz, ky, kx]
echo_train: [phases, echoes, slices, 1, segments, 1]
"""
x = np.arange(kspace.shape[-1] * 1.0)
x = np.reshape(x, [1, 1, -1])
p0, p1 = _compute_coefficients_ahncho(kspace_fse_calib)
ksx = fftc.ifftc(kspace, axis=-1)
num_phases = ksx.shape[0]
num_echoes = ksx.shape[1]
num_slices = ksx.shape[2]
num_kz = ksx.shape[-3]
for i_phase in range(num_phases):
for i_echo in range(num_echoes):
for i_slice in range(num_slices):
for i_kz in range(num_kz):
ind = echo_train[i_phase, i_echo, i_slice, 0, i_kz, :, 0]
ind_calib = echo_train_fse_calib[i_phase, i_echo, i_slice, 0, :, 0]
ks_slice = ksx[i_phase, i_echo, i_slice, :, i_kz, :, :]
p0_slice = p0[i_phase, i_echo, i_slice, :, ind_calib, :]
p0_slice = np.transpose(p0_slice[ind, :, :], [1, 0, 2])
p1_slice = p1[i_phase, i_echo, i_slice, :, ind_calib, :]
p1_slice = np.transpose(p1_slice[ind, :, :], [1, 0, 2])
ks_slice *= np.exp(1j * (p0_slice + x * p1_slice))
ksx[i_phase, i_echo, i_slice, :, i_kz, :, :] = ks_slice
kspace_cor = fftc.fftc(ksx, axis=-1)
return kspace_cor
| Python |
2D | MRSRL/mridata-recon | mrirecon/__init__.py | .py | 0 | 0 | null | Python |
2D | MRSRL/mridata-recon | mrirecon/fftc.py | .py | 1,755 | 77 | try:
import pyfftw.interfaces.numpy_fft as fft
except:
from numpy import fft
import numpy as np
def ifftnc(x, axes):
tmp = fft.fftshift(x, axes=axes)
tmp = fft.ifftn(tmp, axes=axes)
return fft.ifftshift(tmp, axes=axes)
def fftnc(x, axes):
tmp = fft.fftshift(x, axes=axes)
tmp = fft.fftn(tmp, axes=axes)
return fft.ifftshift(tmp, axes=axes)
def fftc(x, axis=0, do_orthonorm=True):
if do_orthonorm:
scale = np.sqrt(x.shape[axis])
else:
scale = 1.0
return fftnc(x, (axis,)) / scale
def ifftc(x, axis=0, do_orthonorm=True):
if do_orthonorm:
scale = np.sqrt(x.shape[axis])
else:
scale = 1.0
return ifftnc(x, (axis,)) * scale
def fft2c(x, order='C', do_orthonorm=True):
if order == 'C':
if do_orthonorm:
scale = np.sqrt(np.prod(x.shape[-2:]))
else:
scale = 1.0
return fftnc(x, (-2, -1)) / scale
else:
if do_orthonorm:
scale = np.sqrt(np.prod(x.shape[:2]))
else:
scale = 1.0
return fftnc(x, (0, 1)) / scale
def ifft2c(x, order='C', do_orthonorm=True):
if order == 'C':
if do_orthonorm:
scale = np.sqrt(np.prod(x.shape[-2:]))
else:
scale = 1.0
return ifftnc(x, (-2, -1)) * scale
else:
if do_orthonorm:
scale = np.sqrt(np.prod(x.shape[:2]))
else:
scale = 1.0
return ifftnc(x, (0, 1)) * scale
def fft3c(x, order='C'):
if order == 'C':
return fftnc(x, (-3, -2, -1))
else:
return fftnc(x, (0, 1, 2))
def ifft3c(x, order='C'):
if order == 'C':
return ifftnc(x, (-3, -2, -1))
else:
return ifftnc(x, (0, 1, 2))
| Python |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | Library.m | .m | 21,731 | 709 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Library load %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DB = importdata('materialDB_ZB.csv',',');
%DB = importdata('materialDB_WZ.csv',',');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Here is a patch to be able to load the tables in Matlab AND Octave %%%%%%
% Matlab see the header in multiple cells while Octave see the header in one cell only
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaAs';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaAs = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaAs=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlAs';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlAs = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlAs=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InAs';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InAs = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InAs=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InSb = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InSb=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaSb = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaSb=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlSb = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlSb=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InP = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InP=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaP = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaP=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlP = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlP=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='Si';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
Si = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
Si=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='Ge';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
Ge = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
Ge=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='SiGe';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
SiGe_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
SiGe_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlGaAs';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlGaAs_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlGaAs_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InGaAs';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InGaAs_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InGaAs_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlInAs';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlInAs_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlInAs_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaInP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaInP_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaInP_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlInP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlInP_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlInP_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlGaP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlGaP_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlGaP_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaInSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaInSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaInSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlInSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlInSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlInSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlGaSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlGaSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlGaSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaAsSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaAsSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaAsSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InAsSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InAsSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InAsSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlAsSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlAsSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlAsSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaAsP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaAsP_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaAsP_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InAsP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InAsP_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InAsP_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlAsP';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlAsP_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlAsP_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='GaPSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
GaPSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
GaPSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='InPSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
InPSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
InPSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
M='AlPSb';
if length(DB.textdata(1,:))==1 %% Octave data load
DB.textdata{1,1}=[DB.textdata{1,1} ',']; % patch, add a comma "," at the end
idxM=strfind(DB.textdata{1,1},',');
idx=strfind(DB.textdata{1,1},[',' M ',']);
idxM=find(idxM==idx);
AlPSb_bowing = DB.data(:,idxM)';
else %% Matlab data load
for i=1:length(DB.textdata(1,:))
idx=strcmp(DB.textdata{1,i},M);
if idx==1
AlPSb_bowing=DB.data(:,i-1)';
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | computesISBdipoles.m | .m | 1,345 | 30 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Computes ISB dipoles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Take care! Some people use meff inside the oscillator strenght f
% Actually, meff has sens in an infinite QW because there is a single mass value
% but NOT in multi-QW structure with various materials
% https://www.nextnano.com/nextnano3/tutorial/1Dtutorial_IntrabandTransitions.htm
% https://www.nextnano.com/nextnano3/tutorial/1Dtutorial_InGaAs_MQWs.htm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
z_dipole_c = zeros(length(Ec),length(Ec));
f_dipole_c = zeros(length(Ec),length(Ec));
for i=1:length(Ec)
for j=1:length(Ec)
if j>i
z_dipole_c(i,j) = abs( trapz( z , psic(:,i).*z'.*psic(:,j) ) );
f_dipole_c(i,j) = 2*m0/hbar^2 * ( Ec(j)-Ec(i) )* e * z_dipole_c(i,j)^2 ;
end
end
end
z_dipole_c = z_dipole_c + z_dipole_c.';
f_dipole_c = f_dipole_c + f_dipole_c.';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | SchrodingerPoisson1D_CB_Kane_Main.m | .m | 18,760 | 492 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% last update 20December2021, lne %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program solves the Schrodinger-Poisson equation in the conduction band
% for any heterostructures in the Zinc-Blend material.
% The program solves the Schrodinger equation with m(E,z) using different algorithms:
% -> FDM (Finite Difference Method)
% and / or
% -> Scaning/Shooting method
% The non-parabolicity is implemented via the kp model using the Kane model
% A strain model is included. It basically shifts the conduction band edge
% The strain is mainly interesting for InGaAs/GaAs heterostructures
% The non-parabolicity is also included into the density of states for the Poisson solver.
% It follows the book of Paul Harrison and actually makes the 2d density of states not constant
% -> Additionnal material can be added in the "materialDB_ZB.csv" file
% -> II-VI and cubic nitride material parameters are available but should
% be grabt in the "Library.m" file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If the code doesn t converge:
% -> decrease the doping
% -> increase the resolution dz
% -> increase the temperature (T=0K is very bad while T=10K is already much better)
% -> increase the amount of loops, Nloops
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
close all
clc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h = 6.62606896E-34; %% Planck constant [J.s]
hbar = h/(2*pi);
e = 1.602176487E-19; %% electron charge [C]
m0 = 9.10938188E-31; %% electron mass [kg]
Epsi0= 8.854187817620E-12; %% Vaccum dielectric constant [F/m]
kB = 1.3806488E-23; %% Boltzmann's constant [J/K]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nloops = 5; % number of loops
model = 2; % 1=shooting; 2=Kane
StrainModel = 0; % Activate Strain model
n = 3; % number of solution asked per model
ScF = 0.1; % scaling factor to plot the wave function [Without Dimension]
dz = 1e-10; % resolution of the grid [m]
T = 300; % Temperature [Kelvin]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DisplayResults = 1; % Switch to print or not the ISB dipoles on the shell
plot_density = 1; % Activate the plot 0 or 1
plot_convergence = 0; % Activate the plot 0 or 1
plot_field = 0; % Activate the plot 0 or 1
plot_Vbending = 0; % Activate the plot 0 or 1
plot_mass = 0; % Activate the plot 0 or 1
plot_ro = 0; % Activate the plot 0 or 1
plot_Epsi = 0; % Activate the plot 0 or 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Library; % load material parameter DB from "materialDB_ZB.csv"
ExtractParameters; % extract parameter from the Library
TernaryAlloy; % compute the ternary alloy
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% import the layer structure file %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% first column is the material used from the "library"
% second column is the length of the layer in nm
% third column is the n doping volumique of that layer in 1e18 cm-3
% You have to put a resonable amount of doping! Otherwise, it will diverge
% and you will have to damp it more by increasing the number of loops !
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
input_file;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%% NOTHING TO CHANGE ANYMORE !!! %%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%% Grabbing the parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
zt = M(:,end-1)*1e-9; % conversion of the length from nm to meter
Dopt = M(:,end)*1e18*1e6; % n doping conversion from cm-3 to m-3
Egt = M(:,idx_Eg6c) - (M(:,idx_alphaG)*T^2) ./ (T+M(:,idx_betaG)); %Eg = Eg0 - (a*T.^2)./(T + b);
CBOt = Egt+M(:,idx_VBO); % CBO form band gap difference and temperature
Dsot = M(:,idx_Dso); % Spin-Orbit shift band parameter
EPt_K= M(:,idx_EP_K); % EP Kane
Epsit= M(:,idx_Epsi); % Epsilon; dielectric constant
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Strain Model %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
at = M(:,idx_a); % lattice parameter
act = M(:,idx_ac); % Conduction band strain offset parameter
avt = M(:,idx_av); % Valence band strain offset parameter
bvt = M(:,idx_bv); % Valence band strain offset parameter
c11t = M(:,idx_c11); % strain parameter
c12t = M(:,idx_c12); % strain parameter
a0 = substrate(idx_a);
if StrainModel == 1
exxt = (a0-at)/a0; % eyyt = exxt;
ezzt = -2*c12t./c11t.*exxt;
else
exxt = (a0-at)/a0 * 0; % eyyt = exxt;
ezzt = -2*c12t./c11t.*exxt;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Discretisation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% here, I descretize the grid z, the potential V0 and that values that are needed
z=0; V0=CBOt(1); Eg=Egt(1); Dso=Dsot(1); EP_K=EPt_K(1);
Dop=Dopt(1); Epsi=Epsit(1);
ac=act(1); av=avt(1); bv=bvt(1); exx=exxt(1); ezz=ezzt(1);
for i=1:length(zt)
t=zt(i);
zv= (z(end)+dz): dz : (z(end)+dz)+t;
z=[z zv];
V0 = [ V0 ones(size(zv)) * CBOt(i) ];
Eg = [ Eg ones(size(zv)) * Egt(i) ];
Dop = [ Dop ones(size(zv)) * Dopt(i) ];
Epsi= [ Epsi ones(size(zv)) * Epsit(i) ];
EP_K= [ EP_K ones(size(zv)) * EPt_K(i) ];
Dso = [ Dso ones(size(zv)) * Dsot(i) ];
ac = [ ac ones(size(zv)) * act(i) ];
av = [ av ones(size(zv)) * avt(i) ];
bv = [ bv ones(size(zv)) * bvt(i) ];
exx = [ exx ones(size(zv)) * exxt(i) ];
ezz = [ ezz ones(size(zv)) * ezzt(i) ];
end
V0=V0-min(V0); % Shift the band in order to get the bottom of the well at zero
V0=(F0*z)+V0; % adding the electric field to the potential
Ltot=z(end)-z(1);
eyy = exx;
DCBO = -abs(ac).*(exx+eyy+ezz) ; % shift of the CB due to strain
Ntott= Dopt.*zt;
Ntot = sum(Ntott); % total number of charges
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dE1=1e-3;
dE2=1e-2;
if StrainModel == 0
E1 = min(V0):dE1:min(V0)+0.2 ;
E2 = E1(end):dE2:max(V0);
En = sort([E1 E2]);
else
E1 = min(V0+DCBO):dE1:min(V0+DCBO)+0.2 ;
E2 = E1(end):dE2:max(V0+DCBO);
En = sort([E1 E2]);
end
if model==1
EEn = repmat(En', [1 length(z)]);
V0mat = repmat(V0 , [length(En) 1]);
Egmat = repmat(Eg , [length(En) 1]);
Dsomat = repmat(Dso, [length(En) 1]);
EPmat = repmat(EP_K ,[length(En) 1]);
meK2 = 1 ./ ( 1 + EPmat ./ (EEn + Egmat-V0mat+1/3*Dsomat) ); % m(z,E) in the 2 bands Kane s model
% here, I linearize the mass versus the energy
meff0 = 1 ./ ( 1 + EPmat ./ (Egmat-V0mat+1/3*Dsomat) );
alpha = ( meK2(end,:)./meff0(end,:) - 1 ) ./ EEn(end,:);
alphamat= repmat(alpha , [length(En) 1] );
meK2lin = meff0.*(1+alphamat.*EEn); % => linearized mass
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Starting of the Poisson s loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Vs=zeros(size(z)); Vsold=Vs;
ntot=0; nloop=1;
ErrVec=1; sumVtotVec=1;
while nloop<Nloops
nloop
x = 0.5;
Vbending=Vs*x + Vsold*(1-x);
Vtot=V0+Vbending;
%%%%%%%%%%%%%%%%%%%%%%%%%%%% schrodinger solver %%%%%%%%%%%%%%%%%%%%%%%%%%%%
if model==1
dE=0.002;
precision=1e-7;
Vtotmat = repmat(Vtot, [length(En) 1]);
meK2 = 1 ./ ( 1 + EPmat ./ (EEn + Egmat-Vtotmat+1/3*Dsomat) ); % m(z,E) in the 2 bands Kane s model
[Ec,psic] = Schrod_Nbands_shoot_f(z,Vtot+DCBO,meK2,n,En,dE,precision);
elseif model==2
[Ec,psic] = Schrod_2bands_Kane_f(z,Vtot,Eg,EP_K,Dso,n,ac,av,bv,exx,ezz);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Here, I re-define the energy grid in order optimize the meshing
dE1=1e-4;
dE2=1e-2;
if StrainModel == 0
E1 = Ec(1):dE1:Ec(1)+0.1 ;
E2 = E1(end):dE2:max(Vtot);
En=sort([E1 E2]);
else
E1 = Ec(1):dE1:Ec(1)+0.1 ;
E2 = E1(end):dE2:max(Vtot+DCBO);
En=sort([E1 E2]);
end
EEn = repmat(En' , [1 length(z) ]);
V0mat = repmat(V0 , [length(En) 1]);
Vtotmat = repmat(Vtot, [length(En) 1]);
Egmat = repmat(Eg , [length(En) 1]);
Dsomat = repmat(Dso , [length(En) 1]);
EPmat = repmat(EP_K, [length(En) 1]);
meK2 = 1 ./ ( 1 + EPmat ./ (EEn + Egmat-Vtotmat+1/3*Dsomat) ); % m(z,E) in the 2 bands Kane s model
% here, I linearize the mass versus the energy
meff0 = 1 ./ ( 1 + EPmat ./ (Egmat-Vtotmat+1/3*Dsomat) );
alpha = ( meK2(end,:)./meff0(end,:) - 1 ) ./ EEn(end,:);
alphamat= repmat(alpha , [length(En) 1] );
meK2lin = meff0.*(1+alphamat.*EEn); % => linearized mass
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Paul Harrisson
% Quantum Wells, Wires and Dots.
% 4th edition (2016),
% chap 2 : "Solutions to Schrodinger's equation"
% 2.42: "Two-dimensional systems" page 31
meffro = meff0.*(1+2*alphamat.*EEn); % => linearized mass
ro=[];
for i=1:length(Ec)
%ro( En>Ec(i),:,i) = e* meK2(En>Ec(i),:) * m0/(pi*hbar^2);
%ro( En>Ec(i),:,i) = e*meK2lin(En>Ec(i),:) * m0/(pi*hbar^2);
ro( En>Ec(i),:,i) = e*meffro(En>Ec(i),:) * m0/(pi*hbar^2);
ro( En<Ec(i),:,i) = 0;
end
% here is what make the code very slow
if Ntot==0
idx=find(min(CBOt)==CBOt);
Ef=-Egt(idx(1))/2;
NN=0*Ec';
roEf=ro*0;
else
[Ef,NN,roEf]=find_Ef_f(z,Ec,psic,En,ro,Ntot,T);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ntot2 = repmat(NN,[length(z) 1]).*abs(psic).^2 ;
ntot = sum(ntot2,2)' - Dop; % remove the charge positives (ions)
%%%%%%%%%%%%%%%%%%%%%%%%%% Electrical Field %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
F = e*cumtrapz(z,ntot)./(Epsi0*Epsi);
MF = trapz(z,F)/(z(end)-z(1)); % MF=mean(F) on a nonlinear grid z
F = F-MF;
%%%%%%%%%%%%%%%%%%%%%%%%%%% New Potential %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Vsold = Vs;
Vs = -cumsum(F)*dz;
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Convergence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Err = abs( 1 - sumVtotVec(end)/sum(Vs) );
sumVtotVec(nloop) = sum(Vs);
ErrVec = [ErrVec Err];
nloop=nloop+1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Display Results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
scale_PSI;
computesISBdipoles;
if DisplayResults == 1
PrintResults;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figures %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%figure('position',[-3500 100 1000 700],'color','w');
figure('position',[10 100 1000 700],'color','w');
subplot(1,1,1,'fontsize',15)
hold on; grid on; box on;
col=colormap(jet);
if plot_density==1
grid off
pcolor(z*1e9,En,sum(ROEf,3)*1e-6 )
set(gca,'color',col(1,:))
shading flat
hcb=colorbar;
caxis([0 max(max(sum(ROEf,3)*1e-6))+1])
title(hcb,'\fontsize{8}cm-3')
if StrainModel == 0
plot(z*1e9,V0, 'w--','linewidth',1)
plot(z*1e9,Vtot,'w-' ,'linewidth',1)
else
plot(z*1e9,V0+DCBO, 'k--','linewidth',1)
plot(z*1e9,Vtot+DCBO,'k-' ,'linewidth',1)
end
elseif plot_density==0
if StrainModel == 0
plot(z*1e9,V0, 'b--','linewidth',1)
plot(z*1e9,Vtot,'b-' ,'linewidth',1)
else
plot(z*1e9,V0+DCBO, 'k--','linewidth',1)
plot(z*1e9,Vtot+DCBO,'k-' ,'linewidth',1)
end
end
for i=1:length(Ec)
plot(z*1e9,PSIc(:,i),'color','r','linewidth',1)
end
plot([z(1) z(end)]*1e9,[1 1]*Ef,'g','linewidth',1)
text(z(end)*1e9*0.95,Ef+0.01,'\color{green}Fermi')
xlabel('z (nm)')
ylabel('Energy (eV)')
xlim([0 z(end)*1e9])
if StrainModel == 1
title(strcat('T=',num2str(T),'K ; dz=',num2str(dz*1e9),'nm; Ntot=',num2str(Ntot*1e-4,'%.1e'),'cm-2; with STRAIN'))
else
title(strcat('T=',num2str(T),'K ; dz=',num2str(dz*1e9),'nm; Ntot=',num2str(Ntot*1e-4,'%.1e'),'cm-2; without STRAIN'))
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_convergence==1
figure('color','w')
semilogy(1:nloop,ErrVec,'bo-')
hold on; grid on; box on;
xlabel('Cycles')
ylabel('Convergence (norm. units)')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_field==1
figure('color','w')
hold on; grid on; box on;
[AX,H1,H2]=plotyy(z*1e9,F*1e-2*1e-3,z*1e9,Dop*1e-18*1e-6);
set(H1,'color','r')
set(H2,'color','b')
xlabel('z (nm)')
ylabel(AX(1),'E- field (kV/cm)','color','red')
ylabel(AX(2),'Doping (1e18 cm-3)','color','blue')
set(AX(1),'ycolor','red')
set(AX(2),'ycolor','blue')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_Vbending==1
figure('color','w')
hold on; grid on; box on;
[AX,H1,H2]=plotyy(z*1e9,Vbending,z*1e9,ntot*1e-18*1e-6);
set(H1,'color','r')
set(H2,'color','b')
xlabel('z (nm)')
ylabel(AX(1),'Vbending (eV)','color','red')
ylabel(AX(2),'ntot (1e18 cm-3)','color','blue')
set(AX(1),'ycolor','red')
set(AX(2),'ycolor','blue')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_mass==1
figure('color','w')
subplot(1,2,1)
hold on; grid on; box on;
pcolor(z*1e9,En,meK2)
colormap(jet)
hcb=colorbar;
title(hcb,'\fontsize{8}meff')
shading flat
xlabel('z (nm)')
ylabel('Energy (eV)')
title('meK2')
xlim([0 z(end)*1e9])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
subplot(1,2,2)
hold on; grid on; box on;
pcolor(z*1e9,En,meK2lin)
colormap(jet)
hcb=colorbar;
title(hcb,'\fontsize{8}meff')
shading flat
xlabel('z (nm)')
ylabel('Energy (eV)')
title('meK2-lin')
xlim([0 z(end)*1e9])
% figure
% hold on;grid on;
% idx=250;
% plot(En,meK2(:,idx),'b')
% plot(En,meK2lin(:,idx),'r')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_ro==1
figure('color','w')
hold on; grid on; box on;
surf(z*1e9,En,sum(ro,3))
view(45,30)
colormap(jet)
hcb=colorbar;
title(hcb,'\fontsize{8}ro')
shading flat
xlabel('z (nm)')
ylabel('Energy (eV)')
xlim([0 z(end)*1e9])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_Epsi==1
figure('color','w')
hold on; grid on; box on;
plot(z*1e9,Epsi,'.-')
xlabel('z (nm)')
ylabel('Epsilon')
xlim([0 z(end)*1e9])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
| MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | scale_PSI.m | .m | 815 | 17 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Scaling and shifting the wavefunctions %%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:length(Ec)
PSIc(:,i)=abs(psic(:,i)).^2/max(abs(psic(:,i)).^2)*ScF + Ec(i); % normalisation for the plotting
end
% ROEf is only build to plot the density of electron in a 2D map
for ii=1:length(Ec)
psic_M = repmat(psic(:,ii),[1,length(En)])';
ROEf(:,:,ii) = roEf(:,:,ii) .* abs(psic_M.^2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | SchrodingerPoisson1D_CB_Main.m | .m | 17,453 | 457 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% last update 25December2021, lne %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This program solves the Schrodinger-Poisson equation in the conduction band
% for any heterostructures.
% The program solves the Schrodinger equation with m(E,z) using the Scaning/Shooting
% method. The non-parabolicity is implemented via the alpha parameter, alpha=1/Egap;
% meff(E)=meff(0)*(1+alpha*E);
% It can be easily modified by tuning the alpha in each layer => line 109
% A strain model is included. It basically shifts the conduction band edge
% The strain is mainly interesting for InGaAs/GaAs heterostructures
% The non-parabolicity is also included into the density of states for the Poisson solver.
% It follows the book of Paul Harrison and actually makes the 2d density of states not constant
% -> Additionnal material can be added in the "materialDB_ZB.csv" file
% -> II-VI and cubic nitride material parameters are available but should
% be grabt in the "Library.m" file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If the code doesn t converge:
% -> decrease the doping
% -> increase the resolution dz
% -> increase the temperature (T=0K is very bad while T=10K is already much better)
% -> increase the amount of loops, Nloops
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
close all
clc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h = 6.62606896E-34; %% Planck constant [J.s]
hbar = h/(2*pi);
e = 1.602176487E-19; %% electron charge [C]
m0 = 9.10938188E-31; %% electron mass [kg]
Epsi0= 8.854187817620E-12; %% Vaccum dielectric constant [F/m]
kB = 1.3806488E-23; %% Boltzmann's constant [J/K]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nloops = 5; % number of loops
StrainModel = 0; % Activate Strain model
n = 4; % number of solution asked per model
ScF = 0.1; % scaling factor to plot the wave function [Without Dimension]
dz = 1e-10; % resolution of the grid [m]
T = 300; % Temperature [Kelvin]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DisplayResults = 1; % Switch to print or not the ISB dipoles on the shell
plot_density = 1; % Activate the plot 0 or 1
plot_convergence = 0; % Activate the plot 0 or 1
plot_field = 0; % Activate the plot 0 or 1
plot_Vbending = 0; % Activate the plot 0 or 1
plot_mass = 0; % Activate the plot 0 or 1
plot_ro = 0; % Activate the plot 0 or 1
plot_Epsi = 0; % Activate the plot 0 or 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Library; % load material parameter DB from "materialDB_ZB.csv"
ExtractParameters; % extract parameter from the Library
TernaryAlloy; % compute the ternary alloy
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% import the layer structure file %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% first column is the material used from the "library"
% second column is the length of the layer in nm
% third column is the n doping volumique of that layer in 1e18 cm-3
% You have to put a resonable amount of doping! Otherwise, it will diverge
% and you will have to damp it more by increasing the number of loops !
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
input_file;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%% NOTHING TO CHANGE ANYMORE !!! %%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%% Grabbing the parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
zt = M(:,end-1)*1e-9; % conversion of the length from nm to meter
Dopt = M(:,end)*1e18*1e6; % n doping conversion from cm-3 to m-3
Egt = M(:,idx_Eg6c) - (M(:,idx_alphaG)*T^2) ./ (T+M(:,idx_betaG)); %Eg = Eg0 - (a*T.^2)./(T + b);
CBOt = Egt+M(:,idx_VBO); % CBO form band gap difference and temperature
%Dsot = M(:,idx_Dso); % Spin-Orbit shift band parameter
%EPt_K= M(:,idx_EP_K); % EP Kane
Epsit = M(:,idx_Epsi); % Epsilon; dielectric constant
mefft = M(:,idx_me); % electron effective mass at band edge
alphat= 1./Egt; % non-parabolicity parameter => can be adjusted!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Strain Model %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
at = M(:,idx_a); % lattice parameter
act = M(:,idx_ac); % Conduction band strain offset parameter
avt = M(:,idx_av); % Valence band strain offset parameter
bvt = M(:,idx_bv); % Valence band strain offset parameter
c11t = M(:,idx_c11); % strain parameter
c12t = M(:,idx_c12); % strain parameter
a0 = substrate(idx_a);
if StrainModel == 1
exxt = (a0-at)/a0; % eyyt = exxt;
ezzt = -2*c12t./c11t.*exxt;
else
exxt = (a0-at)/a0 * 0; % eyyt = exxt;
ezzt = -2*c12t./c11t.*exxt;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Discretisation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% here, I descretize the grid z, the potential V0 and that values that are needed
z=0; V0=CBOt(1); Eg=Egt(1);
meff=mefft(1); alpha=alphat(1);
Dop=Dopt(1); Epsi=Epsit(1);
ac=act(1); av=avt(1); bv=bvt(1); exx=exxt(1); ezz=ezzt(1);
for i=1:length(zt)
t = zt(i);
zv = (z(end)+dz): dz : (z(end)+dz)+t;
z = [z zv];
V0 = [ V0 ones(size(zv)) * CBOt(i) ];
Eg = [ Eg ones(size(zv)) * Egt(i) ];
Dop = [ Dop ones(size(zv)) * Dopt(i) ];
Epsi = [ Epsi ones(size(zv)) * Epsit(i) ];
meff = [ meff ones(size(zv)) * mefft(i) ];
alpha= [ alpha ones(size(zv)) * alphat(i)];
ac = [ ac ones(size(zv)) * act(i) ];
av = [ av ones(size(zv)) * avt(i) ];
bv = [ bv ones(size(zv)) * bvt(i) ];
exx = [ exx ones(size(zv)) * exxt(i) ];
ezz = [ ezz ones(size(zv)) * ezzt(i) ];
end
V0=V0-min(V0); % Shift the band in order to get the bottom of the well at zero
V0=(F0*z)+V0; % adding the electric field to the potential
Ltot=z(end)-z(1);
eyy = exx;
DCBO = -abs(ac).*(exx+eyy+ezz) ; % shift of the CB due to strain
Ntott=Dopt.*zt;
Ntot=sum(Ntott); % total number of charges
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dE1=1e-3;
dE2=1e-2;
if StrainModel == 0
E1 = min(V0):dE1:min(V0)+0.2 ;
E2 = E1(end):dE2:max(V0);
En=sort([E1 E2]);
else
E1 = min(V0+DCBO):dE1:min(V0+DCBO)+0.2 ;
E2 = E1(end):dE2:max(V0+DCBO);
En=sort([E1 E2]);
end
EEn = repmat(En', [1 length(z)]);
V0mat = repmat(V0 , [length(En) 1]);
Egmat = repmat(Eg , [length(En) 1]);
meffmat = repmat(meff , [length(En) 1]);
alphamat= repmat(alpha, [length(En) 1]);
melin = meffmat.*(1+alphamat.*(EEn-V0mat)); % => linearized mass
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Starting of the Poisson s loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Vs=zeros(size(z)); Vsold=Vs;
ntot=0; nloop=1;
ErrVec=1; sumVtotVec=1;
while nloop<Nloops
nloop
x = 0.5;
Vbending=Vs*x + Vsold*(1-x);
Vtot=V0+Vbending;
%%%%%%%%%%%%%%%%%%%%%%%%%%%% schrodinger solver %%%%%%%%%%%%%%%%%%%%%%%%%%%%
dE=0.002; precision=1e-7;
Vtotmat = repmat(Vtot, [length(En) 1]);
melin = meffmat.*(1+alphamat.*(EEn-Vtotmat)); % => linearized mass
[Ec,psic] = Schrod_Nbands_shoot_f(z,Vtot+DCBO,melin,n,En,dE,precision);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Here, I re-define the energy grid in order optimize the meshing
dE1=1e-4;
dE2=1e-2;
if StrainModel == 0
E1 = Ec(1):dE1:Ec(1)+0.1 ;
E2 = E1(end):dE2:max(Vtot);
En=sort([E1 E2]);
else
E1 = Ec(1):dE1:Ec(1)+0.1 ;
E2 = E1(end):dE2:max(Vtot+DCBO);
En=sort([E1 E2]);
end
EEn = repmat(En' , [1 length(z) ]);
V0mat = repmat(V0 , [length(En) 1]);
Vtotmat = repmat(Vtot, [length(En) 1]);
Egmat = repmat(Eg , [length(En) 1]);
meffmat = repmat(meff ,[length(En) 1]);
alphamat= repmat(alpha, [length(En) 1]);
melin = meffmat.*(1+alphamat.*(EEn-Vtotmat)); % => linearized mass
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Paul Harrisson
% Quantum Wells, Wires and Dots.
% 4th edition (2016),
% chap 2 : "Solutions to Schrodinger's equation"
% 2.42: "Two-dimensional systems" page 31
meffro = meffmat.*(1+2*alphamat.*EEn); % => linearized mass
ro=[];
for i=1:length(Ec)
ro( En>Ec(i),:,i) = e*meffro(En>Ec(i),:) * m0/(pi*hbar^2);
ro( En<Ec(i),:,i) = 0;
end
% here is what make the code very slow
if Ntot==0
idx=find(min(CBOt)==CBOt);
Ef=-Egt(idx(1))/2;
NN=0*Ec';
roEf=ro*0;
else
[Ef,NN,roEf]=find_Ef_f(z,Ec,psic,En,ro,Ntot,T);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ntot2 = repmat(NN,[length(z) 1]).*abs(psic).^2 ;
ntot = sum(ntot2,2)' - Dop; % remove the charge positives (ions)
%%%%%%%%%%%%%%%%%%%%%%%%%% Electrical Field %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
F = e*cumtrapz(z,ntot)./(Epsi0*Epsi);
MF = trapz(z,F)/(z(end)-z(1)); % MF=mean(F) on a nonlinear grid z
F = F-MF;
%%%%%%%%%%%%%%%%%%%%%%%%%%% New Potential %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Vsold = Vs;
Vs = -cumsum(F)*dz;
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Convergence %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Err = abs( 1 - sumVtotVec(end)/sum(Vs) );
sumVtotVec(nloop) = sum(Vs);
ErrVec = [ErrVec Err];
nloop=nloop+1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Display Results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
scale_PSI;
computesISBdipoles;
if DisplayResults == 1
PrintResults;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% figures %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%figure('position',[-3500 100 1000 700],'color','w');
figure('position',[10 100 1000 700],'color','w');
subplot(1,1,1,'fontsize',15)
hold on; grid on; box on;
col=colormap(jet);
if plot_density==1
grid off
pcolor(z*1e9,En,sum(ROEf,3)*1e-6 )
set(gca,'color',col(1,:))
shading flat
hcb=colorbar;
caxis([0 max(max(sum(ROEf,3)*1e-6))+1])
title(hcb,'\fontsize{8}cm-3')
if StrainModel == 0
plot(z*1e9,V0, 'w--','linewidth',1)
plot(z*1e9,Vtot,'w-' ,'linewidth',1)
else
plot(z*1e9,V0+DCBO, 'k--','linewidth',1)
plot(z*1e9,Vtot+DCBO,'k-' ,'linewidth',1)
end
elseif plot_density==0
if StrainModel == 0
plot(z*1e9,V0, 'b--','linewidth',1)
plot(z*1e9,Vtot,'b-' ,'linewidth',1)
else
plot(z*1e9,V0+DCBO, 'k--','linewidth',1)
plot(z*1e9,Vtot+DCBO,'k-' ,'linewidth',1)
end
end
for i=1:length(Ec)
plot(z*1e9,PSIc(:,i),'color','r','linewidth',1)
end
plot([z(1) z(end)]*1e9,[1 1]*Ef,'g','linewidth',1)
text(z(end)*1e9*0.95,Ef+0.01,'\color{green}Fermi')
xlabel('z (nm)')
ylabel('Energy (eV)')
xlim([0 z(end)*1e9])
if StrainModel == 1
title(strcat('T=',num2str(T),'K ; dz=',num2str(dz*1e9),'nm; Ntot=',num2str(Ntot*1e-4,'%.1e'),'cm-2; with STRAIN'))
else
title(strcat('T=',num2str(T),'K ; dz=',num2str(dz*1e9),'nm; Ntot=',num2str(Ntot*1e-4,'%.1e'),'cm-2; without STRAIN'))
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_convergence==1
figure('color','w')
semilogy(1:nloop,ErrVec,'bo-')
hold on; grid on; box on;
xlabel('Cycles')
ylabel('Convergence (norm. units)')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_field==1
figure('color','w')
hold on; grid on; box on;
[AX,H1,H2]=plotyy(z*1e9,F*1e-2*1e-3,z*1e9,Dop*1e-18*1e-6);
set(H1,'color','r')
set(H2,'color','b')
xlabel('z (nm)')
ylabel(AX(1),'E- field (kV/cm)','color','red')
ylabel(AX(2),'Doping (1e18 cm-3)','color','blue')
set(AX(1),'ycolor','red')
set(AX(2),'ycolor','blue')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_Vbending==1
figure('color','w')
hold on; grid on; box on;
[AX,H1,H2]=plotyy(z*1e9,Vbending,z*1e9,ntot*1e-18*1e-6);
set(H1,'color','r')
set(H2,'color','b')
xlabel('z (nm)')
ylabel(AX(1),'Vbending (eV)','color','red')
ylabel(AX(2),'ntot (1e18 cm-3)','color','blue')
set(AX(1),'ycolor','red')
set(AX(2),'ycolor','blue')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_mass==1
figure('color','w')
subplot(1,1,1)
hold on; grid on; box on;
pcolor(z*1e9,En,melin)
colormap(jet)
hcb=colorbar;
title(hcb,'\fontsize{8}meff')
shading flat
xlabel('z (nm)')
ylabel('Energy (eV)')
title('me-lin')
xlim([0 z(end)*1e9])
% figure
% hold on;grid on;
% idx=250;
% plot(En,melin(:,idx),'r')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_ro==1
figure('color','w')
hold on; grid on; box on;
surf(z*1e9,En,sum(ro,3))
view(45,30)
colormap(jet)
hcb=colorbar;
title(hcb,'\fontsize{8}ro')
shading flat
xlabel('z (nm)')
ylabel('Energy (eV)')
xlim([0 z(end)*1e9])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if plot_Epsi==1
figure('color','w')
hold on; grid on; box on;
plot(z*1e9,Epsi,'.-')
xlabel('z (nm)')
ylabel('Epsilon')
xlim([0 z(end)*1e9])
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
| MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | TernaryAlloy.m | .m | 5,184 | 123 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% III-V Ternary alloys on InP %%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=0.53;
InGaAs = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing; % In0.53Ga0.47As is lattice matched on InP
x=0.37;
InGaAs37 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing; % In0.37Ga0.63As STRAINED on InP
x=0.45;
InGaAs45 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing; % In0.45Ga0.55As STRAINED on InP
x=0.715;
InGaAs71 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing; % In0.715Ga0.285As STRAINED on InP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=0.48;
AlInAs = x*AlAs + (1-x)*InAs - x*(1-x)*AlInAs_bowing; % Al0.48In0.52As is lattice matched on InP
x=0.80;
AlInAs80 = x*AlAs + (1-x)*InAs - x*(1-x)*AlInAs_bowing; % Al0.80In0.20As STRAINED on InP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=0.51;
GaAsSb = x*GaAs + (1-x)*GaSb - x*(1-x)*GaAsSb_bowing; % GaAs0.51Sb0.49 is lattice matched on InP
% QCL: Al-fee by G. Strasser's group in Vienna, JVSTB, 32. 02C104 (2014)
% I did adjust VBO_bowing in order to get CBO=0.36eV between InGaAs/GaAsSb
x=0.56;
AlAsSb = x*AlAs + (1-x)*AlSb - x*(1-x)*AlAsSb_bowing; % AlAs0.56Sb0.44 is lattice matched on InP
% the X-valley is 0.5eV above Gamma point (indirect bandgap material)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% III-V Ternary alloys on GaAs %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=0.10;
AlGaAs_bowing(idx_Eg6c) = -0.127 + 1.310*x; % from Vurgaftman
AlGaAs_bowing(idx_VBO) = 0.27 - 1.05*x; % to adjust VBO in order to fit CBO from THz QCL
AlGaAs10 = x*AlAs + (1-x)*GaAs - x*(1-x)*AlGaAs_bowing;
x=0.15;
AlGaAs_bowing(idx_Eg6c) = -0.127 + 1.310*x; % from Vurgaftman
AlGaAs_bowing(idx_VBO) = 0.27 - 1.05*x; % to adjust VBO in order to fit CBO from THz QCL
AlGaAs15 = x*AlAs + (1-x)*GaAs - x*(1-x)*AlGaAs_bowing;
x=0.20;
AlGaAs_bowing(idx_Eg6c) = -0.127 + 1.310*x; % from Vurgaftman
AlGaAs_bowing(idx_VBO) = 0.27 - 1.05*x; % to adjust VBO in order to fit CBO from THz QCL
AlGaAs20 = x*AlAs + (1-x)*GaAs - x*(1-x)*AlGaAs_bowing;
x=0.30;
AlGaAs_bowing(idx_Eg6c) = -0.127 + 1.310*x; % from Vurgaftman
AlGaAs_bowing(idx_VBO) = 0.27 - 1.05*x; % to adjust VBO in order to fit CBO from THz QCL
AlGaAs30 = x*AlAs + (1-x)*GaAs - x*(1-x)*AlGaAs_bowing;
x=0.40;
AlGaAs_bowing(idx_Eg6c) = -0.127 + 1.310*x; % from Vurgaftman
AlGaAs_bowing(idx_VBO) = 0.27 - 1.05*x; % to adjust VBO in order to fit CBO from THz QCL
AlGaAs40 = x*AlAs + (1-x)*GaAs - x*(1-x)*AlGaAs_bowing;
x=0.50;
AlGaAs_bowing(idx_Eg6c) = -0.127 + 1.310*x; % from Vurgaftman
AlGaAs_bowing(idx_VBO) = 0.27 - 1.05*x; % to adjust VBO in order to fit CBO from THz QCL
AlGaAs50 = x*AlAs + (1-x)*GaAs - x*(1-x)*AlGaAs_bowing;
x=0.05;
InGaAs05 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.06;
InGaAs06 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.07;
InGaAs07 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.08;
InGaAs08 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.09;
InGaAs09 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.10;
InGaAs10 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.15;
InGaAs15 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.20;
InGaAs20 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.25;
InGaAs25 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.30;
InGaAs30 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
x=0.40;
InGaAs40 = x*InAs + (1-x)*GaAs - x*(1-x)*InGaAs_bowing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% III-V Ternary alloys on InAs/GaSb/AlSb %%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=0.25;
GaInSb25 = x*InSb + (1-x)*GaSb - x*(1-x)*GaInSb_bowing;
x=0.35;
GaInSb35 = x*InSb + (1-x)*GaSb - x*(1-x)*GaInSb_bowing;
x=0.09;
GaAsSb91 = x*GaAs + (1-x)*GaSb - x*(1-x)*GaAsSb_bowing; % GaAs0.09Sb0.91 is lattice matched on InAs
x=0.91;
InAsSb = x*InAs + (1-x)*InSb - x.*(1-x)*InAsSb_bowing; % In0.09As0.91Sb is lattice matched on GaSb, Eg~0.3eV
x=0.5;y=0.08;
AlGaAsSb = x*GaSb + (1-x)*(y*AlAs + (1-y)*AlSb - y*(1-y)*AlAsSb_bowing); % high barrier lattice matched on GaSb
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%% IV-IV Ternary alloys %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x=0.25;
SiGe25 = x*Ge + (1-x)*Si - x*(1-x)*SiGe_bowing;
x=0.3;
SiGe30 = x*Ge + (1-x)*Si - x*(1-x)*SiGe_bowing;
x=0.35;
SiGe35 = x*Ge + (1-x)*Si - x*(1-x)*SiGe_bowing;
x=0.4;
SiGe40 = x*Ge + (1-x)*Si - x*(1-x)*SiGe_bowing;
x=0.5;
SiGe50 = x*Ge + (1-x)*Si - x*(1-x)*SiGe_bowing;
x=0.8;
SiGe80 = x*Ge + (1-x)*Si - x*(1-x)*SiGe_bowing;
| MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | input_file.m | .m | 1,620 | 46 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Layers Structure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% first column is the material used from the "library"
% second column is the length of the layer in nm = 1e-9m
% third column is the doping of the layer in 1e18 cm-3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
substrate=InP;
F0=0;%6e6;%0; % Electric field [Volt/meter]
M=[
AlInAs 5 0
AlInAs 1 7
AlInAs 5 0
InGaAs 6 0
AlInAs 5 0
InGaAs 7 0
AlInAs 5 0
AlInAs 1 5
AlInAs 5 0
];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% substrate=GaAs; % Important for the Strain model (Si, GaAs, InP, InAs, GaSb)
% F0=0;%6e6;%0; % Electric field [Volt/meter]
% M=[
% GaAs 10 0.5
% InGaAs20 15 0
% GaAs 10 0.5
% ];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% substrate=GaAs; % Important for the Strain model (Si, GaAs, InP, InAs, GaSb)
% F0=0;%16e6;%0; % Electric field [Volt/meter]
% M=[
% AlGaAs40 5 2
% GaAs 10 0
% AlGaAs40 5 2
% ];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | find_Ef_f.m | .m | 1,701 | 54 | function[Ef,NN,roEf]=find_Ef_f(z,Ec,psic,E,ro,Ntot,T)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
e = 1.602176487E-19; %% electron charge [C]
kB = 1.3806488E-23; %% Boltzmann's constant [J/K]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
EE = repmat(E' ,[1 length(z)]);
%%%%%%%%%%%%%%%%%%% Computes the Fermi level at any T %%%%%%%%%%%%%%%%%%%%%%%%%%
if T==0
T=1e-10;
end
Ef=Ec(1);
Fermi= 1./(1+exp((EE-Ef)/(kB*T/e))) ;
FFermi=repmat(Fermi,[1 1 length(Ec)]);
roEf = ro.*FFermi;
NNz = squeeze(trapz(E,roEf,1));
NN = trapz(z,NNz.*abs(psic).^2 ,1) ;
NtotX=sum(NN);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now, it will try to get as close as posible to the real Ef with an
% error of 0.1% by dichotomy
ddE=0.01; % eV
Ef1=Ef;
Ef2=Ef1+ddE;
while abs(NtotX - Ntot)/Ntot > 0.001 % find the Fermi level at any temperature
if NtotX > Ntot
Ef = Ef - abs(Ef1-Ef2)/2 ;
Ef1 = Ef ;
else
Ef = Ef + abs(Ef1-Ef2)/2 ;
Ef2 = Ef ;
end
Fermi = 1./(1+exp((EE-Ef)/(kB*T/e))) ; % Fermi Dirac distribution function
FFermi = repmat(Fermi,[1 1 length(Ec)]);
roEf = ro.*FFermi;
NNz = squeeze(trapz(E,roEf,1));
NN = trapz(z,NNz.*abs(psic).^2 ,1) ;
NtotX = sum(NN);
end
end | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | Schrod_Nbands_shoot_f.m | .m | 3,601 | 116 | function[E,psi]=Schrod_Nbands_shoot_f(z,V0,me,n,Evec,dE,precision)
method=2; % method "2" is much more acurate than "1" but take also more time...
e=min(V0);
Emax=max(V0)+0.1;
C=0; N=0; E=[];
psi=z*0+1; psi_old=psi;
while e<Emax && length(E)<n
C = C+1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% In this block, it is scanning to find the mass at the right Energy, m(E)
idx=[0 0];
epsi=1;
while length(idx)>1
idx=find( abs( (Evec-e )) < epsi ) ;
if isempty(idx)
idx=IDX(1);
else
IDX=idx;
epsi=epsi/2;
end
end
Mass=me(idx,:);
% [ e Mass(round(end/2)) ];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
psi_old = psi;
psi=Schroed1D_Euler_Eval(z,V0,Mass,e,method);
if (sign( psi(end) ) ~= sign( psi_old(end) ) ) && C>1 % here, I catch a quantum state because the last point of psi change sign
N=N+1; de=dE;
while abs(de)>precision
if sign( psi(end) ) ~= sign( psi_old(end) )
de = -de/2;
end
e=e+de;
psi_old=psi;
psi=Schroed1D_Euler_Eval(z,V0,Mass,e,method);
end
E(N,:)=e; PSI(:,N)= psi;
C=0;
end
e=e+dE;
end
psi=PSI;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% Normalization of the Wavefunction %%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:N
z=z';
psi(:,i)=psi(:,i)/sqrt(trapz(z,abs(psi(:,i)).^2));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function[psi]=Schroed1D_Euler_Eval(z,V0,Mass,ee,method)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h=6.62606896E-34; %% Planck constant [J.s]
hbar=h/(2*pi);
e=1.602176487E-19; %% electron charge [C]
m0=9.10938188E-31; %% electron mass [kg]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dz=z(2)-z(1);
dz=[ dz diff(z)];
y = [0 1];
if method==1
for i = 1:length(z) %% number of z steps to take
dy(2) = -2*e/(hbar^2) * ( ee - V0(i) ) * y(1) ; %% Equation for dv/dz
dy(1) = Mass(i)*m0*y(2); %% Equation for dx/dz
y = y + dz(i)*dy ; %% integrate both equations with Euler
psi(i)= y(1);
end
elseif method==2
for i = 1:length(z) %% number of z steps to take
dy(2) = -2*e/(hbar^2) * ( ee - V0(i) ) * y(1) ; %% Equation for dv/dz
dy(1) = Mass(i)*m0*y(2); %% Equation for dx/dz
K = y + 0.5*dz(i)*dy;
dK(2) = -2*e/(hbar^2) * ( ee - V0(i) ) * K(1) ; %% Equation for dv/dz
dK(1) = Mass(i)*m0*K(2); %% Equation for dx/dz
y = y + dz(i)*dK;
psi(i)= y(1);
end
end
end | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | PrintResults.m | .m | 1,065 | 25 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Print Results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%display('')
display('===================================================')
display('Intersubband Results:')
display('===================================================')
%display('')
for i=1:length(Ec)
for j=1:length(Ec)
if j>i
display(strcat(...
'e',num2str(i),'-e',num2str(j),' = ',num2str( Ec(j)-Ec(i),'%.3f' ),'eV; z'...
,num2str(i),'-',num2str(j),' = ',num2str( z_dipole_c(i,j)*1e9,'%.3f' ),'nm; f'...
,num2str(i),'-',num2str(j),' = ',num2str( f_dipole_c(i,j),'%.3f' ) ...
) )
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | ExtractParameters.m | .m | 8,801 | 271 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% Extract general parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% lattice parameter
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'a');
if idx==1
idx_a=i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Epsilon static
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'Epsi_stat');
if idx==1
idx_Epsi=i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EP from the Kane model
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'EP_Kane');
if idx==1
idx_EP_K = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EP from the Luttinger model
% for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'EP_Luttinger');
% if idx==1
% idx_EP_L = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Energy level of the band 7c
%for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'Eg7c');
% if idx==1
% idx_Eg7c = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Energy level of the band 8c
%for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'Eg8c');
% if idx==1
% idx_Eg8c = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Energy level of the band 6v
%for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'Eg6v');
% if idx==1
% idx_Eg6v = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Energy level of the band 6c (the band gap in a direct band gap semiconductor)
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'Eg6cG');
if idx==1
idx_Eg6c = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Bandgap Temperature dependency parameter "alpha" at the Gamma point
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'alphaG');
if idx==1
idx_alphaG = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Bandgap Temperature dependency parameter "beta" at the Gamma point
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'betaG');
if idx==1
idx_betaG = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% split-off band energy Delta-so
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'Dso');
if idx==1
idx_Dso = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Luttinger parameter for the electrons
% for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'F');
% if idx==1
% idx_F = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Luttinger parameter gamma1
% for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'gamma1');
% if idx==1
% idx_g1 = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Luttinger parameter gamma2
% for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'gamma2');
% if idx==1
% idx_g2 = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Luttinger parameter gamma3
% for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'gamma3');
% if idx==1
% idx_g3 = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Valence band offset
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'VBO');
if idx==1
idx_VBO = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% mass for the 1band Schrodinger solver
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'me');
if idx==1
idx_me = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%% Strain parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ac Conduction band Strain parameter
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'ac');
if idx==1
idx_ac = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% av Valence band Strain parameter
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'av');
if idx==1
idx_av = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% bv Valence band Strain parameter
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'bv');
if idx==1
idx_bv = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% dv Valence band Strain parameter
%for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'dv');
% if idx==1
% idx_dv = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% c11 Valence band Strain parameter
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'c11');
if idx==1
idx_c11 = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% c12 Valence band Strain parameter
for i=1:length(DB.textdata(:,1))
idx=strcmp(DB.textdata{i,1},'c12');
if idx==1
idx_c12 = i-1;
% break % removing the break makes it slower but more compatible between Matlab and Octave
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% c44 Valence band Strain parameter
%for i=1:length(DB.textdata(:,1))
% idx=strcmp(DB.textdata{i,1},'c44');
% if idx==1
% idx_c44 = i-1;
% % break % removing the break makes it slower but more compatible between Matlab and Octave
% end
%end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | MATLAB |
2D | LaurentNevou/Q_SchrodingerPoisson1D_CB | Schrod_2bands_Kane_f.m | .m | 4,189 | 121 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Schrodinger solver on uniform grid with m(z,E)!!! %%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%% With the non-parabolic band 2x2k.p Kane model %%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function[Ec,psi_c]=Schrod_2bands_Kane_f(z,Vc,Eg,EP,Dso,n,ac,av,bv,exx,ezz)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
h=6.62606896E-34; %% Planck constant J.s
hbar=h/(2*pi);
e=1.602176487E-19; %% charge de l electron Coulomb
m0=9.10938188E-31; %% electron mass kg
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nz=length(z);
dz = z(2)-z(1);
eyy = exx;
DCBO = -abs(ac).*(exx+eyy+ezz) ; % shift of the CB due to strain
DVBOLH = +abs(av).*(exx+eyy+ezz) + abs(bv).*(exx-ezz) ; % shift of the VB due to strain
DVBOSO = +abs(av).*(exx+eyy+ezz) ; % shift of the VB due to strain
Vc=Vc+DCBO;
Vc(1)=5;
Vc(end)=5;
shift=min(Vc);
Vc=Vc-shift;
Vv=Vc-Eg+DVBOLH;
Vso=Vc-Dso-Eg+DVBOSO;
Vveff= (2*Vv+Vso)/3; % here is an effective valence band that make a ratio between LH and SO
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%% Building of the operators %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% First derivative %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%DZ1c = (0.5)*diag(ones(1,Nz-1),+1) + (-0.5)*diag(ones(1,Nz-1),-1) ;
DZ1b = (1)*diag(ones(1,Nz) ,0 ) + (-1)*diag(ones(1,Nz-1),-1) ;
DZ1f = (1)*diag(ones(1,Nz-1),+1) + (-1)*diag(ones(1,Nz) ,0 ) ;
%DZ1c=DZ1c/dz;
DZ1b=DZ1b/dz;
DZ1f=DZ1f/dz;
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Second derivative %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DZ2 =(-2)*diag(ones(1,Nz)) + (1)*diag(ones(1,Nz-1),-1) + (1)*diag(ones(1,Nz-1),1);
DZ2=DZ2/dz^2;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% Building of the Hamiltonien %%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Vc = [ (Vc(1:end-1) + Vc(2:end)) / 2 Vc(end) ];
Vveff = [ (Vveff(1:end-1) + Vveff(2:end))/ 2 Vveff(end) ];
EP = [ (EP(1:end-1) + EP(2:end)) / 2 EP(end) ];
H0=(-(hbar^2)/(2*m0)) * DZ2 ;
H11 = H0 + diag(Vc*e) ;
H22 = -H0 + diag( (Vveff)*e ) ;
% Xunpeng Ma et al. JAP, 114, 063101 (2013)
% "Two-band finite difference method for the bandstructure calculation with nonparabolicity effects in quantum cascade lasers"
% ==> It s seems to be by far the most accurate method
H12 = +1*hbar/sqrt(2*m0) * ( diag(sqrt(EP*e),0) + diag(sqrt(EP(1:end-1)*e),-1) ) .* DZ1b ;
H21 = -1*hbar/sqrt(2*m0) * ( diag(sqrt(EP*e),0) + diag(sqrt(EP(1:end-1)*e),+1) ) .* DZ1f ;
H2x2=[
H11 H12
H21 H22
];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%% Diagonalisation of the Hamiltonien %%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
H2x2=sparse(H2x2);
[psi_2x2,Energy] = eigs(H2x2,n,'SM');
E_2x2 = diag(Energy)/e ;
psi_c=[];
Ec=[];
for i=1:n
if E_2x2(i) > min(Vc)
Ec=[Ec abs(E_2x2(i))];
psi_c = [psi_c psi_2x2(1:length(z),i) ];
end
end
Ec=Ec'+shift;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Normalization of the Wavefunction %%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i=1:length(Ec)
psi_c(:,i)=psi_c(:,i)/sqrt(trapz(z',abs(psi_c(:,i)).^2));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% here is a small patch due to differences between Octave and Matlab
% Matlab order the eigen values while Octave reverse it
if length(Ec)>1
if Ec(1)>Ec(2)
psi_c=psi_c(:,end:-1:1);
Ec=Ec(end:-1:1);
end
end
end | MATLAB |
2D | obaica/vasp_wavecar_parity | main.f90 | .f90 | 587 | 19 | program main
implicit none
integer :: ierr
ierr=0
open(unit=19, file='GCOEFF.txt', status='old', action='read', iostat=ierr)
close(unit=19)
if ( ierr.eq.0 ) then
write(*,*) "'GCOEFF.txt' file exits, now calc parity."
call parity
write(*,*) "**************End of parity calculation!*********************"
else
write(*,*) "'GCOEFF.txt' file dosn't exit, now read WAVECAR."
call wavetrans
call parity
write(*,*) "**************End of parity calculation!*********************"
end if
end program main
| Fortran |
2D | obaica/vasp_wavecar_parity | wavetrans.f90 | .f90 | 10,118 | 310 | !!$************************* WaveTrans
!************************************
!!$*
!!$* input the WAVECAR file in binary format from VASP, and output
!!$* in text format a file GCOEFF of G values and corresponding plane
!!$* wave coefficients, together with energy eigenvalues and
!occupations
!!$*
!!$* Compile with gfortran or ifort. Flag "-assume byterecl" is
!required
!!$* for ifort.
!!$*
!!$* version 2.0 - July 5, 2012 - R. M. Feenstra and M. Widom
!!$* version 2.1 - Sept 30, 2012 - changed estimator for max. no. of
!!$* plane waves
!!$* version 1.3 - Sept 17, 2014 - updated 'c' value
!!$*
!!$* format of GCOEFF file:
!!$* no. wavevector values (integer)
!!$* no. bands (integer)
!!$* real space lattice vector (a1) x,y,z coefficients (real)
!!$* real space lattice vector (a2) x,y,z coefficients (real)
!!$* real space lattice vector (a3) x,y,z coefficients (real)
!!$* recip. lattice vector 1 (b1) x,y,z coefficients (real)
!!$* recip. lattice vector 2 (b2) x,y,z coefficients (real)
!!$* recip. lattice vector 3 (b3) x,y,z coefficients (real)
!!$* loop over spins
!!$* loop through wavevector values:
!!$* wavevector x,y,z components (real)
!!$* energy (complex), occupation (real)
!!$* loop through bands:
!!$* index of band (integer), no. plane waves (integer)
!!$* loop through plane waves:
!!$* ig1,ig2,ig3 values (integer) and coefficient
!(complex)
!!$* end loop through plane waves
!!$* end loop through bands
!!$* end loop through wavevector values
!!$* end loop over spins
!!$*
!!$* the x,y,z components of each G value are given in terms of the
!!$* ig1,ig2,ig3 values and the components of the recip. lattice
!vectors
!!$* according to:
!!$* ig1*b1_x + ig2*b2_x + ig3*b3_x,
!!$* ig1*b1_y + ig2*b2_y + ig3*b3_y, and
!!$* ig1*b1_z + ig2*b2_z + ig3*b3_z, respectively
!!$*
!!$* note that the energy eigenvalues are complex, as provided in the
!!$* WAVECAR file, but the imaginary part is zero (at least for all
!cases
!!$* investigated thus far)
!!$*
subroutine wavetrans
implicit real*8 (a-h, o-z)
character :: soc
complex*8, allocatable :: coeff(:,:)
complex*16, allocatable :: cener(:)
real*8, allocatable :: occ(:)
integer, allocatable :: igall(:,:)
dimension a1(3),a2(3),a3(3),b1(3),b2(3),b3(3),vtmp(3),sumkg(3),wk(3)
!!$* constant 'c' below is 2m/hbar**2 in units of 1/eV Ang^2 (value is
!!$* adjusted in final decimal places to agree with VASP value;
!!$* checks for discrepancy of any results between this and VASP
!values)
data c/0.262465831d0/
!!$* data c/0.26246582250210965422d0/
pi=4.*atan(1.)
!!$* input
soc='n'
nrecl=24
do
write(*,*)"Calculation with SoC ? 'y/n'"
read(*,*) soc
if ( soc.eq.'y' ) then
write(*,*)"Calculation with SoC!"
exit
else if ( soc.eq.'n' ) then
write(*,*)"Calculation without SoC!"
exit
else
write(*,*)"Input error, y or n"
end if
end do
write(*,*)
open(unit=10,file='WAVECAR',access='direct',recl=nrecl, &
iostat=iost,status='old')
if (iost.ne.0) write(6,*) 'open error - iostat =',iost
read(unit=10,rec=1) xnrecl,xnspin,xnprec
close(unit=10)
nrecl=nint(xnrecl)
nspin=nint(xnspin)
nprec=nint(xnprec)
if(nprec.eq.45210) then
write(6,*) '*** error - WAVECAR_double requires complex*16'
stop
endif
write(6,*)
write(6,*) 'record length =',nrecl,' spins =',nspin, &
'prec flag ',nprec
open(unit=10,file='WAVECAR',access='direct',recl=nrecl, &
iostat=iost,status='old')
if (iost.ne.0) write(6,*) 'open error - iostat =',iost
open(unit=11,file='GCOEFF.txt')
read(unit=10,rec=2) xnwk,xnband,ecut,(a1(j),j=1,3),(a2(j),j=1,3), &
(a3(j),j=1,3)
nwk=nint(xnwk)
if (nwk.eq.0) write(*,*) 'no kpoints in WAVECAR or reading error'
nband=nint(xnband)
allocate(occ(nband))
allocate(cener(nband))
write(6,*) 'no. k points =',nwk
write(6,*) 'no. bands =',nband
write(6,*) 'max. energy =',sngl(ecut)
write(6,*) 'real space lattice vectors:'
write(6,*) 'a1 =',(sngl(a1(j)),j=1,3)
write(6,*) 'a2 =',(sngl(a2(j)),j=1,3)
write(6,*) 'a3 =',(sngl(a3(j)),j=1,3)
write(6,*) ' '
write(11,*) nspin
write(11,*) nwk
write(11,*) nband
!!$* compute reciprocal properties
write(6,*) ' '
call vcross(vtmp,a2,a3)
Vcell=a1(1)*vtmp(1)+a1(2)*vtmp(2)+a1(3)*vtmp(3)
write(11,*) Vcell
write(6,*) 'volume unit cell =',sngl(Vcell)
call vcross(b1,a2,a3)
call vcross(b2,a3,a1)
call vcross(b3,a1,a2)
do j=1,3
b1(j)=2.*pi*b1(j)/Vcell
b2(j)=2.*pi*b2(j)/Vcell
b3(j)=2.*pi*b3(j)/Vcell
enddo
b1mag=dsqrt(b1(1)**2+b1(2)**2+b1(3)**2)
b2mag=dsqrt(b2(1)**2+b2(2)**2+b2(3)**2)
b3mag=dsqrt(b3(1)**2+b3(2)**2+b3(3)**2)
write(6,*) 'reciprocal lattice vectors:'
write(6,*) 'b1 =',(sngl(b1(j)),j=1,3)
write(6,*) 'b2 =',(sngl(b2(j)),j=1,3)
write(6,*) 'b3 =',(sngl(b3(j)),j=1,3)
write(6,*) 'reciprocal lattice vector magnitudes:'
write(6,*) sngl(b1mag),sngl(b2mag),sngl(b3mag)
write(6,*) ' '
write(11,*) (sngl(a1(j)),j=1,3)
write(11,*) (sngl(a2(j)),j=1,3)
write(11,*) (sngl(a3(j)),j=1,3)
write(11,*) (sngl(b1(j)),j=1,3)
write(11,*) (sngl(b2(j)),j=1,3)
write(11,*) (sngl(b3(j)),j=1,3)
phi12=acos((b1(1)*b2(1)+b1(2)*b2(2)+b1(3)*b2(3))/(b1mag*b2mag))
call vcross(vtmp,b1,b2)
vmag=dsqrt(vtmp(1)**2+vtmp(2)**2+vtmp(3)**2)
sinphi123=(b3(1)*vtmp(1)+b3(2)*vtmp(2)+b3(3)*vtmp(3))/(vmag*b3mag)
nb1maxA=(dsqrt(ecut*c)/(b1mag*abs(sin(phi12))))+1
nb2maxA=(dsqrt(ecut*c)/(b2mag*abs(sin(phi12))))+1
nb3maxA=(dsqrt(ecut*c)/(b3mag*abs(sinphi123)))+1
npmaxA=nint(4.*pi*nb1maxA*nb2maxA*nb3maxA/3.)
phi13=acos((b1(1)*b3(1)+b1(2)*b3(2)+b1(3)*b3(3))/(b1mag*b3mag))
call vcross(vtmp,b1,b3)
vmag=dsqrt(vtmp(1)**2+vtmp(2)**2+vtmp(3)**2)
sinphi123=(b2(1)*vtmp(1)+b2(2)*vtmp(2)+b2(3)*vtmp(3))/(vmag*b2mag)
phi123=abs(asin(sinphi123))
nb1maxB=(dsqrt(ecut*c)/(b1mag*abs(sin(phi13))))+1
nb2maxB=(dsqrt(ecut*c)/(b2mag*abs(sinphi123)))+1
nb3maxB=(dsqrt(ecut*c)/(b3mag*abs(sin(phi13))))+1
npmaxB=nint(4.*pi*nb1maxB*nb2maxB*nb3maxB/3.)
phi23=acos((b2(1)*b3(1)+b2(2)*b3(2)+b2(3)*b3(3))/(b2mag*b3mag))
call vcross(vtmp,b2,b3)
vmag=dsqrt(vtmp(1)**2+vtmp(2)**2+vtmp(3)**2)
sinphi123=(b1(1)*vtmp(1)+b1(2)*vtmp(2)+b1(3)*vtmp(3))/(vmag*b1mag)
phi123=abs(asin(sinphi123))
nb1maxC=(dsqrt(ecut*c)/(b1mag*abs(sinphi123)))+1
nb2maxC=(dsqrt(ecut*c)/(b2mag*abs(sin(phi23))))+1
nb3maxC=(dsqrt(ecut*c)/(b3mag*abs(sin(phi23))))+1
npmaxC=nint(4.*pi*nb1maxC*nb2maxC*nb3maxC/3.)
nb1max=max0(nb1maxA,nb1maxB,nb1maxC)
nb2max=max0(nb2maxA,nb2maxB,nb2maxC)
nb3max=max0(nb3maxA,nb3maxB,nb3maxC)
if ( soc.eq.'y') then
npmax=2*min0(npmaxA,npmaxB,npmaxC)
else if ( soc.eq.'n' ) then
npmax=min0(npmaxA,npmaxB,npmaxC)
endif
write(6,*) 'max. no. G values; 1,2,3 =',nb1max,nb2max,nb3max
write(6,*) ' '
allocate (igall(3,npmax))
write(6,*) 'estimated max. no. plane waves =',npmax
write(11, *) npmax
allocate (coeff(npmax,nband))
!!$* Begin loops over spin, k-points and bands
irec=2
do isp=1,nspin
write(*,*) ' '
write(*,*) '******'
write(*,*) 'reading spin ',isp
do iwk=1,nwk
irec=irec+1
read(unit=10,rec=irec) xnplane,(wk(i),i=1,3), &
(cener(iband),occ(iband),iband=1,nband)
nplane=nint(xnplane)
write(6,*) 'k point #',iwk,' input no. of plane waves =', &
nplane
write(6,*) 'k value =',(sngl(wk(j)),j=1,3)
write(11,*) (sngl(wk(j)),j=1,3)
!!$* Calculate plane waves
ncnt=0
do ig3=0,2*nb3max
ig3p=ig3
if (ig3.gt.nb3max) ig3p=ig3-2*nb3max-1
do ig2=0,2*nb2max
ig2p=ig2
if (ig2.gt.nb2max) ig2p=ig2-2*nb2max-1
do ig1=0,2*nb1max
ig1p=ig1
if (ig1.gt.nb1max) ig1p=ig1-2*nb1max-1
do j=1,3
sumkg(j)=(wk(1)+ig1p)*b1(j)+ &
(wk(2)+ig2p)*b2(j)+(wk(3)+ig3p)*b3(j)
enddo
gtot=sqrt(sumkg(1)**2+sumkg(2)**2+sumkg(3)**2)
etot=gtot**2/c
if (etot.lt.ecut) then
ncnt=ncnt+1
igall(1,ncnt)=ig1p
igall(2,ncnt)=ig2p
igall(3,ncnt)=ig3p
end if
enddo
enddo
enddo
if ( soc.eq.'y') then
if (2*ncnt.ne.nplane) then
write(6,*) 'ncnt=',ncnt, '// nplane=',nplane, 'npmax=', npmax
write(6,*) '*** error - computed no. != input no.'
stop
endif
else if ( soc.eq.'n' ) then
if (ncnt.ne.nplane) then
write(6,*) 'ncnt=',ncnt, '// nplane=',nplane, 'npmax=', npmax
write(6,*) '*** error - computed no. != input no.'
stop
endif
endif
if (ncnt.gt.npmax) then
write(6,*) '*** error - plane wave count exceeds estimate'
stop
endif
do iband=1,nband
irec=irec+1
read(unit=10,rec=irec) (coeff(iplane,iband), &
iplane=1,nplane)
enddo
!!$* output G values and coefficients
560 format('( ',g14.6,' , ',g14.6,' ) ',g14.6)
570 format(3i6,' ( ',g14.6,' , ',g14.6,' )')
if ( soc.eq.'y' ) then
do iband=1,nband
write(11,*) iband,nplane
write(11,560) cener(iband),occ(iband)
do iplane=1,nplane
write(11,570) (igall(j,mod(iplane-1, ncnt)+1),j=1,3), &
coeff(iplane,iband)
enddo
enddo
else
do iband=1,nband
write(11,*) iband,nplane
write(11,560) cener(iband),occ(iband)
do iplane=1,nplane
write(11,570) (igall(j,iplane),j=1,3), &
coeff(iplane,iband)
enddo
enddo
end if
enddo
enddo
end subroutine wavetrans
!!$*
!!$* routine for computing vector cross-product
!!$*
subroutine vcross(a,b,c)
implicit real*8(a-h,o-z)
dimension a(3),b(3),c(3)
a(1)=b(2)*c(3)-b(3)*c(2)
a(2)=b(3)*c(1)-b(1)*c(3)
a(3)=b(1)*c(2)-b(2)*c(1)
return
end subroutine vcross
| Fortran |
2D | obaica/vasp_wavecar_parity | parity.f90 | .f90 | 5,331 | 172 | subroutine parity
implicit none
complex, parameter :: zi=(0.000, 0.000)
integer :: i, j, l, n, m
real:: V
complex, allocatable :: coeff(:, :)
integer :: nspin, nkpt, nband, npmax
integer, allocatable :: Gvector(:, :, :)
real :: a1(3),a2(3),a3(3), b1(3),b2(3),b3(3)
real :: kcurrent(3)
real :: ktarget(3)
integer :: bandindex, nplane
complex :: energy
real :: occ
integer :: inot,rpt
real :: r0(3), is(3)
complex :: psi1, psi2
real :: pindex
complex, allocatable :: parityresult(:,:,:)
real :: diff
complex :: mp
character :: pos
a1=0.00;a2=0.00;a3=0.00
b1=0.00;b2=0.00;b3=0.00
rpt=5
is=[0.00, 0.00, 0.00]
open(unit=10, file='GCOEFF.txt', status='old')
write(*,*) "Specified the target kpoint (kx, ky, kz):"
read(*, *) ktarget(1), ktarget(2), ktarget(3)
write(*,*) "Specified the Inversion Centre (x, y, z):"
read(*,*) is(1), is(2), is(3)
read(10, *) nspin
read(10, *) nkpt
read(10, *) nband
read(10, *) V
read(10, *) a1(1), a1(2), a1(3)
read(10, *) a2(1), a2(2), a2(3)
read(10, *) a3(1), a3(2), a3(3)
read(10, *) b1(1), b1(2), b1(3)
read(10, *) b2(1), b2(2), b2(3)
read(10, *) b3(1), b3(2), b3(3)
read(10, *) npmax
allocate(coeff(nband, npmax))
allocate(Gvector(nband, npmax, 3))
allocate(parityresult(5,nband,2))
Gvector=0.00
coeff=0.00
pindex=0
do i=1, nkpt
inot=0 ! assume current k point not in target k list
read(10, *) kcurrent(1), kcurrent(2), kcurrent(3)
do j=1, nband
read(10, *) bandindex, nplane
read(10, *) energy, occ
do l=1, nplane
read(10, *) Gvector(bandindex,l,1),Gvector(bandindex,l,2), Gvector(bandindex, l, 3), coeff(j, l)
! write(*, *) Gvector(bandindex, l, :)
end do ! l=1, nplane
end do ! j=1, nband
!call inlist(kcurrent, ktarget, nktarget, inot)
diff = sqrt((kcurrent(1)-ktarget(1))**2+(kcurrent(2)-ktarget(2))**2&
+(kcurrent(3)-ktarget(3))**2)
if ( diff<=1d-5 ) then ! if the current kpt is target kpt
write(*, *) 'current k point:', kcurrent
write(*, *) 'target k point:', ktarget
write(*,*) "#band index, parity, wf(+r)/wf(-r)"
do l=1, nband
do m=1, rpt
call rvector(r0)
call wavefun(Gvector(l,1:nplane,:),coeff(l,1:nplane),nplane,kcurrent, r0, is, V, psi1, psi2)
parityresult(m, l, 1)= psi1
parityresult(m, l, 2)= psi2
end do
end do ! l=1, nband
do l=1, nband
mp=0.00
do m=1,rpt
!if (mod(l,2).eq.0) cycle
mp=mp+parityresult(m,l,1)/parityresult(m,l, 2)
end do
mp = mp/dble(rpt) !take 5 points to avoid accident fault
if (real(mp) < -0.99 .and. real(mp) > -1.01) then
pos="-"
else if ( real(mp)>0.99 .and. real(mp)<1.01) then
pos="+"
end if
write(*,770)l, pos, mp
770 format (I10, A4, ' (', ES15.6, ', i', ES15.6, ')')
end do
exit
end if ! if kcurrent in ktarget
end do ! i=1, npkt
close(10)
write(*,*)"### IF the parity of bands are not +/- or not showing "
write(*,*)"### or wf(+)/wf(-) are not around +/-(1., i 0.) then "
write(*,*)"### you need reconsider the INVERSION CENTRE coordinate!"
end subroutine parity
subroutine wavefun(G, C, npl, k ,r0, is, v, psi1, psi2)
! this subroutine aims at construct wavefuncion giving coefficients
implicit none
integer :: i
complex, parameter :: pzi=2.0*3.141592654*(0.00,1.0000)
complex, parameter :: zi=(0.00, 1.00)
integer, intent(in) :: npl
integer, intent(in) :: G(npl, 3)
complex, intent(in) :: C(npl)
real, intent(in) :: k(3), r0(3), v, is(3)
real :: r1(3)
complex, intent(out) :: psi1, psi2
real :: ck(3)
real :: dotpd0, dotpd1
psi1=(0.000,0.000)
psi2=(0.000,0.000)
r1=2.0*is-r0
do i=1,npl
ck = G(i, :) + k
dotpd0 = ck(1)*r0(1) + ck(2)*r0(2) + ck(3)*r0(3)
dotpd1 = ck(1)*r1(1) + ck(2)*r1(2) + ck(3)*r1(3)
psi1 = psi1 + C(i)*exp(pzi*dotpd0)/sqrt(v)
psi2 = psi2 + C(i)*exp(pzi*dotpd1)/sqrt(v)
end do
end subroutine wavefun
subroutine inlist(e, list, l, r)
!
!PURPUSE: check if element E in LIST or not
!PARAMETERS:
! e: element
! list: target list
! l: lenth of target list
! r: result, r=1 for e IN list
!
implicit none
integer, intent(in) :: l
real,intent(in):: e(3), list(l, 3)
integer, intent(inout) :: r
integer :: n
real:: tol, diff
tol=1d-6
diff=1d2
do n=1, l
diff=sqrt((e(1)-list(n,1))**2+(e(2)-list(n,2))**2+(e(3)-list(n,3))**2)
if ( diff.lt.tol ) then
r=1
exit
end if ! diff
end do ! n=1, l
end subroutine inlist
subroutine rvector(r)
implicit none
real, intent(out) :: r(3)
integer :: i
real :: x
call random_seed()
do i=1,3
call random_number(x)
r(i)=2.0*x-1.0
end do
end subroutine rvector
| Fortran |
2D | poreathon/poreathon | getdata.sh | .sh | 327 | 10 | #!/bin/bash
cd input/nanopore
wget http://pathogenomics.bham.ac.uk/filedist/nanopore/Ecoli_R7_2D.fastq
wget http://pathogenomics.bham.ac.uk/filedist/nanopore/Ecoli_R7_2D.fasta
wget http://pathogenomics.bham.ac.uk/filedist/nanopore/Ecoli_R73_2D.fasta
wget http://pathogenomics.bham.ac.uk/filedist/nanopore/Ecoli_R73_2D.fastq
| Shell |
2D | poreathon/poreathon | makemakefile.py | .py | 794 | 23 | import glob
import yaml
pipelines = yaml.load(file('pipelines.yaml'))
recipes = glob.glob('recipes/*.yaml')
recipes = dict([(r[8:-5], yaml.load(file(r))) for r in recipes])
for pipeline, inputs in pipelines.iteritems():
for input_file in inputs:
for recipe_name, recipe_info in recipes.iteritems():
if recipe_info['type'] == pipeline:
if recipe_info['input'] == 'fasta':
suffix = 'fasta'
elif recipe_info['input'] == 'fastq':
suffix = 'fastq'
else:
raise SystemError("Wrong suffix name in YAML file %s" % (recipe_name))
print "bpipe run -r -f %s_%s.html -d output/%s/%s -p ENTRYPOINT=recipes/%s.pipe @params.txt pipelines/%s.pipe input/nanopore/%s.%s" % (recipe_name, input_file, pipeline, recipe_name, recipe_name, pipeline, input_file, suffix)
| Python |
2D | poreathon/poreathon | PIPELINES.md | .md | 1,322 | 67 | # Proposed Pipelines
## Alignment
The alignment pipeline aligns FASTA or FASTQ or FAST5 files to a reference.
Input: FASTA/FASTQ/FAST5 file & reference
Output: Sorted BAM file
Tests:
- # mapped/ # unmapped
- median/mean coverage
- time to run
- histogram of alignment lengths
- coverage plots
## Alignment corrector
This pipeline takes an alignment and post-processes it, e.g. with the aim of improving SNP or indel calling sensitivity/specificity.
Input: Sorted BAM file
Output: Sorted BAM file
Tests:
- ??
## Consensus calling (normal reference)
This pipeline takes results from alignment or alignment corrector and produces a consensus output.
Input: FASTA file & reference
Output: VCF file
Tests:
- number of bases correct
- number of bases called
- number of bases incorrect (SNPs, indels)
## Consensus calling (mutated references)
The reference is mutated, e.g. 0.1%, 1%, 5% nucleotide divergence and a consensus is produced.
Tests:
- truth table
- ROC curves
## Hybrid assembly
De novo assembly using Illumina reads as guide.
Tests:
- QUAST output
## Nanopore-only assembly
Nanopore only assembly.
## Read correction by Illumina
Reads are corrected by Illumian reads.
## Read correction de novo
Reads are corrected, e.g. by a statistical model or by FAST5 squiggles.
| Markdown |
2D | poreathon/poreathon | analysis/count-errors.py | .py | 2,263 | 83 | import sys
import pysam
from collections import Counter
# http://pysam.readthedocs.org/en/latest/api.html#pysam.AlignedRead.cigar
MATCH = 0 # M
INS = 1 # I
DEL = 2 # D
SKIP = 3 # N
SOFT = 4 # S
HARD = 5 # H
PAD = 6 # P
EQUAL = 7 # =
DIFF = 9 # X
def cigar_profile(cigar_tuples):
"""
Return a dictionary that tabulates the total number
of bases associated with each CIGAR operation.
cigar_tuples is a list of (op, length) tuples.
"""
cigar_prof = Counter()
for cigar_tuple in cigar_tuples:
cigar_prof[cigar_tuple[0]] += cigar_tuple[1]
return cigar_prof
def get_total_differences(cigar_prof):
"""
return the total number of get_total_differences
in the alignment between the query and the reference.
(mismatches + insertions + deletions)
"""
return cigar_prof[DIFF] + cigar_prof[INS] + cigar_prof[DEL]
def get_total_unaligned(cigar_prof):
"""
return the total number unaligned bases (hard or softclips.)
"""
return cigar_prof[HARD] + cigar_prof[SOFT]
# Pass 1:
# iterate through each BAM alignment
# and store the best alignment for the read
# best_align:
# key is query name
# val is tuple of (alignment length, cigar_prof)
best_align = {}
bam = pysam.Samfile(sys.argv[1])
for read in bam:
cigar_prof = cigar_profile(read.cigar)
if read.qname not in best_align:
best_align[read.qname] = (read.alen, read.inferred_length, cigar_prof)
elif read.qname in best_align \
and read.alen > best_align[read.qname][0]:
best_align[read.qname] = (read.alen, read.inferred_length, cigar_prof)
# Pass 2:
# Report the alignment and error profile for each read's best alignment
print '\t'.join(['query', 'read_type', 'read_len', 'align_len', 'unalign_len', 'matches',
'mismatches', 'insertions', 'deletions', 'tot_errors'])
for query in best_align:
read_type = query.split('_')[4]
alen = best_align[query][0]
inferred_length = best_align[query][1]
cigar_prof = best_align[query][2]
total_errors = get_total_differences(cigar_prof)
unaligned_len = get_total_unaligned(cigar_prof)
print '\t'.join(str(s) for s in [query, read_type, inferred_length, alen,
unaligned_len, \
cigar_prof[EQUAL], \
cigar_prof[DIFF], \
cigar_prof[INS], \
cigar_prof[DEL], \
total_errors])
| Python |
2D | poreathon/poreathon | analysis/cov_histogram.R | .R | 287 | 7 | #!/usr/bin/Rscript
library(ggplot2)
args=commandArgs(TRUE)
cov=read.table(args[1], sep="\t", header=F)
p=ggplot(cov, aes(x=V2, y=V3)) + geom_bar(stat="identity") + scale_x_continuous("Coverage depth") + scale_y_continuous("Number of bases") + theme_bw()
ggsave(filename=args[2], plot=p)
| R |
2D | poreathon/poreathon | analysis/aln_histogram.R | .R | 342 | 9 | #!/usr/bin/Rscript
library(ggplot2)
args=commandArgs(TRUE)
cov=read.table(args[1], sep="\t", header=T, stringsAsFactors=T)
cov=subset(cov, align_len != 'None')
cov=cbind(cov,"frac" = as.numeric(cov$align_len) / as.numeric(cov$read_len))
p=ggplot(cov, aes(x=frac)) + geom_histogram() + xlim(0, 2) + theme_bw()
ggsave(filename=args[2], plot=p)
| R |
2D | poreathon/poreathon | analysis/expand-cigar.py | .py | 3,347 | 114 | import sys
import pysam
import argparse
"""Author: Aaron R. Quinlan, December 2014"""
# http://pysam.readthedocs.org/en/latest/api.html#pysam.AlignedRead.cigar
MATCH = 0 # M
INS = 1 # I
DEL = 2 # D
SKIP = 3 # N
SOFT = 4 # S
HARD = 5 # H
PAD = 6 # P
EQUAL = 7 # =
DIFF = 8 # X
def get_chrom(fasta_fh, chrom):
"""
Return the chromosome sequence
"""
return fasta_fh.fetch(chrom)
def expand_match(qry_seq, ref_seq):
"""
Return an expanded list of CIGAR ops
based upon nuceltotide matches (=, or 7)
and mismatches (X, or 8)
"""
prev_op = None
curr_op = None
length = 1
for idx, q_nucl in enumerate(qry_seq):
if q_nucl == ref_seq[idx]: curr_op = 7 # EQUAL (=)
else: curr_op = 8 # DIFF (X)
if curr_op == prev_op:
length += 1
elif prev_op is not None:
yield (prev_op, length)
length = 1
prev_op = curr_op
yield (curr_op, length)
def main(args):
bam = pysam.AlignmentFile(args.bam)
fa = pysam.FastaFile(args.fasta)
outfile = pysam.AlignmentFile("-", "wb", template=bam)
prev_chrom_id = None
curr_chrom_id = None
curr_chrom_seq = None
for read in bam:
curr_chrom_id = read.reference_id
# load the current chromosome into memory
if curr_chrom_id != prev_chrom_id:
curr_chrom_seq = get_chrom(fa, bam.getrname(curr_chrom_id))
# iterate through the existing CIGAR
# and replace M ops with expanded X and = ops.
ref_pos = read.reference_start
qry_pos = 0
new_cigar = []
for cigar_tuple in read.cigar:
op = cigar_tuple[0]
op_len = cigar_tuple[1]
if op == EQUAL or op == DIFF or op == MATCH:
if op == MATCH:
qry_seq = read.query_sequence[qry_pos:qry_pos + op_len]
ref_seq = curr_chrom_seq[ref_pos:ref_pos + op_len]
if qry_seq == ref_seq:
new_cigar.append((7, len(qry_seq))) # EQUAL (=)
else: # expand the M CIGAR op into X and = ops.
for new_cigar_tuple in expand_match(qry_seq, ref_seq):
new_cigar.append(new_cigar_tuple)
else:
new_cigar.append(cigar_tuple)
ref_pos += op_len
qry_pos += op_len
elif op == DEL or op == SKIP:
ref_pos += op_len
new_cigar.append(cigar_tuple)
elif op == INS or op == SOFT:
qry_pos += op_len
new_cigar.append(cigar_tuple)
elif op == HARD:
new_cigar.append(cigar_tuple)
# replace the old CIGAR and write updated record.
read.cigar=new_cigar
outfile.write(read)
prev_chrom_id=curr_chrom_id
outfile.close()
if __name__ == "__main__":
parser=argparse.ArgumentParser(prog='expand_cigar.py')
parser.add_argument('--bam',
dest='bam',
metavar='STRING',
help='The sorted BAM file whose CIGARs you wish expand.')
parser.add_argument('--fasta',
dest='fasta',
metavar='STRING',
help='The reference genome used to create the BAM.')
args=parser.parse_args()
main(args)
| Python |
2D | poreathon/poreathon | analysis/basic-stats.py | .py | 500 | 26 | import sys
import pysam
from collections import Counter
import numpy
def stats(fn):
unaligned = 0
best_align = {}
bam = pysam.Samfile(fn)
for read in bam:
if read.is_unmapped:
unaligned += 1
continue
if read.qname not in best_align:
best_align[read.qname] = read.alen
print """- Filename: %s
Mean_Alignment_Length: %d
Unaligned_Reads: %d
Aligned_Reads: %d""" % (fn, numpy.mean(best_align.values()), unaligned, len(best_align.values()))
for fn in sys.argv[1:]:
stats(fn)
| Python |
2D | poreathon/poreathon | analysis/collate_alignment_stats.py | .py | 1,845 | 51 | import glob
import os
import yaml
import sys
import pysam
from collections import Counter
from Bio import SeqIO
import numpy
def count_sequences(input_file, typ):
return len([s for s in SeqIO.parse(open(input_file), typ)])
def dump_pipeline(input_file, recipe_name, recipe_info):
input_lines = count_sequences("input/nanopore/%s.%s" % (input_file, recipe_info['input']), recipe_info['input'])
## this is all super hacky right now and will break eventually
filenames = glob.glob("output/alignment/%s/%s.*.bam" % (recipe_name, input_file))
unaligned = 0
best_align = {}
bam = pysam.Samfile(filenames[0])
for read in bam:
if read.is_unmapped:
unaligned += 1
continue
if read.qname not in best_align:
best_align[read.qname] = read.alen
output = recipe_info
output['Recipe'] = recipe_name
output['Input'] = input_file
output['Mean_Alignment_Length'] = int(numpy.mean(best_align.values()))
output['Aligned_Reads'] = len(best_align.values())
output['Unaligned_Reads'] = input_lines - output['Aligned_Reads']
output['Percent_Aligned'] = "%.2f" % (100.0 / input_lines * output['Aligned_Reads'])
print "- " + yaml.dump(output)
filenames = glob.glob("output/alignment/%s/%s*.draw_histo.png" % (recipe_name, input_file))
os.system("cp %s ../poreathon.github.io/output/alignment/%s_%s.histogram.png" % (filenames[0], recipe_name, input_file))
pipelines = yaml.load(file('pipelines.yaml'))
recipes = glob.glob('recipes/*.yaml')
recipes = dict([(r[8:-5], yaml.load(file(r))) for r in recipes])
for input_file in pipelines['alignment']:
for recipe_name, recipe_info in recipes.iteritems():
if recipe_info['type'] == 'alignment':
dump_pipeline(input_file, recipe_name, recipe_info)
| Python |
2D | lhalloran/ERTplot | ERTplot.py | .py | 2,432 | 66 | """
ERTplot.py
Landon Halloran 29-Nov-2016
Script to read in 2D electrical resistivity tomography (ERT) data
(i.e., inversion output from RES2DINV) and topography data and plot
it with much more user control than RES2DINV allows. Data must first be
exported to .xls/.xlsx format (see example file).
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
###### User must define these: ######
filein = "example/Resistivity_and_Topography_Data.xlsx" # where the data is located
ncolours=12 # number of colours for plots
colourscheme='viridis' # for others see https://matplotlib.org/examples/color/colormaps_reference.html
linekeys=['LINE_A','LINE_B'] # labels of tabs of ERT data
topokeys=['LINE_A_TOPO','LINE_B_TOPO'] # labels of tabs of topography data (e.g. from GNSS survey)
#####################################
nsubfigs=np.size(linekeys)
xl_file = pd.ExcelFile(filein)
ERT={}
for j in xl_file.sheet_names:
ERT[j]=xl_file.parse(j)
allrhos=[]
for i in linekeys:
rho=ERT[i]['Res'].values
allrhos.append(rho)
allrhos = np.concatenate(allrhos)
clevels = np.logspace(np.log10(np.min(allrhos)),np.log10(np.max(allrhos)),num=ncolours,base=10)
fig, axes = plt.subplots(nrows=nsubfigs, ncols=1,sharex=False) # turn on sharex to share x!
i=0
for ax in axes.flat:
keyhere=linekeys[i]
x=ERT[keyhere]['X']
z=ERT[keyhere]['Z']
rho=ERT[keyhere]['Res']
triang = mpl.tri.Triangulation(x, z)
mask = mpl.tri.TriAnalyzer(triang).get_flat_tri_mask(.1)
triang.set_mask(mask)
topokeyhere=topokeys[i]
xt=ERT[topokeyhere]['X']
zt=ERT[topokeyhere]['Z']
#plt.tricontourf(triang,rho,levels=clevels, cmap=colourscheme)
#cc=ax.tricontourf(triang,rho,levels=clevels, cmap=colourscheme)
cc=ax.tricontourf(triang,rho,levels=clevels, norm=mpl.colors.LogNorm(vmin=allrhos.min(), vmax=allrhos.max()), cmap=colourscheme)
ax.axis('equal') # make axes equal (i.e. 1m x = 1m y)
topokeyhere=topokeys[i]
ax.plot(xt,zt,'k')
i=i+1
fig.text(0.5, 0.04, 'X (m)', ha='center')
fig.text(0.04, 0.5, 'Z (m)', va='center', rotation='vertical')
fig.suptitle('Resistivity ($\Omega\cdot$m)')
clabels=[]
for c in clevels:
clabels.append('%d' % c) # label all levels with no-decimal formatting
thecbar=fig.colorbar(cc, ax=axes,ticks=clevels)
thecbar.ax.set_yticklabels(clabels) | Python |
2D | pl992/VirusPropagator | VirusPropagator.py | .py | 3,859 | 134 | import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#2D World -> People fluctuating around central points
#Person with infection leaves infected area for dt
#People on those areas get infected with probability p
#People after t1 die
dt = 3
space = 100
npeople = 1000
ninfected = 1
p_get_infected = .6
lifetime = 50
displacement = 3
"""
Function creation movie
"""
def animate(i,fig,ax):
ax.clear()
data = np.genfromtxt('worlds/world{0:04d}'.format(i))
ax.scatter(data[:,0],data[:,1],c=data[:,2])
ax.set_xlim(0,space)
ax.set_ylim(0,space)
def GenerateMovie(filename,nworlds):
fig = plt.figure()
ax = fig.add_subplot(111)
anim = animation.FuncAnimation(fig,animate,interval=40,fargs=(fig,ax),frames=nworlds)
anim.save(filename,writer='ffmpeg')
"""
End function creation movie
"""
class World:
#Infected area represented by 1, normal area represented by 0
def __init__(self,space):
self.x = np.zeros((space,space)).astype('int')
def checkAreas(self):
notzeros = np.where(self.x != 0)
self.x[notzeros] += 1
uninfected = np.where(self.x > 3)
self.x[uninfected] = 0
def writeWorld(self,filename):
output = open(filename,'w')
for i in range(len(self.x)):
for j in range(len(self.x)):
output.write('{0:d}\t{1:d}\t{2:d}\n'.format(i,j,self.x[i,j]))
output.close()
class Person:
def __init__(self,space):
self.x = np.random.randint(space)
self.y = np.random.randint(space)
self.infected = 0
self.infected_time = 0
def move(self,world):
self.motion()
#If the area is infected the person becomes infected
if world.x[self.x,self.y] != 0:
if np.random.random() < p_get_infected:
if self.infected == 0:
self.infected = 1
#If the person is infected the area becomes infected or it's counter start over
#The living time of the infected increases
if self.infected != 0:
world.x[self.x,self.y] = 1
self.infected_time += 1
def motion(self):
dx,dy = int((np.random.randint(displacement+1))-(displacement/2)),int((np.random.randint(displacement+1))-(displacement/2))
self.x += dx
self.y += dy
if self.x >= space or self.x < 0:
self.x = space - np.abs(self.x)
if self.y >= space or self.y < 0:
self.y = space - np.abs(self.y)
class People:
def __init__(self,npeople,world):
self.people = []
for i in range(npeople):
self.people.append(Person(space))
self.people[0].infected = 1
self.people[0].infected_time += 1
x,y = self.GetCoordinate(i)
world.x[x,y] = 1
def MovePeople(self,world):
for i in self.people:
i.move(world)
self.people = [i for i in self.people if i.infected_time < lifetime]
def GetInfected(self):
return len([i for i in self.people if i.infected>0])
def GetCoordinate(self,i):
return self.people[i].x, self.people[i].y
def writePeople(self,filename):
output = open(filename,'w')
for i in range(len(self.people)):
x,y = self.GetCoordinate(i)
output.write('{0:d}\t{1:d}\t{2:d}\n'.format(x,y,self.people[i].infected))
output.close()
T = 10000
world = World(space)
population = People(npeople,world)
#Create worlds directory if it doesn't exist
if not os.path.isdir('worlds'):
os.mkdir('worlds')
filename = 'worlds/world{0:04d}'
i=0
while i < T and population.GetInfected() > 0:
population.MovePeople(world)
world.checkAreas()
population.writePeople(filename.format(i))
i+=1
print (i,end='\r')
GenerateMovie('Movie.mp4',i)
| Python |
2D | NSDRLIISc/e2e | e2e.py | .py | 52,301 | 1,535 | '''#!/home/magtest/test_env/bin/python'''
from pymatgen.io.vasp.sets import MPRelaxSet, MPStaticSet, MPSOCSet
from pymatgen import Structure
from pymatgen.core.periodic_table import Element
from pymatgen.analysis.magnetism.analyzer import MagneticStructureEnumerator, CollinearMagneticStructureAnalyzer
from pymatgen.io.vasp.outputs import Vasprun, Chgcar, Oszicar, Outcar, Potcar
from pymatgen.command_line.bader_caller import bader_analysis_from_objects
import sys
import os
from shutil import copyfile
from subprocess import Popen
import datetime
from time import time, sleep
from ase.io import read, write
from ase.build import make_supercell, sort
import numpy as np
from sympy import Symbol, linsolve
from itertools import combinations
import math
from numba import jit, cuda
from pickle import load, dump
__author__ = "Arnab Kabiraj"
__copyright__ = "Copyright 2019, NSDRL, IISc Bengaluru"
__credits__ = ["Arnab Kabiraj", "Santanu Mahapatra"]
root_path = os.getcwd()
start_time_global = time()
xc = 'PBE_54'
mag_prec = 0.1
enum_prec = 0.001
max_neigh = 5
GPU_accel = False
padding = True
nsim = 4
kpar = 2
ncore = 1
symprec = 1e-8
d_thresh = 0.05
acc = 'default'
LDAUJ_povided = {}
LDAUU_povided = {}
LDAUL_povided = {}
with open('input') as f:
for line in f:
row = line.split()
if 'structure_file' in line:
struct_file = row[-1]
elif 'XC_functional' in line:
xc = row[-1]
elif 'VASP_command_std' in line:
cmd = line[len('VASP_command_std =')+1:-1]
elif 'VASP_command_ncl' in line:
cmd_ncl = line[len('VASP_command_ncl =')+1:-1]
elif 'mag_prec' in line:
mag_prec = float(row[-1])
elif 'enum_prec' in line:
enum_prec = float(row[-1])
elif 'max_neighbors' in line:
max_neigh = int(row[-1])+1
elif 'GPU_accel' in line:
GPU_accel = row[-1]=='True'
elif 'more_than_2_metal_layers' in line:
padding = row[-1]=='True'
elif 'NSIM' in line:
nsim = int(row[-1])
elif 'KPAR' in line:
kpar = int(row[-1])
elif 'NCORE' in line:
ncore = int(row[-1])
elif 'SYMPREC' in line:
symprec= float(row[-1])
elif 'LDAUJ' in line:
num_spec = len(row)-2
for i in range(2,num_spec+1,2):
LDAUJ_povided[row[i]] = float(row[i+1])
elif 'LDAUU' in line:
num_spec = len(row)-2
for i in range(2,num_spec+1,2):
LDAUU_povided[row[i]] = float(row[i+1])
elif 'LDAUL' in line:
num_spec = len(row)-2
for i in range(2,num_spec+1,2):
LDAUL_povided[row[i]] = float(row[i+1])
elif 'same_neighbor_thresh' in line:
d_thresh = float(row[-1])
elif 'accuracy' in line:
acc = row[-1]
#print(LDAUU_povided)
# all functions
def replaceText(fileName,toFind,replaceWith):
s = open(fileName).read()
s = s.replace(toFind, replaceWith)
f = open(fileName, 'w')
f.write(s)
f.close()
def writeLog(string):
string = str(string)
f = open(root_path+'/log','a+')
time = datetime.datetime.now()
f.write(str(time)+' '+string+'\n')
f.close()
def dist_neighbors(struct):
struct_l = struct.copy()
struct_l.make_supercell([20,20,1])
distances = np.unique(np.sort(np.around(struct_l.distance_matrix[1],2)))[0:15]
dr_max = 0.01
for i in range(len(distances)):
for j in range(len(distances)):
dr = np.abs(distances[i]-distances[j])
if distances[j]<distances[i] and dr<d_thresh:
distances[i]=distances[j]
if dr>dr_max:
dr_max = dr
distances = np.unique(distances)
msg = 'neighbor distances are: '+str(distances)+' ang'
print(msg)
writeLog(msg)
msg = 'treating '+str(dr_max)+' ang separated atoms as same neighbors'
print(msg)
writeLog(msg)
distances[0]=dr_max
return distances
def Nfinder(struct_mag,site,d_N,dr):
N = len(struct_mag)
coord_site = struct_mag.cart_coords[site]
Ns = struct_mag.get_neighbors_in_shell(coord_site,d_N,dr)
Ns_wrapped = Ns[:]
candidates = Ns[:]
for i in range(len(Ns)):
Ns_wrapped[i] = Ns[i][0].to_unit_cell()
for j in range(N):
if struct_mag[j].distance(Ns_wrapped[i])<0.01:
candidates[i] = j
break
return candidates
@cuda.jit
def my_kernel(all_coords,coord_N,index):
"""
Code for kernel.
"""
pos = cuda.grid(1)
if pos < all_coords.size:
if math.sqrt((all_coords[pos]-coord_N[0])**2 + (all_coords[pos+1]-coord_N[1])**2 + (all_coords[pos+2]-coord_N[2])**2) < 0.01:
index[0] = pos/3
def NfinderGPU(struc_mag,site, d_N, dr):
coord_site = struc_mag.cart_coords[site]
Ns = struc_mag.get_neighbors_in_shell(coord_site,d_N,dr)
#print(Ns)
Ns_wrapped = Ns[:]
candidates = Ns[:]
for i in range(len(Ns)):
Ns_wrapped[i] = Ns[i][0].to_unit_cell()
coord_N = np.array([Ns_wrapped[i].x,Ns_wrapped[i].y,Ns_wrapped[i].z],dtype='float32')
index = np.array([-5])
threadsperblock = 480
blockspergrid = math.ceil(all_coords.shape[0] / threadsperblock)
my_kernel[blockspergrid,threadsperblock](all_coords,coord_N,index)
candidates[i]=index[0]
return candidates
def find_max_len(lst):
maxList = max(lst, key = lambda i: len(i))
maxLength = len(maxList)
return maxLength
def make_homogenous(lst):
msg = 'finding and padding neighbors'
print(msg)
writeLog(msg)
max_len = find_max_len(lst)
for i in range(len(lst)):
if len(lst[i])<max_len:
pad = [100000]*(max_len-len(lst[i]))
lst[i] += pad
print(str(i)+'p / '+str(len(lst)-1))
@jit(nopython=True)
def tFunc(spin_abs,spin_x,spin_y,spin_z,mags,magsqs,T,J2flag,J3flag,J4flag,J5flag):
for t in range(trange):
mag = 0
for i in range(N):
site = np.random.randint(0,N)
N1s = N1list[site]
N2s = N2list[site]
N3s = N3list[site]
N4s = N4list[site]
N5s = N5list[site]
S_current = np.array([spin_x[site],spin_y[site],spin_z[site]])
u, v = np.random.random(),np.random.random()
phi = 2*np.pi*u
theta = np.arccos(2*v-1)
S_x = spin_abs[site]*np.sin(theta)*np.cos(phi)
S_y = spin_abs[site]*np.sin(theta)*np.sin(phi)
S_z = spin_abs[site]*np.cos(theta)
S_after = np.array([S_x,S_y,S_z])
E_current = 0
E_after = 0
for N1 in N1s:
if N1!=100000 or N1!=-5:
S_N1 = np.array([spin_x[N1],spin_y[N1],spin_z[N1]])
E_current += -J1*np.dot(S_current,S_N1)
E_after += -J1*np.dot(S_after,S_N1)
if J2flag:
for N2 in N2s:
if N2!=100000 or N2!=-5:
S_N2 = np.array([spin_x[N2],spin_y[N2],spin_z[N2]])
E_current += -J2*np.dot(S_current,S_N2)
E_after += -J2*np.dot(S_after,S_N2)
if J3flag:
for N3 in N3s:
if N3!= 100000 or N3!=-5:
S_N3 = np.array([spin_x[N3],spin_y[N3],spin_z[N3]])
E_current += -J3*np.dot(S_current,S_N3)
E_after += -J3*np.dot(S_after,S_N3)
if J4flag:
for N4 in N4s:
if N4!= 100000 or N4!=-5:
S_N4 = np.array([spin_x[N4],spin_y[N4],spin_z[N4]])
E_current += -J4*np.dot(S_current,S_N4)
E_after += -J4*np.dot(S_after,S_N4)
if J5flag:
for N5 in N5s:
if N5!= 100000 or N5!=-5:
S_N5 = np.array([spin_x[N5],spin_y[N5],spin_z[N5]])
E_current += -J5*np.dot(S_current,S_N5)
E_after += -J5*np.dot(S_after,S_N5)
E_current += k_x*np.square(S_current[0]) + k_y*np.square(S_current[1]) + k_z*np.square(S_current[2])
E_after += k_x*np.square(S_x) + k_y*np.square(S_y) + k_z*np.square(S_z)
del_E = E_after-E_current
if del_E < 0:
spin_x[site],spin_y[site],spin_z[site] = S_x,S_y,S_z
else:
samp = np.random.random()
if samp <= np.exp(-del_E/(kB*T)):
spin_x[site],spin_y[site],spin_z[site] = S_x,S_y,S_z
if t>=threshold:
mag_vec = 2*np.array([np.sum(spin_x),np.sum(spin_y),np.sum(spin_z)])
mag = np.linalg.norm(mag_vec)
mags[t-threshold]=np.abs(mag)
magsqs[t-threshold]=np.square(mag)
return np.mean(mags),np.mean(magsqs)
# main code
msg = '*'*150
print(msg)
writeLog(msg)
msg = '*** this code have been developed by Arnab Kabiraj at Nano-Scale Device Research Laboratory (NSDRL), IISc, Bengaluru, India ***\n'
msg += '*** for any queries please contact the authors at kabiraj@iisc.ac.in or santanu@iisc.ac.in ***'
print(msg)
writeLog(msg)
msg = '*'*150
print(msg)
writeLog(msg)
if acc == 'high':
msg = '* command for high accuracy detected, the calculations could take significantly more time than ususal\n'
msg += '* make sure the number of cores is an integer multiple of 4'
print(msg)
writeLog(msg)
cell = read(struct_file)
c = cell.get_cell_lengths_and_angles()[2]
for i in range(len(cell)):
if cell[i].z > c*0.75:
cell[i].z = cell[i].z - c
cell.center(12.75,2)
write('2D.xsf', sort(cell))
struct = Structure.from_file('2D.xsf')
mag_enum = MagneticStructureEnumerator(struct,transformation_kwargs={'symm_prec':mag_prec,'enum_precision_parameter':enum_prec})
mag_structs = []
for s_mag in mag_enum.ordered_structures:
if (s_mag.lattice.c < struct.lattice.c+3.0 and s_mag.lattice.c > struct.lattice.c-3.0):
mag_structs.append(s_mag)
num_struct = len(mag_structs)
if num_struct == 1:
msg = '*** only one config could be generated, exiting, try out a new material'
print(msg)
writeLog(msg)
sys.exit()
msg = 'total '+str(num_struct)+' configs generated'
print(msg)
writeLog(msg)
sleep_time = 45
num_atoms = []
for struct in mag_structs:
num_atoms.append(len(struct))
lcm_atoms = np.lcm.reduce(num_atoms)
num_valid_configs = 0
magnetic_list = [Element('Co'), Element('Cr'), Element('Fe'), Element('Mn'), Element('Mo'),
Element('Ni'), Element('V'), Element('W'), Element('Ce'), Element('Os'), Element('Sc'),
Element('Ti'), Element('Ag'), Element('Zr'), Element('Pd'), Element('Rh'), Element('Hf'),
Element('Nb'), Element('Y'), Element('Re'), Element('Cu'), Element('Ru'), Element('Pt'), Element('La')]
LDAUJ_dict = {'Co': 0, 'Cr': 0, 'Fe': 0, 'Mn': 0, 'Mo': 0, 'Ni': 0, 'V': 0, 'W': 0,
'Nb': 0, 'Sc': 0, 'Ru': 0, 'Rh': 0, 'Pd': 0, 'Cu': 0, 'Y': 0, 'Os': 0, 'Ti': 0, 'Zr': 0, 'Re': 0, 'Hf': 0, 'Pt':0, 'La':0}
if LDAUJ_povided:
LDAUJ_dict.update(LDAUJ_povided)
LDAUU_dict = {'Co': 3.32, 'Cr': 3.7, 'Fe': 5.3, 'Mn': 3.9, 'Mo': 4.38, 'Ni': 6.2, 'V': 3.25, 'W': 6.2,
'Nb': 1.45, 'Sc': 4.18, 'Ru': 4.29, 'Rh': 4.17, 'Pd': 2.96, 'Cu': 7.71, 'Y': 3.23, 'Os': 2.47, 'Ti': 5.89, 'Zr': 5.55,
'Re': 1.28, 'Hf': 4.77, 'Pt': 2.95, 'La':5.3}
if LDAUU_povided:
LDAUU_dict.update(LDAUU_povided)
LDAUL_dict = {'Co': 2, 'Cr': 2, 'Fe': 2, 'Mn': 2, 'Mo': 2, 'Ni': 2, 'V': 2, 'W': 2,
'Nb': 2, 'Sc': 2, 'Ru': 2, 'Rh': 2, 'Pd': 2, 'Cu': 2, 'Y': 2, 'Os': 2, 'Ti': 2, 'Zr': 2, 'Re': 2, 'Hf': 2, 'Pt':2, 'La':2}
if LDAUL_povided:
LDAUL_dict.update(LDAUL_povided)
relx_dict = {'ISMEAR': 0, 'SIGMA': 0.01, 'ISIF': 4, 'EDIFF': 1E-4, 'POTIM': 0.3,
'EDIFFG': -0.01, 'SYMPREC': 1E-8, 'KPAR': kpar, 'NCORE': ncore, 'NSIM': nsim, 'LCHARG': False, 'ICHARG': 2,
'LDAU': True, 'LDAUJ': LDAUJ_dict, 'LDAUL': LDAUL_dict, 'LDAUU': LDAUU_dict, 'LWAVE': False,
'LDAUPRINT': 1, 'LDAUTYPE': 2, 'LASPH': True, 'LMAXMIX': 4}
stat_dict = {'ISMEAR': -5, 'EDIFF': 1E-6, 'SYMPREC': 1E-8, 'KPAR': kpar, 'NCORE': ncore, 'NSIM': nsim, 'ICHARG': 2,
'LDAU': True, 'LDAUJ': LDAUJ_dict, 'LDAUL': LDAUL_dict, 'LDAUU': LDAUU_dict, 'NELM': 120, 'LVHAR': False,
'LDAUPRINT': 1, 'LDAUTYPE': 2, 'LASPH': True, 'LMAXMIX': 4, 'LCHARG': True, 'LWAVE': False, 'LVTOT': False}
mae_dict = {'ISMEAR': -5, 'EDIFF': 1E-8, 'SYMPREC': 1E-8, 'KPAR': kpar, 'NCORE': ncore, 'NSIM': nsim, 'LORBMOM': True, 'LAECHG': False,
'LDAU': True, 'LDAUJ': LDAUJ_dict, 'LDAUL': LDAUL_dict, 'LDAUU': LDAUU_dict,'NELMIN': 6, 'ICHARG': 1, 'NELM': 250, 'LVHAR': False,
'LDAUPRINT': 1, 'LDAUTYPE': 2, 'LASPH': True, 'LMAXMIX': 4, 'LCHARG': True, 'LWAVE': True, 'ISYM': -1, 'LVTOT': False}
if acc == 'high':
relx_dict['ALGO'] = 'Normal'
relx_dict['PREC'] = 'Accurate'
relx_dict['EDIFF'] = 1E-5
relx_dict['KPAR'] = 4
stat_dict['KPAR'] = 4
mae_dict['KPAR'] = 4
start_time_dft = time()
for i in range(num_struct):
struct_current = mag_structs[i].get_sorted_structure()
mag_tot = 0
for j in range(len(struct_current)):
element = struct_current[j].specie.element
if element in magnetic_list:
try:
mag_tot += struct_current[j].specie.spin
except Exception:
msg = '** the structure '+str(i)+' has uneven spins, continuing without it'
print(msg)
writeLog(msg)
mag_tot = 1000
break
if i>0 and np.abs(mag_tot) > 0.1:
msg = '** the structure '+str(i)+' seems ferrimagnetic, continuing without it'
print(msg)
writeLog(msg)
continue
submission = 0
p = 0
relx_path = root_path+'/config_'+str(i)+'/relx'
n = len(struct_current)
spins = [0]*n
for j in range(n):
try:
spins[j] = struct_current.species[j].spin
except Exception:
spins[j] = 0.0
factor = float(lcm_atoms)/n
if acc == 'high':
relx = MPRelaxSet(struct_current,user_incar_settings=relx_dict,user_kpoints_settings={'reciprocal_density':300},force_gamma=True,user_potcar_functional=xc)
else:
relx = MPRelaxSet(struct_current,user_incar_settings=relx_dict,force_gamma=True,user_potcar_functional=xc)
relx.write_input(relx_path)
num_valid_configs += 1
while 1:
if submission>2:
nsim_old = nsim
nsim = max([4,nsim-4])
replaceText(relx_path+'/INCAR','NSIM = '+str(nsim_old),'NSIM = '+str(nsim))
msg = 'current NSIM is '+str(nsim_old)+', it will be changed to '+str(nsim)+' in this run'
print(msg)
writeLog(msg)
if submission==5:
replaceText(relx_path+'/INCAR','POTIM = 0.3','POTIM = 0.1')
msg = 'reducing POTIM to 0.1'
print(msg)
writeLog(msg)
elif submission==7:
replaceText(relx_path+'/INCAR','POTIM = 0.1','POTIM = 0.05')
msg = 'reducing POTIM to 0.05'
print(msg)
writeLog(msg)
elif submission==9:
replaceText(relx_path+'/INCAR','POTIM = 0.05','POTIM = 0.01')
msg = 'reducing POTIM to 0.01'
print(msg)
writeLog(msg)
elif submission==11:
replaceText(relx_path+'/INCAR','SYMPREC = 1e-08','SYMPREC = 1e-05')
msg = 'increasing SYMPREC'
print(msg)
writeLog(msg)
elif submission==14:
f = open(relx_path+'/INCAR','a+')
f.write('\nISYM = 0')
f.close()
msg = 'lots of calculation have failed, turning off symmetry'
print(msg)
writeLog(msg)
try:
msg = 'checking vasp run status for config_'+str(i)+' relaxation'
print(msg)
writeLog(msg)
try:
temp_struct = Structure.from_file(relx_path+'/CONTCAR')
copyfile(relx_path+'/CONTCAR',relx_path+'/CONTCAR.last')
copyfile(relx_path+'/CONTCAR',relx_path+'/POSCAR')
msg = 'copied CONTCAR to POSCAR'
print(msg)
writeLog(msg)
except Exception:
msg = 'no CONTCAR so far'
print(msg)
writeLog(msg)
run = Vasprun(relx_path+'/vasprun.xml',parse_dos=False,parse_eigen=False)
if run.converged:
msg = 'relaxation finished'
print(msg)
writeLog(msg)
break
else:
msg = 'relaxation have not converged, resubmitting'
print(msg)
writeLog(msg)
raise ValueError
except Exception as e:
print(e)
writeLog(e)
os.chdir(relx_path)
p = (Popen(cmd, shell=True))
os.chdir(root_path)
submission += 1
msg = 'submitted relaxation for config_'+str(i)+''
print(msg)
writeLog(msg)
msg = 'this is submission #'+str(submission)+' for this config'
print(msg)
writeLog(msg)
while p.poll() is None:
msg = 'job running, waiting..'
print(msg)
sleep(sleep_time)
path = root_path+'/config_'+str(i)+'/stat'
stat_struct = Structure.from_file(relx_path+'/CONTCAR',sort=True)
stat_struct.add_spin_by_site(spins)
if acc == 'high':
stat = MPStaticSet(stat_struct,user_incar_settings=stat_dict,reciprocal_density=1000,force_gamma=True,user_potcar_functional=xc)
else:
stat = MPStaticSet(stat_struct,user_incar_settings=stat_dict,reciprocal_density=300,force_gamma=True,user_potcar_functional=xc)
stat.write_input(path)
p = 0
submission = 0
while 1:
if submission>2:
nsim_old = nsim
nsim = max([4,nsim-4])
replaceText(path+'/INCAR','NSIM = '+str(nsim_old),'NSIM = '+str(nsim))
msg = 'current NSIM is '+str(nsim_old)+', it will be changed to '+str(nsim)+' in this run'
print(msg)
writeLog(msg)
if submission==5:
f = open(path+'/INCAR','a+')
f.write('\nAMIX = 0.2\nBMIX = 0.0001\nAMIX_MAG = 0.8\nBMIX_MAG = 0.0001')
f.close()
msg = 'lots of calculation have failed, switching to Linear Mixing'
print(msg)
writeLog(msg)
os.remove(path+'/WAVECAR')
os.remove(path+'/CHGCAR')
elif submission==7:
replaceText(path+'/INCAR','SYMPREC = 1e-08','SYMPREC = 1e-05')
msg = 'increasing SYMPREC'
print(msg)
writeLog(msg)
elif submission==9:
f = open(path+'/INCAR','a+')
f.write('\nISYM = 0')
f.close()
msg = 'lots of calculation have failed, turning off symmetry'
print(msg)
writeLog(msg)
try:
msg = 'checking vasp run status for config_'+str(i)+' static run'
print(msg)
writeLog(msg)
run = Vasprun(path+'/vasprun.xml',parse_dos=False,parse_eigen=False)
if run.converged_electronic:
msg = 'static run finished'
print(msg)
writeLog(msg)
energy = float(run.final_energy)
energy = energy*factor
if i==0:
E_FM = energy
elif energy<E_FM:
msg = 'config_'+str(i)+' is more stable than FM'
print(msg)
writeLog(msg)
msg = '*** this material is NOT FM, exiting, try out a new material'
print(msg)
writeLog(msg)
sys.exit()
osz = Oszicar(path+'/OSZICAR')
config_mag = float(osz.ionic_steps[-1]['mag'])
if i==0 and np.abs(config_mag)<1.0:
msg = '** too low magnetization ('+str(config_mag)+') for an FM config_'+str(i)+', check OUTCAR'
print(msg)
writeLog(msg)
elif i>0 and np.abs(config_mag)>0.05:
msg = '** too large magnetization ('+str(config_mag)+') for an AFM config_'+str(i)+', check OUTCAR'
print(msg)
writeLog(msg)
try:
charge = Chgcar.from_file(path+'/CHGCAR')
except Exception:
charge = Chgcar.from_file(path+'/CHGCAR.sp')
if charge.is_spin_polarized:
try:
os.rename(path+'/CHGCAR',path+'/CHGCAR.sp')
msg = 'renamed CHGCAR to CHGCAR.sp'
print(msg)
writeLog(msg)
except Exception:
msg = 'CHGCAR.sp found'
else:
msg = '*** no spin-polarized CHGCAR found for config_'+str(i)+' static run'
print(msg)
writeLog(msg)
break
else:
msg = 'static run have not converged, resubmitting..'
print(msg)
writeLog(msg)
raise ValueError
except Exception as e:
print(e)
writeLog(e)
os.chdir(path)
p = (Popen(cmd, shell=True))
os.chdir(root_path)
submission += 1
msg = 'submitted static_run for config_'+str(i)+''
print(msg)
writeLog(msg)
msg = 'this is submission #'+str(submission)+' for this config'
print(msg)
writeLog(msg)
while p.poll() is None:
msg = 'job running, waiting..'
print(msg)
sleep(sleep_time)
end_time_dft = time()
time_dft = np.around(end_time_dft - start_time_dft, 2)
msg = 'all relaxations and static runs have finished gracefully, proceeding to MAE calculations now'
print(msg)
writeLog(msg)
msg = 'DFT energy calculations of all possible configurations took total '+str(time_dft)+' s'
print(msg)
writeLog(msg)
submission = 0
p = 0
pre_path = root_path+'/config_0/stat'
path_coll = root_path+'/MAE/coll'
if acc == 'high':
stat = MPStaticSet.from_prev_calc(pre_path,user_incar_settings=mae_dict,reciprocal_density=1000,force_gamma=True,user_potcar_functional=xc)
else:
stat = MPStaticSet.from_prev_calc(pre_path,user_incar_settings=mae_dict,reciprocal_density=300,force_gamma=True,user_potcar_functional=xc)
stat.write_input(path_coll)
if os.path.isfile(path_coll+'/WAVECAR'):
msg = 'collinear WAVECAR exists'
print(msg)
writeLog(msg)
if not os.path.isfile(path_coll+'/CHGCAR'):
try:
copyfile(pre_path+'/CHGCAR.sp',path_coll+'/CHGCAR')
except:
msg = 'no CHGCAR found in stat, continuing but it might fail'
print(msg)
writeLog(msg)
else:
msg = 'collinear CHGCAR exists'
print(msg)
writeLog(msg)
start_time_mae = time()
while 1:
if submission>2:
nsim_old = nsim
nsim = max([4,nsim-4])
replaceText(path_coll+'/INCAR','NSIM = '+str(nsim_old),'NSIM = '+str(nsim))
msg = 'current NSIM is '+str(nsim_old)+', it will be changed to '+str(nsim)+' in this run'
print(msg)
writeLog(msg)
if submission==5:
f = open(path_coll+'/INCAR','a+')
f.write('\nAMIX = 0.2\nBMIX = 0.0001\nAMIX_MAG = 0.8\nBMIX_MAG = 0.0001')
f.close()
msg = 'lots of calculation have failed, switching to Linear Mixing'
print(msg)
writeLog(msg)
os.remove(path_coll+'/WAVECAR')
os.remove(path_coll+'/CHGCAR')
try:
copyfile(pre_path+'/CHGCAR',path_coll+'/CHGCAR')
except:
msg = 'no CHGCAR found in stat, continuing but it might fail'
print(msg)
writeLog(msg)
try:
msg = 'checking vasp run status for collinear'
print(msg)
writeLog(msg)
run = Vasprun(path_coll+'/vasprun.xml',parse_dos=False,parse_eigen=False)
if run.converged_electronic:
msg = 'collinear run finished'
print(msg)
writeLog(msg)
break
else:
msg = 'collinear run have not converged, resubmitting..'
print(msg)
writeLog(msg)
raise ValueError
except:
os.chdir(path_coll)
p = (Popen(cmd, shell=True))
os.chdir(root_path)
submission += 1
msg = 'submitted collinear run'
print(msg)
writeLog(msg)
msg = 'this is submission #'+str(submission)
print(msg)
writeLog(msg)
while p.poll() is None:
msg = 'job running, waiting..'
print(msg)
sleep(sleep_time)
saxes = [(1,0,0),(0,1,0),(1,1,0),(0,0,1)]
for axis in saxes:
path = root_path+'/MAE/'+str(axis).replace(' ','')
submission = 0
p = 0
if acc == 'high':
soc = MPSOCSet.from_prev_calc(path_coll,saxis=axis,nbands_factor=2,reciprocal_density=1000,force_gamma=True,user_potcar_functional=xc)
else:
soc = MPSOCSet.from_prev_calc(path_coll,saxis=axis,nbands_factor=2,reciprocal_density=300,force_gamma=True,user_potcar_functional=xc)
soc.write_input(path)
replaceText(path+'/INCAR','LCHARG = True','LCHARG = False')
replaceText(path+'/INCAR','LWAVE = True','LWAVE = False')
if acc == 'high':
replaceText(path+'/INCAR','LVTOT = False','KPAR = 4')
else:
replaceText(path+'/INCAR','LVTOT = False','KPAR = 2')
try:
copyfile(path_coll+'/WAVECAR',path+'/WAVECAR')
except:
msg = '*** no collinear WAVECAR found, exiting'
print(msg)
writeLog(msg)
raise ValueError
while 1:
if submission>2:
nsim_old = nsim
nsim = max([4,nsim-4])
replaceText(path+'/INCAR','NSIM = '+str(nsim_old),'NSIM = '+str(nsim))
msg = 'current NSIM is '+str(nsim_old)+', it will be changed to '+str(nsim)+' in this run'
print(msg)
writeLog(msg)
if submission==7:
f = open(path+'/INCAR','a+')
f.write('\nAMIX = 0.2\nBMIX = 0.0001\nAMIX_MAG = 0.8\nBMIX_MAG = 0.0001')
f.close()
msg = 'lots of calculation have failed, applying Linear Mixing'
print(msg)
writeLog(msg)
try:
msg = 'checking vasp run status for non-collinear '+str(axis)
print(msg)
writeLog(msg)
run = Vasprun(path+'/vasprun.xml',parse_dos=False,parse_eigen=False)
if run.converged_electronic:
msg = 'non-collinear run finished for '+str(axis)
print(msg)
writeLog(msg)
try:
os.remove(path+'/CHGCAR')
msg = 'removed CHGCAR'
print(msg)
writeLog(msg)
except:
msg = 'no CHGCAR found to remove'
print(msg)
writeLog(msg)
try:
os.remove(path+'/WAVECAR')
msg = 'removed WAVECAR'
print(msg)
writeLog(msg)
except:
msg = 'no WAVERCAR found to remove'
print(msg)
writeLog(msg)
break
else:
msg = 'non-collinear run have not converged for '+str(axis)+', resubmitting..'
print(msg)
writeLog(msg)
raise ValueError
except:
os.chdir(path)
p = (Popen(cmd_ncl, shell=True))
os.chdir(root_path)
submission += 1
msg = 'submitted non-collinear run for '+str(axis)
print(msg)
writeLog(msg)
msg = 'this is submission #'+str(submission)+' for this axis'
print(msg)
writeLog(msg)
while p.poll() is None:
msg = 'job running, waiting..'
print(msg)
sleep(sleep_time)
end_time_mae = time()
time_mae = np.around(end_time_mae - start_time_mae, 2)
msg='all MAE calculations finished, attempting to fit the Hamiltonian now'
print(msg)
writeLog(msg)
msg = 'the MAE calculations took '+str(time_mae)+' s'
print(msg)
writeLog(msg)
E0 = Symbol('E0')
J1 = Symbol('J1')
J2 = Symbol('J2')
J3 = Symbol('J3')
J4 = Symbol('J4')
J5 = Symbol('J5')
kB = np.double(8.6173303e-5)
num_neigh = min([max_neigh, num_valid_configs])
msg = 'total '+str(num_valid_configs)+' valid FM/AFM configs have been detected, including '+str(num_neigh)+' nearest-neighbors in the fitting'
print(msg)
writeLog(msg)
fitted = False
semifinal_list = []
for i in range(num_struct):
path = root_path+'/config_'+str(i)+'/stat'
msg = 'checking vasp run status for config_'+str(i)+' static run'
print(msg)
writeLog(msg)
struct = mag_structs[i].get_sorted_structure()
#print(struct)
mag_tot = 0
for j in range(len(struct)):
element = struct[j].specie.element
if element in magnetic_list:
try:
mag_tot += struct[j].specie.spin
except Exception:
msg = '** the structure '+str(i)+' has uneven spins, continuing without it'
print(msg)
writeLog(msg)
mag_tot = 1000
break
if i>0 and np.abs(mag_tot) > 0.1:
msg = '** the structure '+str(i)+' seems ferrimagnetic, continuing without it'
print(msg)
writeLog(msg)
continue
run = Vasprun(path+'/vasprun.xml',parse_dos=False,parse_eigen=False)
if not run.converged_electronic:
msg = '*** static run have not converged for config_'+str(i)+', exiting'
print(msg)
writeLog(msg)
raise ValueError
else:
msg = 'found converged static run'
print(msg)
writeLog(msg)
energy = float(run.final_energy)
factor = float(lcm_atoms)/len(struct)
if factor!=int(factor):
msg = '*** factor is float, '+str(factor)+', exiting'
print(msg)
writeLog(msg)
raise ValueError
energy = energy*factor
if i==0:
E_FM = energy
elif energy<E_FM:
msg = 'config_'+str(i)+' is more stable than FM'
print(msg)
writeLog(msg)
msg = '*** this material is NOT FM'
print(msg)
writeLog(msg)
semifinal_list.append((path,energy,struct))
semifinal_list = sorted(semifinal_list, key = lambda x : x[1])
while num_neigh>=2:
if len(semifinal_list)>num_neigh:
final_list = semifinal_list[0:num_neigh]
else:
final_list = semifinal_list[:]
num_struct = len(final_list)
eqn_set = [0]*num_struct
for i in range(num_struct):
path = final_list[i][0]
energy = final_list[i][1]
struct = final_list[i][2]
factor = float(lcm_atoms)/len(struct)
config = path[-13:-5]
if '_0' in config:
if not os.path.exists(path+'/bader.dat'):
chgcar = Chgcar.from_file(path+'/CHGCAR.sp')
if not chgcar.is_spin_polarized:
msg = '** '+path+'/CHGCAR.sp is not spin-polarized, exiting'
print(msg)
writeLog(msg)
raise ValueError
potcar = Potcar.from_file(path+'/POTCAR')
aeccar0 = Chgcar.from_file(path+'/AECCAR0')
aeccar2 = Chgcar.from_file(path+'/AECCAR2')
msg = 'starting bader analysis for '+config
print(msg)
writeLog(msg)
ba = bader_analysis_from_objects(chgcar=chgcar,potcar=potcar,aeccar0=aeccar0,aeccar2=aeccar2)
msg = 'finished bader analysis successfully'
print(msg)
writeLog(msg)
f = open(path+'/bader.dat','wb')
dump(ba,f)
f.close()
magmom_FM = max(ba['magmom'])
else:
f = open(path+'/bader.dat','rb')
ba = load(f)
f.close()
magmom_FM = max(ba['magmom'])
msg = 'read magmoms from file'
print(msg)
writeLog(msg)
osz = Oszicar(path+'/OSZICAR')
out = Outcar(path+'/OUTCAR')
config_mag = float(osz.ionic_steps[-1]['mag'])
if i==0 and np.abs(config_mag)<1.0:
msg = '** too low magnetization ('+str(config_mag)+') for an FM config_'+str(i)+', check OUTCAR'
print(msg)
writeLog(msg)
elif i>0 and np.abs(config_mag)>0.05:
msg = '** too large magnetization ('+str(config_mag)+') for an AFM config_'+str(i)+', check OUTCAR'
print(msg)
writeLog(msg)
sites_mag = []
magmoms_mag = []
magmoms_out = []
for j in range(len(struct)):
element = struct[j].specie.element
if element in magnetic_list:
sign_magmom = np.sign(struct[j].specie.spin)
magmom = sign_magmom*magmom_FM
magmoms_mag.append(magmom)
sites_mag.append(struct[j])
magmoms_out.append(out.magnetization[j]['tot'])
struct_mag = Structure.from_sites(sites_mag)
struct_mag_out = Structure.from_sites(sites_mag)
struct_mag.remove_spin()
struct_mag.add_site_property('magmom',magmoms_mag)
struct_mag_out.add_site_property('magmom',magmoms_out)
N = len(struct_mag)
msg = config+' with scaling factor '+str(factor)+' = '
print(msg)
writeLog(msg)
print(struct_mag)
writeLog(struct_mag)
msg = 'same config with magmoms from OUTCAR is printed below, make sure this does not deviate too much from above'
print(msg)
writeLog(msg)
print(struct_mag_out)
writeLog(struct_mag_out)
if i==0:
S_FM = magmom_FM/2.0
N_FM = float(len(struct_mag))
ds = dist_neighbors(struct_mag)
dr = ds[0]
eqn = E0 - energy
for j in range(N):
site = j
S_site = struct_mag.site_properties['magmom'][j]/2.0
if num_struct==2:
N1s = Nfinder(struct_mag,site,ds[1],dr)
N2s = []
N3s = []
N4s = []
N5s = []
elif num_struct==3:
N1s = Nfinder(struct_mag,site,ds[1],dr)
N2s = Nfinder(struct_mag,site,ds[2],dr)
N3s = []
N4s = []
N5s = []
elif num_struct==4:
N1s = Nfinder(struct_mag,site,ds[1],dr)
N2s = Nfinder(struct_mag,site,ds[2],dr)
N3s = Nfinder(struct_mag,site,ds[3],dr)
N4s = []
N5s = []
elif num_struct==5:
N1s = Nfinder(struct_mag,site,ds[1],dr)
N2s = Nfinder(struct_mag,site,ds[2],dr)
N3s = Nfinder(struct_mag,site,ds[3],dr)
N4s = Nfinder(struct_mag,site,ds[4],dr)
N5s = []
elif num_struct==6:
N1s = Nfinder(struct_mag,site,ds[1],dr)
N2s = Nfinder(struct_mag,site,ds[2],dr)
N3s = Nfinder(struct_mag,site,ds[3],dr)
N4s = Nfinder(struct_mag,site,ds[4],dr)
N5s = Nfinder(struct_mag,site,ds[5],dr)
for N1 in N1s:
S_N1 = struct_mag.site_properties['magmom'][N1]/2.0
eqn += -0.5*J1*S_site*S_N1*factor
if N2s:
for N2 in N2s:
S_N2 = struct_mag.site_properties['magmom'][N2]/2.0
eqn += -0.5*J2*S_site*S_N2*factor
if N3s:
for N3 in N3s:
S_N3 = struct_mag.site_properties['magmom'][N3]/2.0
eqn += -0.5*J3*S_site*S_N3*factor
if N4s:
for N4 in N4s:
S_N4 = struct_mag.site_properties['magmom'][N4]/2.0
eqn += -0.5*J4*S_site*S_N4*factor
if N5s:
for N5 in N5s:
S_N5 = struct_mag.site_properties['magmom'][N5]/2.0
eqn += -0.5*J5*S_site*S_N5*factor
eqn_set[i] = eqn
msg = 'mu = '+str(magmom_FM)+' bohr magnetron/magnetic atom'
print(msg)
writeLog(msg)
msg = 'eqns are:'
print(msg)
writeLog(msg)
for eqn in eqn_set:
msg = str(eqn)+' = 0'
print(msg)
writeLog(msg)
if num_struct == 2:
soln = linsolve(eqn_set, E0, J1)
elif num_struct == 3:
soln = linsolve(eqn_set, E0, J1, J2)
elif num_struct == 4:
soln = linsolve(eqn_set, E0, J1, J2, J3)
elif num_struct == 5:
soln = linsolve(eqn_set, E0, J1, J2, J3, J4)
elif num_struct == 6:
soln = linsolve(eqn_set, E0, J1, J2, J3, J4, J5)
soln = list(soln)
msg = 'the solutions are:'
print(msg)
writeLog(msg)
print(soln)
writeLog(soln)
if soln and np.max(np.abs(soln[0]))<1e3:
fitted = True
break
else:
num_neigh -= 1
msg = 'looks like these set of equations are either not solvable or yielding unphysical values'
print(msg)
writeLog(msg)
msg = 'reducing the number of included NNs to '+str(num_neigh)
print(msg)
writeLog(msg)
if not fitted:
msg = '*** could not fit the Hamiltonian, exiting'
print(msg)
writeLog(msg)
sys.exit()
if num_struct == 2:
E0 = soln[0][0]
J1 = soln[0][1]
J2 = 0
J3 = 0
J4 = 0
J5 = 0
msg = 'the solutions are:'
print(msg)
writeLog(msg)
msg = 'E0 = '+str(E0)+' eV'
print(msg)
writeLog(msg)
msg = 'J1 = '+str(J1*1e3)+' meV/link with d1 = '+str(ds[1])+' ang and NN coordination = '+str(len(N1s))
print(msg)
writeLog(msg)
elif num_struct == 3:
E0 = soln[0][0]
J1 = soln[0][1]
J2 = soln[0][2]
J3 = 0
J4 = 0
J5 = 0
msg = 'the solutions are:'
print(msg)
writeLog(msg)
msg = 'E0 = '+str(E0)+' eV'
print(msg)
writeLog(msg)
msg = 'J1 = '+str(J1*1e3)+' meV/link with d1 = '+str(ds[1])+' ang and NN coordination = '+str(len(N1s))
print(msg)
writeLog(msg)
msg = 'J2 = '+str(J2*1e3)+' meV/link with d2 = '+str(ds[2])+' ang and NNN coordination = '+str(len(N2s))
print(msg)
writeLog(msg)
elif num_struct == 4:
E0 = soln[0][0]
J1 = soln[0][1]
J2 = soln[0][2]
J3 = soln[0][3]
J4 = 0
J5 = 0
msg = 'the solutions are:'
print(msg)
writeLog(msg)
msg = 'E0 = '+str(E0)+' eV'
print(msg)
writeLog(msg)
msg = 'J1 = '+str(J1*1e3)+' meV/link with d1 = '+str(ds[1])+' ang and NN coordination = '+str(len(N1s))
print(msg)
writeLog(msg)
msg = 'J2 = '+str(J2*1e3)+' meV/link with d2 = '+str(ds[2])+' ang and NNN coordination = '+str(len(N2s))
print(msg)
writeLog(msg)
msg = 'J3 = '+str(J3*1e3)+' meV/link with d3 = '+str(ds[3])+' ang and NNNN coordination = '+str(len(N3s))
print(msg)
writeLog(msg)
elif num_struct == 5:
E0 = soln[0][0]
J1 = soln[0][1]
J2 = soln[0][2]
J3 = soln[0][3]
J4 = soln[0][4]
J5 = 0
msg = 'the solutions are:'
print(msg)
writeLog(msg)
msg = 'E0 = '+str(E0)+' eV'
print(msg)
writeLog(msg)
msg = 'J1 = '+str(J1*1e3)+' meV/link with d1 = '+str(ds[1])+' ang and NN coordination = '+str(len(N1s))
print(msg)
writeLog(msg)
msg = 'J2 = '+str(J2*1e3)+' meV/link with d2 = '+str(ds[2])+' ang and NNN coordination = '+str(len(N2s))
print(msg)
writeLog(msg)
msg = 'J3 = '+str(J3*1e3)+' meV/link with d3 = '+str(ds[3])+' ang and NNNN coordination = '+str(len(N3s))
print(msg)
writeLog(msg)
msg = 'J4 = '+str(J4*1e3)+' meV/link with d4 = '+str(ds[4])+' ang and NNNNN coordination = '+str(len(N4s))
print(msg)
writeLog(msg)
elif num_struct == 6:
E0 = soln[0][0]
J1 = soln[0][1]
J2 = soln[0][2]
J3 = soln[0][3]
J4 = soln[0][4]
J5 = soln[0][5]
msg = 'the solutions are:'
print(msg)
writeLog(msg)
msg = 'E0 = '+str(E0)+' eV'
print(msg)
writeLog(msg)
msg = 'J1 = '+str(J1*1e3)+' meV/link with d1 = '+str(ds[1])+' ang and NN coordination = '+str(len(N1s))
print(msg)
writeLog(msg)
msg = 'J2 = '+str(J2*1e3)+' meV/link with d2 = '+str(ds[2])+' ang and NNN coordination = '+str(len(N2s))
print(msg)
writeLog(msg)
msg = 'J3 = '+str(J3*1e3)+' meV/link with d3 = '+str(ds[3])+' ang and NNNN coordination = '+str(len(N3s))
print(msg)
writeLog(msg)
msg = 'J4 = '+str(J4*1e3)+' meV/link with d4 = '+str(ds[4])+' ang and NNNNN coordination = '+str(len(N4s))
print(msg)
writeLog(msg)
msg = 'J5 = '+str(J5*1e3)+' meV/link with d5 = '+str(ds[5])+' ang and NNNNNN coordination = '+str(len(N5s))
print(msg)
writeLog(msg)
if ds[1]/ds[2] >= 0.8:
msg = '** d1/d2 is greater than 0.8, consider adding the 2nd neighbor for accurate results'
print(msg)
writeLog(msg)
elif ds[1]/ds[3] >= 0.7:
msg = '** d1/d3 is greater than 0.7, consider adding the 3rd neighbor for accurate results'
print(msg)
writeLog(msg)
saxes = [(1,0,0),(0,1,0),(1,1,0),(0,0,1)]
energies_ncl = [0]*len(saxes)
for i in range(len(saxes)):
axis = saxes[i]
path = root_path+'/MAE/'+str(axis).replace(' ','')
msg = 'checking vasp run status for non-collinear '+str(axis)
print(msg)
writeLog(msg)
run = Vasprun(path+'/vasprun.xml',parse_dos=False,parse_eigen=False)
energies_ncl[i] = float(run.final_energy)
EMA = saxes[np.argmin(energies_ncl)]
msg = 'the easy magnetization axis is '+str(EMA)
print(msg)
writeLog(msg)
E_100_001 = (energies_ncl[0] - energies_ncl[3])/N_FM
E_010_001 = (energies_ncl[1] - energies_ncl[3])/N_FM
E_110_001 = (energies_ncl[2] - energies_ncl[3])/N_FM
msg = 'magnetocrystalline anisotropic energies are:'
print(msg)
writeLog(msg)
msg = 'E[100]-E[001] = '+str(E_100_001*1e6)+' ueV/magnetic_atom'
print(msg)
writeLog(msg)
msg = 'E[010]-E[001] = '+str(E_010_001*1e6)+' ueV/magnetic_atom'
print(msg)
writeLog(msg)
msg = 'E[110]-E[001] = '+str(E_110_001*1e6)+' ueV/magnetic_atom'
print(msg)
writeLog(msg)
if np.around(E_100_001,9) == np.around(E_010_001,9) and np.around(E_100_001,9) == np.around(E_110_001,9):
TC_XY = ((final_list[1][1]-final_list[0][1])/(N*factor))*(0.89/(8*kB))
print(lcm_atoms)
msg = 'this material seems to be an XY magnet, the calculated TC is '+str(TC_XY)+' k, not performing MC'
print(msg)
writeLog(msg)
sys.exit()
if not os.path.exists(root_path+'/input_MC'):
msg = 'no input_MC file detected, writing this'
print(msg)
writeLog(msg)
energies_xyz = [energies_ncl[0], energies_ncl[1], energies_ncl[3]]
k_x = (energies_ncl[0]-np.max(energies_xyz))/(np.square(S_FM)*N_FM)
k_y = (energies_ncl[1]-np.max(energies_xyz))/(np.square(S_FM)*N_FM)
k_z = (energies_ncl[3]-np.max(energies_xyz))/(np.square(S_FM)*N_FM)
T_MF = (S_FM*(S_FM+1)/(3*kB))*(J1*len(N1s)) + (S_FM*(S_FM+1)/(3*kB))*(J2*len(N2s)) + (S_FM*(S_FM+1)/(3*kB))*(J3*len(N3s)) + (
S_FM*(S_FM+1)/(3*kB))*(J4*len(N4s)) + (S_FM*(S_FM+1)/(3*kB))*(J5*len(N5s))
f = open('input_MC','w+')
f.write('directory = MC_Heisenberg\n')
f.write('repeat = 50 50 1\n')
f.write('restart = 0\n')
f.write('J1 (eV/link) = '+str(J1)+'\n')
f.write('J2 (eV/link) = '+str(J2)+'\n')
f.write('J3 (eV/link) = '+str(J3)+'\n')
f.write('J4 (eV/link) = '+str(J4)+'\n')
f.write('J5 (eV/link) = '+str(J5)+'\n')
f.write('EMA = '+str(EMA)+'\n')
f.write('k_x (eV/atom) = '+str(k_x)+'\n')
f.write('k_y (eV/atom) = '+str(k_y)+'\n')
f.write('k_z (eV/atom) = '+str(k_z)+'\n')
f.write('T_start (K) = 1e-6\n')
f.write('T_end (K) = '+str(T_MF)+'\n')
f.write('div_T = 25\n')
f.write('mu (mu_B/atom) = '+str(S_FM*2)+'\n')
f.write('MCS = 100000\n')
f.write('thresh = 10000\n')
f.close()
msg = 'successfully written input_MC, now will try to run Monte-Carlo based on this'
print(msg)
writeLog(msg)
msg = 'if you want to run the MC with some other settings, make the neccesarry changes in input_MC and stop and re-run this script'
print(msg)
writeLog(msg)
sleep(3)
else:
msg = 'existing input_MC detected, will try to run the MC based on this'
print(msg)
writeLog(msg)
sleep(3)
with open('input_MC') as f:
for line in f:
row = line.split()
if 'directory' in line:
path = root_path+'/'+row[-1]
elif 'restart' in line:
restart = int(row[-1])
elif 'repeat' in line:
rep_z = int(row[-1])
rep_y = int(row[-2])
rep_x = int(row[-3])
elif 'J1' in line:
J1 = np.double(row[-1])
elif 'J2' in line:
J2 = np.double(row[-1])
elif 'J3' in line:
J3 = np.double(row[-1])
elif 'J4' in line:
J4 = np.double(row[-1])
elif 'J5' in line:
J5 = np.double(row[-1])
elif 'k_x' in line:
k_x = np.double(row[-1])
elif 'k_y' in line:
k_y = np.double(row[-1])
elif 'k_z' in line:
k_z = np.double(row[-1])
elif 'T_start' in line:
Tstart = float(row[-1])
elif 'T_end' in line:
Trange = float(row[-1])
elif 'div_T' in line:
div_T = int(row[-1])
elif 'mu' in line:
mu = float(row[-1])
elif 'MCS' in line:
trange = int(row[-1])
elif 'thresh' in line:
threshold = int(row[-1])
if os.path.exists(path):
new_name = path+str(time())
os.rename(path,new_name)
msg = 'found an old MC directory, renaming it to '+new_name
print(msg)
writeLog(msg)
os.makedirs(path)
repeat = [rep_x,rep_y,rep_z]
S = mu/2
struc = Structure.from_file('2D.xsf')
os.chdir(path)
if restart==0:
analyzer = CollinearMagneticStructureAnalyzer(struc,overwrite_magmom_mode='replace_all_if_undefined')
struc_mag = analyzer.get_structure_with_only_magnetic_atoms()
struc_mag.make_supercell(repeat)
N = len(struc_mag)
dr_max = ds[0]
d_N1 = ds[1]
d_N2 = ds[2]
d_N3 = ds[3]
d_N4 = ds[4]
d_N5 = ds[5]
all_coords = [0]*N
for i in range(N):
all_coords[i] = [struc_mag[i].x,struc_mag[i].y,struc_mag[i].z]
all_coords = np.array(all_coords,dtype='float32')
all_coords = all_coords.flatten()
N1list = [[1,2]]*N
N2list = [[1,2]]*N
N3list = [[1,2]]*N
N4list = [[1,2]]*N
N5list = [[1,2]]*N
if GPU_accel:
nf = NfinderGPU
msg = 'neighbor mapping will try to use GPU acceleration'
print(msg)
writeLog(msg)
else:
nf = Nfinder
msg = 'neighbor mapping will be sequentially done in CPU, can be quite slow'
print(msg)
writeLog(msg)
start_time_map = time()
for i in range(N):
N1list[i] = nf(struc_mag,i,d_N1,dr_max)
if J2!=0:
N2list[i] = nf(struc_mag,i,d_N2,dr_max)
if J3!=0:
N3list[i] = nf(struc_mag,i,d_N3,dr_max)
if J4!=0:
N4list[i] = nf(struc_mag,i,d_N4,dr_max)
if J5!=0:
N5list[i] = nf(struc_mag,i,d_N5,dr_max)
print(str(i)+' / '+str(N-1))
if padding:
msg = 'anticipating inhomogenous number of neighbors for some atoms, trying padding'
print(msg)
writeLog(msg)
make_homogenous(N1list)
make_homogenous(N2list)
make_homogenous(N3list)
make_homogenous(N4list)
make_homogenous(N5list)
end_time_map = time()
time_map = np.around(end_time_map - start_time_map, 2)
with open('N1list', 'wb') as f:
dump(N1list, f)
with open('N2list', 'wb') as f:
dump(N2list, f)
with open('N3list', 'wb') as f:
dump(N3list, f)
with open('N4list', 'wb') as f:
dump(N4list, f)
with open('N5list', 'wb') as f:
dump(N5list, f)
msg = 'neighbor mapping finished and dumped'
print(msg)
writeLog(msg)
msg = 'the neighbor mapping process for a '+str(N)+' site lattice took '+str(time_map)+' s'
print(msg)
writeLog(msg)
else:
with open('N1list', 'rb') as f:
N1list = load(f)
with open('N2list', 'rb') as f:
N2list = load(f)
with open('N3list', 'rb') as f:
N3list = load(f)
with open('N4list', 'rb') as f:
N4list = load(f)
with open('N5list', 'rb') as f:
N5list = load(f)
N = len(N1list)
print('neighbor mapping successfully read')
N1list = np.array(N1list)
N2list = np.array(N2list)
N3list = np.array(N3list)
N4list = np.array(N4list)
N5list = np.array(N5list)
temp = N1list.flatten()
corrupt = np.count_nonzero(temp == -5)
msg = 'the amount of site corruption in NNs is ' + str(corrupt) + ' / ' + str(len(temp)) + ', or ' + str(100.0*corrupt/len(temp)) + '%'
print(msg)
writeLog(msg)
if J2!=0:
temp = N2list.flatten()
corrupt = np.count_nonzero(temp == -5)
msg = 'the amount of site corruption in NNNs is ' + str(corrupt) + ' / ' + str(len(temp)) + ', or ' + str(100.0*corrupt/len(temp)) + '%'
print(msg)
writeLog(msg)
if J3!=0:
temp = N3list.flatten()
corrupt = np.count_nonzero(temp == -5)
msg = 'the amount of site corruption in NNNNs is ' + str(corrupt) + ' / ' + str(len(temp)) + ', or ' + str(100.0*corrupt/len(temp)) + '%'
print(msg)
writeLog(msg)
if J4!=0:
temp = N4list.flatten()
corrupt = np.count_nonzero(temp == -5)
msg = 'the amount of site corruption in NNNNNs is ' + str(corrupt) + ' / ' + str(len(temp)) + ', or ' + str(100.0*corrupt/len(temp)) + '%'
print(msg)
writeLog(msg)
if J5!=0:
temp = N5list.flatten()
corrupt = np.count_nonzero(temp == -5)
msg = 'the amount of site corruption in NNNNNNs is ' + str(corrupt) + ' / ' + str(len(temp)) + ', or ' + str(100.0*corrupt/len(temp)) + '%'
print(msg)
writeLog(msg)
Ts = np.linspace(Tstart,Trange,div_T)
Ms = []
Xs = []
start_time_mc = time()
for T in Ts:
spin_abs = S*np.ones(N)
spin_x = np.zeros(N)
spin_y = np.zeros(N)
spin_z = S*np.ones(N)
mags = np.zeros(trange-threshold)
magsqs = np.zeros(trange-threshold)
M,Msq=tFunc(spin_abs,spin_x,spin_y,spin_z,mags,magsqs,T,J2!=0,J3!=0,J4!=0,J5!=0)
X = (Msq-np.square(M))/T
Ms.append(M)
Xs.append(X)
print(str(T)+' '+str(M)+' '+str(X))
f = open(str(struc.formula).replace(' ','').replace('1','')+'_'+str(int(np.floor(Tstart)))+'-'+str(int(np.floor(Trange)))+'.dat','a+')
f.write(str(T)+' '+str(M)+' '+str(X)+'\n')
f.close()
end_time_mc = time()
time_mc = np.around(end_time_mc - start_time_mc, 2)
msg = 'MC simulation have finished, analyse the output to determine the Curire temp.'
print(msg)
writeLog(msg)
msg = 'the MC simulation took '+str(time_mc)+' s'
print(msg)
writeLog(msg)
end_time_global = time()
time_global = np.around(end_time_global - start_time_global, 2)
msg = 'the whole end-to-end process took '+str(time_global)+' s'
print(msg)
writeLog(msg)
| Python |
2D | rpestourie/fdfd_local_field | src/simulation_unit_cell.jl | .jl | 4,271 | 110 | # TODO: modularize code, write simulate_unit_cell independent of the geometry, all geometry related code should be in geometry_code
"""
```x, y, Ez, dpml, dsource, resolution = simulate_unit_cell(ps; refractive_indexes=zeros(3), frequency=1, interstice = 0.5, hole = 0.75, Ly = 17)```
This function simulates Helmholtz equation for a unit-cell consisting of holes in a substrate."""
function simulation_hole_layers_unit_cell(ps; refractive_indexes=zeros(3), frequency=1, interstice = 0.5, hole = 0.75, Ly = 17)
#parameters for Maxwell solver
# specific to the unit-cell
Lx = 0.95
# Ly = 17
ω = 2pi*frequency
dpml = 2
resolution = 40
dsource = 1
# specific to the unit-cell
if refractive_indexes == zeros(3)
refractive_indexes = Float64[1.0, 1.0, 1.45]
end
# ϵ_hole_layers is specific to the unit cell, all the rest is not
A, nx, ny, x, y = Maxwell_2d(Lx, Ly,
(x,y)-> ϵ_hole_layers(x, y, ps, refractive_indexes=refractive_indexes, interstice = interstice, hole = hole),
ω, dpml, resolution)
J = zeros(ComplexF64, (ny, nx))
J[end-(dpml + dsource) * resolution, :] = 1im * ω * ones(nx)*resolution
Ez = reshape(A \ J[:], (ny, nx))
return x, y, Ez, dpml, dsource, resolution
end
"""
```function simulation_pillar_unit_cell(p; kwargs=Dict())```
This function simulated Helmholtz equation for a unit-cell consisting of a pillar on top of a substrate.
@ parameters:
- p: width of the pillar in adimensional units
- kwargs: dictionary with parameters of the unit cell we would want to change
@return (everything needed to compute the local field)
- x, y: coordinates
- Ez: values of the electric field out of plane
- dpml
- dsource is the distance of the source from the pml (in adimensional unit), also use for the distance between the monitor and the pml
- resolution
"""
function simulation_pillar_unit_cell(p; kwargs=Dict())
@assert length(p) == 1
# parameter unit cell
height= get(kwargs, "height", 600/443)
#parameters for Maxwell solver
refractive_indexes= get(kwargs, "refractive_indexes", [1., 2., 1.4])
frequency= get(kwargs, "frequency", 1.)
Ly = get(kwargs, "Ly", 7)
resolution = get(kwargs, "resolution", 40)
dpml = get(kwargs, "dpml", 2)
Lx = get(kwargs, "Lx", 1)
dsource = get(kwargs, "dsource", 1)
ω = 2pi*frequency
# specific to the unit-cell
A, nx, ny, x, y = Maxwell_2d(Lx, Ly,
(x,y)-> ϵ_pillar_function(x, y, [p, height], refractive_indexes=refractive_indexes),
ω, dpml, resolution)
J = zeros(ComplexF64, (ny, nx))
J[end-(dpml + dsource) * resolution, :] = 1im * ω * ones(nx)*resolution
Ez = reshape(A \ J[:], (ny, nx))
return x, y, Ez, dpml, dsource, resolution
end
"""
```x, y, zeroth_order = get_local_field(ps; refractive_indexes=zeros(3), frequency=1, interstice = 0.5, hole = 0.75, Ly = 17)```
this function simulates the structure with holes using Maxwell's equations,
and computes the zeroth-order Fourier coefficient.
input arguments:
- ps: array with parametrization of the unit-cell corresponding the widths of holes in the substrate
- refractive_indexes: optional argument with refractive indexes of background, hole and substrate. For reference simulation: set refractive indexes to ones(3)*eps_substrate
- frequency (optional): frequency of simulation
- interstice (optional): number of wavelength between holes
- hole (optional): number of wavelength inside holes
- Ly (optional): length of the computational domain
returns:
- return the complex zeroth order Fourier coefficient of the transmitted field
"""
function get_local_field(ps; simulate_unit_cell=simulation_hole_layers_unit_cell, refractive_indexes=zeros(3), frequency=1, interstice = 0.5, hole = 0.75, Ly = 17)
x, y, Ez, dpml, dsource, resolution = simulate_unit_cell(ps,
refractive_indexes=refractive_indexes, frequency=frequency,
interstice = interstice, hole = hole, Ly = Ly)
return x, y, mean(Ez[(dpml + dsource) * resolution, :])
end
function get_local_field(ps, simulate_unit_cell; kwargs=Dict())
x, y, Ez, dpml, dsource, resolution = simulate_unit_cell(ps, kwargs=kwargs)
return x, y, mean(Ez[(dpml + dsource) * resolution, :])
end
| Julia |
2D | rpestourie/fdfd_local_field | src/misc.jl | .jl | 1,929 | 50 | function rescaling(x, lb, ub)
@assert all([x <= 1, x >= 0])
lb + x * (ub-lb)
end
function create_parameters(number_holes, number_training_data, δ, lb, ub)
ps_vec = zeros(number_holes)
for it_training = 1:number_training_data
cur_ps = rescaling.(rand(number_holes), lb, ub)
ps_vec = vcat(ps_vec, cur_ps)
for it_hole = 1:number_holes
perturb = zeros(number_holes)
perturb[it_hole]+= δ
ps_vec = vcat(ps_vec, cur_ps .+ perturb)
end
end
return transpose(reshape(ps_vec[number_holes+1:end], (number_holes, number_training_data*6)))
end
function finite_difference_deriv(curv, vperturb, δ)
return (vperturb-curv)/δ
end
function get_val_gradient_from_data(data_array; δ=1e-2)
n_variable = size(data_array)[2]-2
n_data_val_gradient = size(data_array)[1]÷(1+n_variable)
real_val_gradient = zeros(Float64, (n_data_val_gradient, 2*n_variable+1))
imag_val_gradient = zeros(Float64, (n_data_val_gradient, 2*n_variable+1))
for i=1:n_data_val_gradient
real_vector_data = data_array[(i-1)*(1+n_variable)+1, 1:n_variable] #push the data input
real_curval = data_array[(i-1)*(1+n_variable)+1, n_variable+1]
push!(real_vector_data, real_curval)
imag_vector_data = data_array[(i-1)*(1+n_variable)+1, 1:n_variable]
imag_curval = data_array[(i-1)*(1+n_variable)+1, n_variable+2]
push!(imag_vector_data, imag_curval)
for j=1:n_variable
push!(real_vector_data, finite_difference_deriv(real_curval, data_array[(i-1)*(1+n_variable)+1+j, n_variable+1], δ))
push!(imag_vector_data, finite_difference_deriv(imag_curval, data_array[(i-1)*(1+n_variable)+1+j, n_variable+2], δ))
end
real_val_gradient[i,:] = real_vector_data
imag_val_gradient[i,:] = imag_vector_data
end
return real_val_gradient, imag_val_gradient
end
| Julia |
2D | rpestourie/fdfd_local_field | src/fdfd_maxwell_solver.jl | .jl | 2,488 | 81 | """
```Maxwell_2d(Lx, Ly, ϵ, ω, dpml, resolution; Rpml=1e-20, show_geometry=false)```
This function compute the finite difference operator for a Maxwell Finite Difference Frequency Domain solver.
The solver is in 2D and handles the out-of-plane polarization.
Boundary conditions:
- periodic in x
- pml at y = Ly and y = 0
Argument:
- Lx : length in x direction
- Ly : length in y direction
- ϵ : function that gives the permittivity in function of a spatial point
- ω : frequency
- dpml : width of the pml
- resolution : number of points per unit
- Rpml : pml extinction parameter
- show_geometry : flag to plot the geometry
Returns:
- the operator matrix
- the number of points in x direction
- the number of points in y direction
- x grid points
- y grid points
"""
function Maxwell_2d(Lx, Ly, ϵ, ω, dpml, resolution;
Rpml=1e-20)
nx = round(Int, Lx * resolution) #nb point in x
ny = round(Int, (Ly + 2*dpml) * resolution) #nb points in y
npml = round(Int, dpml*resolution)
δ = 1/resolution
# coordinates centered in (0,0)
x = (1:nx) * δ
y = (1-npml:ny-npml) * δ
#define the laplacian operator in x direction
o = ones(nx)/δ
# D = spdiagm((-o,o), (-1,0), nx+1, nx) # v0.6
Imat, J, V = SparseArrays.spdiagm_internal(-1 => -o, 0 => o);
D = sparse(Imat, J, V, nx+1, nx)
∇2x = transpose(D) * D
#periodic boundary condition in x direction
∇2x[end,1]-=1/δ^2
∇2x[1,end]-=1/δ^2
#define the laplacian operator in y direction
o = ones(ny) / δ
σ0 = -log(Rpml) / (4dpml^3/3)
y′=((-npml:ny-npml) .+ 0.5) * δ
σ = Float64[ξ>Ly ? σ0 * (ξ-Ly)^2 : ξ<0 ? σ0 * ξ^2 : 0.0 for ξ in y]
Σ = spdiagm(0 => 1.0 ./(1 .+ (im/ω)*σ))
σ′ = Float64[ξ>Ly ? σ0 * (ξ-Ly)^2 : ξ<0 ? σ0 * ξ^2 : 0.0 for ξ in y′]
Σ′ = spdiagm(0 => 1.0 ./(1 .+ (im/ω)*σ′))
# D = spdiagm((-o, o), (-1, 0), ny+1, ny) # v0.6
Imat, J, V = SparseArrays.spdiagm_internal(-1 => -o, 0 => o);
D = sparse(Imat, J, V, ny+1, ny)
∇2y = Σ * transpose(D) * Σ′ * D
#get 2d laplacian using kronecker product
Ix = sparse(1.0I, nx, nx)
# Ix = speye(nx) # v0.6
Iy = sparse(1.0I, ny, ny)
# Iy = speye(ny) # v0.6
∇2d = (kron(Ix, ∇2y) + kron(∇2x, Iy))
# geometry = ComplexF64[ϵ(ξ, ζ) for ζ in y, ξ in x]
geometry = ϵ(x, y)
return (∇2d - spdiagm(0 => reshape(ω^2 * geometry, length(x)*length(y))),
nx, ny, x, y)
end
| Julia |
2D | rpestourie/fdfd_local_field | src/fdfd_local_field.jl | .jl | 201 | 9 | using Statistics
using LinearAlgebra
using SparseArrays
include("../src/fdfd_maxwell_solver.jl")
include("../src/geometry_code.jl")
include("../src/simulation_unit_cell.jl")
include("../src/misc.jl")
| Julia |
2D | rpestourie/fdfd_local_field | src/geometry_code.jl | .jl | 6,132 | 174 | """
```ϵ_hole_layers(x, y, ps, interstice = 0.5, hole = 0.75)```
return the permittivity of a unit-cell which consists of air holes in silica
Arguments:
- ps : widths of the air holes (need to be unit-less)
- refractive_indexes : optional argument with refractive indexes of background, hole and substrate. For reference simulation: set refractive indexes to ones(3)*eps_substrate
- interstice (optional): number of length_scale in between holes acounting for the permittivity of the substrate
- hole (optional): number of length_scale in the holes
Returns:
- geometry : a complex array with the epsilon data of the unit-cell
"""
function ϵ_hole_layers(x, y, ps; refractive_indexes=zeros(3), interstice = 0.5, hole = 0.75)
@assert length(x)> 2 # makes sure δ is defined
nx, ny = length(x), length(y)
δ = x[2] - x[1]
Ly_pml = y[end] - y[1] + δ
Lx = x[end] - x[1] + δ
@assert all(ps .> δ) # makes sure pixel-averaging handles all cases
@assert all(ps .<= Lx) # makes sure that the holes are not bigger than the period
# material properties of the unit-cell
if refractive_indexes == zeros(3)
refractive_index_background = 1.0
refractive_index_hole = 1.0
refractive_index_substrate = 1.45
else
refractive_index_background, refractive_index_hole,
refractive_index_substrate = refractive_indexes
end
eps_background, eps_hole, eps_substrate =
refractive_index_background^2, refractive_index_hole^2,
refractive_index_substrate^2
geometry = ones(ComplexF64, ny, nx) * eps_background
index_top_substrate = floor(Int64, Ly_pml * 0.35/ δ) # 80% of the domain is substrate
# substrate
geometry[index_top_substrate:end, :] .= eps_substrate
# handles case for sub-pixel averaging
if x[nx÷2] == 0
w_offset=1/2
else
w_offset=0
end
# holes
number_holes = length(ps)
n_inter_hole = floor(Int64, interstice / refractive_index_substrate / δ)
n_hole_height = floor(Int64, hole / δ)
@assert index_top_substrate + number_holes * (n_inter_hole + n_hole_height) < ny
# makes sure that Ly is big enough for the holes (possibly in PML)
for it_holes = 1:number_holes
half_width = ps[it_holes]/2δ - w_offset
n_half_width = floor(Int64, half_width)
weight_eps_hole = half_width - n_half_width
# inside holes
n_start = floor(Int64, (nx - 2*n_half_width)/2 - w_offset)
geometry[index_top_substrate + it_holes * n_inter_hole + (it_holes-1) *
n_hole_height + 1:index_top_substrate + it_holes *
(n_inter_hole + n_hole_height),
n_start + 1: n_start + floor(Int64, 2*(n_half_width + w_offset)) + 1] .=
eps_hole
# pixel averaging
# left
geometry[index_top_substrate + it_holes * n_inter_hole + (it_holes-1) *
n_hole_height + 1:index_top_substrate + it_holes *
(n_inter_hole + n_hole_height), n_start] .=
weight_eps_hole * eps_hole + (1 - weight_eps_hole) * eps_substrate
# right
geometry[index_top_substrate + it_holes * n_inter_hole + (it_holes-1) *
n_hole_height + 1:index_top_substrate + it_holes *
(n_inter_hole + n_hole_height), end-n_start+1] .=
weight_eps_hole * eps_hole + (1 - weight_eps_hole) * eps_substrate
end
return geometry
end
"""
```function ϵ_pillar_function(x, y, ps; refractive_indexes=zeros(3))```
return the permittivity of a unit-cell which consists of a pillar on top of a substrate
Arguments:
- ps : width and height of the pillar (adimensional)
- refractive_indexes : optional argument with refractive indexes of background, hole and substrate. For reference simulation: set refractive indexes to ones(3)*eps_substrate
Returns:
- geometry : a complex array with the epsilon data of the unit-cell
"""
function ϵ_pillar_function(x, y, ps; refractive_indexes=zeros(3))
@assert length(x)> 2 # makes sure δ is defined
@assert length(ps) == 2
width = ps[1]
height = ps[2]
nx, ny = length(x), length(y)
δ = x[2] - x[1]
Ly_pml = y[end] - y[1] + δ
Lx = x[end] - x[1] + δ
p = width/Lx
@assert all(ps .> δ) # makes sure pixel-averaging handles all cases
@assert (width <= Lx) # makes sure that the pillar width are not bigger than the period
@assert (height <= Ly_pml) # makes sure that height fits in domain (TODO: need to be careful of PML)
# material properties of the unit-cell
if refractive_indexes == zeros(3)
refractive_index_background = 1.0
refractive_index_pillar = 2.0
refractive_index_substrate = 1.4
else
refractive_index_background, refractive_index_pillar,
refractive_index_substrate = refractive_indexes
end
eps_background, eps_pillar, eps_substrate =
refractive_index_background^2, refractive_index_pillar^2,
refractive_index_substrate^2
geometry = ones(ComplexF64, ny, nx) * eps_background
index_top_substrate = floor(Int64, Ly_pml * 0.5/ δ) # 80% of the domain is substrate
# substrate
geometry[index_top_substrate:end, :] .= eps_substrate
# handles case for sub-pixel averaging
if x[nx÷2] == 0
w_offset=1/2
else
w_offset=0
end
# pillar
n_pillar_height = floor(Int64, height / δ)
half_width = p/2δ - w_offset
n_half_width = floor(Int64, half_width)
weight_eps_hole = half_width - n_half_width
# inside pillar
n_start = floor(Int64, (nx - 2*n_half_width)/2 - w_offset)
geometry[index_top_substrate-n_pillar_height:index_top_substrate-1,
n_start + 1: n_start + floor(Int64, 2*(n_half_width + w_offset)) + 1] .=
eps_pillar
# pixel averaging
# left
geometry[index_top_substrate-n_pillar_height:index_top_substrate-1, n_start] .=
weight_eps_hole * eps_pillar + (1 - weight_eps_hole) * eps_background
# right
geometry[index_top_substrate-n_pillar_height:index_top_substrate-1, end-n_start+1] .=
weight_eps_hole * eps_pillar + (1 - weight_eps_hole) * eps_background
return geometry
end | Julia |
2D | rpestourie/fdfd_local_field | test/test_get_gradient.jl | .jl | 1,023 | 20 | data_array = [0.405503 0.707334 0.211959 0.2539 0.479168 0.161135 -0.0888367
0.415503 0.707334 0.211959 0.2539 0.479168 0.153381 -0.102154
0.405503 0.717334 0.211959 0.2539 0.479168 0.14144 -0.106894
0.405503 0.707334 0.221959 0.2539 0.479168 0.150405 -0.0882103
0.405503 0.707334 0.211959 0.2639 0.479168 0.135277 -0.108619
0.405503 0.707334 0.211959 0.2539 0.489168 0.162739 -0.0966177]
real_gd, imag_gd = get_val_gradient_from_data(data_array, δ=1e-2)
@test imag_gd[1, end-4] == (data_array[2, end] - data_array[1, end])*1e2
@test imag_gd[1, end-2] == (data_array[4, end] - data_array[1, end])*1e2
@test imag_gd[1, end] == (data_array[6, end] - data_array[1, end])*1e2
@test real_gd[1, end-4] == (data_array[2, end-1] - data_array[1, end-1])*1e2
# note that this value is wrong because the data was simulated with a δ=1e-2 pertubation
real_gd, imag_gd = get_val_gradient_from_data(data_array, δ=1e-4)
@test imag_gd[1, end-4] ≈ (data_array[2, end] - data_array[1, end])*1e4
| Julia |
2D | rpestourie/fdfd_local_field | test/test_fdfd_maxwell_solver.jl | .jl | 577 | 11 | # checks Fresnel's transmission coefficient numerically
n_incident = 1.
n_transmit = 1.45
ref_local_field = get_local_field(Float64[0.5], refractive_indexes=ones(3) * n_incident)[3]
interface_localfield = get_local_field(Float64[0.5], refractive_indexes=Float64[n_transmit, n_incident, n_incident])[3]
transmission_numerical = abs2(interface_localfield)/abs2(ref_local_field)/n_incident*n_transmit
transmission_fresnel = ((2n_incident)/(n_incident+n_transmit))^2/n_incident*n_transmit
@test abs(transmission_fresnel - transmission_numerical)/abs(transmission_fresnel)< 1e-2
| Julia |
2D | rpestourie/fdfd_local_field | test/runtests.jl | .jl | 409 | 10 | using Test
include("../src/fdfd_local_field.jl")
@testset "fdfd_local_field" begin
@testset "maxwell_fdfd_solver" begin include("test_fdfd_maxwell_solver.jl") end
@testset "pixel averaging" begin include("test_geometry_code.jl") end
@testset "finite difference gradient" begin include("test_get_gradient.jl") end
@testset "parallelization" begin include("test_parallel_vs_serial.jl") end
end
| Julia |
2D | rpestourie/fdfd_local_field | test/test_parallel_vs_serial.jl | .jl | 970 | 27 | number_training_data = 6
r = rand()
δ = 1e-2
number_holes = 5
lb = 0.1 # for a blue wavelength this corresponds to a minimum feature of ≈40 nm
ub = 0.95 - lb # this assumes a period of 0.95 λ
# create parameters
ps_array = create_parameters(number_holes, number_training_data, δ, lb, ub)
# reference simulation
refractive_indexes_ref = ones(3) * 1.45
ref_local_field = get_local_field(Float64[0.5], refractive_indexes=refractive_indexes_ref)[3]
# simulations
refractive_indexes_sim = Float64[1.0, 1.0, 1.45]
sim_local_fields = ComplexF32[get_local_field(ps_array[it_ps, :], refractive_indexes=refractive_indexes_sim)[3] for it_ps=1:size(ps_array)[1]]
sim_local_fields2 = zeros(ComplexF64, (number_holes+1)*number_training_data)
@inbounds Base.Threads.@threads for it_ps=1:size(ps_array)[1]
sim_local_fields2[it_ps] = get_local_field(ps_array[it_ps, :], refractive_indexes=refractive_indexes_sim)[3]
end
@test all(sim_local_fields .≈ sim_local_fields2)
| Julia |
2D | rpestourie/fdfd_local_field | test/test_geometry_code.jl | .jl | 490 | 15 |
ps = [37/40]
refractive_indexes = Float64[1., 1., sqrt(3)]
x, y, Ez, dpml, dsource, resolution = simulation_hole_layers_unit_cell(ps, refractive_indexes=refractive_indexes)
δ = x[2] - x[1]
Ly_pml = y[end] - y[1] + δ
# test that the unit-cell is correct
@test resolution == 40
@test Ly_pml == 16
# test that some permittivity are 2 which is the desired pixel-averaging
geometry = real.(ϵ_hole_layers(x, y, ps, refractive_indexes=refractive_indexes))
@test any(isapprox.(geometry, 2.))
| Julia |
2D | rpestourie/fdfd_local_field | examples/example_Ez_geometry_plots.jl | .jl | 805 | 25 | include("../src/fdfd_local_field.jl")
using Plots
pyplot()
### reference simulation
refractive_indexes = ones(3) * 1.45
ps = [0.75, 0.5, 0.66, 0.33, 0.66, 0.5, 0.75, 0.5, 0.66, 0.33]
x, y, Ez, dpml, dsource, resolution = simulation_hole_layers_unit_cell(ps, refractive_indexes=refractive_indexes, frequency=0.25)
heatmap(real.(ϵ_hole_layers(x, y, ps, refractive_indexes=refractive_indexes)))
gui()
heatmap(real.(Ez), c=ColorGradient([:red, :white, :blue]))
gui()
### structure simulation
refractive_indexes = Float64[1.0, 1.0, 1.45]
x, y, Ez, dpml, dsource, resolution = simulation_hole_layers_unit_cell(ps, refractive_indexes=refractive_indexes)
heatmap(real.(ϵ_hole_layers(x, y, ps, refractive_indexes=refractive_indexes)))
gui()
heatmap(real.(Ez), c=ColorGradient([:red, :white, :blue]))
gui()
| Julia |
2D | rpestourie/fdfd_local_field | examples/serial_simulations.jl | .jl | 1,219 | 35 | include("../src/fdfd_local_field.jl")
cd("examples/")
using BenchmarkTools
using DelimitedFiles
println("$(Threads.nthreads()) threads!")
number_training_data = 150000 # ideally 1e5 here
r = rand()
δ = 1e-2
fname = "test_data_$(round(Int, r*1e5))_$δ.csv"
number_holes = 10
lb = 0.1 # for a blue wavelength this corresponds to a minimum feature of ≈40 nm
ub = 0.95 - lb # this assumes a period of 0.95 λ
# create parameters
ps_array = create_parameters(number_holes, number_training_data, δ, lb, ub)
# reference simulation
refractive_indexes_ref = ones(3) * 1.45
ref_local_field = get_local_field(Float64[0.5], refractive_indexes=refractive_indexes_ref)[3]
# simulations
refractive_indexes_sim = Float64[1.0, 1.0, 1.45]
# embarassingly parallel loop (used to be serial hence the name of the file)
sim_local_fields = zeros(ComplexF64, (number_holes+1)*number_training_data)
@time @inbounds Base.Threads.@threads for it_ps=1:size(ps_array)[1]
sim_local_fields[it_ps] = get_local_field(ps_array[it_ps, :], refractive_indexes=refractive_indexes_sim)[3]
end
local_field_data = sim_local_fields./ref_local_field
writedlm("./data/"*fname,hcat(ps_array, real.(local_field_data), imag.(local_field_data)), ',')
| Julia |
2D | rpestourie/fdfd_local_field | examples/Simulate_RGB_data.ipynb | .ipynb | 63,282 | 113 | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"┌ Warning: PyPlot is using tkagg backend, which is known to cause crashes on MacOS (#410); use the MPLBACKEND environment variable to request a different backend.\n",
"└ @ PyPlot /Users/raphaelpestourie/.julia/packages/PyPlot/XHEG0/src/init.jl:192\n"
]
},
{
"data": {
"text/plain": [
"get_val_gradient_from_data (generic function with 1 method)"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"using PyPlot\n",
"include(\"../src/fdfd_local_field.jl\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"wavelengths = Float64[488, 532, 658]\n",
"lb = .15\n",
"ub = .85\n",
"\n",
"### simulations\n",
"# reference simulation\n",
"refractive_indexes_ref = ones(3) * 1.45\n",
"ref_local_field = Dict()\n",
"for j in eachindex(wavelengths)\n",
" ref_local_field[wavelengths[j]] = get_local_field(Float64[0.5], refractive_indexes=refractive_indexes_ref, frequency=wavelengths[j]/wavelengths[1])[3]\n",
"end\n",
"\n",
"# simulations\n",
"refractive_indexes_sim = Float64[1.0, 1.0, 1.45]\n",
"ps = .15:0.01:0.85\n",
"local_field_data = zeros(ComplexF64, (length(ps), length(wavelengths)))\n",
"\n",
"for (j, lambda) in enumerate(wavelengths)\n",
" for (i, p) in enumerate(ps)\n",
" freq = wavelengths[1]/wavelengths[j]\n",
" local_field_data[i,j] = get_local_field([p], refractive_indexes=refractive_indexes_sim, frequency=freq)[3]/ref_local_field[wavelengths[j]]\n",
" end\n",
"end"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAnYAAAHWCAYAAAD6oMSKAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAPYQAAD2EBqD+naQAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjMsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+AADFEAAAgAElEQVR4nOzdd1zV9f7A8dc57C2gyBScoIiKe++dJpppjrQ0zVtZZt7Kurdxvb/stodpablnau5SyQQN98CJKAqoDBVUkCHrnN8fX8FIWcrhy4H38/E4j3PgfL7w5qvfL28+4/3R6PV6PUIIIYQQwuhp1Q5ACCGEEEKUD0nshBBCCCGqCEnshBBCCCGqCEnshBBCCCGqCEnshBBCCCGqCEnshBBCCCGqCEnshBBCCCGqCEnshBBCCCG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A7NKl544QVRp9OJe/bsEXNycixXSUmJpc17770n6nQ6cePGjWJqaqo4ZsyYZr/t+25+v0tMFJXRB0lJSaJGoxHnzp0rnj17Vly9erXo5OQkrlq1ytJGCf2gJBzvON6JovLGO6WOdYpN7ERRFD/55BMxKChItLe3F3v06GHZCi9HAG55LVu2zNKmqqpKfOutt0QfHx9Rq9WKjzzyiJiamipd0E3gjwOdUvrg22+/FcPCwkStViuGhISIixcvrvV9pfSDknC843inxPFOiWOdIIqiKM1cIRERERE1JkWusSMiIiKSIyZ2RERERDLBxI6IiIhIJpjYEREREckEEzsiIiIimWBiR0RERCQTTOyIiIiIZIKJHREREZFMMLEjIiIikgkmdkREREQywcSOiIiISCaY2BERERHJxP8D3CwgsGefXwcAAAAASUVORK5CYII=",
"text/plain": [
"Figure(PyObject <Figure size 640x480 with 2 Axes>)"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"subplot(121)\n",
"plot(angle.(local_field_data))\n",
"subplot(122)\n",
"plot(abs.(local_field_data));\n",
"tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"# writedlm(\"RGB_uc_data.csv\", hcat(ps, real.(local_field_data), imag.(local_field_data)), ',')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.4.2",
"language": "julia",
"name": "julia-1.4"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.4.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
| Unknown |
2D | rpestourie/fdfd_local_field | examples/example_parameter_sweep_single_hole.jl | .jl | 271 | 16 | include("../src/fdfd_local_field.jl")
using Plots
pyplot()
ps = transpose(0.1:0.01:0.9)
E_local_field = [get_local_field(ps[:,i])[3] for i=1:length(ps)]
Plots.plot(real.(E_local_field))
Plots.plot!(imag.(E_local_field))
gui()
Plots.plot(angle.(E_local_field))
gui()
| Julia |
2D | rpestourie/fdfd_local_field | examples/get_val_gradients.jl | .jl | 454 | 14 | include("../src/fdfd_local_field.jl")
using DelimitedFiles
fname="examples/data/test_data__0.01.csv"
data_array = readdlm(fname, ',')
start_index = findnext('.', fname, 1) - 1
end_index = findnext('.', fname, start_index+2) - 1
δ = parse(Float64, fname[start_index:end_index])
real_gd, imag_gd = get_val_gradient_from_data(data_array, δ=δ)
writedlm(fname[1:end-4]*"_real_gd.csv", real_gd, ',')
writedlm(fname[1:end-4]*"_imag_gd.csv", imag_gd, ',')
| Julia |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.