plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
sanghosuh/lens_nmf-matlab-master
compute_total_doc_cvrg.m
.m
lens_nmf-matlab-master/evaluation/total_document_coverage/compute_total_doc_cvrg.m
3,754
utf_8
04b200587eeed0ab2478d94ed634045a
% Total Document Coverage % % Written by Sangho Suh ([email protected]) % Dept. of Computer Science and Engineering, % Korea University % % Reference: % % [1] Sangho Suh, Jaegul Choo, Joonseok Lee and Chandan K. Reddy. % L-EnsNMF: Boosted Local Topic Discovery via Ensemble of Nonnegative Matrix Factorization. % % Please send bug reports, comments, or questions to Sangho Suh. % This comes with no guarantee or warranty of any kind. % % Last modified 11/04/2016 % % this function returns a single value % i.e. an average value from a number of pmi values % % <Inputs> % % A : [matrix] Input matrix (m x n) % term_idx : [matrix] Wtopk matrix with corresponding indices % min_nterm : [scalar] min number of keywords % % <Output> % % qualtopic : [vector] number of documents covered by each topic % tot_covrg : [scalar] total number of documents covered by k topics % function [qualtopic,tot_covrg] = compute_total_doc_cvrg(A, term_idx, min_nterm) % create 1 x k vector, where k is number of topics qualtopic = zeros(1,size(term_idx,2)); % create k x n matrix, where n is number of documents qualtopic_mat = zeros(size(term_idx,2), size(A,2)); % repeat k number of times (where k is number of topics) for i=1:size(term_idx,2) % get a scalar value that tells how many doc contain min_nterm(c2) number of keywords in a given single topic qualtopic(i) = sum( sum( A(term_idx(:,i),:)~=0 )>=min_nterm ); % ... cf.[1] % get a list of 0's and 1's where 1 indicates that corresponding column has number of keywords more than min_nterm qualtopic_mat(i,:) = sum( A(term_idx(:,i),:)~=0 ) >=min_nterm; % ... cf.[2] end % calculate how many documents are covered by all topics tot_covrg = sum( sum(qualtopic_mat) ~=0 ) / size(A,2); % ... cf.[3] end % Breakdown of [1] % (1) term_idx(:,i) is e.g., 3, 32, 47, ... ,132 (where each number refers to index) % (2) A(term_idx(:,i),:) is then e.g., A(3,:), A(32,:), A(47,:), ... , (132,:) % (3) A(term_idx(:,i),:)~=0 is then e.g., % [1 0 1 1 0 1 0 0 0 ... ] % [0 1 0 0 1 1 0 0 1 ... ] % ... % where 1 means it appears at least once in given doc % % (4) sum(A(term_idx(:,i),:)~=0) is a summation of the above stacked list to give single vector % e.g., [4 2 10 3 0 0 2 ...] where each number % % represents the number of keywords each doc contains. So, above % case means doc1 has 4 keywords of given topic, doc2 has 2 keywords of given topic, and so on. % % (5) sum(sum(A(term_idx(:,i),:)~=0)>=min_nterm) is a summation of the above single vector to give a scalar value, % e.g. 350 where the number represents the total number of % documents that has the same or more number of keywords than min_nterm % thus, qualtopic(1) has the total number of documents covered by Topic 1 % So, it is a measure of how good each topic is. % e.g. qualtopic(1) = 24, means, Topic 1's keywords appear in 24 documents in total. % Breakdown of [2] % qualtopic_mat is a matrix where each row represents documents per topic % e.g. qualtopic_mat(1,:) is a 1 x n vector % (containing 1's and 0's where 1 indicates that corresponding doc(column) has at least min_nterm keywords)
github
sanghosuh/lens_nmf-matlab-master
weakorthonmf.m
.m
lens_nmf-matlab-master/library/ramkis/weakorthonmf.m
33,961
utf_8
35a6c05d74c3570a95b513b216f63769
% Weakly Orthogonal Nonnegative Matrix Factorization % % Written by Jaegul Choo ([email protected]) % Dept. of Computer Science and Engineering, % Korea University % % Please send bug reports, comments, or questions to Jingu Kim. % This code comes with no guarantee or warranty of any kind. % % Reference: % Jingu Kim and Haesun Park, % Fast Nonnegative Matrix Factorization: An Active-set-like Method And Comparisons, % SIAM Journal on Scientific Computing (SISC), 33(6), pp. 3261-3281, 2012 % % Last modified on 08/24/2015 % % <Inputs> % A : Input data matrix (m x n) % k : Target low-rank % % (Below are optional arguments: can be set by providing name-value pairs) % % METHOD : Algorithm for solving NMF. One of the following values: % 'anls_bpp' 'hals' 'anls_asgroup' 'anls_asgivens' 'anls_pgrad' 'anls_pqn' 'als' 'mu' % See above paper (and references therein) for the details of these algorithms. % Default is 'anls_bpp'. % TOL : Stopping tolerance. Default is 1e-3. % If you want to obtain a more accurate solution, decrease TOL and increase MAX_ITER at the same time. % MAX_ITER : Maximum number of iterations. Default is 500. % MIN_ITER : Minimum number of iterations. Default is 20. % MAX_TIME : Maximum amount of time in seconds. Default is 1,000,000. % INIT : A struct containing initial values. INIT.W and INIT.H should contain initial values of % W and H of size (m x k) and (k x n), respectively. % VERBOSE : 0 (default) - No debugging information is collected. % 1 (debugging/experimental purpose) - History of computation is returned. See 'REC' variable. % 2 (debugging/experimental purpose) - History of computation is additionally printed on screen. % REG_W, REG_H : Regularization parameters for W and H. % Both REG_W and REG_H should be vector of two nonnegative numbers. % The first component is a parameter with Frobenius norm regularization, and % the second component is a parameter with L1-norm regularization. % For example, to promote sparsity in H, one might set REG_W = [alpha 0] and REG_H = [0 beta] % where alpha and beta are positive numbers. See above paper for more details. % Defaut is [0 0] for both REG_W and REG_H, which means no regularization. % <Outputs> % W : Obtained basis matrix (m x k) % H : Obtained coefficient matrix (k x n) % iter : Number of iterations % HIS : (debugging/experimental purpose) Auxiliary information about the execution % <Usage Examples> % nmf(A,10) % nmf(A,20,'verbose',2) % nmf(A,20,'verbose',1,'method','anls_bpp') % nmf(A,20,'verbose',1,'method','hals') % nmf(A,20,'verbose',1,'method','comp','n1',,'n2',,'k1',,'k2',,'ks',,'kd1',,'kd2',,'alpha',,'beta',) % nmf(A,20,'verbose',1,'reg_w',[0.1 0],'reg_h',[0 0.5]) function [W,H,res,iter,REC]=weakorthonmf(A,Winit,Hinit,k,beta,varargin) % parse parameters params = inputParser; params.addParamValue('method' ,'comp',@(x) ischar(x) ); % params.addParamValue('method' ,'anls_bpp',@(x) ischar(x) ); % params.addParamValue('method' ,'hals',@(x) ischar(x) ); % params.addParamValue('tol' ,1e-2 ,@(x) isscalar(x) & x > 0); % params.addParamValue('min_iter' ,20 ,@(x) isscalar(x) & x > 0); % params.addParamValue('max_iter' ,100 ,@(x) isscalar(x) & x > 0); % params.addParamValue('max_time' ,1e6 ,@(x) isscalar(x) & x > 0); % params.addParamValue('init' ,struct([]),@(x) isstruct(x)); % params.addParamValue('verbose' ,1 ,@(x) isscalar(x) & x >= 0); % params.addParamValue('reg_w' ,[0 0] ,@(x) isvector(x) & length(x) == 2); % params.addParamValue('reg_h' ,[0 0] ,@(x) isvector(x) & length(x) == 2); % % The following options are reserved for debugging/experimental purposes. % % Make sure to understand them before making changes % params.addParamValue('subparams' ,struct([]),@(x) isstruct(x) ); % params.addParamValue('track_grad' ,1 ,@(x) isscalar(x) & x >= 0); % params.addParamValue('track_prev' ,1 ,@(x) isscalar(x) & x >= 0); % params.addParamValue('stop_criterion',0 ,@(x) isscalar(x) & x >= 0); % params.parse(varargin{:}); params.addParamValue('tol' ,1e-18 ,@(x) isscalar(x) & x > 0); params.addParamValue('min_iter' ,20 ,@(x) isscalar(x) & x > 0); % params.addParamValue('max_iter' ,500 ,@(x) isscalar(x) & x > 0); params.addParamValue('max_iter' ,2000 ,@(x) isscalar(x) & x > 0); % by sangho params.addParamValue('max_time' ,1e6 ,@(x) isscalar(x) & x > 0); params.addParamValue('init' ,struct([]),@(x) isstruct(x)); params.addParamValue('verbose' ,0 ,@(x) isscalar(x) & x >= 0); params.addParamValue('reg_w' ,[0 0] ,@(x) isvector(x) & length(x) == 2); params.addParamValue('reg_h' ,[0 0] ,@(x) isvector(x) & length(x) == 2); % The following options are reserved for debugging/experimental purposes. % Make sure to understand them before making changes params.addParamValue('subparams' ,struct([]),@(x) isstruct(x) ); % params.addParamValue('track_grad' ,0 ,@(x) isscalar(x) & x >= 0); % by sangho params.addParamValue('track_grad' ,1 ,@(x) isscalar(x) & x >= 0); params.addParamValue('track_prev' ,1 ,@(x) isscalar(x) & x >= 0); % params.addParamValue('stop_criterion',0 ,@(x) isscalar(x) & x >= 0); % by sangho params.addParamValue('stop_criterion',3 ,@(x) isscalar(x) & x >= 0); params.parse(varargin{:}); % % joyfull % save tmp_data; REC=0; % if size(A,2)==3 % A=full(sparse(A(:,1),A(:,2),A(:,3))); % size(A) % % X=X(:,data_ind); % % X=X((sum(abs(X),2)~=0)',:); % % size(X) % end % X=X-repmat(mean(X,2),1,size(X,2)); % params % copy from params object [m,n] = size(A); par = params.Results; par.m = m; par.n = n; par.k = k; par.beta = beta*n; % Stopping criteria are based on the gradient information. % Hence, 'track_grad' option needs to be turned on to use a criterion. if par.stop_criterion > 0 par.track_grad = 1; end initializer= str2func([par.method,'_initializer']); iterSolver = str2func([par.method,'_iterSolver']); iterLogger = str2func([par.method,'_iterLogger']); % initialize W = rand(m,par.k); H = rand(par.k,n); [W,H,par,val,ver] = feval(initializer,A,W,H,par); if ~isempty(Winit) W = Winit; end if ~isempty(Hinit) H = Hinit; end init_time = tic; res = struct; res.obj = zeros(par.max_iter,1); res.time = zeros(par.max_iter,1); res.grad = zeros(par.max_iter,1); residual_iter = zeros(par.max_iter,1); tStart = cputime;, tTotal = 0; for iter=1:par.max_iter % iter W_old = W; % Actual work of this iteration is executed here. convd = -1; while (convd == -1) [W_tmp,H_tmp,gradW,gradH,val,convd] = feval(iterSolver,A,W,H,iter,par,val); par.beta = par.beta/2; break; end W = W_tmp; H = H_tmp; if (iter > par.min_iter) if mean(abs(W(:) - W_old(:)))<par.tol break; end % if (par.verbose && (tTotal > par.max_time)) || (~par.verbose && ((cputime-tStart)>par.max_time)) % break; % elseif par.track_grad % SC = getStopCriterion(par.stop_criterion,A,W,H,par,gradW,gradH); % if (SC/initSC <= par.tol) % SCconv = SCconv + 1; % if (SCconv >= SC_COUNT), break;, end % else % SCconv = 0; % end % end end end % plot(residual_iter); error = norm(A-W*H,'fro')/par.n; res.iter = iter; [m,n]=size(A); [W,H]=normalize_by_W(W,H); end %---------------------------------------------------------------------------- % Implementation of methods %---------------------------------------------------------------------------- % % %----------------- ANLS with Block Principal Pivoting Method -------------------------- % % function [W,H,par,val,ver] = anls_bpp_initializer(A,W,H,par) % H = zeros(size(H)); % % ver.turnZr_W = 0; % ver.turnZr_H = 0; % ver.turnNz_W = 0; % ver.turnNz_H = 0; % ver.numChol_W = 0; % ver.numChol_H = 0; % ver.numEq_W = 0; % ver.numEq_H = 0; % ver.suc_W = 0; % ver.suc_H = 0; % % val(1).WtA = W'*A; % val.WtW = W'*W; % end % % function [W,H,gradW,gradH,val] = anls_bpp_iterSolver(A,W,H,iter,par,val) % % WtW_reg = applyReg(val.WtW,par,par.reg_h); % [H,temp,suc_H,numChol_H,numEq_H] = nnlsm_blockpivot(WtW_reg,val.WtA,1,H); % % HHt_reg = applyReg(H*H',par,par.reg_w); % [W,gradW,suc_W,numChol_W,numEq_W] = nnlsm_blockpivot(HHt_reg,H*A',1,W'); % W = W'; % % val.WtA = W'*A; % val.WtW = W'*W; % % if par.track_grad % gradW = gradW'; % gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); % else % gradW = 0;gradH =0; % end % % val(1).numChol_W = numChol_W; % val.numChol_H = numChol_H; % val.numEq_W = numEq_W; % val.numEq_H = numEq_H; % val.suc_W = suc_W; % val.suc_H = suc_H; % end % % function [ver] = anls_bpp_iterLogger(ver,par,val,W,H,prev_W,prev_H) % if par.track_prev % ver.turnZr_W = length(find( (prev_W>0) & (W==0) ))/(par.m*par.k); % ver.turnZr_H = length(find( (prev_H>0) & (H==0) ))/(par.n*par.k); % ver.turnNz_W = length(find( (prev_W==0) & (W>0) ))/(par.m*par.k); % ver.turnNz_H = length(find( (prev_H==0) & (H>0) ))/(par.n*par.k); % end % ver.numChol_W = val.numChol_W; % ver.numChol_H = val.numChol_H; % ver.numEq_W = val.numEq_W; % ver.numEq_H = val.numEq_H; % ver.suc_W = val.suc_W; % ver.suc_H = val.suc_H; % end % % %----------------- ANLS with Active Set Method / Givens Updating -------------------------- % % function [W,H,par,val,ver] = anls_asgivens_initializer(A,W,H,par) % H = zeros(size(H)); % % ver.turnZr_W = 0; % ver.turnZr_H = 0; % ver.turnNz_W = 0; % ver.turnNz_H = 0; % ver.numChol_W = 0; % ver.numChol_H = 0; % ver.suc_W = 0; % ver.suc_H = 0; % % val(1).WtA = W'*A; % val.WtW = W'*W; % end % % function [W,H,gradW,gradH,val] = anls_asgivens_iterSolver(A,W,H,iter,par,val) % WtW_reg = applyReg(val.WtW,par,par.reg_h); % ow = 0; % suc_H = zeros(1,size(H,2)); % numChol_H = zeros(1,size(H,2)); % for i=1:size(H,2) % [H(:,i),temp,suc_H(i),numChol_H(i)] = nnls1_asgivens(WtW_reg,val.WtA(:,i),ow,1,H(:,i)); % end % % suc_W = zeros(1,size(W,1)); % numChol_W = zeros(1,size(W,1)); % % HHt_reg = applyReg(H*H',par,par.reg_w); % HAt = H*A'; % Wt = W'; % gradWt = zeros(size(Wt)); % for i=1:size(W,1) % [Wt(:,i),gradWt(:,i),suc_W(i),numChol_W(i)] = nnls1_asgivens(HHt_reg,HAt(:,i),ow,1,Wt(:,i)); % end % W = Wt'; % % val.WtA = W'*A; % val.WtW = W'*W; % % if par.track_grad % gradW = gradWt'; % gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); % else % gradW = 0; gradH =0; % end % % val(1).numChol_W = sum(numChol_W); % val.numChol_H = sum(numChol_H); % val.suc_W = any(suc_W); % val.suc_H = any(suc_H); % end % % function [ver] = anls_asgivens_iterLogger(ver,par,val,W,H,prev_W,prev_H) % if par.track_prev % ver.turnZr_W = length(find( (prev_W>0) & (W==0) ))/(par.m*par.k); % ver.turnZr_H = length(find( (prev_H>0) & (H==0) ))/(par.n*par.k); % ver.turnNz_W = length(find( (prev_W==0) & (W>0) ))/(par.m*par.k); % ver.turnNz_H = length(find( (prev_H==0) & (H>0) ))/(par.n*par.k); % end % ver.numChol_W = val.numChol_W; % ver.numChol_H = val.numChol_H; % ver.suc_W = val.suc_W; % ver.suc_H = val.suc_H; % end % % %----------- ANLS with Active Set Method / Column Grouping / No Overwrite ----------------- % % function [W,H,par,val,ver] = anls_asgroup_initializer(A,W,H,par) % [W,H,par,val,ver] = anls_bpp_initializer(A,W,H,par); % end % % function [W,H,gradW,gradH,val] = anls_asgroup_iterSolver(A,W,H,iter,par,val) % WtW_reg = applyReg(val.WtW,par,par.reg_h); % ow = 0; % [H,temp,suc_H,numChol_H,numEq_H] = nnlsm_activeset(WtW_reg,val.WtA,ow,1,H); % % HHt_reg = applyReg(H*H',par,par.reg_w); % [W,gradW,suc_W,numChol_W,numEq_W] = nnlsm_activeset(HHt_reg,H*A',ow,1,W'); % W = W'; % % val.WtA = W'*A; % val.WtW = W'*W; % % if par.track_grad % gradW = gradW'; % gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); % else % gradW = 0; gradH =0; % end % % val(1).numChol_W = numChol_W; % val.numChol_H = numChol_H; % val.numEq_W = numEq_W; % val.numEq_H = numEq_H; % val.suc_W = suc_W; % val.suc_H = suc_H; % end % % function [ver] = anls_asgroup_iterLogger(ver,par,val,W,H,prev_W,prev_H) % ver = anls_bpp_iterLogger(ver,par,val,W,H,prev_W,prev_H); % end % % %----------------- ANLS with Projected Gradient Method -------------------------- % % function [W,H,par,val,ver] = anls_pgrad_initializer(A,W,H,par) % if isempty(par.subparams) % par.subparams(1).subtol_init = 0.1; % par.subparams.reduce_factor = 0.1; % par.subparams.num_warmup_iter = 5; % par.subparams.min_subiter = 1; % par.subparams.max_subiter = 100; % par.subparams.min_tol = 1e-10; % end % % [gradW,gradH] = getGradient(A,W,H,par); % val(1).tol_W = par.subparams.subtol_init*norm(gradW,'fro'); % val.tol_H = par.subparams.subtol_init*norm(gradH,'fro'); % % ver.subIter_W = 0; % ver.subIter_H = 0; % ver.numLineSearch_W = 0; % ver.numLineSearch_H = 0; % end % % function [W,H,gradW,gradH,val] = anls_pgrad_iterSolver(A,W,H,iter,par,val) % % if (iter>1 && iter<=par.subparams.num_warmup_iter) % val.tol_W = val.tol_W * par.subparams.reduce_factor; % val.tol_H = val.tol_H * par.subparams.reduce_factor; % end % % WtW_reg = applyReg(W'*W,par,par.reg_h); % WtA = W'*A; % [H,gradHX,subIter_H,numLineSearch_H] = nnlssub_projgrad(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); % if (iter > par.subparams.num_warmup_iter) && (subIter_H < par.subparams.min_subiter) && (val.tol_H >= par.subparams.min_tol) % val.tol_H = par.subparams.reduce_factor * val.tol_H; % [H,gradHX,subAddH,lsAddH] = nnlssub_projgrad(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); % subIter_H = subIter_H + subAddH; % numLineSearch_H = numLineSearch_H + lsAddH; % end % % HHt_reg = applyReg(H*H',par,par.reg_w); % HAt = H*A'; % [W,gradW,subIter_W,numLineSearch_W] = nnlssub_projgrad(HHt_reg,HAt,val.tol_W,W',par.subparams.max_subiter,1); % if (iter > par.subparams.num_warmup_iter) && (subIter_W < par.subparams.min_subiter) && (val.tol_W >= par.subparams.min_tol) % val.tol_W = par.subparams.reduce_factor * val.tol_W; % [W,gradW,subAddW,lsAddW] = nnlssub_projgrad(HHt_reg,HAt,val.tol_W,W,par.subparams.max_subiter,1); % subIter_W = subIter_W + subAddW; % numLineSearch_W = numLineSearch_W + lsAddW; % end % W = W'; % if par.track_grad % gradW = gradW'; % gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par); % else % gradH = 0; gradW = 0; % end % % val(1).subIter_W = subIter_W; % val.subIter_H = subIter_H; % val.numLineSearch_W = numLineSearch_W; % val.numLineSearch_H = numLineSearch_H; % end % % function [ver] = anls_pgrad_iterLogger(ver,par,val,W,H,prev_W,prev_H) % ver.tol_W = val.tol_W; % ver.tol_H = val.tol_H; % ver.subIter_W = val.subIter_W; % ver.subIter_H = val.subIter_H; % ver.numLineSearch_W = val.numLineSearch_W; % ver.numLineSearch_H = val.numLineSearch_H; % end % % %----------------- ANLS with Projected Quasi Newton Method -------------------------- % % function [W,H,par,val,ver] = anls_pqn_initializer(A,W,H,par) % [W,H,par,val,ver] = anls_pgrad_initializer(A,W,H,par); % end % % function [W,H,gradW,gradH,val] = anls_pqn_iterSolver(A,W,H,iter,par,val) % % if (iter>1 && iter<=par.subparams.num_warmup_iter) % val.tol_W = val.tol_W * par.subparams.reduce_factor; % val.tol_H = val.tol_H * par.subparams.reduce_factor; % end % % WtW_reg = applyReg(W'*W,par,par.reg_h); % WtA = W'*A; % [H,gradHX,subIter_H] = nnlssub_projnewton_mod(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); % if (iter > par.subparams.num_warmup_iter) && (subIter_H/par.n < par.subparams.min_subiter) && (val.tol_H >= par.subparams.min_tol) % val.tol_H = par.subparams.reduce_factor * val.tol_H; % [H,gradHX,subAddH] = nnlssub_projnewton_mod(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); % subIter_H = subIter_H + subAddH; % end % % HHt_reg = applyReg(H*H',par,par.reg_w); % HAt = H*A'; % [W,gradW,subIter_W] = nnlssub_projnewton_mod(HHt_reg,HAt,val.tol_W,W',par.subparams.max_subiter,1); % if (iter > par.subparams.num_warmup_iter) && (subIter_W/par.m < par.subparams.min_subiter) && (val.tol_W >= par.subparams.min_tol) % val.tol_W = par.subparams.reduce_factor * val.tol_W; % [W,gradW,subAddW] = nnlssub_projnewton_mod(HHt_reg,HAt,val.tol_W,W,par.subparams.max_subiter,1); % subIter_W = subIter_W + subAddW; % end % W = W'; % % if par.track_grad % gradW = gradW'; % gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par); % else % gradH = 0; gradW = 0; % end % % val(1).subIter_W = subIter_W; % val.subIter_H = subIter_H; % end % % function [ver] = anls_pqn_iterLogger(ver,par,val,W,H,prev_W,prev_H) % ver.tol_W = val.tol_W; % ver.tol_H = val.tol_H; % ver.subIter_W = val.subIter_W; % ver.subIter_H = val.subIter_H; % end % % %----------------- Alternating Least Squares Method -------------------------- % % function [W,H,par,val,ver] = als_initializer(A,W,H,par) % ver = struct([]); % % val.WtA = W'*A; % val.WtW = W'*W; % end % % function [W,H,gradW,gradH,val] = als_iterSolver(A,W,H,iter,par,val) % WtW_reg = applyReg(val.WtW,par,par.reg_h); % H = WtW_reg\val.WtA; % H(H<0)=0; % % AHt = A*H'; % HHt_reg = applyReg(H*H',par,par.reg_w); % Wt = HHt_reg\AHt'; W=Wt'; % W(W<0)=0; % % % normalize : necessary for ALS % [W,H,weights] = normalize_by_W(W,H); % D = diag(weights); % % val.WtA = W'*A; % val.WtW = W'*W; % AHt = AHt*D; % HHt_reg = D*HHt_reg*D; % % if par.track_grad % gradW = W*HHt_reg - AHt; % gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); % else % gradH = 0; gradW = 0; % end % end % % function [ver] = als_iterLogger(ver,par,val,W,H,prev_W,prev_H) % end % % %----------------- Multiplicatve Updating Method -------------------------- % % function [W,H,par,val,ver] = mu_initializer(A,W,H,par) % ver = struct([]); % % val.WtA = W'*A; % val.WtW = W'*W; % end % % function [W,H,gradW,gradH,val] = mu_iterSolver(A,W,H,iter,par,val) % epsilon = 1e-16; % % WtW_reg = applyReg(val.WtW,par,par.reg_h); % H = H.*val.WtA./(WtW_reg*H + epsilon); % % WtW_reg = W'*W; % % H = H.*(W'*A)./(WtW_reg*H + epsilon); % % HHt_reg = applyReg(H*H',par,par.reg_w); % AHt = A*H'; % W = W.*AHt./(W*HHt_reg + epsilon); % % HHt_reg = H*H'; % % AHt = A*H'; % % W = W.*AHt./(W*HHt_reg+epsilon); % % val.WtA = W'*A; % val.WtW = W'*W; % % if par.track_grad % gradW = W*HHt_reg - AHt; % gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); % else % gradH = 0; gradW = 0; % end % % norm(A-W*H,'fro') % end % % function [ver] = mu_iterLogger(ver,par,val,W,H,prev_W,prev_H) % end % % %----------------- HALS Method : Algorith 2 of Cichocki and Phan ----------------------- % % function [W,H,par,val,ver] = hals_initializer(A,W,H,par) % [W,H]=normalize_by_W(W,H); % % val = struct([]); % ver = struct([]); % end % % function [W,H,gradW,gradH,val] = hals_iterSolver(A,W,H,iter,par,val) % epsilon = 1e-16; % % WtA = W'*A; % WtW = W'*W; % WtW_reg = applyReg(WtW,par,par.reg_h); % for i = 1:par.k % H(i,:) = max(H(i,:) + WtA(i,:) - WtW_reg(i,:) * H,epsilon); % end % % AHt = A*H'; % HHt_reg = applyReg(H*H',par,par.reg_w); % for i = 1:par.k % W(:,i) = max(W(:,i) * HHt_reg(i,i) + AHt(:,i) - W * HHt_reg(:,i),epsilon); % if sum(W(:,i))>0 % W(:,i) = W(:,i)/norm(W(:,i)); % end % end % % if par.track_grad % gradW = W*HHt_reg - AHt; % gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par); % else % gradH = 0; gradW = 0; % end % end % % function [ver] = hals_iterLogger(ver,par,val,W,H,prev_W,prev_H) % end % % %----------------- new ----------------------- % % function [W,H,U,V,par,val,ver] = fix_initializer(A,B,W,H,U,V,par) % [W,H]=normalize_by_W(W,H); % [U,V]=normalize_by_W(U,V); % % par.max_iter = % % val = struct([]); % ver = struct([]); % end % % function [W,H,U,V,gradW,gradH,val] = fix_iterSolver(A,B,W,H,U,V,iter,par,val) % epsilon = 1e-16; % % % for i = 1:par.ks % % WtU = (W(:,i:par.k1))'*U(:,i:par.k2); % % [C,I]=max(WtU); [C2,I2]=max(C); I1=I(I2); % % W(:,[i I1+i-1]) = W(:,[I1+i-1 i]); % % U(:,[i I2+i-1]) = U(:,[I2+i-1 i]); % % end % % if iter == 10 % for i = 1:par.ks % WtU = (W(:,i:par.k1))'*U(:,i:par.k2); % [C,I]=max(WtU); [C2,I2]=max(C); I1=I(I2); % W(:,[i I1+i-1]) = W(:,[I1+i-1 i]); % U(:,[i I2+i-1]) = U(:,[I2+i-1 i]); % end % for i = 1:par.kd1 % WtU = (W(:,par.ks+i:par.k1))'*U(:,par.ks+1:par.k2); % [C,I]=min(sum(WtU,2)); % W(:,[par.ks+i par.ks+i-1+I]) = W(:,[par.ks+i-1+I par.ks+i]); % end % for i = 1:par.kd2 % WtU = (W(:,par.ks+1:par.k1))'*U(:,par.ks+i:par.k2); % [C,I]=min(sum(WtU)); % U(:,[par.ks+i par.ks+i-1+I]) = U(:,[par.ks+i-1+I par.ks+i]); % end % end % % error = norm(A-W*H,'fro') + norm(B-U*V,'fro') ; % error1 = norm(W(:,1:par.ks)-U(:,1:par.ks),'fro');% * par.alpha; % error2 = ones(1,par.kd1)*(W(:,par.ks+1:par.ks+par.kd1))'*U(:,par.ks+1:par.ks+par.kd2)*ones(par.kd2,1);% * par.beta; % fprintf('%i error: %d,, %d,, %d,, total: %d %s \n', iter, error, error1, error2, error+error1+error2, 'before'); % % WtA = W'*A; % WtW = W'*W; % WtW_reg = applyReg(WtW,par,par.reg_h); % for i = 1:par.k1 % H(i,:) = max(H(i,:) + WtA(i,:) - WtW_reg(i,:) * H,epsilon); % end % % error = norm(A-W*H,'fro') + norm(B-U*V,'fro') ; % error1 = norm(W(:,1:par.ks)-U(:,1:par.ks),'fro');% * par.alpha; % error2 = ones(1,par.kd1)*(W(:,par.ks+1:par.ks+par.kd1))'*U(:,par.ks+1:par.ks+par.kd2)*ones(par.kd2,1);% * par.beta; % %fprintf('%s error: %d,, %d,, %d,, total: %d\n', 'H', error, error1, error2, error+error1+error2); % % AHt = A*H'; % HHt_reg = applyReg(H*H',par,par.reg_w); % for i = 1:par.ks % W(:,i) = max(W(:,i) * HHt_reg(i,i)/(HHt_reg(i,i)+par.alpha) + (AHt(:,i)+par.alpha*U(:,i)-W*HHt_reg(:,i)) / (HHt_reg(i,i)+par.alpha),epsilon); % if sum(W(:,i))>0 % W(:,i) = W(:,i)/norm(W(:,i)); % end % end % for i = par.ks+1:par.ks+par.kd1 % W(:,i) = max(W(:,i) + (AHt(:,i) - W * HHt_reg(:,i)-par.beta/2*U(:,par.ks+1:par.ks+par.kd2)*ones(par.kd2,1))/HHt_reg(i,i),epsilon); % if sum(W(:,i))>0 % W(:,i) = W(:,i)/norm(W(:,i)); % end % end % for i = par.ks+par.kd1+1:par.k1 % W(:,i) = max(W(:,i) + (AHt(:,i) - W * HHt_reg(:,i))/HHt_reg(i,i),epsilon); % if sum(W(:,i))>0 % W(:,i) = W(:,i)/norm(W(:,i)); % end % end % % error = norm(A-W*H,'fro') + norm(B-U*V,'fro') ; % error1 = norm(W(:,1:par.ks)-U(:,1:par.ks),'fro');% * par.alpha; % error2 = ones(1,par.kd1)*(W(:,par.ks+1:par.ks+par.kd1))'*U(:,par.ks+1:par.ks+par.kd2)*ones(par.kd2,1);% * par.beta; % %fprintf('%s error: %d,, %d,, %d,, total: %d\n', 'W', error, error1, error2, error+error1+error2); % % UtB = U'*B; % UtU = U'*U; % UtU_reg = applyReg(UtU,par,par.reg_h); % for i = 1:par.k2 % V(i,:) = max(V(i,:) + UtB(i,:) - UtU_reg(i,:) * V,epsilon); % end % % error = norm(A-W*H,'fro') + norm(B-U*V,'fro') ; % error1 = norm(W(:,1:par.ks)-U(:,1:par.ks),'fro');% * par.alpha; % error2 = ones(1,par.kd1)*(W(:,par.ks+1:par.ks+par.kd1))'*U(:,par.ks+1:par.ks+par.kd2)*ones(par.kd2,1);% * par.beta; % %fprintf('%s error: %d,, %d,, %d,, total: %d\n', 'V', error, error1, error2, error+error1+error2); % % BVt = B*V'; % VVt_reg = applyReg(V*V',par,par.reg_w); % for i = 1:par.ks % U(:,i) = max(U(:,i) * VVt_reg(i,i)/(VVt_reg(i,i)+par.alpha) + (BVt(:,i)+par.alpha*W(:,i)-U*VVt_reg(:,i)) / (VVt_reg(i,i)+par.alpha),epsilon); % if sum(U(:,i))>0 % U(:,i) = U(:,i)/norm(U(:,i)); % end % end % for i = par.ks+1:par.ks+par.kd2 % U(:,i) = max(U(:,i) + (BVt(:,i) - U * VVt_reg(:,i)-par.beta/2*W(:,par.ks+1:par.ks+par.kd1)*ones(par.kd1,1))/VVt_reg(i,i),epsilon); % if sum(U(:,i))>0 % U(:,i) = U(:,i)/norm(U(:,i)); % end % end % for i = par.ks+par.kd2+1:par.k2 % U(:,i) = max(U(:,i) + (BVt(:,i) - U * VVt_reg(:,i))/VVt_reg(i,i),epsilon); % if sum(U(:,i))>0 % U(:,i) = U(:,i)/norm(U(:,i)); % end % end % % error = norm(A-W*H,'fro') + norm(B-U*V,'fro') ; % error1 = norm(W(:,1:par.ks)-U(:,1:par.ks),'fro') * par.alpha; % error2 = ones(1,par.kd1)*(W(:,par.ks+1:par.ks+par.kd1))'*U(:,par.ks+1:par.ks+par.kd2)*ones(par.kd2,1) * par.beta; % %fprintf('%s error: %d,, %d,, %d,, total: %d\n', 'U', error, error1, error2, error+error1+error2); % % if par.track_grad % % gradW = [W*HHt_reg - AHt, U*VVt_reg - BVt]; % % gradH = [getGradientOne(W'*W,W'*A,H,par.reg_h,par);getGradientOne(U'*U,U'*B,V,par.reg_h,par)]; % gradH = 0; gradW = 0; % else % gradH = 0; gradW = 0; % end % end % % function [ver] = fix_iterLogger(ver,par,val,W,H,prev_W,prev_H) % end %----------------- Comp ----------------------- function [W,H,par,val,ver] = comp_initializer(A,W,H,par) epsilon = 1e-16; for iter=1:5 WtA = W'*A; WtW = W'*W; WtW_reg = applyReg(WtW,par,par.reg_h); for i = 1:par.k H(i,:) = max(H(i,:) + WtA(i,:) - WtW_reg(i,:) * H,epsilon); end AHt = A*H'; HHt_reg = applyReg(H*H',par,par.reg_w); for i = 1:par.k W(:,i) = max(W(:,i) * HHt_reg(i,i) + AHt(:,i) - W * HHt_reg(:,i),epsilon); if sum(W(:,i))>0 W(:,i) = W(:,i)/norm(W(:,i)); end end end [W,H]=normalize_by_W(W,H); val = struct([]); ver = struct([]); end function [W,H,gradW,gradH,val,convd] = comp_iterSolver(A,W,H,iter,par,val) epsilon = 1e-16; convd = 1; % if iter == 10 % for i = 1:par.ks % WtU = (W(:,i:par.k1))'*U(:,i:par.k2); % [C,I]=max(WtU); [C2,I2]=max(C); I1=I(I2); % W(:,[i I1+i-1]) = W(:,[I1+i-1 i]); % U(:,[i I2+i-1]) = U(:,[I2+i-1 i]); % end % for i = 1:par.kd1 % WtU = (W(:,par.ks+i:par.k1))'*U(:,par.ks+1:par.k2); % [C,I]=min(sum(WtU,2)); % W(:,[par.ks+i par.ks+i-1+I]) = W(:,[par.ks+i-1+I par.ks+i]); % end % for i = 1:par.kd2 % WtU = (W(:,par.ks+1:par.k1))'*U(:,par.ks+i:par.k2); % [C,I]=min(sum(WtU)); % U(:,[par.ks+i par.ks+i-1+I]) = U(:,[par.ks+i-1+I par.ks+i]); % end % end WtA = W'*A; WtW = W'*W; WtW_reg = applyReg(WtW,par,par.reg_h); for i = 1:par.k H(i,:) = max(H(i,:) + (WtA(i,:) - WtW_reg(i,:) * H)/WtW_reg(i,i),epsilon); end AHt = A*H'; HHt_reg = applyReg(H*H',par,par.reg_w); for i = 1:par.k % W(:,i) = max(W(:,i) + (AHt(:,i) - W * HHt_reg(:,i)-par.beta/2*sum(W(:,[(1:i-1) (i+1):end]),2))/HHt_reg(i,i),epsilon); W(:,i) = max(W(:,i) + (AHt(:,i) - W * HHt_reg(:,i)-par.beta/2*sum(W(:,[(1:i-1) (i+1):end]),2))/HHt_reg(i,i),0); if sum(W(:,i))==0 tttmp = floor(length(W(:,i))/par.k/2); W(randsample(length(W(:,i)),tttmp,false),i) = rand(tttmp,1); convd = -1; % break; end % if sum(W(:,i))>0 W(:,i) = W(:,i)/norm(W(:,i)); % end end if par.track_grad % gradW = [W*HHt_reg - AHt, U*VVt_reg - BVt]; % gradH = [getGradientOne(W'*W,W'*A,H,par.reg_h,par);getGradientOne(U'*U,U'*B,V,par.reg_h,par)]; gradH = 0; gradW = 0; else gradH = 0; gradW = 0; end end function [ver] = comp_iterLogger(ver,par,val,W,H,prev_W,prev_H) end %---------------------------------------------------------------------------------------------- % Utility Functions %---------------------------------------------------------------------------------------------- % This function prepares information about execution for a experiment purpose function ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,iter,elapsed,gradW,gradH) ver.iter = iter; ver.elapsed = elapsed; sqErr = getSquaredError(A,W,H,init); ver.rel_Error = sqrt(sqErr)/init.norm_A; ver.rel_Obj = getObj(sqErr,W,H,par)/init.baseObj; ver.norm_W = norm(W,'fro'); ver.norm_H = norm(H,'fro'); if par.track_prev ver.rel_Change_W = norm(W-prev_W,'fro')/init.norm_W; ver.rel_Change_H = norm(H-prev_H,'fro')/init.norm_H; end if par.track_grad ver.rel_NrPGrad_W = norm(projGradient(W,gradW),'fro')/init.normGr_W; ver.rel_NrPGrad_H = norm(projGradient(H,gradH),'fro')/init.normGr_H; ver.SC_NM_PGRAD = getStopCriterion(1,A,W,H,par,gradW,gradH)/init.SC_NM_PGRAD; ver.SC_PGRAD = getStopCriterion(2,A,W,H,par,gradW,gradH)/init.SC_PGRAD; ver.SC_DELTA = getStopCriterion(3,A,W,H,par,gradW,gradH)/init.SC_DELTA; end ver.density_W = length(find(W>0))/(par.m*par.k); ver.density_H = length(find(H>0))/(par.n*par.k); end % Execution information is collected in HIS variable function HIS = saveHIS(idx,ver,HIS) %idx = length(HIS.iter)+1; fldnames = fieldnames(ver); for i=1:length(fldnames) flname = fldnames{i}; HIS.(flname)(idx) = ver.(flname); end end %------------------------------------------------------------------------------- function retVal = getInitCriterion(stopRule,A,W,H,par,gradW,gradH) % STOPPING_RULE : 1 - Normalized proj. gradient % 2 - Proj. gradient % 3 - Delta by H. Kim % 0 - None (want to stop by MAX_ITER or MAX_TIME) if nargin~=7 [gradW,gradH] = getGradient(A,W,H,par); end [m,k]=size(W);, [k,n]=size(H);, numAll=(m*k)+(k*n); switch stopRule case 1 retVal = norm([gradW(:); gradH(:)])/numAll; case 2 retVal = norm([gradW(:); gradH(:)]); case 3 retVal = getStopCriterion(3,A,W,H,par,gradW,gradH); case 0 retVal = 1; end end %------------------------------------------------------------------------------- function retVal = getStopCriterion(stopRule,A,W,H,par,gradW,gradH) % STOPPING_RULE : 1 - Normalized proj. gradient % 2 - Proj. gradient % 3 - Delta by H. Kim % 0 - None (want to stop by MAX_ITER or MAX_TIME) if nargin~=7 [gradW,gradH] = getGradient(A,W,H,par); end switch stopRule case 1 pGradW = projGradient(W,gradW); pGradH = projGradient(H,gradH); pGrad = [pGradW(:); pGradH(:)]; retVal = norm(pGrad)/length(pGrad); case 2 pGradW = projGradient(W,gradW); pGradH = projGradient(H,gradH); pGrad = [pGradW(:); pGradH(:)]; retVal = norm(pGrad); case 3 resmat=min(H,gradH); resvec=resmat(:); resmat=min(W,gradW); resvec=[resvec; resmat(:)]; deltao=norm(resvec,1); %L1-norm num_notconv=length(find(abs(resvec)>0)); retVal=deltao/num_notconv; case 0 retVal = 1e100; end end %------------------------------------------------------------------------------- function sqErr = getSquaredError(A,W,H,init) sqErr = max((init.norm_A)^2 - 2*trace(H*(A'*W))+trace((W'*W)*(H*H')),0 ); end function retVal = getObj(sqErr,W,H,par) retVal = 0.5 * sqErr; retVal = retVal + par.reg_w(1) * sum(sum(W.*W)); retVal = retVal + par.reg_w(2) * sum(sum(W,2).^2); retVal = retVal + par.reg_h(1) * sum(sum(H.*H)); retVal = retVal + par.reg_h(2) * sum(sum(H,1).^2); end function AtA = applyReg(AtA,par,reg) % Frobenius norm regularization if reg(1) > 0 AtA = AtA + 2 * reg(1) * eye(par.k); end % L1-norm regularization if reg(2) > 0 AtA = AtA + 2 * reg(2) * ones(par.k,par.k); end end function [grad] = modifyGradient(grad,X,reg,par) if reg(1) > 0 grad = grad + 2 * reg(1) * X; end if reg(2) > 0 grad = grad + 2 * reg(2) * ones(par.k,par.k) * X; end end function [grad] = getGradientOne(AtA,AtB,X,reg,par) grad = AtA*X - AtB; grad = modifyGradient(grad,X,reg,par); end function [gradW,gradH] = getGradient(A,W,H,par) HHt = H*H'; HHt_reg = applyReg(HHt,par,par.reg_w); WtW = W'*W; WtW_reg = applyReg(WtW,par,par.reg_h); gradW = W*HHt_reg - A*H'; gradH = WtW_reg*H - W'*A; end %------------------------------------------------------------------------------- function pGradF = projGradient(F,gradF) pGradF = gradF(gradF<0|F>0); end %------------------------------------------------------------------------------- function [W,H,weights] = normalize_by_W(W,H) norm2=sqrt(sum(W.^2,1)); toNormalize = norm2>0; W(:,toNormalize) = W(:,toNormalize)./repmat(norm2(toNormalize),size(W,1),1); H(toNormalize,:) = H(toNormalize,:).*repmat(norm2(toNormalize)',1,size(H,2)); weights = ones(size(norm2)); weights(toNormalize) = norm2(toNormalize); end
github
sanghosuh/lens_nmf-matlab-master
fcnnls.m
.m
lens_nmf-matlab-master/library/nmf/fcnnls.m
4,407
utf_8
b1a8ecaaeeec231beb8a0a043366505e
% M. H. Van Benthem and M. R. Keenan, J. Chemometrics 2004; 18: 441-450 % % Given A and C this algorithm solves for the optimal % K in a least squares sense, using that % A = C*K % in the problem % min ||A-C*K||, s.t. K>=0, for given A and C. % function [K, Pset, many_iter] = fcnnls(C, A) % NNLS using normal equations and the fast combinatorial strategy % % I/O: [K, Pset] = fcnnls(C, A); % K = fcnnls(C, A); % % C is the nObs x lVar coefficient matrix % A is the nObs x pRHS matrix of observations % K is the lVar x pRHS solution matrix % Pset is the lVar x pRHS passive set logical array % % M. H. Van Benthem and M. R. Keenan % Sandia National Laboratories % % Pset: set of passive sets, one for each column % Fset: set of column indices for solutions that have not yet converged % Hset: set of column indices for currently infeasible solutions % Jset: working set of column indices for currently optimal solutions % % Check the input arguments for consistency and initialize error(nargchk(2,2,nargin)) [nObs, lVar] = size(C); if size(A,1)~= nObs, error('C and A have imcompatible sizes'), end pRHS = size(A,2); W = zeros(lVar, pRHS); iter=0; maxiter=3*lVar; % Precompute parts of pseudoinverse CtC = C'*C; CtA = C'*A; % Obtain the initial feasible solution and corresponding passive set K = cssls(CtC, CtA); Pset = K > 0; K(~Pset) = 0; D = K; Fset = find(~all(Pset)); % Active set algorithm for NNLS main loop oitr=0; % HKim many_iter = 0; while ~isempty(Fset) many_iter = many_iter + 1; if(many_iter == 5200) many_iter = 1; break; end oitr=oitr+1; if oitr > 5, fprintf('%d ',oitr);, end % HKim % Solve for the passive variables (uses subroutine below) K(:,Fset) = cssls(CtC, CtA(:,Fset), Pset(:,Fset)); % Find any infeasible solutions Hset = Fset(find(any(K(:,Fset) < 0))); % Make infeasible solutions feasible (standard NNLS inner loop) if ~isempty(Hset) nHset = length(Hset); alpha = zeros(lVar, nHset); while ~isempty(Hset) & (iter < maxiter) iter = iter + 1; alpha(:,1:nHset) = Inf; % Find indices of negative variables in passive set [i, j] = find(Pset(:,Hset) & (K(:,Hset) < 0)); if isempty(i), break, end hIdx = sub2ind([lVar nHset], i, j); if nHset==1, % HKim negIdx = sub2ind(size(K), i, Hset*ones(length(j),1)); %HKim else % HKim negIdx = sub2ind(size(K), i, Hset(j)'); end % HKim alpha(hIdx) = D(negIdx)./(D(negIdx) - K(negIdx)); [alphaMin,minIdx] = min(alpha(:,1:nHset)); alpha(:,1:nHset) = repmat(alphaMin, lVar, 1); D(:,Hset) = D(:,Hset)-alpha(:,1:nHset).*(D(:,Hset)-K(:,Hset)); idx2zero = sub2ind(size(D), minIdx, Hset); D(idx2zero) = 0; Pset(idx2zero) = 0; K(:, Hset) = cssls(CtC, CtA(:,Hset), Pset(:,Hset)); Hset = find(any(K < 0)); nHset = length(Hset); end end %if % Make sure the solution has converged %if iter == maxiter, error('Maximum number iterations exceeded'), end % Check solutions for optimality W(:,Fset) = CtA(:,Fset)-CtC*K(:,Fset); Jset = find(all(~Pset(:,Fset).*W(:,Fset) <= 0)); Fset = setdiff(Fset, Fset(Jset)); % For non-optimal solutions, add the appropriate variable to Pset if ~isempty(Fset) [mx, mxidx] = max(~Pset(:,Fset).*W(:,Fset)); Pset(sub2ind([lVar pRHS], mxidx, Fset)) = 1; D(:,Fset) = K(:,Fset); end end % ****************************** Subroutine**************************** function [K] = cssls(CtC, CtA, Pset) % Solve the set of equations CtA = CtC*K for the variables in set Pset % using the fast combinatorial approach K = zeros(size(CtA)); if (nargin == 2) || isempty(Pset) || all(Pset(:)) K = CtC\CtA; %K=pinv(CtC)*CtA; else [lVar pRHS] = size(Pset); codedPset = 2.^(lVar-1:-1:0)*Pset; [sortedPset, sortedEset] = sort(codedPset); breaks = diff(sortedPset); breakIdx = [0 find(breaks) pRHS]; for k = 1:length(breakIdx)-1 cols2solve = sortedEset(breakIdx(k)+1:breakIdx(k+1)); vars = Pset(:,sortedEset(breakIdx(k)+1)); K(vars,cols2solve) = CtC(vars,vars)\CtA(vars,cols2solve); %K(vars,cols2solve) = pinv(CtC(vars,vars))*CtA(vars,cols2solve); end end
github
sanghosuh/lens_nmf-matlab-master
nmfsh_comb_original.m
.m
lens_nmf-matlab-master/library/nmf/nmfsh_comb_original.m
4,989
utf_8
033ed6a9348041d0caab80dc5834ee2b
% % SNMF/R % % Author: Hyunsoo Kim and Haesun Park, Georgia Insitute of Technology % % Reference: % % Sparse Non-negative Matrix Factorizations via Alternating % Non-negativity-constrained Least Squares for Microarray Data Analysis % Hyunsoo Kim and Haesun Park, Bioinformatics, 2007, to appear. % % This software requires fcnnls.m, which can be obtained from % M. H. Van Benthem and M. R. Keenan, J. Chemometrics 2004; 18: 441-450 % % NMF: min_{W,H} (1/2) || A - WH ||_F^2 s.t. W>=0, H>=0 % SNMF/R: NMF with additional sparsity constraints on H % % min_{W,H} (1/2) (|| A - WH ||_F^2 + eta ||W||_F^2 % + beta (sum_(j=1)^n ||H(:,j)||_1^2)) % s.t. W>=0, H>=0 % % A: m x n data matrix (m: features, n: data points) % W: m x k basis matrix % H: k x n coefficient matrix % % function [W,H,i]=nmfsh_comb(A,k,param,verbose,bi_conv,eps_conv) % % input parameters: % A: m x n data matrix (m: features, n: data points) % k: desired positive integer k % param=[eta beta]: % eta (for supressing ||W||_F) % if eta < 0, software uses maxmum value in A as eta. % beta (for sparsity control) % Larger beta generates higher sparseness on H. % Too large beta is not recommended. % verbos: verbose = 0 for silence mode, otherwise print output % eps_conv: KKT convergence test (default eps_conv = 1e-4) % bi_conv=[wminchange iconv] biclustering convergence test % wminchange: the minimal allowance of the change of % row-clusters (default wminchange=0) % iconv: decide convergence if row-clusters (within wminchange) % and column-clusters have not changed for iconv convergence % checks. (default iconv=10) % % output: % W: m x k basis matrix % H: k x n coefficient matrix % i: the number of iterations % % sample usage: % [W,H]=nmfsh_comb(amlall,3,[-1 0.01],1); % [W,H]=nmfsh_comb(amlall,3,[-1 0.01],1,[3 10]); % -- in the convergence check, the change of row-clusters to % at most three rows is allowed. % % function [W,H,i,total_iter]=nmfsh_comb_original(A,k,param,verbose,bi_conv,eps_conv) if nargin<6, eps_conv=1e-4;, end if nargin<5, bi_conv=[0 10];, end if nargin<4, verbose=0;, end if nargin<3, error('too small number of input arguments.');, end maxiter = 500; % maximum number of iterations total_iter = 0; % by Sangho [m,n]=size(A); erravg1=[]; eta=param(1); beta=param(2); maxA=max(A(:)); if eta<0, eta=maxA; end eta2=eta^2; wminchange=bi_conv(1); iconv=bi_conv(2); % if verbose, fprintf('SNMF/R k=%d eta=%.4e beta (for sparse H)=%.4e wminchange=%d iconv=%d\n',... % k,full(eta),beta,wminchange,iconv);, end idxWold=zeros(m,1); idxHold=zeros(1,n); inc=0; % initialize random W W=rand(m,k); W=W./repmat(sqrt(sum(W.^2,1)),m,1); % normalize I_k=eta*eye(k); betavec=sqrt(beta)*ones(1,k); nrestart=0; for i=1:maxiter % min_h ||[[W; 1 ... 1]*H - [A; 0 ... 0]||, s.t. H>=0, for given A and W. % H = fcnnls_original([W; betavec],[A; zeros(1,n)]); if exist('H','var') H = nnlsm_blockpivot( [W; betavec], [A; zeros(1,n)], 0, H ); else H = nnlsm_blockpivot( [W; betavec], [A; zeros(1,n)], 0 ); end if find(sum(H,2)==0), fprintf('iter%d: 0 row in H eta=%.4e restart!\n',full(i),full(eta)); % modified by Sangho b/c of sparsity problem % fprintf('iter%d: 0 row in H eta=%.4e restart!\n',i,eta); % original code nrestart=nrestart+1; if nrestart >= 10, fprintf('[*Warning*] too many restarts due to too big beta value...\n'); i=-1; break; end idxWold=zeros(m,1); idxHold=zeros(1,n); inc=0; W=rand(m,k); W=W./repmat(sqrt(sum(W.^2,1)),m,1); % normalize continue; end % min_w ||[H'; I_k]*W' - [A'; 0]||, s.t. W>=0, for given A and H. % Wt=fcnnls([H'; I_k],[A'; zeros(k,m)]); W=Wt'; W = nnlsm_blockpivot( [H'; I_k], [A'; zeros(k,m)], 0, W' )'; % test convergence every 5 iterations if(mod(i,5)==0) | (i==1) [y,idxW]=max(W,[],2); [y,idxH]=max(H,[],1); changedW=length(find(idxW ~= idxWold)); changedH=length(find(idxH ~= idxHold)); if (changedW<=wminchange) & (changedH==0), inc=inc+1;, else inc=0;, end resmat=min(H,(W'*W)*H-W'*A+beta*ones(k,k)*H); resvec=resmat(:); resmat=min(W,W*(H*H')-A*H'+eta2*W); resvec=[resvec; resmat(:)]; conv=norm(resvec,1); %L1-norm convnum=length(find(abs(resvec)>0)); erravg=conv/convnum; if i==1, erravg1=erravg;, end % if verbose | (mod(i,1000)==0) % prints number of changing elements % fprintf('\t%d\t%d\t%d %d --- erravg1: %.4e erravg: %.4e\n',... % i,inc,changedW,changedH,erravg1,erravg); % end if (inc>=iconv) & (erravg<=eps_conv*erravg1), break, end idxWold=idxW; idxHold=idxH; end total_iter = total_iter + 1; % by Sangho end return;
github
sanghosuh/lens_nmf-matlab-master
nmf.m
.m
lens_nmf-matlab-master/library/nmf/nmf.m
25,072
utf_8
6ff4cbae3d1bff8b4c05b0a8a3485728
% Nonnegative Matrix Factorization : Algorithms Toolbox % % Written by Jingu Kim ([email protected]) % School of Computational Science and Engineering, % Georgia Institute of Technology % % Please send bug reports, comments, or questions to Jingu Kim. % This code comes with no guarantee or warranty of any kind. % % Reference: % Jingu Kim and Haesun Park, % Fast Nonnegative Matrix Factorization: An Active-set-like Method And Comparisons, % SIAM Journal on Scientific Computing (SISC), 33(6), pp. 3261-3281, 2011. % % Last modified on 02/22/2012 % % <Inputs> % A : Input data matrix (m x n) % k : Target low-rank % % (Below are optional arguments: can be set by providing name-value pairs) % % METHOD : Algorithm for solving NMF. One of the following values: % 'anls_bpp' 'hals' 'anls_asgroup' 'anls_asgivens' 'anls_pgrad' 'anls_pqn' 'als' 'mu' % See above paper (and references therein) for the details of these algorithms. % Default is 'anls_bpp'. % TOL : Stopping tolerance. Default is 1e-3. % If you want to obtain a more accurate solution, decrease TOL and increase MAX_ITER at the same time. % MAX_ITER : Maximum number of iterations. Default is 500. % MIN_ITER : Minimum number of iterations. Default is 20. % MAX_TIME : Maximum amount of time in seconds. Default is 1,000,000. % INIT : A struct containing initial values. INIT.W and INIT.H should contain initial values of % W and H of size (m x k) and (k x n), respectively. % VERBOSE : 0 (default) - No debugging information is collected. % 1 (debugging/experimental purpose) - History of computation is returned. See 'REC' variable. % 2 (debugging/experimental purpose) - History of computation is additionally printed on screen. % REG_W, REG_H : Regularization parameters for W and H. % Both REG_W and REG_H should be vector of two nonnegative numbers. % The first component is a parameter with Frobenius norm regularization, and % the second component is a parameter with L1-norm regularization. % For example, to promote sparsity in H, one might set REG_W = [alpha 0] and REG_H = [0 beta] % where alpha and beta are positive numbers. See above paper for more details. % Defaut is [0 0] for both REG_W and REG_H, which means no regularization. % <Outputs> % W : Obtained basis matrix (m x k) % H : Obtained coefficient matrix (k x n) % iter : Number of iterations % HIS : (debugging/experimental purpose) Auxiliary information about the execution % <Usage Examples> % nmf(A,10) % nmf(A,20,'verbose',2) % nmf(A,20,'verbose',1,'method','anls_bpp') % nmf(A,20,'verbose',1,'method','hals') % nmf(A,20,'verbose',1,'reg_w',[0.1 0],'reg_h',[0 0.5]) function [W,H,iter,REC]=nmf(A,k,varargin) % parse parameters params = inputParser; params.addParamValue('method' ,'anls_bpp',@(x) ischar(x) ); % params.addParamValue('tol' ,1e-3 ,@(x) isscalar(x) & x > 0); params.addParamValue('tol' ,1e-8 ,@(x) isscalar(x) & x > 0); % by sangho params.addParamValue('min_iter' ,20 ,@(x) isscalar(x) & x > 0); % params.addParamValue('max_iter' ,500 ,@(x) isscalar(x) & x > 0); params.addParamValue('max_iter' ,1000 ,@(x) isscalar(x) & x > 0); params.addParamValue('max_time' ,1e6 ,@(x) isscalar(x) & x > 0); params.addParamValue('init' ,struct([]),@(x) isstruct(x)); params.addParamValue('verbose' ,0 ,@(x) isscalar(x) & x >= 0); params.addParamValue('reg_w' ,[0 0] ,@(x) isvector(x) & length(x) == 2); params.addParamValue('reg_h' ,[0 0] ,@(x) isvector(x) & length(x) == 2); % The following options are reserved for debugging/experimental purposes. % Make sure to understand them before making changes params.addParamValue('subparams' ,struct([]),@(x) isstruct(x) ); params.addParamValue('track_grad' ,1 ,@(x) isscalar(x) & x >= 0); params.addParamValue('track_prev' ,1 ,@(x) isscalar(x) & x >= 0); params.addParamValue('stop_criterion',2 ,@(x) isscalar(x) & x >= 0); params.parse(varargin{:}); % joyfull % size(A) % if size(A,2)==3 % A=sparse(A(:,1),A(:,2),A(:,3)); % end % size(A) % params % copy from params object [m,n] = size(A); par = params.Results; par.m = m; par.n = n; par.k = k; % Stopping criteria are based on the gradient information. % Hence, 'track_grad' option needs to be turned on to use a criterion. if par.stop_criterion > 0 par.track_grad = 1; end % initialize if isempty(par.init) W = rand(m,k); H = rand(k,n); else W = par.init.W; H = par.init.H; end % This variable is for analysis/debugging, so it does not affect the output (W,H) of this program REC = struct([]); if par.verbose % Collect initial information for analysis/debugging clear('init'); init.norm_A = norm(A,'fro'); init.norm_W = norm(W,'fro'); init.norm_H = norm(H,'fro'); init.baseObj = getObj((init.norm_A)^2,W,H,par); if par.track_grad [gradW,gradH] = getGradient(A,W,H,par); init.normGr_W = norm(gradW,'fro'); init.normGr_H = norm(gradH,'fro'); init.SC_NM_PGRAD = getInitCriterion(1,A,W,H,par,gradW,gradH); init.SC_PGRAD = getInitCriterion(2,A,W,H,par,gradW,gradH); init.SC_DELTA = getInitCriterion(3,A,W,H,par,gradW,gradH); else gradW = 0; gradH = 0; end if par.track_prev prev_W = W; prev_H = H; else prev_W = 0; prev_H = 0; end ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,0,0,gradW,gradH); REC(1).init = init; REC.HIS = ver; if par.verbose == 2 display(init); end tPrev = cputime; end initializer= str2func([par.method,'_initializer']); iterSolver = str2func([par.method,'_iterSolver']); iterLogger = str2func([par.method,'_iterLogger']); [W,H,par,val,ver] = feval(initializer,A,W,H,par); if par.verbose & ~isempty(ver) tTemp = cputime; REC.HIS = saveHIS(1,ver,REC.HIS); tPrev = tPrev+(cputime-tTemp); end REC(1).par = par; REC.start_time = datestr(now); if par.verbose display(par); end tStart = cputime;, tTotal = 0; if par.track_grad initSC = getInitCriterion(par.stop_criterion,A,W,H,par); end SCconv = 0; SC_COUNT = 3; for iter=1:par.max_iter % Actual work of this iteration is executed here. [W,H,gradW,gradH,val] = feval(iterSolver,A,W,H,iter,par,val); if par.verbose % Collect information for analysis/debugging elapsed = cputime-tPrev; tTotal = tTotal + elapsed; clear('ver'); ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,iter,elapsed,gradW,gradH); ver = feval(iterLogger,ver,par,val,W,H,prev_W,prev_H); REC.HIS = saveHIS(iter+1,ver,REC.HIS); if par.track_prev, prev_W = W; prev_H = H; end if par.verbose == 2, display(ver);, end tPrev = cputime; end if (iter > par.min_iter) if (par.verbose && (tTotal > par.max_time)) || (~par.verbose && ((cputime-tStart)>par.max_time)) break; elseif par.track_grad SC = getStopCriterion(par.stop_criterion,A,W,H,par,gradW,gradH); if (SC/initSC <= par.tol) SCconv = SCconv + 1; if (SCconv >= SC_COUNT), break;, end else SCconv = 0; end end end end [m,n]=size(A); [W,H]=normalize_by_W(W,H); if par.verbose final.elapsed_total = sum(REC.HIS.elapsed); else final.elapsed_total = cputime-tStart; end final.iterations = iter; % sqErr = getSquaredError(A,W,H,init); % final.relative_error = sqrt(sqErr)/init.norm_A; % final.relative_obj = getObj(sqErr,W,H,par)/init.baseObj; final.W_density = length(find(W>0))/(m*k); final.H_density = length(find(H>0))/(n*k); if par.verbose REC.final = final; end REC.finish_time = datestr(now); if par.verbose display(final); end end %---------------------------------------------------------------------------- % Implementation of methods %---------------------------------------------------------------------------- %----------------- ANLS with Block Principal Pivoting Method -------------------------- function [W,H,par,val,ver] = anls_bpp_initializer(A,W,H,par) H = zeros(size(H)); ver.turnZr_W = 0; ver.turnZr_H = 0; ver.turnNz_W = 0; ver.turnNz_H = 0; ver.numChol_W = 0; ver.numChol_H = 0; ver.numEq_W = 0; ver.numEq_H = 0; ver.suc_W = 0; ver.suc_H = 0; val(1).WtA = W'*A; val.WtW = W'*W; end function [W,H,gradW,gradH,val] = anls_bpp_iterSolver(A,W,H,iter,par,val) WtW_reg = applyReg(val.WtW,par,par.reg_h); [H,temp,suc_H,numChol_H,numEq_H] = nnlsm_blockpivot(WtW_reg,val.WtA,1,H); HHt_reg = applyReg(H*H',par,par.reg_w); [W,gradW,suc_W,numChol_W,numEq_W] = nnlsm_blockpivot(HHt_reg,H*A',1,W'); W = W'; val.WtA = W'*A; val.WtW = W'*W; if par.track_grad gradW = gradW'; gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); else gradW = 0;gradH =0; end val(1).numChol_W = numChol_W; val.numChol_H = numChol_H; val.numEq_W = numEq_W; val.numEq_H = numEq_H; val.suc_W = suc_W; val.suc_H = suc_H; end function [ver] = anls_bpp_iterLogger(ver,par,val,W,H,prev_W,prev_H) if par.track_prev ver.turnZr_W = length(find( (prev_W>0) & (W==0) ))/(par.m*par.k); ver.turnZr_H = length(find( (prev_H>0) & (H==0) ))/(par.n*par.k); ver.turnNz_W = length(find( (prev_W==0) & (W>0) ))/(par.m*par.k); ver.turnNz_H = length(find( (prev_H==0) & (H>0) ))/(par.n*par.k); end ver.numChol_W = val.numChol_W; ver.numChol_H = val.numChol_H; ver.numEq_W = val.numEq_W; ver.numEq_H = val.numEq_H; ver.suc_W = val.suc_W; ver.suc_H = val.suc_H; end %----------------- ANLS with Active Set Method / Givens Updating -------------------------- function [W,H,par,val,ver] = anls_asgivens_initializer(A,W,H,par) H = zeros(size(H)); ver.turnZr_W = 0; ver.turnZr_H = 0; ver.turnNz_W = 0; ver.turnNz_H = 0; ver.numChol_W = 0; ver.numChol_H = 0; ver.suc_W = 0; ver.suc_H = 0; val(1).WtA = W'*A; val.WtW = W'*W; end function [W,H,gradW,gradH,val] = anls_asgivens_iterSolver(A,W,H,iter,par,val) WtW_reg = applyReg(val.WtW,par,par.reg_h); ow = 0; suc_H = zeros(1,size(H,2)); numChol_H = zeros(1,size(H,2)); for i=1:size(H,2) [H(:,i),temp,suc_H(i),numChol_H(i)] = nnls1_asgivens(WtW_reg,val.WtA(:,i),ow,1,H(:,i)); end suc_W = zeros(1,size(W,1)); numChol_W = zeros(1,size(W,1)); HHt_reg = applyReg(H*H',par,par.reg_w); HAt = H*A'; Wt = W'; gradWt = zeros(size(Wt)); for i=1:size(W,1) [Wt(:,i),gradWt(:,i),suc_W(i),numChol_W(i)] = nnls1_asgivens(HHt_reg,HAt(:,i),ow,1,Wt(:,i)); end W = Wt'; val.WtA = W'*A; val.WtW = W'*W; if par.track_grad gradW = gradWt'; gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); else gradW = 0; gradH =0; end val(1).numChol_W = sum(numChol_W); val.numChol_H = sum(numChol_H); val.suc_W = any(suc_W); val.suc_H = any(suc_H); end function [ver] = anls_asgivens_iterLogger(ver,par,val,W,H,prev_W,prev_H) if par.track_prev ver.turnZr_W = length(find( (prev_W>0) & (W==0) ))/(par.m*par.k); ver.turnZr_H = length(find( (prev_H>0) & (H==0) ))/(par.n*par.k); ver.turnNz_W = length(find( (prev_W==0) & (W>0) ))/(par.m*par.k); ver.turnNz_H = length(find( (prev_H==0) & (H>0) ))/(par.n*par.k); end ver.numChol_W = val.numChol_W; ver.numChol_H = val.numChol_H; ver.suc_W = val.suc_W; ver.suc_H = val.suc_H; end %----------- ANLS with Active Set Method / Column Grouping / No Overwrite ----------------- function [W,H,par,val,ver] = anls_asgroup_initializer(A,W,H,par) [W,H,par,val,ver] = anls_bpp_initializer(A,W,H,par); end function [W,H,gradW,gradH,val] = anls_asgroup_iterSolver(A,W,H,iter,par,val) WtW_reg = applyReg(val.WtW,par,par.reg_h); ow = 0; [H,temp,suc_H,numChol_H,numEq_H] = nnlsm_activeset(WtW_reg,val.WtA,ow,1,H); HHt_reg = applyReg(H*H',par,par.reg_w); [W,gradW,suc_W,numChol_W,numEq_W] = nnlsm_activeset(HHt_reg,H*A',ow,1,W'); W = W'; val.WtA = W'*A; val.WtW = W'*W; if par.track_grad gradW = gradW'; gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); else gradW = 0; gradH =0; end val(1).numChol_W = numChol_W; val.numChol_H = numChol_H; val.numEq_W = numEq_W; val.numEq_H = numEq_H; val.suc_W = suc_W; val.suc_H = suc_H; end function [ver] = anls_asgroup_iterLogger(ver,par,val,W,H,prev_W,prev_H) ver = anls_bpp_iterLogger(ver,par,val,W,H,prev_W,prev_H); end %----------------- ANLS with Projected Gradient Method -------------------------- function [W,H,par,val,ver] = anls_pgrad_initializer(A,W,H,par) if isempty(par.subparams) par.subparams(1).subtol_init = 0.1; par.subparams.reduce_factor = 0.1; par.subparams.num_warmup_iter = 5; par.subparams.min_subiter = 1; par.subparams.max_subiter = 100; par.subparams.min_tol = 1e-10; end [gradW,gradH] = getGradient(A,W,H,par); val(1).tol_W = par.subparams.subtol_init*norm(gradW,'fro'); val.tol_H = par.subparams.subtol_init*norm(gradH,'fro'); ver.subIter_W = 0; ver.subIter_H = 0; ver.numLineSearch_W = 0; ver.numLineSearch_H = 0; end function [W,H,gradW,gradH,val] = anls_pgrad_iterSolver(A,W,H,iter,par,val) if (iter>1 && iter<=par.subparams.num_warmup_iter) val.tol_W = val.tol_W * par.subparams.reduce_factor; val.tol_H = val.tol_H * par.subparams.reduce_factor; end WtW_reg = applyReg(W'*W,par,par.reg_h); WtA = W'*A; [H,gradHX,subIter_H,numLineSearch_H] = nnlssub_projgrad(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); if (iter > par.subparams.num_warmup_iter) && (subIter_H < par.subparams.min_subiter) && (val.tol_H >= par.subparams.min_tol) val.tol_H = par.subparams.reduce_factor * val.tol_H; [H,gradHX,subAddH,lsAddH] = nnlssub_projgrad(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); subIter_H = subIter_H + subAddH; numLineSearch_H = numLineSearch_H + lsAddH; end HHt_reg = applyReg(H*H',par,par.reg_w); HAt = H*A'; [W,gradW,subIter_W,numLineSearch_W] = nnlssub_projgrad(HHt_reg,HAt,val.tol_W,W',par.subparams.max_subiter,1); if (iter > par.subparams.num_warmup_iter) && (subIter_W < par.subparams.min_subiter) && (val.tol_W >= par.subparams.min_tol) val.tol_W = par.subparams.reduce_factor * val.tol_W; [W,gradW,subAddW,lsAddW] = nnlssub_projgrad(HHt_reg,HAt,val.tol_W,W,par.subparams.max_subiter,1); subIter_W = subIter_W + subAddW; numLineSearch_W = numLineSearch_W + lsAddW; end W = W'; if par.track_grad gradW = gradW'; gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par); else gradH = 0; gradW = 0; end val(1).subIter_W = subIter_W; val.subIter_H = subIter_H; val.numLineSearch_W = numLineSearch_W; val.numLineSearch_H = numLineSearch_H; end function [ver] = anls_pgrad_iterLogger(ver,par,val,W,H,prev_W,prev_H) ver.tol_W = val.tol_W; ver.tol_H = val.tol_H; ver.subIter_W = val.subIter_W; ver.subIter_H = val.subIter_H; ver.numLineSearch_W = val.numLineSearch_W; ver.numLineSearch_H = val.numLineSearch_H; end %----------------- ANLS with Projected Quasi Newton Method -------------------------- function [W,H,par,val,ver] = anls_pqn_initializer(A,W,H,par) [W,H,par,val,ver] = anls_pgrad_initializer(A,W,H,par); end function [W,H,gradW,gradH,val] = anls_pqn_iterSolver(A,W,H,iter,par,val) if (iter>1 && iter<=par.subparams.num_warmup_iter) val.tol_W = val.tol_W * par.subparams.reduce_factor; val.tol_H = val.tol_H * par.subparams.reduce_factor; end WtW_reg = applyReg(W'*W,par,par.reg_h); WtA = W'*A; [H,gradHX,subIter_H] = nnlssub_projnewton_mod(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); if (iter > par.subparams.num_warmup_iter) && (subIter_H/par.n < par.subparams.min_subiter) && (val.tol_H >= par.subparams.min_tol) val.tol_H = par.subparams.reduce_factor * val.tol_H; [H,gradHX,subAddH] = nnlssub_projnewton_mod(WtW_reg,WtA,val.tol_H,H,par.subparams.max_subiter,1); subIter_H = subIter_H + subAddH; end HHt_reg = applyReg(H*H',par,par.reg_w); HAt = H*A'; [W,gradW,subIter_W] = nnlssub_projnewton_mod(HHt_reg,HAt,val.tol_W,W',par.subparams.max_subiter,1); if (iter > par.subparams.num_warmup_iter) && (subIter_W/par.m < par.subparams.min_subiter) && (val.tol_W >= par.subparams.min_tol) val.tol_W = par.subparams.reduce_factor * val.tol_W; [W,gradW,subAddW] = nnlssub_projnewton_mod(HHt_reg,HAt,val.tol_W,W,par.subparams.max_subiter,1); subIter_W = subIter_W + subAddW; end W = W'; if par.track_grad gradW = gradW'; gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par); else gradH = 0; gradW = 0; end val(1).subIter_W = subIter_W; val.subIter_H = subIter_H; end function [ver] = anls_pqn_iterLogger(ver,par,val,W,H,prev_W,prev_H) ver.tol_W = val.tol_W; ver.tol_H = val.tol_H; ver.subIter_W = val.subIter_W; ver.subIter_H = val.subIter_H; end %----------------- Alternating Least Squares Method -------------------------- function [W,H,par,val,ver] = als_initializer(A,W,H,par) ver = struct([]); val.WtA = W'*A; val.WtW = W'*W; end function [W,H,gradW,gradH,val] = als_iterSolver(A,W,H,iter,par,val) WtW_reg = applyReg(val.WtW,par,par.reg_h); H = WtW_reg\val.WtA; H(H<0)=0; AHt = A*H'; HHt_reg = applyReg(H*H',par,par.reg_w); Wt = HHt_reg\AHt'; W=Wt'; W(W<0)=0; % normalize : necessary for ALS [W,H,weights] = normalize_by_W(W,H); D = diag(weights); val.WtA = W'*A; val.WtW = W'*W; AHt = AHt*D; HHt_reg = D*HHt_reg*D; if par.track_grad gradW = W*HHt_reg - AHt; gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); else gradH = 0; gradW = 0; end end function [ver] = als_iterLogger(ver,par,val,W,H,prev_W,prev_H) end %----------------- Multiplicatve Updating Method -------------------------- function [W,H,par,val,ver] = mu_initializer(A,W,H,par) ver = struct([]); val.WtA = W'*A; val.WtW = W'*W; end function [W,H,gradW,gradH,val] = mu_iterSolver(A,W,H,iter,par,val) epsilon = 1e-16; WtW_reg = applyReg(val.WtW,par,par.reg_h); H = H.*val.WtA./(WtW_reg*H + epsilon); HHt_reg = applyReg(H*H',par,par.reg_w); AHt = A*H'; W = W.*AHt./(W*HHt_reg + epsilon); val.WtA = W'*A; val.WtW = W'*W; if par.track_grad gradW = W*HHt_reg - AHt; gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par); else gradH = 0; gradW = 0; end end function [ver] = mu_iterLogger(ver,par,val,W,H,prev_W,prev_H) end %----------------- HALS Method : Algorith 2 of Cichocki and Phan ----------------------- function [W,H,par,val,ver] = hals_initializer(A,W,H,par) [W,H]=normalize_by_W(W,H); val = struct([]); ver = struct([]); end function [W,H,gradW,gradH,val] = hals_iterSolver(A,W,H,iter,par,val) epsilon = 1e-16; WtA = W'*A; WtW = W'*W; WtW_reg = applyReg(WtW,par,par.reg_h); for i = 1:par.k H(i,:) = max(H(i,:) + WtA(i,:) - WtW_reg(i,:) * H,epsilon); end AHt = A*H'; HHt_reg = applyReg(H*H',par,par.reg_w); for i = 1:par.k W(:,i) = max(W(:,i) * HHt_reg(i,i) + AHt(:,i) - W * HHt_reg(:,i),epsilon); if sum(W(:,i))>0 W(:,i) = W(:,i)/norm(W(:,i)); end end if par.track_grad gradW = W*HHt_reg - AHt; gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par); else gradH = 0; gradW = 0; end end function [ver] = hals_iterLogger(ver,par,val,W,H,prev_W,prev_H) end %---------------------------------------------------------------------------------------------- % Utility Functions %---------------------------------------------------------------------------------------------- % This function prepares information about execution for a experiment purpose function ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,iter,elapsed,gradW,gradH) ver.iter = iter; ver.elapsed = elapsed; sqErr = getSquaredError(A,W,H,init); ver.rel_Error = sqrt(sqErr)/init.norm_A; ver.rel_Obj = getObj(sqErr,W,H,par)/init.baseObj; ver.norm_W = norm(W,'fro'); ver.norm_H = norm(H,'fro'); if par.track_prev ver.rel_Change_W = norm(W-prev_W,'fro')/init.norm_W; ver.rel_Change_H = norm(H-prev_H,'fro')/init.norm_H; end if par.track_grad ver.rel_NrPGrad_W = norm(projGradient(W,gradW),'fro')/init.normGr_W; ver.rel_NrPGrad_H = norm(projGradient(H,gradH),'fro')/init.normGr_H; ver.SC_NM_PGRAD = getStopCriterion(1,A,W,H,par,gradW,gradH)/init.SC_NM_PGRAD; ver.SC_PGRAD = getStopCriterion(2,A,W,H,par,gradW,gradH)/init.SC_PGRAD; ver.SC_DELTA = getStopCriterion(3,A,W,H,par,gradW,gradH)/init.SC_DELTA; end ver.density_W = length(find(W>0))/(par.m*par.k); ver.density_H = length(find(H>0))/(par.n*par.k); end % Execution information is collected in HIS variable function HIS = saveHIS(idx,ver,HIS) %idx = length(HIS.iter)+1; fldnames = fieldnames(ver); for i=1:length(fldnames) flname = fldnames{i}; HIS.(flname)(idx) = ver.(flname); end end %------------------------------------------------------------------------------- function retVal = getInitCriterion(stopRule,A,W,H,par,gradW,gradH) % STOPPING_RULE : 1 - Normalized proj. gradient % 2 - Proj. gradient % 3 - Delta by H. Kim % 0 - None (want to stop by MAX_ITER or MAX_TIME) if nargin~=7 [gradW,gradH] = getGradient(A,W,H,par); end [m,k]=size(W);, [k,n]=size(H);, numAll=(m*k)+(k*n); switch stopRule case 1 retVal = norm([gradW(:); gradH(:)])/numAll; case 2 retVal = norm([gradW(:); gradH(:)]); case 3 retVal = getStopCriterion(3,A,W,H,par,gradW,gradH); case 0 retVal = 1; end end %------------------------------------------------------------------------------- function retVal = getStopCriterion(stopRule,A,W,H,par,gradW,gradH) % STOPPING_RULE : 1 - Normalized proj. gradient % 2 - Proj. gradient % 3 - Delta by H. Kim % 0 - None (want to stop by MAX_ITER or MAX_TIME) if nargin~=7 [gradW,gradH] = getGradient(A,W,H,par); end switch stopRule case 1 pGradW = projGradient(W,gradW); pGradH = projGradient(H,gradH); pGrad = [pGradW(:); pGradH(:)]; retVal = norm(pGrad)/length(pGrad); case 2 pGradW = projGradient(W,gradW); pGradH = projGradient(H,gradH); pGrad = [pGradW(:); pGradH(:)]; retVal = norm(pGrad); case 3 resmat=min(H,gradH); resvec=resmat(:); resmat=min(W,gradW); resvec=[resvec; resmat(:)]; deltao=norm(resvec,1); %L1-norm num_notconv=length(find(abs(resvec)>0)); retVal=deltao/num_notconv; case 0 retVal = 1e100; end end %------------------------------------------------------------------------------- function sqErr = getSquaredError(A,W,H,init) sqErr = max((init.norm_A)^2 - 2*trace(H*(A'*W))+trace((W'*W)*(H*H')),0 ); end function retVal = getObj(sqErr,W,H,par) retVal = 0.5 * sqErr; retVal = retVal + par.reg_w(1) * sum(sum(W.*W)); retVal = retVal + par.reg_w(2) * sum(sum(W,2).^2); retVal = retVal + par.reg_h(1) * sum(sum(H.*H)); retVal = retVal + par.reg_h(2) * sum(sum(H,1).^2); end function AtA = applyReg(AtA,par,reg) % Frobenius norm regularization if reg(1) > 0 AtA = AtA + 2 * reg(1) * eye(par.k); end % L1-norm regularization if reg(2) > 0 AtA = AtA + 2 * reg(2) * ones(par.k,par.k); end end function [grad] = modifyGradient(grad,X,reg,par) if reg(1) > 0 grad = grad + 2 * reg(1) * X; end if reg(2) > 0 grad = grad + 2 * reg(2) * ones(par.k,par.k) * X; end end function [grad] = getGradientOne(AtA,AtB,X,reg,par) grad = AtA*X - AtB; grad = modifyGradient(grad,X,reg,par); end function [gradW,gradH] = getGradient(A,W,H,par) HHt = H*H'; HHt_reg = applyReg(HHt,par,par.reg_w); WtW = W'*W; WtW_reg = applyReg(WtW,par,par.reg_h); gradW = W*HHt_reg - A*H'; gradH = WtW_reg*H - W'*A; end %------------------------------------------------------------------------------- function pGradF = projGradient(F,gradF) pGradF = gradF(gradF<0|F>0); end %------------------------------------------------------------------------------- function [W,H,weights] = normalize_by_W(W,H) norm2=sqrt(sum(W.^2,1)); toNormalize = norm2>0; W(:,toNormalize) = W(:,toNormalize)./repmat(norm2(toNormalize),size(W,1),1); H(toNormalize,:) = H(toNormalize,:).*repmat(norm2(toNormalize)',1,size(H,2)); weights = ones(size(norm2)); weights(toNormalize) = norm2(toNormalize); end
github
sanghosuh/lens_nmf-matlab-master
nnlsm_blockpivot.m
.m
lens_nmf-matlab-master/library/nmf/nnlsm_blockpivot.m
4,547
utf_8
f7cbdd610f2388c434a4444f43bdc3f2
% Nonnegativity Constrained Least Squares with Multiple Righthand Sides % using Block Principal Pivoting method % % This software solves the following problem: given A and B, find X such that % minimize || AX-B ||_F^2 where X>=0 elementwise. % % Reference: % Jingu Kim and Haesun Park, Toward Faster Nonnegative Matrix Factorization: A New Algorithm and Comparisons, % In Proceedings of the 2008 Eighth IEEE International Conference on Data Mining (ICDM'08), 353-362, 2008 % % Written by Jingu Kim ([email protected]) % Copyright 2008-2009 by Jingu Kim and Haesun Park, % School of Computational Science and Engineering, % Georgia Institute of Technology % % Check updated code at http://www.cc.gatech.edu/~jingu % Please send bug reports, comments, or questions to Jingu Kim. % This code comes with no guarantee or warranty of any kind. Note that this algorithm assumes that the % input matrix A has full column rank. % % Modified Feb-20-2009 % Modified Mar-13-2011: numChol and numEq % % <Inputs> % A : input matrix (m x n) (by default), or A'*A (n x n) if isInputProd==1 % B : input matrix (m x k) (by default), or A'*B (n x k) if isInputProd==1 % isInputProd : (optional, default:0) if turned on, use (A'*A,A'*B) as input instead of (A,B) % init : (optional) initial value for X % <Outputs> % X : the solution (n x k) % Y : A'*A*X - A'*B where X is the solution (n x k) % success : 0 for success, 1 for failure. % Failure could only happen on a numericall very ill-conditioned problem. % numChol : number of unique cholesky decompositions done % numEqs : number of systems of linear equations solved function [ X,Y,success,numChol,numEq ] = nnlsm_blockpivot( A, B, isInputProd, init ) if nargin<3, isInputProd=0;, end if isInputProd AtA = A;, AtB = B; else AtA = A'*A;, AtB = A'*B; end [n,k]=size(AtB); MAX_BIG_ITER = n*5; % set initial feasible solution X = zeros(n,k); if nargin<4 Y = - AtB; PassiveSet = false(n,k); numChol = 0; numEq = 0; else PassiveSet = (init > 0); [ X,numChol,numEq] = normalEqComb(AtA,AtB,PassiveSet); Y = AtA * X - AtB; end % parameters pbar = 3; P = zeros(1,k);, P(:) = pbar; Ninf = zeros(1,k);, Ninf(:) = n+1; NonOptSet = (Y < 0) & ~PassiveSet; InfeaSet = (X < 0) & PassiveSet; NotGood = sum(NonOptSet)+sum(InfeaSet); NotOptCols = NotGood > 0; bigIter = 0;, success=0; while(~isempty(find(NotOptCols))) bigIter = bigIter+1; if ((MAX_BIG_ITER >0) && (bigIter > MAX_BIG_ITER)) % set max_iter for ill-conditioned (numerically unstable) case success = 1;, break end Cols1 = NotOptCols & (NotGood < Ninf); Cols2 = NotOptCols & (NotGood >= Ninf) & (P >= 1); Cols3Ix = find(NotOptCols & ~Cols1 & ~Cols2); if ~isempty(find(Cols1)) P(Cols1) = pbar;,Ninf(Cols1) = NotGood(Cols1); PassiveSet(NonOptSet & repmat(Cols1,n,1)) = true; PassiveSet(InfeaSet & repmat(Cols1,n,1)) = false; end if ~isempty(find(Cols2)) P(Cols2) = P(Cols2)-1; PassiveSet(NonOptSet & repmat(Cols2,n,1)) = true; PassiveSet(InfeaSet & repmat(Cols2,n,1)) = false; end if ~isempty(Cols3Ix) for i=1:length(Cols3Ix) Ix = Cols3Ix(i); toChange = max(find( NonOptSet(:,Ix)|InfeaSet(:,Ix) )); if PassiveSet(toChange,Ix) PassiveSet(toChange,Ix)=false; else PassiveSet(toChange,Ix)=true; end end end [ X(:,NotOptCols),tempChol,tempEq ] = normalEqComb(AtA,AtB(:,NotOptCols),PassiveSet(:,NotOptCols)); numChol = numChol + tempChol; numEq = numEq + tempEq; X(abs(X)<1e-12) = 0; % One can uncomment this line for numerical stability. Y(:,NotOptCols) = AtA * X(:,NotOptCols) - AtB(:,NotOptCols); Y(abs(Y)<1e-12) = 0; % One can uncomment this line for numerical stability. % check optimality NotOptMask = repmat(NotOptCols,n,1); NonOptSet = NotOptMask & (Y < 0) & ~PassiveSet; InfeaSet = NotOptMask & (X < 0) & PassiveSet; NotGood = sum(NonOptSet)+sum(InfeaSet); NotOptCols = NotGood > 0; end end
github
sanghosuh/lens_nmf-matlab-master
nmfsh_comb.m
.m
lens_nmf-matlab-master/library/nmf/nmfsh_comb.m
4,550
utf_8
256156e36e548ecf054efe5ef6c2a532
% % SNMF/R % % Author: Hyunsoo Kim and Haesun Park, Georgia Insitute of Technology % % Reference: % % Sparse Non-negative Matrix Factorizations via Alternating % Non-negativity-constrained Least Squares for Microarray Data Analysis % Hyunsoo Kim and Haesun Park, Bioinformatics, 2007, to appear. % % This software requires fcnnls.m, which can be obtained from % M. H. Van Benthem and M. R. Keenan, J. Chemometrics 2004; 18: 441-450 % % NMF: min_{W,H} (1/2) || A - WH ||_F^2 s.t. W>=0, H>=0 % SNMF/R: NMF with additional sparsity constraints on H % % min_{W,H} (1/2) (|| A - WH ||_F^2 + eta ||W||_F^2 % + beta (sum_(j=1)^n ||H(:,j)||_1^2)) % s.t. W>=0, H>=0 % % A: m x n data matrix (m: features, n: data points) % W: m x k basis matrix % H: k x n coefficient matrix % % function [W,H,i]=nmfsh_comb(A,k,param,verbose,bi_conv,eps_conv) % % input parameters: % A: m x n data matrix (m: features, n: data points) % k: desired positive integer k % param=[eta beta]: % eta (for supressing ||W||_F) % if eta < 0, software uses maxmum value in A as eta. % beta (for sparsity control) % Larger beta generates higher sparseness on H. % Too large beta is not recommended. % verbos: verbose = 0 for silence mode, otherwise print output % eps_conv: KKT convergence test (default eps_conv = 1e-4) % bi_conv=[wminchange iconv] biclustering convergence test % wminchange: the minimal allowance of the change of % row-clusters (default wminchange=0) % iconv: decide convergence if row-clusters (within wminchange) % and column-clusters have not changed for iconv convergence % checks. (default iconv=10) % % output: % W: m x k basis matrix % H: k x n coefficient matrix % i: the number of iterations % % sample usage: % [W,H]=nmfsh_comb(amlall,3,[-1 0.01],1); % [W,H]=nmfsh_comb(amlall,3,[-1 0.01],1,[3 10]); % -- in the convergence check, the change of row-clusters to % at most three rows is allowed. % % function [W,H,i]=nmfsh_comb(A,k,param,verbose,bi_conv,eps_conv) if nargin<6, eps_conv=1e-4;, end if nargin<5, bi_conv=[0 10];, end if nargin<4, verbose=0;, end if nargin<3, error('too small number of input arguments.');, end maxiter = 200; % maximum number of iterations total_iter = 0; % by Sangho [m,n]=size(A); erravg1=[]; eta=param(1); beta=param(2); maxA=max(A(:)); if eta<0, eta=full(maxA); end eta2=eta^2; wminchange=bi_conv(1); iconv=bi_conv(2); if verbose, fprintf('SNMF/R k=%d eta=%.4e beta (for sparse H)=%.4e wminchange=%d iconv=%d\n',... k,eta,beta,wminchange,iconv);, end idxWold=zeros(m,1); idxHold=zeros(1,n); inc=0; % initialize random W W=rand(m,k); W=W./repmat(sqrt(sum(W.^2,1)),m,1); % normalize I_k=eta*eye(k); betavec=sqrt(beta)*ones(1,k); nrestart=0; for i=1:maxiter % min_h ||[[W; 1 ... 1]*H - [A; 0 ... 0]||, s.t. H>=0, for given A and W. [H, pset, many_iter] = fcnnls([W; betavec],[A; zeros(1,n)]); total_iter = total_iter + 1; % by Sangho if find(sum(H,2)==0), fprintf('iter%d: 0 row in H eta=%.4e restart!\n',i,eta); nrestart=nrestart+1; if nrestart >= 10, fprintf('[*Warning*] too many restarts due to too big beta value...\n'); i=-1; break; end idxWold=zeros(m,1); idxHold=zeros(1,n); inc=0; W=rand(m,k); W=W./repmat(sqrt(sum(W.^2,1)),m,1); % normalize continue; end % min_w ||[H'; I_k]*W' - [A'; 0]||, s.t. W>=0, for given A and H. Wt=fcnnls([H'; I_k],[A'; zeros(k,m)]); W=Wt'; % test convergence every 5 iterations if(mod(i,5)==0) | (i==1) [y,idxW]=max(W,[],2); [y,idxH]=max(H,[],1); changedW=length(find(idxW ~= idxWold)); changedH=length(find(idxH ~= idxHold)); if (changedW<=wminchange) & (changedH==0), inc=inc+1;, else inc=0;, end resmat=min(H,(W'*W)*H-W'*A+beta*ones(k,k)*H); resvec=resmat(:); resmat=min(W,W*(H*H')-A*H'+eta2*W); resvec=[resvec; resmat(:)]; conv=norm(resvec,1); %L1-norm convnum=length(find(abs(resvec)>0)); erravg=conv/convnum; if i==1, erravg1=erravg;, end if verbose | (mod(i,1000)==0) % prints number of changing elements fprintf('\t%d\t%d\t%d %d --- erravg1: %.4e erravg: %.4e\n',... i,inc,changedW,changedH,erravg1,erravg); end if (inc>=iconv) & (erravg<=eps_conv*erravg1), break, end idxWold=idxW; idxHold=idxH; end end return;
github
sanghosuh/lens_nmf-matlab-master
nnlsm_activeset.m
.m
lens_nmf-matlab-master/library/nmf/nnlsm_activeset.m
5,020
utf_8
5d51124cecf5c37d8ab6c1ec91dbad32
% Nonnegativity Constrained Least Squares with Multiple Righthand Sides % using Active Set method % % This software solves the following problem: given A and B, find X such that % minimize || AX-B ||_F^2 where X>=0 elementwise. % % Reference: % Charles L. Lawson and Richard J. Hanson, Solving Least Squares Problems, % Society for Industrial and Applied Mathematics, 1995 % M. H. Van Benthem and M. R. Keenan, % Fast Algorithm for the Solution of Large-scale Non-negativity-constrained Least Squares Problems, % J. Chemometrics 2004; 18: 441-450 % % Written by Jingu Kim ([email protected]) % School of Computational Science and Engineering, % Georgia Institute of Technology % % Updated Feb-20-2010 % Updated Mar-20-2011: numChol, numEq % % <Inputs> % A : input matrix (m x n) (by default), or A'*A (n x n) if isInputProd==1 % B : input matrix (m x k) (by default), or A'*B (n x k) if isInputProd==1 % overwrite : (optional, default:0) if turned on, unconstrained least squares solution is computed in the beginning % isInputProd : (optional, default:0) if turned on, use (A'*A,A'*B) as input instead of (A,B) % init : (optional) initial value for X % <Outputs> % X : the solution (n x k) % Y : A'*A*X - A'*B where X is the solution (n x k) % iter : number of systems of linear equations solved % success : 0 for success, 1 for failure. % Failure could only happen on a numericall very ill-conditioned problem. function [ X,Y,success,numChol,numEq ] = nnlsm_activeset( A, B, overwrite, isInputProd, init) if nargin<3, overwrite=0;, end if nargin<4, isInputProd=0;, end if isInputProd AtA=A;,AtB=B; else AtA=A'*A;, AtB=A'*B; end [n,k]=size(AtB); MAX_ITER = n*5; % set initial feasible solution if overwrite [X,numChol,numEq] = normalEqComb(AtA,AtB); PassSet = (X > 0); NotOptSet = any(X<0); elseif nargin>=5 X = init; X(X<0)=0; PassSet = (X > 0); NotOptSet = true(1,k); numChol = 0; numEq = 0; else X = zeros(n,k); PassSet = false(n,k); NotOptSet = true(1,k); numChol = 0; numEq = 0; end Y = zeros(n,k); Y(:,~NotOptSet)=AtA*X(:,~NotOptSet) - AtB(:,~NotOptSet); NotOptCols = find(NotOptSet); bigIter = 0;, success=0; while(~isempty(NotOptCols)) bigIter = bigIter+1; if ((MAX_ITER >0) && (bigIter > MAX_ITER)) % set max_iter for ill-conditioned (numerically unstable) case success = 1;, break end % find unconstrained LS solution for the passive set %Z = zeros(n,length(NotOptCols)); [ Z,tempChol,tempEq ] = normalEqComb(AtA,AtB(:,NotOptCols),PassSet(:,NotOptCols)); numChol = numChol + tempChol; numEq = numEq + tempEq; Z(abs(Z)<1e-12) = 0; % One can uncomment this line for numerical stability. InfeaSubSet = Z < 0; InfeaSubCols = find(any(InfeaSubSet)); FeaSubCols = find(all(~InfeaSubSet)); if ~isempty(InfeaSubCols) % for infeasible cols ZInfea = Z(:,InfeaSubCols); InfeaCols = NotOptCols(InfeaSubCols); Alpha = zeros(n,length(InfeaSubCols));, Alpha(:) = Inf; %InfeaSubSet(:,InfeaSubCols); [i,j] = find(InfeaSubSet(:,InfeaSubCols)); InfeaSubIx = sub2ind(size(Alpha),i,j); if length(InfeaCols) == 1 InfeaIx = sub2ind([n,k],i,InfeaCols * ones(length(j),1)); else InfeaIx = sub2ind([n,k],i,InfeaCols(j)'); end Alpha(InfeaSubIx) = X(InfeaIx)./(X(InfeaIx)-ZInfea(InfeaSubIx)); [minVal,minIx] = min(Alpha); Alpha(:,:) = repmat(minVal,n,1); X(:,InfeaCols) = X(:,InfeaCols)+Alpha.*(ZInfea-X(:,InfeaCols)); IxToActive = sub2ind([n,k],minIx,InfeaCols); X(IxToActive) = 0; PassSet(IxToActive) = false; end if ~isempty(FeaSubCols) % for feasible cols FeaCols = NotOptCols(FeaSubCols); X(:,FeaCols) = Z(:,FeaSubCols); Y(:,FeaCols) = AtA * X(:,FeaCols) - AtB(:,FeaCols); Y( abs(Y)<1e-12 ) = 0; % One can uncomment this line for numerical stability. NotOptSubSet = (Y(:,FeaCols) < 0) & ~PassSet(:,FeaCols); NewOptCols = FeaCols(all(~NotOptSubSet)); UpdateNotOptCols = FeaCols(any(NotOptSubSet)); if ~isempty(UpdateNotOptCols) [minVal,minIx] = min(Y(:,UpdateNotOptCols).*~PassSet(:,UpdateNotOptCols)); PassSet(sub2ind([n,k],minIx,UpdateNotOptCols)) = true; end NotOptSet(NewOptCols) = false; NotOptCols = find(NotOptSet); end end end
github
sanghosuh/lens_nmf-matlab-master
lens_nmf.m
.m
lens_nmf-matlab-master/library/lens_nmf/lens_nmf.m
3,937
utf_8
5cbdf2fafe4b052a4903068efafbcbf4
% Localizd Ensemble of Nonnegative Matrix Factorization (L-EnsNMF) % % Written by Sangho Suh ([email protected]) % Dept. of Computer Science and Engineering, % Korea University % % Reference: % % [1] Sangho Suh et al. % Boosted L-EnsNMF: Local Topic Discovery via Ensemble of Nonnegative Matrix Factorization. % IEEE International Conference on Data Mining 2016. % % [2] Da Kuang Haesun Park % Fast Rank-2 Nonnegative Matrix Factorization for Hierarchical Document Clustering % International conference on Knowledge Discovery and Data mining 2013 % % Please send bug reports, comments, or questions to Sangho Suh. % This code comes with no guarantee or warranty of any kind. % % Last modified 09/26/2016 % % <Inputs> % % A : Input matrix % k : Number of topics % topk : Number of keywords % total : Number of iterations % % <Outputs> % % Ws, Hs: Results of rank-2 NMF % Drs : Set of stage-wise rows with cosine similarity values % Dcs : Set of stage-wise columns with cosine similarity values % As : Updated input matrix % % <Usage Example> % % [Ws, Hs, Drs, Dcs, As] = lens_nmf(A, k, topk, total); function [Ws, Hs, Drs, Dcs, As] = lens_nmf(A, k, topk, total) % apply l2-normalization and get row-wise and column-wise cosine similarity values A_l2norm_row = bsxfun(@rdivide,A',sqrt(sum((A').^2)))'; A_cossim_row = A_l2norm_row*A_l2norm_row'; A_l2norm_col = bsxfun(@rdivide,A,sqrt(sum(A.^2))); A_cossim_col = A_l2norm_col'*A_l2norm_col; %% % initialization Ws = cell(total, 1); Hs = cell(total, 1); Rs = cell(total, 1); As = A; Rs{1} = A; vec_norm = 2.0; normW = true; anls_alg = @anls_entry_rank2_precompute; tol = 1e-4; maxiter = 10000; params_r2 = []; params_r2.vec_norm = vec_norm; params_r2.normW = normW; params_r2.anls_alg = anls_alg; params_r2.tol = tol; params_r2.maxiter = maxiter; %% for iter=1:(total) % loop for given number of iterations if iter == 1 row_idx = datasample(1:size(A,1),1,'Replace',false); else % sample with weight to get one row index row_idx = datasample(1:size(A,1),1,'Replace',false,'Weights', sum(cell2mat(Ws'),2)); end % get one column index col_idx = datasample(1:size(A,2),1,'Replace',false,'Weights', full(sum(abs(Rs{iter})))); % update Drs, Dcs with cosine similarity [Drs{iter}, Dcs{iter}] = getWeight(Rs{iter},A_cossim_row,A_cossim_col,row_idx,col_idx); % update A matrix using Drs,Dcs As = update(Rs{iter}, Drs{iter}, Dcs{iter}); [Ws{iter}, Hs{iter}] = nmfsh_comb_rank2(As, rand(size(As,1),2), rand(2,size(As,2)),params_r2); if iter <= total % fix W and use unweighted version of A to get H [Hs{iter},temp,suc_H,numChol_H,numEq_H] = nnlsm_activeset(Ws{iter}'*Ws{iter},Ws{iter}'*A,0,1,bsxfun(@times,Hs{iter}',1./Dcs{iter})'); % update residual matrix Rs{iter+1} = update_res_matrix(Rs{iter}, Ws{iter},Hs{iter}); end end end %% function [Dr_new, Dc_new] = getWeight(A,A_cossim_row,A_cossim_col,trm_idx,doc_idx) row_smooth = .01; col_smooth = .01; Dr_new = A_cossim_row(:,trm_idx)*(1-row_smooth)+row_smooth; Dc_new = A_cossim_col(:,doc_idx)*(1-col_smooth)+col_smooth; end %% function [newA] = update(A, Dr, Dc) newA = bsxfun(@times,A,Dr); % multiply each row of A with Dr row newA = bsxfun(@times,newA',Dc)'; % multiply each column of A with Dc column end %% function [newA] = update_res_matrix(A, W, H) newA = A - W*H; % get residual matrix newA (newA<0) = 0; % set any negative element to zero end
github
sanghosuh/lens_nmf-matlab-master
lens_nmf.bak.m
.m
lens_nmf-matlab-master/library/lens_nmf/lens_nmf.bak.m
4,098
utf_8
2d70f47e31eb3f1cc1db8f894af46665
% NOTE: This version is NOT in use as it is outdated % (It is before rank-2 NMF has been applied) % % Localizd Ensemble of Nonnegative Matrix Factorization (L-EnsNMF) % % Written by Sangho Suh ([email protected]) % Dept. of Computer Science and Engineering, % Korea University % % Reference: % % [1] Sangho Suh et al. % Boosted L-EnsNMF: Local Topic Discovery via Ensemble of Nonnegative Matrix Factorization. % IEEE International Conference on Data Mining 2016. % % [2] Da Kuang Haesun Park % Fast Rank-2 Nonnegative Matrix Factorization for Hierarchical Document Clustering % International conference on Knowledge Discovery and Data mining 2013 % % Please send bug reports, comments, or questions to Sangho Suh. % This code comes with no guarantee or warranty of any kind. % % Last modified 11/04/2016 % % <Inputs> % % A : Input matrix % k : Number of topics % topk : Number of keywords % iter : Number of iterations % % <Outputs> % % Ws, Hs: Results of standard NMF (rank-2 nmf is NOT applied here) % Drs : Set of stage-wise rows with cosine similarity values % Dcs : Set of stage-wise columns with cosine similarity values % As : Updated input matrix % % <Usage Example> % % [Ws, Hs, Drs, Dcs, As] = lens_nmf(A, k, topk, iter); function [Ws, Hs, Drs, Dcs, As] = lens_nmf(A, k, topk, iter) params = inputParser; params.addParamValue('method','absolute',@(x) ischar(x) ); par = params.Results; % apply l2-normalization and get row-wise and column-wise cosine similarity values A_l2norm_row = bsxfun(@rdivide,A',sqrt(sum((A').^2)))'; A_cossim_row = A_l2norm_row*A_l2norm_row'; A_l2norm_col = bsxfun(@rdivide,A,sqrt(sum(A.^2))); A_cossim_col = A_l2norm_col'*A_l2norm_col; Ws = cell(iter, 1); Hs = cell(iter, 1); Rs = cell(iter, 1); As = A; Rs{1} = A; for iter=1:(iter) if iter == 1 row_idx = datasample(1:size(A,1),1,'Replace',false); else % sample with weight to get one row index row_idx = datasample(1:size(A,1),1,'Replace',false,'Weights', full(sum(abs(Rs{iter}),2))); end % get one column index col_idx = datasample(1:size(A,2),1,'Replace',false,'Weights', full(sum(abs(Rs{iter})))); % update Drs, Dcs with cosine similarity [Drs{iter}, Dcs{iter}] = getWeight(Rs{iter},A_cossim_row,A_cossim_col,row_idx,col_idx); % update A matrix using Drs,Dcs As = update(Rs{iter}, Drs{iter}, Dcs{iter}); if exist('method','var') & strcmp(method,'hals') % if 'method' variable exists and it is 'hals', then do the following [Ws{iter}, Hs{iter}] = nmf(As, k,'verbose',0,'method','hals'); else [Ws{iter}, Hs{iter}] = nmf(As, k,'verbose',0); end if iter <= iter % fix W and use unweighted version of A to get H [Hs{iter},temp,suc_H,numChol_H,numEq_H] = nnlsm_activeset(Ws{iter}'*Ws{iter},Ws{iter}'*A,0,1,bsxfun(@times,Hs{iter}',1./Dcs{iter})'); % update residual matrix Rs{iter+1} = update_res_matrix(Rs{iter}, Ws{iter},Hs{iter}); end end end %% function [Dr_new, Dc_new] = getWeight(A,A_cossim_row,A_cossim_col,trm_idx,doc_idx) row_smooth = .01; col_smooth = .01; Dr_new = A_cossim_row(:,trm_idx)*(1-row_smooth)+row_smooth; Dc_new = A_cossim_col(:,doc_idx)*(1-col_smooth)+col_smooth; end function [newA] = update(A, Dr, Dc) newA = bsxfun(@times,A,Dr); % multiply each row of A with Dr row newA = bsxfun(@times,newA',Dc)'; % multiply each column of A with Dc column end function [newA] = update_res_matrix(A, W, H) newA = A - W*H; % get residual matrix newA (newA<0) = 0; % set any negative element to zero end
github
sanghosuh/lens_nmf-matlab-master
tfidf2.m
.m
lens_nmf-matlab-master/library/topictoolbox/tfidf2.m
794
utf_8
7e53767d9b5be3579b2c33e015e1991e
function [Y w] = tfidf2( X ) % FUNCTION applies TF-IDF weighting to word count vector matrix. % % [Y w] = tfidf2( X ); % % INPUT : % X - word count vectors (one column = one document) % % OUTPUT : % Y - TF-IDF weighted document-term matrix % w - IDF weights (useful to process other documents) % % get inverse document frequencies w = idf( X ); % TF * IDF Y = tf( X ) .* repmat( w, 1, size(X,2) ); function Y = tf( X ) % SUBFUNCTION computes word frequencies Y = X ./ repmat( sum(X,1), size(X,1), 1 ); Y( isnan(Y) ) = 0; function I = idf(X) % SUBFUNCTION computes inverse document frequencies % count DF (document frequency, i.e., the number of words in corpus) nz = sum( ( X > 0 ), 2 ); % compute idf for each document I = log( size(X,2) ./ (nz(:) + 1) );
github
masa-nudt/KCFDPT-master
run_tracker.m
.m
KCFDPT-master/run_tracker.m
4,772
utf_8
01f944bd59d3493d2df3bc098150dc22
% KCFDPT enhances KCFDP with "Background Suppression" % KCFDP is the visual object tracker presented in: % "Enable Scale and Aspect Ratio Adaptability in Visual Tracking with Detection Proposals" BMVC, 2015 % % Dafei Huang, Lei Luo, Mei Wen, Zhaoyun Chen and Chunyuan Zhang % % Utilization of EdgeBoxes to enable scale and aspect ratio adaptibility % "Exploiting the Circulant Structure of Tracking-by-detection with Kernels" ECCV, 2012 % % J. F. Henriques, R. Caseiro, P. Martins and J. Batista % % Original CSK tracker implementation % "High-Speed Tracking with Kernelized Correlation Filters" TPAMI, 2015 % http://www.isr.uc.pt/~henriques/circulant/ % % J. F. Henriques, R. Caseiro, P. Martins, J. Batista % % Original KCF and DCF tracker implementation % "Online Object Tracking: A Benchmark", CVPR, 2013. % http://visual-tracking.net/ % % Y. Wu, J. Lim, M.-H. Yang % % Benchmark sequences and toolkit % "Piotr's Image and Video Matlab Toolbox (PMT)" % http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html % % P. Dollar % % Tools untilized % "Adaptive Color Attributes for Real-Time Visual Tracking" CVPR, 2014. % % Martin Danelljan, Fahad Shahbaz Khan, Michael Felsberg and Joost van de Weijer % % Extended CSK tracker implementation with color attributes, new updating scheme and adaptive dimensionality reduction % "Structured Forests for Fast Edge Detection", ICCV 2013 % % P. Dollar and C. Zitnick % % Very fast edge detector (up to 60 fps depending on parameter settings) that achieves excellent accuracy % "Edge Boxes: Locating Object Proposals from Edges", ECCV 2014. % % C. Zitnick and P. Dollar % % Edge Boxes object proposal generation % Codes above are integrated and modified by Dafei Huang function run_tracker() addpath(genpath('/Users/dafei/Projects/toolbox-master/')); close all bSaveImage = 0; res_path = './result'; if bSaveImage & ~exist(res_path,'dir') mkdir(res_path); end % config sequence: seq=struct('name','Skating1','path','/Users/dafei/D11BAK/data_seq/Skating1/','startFrame',1,'endFrame',400,'nz',4,'ext','jpg','init_rect', [0,0,0,0]); seq.len = seq.endFrame - seq.startFrame + 1; seq.s_frames = cell(seq.len,1); nz = strcat('%0',num2str(seq.nz),'d'); %number of zeros in the name of image for i=1:seq.len image_no = seq.startFrame + (i-1); id = sprintf(nz,image_no); seq.s_frames{i} = strcat(seq.path,'img/',id,'.',seq.ext); % add 'img/' in every image path end rect_anno = dlmread(['./' seq.name '/groundtruth_rect.txt']); seq.init_rect = rect_anno(seq.startFrame,:); s_frames = seq.s_frames; % parameters according to the paper padding = 1.5; %extra area surrounding the target lambda = 1e-4; %regularization % output_sigma_factor = 0.1; %spatial bandwidth (proportional to target) output_sigma_factor = 0.06; %spatial bandwidth (proportional to target) % interp_factor = 0.02; interp_factor = 0.01; sigma = 0.5; hog_orientations = 9; cell_size = 4; target_sz = [seq.init_rect(1,4), seq.init_rect(1,3)]; pos = floor([seq.init_rect(1,2), seq.init_rect(1,1)]) + floor(target_sz/2); % general parameters params.visualization = 1; params.init_pos = pos; params.wsize = floor(target_sz); params.video_path = seq.path; params.s_frames = s_frames; params.bSaveImage = bSaveImage; params.res_path = res_path; % load pre-trained edge detection model and set opts model = load('./models/forest/modelBsds'); model = model.model; model.opts.multiscale = 0; model.opts.sharpen = 0; model.opts.nThreads = 4; % set up parameters for edgeBoxes (see edgeBoxesTrackParam.m) opts = edgeBoxesTrackParam; opts.alpha = .65; % step size of sliding window search opts.beta = .75; % nms threshold for object proposals %opts.maxBoxes = 1e4; % max number of boxes to detect opts.maxBoxes = 1e3; % don't need that many proposals (default is 1e4) opts.minScore = 0.0005; % min score of boxes to detect opts.kappa = 1.4; % 1.5 as default, can be changed for larger overlapping opts.minBoxArea = 200; opts.edgeMinMag = 0.1; % set up parameters for using edgeBoxes in scale and aspect ratio detection scale_params.scale_detect_window_factor = 1.4; scale_params.proposal_num_limit = 200; scale_params.pos_shift_damping = 0.7; scale_params.rescale_damping = 0.7; scale_params.EB_maxAR_factor = 1.5; scale_params.EB_minArea_factor = 0.3; scale_params.backSup_size = 64; [rect_position, fps] = tracker(params, ... padding, sigma, lambda, output_sigma_factor, interp_factor, ... cell_size, hog_orientations, ... model, opts, scale_params); disp(['fps: ' num2str(fps)]) end
github
masa-nudt/KCFDPT-master
run_KCFDPT.m
.m
KCFDPT-master/run_KCFDPT.m
4,286
utf_8
50eee1de0783f61cec78a3c38ae0e7e7
% KCFDPT enhances KCFDP with "Background Suppression" % KCFDP is the visual object tracker presented in: % "Enable Scale and Aspect Ratio Adaptability in Visual Tracking with Detection Proposals" BMVC, 2015 % % Dafei Huang, Lei Luo, Mei Wen, Zhaoyun Chen and Chunyuan Zhang % % Utilization of EdgeBoxes to enable scale and aspect ratio adaptibility % "Exploiting the Circulant Structure of Tracking-by-detection with Kernels" ECCV, 2012 % % J. F. Henriques, R. Caseiro, P. Martins and J. Batista % % Original CSK tracker implementation % "High-Speed Tracking with Kernelized Correlation Filters" TPAMI, 2015 % http://www.isr.uc.pt/~henriques/circulant/ % % J. F. Henriques, R. Caseiro, P. Martins, J. Batista % % Original KCF and DCF tracker implementation % "Online Object Tracking: A Benchmark", CVPR, 2013. % http://visual-tracking.net/ % % Y. Wu, J. Lim, M.-H. Yang % % Benchmark sequences and toolkit % "Piotr's Image and Video Matlab Toolbox (PMT)" % http://vision.ucsd.edu/~pdollar/toolbox/doc/index.html % % P. Dollar % % Tools untilized % "Adaptive Color Attributes for Real-Time Visual Tracking" CVPR, 2014. % % Martin Danelljan, Fahad Shahbaz Khan, Michael Felsberg and Joost van de Weijer % % Extended CSK tracker implementation with color attributes, new updating scheme and adaptive dimensionality reduction % "Structured Forests for Fast Edge Detection", ICCV 2013 % % P. Dollar and C. Zitnick % % Very fast edge detector (up to 60 fps depending on parameter settings) that achieves excellent accuracy % "Edge Boxes: Locating Object Proposals from Edges", ECCV 2014. % % C. Zitnick and P. Dollar % % Edge Boxes object proposal generation % Codes above are integrated and modified by Dafei Huang function results=run_KCFDPT(seq, res_path, bSaveImage) % 'res=run_' t.name '(subS, rp, bSaveImage);' sequence info, result path: ./tmp/evalType/sequence name_SCKCF_1.mat, whether to save result image addpath(genpath('/Users/dafei/Projects/toolbox-master/')); addpath(('../../rstEval')); close all s_frames = seq.s_frames; % parameters according to the paper padding = 1.5; %extra area surrounding the target lambda = 1e-4; %regularization % output_sigma_factor = 0.1; %spatial bandwidth (proportional to target) output_sigma_factor = 0.06; %spatial bandwidth (proportional to target) % interp_factor = 0.02; interp_factor = 0.01; sigma = 0.5; hog_orientations = 9; cell_size = 4; target_sz = [seq.init_rect(1,4), seq.init_rect(1,3)]; pos = floor([seq.init_rect(1,2), seq.init_rect(1,1)]) + floor(target_sz/2); % general parameters params.visualization = 0; params.init_pos = pos; params.wsize = floor(target_sz); params.video_path = seq.path; params.s_frames = s_frames; params.bSaveImage = bSaveImage; params.res_path = res_path; % load pre-trained edge detection model and set opts model = load('./models/forest/modelBsds'); model = model.model; model.opts.multiscale = 0; model.opts.sharpen = 0; model.opts.nThreads = 4; % set up parameters for edgeBoxes (see edgeBoxesTrackParam.m) opts = edgeBoxesTrackParam; opts.alpha = .65; % step size of sliding window search opts.beta = .75; % nms threshold for object proposals %opts.maxBoxes = 1e4; % max number of boxes to detect opts.maxBoxes = 1e3; % don't need that many proposals (default is 1e4) opts.minScore = 0.0005; % min score of boxes to detect opts.kappa = 1.4; % 1.5 as default, can be changed for larger overlapping opts.minBoxArea = 200; opts.edgeMinMag = 0.1; % set up parameters for using edgeBoxes in scale and aspect ratio detection scale_params.scale_detect_window_factor = 1.4; scale_params.proposal_num_limit = 200; scale_params.damping_factor = 0.7; scale_params.pos_shift_damping = scale_params.damping_factor; scale_params.rescale_damping = scale_params.damping_factor; scale_params.EB_maxAR_factor = 1.5; scale_params.EB_minArea_factor = 0.3; scale_params.backSup_size = 64; [rect_position, fps] = tracker(params, ... padding, sigma, lambda, output_sigma_factor, interp_factor, ... cell_size, hog_orientations, ... model, opts, scale_params); disp(['fps: ' num2str(fps)]) results.type = 'rect'; results.res = rect_position;%each row is a rectangle results.fps = fps; end
github
masa-nudt/KCFDPT-master
tracker.m
.m
KCFDPT-master/tracker.m
12,152
utf_8
03823a16cd4562c9c8895d265bfebe8f
% Original code is from Kernelized/Dual Correlation Filter (KCF/DCF) % by Joao F. Henriques, 2015 % Integrated and modified by Dafei Huang function [rect_position, fps] = tracker(params, ... padding, sigma, lambda, output_sigma_factor, interp_factor, ... cell_size, hog_orientations, ... model, opts, scale_params) % general parameters bSaveImage = params.bSaveImage; res_path = params.res_path; video_path = params.video_path; s_frames = params.s_frames; pos = floor(params.init_pos); target_sz = floor(params.wsize); visualization = params.visualization; % scale detection parameters scale_detect_window_factor = scale_params.scale_detect_window_factor; proposal_num_limit = scale_params.proposal_num_limit; pos_shift_damping = scale_params.pos_shift_damping; rescale_damping = scale_params.rescale_damping; EB_maxAR_factor = scale_params.EB_maxAR_factor; EB_minArea_factor = scale_params.EB_minArea_factor; backSup_size = scale_params.backSup_size; num_frames = numel(s_frames); %if the target is large, lower the resolution, we don't need that much %detail resize_image = (sqrt(prod(target_sz)) >= 100); %diagonal size >= threshold if resize_image, pos = floor(pos / 2); target_sz = floor(target_sz / 2); end org_target_sz = target_sz; %window size, taking padding into account window_sz = floor(target_sz * (1 + padding)); org_window_sz = window_sz; % %we could choose a size that is a power of two, for better FFT % %performance. in practice it is slower, due to the larger window size. % window_sz = 2 .^ nextpow2(window_sz); %create regression labels, gaussian shaped, with a bandwidth %proportional to target size output_sigma = sqrt(prod(target_sz)) * output_sigma_factor / cell_size; yf = fft2(gaussian_shaped_labels(output_sigma, floor(window_sz / cell_size))); %store pre-computed cosine window cos_window = hann(size(yf,1)) * hann(size(yf,2))'; rect_position = zeros(numel(s_frames), 4); temp = load('w2crs'); w2c = temp.w2crs; %note: variables ending with 'f' are in the Fourier domain. time = 0; %to calculate FPS for frame = 1:numel(s_frames), %load image im = imread(s_frames{frame}); org_im = imread(s_frames{frame}); if size(im,3) > 1, im = rgb2gray(im); end if resize_image, im = imresize(im, 0.5); org_im = imresize(org_im, 0.5, 'bilinear'); end tic() if frame > 1, %obtain a subwindow for detection at the position from last %frame, and convert to Fourier domain (its size is unchanged) patch = get_subwindow(im, pos, window_sz); patch = imresize(patch, org_window_sz, 'bilinear'); % scale its size to original size org_patch = get_subwindow(org_im, pos, window_sz); org_patch = imresize(org_patch, org_window_sz, 'bilinear'); zf = fft2(get_features(patch, org_patch, hog_orientations, cell_size, cos_window, w2c)); %calculate response of the classifier at all shifts kzf = gaussian_correlation(zf, model_xf, sigma); response = real(ifft2(model_alphaf .* kzf)); %equation for fast detection %target location is at the maximum response. we must take into %account the fact that, if the target doesn't move, the peak %will appear at the top-left corner, not at the center (this is %discussed in the paper). the responses wrap around cyclically. max_response = max(response(:)); [vert_delta, horiz_delta] = find(response == max_response, 1); if vert_delta > size(zf,1) / 2, %wrap around to negative half-space of vertical axis vert_delta = vert_delta - size(zf,1); end if horiz_delta > size(zf,2) / 2, %same for horizontal axis horiz_delta = horiz_delta - size(zf,2); end scale = window_sz ./ org_window_sz; pos = pos + ( (cell_size * [vert_delta - 1, horiz_delta - 1]) .* scale ); pre_target_rect = [pos([2,1]) - target_sz([2,1])/2, target_sz([2,1])]; % begin scale detection detect_sz = floor(target_sz * scale_detect_window_factor); % window size for scale detection mid_pt = detect_sz * 0.5; % center position in the window for scale detection % get the window for scale detection edgeBoxes_window = get_subwindow(org_im, pos, detect_sz); if size(org_im,3) == 1 % for gray sequences edgeBoxes_window = single(edgeBoxes_window / 255); edgeBoxes_window = cat(3, edgeBoxes_window, edgeBoxes_window, edgeBoxes_window); end % dynamically adjust edgeBoxes parameters opts.maxAspectRatio = max([target_sz(1)/target_sz(2), target_sz(2)/target_sz(1)]) * EB_maxAR_factor; opts.minBoxArea = floor( prod(target_sz) * EB_minArea_factor); % edgeBoxes proposals % Background Suppression is implemented within edgeBoxesTrackParam.m and edgeBoxesTrackParamMex.cpp edgeBoxes_window_proposals = edgeBoxesTrackParam(edgeBoxes_window, model, backSup_size, opts); % choose candidate proposals num_of_proposals = 0; proposals = zeros(proposal_num_limit,4); % center_y, center_x, rows, cols proposals_xywh = zeros(proposal_num_limit,4); target_in_edgeBoxes_window = [mid_pt([2,1]) - target_sz([2,1])/2, target_sz([2,1])]; % find candidate proposals among the top proposal_num_limit proposals detected by edgeBoxes for i = 1 : min([size(edgeBoxes_window_proposals,1) proposal_num_limit]) if calcRectInt(edgeBoxes_window_proposals(i,[1:4]), target_in_edgeBoxes_window) > 0.6 && ... calcRectInt(edgeBoxes_window_proposals(i,[1:4]), target_in_edgeBoxes_window) < 0.9 proposal_sz = [edgeBoxes_window_proposals(i,4) edgeBoxes_window_proposals(i,3)]; proposal_pos = [edgeBoxes_window_proposals(i,2) edgeBoxes_window_proposals(i,1)] + floor(proposal_sz/2); num_of_proposals = num_of_proposals + 1; proposals(num_of_proposals,:) = [pos+proposal_pos-mid_pt, proposal_sz]; proposals_xywh(num_of_proposals,:) = [proposals(num_of_proposals,[2,1]) - proposal_sz([2,1])/2, proposal_sz([2,1])]; end end % evaluate all the candidate proposals using kernel correlation model_alpha = ifft2(model_alphaf); max_proposal_response = max_response; new_pos = pos; new_target_sz = target_sz; for j = 1 : num_of_proposals proposal_patch = get_subwindow( im, proposals(j,1:2), proposals(j,3:4)*(1 + padding) ); proposal_patch = imresize(proposal_patch, org_window_sz, 'bilinear'); proposal_org_patch = get_subwindow( org_im, proposals(j,1:2), proposals(j,3:4)*(1 + padding) ); proposal_org_patch = imresize(proposal_org_patch, org_window_sz, 'bilinear'); proposal_zf = fft2(get_features(proposal_patch, proposal_org_patch, hog_orientations, cell_size, cos_window, w2c)); proposal_kz = gaussian_correlation_nofft(proposal_zf, model_xf, sigma); % no fft needed here % calculate the response of the classifier without considering the cyclic shifts proposal_response = model_alpha(:)' * proposal_kz(:); if proposal_response > max_proposal_response max_proposal_response = proposal_response; new_pos = proposals(j,1:2); new_target_sz = proposals(j,3:4); end end chosen_proposal = [new_pos([2,1]) - new_target_sz([2,1])/2, new_target_sz([2,1])]; pos = floor( ( 1 - pos_shift_damping ) * pos + pos_shift_damping * new_pos ); target_sz = floor( ( 1 - rescale_damping ) * target_sz + rescale_damping * new_target_sz ); window_sz = floor( target_sz * (1 + padding) ); end %obtain a subwindow for training at newly estimated target position patch = get_subwindow(im, pos, window_sz); org_patch = get_subwindow(org_im, pos, window_sz); if frame > 1 patch = imresize(patch, org_window_sz, 'bilinear'); % resize to original window size then train the new model org_patch = imresize(org_patch, org_window_sz, 'bilinear'); end xf = fft2(get_features(patch, org_patch, hog_orientations, cell_size, cos_window, w2c)); %Kernel Ridge Regression, calculate alphas (in Fourier domain) kf = gaussian_correlation(xf, xf, sigma); % alphaf = yf ./ (kf + lambda); %equation for fast training %utilize the updating scheme proposed in ACT new_alphaf_num = yf .* kf; new_alphaf_den = kf .* (kf + lambda); if frame == 1, %first frame, train with a single image % model_alphaf = alphaf; %utilize the updating scheme proposed in ACT alphaf_num = new_alphaf_num; alphaf_den = new_alphaf_den; model_xf = xf; else %subsequent frames, interpolate model % model_alphaf = (1 - interp_factor) * model_alphaf + interp_factor * alphaf; %utilize the updating scheme proposed in ACT alphaf_num = (1 - interp_factor) * alphaf_num + interp_factor * new_alphaf_num; alphaf_den = (1 - interp_factor) * alphaf_den + interp_factor * new_alphaf_den; model_xf = (1 - interp_factor) * model_xf + interp_factor * xf; end model_alphaf = alphaf_num ./ alphaf_den; %save position and timing rect_position(frame,:) = [pos([2,1]) - target_sz([2,1])/2, target_sz([2,1])]; time = time + toc(); %visualization (uncomment the commented code below for detailed visual effects) if visualization >= 1 if frame == 1, %first frame, create GUI figure('Number','off', 'Name',['Tracker - ' video_path]); im_handle = imshow(uint8(org_im), 'Border','tight', 'InitialMag', 100 + 100 * (length(im) < 500)); rect_handle = rectangle('Position',rect_position(frame,:), 'EdgeColor','g', 'LineWidth', 5); % top scored proposals % for j = 1 : 4 % proposal_handle(j) = rectangle('Position',[0,0,1,1], 'EdgeColor', 'r', 'LineWidth', 3); % end % preniminary location and previous size % pre_target_handle = rectangle('Position', [0,0,1,1], 'EdgeColor', [0.3,0.3,1], 'LineWidth', 4, 'lineStyle', '--'); % the most promising proposal % chosen_proposal_handle = rectangle('Position', [0,0,1,1], 'EdgeColor', [1,1,0], 'LineWidth', 3); % frame index % text_handle = text(30, 30, ['# ' int2str(frame)]); % set(text_handle, 'color', [0 1 1], 'FontSize', 30, 'FontWeight', 'Bold'); else try %subsequent frames, update GUI set(im_handle, 'CData', org_im) set(rect_handle, 'Position', rect_position(frame,:)); % for j = 1 : min([num_of_proposals 4]) % set(proposal_handle(j), 'Position', proposals_xywh(j,:)); % end % for j = (min([num_of_proposals 4])+1) : 4 % set(proposal_handle(j), 'Position', [0,0,1,1]); % end % set(pre_target_handle, 'Position', pre_target_rect); % set(chosen_proposal_handle, 'Position', chosen_proposal); % set(text_handle, 'string', ['# ' int2str(frame)]); catch return end end drawnow % pause end if bSaveImage == 1 imwrite(frame2im(getframe(gcf)),['../.' res_path num2str(frame) '.jpg']); end end if resize_image, rect_position = rect_position * 2; end fps = num_frames/time; end
github
masa-nudt/KCFDPT-master
edgeBoxesTrackParam.m
.m
KCFDPT-master/edgeBoxesTrackParam.m
4,994
utf_8
aae1f43113514db72a60c1023b1543cb
function bbs = edgeBoxesTrackParam( I, model, backSup_size, varargin ) % Generate Edge Boxes object proposals in given image(s). % % Compute Edge Boxes object proposals as described in: % C. Lawrence Zitnick and Piotr Doll? % "Edge Boxes: Locating Object Proposals from Edges", ECCV 2014. % The proposal boxes are fast to compute and give state-of-the-art recall. % Please cite the above paper if you end up using the code. % % The most important params are alpha and beta. The defaults are optimized % for detecting boxes at intersection over union (IoU) of 0.7. For other % settings of alpha/beta see the ECCV paper. In general larger alpha/beta % improve results at higher IoU (but using large alpha can be quite slow). % minScore/maxBoxes control the number of boxes returned and impact speed. % Finally, a number of additional params listed below are set to reasonable % defaults and in most cases should not need to be altered. % % For a faster version the proposal code runs at ~10 fps on average use: % model.opts.sharpen=0; opts.alpha=.625; opts.minScore=.02; % % The code uses the Structured Edge Detector to compute edge strength and % orientation. See edgesDetect.m for details. Alternatively, the code could % be altered to use any other edge detector such as Canny. % % The input 'I' can either be a single (color) image (or filename) or a % cell array of images (or filenames). In the first case, the return is a % set of bbs where each row has the format [x y w h score] and score is the % confidence of detection. If the input is a cell array, the output is a % cell array where each element is a set of bbs in the form above (in this % case a parfor loop is used to speed execution). % % USAGE % opts = edgeBoxes() % bbs = edgeBoxes( I, model, opts ) % % INPUTS % I - input image(s) of filename(s) of input image(s) % model - Structured Edge model trained with edgesTrain % opts - parameters (struct or name/value pairs) % (1) main parameters, see above for details % .name - [] target filename (if specified return is 1) % .alpha - [.65] step size of sliding window search % .beta - [.75] nms threshold for object proposals % .minScore - [.01] min score of boxes to detect //boxes with score smaller than .minScore will be removed and not refined % .maxBoxes - [1e4] max number of boxes to detect //used in boxesNms, together with .beta to decide the number of output boxes % (2) additional parameters, safe to ignore and leave at default vals % .edgeMinMag - [.1] increase to trade off accuracy for speed //eliminate weak edge pixels % .edgeMergeThr - [.5] increase to trade off accuracy for speed //form edge pixels into edge groups % .clusterMinMag - [.5] increase to trade off accuracy for speed //any edge pixel in a edge group whose response sum smaller than _clusterMinMag, will be removed or merged to anoter group % .maxAspectRatio - [3] max aspect ratio of boxes % .minBoxArea - [1000] minimum area of boxes % .gamma - [2] affinity sensitivity, see equation 1 in paper % .kappa - [1.5] scale sensitivity, see equation 3 in paper % % OUTPUTS % bbs - [nx5] array containing proposal bbs [x y w h score] % % EXAMPLE % % See also edgeBoxesDemo, edgesDetect % % Structured Edge Detection Toolbox Version 3.0 % Copyright 2014 P. Dollar and L. Zitnick. [pdollar-at-microsoft.com] % Please email me if you find bugs, or have suggestions or questions! % Licensed under the MSR-LA Full Rights License [see license.txt] % Modified by Dafei Huang to introduce Background Suppression % get default parameters (unimportant parameters are undocumented) dfs={'name','', 'alpha',.65, 'beta',.75, 'minScore',.01, 'maxBoxes',1e4,... 'edgeMinMag',.1, 'edgeMergeThr',.5, 'clusterMinMag',.5, ... 'maxAspectRatio',3, 'minBoxArea',1000, 'gamma',2, 'kappa',1.5 }; o=getPrmDflt(varargin,dfs,1); if(nargin==0), bbs=o; return; end % run detector possibly over multiple images and optionally save results f=o.name; if(~isempty(f) && exist(f,'file')), bbs=1; return; end if(~iscell(I)), bbs=edgeBoxesImg(I,model,o,backSup_size); else n=length(I); bbs=cell(n,1); parfor i=1:n, bbs{i}=edgeBoxesImg(I{i},model,o,backSup_size); end; end d=fileparts(f); if(~isempty(d)&&~exist(d,'dir')), mkdir(d); end if(~isempty(f)), save(f,'bbs'); bbs=1; end end function bbs = edgeBoxesImg( I, model, o, backSup_size ) % Generate Edge Boxes object proposals in single image. if(all(ischar(I))), I=imread(I); end model.opts.nms=0; [E,O]=edgesDetect(I,model); if(0), E=gradientMag(convTri(single(I),4)); E=E/max(E(:)); end E=edgesNmsMex(E,O,2,0,1,model.opts.nThreads); bbs=edgeBoxesTrackParamMex(E,O,o.alpha,o.beta,o.minScore,o.maxBoxes,... o.edgeMinMag,o.edgeMergeThr,o.clusterMinMag,... o.maxAspectRatio,o.minBoxArea,o.gamma,o.kappa,backSup_size); end
github
masa-nudt/KCFDPT-master
find_scale_change_level_seqs.m
.m
KCFDPT-master/anno_tool/find_scale_change_level_seqs.m
1,502
utf_8
ff2265e4bcedb5b56bfa05372b7d4d16
% Use 2.0, 1.8, 1.6 as parameter to find out sequences with different scale variation levels function find_scale_change_level_seqs(scale_exam_thres) pathAnno = './anno/'; attPath = './anno/att/'; addpath('./util/'); seqs = configSeqs; total_sc_variation = 0; total_frame = 0; count_variation_seqs = 0; for idxSeq=1:length(seqs) s = seqs{idxSeq}; att_anno = dlmread([attPath s.name '.txt']); % Make sure the sequence is annotated as "scale variation" in OTB if att_anno(3) == 0 continue; end s.len = s.endFrame - s.startFrame + 1; s.s_frames = cell(s.len,1); rect_anno = dlmread([pathAnno s.name '.txt']); numSeg = 20; [subSeqs, subAnno]=splitSeqTRE(s,numSeg,rect_anno); anno=subAnno{1}; count_sc_variation = 0; for i = 1 : size(anno,1) j = 1; j(i>30) = i-30 ; for k = j : i if anno(i,3)*anno(i,4) > scale_exam_thres * anno(k,3)*anno(k,4) || anno(i,3)*anno(i,4) < 1/scale_exam_thres * anno(k,3)*anno(k,4) count_sc_variation = count_sc_variation+1; break; end end end if count_sc_variation/size(anno,1) >= 0.1 disp(s.name); total_sc_variation = total_sc_variation + count_sc_variation; count_variation_seqs = count_variation_seqs + 1; total_frame = total_frame + size(anno,1); end end
github
masa-nudt/KCFDPT-master
find_aspect_ratio_change_seqs.m
.m
KCFDPT-master/anno_tool/find_aspect_ratio_change_seqs.m
1,666
utf_8
484a19e57cc10a9eb4bc3da64a0835ff
% Find out and annotate sequences with obvious aspect ratio variation function find_aspect_ratio_change_seqs() pathAnno = './anno/'; attPath = './anno/att/'; addpath('./util/'); seqs = configSeqs; total_ar_variation = 0; total_frame = 0; for idxSeq=1:length(seqs) s = seqs{idxSeq}; s.len = s.endFrame - s.startFrame + 1; s.s_frames = cell(s.len,1); rect_anno = dlmread([pathAnno s.name '.txt']); numSeg = 20; [subSeqs, subAnno]=splitSeqTRE(s,numSeg,rect_anno); anno=subAnno{1}; aspect_ratio_att = 0; count_ar_variation = 0; for i = 1 : size(anno,1) j = 1; j(i>30) = i-30 ; for k = j : i if anno(i,3)/anno(i,4) > 1.4 * anno(k,3)/anno(k,4) || anno(i,3)/anno(i,4) < 1/1.4 * anno(k,3)/anno(k,4) count_ar_variation = count_ar_variation+1; break; end end end if count_ar_variation/size(anno,1) >= 0.1 aspect_ratio_att = 1; disp(s.name); total_ar_variation = total_ar_variation + count_ar_variation; total_frame = total_frame + size(anno,1); end % Uncomment the commented code below to write into annotation files. % Use ONCE ONLY to prevent duplicate annotation. % att_anno = dlmread([attPath s.name '.txt']); % att_anno = [att_anno, aspect_ratio_att]; % dlmwrite([attPath s.name '.txt'], att_anno); end disp([num2str(total_ar_variation) ' frames undergoing aspect ratio variation out of ' ... num2str(total_frame) ' total frames.']);
github
masa-nudt/KCFDPT-master
find_aspect_ratio_change_level_seqs.m
.m
KCFDPT-master/anno_tool/find_aspect_ratio_change_level_seqs.m
1,266
utf_8
d7d2537ca8c5744e27546ffddf18a76c
% Use 1.6, 1.5, 1.4 as parameter to find out sequences with different aspect ratio variation levels function find_aspect_ratio_change_level_seqs(aspect_ratio_exam_thres) pathAnno = './anno/'; attPath = './anno/att/'; addpath('./util/'); seqs = configSeqs; total_ar_variation = 0; total_frame = 0; for idxSeq=1:length(seqs) s = seqs{idxSeq}; s.len = s.endFrame - s.startFrame + 1; s.s_frames = cell(s.len,1); rect_anno = dlmread([pathAnno s.name '.txt']); numSeg = 20; [subSeqs, subAnno]=splitSeqTRE(s,numSeg,rect_anno); anno=subAnno{1}; count_ar_variation = 0; for i = 1 : size(anno,1) j = 1; j(i>30) = i-30 ; for k = j : i if anno(i,3)/anno(i,4) > aspect_ratio_exam_thres * anno(k,3)/anno(k,4) || anno(i,3)/anno(i,4) < 1/aspect_ratio_exam_thres * anno(k,3)/anno(k,4) count_ar_variation = count_ar_variation+1; break; end end end if count_ar_variation/size(anno,1) >= 0.1 disp(s.name); total_ar_variation = total_ar_variation + count_ar_variation; total_frame = total_frame + size(anno,1); end end
github
masa-nudt/KCFDPT-master
find_scale_change_rate_seqs.m
.m
KCFDPT-master/anno_tool/find_scale_change_rate_seqs.m
1,502
utf_8
8cd0438817329932aab7fd4f6f2dc435
% Use 10, 20, 30 as parameter to find out sequences with different scale variation rates function find_scale_change_rate_seqs(scale_exam_window) pathAnno = './anno/'; attPath = './anno/att/'; addpath('./util/'); seqs = configSeqs; total_sc_variation = 0; total_frame = 0; count_variation_seqs = 0; for idxSeq=1:length(seqs) s = seqs{idxSeq}; att_anno = dlmread([attPath s.name '.txt']); % Make sure the sequence is annotated as "scale variation" in OTB if att_anno(3) == 0 continue; end s.len = s.endFrame - s.startFrame + 1; s.s_frames = cell(s.len,1); rect_anno = dlmread([pathAnno s.name '.txt']); numSeg = 20; [subSeqs, subAnno]=splitSeqTRE(s,numSeg,rect_anno); anno=subAnno{1}; count_sc_variation = 0; for i = 1 : size(anno,1) j = 1; j(i>scale_exam_window) = i-scale_exam_window ; for k = j : i if anno(i,3)*anno(i,4) > 1.6 * anno(k,3)*anno(k,4) || anno(i,3)*anno(i,4) < 1/1.6 * anno(k,3)*anno(k,4) count_sc_variation = count_sc_variation+1; break; end end end if count_sc_variation/size(anno,1) >= 0.1 disp(s.name); total_sc_variation = total_sc_variation + count_sc_variation; count_variation_seqs = count_variation_seqs + 1; total_frame = total_frame + size(anno,1); end end
github
masa-nudt/KCFDPT-master
find_aspect_ratio_change_rate_seqs.m
.m
KCFDPT-master/anno_tool/find_aspect_ratio_change_rate_seqs.m
1,266
utf_8
2b76b2d3af9ff02bb8bf9677ee8f35ea
% Use 10, 20, 30 as parameter to find out sequences with different aspect ratio variation rates function find_aspect_ratio_change_rate_seqs(aspect_ratio_exam_window) pathAnno = './anno/'; attPath = './anno/att/'; addpath('./util/'); seqs = configSeqs; total_ar_variation = 0; total_frame = 0; for idxSeq=1:length(seqs) s = seqs{idxSeq}; s.len = s.endFrame - s.startFrame + 1; s.s_frames = cell(s.len,1); rect_anno = dlmread([pathAnno s.name '.txt']); numSeg = 20; [subSeqs, subAnno]=splitSeqTRE(s,numSeg,rect_anno); anno=subAnno{1}; count_ar_variation = 0; for i = 1 : size(anno,1) j = 1; j(i>aspect_ratio_exam_window) = i-aspect_ratio_exam_window ; for k = j : i if anno(i,3)/anno(i,4) > 1.4 * anno(k,3)/anno(k,4) || anno(i,3)/anno(i,4) < 1/1.4 * anno(k,3)/anno(k,4) count_ar_variation = count_ar_variation+1; break; end end end if count_ar_variation/size(anno,1) >= 0.1 disp(s.name); total_ar_variation = total_ar_variation + count_ar_variation; total_frame = total_frame + size(anno,1); end end
github
tsajed/nmr-pred-master
s2spinach.m
.m
nmr-pred-master/spinach/etc/s2spinach.m
5,215
utf_8
66d7be1c0060b13e05fc7e6e10f05a32
% Reads SIMPSON spin system specification file and converts the % information into Spinach data structures. Syntax: % % [sys,inter]=s2spinach(filename) % % [email protected] function [sys,inter]=s2spinach(filename) % Check consistency grumble(filename); % Read the file fid=fopen(filename); simpson_file=textscan(fid,'%s','delimiter','\n'); simpson_file=simpson_file{:}; fclose(fid); % Locate the boundaries of the spinsys{} field for n=1:length(simpson_file) current_line=deblank(char(simpson_file{n})); if (length(current_line)>=7)&&strcmp(current_line(1:7),'spinsys') spinsys_start=n; for k=(n+1):length(simpson_file) current_line=deblank(char(simpson_file{k})); if strcmp(current_line,'}') spinsys_end=k; break end end end end % Tell the user if we found the spinsys{} section if exist('spinsys_start','var')&&exist('spinsys_end','var') disp(['SIMPSON spinsys{} section located between lines ' num2str(spinsys_start) ' and ' num2str(spinsys_end) '.']); else error('could not locate SIMPSON spinsys{} section'); end % Search for the isotope information for n=spinsys_start:spinsys_end current_line=deblank(char(simpson_file{n})); if (length(current_line)>=6)&&strcmp(current_line(1:6),'nuclei') sys.isotopes=textscan(current_line(7:end),'%s'); sys.isotopes=sys.isotopes{:}'; end end % Preallocate the coupling arrays nspins=length(sys.isotopes); inter.zeeman.matrix=mat2cell(zeros(3*nspins,3),3*ones(nspins,1))'; inter.coupling.matrix=mat2cell(zeros(3*nspins),3*ones(nspins,1),3*ones(nspins,1)); % Absorb the couplings for n=spinsys_start:spinsys_end % Kill the spaces at either end current_line=deblank(char(simpson_file{n})); % Parse the specification if (length(current_line)>=5)&&strcmp(current_line(1:5),'shift') % Bomb out if the Zeeman tensor is not in ppm if nnz(current_line(6:end)=='p')~=2 error('only ppm specification (# #p #p # # # #) is supported for Zeeman tensors.'); end % Get the ppm Zeeman tensor information zeeman_line=textscan(current_line(6:end),'%n %np %np %n %n %n %n'); eigvals=[zeeman_line{2}-zeeman_line{3}*(1+zeeman_line{4})/2 zeeman_line{2}-zeeman_line{3}*(1-zeeman_line{4})/2 zeeman_line{3}+zeeman_line{2}]; S=euler2dcm(pi*[zeeman_line{5} zeeman_line{6} zeeman_line{7}]/180); inter.zeeman.matrix{zeeman_line{1}}=inter.zeeman.matrix{zeeman_line{1}}+S*diag(eigvals)*S'; elseif (length(current_line)>=6)&&strcmp(current_line(1:6),'dipole') % Get the dipole-dipole coupling information dipole_line=textscan(current_line(7:end),'%n %n %n %n %n %n'); eigvals=[-dipole_line{3}/2 -dipole_line{3}/2 dipole_line{3}]; S=euler2dcm(pi*[dipole_line{4} dipole_line{5} dipole_line{6}]/180); inter.coupling.matrix{dipole_line{1},dipole_line{2}}=inter.coupling.matrix{dipole_line{1},dipole_line{2}}+S*diag(eigvals)*S'; elseif (length(current_line)>=9)&&strcmp(current_line(1:9),'jcoupling') % Get the generic coupling information coupling_line=textscan(current_line(10:end),'%n %n %n %n %n %n %n %n'); eigvals=[coupling_line{3}-coupling_line{4}*(1+coupling_line{5})/2 coupling_line{3}-coupling_line{4}*(1-coupling_line{5})/2 coupling_line{4}+coupling_line{3}]; S=euler2dcm(pi*[coupling_line{6} coupling_line{7} coupling_line{8}]/180); inter.coupling.matrix{coupling_line{1},coupling_line{2}}=inter.coupling.matrix{coupling_line{1},coupling_line{2}}+S*diag(eigvals)*S'; elseif (length(current_line)>=10)&&strcmp(current_line(1:10),'quadrupole') % Bomb out if the quadrupole tensor is not in Hz if nnz(current_line(11:end)=='p')~=0 error('only Hz specification (# # # # # # #) is supported for quadrupole tensors.'); end % Get the quadrupole tensor information quad_line=textscan(current_line(11:end),'%n %n %n %n %n %n %n'); eigvals=[-quad_line{3}*(1+quad_line{4})/2 -quad_line{3}*(1-quad_line{4})/2 quad_line{3}]; S=euler2dcm(pi*[quad_line{5} quad_line{6} quad_line{7}]/180); inter.coupling.matrix{quad_line{1},quad_line{1}}=inter.coupling.matrix{quad_line{1},quad_line{1}}+S*diag(eigvals)*S'; end end end % Consistency enforcement function grumble(filename) if ~ischar(filename) error('filename must be a character string.'); end end % According to a trade rumour, the 1983 vacancy for a Lecturer post % at Corpus Christi College, Oxford, was contested, amongst others, % by three candidates: Geoffrey Bodenhausen, Peter Hore and Malcolm % Levitt. Scrolling the Scopus database to that year and sorting the % results by citation numbers would provide much food for thought to % any young researcher seeking to further his academic career.
github
tsajed/nmr-pred-master
fid2ascii.m
.m
nmr-pred-master/spinach/etc/fid2ascii.m
2,254
utf_8
d290db1a84bcaac9d24a144a520fdb7a
% Writes free induction decays into ASCII files. % % <http://spindynamics.org/wiki/index.php?title=Fid2ascii.m> function fid2ascii(file_name,fid) % Check consistency grumble(fid) % Open the file for writing file_id=fopen(file_name,'w'); % Decide data dimensions if isvector(fid) % Interleave real and imaginary parts for n=1:numel(fid) fprintf(file_id,'%d %12.8E \n',[n real(fid(n))]); end for n=1:numel(fid) fprintf(file_id,'%d %12.8E \n',[(n+numel(fid)) imag(fid(n))]); end elseif ismatrix(fid) % Write out the fid for k=1:size(fid,2) % Interleave real and imaginary parts for n=1:size(fid,1) fprintf(file_id,'%d %d %12.8E \n',[n k real(fid(n,k))]); end for n=1:size(fid,1) fprintf(file_id,'%d %d %12.8E \n',[(n+size(fid,1)) k imag(fid(n,k))]); end end elseif ndims(fid)==3 % Write out the fid for m=1:size(fid,3) for k=1:size(fid,2) % Interleave real and imaginary parts for n=1:size(fid,1) fprintf(file_id,'%d %d %d %12.8E \n',[n k m real(fid(n,k,m))]); end for n=1:size(fid,1) fprintf(file_id,'%d %d %d %12.8E \n',[(n+size(fid,1)) k m imag(fid(n,k,m))]); end end end else % Complain and bomb out error('insupported data dimensionality.'); end % Close the file fclose(file_id); end % Consistency enforcement function grumble(fid) if ~isnumeric(fid), error('fid must be numeric.'); end end % To be a - I don't know if this phrase is an oxymoron - but to be a sensible % theologian, or at least one who has a pretense of being scholarly, you at % least have to have some vague idea of what's going on in science, how old % the universe is, etc. But to do science you don't have to know anything % about theology. Scientists don't read theology, they don't read philosophy, % it doesn't make any difference to what they're doing - for better or worse, % it may not be a value judgment, but it's true. % % Lawrence Krauss
github
tsajed/nmr-pred-master
destreak.m
.m
nmr-pred-master/spinach/etc/destreak.m
1,830
utf_8
e9cdee5122a200e1b85297391b7ffc4e
% Reduces streak artefacts in 2D and 3D NMR spectra. % % <http://spindynamics.org/wiki/index.php?title=Destreak.m> function spectrum=destreak(spectrum) % Process structures and cell arrays recursively if isstruct(spectrum) % Get the field names struct_fieldnames=fieldnames(spectrum); % Loop over field names for n=1:length(struct_fieldnames) % Call itself for each field name spectrum.(struct_fieldnames{n})=destreak(spectrum.(struct_fieldnames{n})); end elseif iscell(spectrum) % Loop over cells parfor n=1:numel(spectrum) % Call itself for each cell spectrum{n}=destreak(spectrum{n}); end end % Check consistency grumble(spectrum); % Decide problem dimensionality switch ndims(spectrum) case 2 % Destreak the spectrum spectrum=spectrum-kron(spectrum(:,1),ones(1,size(spectrum,2))); spectrum=spectrum-kron(spectrum(1,:),ones(size(spectrum,1),1)); case 3 % Destreak the spectrum spectrum=spectrum-repmat(spectrum(:,1,:),1,size(spectrum,2),1); spectrum=spectrum-repmat(spectrum(1,:,:),size(spectrum,1),1,1); spectrum=spectrum-repmat(spectrum(:,:,1),1,1,size(spectrum,3)); otherwise % Complain and bomb out error('unsupported spectrum dimensionality.'); end end % Consistency enforcement function grumble(spectrum) if ~isnumeric(spectrum) error(['spectrum must be a numeric array, a cell array '... 'of numeric arrays or a structure with numeric arrays inside.']); end end % If it flies, floats or fucks, you are better off renting it. % % Felix Dennis
github
tsajed/nmr-pred-master
guess_csa_pro.m
.m
nmr-pred-master/spinach/etc/guess_csa_pro.m
4,861
utf_8
fd23d5a9383a5e93c2cb219ad3f6e9c2
% Chemical shieft anisotropy estimates for peptide bond heteroatoms. % % <http://spindynamics.org/wiki/index.php?title=Guess_csa_pro.m> function CSAs=guess_csa_pro(aa_nums,pdb_ids,coords) % Check consistency grumble(aa_nums,pdb_ids,coords); % Preallocate CSA array CSAs=cell(numel(pdb_ids),1); % Number the atoms numbers=1:numel(coords); % Loop over amino acids for n=2:(max(aa_nums)-1) % Assign amide nitrogen CSAs if ismember('C',pdb_ids(aa_nums==n))&&... ismember('N',pdb_ids(aa_nums==(n+1)))&&... ismember('H',pdb_ids(aa_nums==(n+1))) % Get C coordinates local_coords=coords(aa_nums==n); C=local_coords{strcmp('C',pdb_ids(aa_nums==n))}; C=C(:); % Get N coordinates local_coords=coords(aa_nums==(n+1)); N=local_coords{strcmp('N',pdb_ids(aa_nums==(n+1)))}; N=N(:); % Get H coordinates local_coords=coords(aa_nums==(n+1)); H=local_coords{strcmp('H',pdb_ids(aa_nums==(n+1)))}; H=H(:); % Get the primary directions N_CO_vec=C-N; N_H_vec=H-N; % Double-check the distances if (norm(N_CO_vec)>2.0)||(norm(N_H_vec)>2.0) error('Amino acid numbering is not sequential.'); end % Make ZZ eigenvector collinear with N-CO bond zz_eigvec=N_CO_vec; zz_eigvec=zz_eigvec/norm(zz_eigvec); % Make YY eigenvector perpendicular to the peptide plane yy_eigvec=cross(N_CO_vec,N_H_vec); yy_eigvec=yy_eigvec/norm(yy_eigvec); % Make XX eigenvector perpendicular to the other two xx_eigvec=cross(yy_eigvec,zz_eigvec); xx_eigvec=xx_eigvec/norm(xx_eigvec); % Build the eigenvalue matrix D=diag([-125 45 80]); % Build the eigenvector matrix V=[xx_eigvec yy_eigvec zz_eigvec]; % Identify the nitrogen local_numbers=numbers(aa_nums==(n+1)); nitrogen_number=local_numbers(strcmp('N',pdb_ids(aa_nums==(n+1)))); % Compose the tensor CSAs{nitrogen_number}=V*D*V'; % Report to the user disp(['Amide nitrogen CSA for residue ' num2str(n) ' guessed from local geometry.']); end % Assign C=O carbon CSAs if ismember('C',pdb_ids(aa_nums==n))&&... ismember('N',pdb_ids(aa_nums==(n+1)))&&... ismember('CA',pdb_ids(aa_nums==n)) % Get C coordinates local_coords=coords(aa_nums==n); C=local_coords{strcmp('C',pdb_ids(aa_nums==n))}; C=C(:); % Get N coordinates local_coords=coords(aa_nums==(n+1)); N=local_coords{strcmp('N',pdb_ids(aa_nums==(n+1)))}; N=N(:); % Get CA coordinates local_coords=coords(aa_nums==n); CA=local_coords{strcmp('CA',pdb_ids(aa_nums==n))}; CA=CA(:); % Get the primary directions N_C_vec=C-N; C_CA_vec=CA-C; % Double-check the distances if (norm(N_C_vec)>2.0)||(norm(C_CA_vec)>2.0) error('Amino acid numbering is not sequential.'); end % Make XX eigenvector collinear with C-CA bond xx_eigvec=C_CA_vec; xx_eigvec=xx_eigvec/norm(xx_eigvec); % Make ZZ eigenvector perpendicular to the >C=O plane zz_eigvec=cross(C_CA_vec,N_C_vec); zz_eigvec=zz_eigvec/norm(zz_eigvec); % Make YY eigenvector perpendicular to the other two yy_eigvec=cross(xx_eigvec,zz_eigvec); yy_eigvec=yy_eigvec/norm(yy_eigvec); % Build the eigenvalue matrix D=diag([70 5 -75]); % Build the eigenvector matrix V=[xx_eigvec yy_eigvec zz_eigvec]; % Identify the carbon local_numbers=numbers(aa_nums==n); carbon_number=local_numbers(strcmp('C',pdb_ids(aa_nums==n))); % Compose the tensor CSAs{carbon_number}=V*D*V'; % Report to the user disp(['Carboxyl carbon CSA for residue ' num2str(n) ' guessed from local geometry.']); end end end % Consistency enforcement function grumble(aa_nums,pdb_ids,coords) if ~isnumeric(aa_nums) error('aa_nums must be a vector of integers.'); end if ~iscell(pdb_ids) error('pdb_ids must be a cell array of character strings.'); end if ~iscell(coords) error('coords must be a cell array of 3-vectors.'); end if (numel(aa_nums)~=numel(pdb_ids))||(numel(pdb_ids)~=numel(coords)) error('the input parameters must have the same number of elements.'); end end % "Where's the PCM solvent?" % % A 3rd year project student, % rummaging through IK's sol- % vent cabinet.
github
tsajed/nmr-pred-master
zfs_sampling.m
.m
nmr-pred-master/spinach/etc/zfs_sampling.m
1,871
utf_8
0641b3e36d23a8312fd27193983e1961
% Sampling function for ZFS parameter distributions. % % <http://spindynamics.org/wiki/index.php?title=Zfs_sampling.m> function [D,E,W]=zfs_sampling(npoints_d,npoints_e,tol) % Check consistency grumble(npoints_d,npoints_e,tol); % Generate Gauss-Legendre point set for D/D1 [X,WX]=lgwt(npoints_d,-2,2); % Get the standard deviation for unit FWHM sigma=1/(2*sqrt(2*log(2))); % Refract weights through a double Gaussian WX=WX.*(normpdf(X,-1,sigma)+normpdf(X,+1,sigma)); WX=WX/sum(WX); % Plot the double Gaussian subplot(1,2,1); plot(X,normpdf(X,-1,sigma)+normpdf(X,+1,sigma),'r-'); title('D/D0 distribution'); xlabel('D/D0'); ylabel('probability density'); axis tight; % Generate Gauss-legendre point set for E/D [Y,WY]=lgwt(npoints_e,0,1/3); % Refract weights through a quadratic function WY=WY.*(-(Y-0.25).^2+0.0625); WY=WY/sum(WY); % Plot the quadratic function subplot(1,2,2); plot(Y,-(Y-0.25).^2+0.0625,'r-'); title('E/D distribution'); xlabel('E/D'); ylabel('probability density'); axis tight; % Kron the weights D=kron(X,ones(size(Y))); E=D.*kron(ones(size(X)),Y); W=kron(WX,WY); W=W/sum(W); % Ignore small weights D(W<tol)=[]; E(W<tol)=[]; W(W<tol)=[]; end % Consistency enforcement function grumble(npoints_d,npoints_e,tol) if (~isnumeric(npoints_d))||(~isreal(npoints_d))||... (npoints_d<5)||(mod(npoints_d,1)~=0) error('npoints_d must be a real integer greater than 5.'); end if (~isnumeric(npoints_e))||(~isreal(npoints_e))||... (npoints_e<5)||(mod(npoints_e,1)~=0) error('npoints_e must be a real integer greater than 5.'); end if (~isnumeric(tol))||(~isreal(tol))||(tol<0) error('tol must be a positive real number much smaller than 1.'); end end % It is a cliche that most cliches are true, but % then, like most cliches, that cliche is untrue. % % Stephen Fry
github
tsajed/nmr-pred-master
strychnine.m
.m
nmr-pred-master/spinach/etc/strychnine.m
6,944
utf_8
1ca29f49a8c2c448992a9ce45a75be9f
% Spin system of strychnine. % % <http://spindynamics.org/wiki/index.php?title=Strychnine.m> function [sys,inter]=strychnine(spins) % Check consistency grumble(spins); % Shorthands for human-readable coupling designations below H1=1; H2=2; H3=3; H4=4; H8=5; H11a=6; H11b=7; H12=8; H13=9; H14=10; H15a=11; H15b=12; H16=13; H17a=14; H17b=15; H18a=16; H18b=17; H20a=18; H20b=19; H22=20; H23a=21; H23b=22; % Hydrogen atoms H_isotopes={'1H','1H','1H','1H','1H','1H','1H','1H','1H','1H','1H',... '1H','1H','1H','1H','1H','1H','1H','1H','1H','1H','1H'}; numH=numel(H_isotopes); % Proton chemical shifts H_zeeman=cell(1,numH); H_zeeman{H3}= 7.255; H_zeeman{H22}= 5.915; H_zeeman{H2}= 7.098; H_zeeman{H1}= 7.167; H_zeeman{H4}= 8.092; H_zeeman{H12}= 4.288; H_zeeman{H23b}=4.066; H_zeeman{H23a}=4.148; H_zeeman{H16}= 3.963; H_zeeman{H8}= 3.860; H_zeeman{H20b}=2.745; H_zeeman{H20a}=3.716; H_zeeman{H18a}=3.219; H_zeeman{H18b}=2.878; H_zeeman{H13}= 1.276; H_zeeman{H17a}=1.890; H_zeeman{H17b}=1.890; H_zeeman{H11a}=3.132; H_zeeman{H11b}=2.670; H_zeeman{H14}= 3.150; H_zeeman{H15b}=1.462; H_zeeman{H15a}=2.360; % Proton J-couplings H_coupling=cell(numH); H_coupling{H3,H4}= 7.90; H_coupling{H22,H23a}= 7.00; H_coupling{H22,H23b}= 6.10; H_coupling{H2,H3}= 7.44; H_coupling{H2,H4}= 0.98; H_coupling{H1,H2}= 7.49; H_coupling{H1,H3}= 1.08; H_coupling{H1,H4}= 0.23; H_coupling{H12,H13}= 3.30; H_coupling{H23a,H23b}=-13.80; H_coupling{H8,H13}= 10.41; H_coupling{H20a,H20b}=-14.80; H_coupling{H20a,H22}= 1.79; H_coupling{H18a,H18b}=-13.90; H_coupling{H13,H14}= 3.29; H_coupling{H17a,H17b}=-13.90; H_coupling{H17a,H18a}= 5.50; H_coupling{H17a,H18b}= 7.20; H_coupling{H17b,H18a}= 3.20; H_coupling{H17b,H18b}= 10.70; H_coupling{H11a,H11b}=-17.34; H_coupling{H11a,H12}= 3.34; H_coupling{H11b,H12}= 8.47; H_coupling{H14,H15a}= 4.11; H_coupling{H14,H15b}= 1.96; H_coupling{H14,H22}= 0.47; H_coupling{H14,H20a}= 1.61; H_coupling{H15a,H15b}=-14.35; H_coupling{H15a,H16}= 4.33; H_coupling{H15b,H16}= 2.42; % Proton coordinates H_coordinates=cell(1,numH); H_coordinates{H1}= [ 2.7336, -2.8961, -0.4256]; H_coordinates{H2}= [ 5.0747, -2.1373, -0.7803]; H_coordinates{H3}= [ 5.6630, 0.2547, -0.5015]; H_coordinates{H4}= [ 3.9144, 1.9280, 0.1137]; H_coordinates{H8}= [-0.6004, 0.4789, 1.3185]; H_coordinates{H11a}=[-0.3262, 4.0926, -0.0781]; H_coordinates{H11b}=[-0.6863, 3.1492, 1.3616]; H_coordinates{H12}= [-1.7489, 2.7068, -1.3360]; H_coordinates{H13}= [-0.0861, 1.0611, -1.5871]; H_coordinates{H14}= [-2.2234, 0.1869, -2.2835]; H_coordinates{H15a}=[ 0.0099, -1.0345, -2.4296]; H_coordinates{H15b}=[-1.3580, -2.1373, -2.4297]; H_coordinates{H16}= [ 0.3886, -2.9088, -0.8537]; H_coordinates{H17a}=[ 1.0318, -2.7083, 1.7742]; H_coordinates{H17b}=[ 0.6059, -1.1921, 2.5799]; H_coordinates{H18a}=[-1.2874, -3.1432, 2.3544]; H_coordinates{H18b}=[-1.7510, -1.4610, 2.0500]; H_coordinates{H20a}=[-2.9738, -2.8430, -1.0448]; H_coordinates{H20b}=[-3.4330, -2.5457, 0.6228]; H_coordinates{H22}= [-4.4597, -0.3928, 0.8115]; H_coordinates{H23a}=[-3.8532, 1.8278, -1.0768]; H_coordinates{H23b}=[-4.5333, 1.9818, 0.5498]; % Carbon and nitrogen atoms CN_isotopes={'13C','13C','13C','13C','13C','13C','13C','13C','15N','13C',... '13C','13C','13C','13C','13C','13C','13C','13C','15N','13C',... '13C','13C','13C'}; numCN=numel(CN_isotopes); % Carbon and nitrogen chemical shifts CN_zeeman=cell(1,numCN); CN_zeeman{10}= 169.28; CN_zeeman{9}= 155.00; CN_zeeman{5}= 142.23; CN_zeeman{21}= 140.45; CN_zeeman{6}= 132.72; CN_zeeman{3}= 128.56; CN_zeeman{22}= 127.34; CN_zeeman{2}= 124.20; CN_zeeman{1}= 122.26; CN_zeeman{4}= 116.23; CN_zeeman{12}= 76.85; CN_zeeman{23}= 64.60; CN_zeeman{16}= 60.28; CN_zeeman{8}= 60.10; CN_zeeman{20}= 52.68; CN_zeeman{7}= 51.96; CN_zeeman{18}= 50.35; CN_zeeman{13}= 48.22; CN_zeeman{17}= 42.85; CN_zeeman{11}= 42.48; CN_zeeman{19}= 35.00; CN_zeeman{14}= 31.60; CN_zeeman{15}= 26.84; % Carbon and nitrogen coordinates CN_coordinates=cell(1,numCN+2); CN_coordinates{4}= [ 3.6711, 0.8813, -0.0049]; CN_coordinates{3}= [ 4.6363, -0.0692, -0.3529]; CN_coordinates{2}= [ 4.3069, -1.4174, -0.5113]; CN_coordinates{1}= [ 2.9885, -1.8448, -0.3155]; CN_coordinates{6}= [ 2.0128, -0.9131, 0.0231]; CN_coordinates{5}= [ 2.3591, 0.4385, 0.1719]; CN_coordinates{8}= [ 0.0012, 0.3360, 0.4149]; CN_coordinates{7}= [ 0.5532, -1.1283, 0.3650]; CN_coordinates{9}= [ 1.2080, 1.1956, 0.4953]; CN_coordinates{17}=[ 0.3655, -1.8391, 1.7302]; CN_coordinates{18}=[-1.0998, -2.2803, 1.7028]; CN_coordinates{19}=[-1.3733, -2.6144, 0.2962]; CN_coordinates{16}=[-0.2694, -2.0788, -0.5579]; CN_coordinates{15}=[-0.8203, -1.4052, -1.8175]; CN_coordinates{14}=[-1.7397, -0.2431, -1.3932]; CN_coordinates{13}=[-0.8137, 0.8361, -0.7930]; CN_coordinates{10}=[ 1.0821, 2.5627, 0.3141]; CN_coordinates{11}=[-0.3587, 3.0755, 0.3170]; CN_coordinates{12}=[-1.4198, 2.2035, -0.4123]; CN_coordinates{23}=[-3.7138, 1.5364, -0.0219]; CN_coordinates{22}=[-3.7170, 0.0350, 0.1391]; CN_coordinates{21}=[-2.8213, -0.7674, -0.4478]; CN_coordinates{20}=[-2.7216, -2.2506, -0.1548]; % Combine the arrays sys.isotopes=[H_isotopes, CN_isotopes]; inter.zeeman.scalar=[H_zeeman, CN_zeeman]; inter.coordinates=[H_coordinates, CN_coordinates]; inter.coupling.scalar=cell(numH+numCN); inter.coupling.scalar(1:numH,1:numH)=H_coupling; % Add 13C-1H J-couplings inter.coupling.scalar{H3,3+numH}= 159.6; inter.coupling.scalar{H22,22+numH}= 157.7; inter.coupling.scalar{H2,2+numH}= 160.9; inter.coupling.scalar{H1,1+numH}= 159.0; inter.coupling.scalar{H4,4+numH}= 168.0; inter.coupling.scalar{H12,12+numH}= 145.4; inter.coupling.scalar{H23b,23+numH}=144.3; inter.coupling.scalar{H23a,23+numH}=137.2; inter.coupling.scalar{H16,16+numH}= 146.2; inter.coupling.scalar{H8,8+numH}= 145.4; inter.coupling.scalar{H20b,20+numH}=141.0; inter.coupling.scalar{H20a,20+numH}=141.0; inter.coupling.scalar{H18a,18+numH}=136.8; inter.coupling.scalar{H18b,18+numH}=0; inter.coupling.scalar{H13,13+numH}= 124.4; inter.coupling.scalar{H17a,17+numH}=133.4; inter.coupling.scalar{H17b,17+numH}=0; inter.coupling.scalar{H11a,11+numH}=126.3; inter.coupling.scalar{H11b,11+numH}=135.9; inter.coupling.scalar{H14,14+numH}= 130.1; inter.coupling.scalar{H15b,15+numH}=131.4; inter.coupling.scalar{H15a,15+numH}=131.4; % Prune the arrays mask=ismember(sys.isotopes,spins); sys.isotopes=sys.isotopes(mask); inter.zeeman.scalar=inter.zeeman.scalar(mask); inter.coordinates=inter.coordinates(mask); inter.coupling.scalar=inter.coupling.scalar(mask,mask); end % Consistency enforcement function grumble(spins) if (~iscell(spins))||(~all(cellfun(@ischar,spins))) error('spins argument must be a cell array of character strings.'); end end % Patience, n. - a minor form of despair, disguised as a virtue. % % Ambrose Bierce
github
tsajed/nmr-pred-master
read_pdb_nuc.m
.m
nmr-pred-master/spinach/etc/read_pdb_nuc.m
2,126
utf_8
39429a1bc93649e3031f4b00e94ac39b
% Reads DNA/RNA PDB files. % % <http://spindynamics.org/wiki/index.php?title=Read_pdb_nuc.m> function [res_num,res_typ,pdb_id,coords]=read_pdb_nuc(pdb_file_name) % Check consistency grumble(pdb_file_name); % Open the PDB file file_id=fopen(pdb_file_name,'r'); % Get the outputs started res_num=[]; res_typ={}; pdb_id={}; coords={}; % Parse the PDB file while ~feof(file_id) data_line=fgetl(file_id); if ~isempty(data_line) parsed_string=textscan(data_line,'ATOM %f %s %s %f %f %f %f %f %f %s','delimiter',' ','MultipleDelimsAsOne',1); if all(~cellfun(@isempty,parsed_string)) res_num(end+1)=parsed_string{4}; %#ok<AGROW> res_typ{end+1}=parsed_string{3}{1}; %#ok<AGROW> pdb_id{end+1}=parsed_string{2}{1}; %#ok<AGROW> coords{end+1}=[parsed_string{5:7}]; %#ok<AGROW> end end end % Capitalize amino acid type specifications for n=1:numel(res_typ) res_typ{n}=upper(res_typ{n}); %#ok<AGROW> end % Make outputs column vectors res_num=res_num'; res_typ=res_typ'; pdb_id=pdb_id'; coords=coords'; % Close the PDB file fclose(file_id); end % Consistency enforcement function grumble(pdb_file_name) if ~ischar(pdb_file_name) error('pdb_file_name must be a character string.'); end end % I think that it might well be premature to make an award of % a Prize to Watson and Crick, because of existing uncertainty % about the detailed structure of nucleic acid. I myself feel % that it is likely that the general nature of the Watson-Crick % structure is correct, but that there is doubt about details. % With respect to Wilkins, I may say that I recognize his virtu- % osity in having grown better fibers of DNA than any that had % been grown before and in having obtained [better] x-ray photo- % graphs than were available before, but I doubt that this work % represents a sufficient contribution to chemistry to permit % him to be included among recipients of a Nobel Prize. % % Linus Pauling, in his letter to the Nobel Prize % Committee, 15 March 1960.
github
tsajed/nmr-pred-master
g2spinach.m
.m
nmr-pred-master/spinach/etc/g2spinach.m
5,250
utf_8
0a51da6a3f1beb6f44e4a32f5bce5cc5
% Forms Spinach data structures from Gaussian parsing output returned by gparse.m function. % % <http://spindynamics.org/wiki/index.php?title=G2spinach.m> function [sys,inter]=g2spinach(props,particles,references,options) % Check consistency grumble(props,particles,references,options); % Index the particles to include sys.isotopes={}; index=[]; ref_index=[]; for n=1:length(props.symbols) %#ok<*AGROW> for k=1:length(particles) if strcmp(props.symbols{n},particles{k}{1}) sys.isotopes=[sys.isotopes particles{k}{2}]; index=[index n]; ref_index=[ref_index k]; end end end nspins=length(index); % Decide whether to include coordinates if nargin<4 include_xyz=true(); else if ~isfield(options,'no_xyz') include_xyz=true(); elseif ~options.no_xyz include_xyz=true(); else include_xyz=false(); end end % Process coordinates if include_xyz inter.coordinates=props.std_geom(index,:); inter.coordinates=num2cell(inter.coordinates,2); end % Decide which magnetic parameters to return switch ismember('E',[particles{:}]) % EPR parameterization case 1 % Add the electron as the last spin in the isotope list sys.isotopes=[sys.isotopes, 'E']; nspins=nspins+1; % Electron coordinates should be treated as unknown if include_xyz, inter.coordinates{end+1}=[]; end % All Zeeman tensors are zero except for the g-tensor of the electron inter.zeeman.matrix=cell(1,nspins); inter.zeeman.matrix{nspins}=props.g_tensor.matrix; % All couplings are zero except for the hyperfine couplings to the electron inter.coupling.matrix=mat2cell(zeros(3*nspins,3*nspins),3*ones(nspins,1),3*ones(nspins,1)); for n=1:(nspins-1) inter.coupling.matrix{n,end}=1e6*gauss2mhz(props.hfc.full.matrix{index(n)}/2); inter.coupling.matrix{end,n}=1e6*gauss2mhz(props.hfc.full.matrix{index(n)}/2); end % Remove small hyperfine couplings if (nargin==4)&&isfield(options,'min_hfc') for n=1:nspins for k=1:nspins if norm(inter.coupling.matrix{n,k},'fro')<options.min_hfc inter.coupling.matrix{n,k}=[]; end end end end % Remove the nuclei that are not coupled to the electron if (nargin==4)&&isfield(options,'purge')&&strcmp(options.purge,'on') killing_pattern=cellfun(@isempty,inter.coupling.matrix(:,nspins)); killing_pattern(end)=0; inter.coupling.matrix(:,killing_pattern)=[]; inter.coupling.matrix(killing_pattern,:)=[]; inter.zeeman.matrix(killing_pattern)=[]; sys.isotopes(killing_pattern)=[]; end % NMR parameterization case 0 % Reference to bare nuclei if the user did not supply any reference values if (nargin<3)||(~any(references)), references=zeros(size(particles)); end % Absorb Zeeman tensors if isfield(props,'cst') inter.zeeman.matrix=cell(1,nspins); for n=1:nspins inter.zeeman.matrix{n}=-props.cst{index(n)}+eye(3)*references(ref_index(n)); end end % Absorb quadrupolar couplings if isfield(props,'nqi') inter.coupling.matrix=cell(nspins,nspins); for n=1:nspins inter.coupling.matrix{n,n}=props.nqi{index(n)}; end end % Absorb spin-rotation couplings if isfield(props,'src') inter.spinrot.matrix=cell(nspins); for n=1:nspins inter.spinrot.matrix{n}=props.src{index(n)}; end end % Absorb and prune scalar couplings if isfield(props,'j_couplings') inter.coupling.scalar=props.j_couplings(index,index)/2; if (nargin==4)&&isfield(options,'min_j') inter.coupling.scalar=inter.coupling.scalar.*(abs(inter.coupling.scalar)>options.min_j); end inter.coupling.scalar=num2cell(inter.coupling.scalar); end end end % Consistency enforcement function grumble(props,nuclei,references,options) %#ok<INUSD> if ~isstruct(props) error('the first argument must be a structure returned by gparse().'); end if ~iscell(nuclei) error('the second argument must have the form {{''H'',''1H''},{''C'',''13C''},...}'); end if (~isnumeric(references))||(numel(nuclei)~=numel(references)) error('references must be a numerical array with the same number of entries as nuclei.'); end end % ACHTUNG! ALLES LOOKENSPEEPERS % Das Computermachine ist nicht fur gefingerpoken und mittengrabben. % Ist easy schnappen der Springenwerk, blowenfusen und poppencorken % mit Spitzensparken. Ist nicht fur gewerken bei das Dumpkopfen. Die % rubbernecken Sichtseeren keepen Hands in die Pockets muss, relaxen % und watchen die Blinkenlichten.
github
tsajed/nmr-pred-master
nuclacid.m
.m
nmr-pred-master/spinach/etc/nuclacid.m
6,159
utf_8
2f294048b43c8779677853ea1a7f6d1e
% Nucleic acid data import function. % % <http://spindynamics.org/wiki/index.php?title=Nuclacid.m> function [sys,inter]=nuclacid(pdb_file,shift_file,options) % Check consistency grumble(pdb_file,shift_file,options); % Parse the PDB file [pdb_res_num,pdb_res_typ,pdb_atom_id,pdb_coords]=read_pdb_nuc(pdb_file); % Open the shift file file_id=fopen(shift_file,'r'); % Get the outputs started bmrb_res_num=[]; bmrb_atom_id={}; bmrb_chemsh={}; % Parse the shift file while ~feof(file_id) data_line=fgetl(file_id); if ~isempty(data_line) parsed_string=textscan(data_line,'%f %s %f','delimiter','\t','MultipleDelimsAsOne',1); if all(~cellfun(@isempty,parsed_string)) bmrb_res_num(end+1)=parsed_string{1}; %#ok<AGROW> bmrb_atom_id{end+1}=parsed_string{2}{1}; %#ok<AGROW> bmrb_chemsh{end+1}=parsed_string{3}; %#ok<AGROW> end end end % Make outputs column vectors bmrb_res_num=bmrb_res_num'; bmrb_atom_id=bmrb_atom_id'; bmrb_chemsh=bmrb_chemsh'; % Close the shift file fclose(file_id); % Remove oxygen, phosphorus and the exchangeable protons kill_mask=ismember(pdb_atom_id,{'O5''','O4''','O4','O6','O2','O2''','O3''','O1P','O2P','P','H2''','H5T','HO''2'}); pdb_res_num(kill_mask)=[]; pdb_atom_id(kill_mask)=[]; pdb_res_typ(kill_mask)=[]; pdb_coords(kill_mask)=[]; disp('WARNING: oxygen atoms will not appear in the simulation.'); % Match chemical shifts pdb_chemsh=cell(numel(pdb_atom_id),1); disp(' '); disp('############# CHEMICAL SHIFT IMPORT SUMMARY ###############'); for n=1:numel(pdb_atom_id) % Pull the current amino acid from BMRB select_mask=(bmrb_res_num==pdb_res_num(n)); bmrb_atoms=bmrb_atom_id(select_mask); bmrb_shifts=bmrb_chemsh(select_mask); % Match PDB and BMRB data if ismember(pdb_atom_id{n},bmrb_atoms) pdb_chemsh{n}=bmrb_shifts(strcmp(pdb_atom_id{n},bmrb_atoms)); pdb_chemsh{n}=pdb_chemsh{n}{1}; disp(['Imported chemical shift for ' pad([pdb_res_typ{n} '(' num2str(pdb_res_num(n)) '):' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); end end % Replace primes with 'p' symbols for convenience for n=1:numel(pdb_atom_id) pdb_atom_id{n}=strrep(pdb_atom_id{n},'''','p'); end % Estimate J-couplings scalar_couplings=guess_j_nuc(pdb_res_num,pdb_res_typ,pdb_atom_id,pdb_coords); % CSA estimation goes here % Assign isotopes and labels isotopes=cell(1,numel(pdb_atom_id)); for n=1:numel(pdb_atom_id) switch pdb_atom_id{n}(1) case 'H' isotopes{n}='1H'; case 'C' isotopes{n}='13C'; case 'N' isotopes{n}='15N'; case 'P' isotopes{n}='31P'; otherwise error('unknown atom type.'); end end % Find missing chemical shifts missing_shifts=find(cellfun(@isempty,pdb_chemsh))'; disp(' '); disp('############# SUMMARY OF MISSING ASSIGNMENTS ###############'); % Process unassigned chemical shifts subset=true(size(pdb_atom_id)); if strcmp(options.noshift,'keep') % Put unassigned spins between -1.0 and 0.0 ppm erzatz_shifts=linspace(-1,0,numel(missing_shifts)); for n=1:numel(missing_shifts) disp(['Missing assignment of ' pdb_res_typ{missing_shifts(n)} '(' num2str(pdb_res_num(missing_shifts(n)))... ')-' pdb_atom_id{missing_shifts(n)} ': the spin is placed at ' num2str(erzatz_shifts(n)) ' ppm.']); pdb_chemsh{missing_shifts(n)}=erzatz_shifts(n); end elseif strcmp(options.noshift,'delete') % Delete unassigned spins for n=missing_shifts disp(['Missing assignment of ' pdb_res_typ{n} '(' num2str(pdb_res_num(n)) ')-' pdb_atom_id{n} ... ': the atom will not appear in the simulation.']); end subset=subset&(~cellfun(@isempty,pdb_chemsh)); else % Complain and bomb out error('incorrect value of options.noshift parameter.'); end % Apply the selection sys.isotopes=isotopes(subset); inter.zeeman.scalar=pdb_chemsh(subset)'; inter.coupling.scalar=scalar_couplings(subset,subset); inter.coordinates=pdb_coords(subset); % Write detailed labels pdb_atom_id=pdb_atom_id(subset); pdb_res_num=pdb_res_num(subset); pdb_res_typ=pdb_res_typ(subset); sys.labels=cell(1,numel(pdb_atom_id)); for n=1:numel(pdb_atom_id) sys.labels{n}=[pdb_res_typ{n} '(' num2str(pdb_res_num(n)) '):' pdb_atom_id{n}]; end % Deuterate the atoms from the list supplied disp(' '); disp('############# SUMMARY OF ISOTOPE REASSIGNMENTS ###############'); for n=1:numel(sys.labels) if ismember([pdb_res_typ{n} ':' pdb_atom_id{n}],options.deut_list) if ~strcmp(sys.isotopes{n},'1H') error('the particle you are trying to deuterate is not a proton.'); else sys.isotopes{n}='2H'; disp(['Isotope type for ' sys.labels{n} ' changed to deuterium, J-coupling guess modified accordingly.']); inter.coupling.scalar(n,:)=inter.coupling.scalar(n,:)*(spin('2H')/spin('1H')); inter.coupling.scalar(:,n)=inter.coupling.scalar(:,n)*(spin('2H')/spin('1H')); end end end end % Consistency enforcement function grumble(pdb_file,shift_file,options) if ~ischar(pdb_file) error('pdb_file must be a character string specifying a file name.'); end if ~ischar(shift_file) error('shift_file must be a character string specifying a file name.'); end if ~isfield(options,'noshift') error('options.noshift switch must be specfied.'); elseif ~ischar(options.noshift) error('options.noshift must be a character string.'); elseif ~ismember(options.noshift,{'keep','delete'}) error('invalid value for options.noshift, please refer to the manual.'); end if ~isfield(options,'deut_list') error('options.deut_list must be supplied.'); elseif ~iscell(options.deut_list) error('options.deut_list must be a cell array of character strings.'); end end % All money is a matter of belief. % % Adam Smith
github
tsajed/nmr-pred-master
karplus_fit.m
.m
nmr-pred-master/spinach/etc/karplus_fit.m
2,163
utf_8
88a96f6fa5b27b83469c881f014c0b4f
% Fits a Karplus curve to a Gaussian dihedral angle scan. % % <http://spindynamics.org/wiki/index.php?title=Karplus_fit.m> function [A,B,C]=karplus_fit(dir_path,atoms) % Get all log files in the directory logfiles=dir([dir_path '/*.log']); % Get the arrays going phi=[]; J=[]; E=[]; % Extract parameters for n=1:numel(logfiles) try props=gparse([dir_path '/' logfiles(n).name]); current_phi=dihedral(props.std_geom(atoms(1),:),props.std_geom(atoms(2),:),... props.std_geom(atoms(3),:),props.std_geom(atoms(4),:)); current_j=props.j_couplings(atoms(1),atoms(4)); phi=[phi current_phi]; J=[J current_j]; E=[E props.energy]; %#ok<AGROW> catch disp(['Gaussian log file ' logfiles(n).name ' could not be interpreted, skipped.']); end end % Rotate phi into [0,360] phi=mod(phi,360); % Compute basis cosines cosine_2=cosd(phi).^2; cosine_1=cosd(phi); cosine_0=ones(size(phi)); % Run linear least squares result=[cosine_2' cosine_1' cosine_0']\J'; % Write the answer A=result(1); B=result(2); C=result(3); % Plot Karplus curve figure(); subplot(2,1,1); plot(phi,J,'ro'); psi=linspace(0,360,128); hold on; plot(psi,A*cosd(psi).^2+B*cosd(psi)+C,'b-'); xlabel('Dihedral angle, degrees'); ylabel('J-coupling, Hz'); axis tight; % Plot probability histogram E=hartree2joule(E); E=E-min(E(:)); P=exp(-E/(8.31*298)); P=P/sum(P); [phi,order]=sort(phi); subplot(2,1,2); stairs(phi,P(order)); xlabel('Dihedral angle, degrees'); ylabel('Probability at 298 K'); axis tight; end % If men learn this, it will implant forgetfulness in their souls; they will % cease to exercise memory because they rely on that which is written [...] % it is no true wisdom that you offer your disciples, but only its semblance, % for by telling them of many things without teaching them you will make them % seem to know much, while for the most part they know nothing, and as men % filled, not with wisdom but with the conceit of wisdom, they will be a bur- % den to their fellows. % % Plato (circa 429-347 BCE), about reading and writing.
github
tsajed/nmr-pred-master
guess_j_nuc.m
.m
nmr-pred-master/spinach/etc/guess_j_nuc.m
22,317
utf_8
f8b937a6d65affdaed2c42d5e0fa4f31
% Assigns J-couplings from literature values and Karplus curves. % % <http://spindynamics.org/wiki/index.php?title=Guess_j_nuc.m> function jmatrix=guess_j_nuc(nuc_num,nuc_typ,pdb_id,coords) % Check consistency grumble(nuc_num,nuc_typ,pdb_id,coords); % Preallocate the answer jmatrix=cell(numel(coords),numel(coords)); % Number the atoms numbers=1:numel(coords); % Determine the connectivity graph proxmatrix=false(numel(coords),numel(coords)); for n=1:numel(coords) for k=1:numel(coords) if (norm(coords{n}-coords{k},2)<1.55), proxmatrix(n,k)=1; end end end % Get all connected subgraphs up to size 2 subgraphs=dfpt(sparse(proxmatrix),2); % Set generic coupling values J_NH=86.0; J_CN=20.0; J_CH=180.0; J_CC=65.0; % Spec all ordered connected pairs pairs_database={... % RNA specific values from the literature 'C1p_N9' , 11.0; 'C1p_N1' , 12.0; 'H_N1' , 95.0; 'H3_N3' , 91.0; 'C6_N1' , 7.5; 'C4_N3' , 10.7; 'C4_C5' , 65.0; 'C5_H5' , 176; 'C8_H8' , 216.0; 'C6_H6' , 185.0; 'C5_C6' , 67.0; 'C2_N3' , 19.0; 'C2_N1' , 19.0; 'C4_N9' , 20.0; 'H41_N4' , 86.0; 'C4_N4' , 20.0; 'C8_N9' , 11.0; 'C1p_H1p' , 170.0; 'C_C5' , 55.0; 'H42_N4' , 86.0; % Generics for the conjugated ring (to be replaced with DFT values - Zenawi) 'C2_H2' , J_CH; 'C5_N7' , J_CN; 'C8_N7' , J_CN; 'C6_N6' , J_CN; 'H61_N6' , J_NH; 'H62_N6' , J_NH; 'C2_N2' , J_CN; 'H21_N2' , J_NH; 'H1_N1' , J_NH; 'H22_N2' , J_NH; 'H61_N1' , J_NH; % Generics for the sugar ring (to be replaced with DFT values - Zenawi) 'C1p_C2p' , J_CC; 'C2p_H2p' , J_CH; 'C3p_C4p' , J_CC; 'C4p_H4p' , J_CH; 'C4p_C5p' , J_CC; 'C5p_H5p' , J_CH; 'C5p_H5pp' , J_CH; 'C2p_C3p' , J_CC; 'C3p_H3p' , J_CH; 'C2p_H2pp' , J_CH; 'C2p_H2p1' , J_CH; 'C5p_H5p2' , J_CH 'C5p_H5p1' , J_CH}; % Loop over subgraphs disp(' '); disp('############# ONE-BOND J-COUPLING SUMMARY ###############'); for n=1:size(subgraphs,1) % Extract labels, residues and numbers spin_labels=pdb_id(subgraphs(n,:)); spin_numbers=numbers(subgraphs(n,:)); spin_resnames=nuc_typ(subgraphs(n,:)); spin_resnums=nuc_num(subgraphs(n,:)); % Index the spins [spin_labels,index]=sort(spin_labels); spin_numbers=spin_numbers(index); spin_resnames=spin_resnames(index); spin_resnums=spin_resnums(index); % Consult the database if numel(spin_labels)==1 % Inform the user about solitary spins disp(['WARNING: solitary spin detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}]); else % Build specification string spec_string=pairs_database(strcmp([spin_labels{1} '_' spin_labels{2}],pairs_database(:,1)),:); % Assign the coupling if isempty(spec_string) % Complain if nothing found disp(['WARNING: unknown atom pair or unphysical proximity, ' spin_labels{1} '_' spin_labels{2} ' in residues ' spin_resnames{1}... '(' num2str(spin_resnums(1)) '), ' spin_resnames{2} '(' num2str(spin_resnums(2)) ')']); elseif size(spec_string,1)>1 % Complain if multiple records found error([spec_string{1} ' coupling has been specified multiple times in the coupling database.']); else % Write the array jmatrix{spin_numbers(1),spin_numbers(2)}=spec_string{2}; % Report to the user disp(['Estimated one-bond J-coupling from ' pad([spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}],19) ' to ' ... pad([spin_resnames{2} '(' num2str(spin_resnums(2)) '):' spin_labels{2}],19) ' ' ... pad(num2str(spec_string{2},'%5.1f'),6,'left') ' Hz']); end end end % Get all connected subgraphs up to size 3 subgraphs=dfpt(sparse(proxmatrix),3); % Set generic coupling values J_CCC=-1.2; % Zenawi's DFT J_CCH=0; % Literature reference J_CCN=7.0; % Zenawi's DFT J_NCN=0; % Literature reference J_NCH=0; % Literature reference J_CNH=0; % Literature reference J_CNC=0; % Literature reference J_HCH=-12.0; % Typical for CH2 J_HNH=-10.0; % Typical for NH2 % Spec all ordered connected triples (sorted atoms, bonding order, coupling from atom 1 to atom 3) triples_database={... % Backbone data from the literature 'C4p_C5p_H5p' 1, 2, 3, -5.5; 'C4p_C5p_H5pp' 1, 2, 3, 2.0; 'C4p_C5p_H4p' 3, 1, 2, -5.5; 'C2p_C3p_H3p' 1, 2, 3, -2.3; 'C2p_C3p_H2p' 3, 2, 1, 2.3; % Conjugated ring data from the literature 'C4_C5_C6' 1, 2, 3, 9.5; 'C4_C8_N9' 1, 3, 2, 8.0; 'C2_C4_N3' 1, 3, 2, 10.0; 'C8_H8_N9' 2, 1, 3, 8.0; 'C8_H8_N7' 2, 1, 3, 11.0; 'C2_H2_N1' 2, 1, 3, 15.0; 'C2_H2_N3' 2, 1, 3, 15.0; % Generic numbers for the conjugated ring (to be replaced with DFT values - Zenawi) 'C6_N1_N6' 2, 1, 3, J_NCN; 'C2_N1_N3' 2, 1, 3, J_NCN; 'C2_C6_N1' 1, 3, 2, J_CNC; 'C4_C5_N3' 2, 1, 3, J_CCN; 'C4_N3_N9' 2, 1, 3, J_NCN; 'C1p_C4_N9' 1, 3, 2, J_CNC; 'C4_C5_N9' 2, 1, 3, J_CCN; 'C5_C6_N6' 1, 2, 3, J_CCN; 'C5_C8_N7' 1, 3, 2, J_CNC; 'C4_C5_N7' 1, 2, 3, J_CCN; 'C5_C6_N7' 2, 1, 3, J_CCN; 'C6_H61_N6' 1, 3, 2, J_CNH; 'C6_H62_N6' 1, 3, 2, J_CNH; 'C8_N7_N9' 2, 1, 3, J_NCN; 'C1p_C8_N9' 2, 3, 1, J_CNC; 'C2_N1_N2' 2, 1, 3, J_NCN; 'C2_H1_N1' 1, 3, 2, J_CNH; 'C2_H21_N2' 1, 3, 2, J_CNH; 'C2_H22_N2' 1, 3, 2, J_CNH; 'C2_N2_N3' 3, 1, 2, J_NCN; 'C6_H1_N1' 1, 3, 2, J_CNH; 'C5_C6_N1' 2, 1, 3, J_CCN; 'C6_H6_N1' 3, 1, 2, J_NCH; 'C1p_C2_N1' 2, 3, 1, J_CNC; 'C4_N3_N4' 2, 1, 3, J_NCN; 'C4_H41_N4' 1, 3, 2, J_CNH; 'C4_H42_N4' 1, 3, 2, J_CNH; 'C4_C5_N4' 2, 1, 3, J_CCN; 'C5_C6_H6' 1, 2, 3, J_CCH; 'C1p_C6_N1' 2, 3, 1, J_CNC; 'C5_C6_H5' 2, 1, 3, J_CCH; 'C2_H3_N3' 1, 3, 2, J_CNH; 'C4_H3_N3' 1, 3, 2, J_CNH; 'C4_C5_H5' 1, 2, 3, J_CCH; 'C1p_H1p_N9' 2, 1, 3, J_NCH; 'C1p_C2p_N9' 2, 1, 3, J_CCN; 'H21_H22_N2' 1, 3, 2, J_HNH; 'C1p_H1p_N1' 2, 1, 3, J_NCH; 'C1p_C2p_N1' 2, 1, 3, J_CCN; 'H41_H42_N4' 1, 3, 2, J_HNH; 'H61_H62_N6' 1, 3, 2, J_HNH; % Generic numbers for the backbone (to be replaced with DFT values - Zenawi) 'C1p_C2p_C3p' 1, 2, 3, J_CCC; 'C1p_C2p_H2p' 1, 2, 3, J_CCH; 'C2p_C3p_C4p' 1, 2, 3, J_CCC; 'C3p_C4p_H4p' 3, 1, 2, J_CCH; 'C3p_C4p_C5p' 1, 2, 3, J_CCC; 'C2p_C3p_H2p' 1, 2, 3, J_CCH; 'C3p_C4p_H3p' 2, 1, 3, J_CCH; 'C5p_H5p_H5pp' 2, 1, 3, J_HCH; 'C1p_C2p_H1p' 3, 1, 2, J_CCH; 'C1p_C2p_H2pp' 3, 2, 1, J_CCH; 'C2p_C3p_H2pp' 3, 1, 2, J_CCH; 'C2p_C3p_H2p1' 1, 2, 3, J_CCH; 'C1p_C2p_H2p1' 1, 2, 3, J_CCH; 'C4p_C5p_H5p2' 1, 2, 3, J_CCH; 'C4p_C5p_H5p1' 1, 2, 3, J_CCH; 'C5p_H5p1_H5p2' 2, 1, 3, J_HCH}; % Exception list for four-membered rings allowed_collision_list={}; % Loop over subgraphs disp(' '); disp('############# TWO-BOND J-COUPLING SUMMARY ###############'); for n=1:size(subgraphs,1) % Extract labels, residues and numbers spin_labels=pdb_id(subgraphs(n,:)); spin_numbers=numbers(subgraphs(n,:)); spin_resnames=nuc_typ(subgraphs(n,:)); spin_resnums=nuc_num(subgraphs(n,:)); % Index the spins [spin_labels,index]=sort(spin_labels); spin_numbers=spin_numbers(index); spin_resnames=spin_resnames(index); spin_resnums=spin_resnums(index); % Consult the database if numel(spin_labels)==1 % Inform the user about solitary spins disp(['WARNING: solitary spin detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}]); elseif numel(spin_labels)==2 % Inform the user about isolated pairs disp(['WARNING: isolated spin pair detected, ' spin_resnames{1} ':' spin_labels{1} ' and ' spin_resnames{2} ':' spin_labels{2}]); else % Build the specification string spec_string=triples_database(strcmp([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3}],triples_database(:,1)),:); % Assign the coupling if isempty(spec_string) % Inform the user about missing data disp(['WARNING: unknown atom triple or unphysical proximity, ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} ' in residues '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) ')']); elseif size(spec_string,1)>1 % Complain if multiple records found error([spec_string{1} ' coupling has been specified multiple times in the coupling database.']); else % Extract spin numbers spin_a=spin_numbers(spec_string{2}); spin_b=spin_numbers(spec_string{3}); spin_c=spin_numbers(spec_string{4}); % Match bonding pattern if proxmatrix(spin_a,spin_b)&&proxmatrix(spin_b,spin_c) % Check for collisions if (~isempty(jmatrix{spin_a,spin_c}))&&(~ismember([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3}],allowed_collision_list)) % Complain and bomb out error(['Atom triple: ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} ' in amino acids '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) ' collides with other data.']); else % Write the array jmatrix{spin_a,spin_c}=spec_string{5}; end % Inform the user disp(['Estimated two-bond J-coupling from ' pad([nuc_typ{spin_a} '(' num2str(nuc_num(spin_a)) '):' pdb_id{spin_a}],19) ' to '... pad([nuc_typ{spin_c} '(' num2str(nuc_num(spin_c)) '):' pdb_id{spin_c}],19) ' '... pad(num2str(jmatrix{spin_a,spin_c},'%5.1f'),6,'left') ' Hz']); end end end end % Get all connected subgraphs up to size 4 subgraphs=dfpt(sparse(proxmatrix),4); % Remove T-shaped subgraphs kill_mask=false(size(subgraphs,1),1); for n=1:size(subgraphs,1) if any(sum(proxmatrix(subgraphs(n,:),subgraphs(n,:)))==4) kill_mask(n)=true(); end end subgraphs(kill_mask,:)=[]; % List of ordered connected quads (sorted atoms, bonding order, Karplus coefficients) quads_database={... 'C3p_C4p_C5p_H5p', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C4p_C5p_H4p_H5p', 4, 2, 1, 3, [0.0 0.0 10.42]; 'C3p_C4p_C5p_H5pp', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C4p_C5p_H4p_H5pp', 4, 2, 1, 3, [0.0 0.0 8.51]; 'C1p_C8_H8_N9', 1, 4, 2, 3, [0.0 0.0 0.0]; 'C1p_C8_N7_N9', 1, 4, 2, 3, [0.0 0.0 0.0]; 'C4_C8_H8_N9', 1, 4, 2, 3, [0.0 0.0 0.0]; 'C5_C8_N7_N9', 4, 2, 3, 1, [0.0 0.0 0.0]; 'C4_C5_C8_N7', 3, 4, 2, 1, [0.0 0.0 0.0]; 'C5_C6_C8_N7', 3, 4, 1, 2, [0.0 0.0 9.00]; 'C5_C6_N6_N7', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C5_C6_N1_N7', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C4_C5_C6_N6', 1, 2, 3, 4, [0.0 0.0 0.0]; 'C4_C5_C6_N1', 1, 2, 3, 4, [0.0 0.0 0.0]; 'C5_C6_H61_N6', 1, 2, 4, 3, [0.0 0.0 0.0]; 'C5_C6_H62_N6', 1, 2, 4, 3, [0.0 0.0 0.0]; 'C6_H61_N1_N6', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C6_H62_N1_N6', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C2_C6_N1_N6', 1, 3, 2, 4, [0.0 0.0 0.0]; 'C2_C6_N1_N3', 4, 1, 3, 2, [0.0 0.0 0.0]; 'C2_C4_H2_N3', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C2_C6_H2_N1', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C2_C4_C5_N3', 3, 2, 4, 1, [0.0 0.0 0.0]; 'C2_C4_N3_N9', 4, 2, 3, 1, [0.0 0.0 0.0]; 'C4_C5_C6_N3', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C4_C5_N3_N7', 4, 2, 1, 3, [0.0 0.0 0.0]; 'C4_C5_C6_N9', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C4_C8_N3_N9', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C2_C5_C6_N1', 1, 4, 3, 2, [0.0 0.0 0.0]; 'C5_C6_H1_N1', 3, 4, 2, 1, [0.0 0.0 0.0]; 'C2_C6_N1_N2', 4, 1, 3, 2, [0.0 0.0 0.0]; 'C2_H1_N1_N2', 4, 1, 3, 2, [0.0 0.0 0.0]; 'C2_H1_N1_N3', 4, 1, 3, 2, [0.0 0.0 0.0]; 'C2_H21_N2_N3', 4, 1, 3, 2, [0.0 0.0 0.0]; 'C2_H21_N1_N2', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C2_H22_N2_N1', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C2_C4_N2_N3', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C1p_C4_C5_N9', 3, 2, 4, 1, [0.0 0.0 0.0]; 'C1p_C4_N3_N9', 3, 2, 4, 1, [0.0 0.0 0.0]; 'C1p_C5_C6_N1', 1, 4, 3, 2, [0.0 0.0 0.0]; 'C2_C6_H6_N1', 1, 4, 2, 3, [0.0 0.0 0.0]; 'C5_C6_H5_N1', 4, 2, 1, 3, [0.0 0.0 0.0]; 'C4_C5_C6_H6', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C5_C6_H5_H6', 4, 2, 1, 3, [0.0 0.0 7.00]; 'C4_C5_C6_N4', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C4_C5_H5_N3', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C4_C5_H5_N4', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C2_H22_N2_N3', 4, 1, 3, 2, [0.0 0.0 0.0]; 'C4_C5_H41_N4', 2, 1, 4, 3, [0.0 0.0 0.0]; 'C4_C5_H42_N4', 2, 1, 4, 3, [0.0 0.0 0.0]; 'C4_H41_N3_N4', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C4_H42_N3_N4', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C2_C4_N3_N4', 4, 2, 3, 1, [0.0 0.0 0.0]; 'C1p_C2_N1_N3', 4, 2, 3, 1, [0.0 0.0 0.0]; 'C1p_C6_H6_N1', 1, 4, 2, 3, [0.0 0.0 0.0]; 'C4_C5_H3_N3', 2, 1, 4, 3, [0.0 0.0 0.0]; 'C2_H3_N1_N3', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C5_C8_H8_N7', 3, 2, 4, 1, [0.0 0.0 0.0]; 'C1p_C2p_H2p_N1', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C1p_C2p_H2p_N9', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C1p_C2p_C3p_N1', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C1p_C2p_C3p_N9', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C2p_C3p_C4p_C5p', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C3p_C4p_H3p_H4p', 4, 2, 1, 3, [0.0 0.0 5.79]; 'C2p_C3p_C4p_H4p', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C3p_C4p_C5p_H3p', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C1p_C2p_C3p_C4p', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C2p_C3p_H2p_H3p', 4, 2, 1, 3, [0.0 0.0 0.0]; 'C1p_C2p_C3p_H3p', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C2p_C3p_C4p_H2p', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C2p_C3p_H2pp_H3p', 3, 1, 2, 4, [0.0 0.0 5.82]; 'C2_C4_N1_N3', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C1p_C2p_H2pp_N1', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C1p_C2_C2p_N1', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C1p_C2p_C6_N1', 3, 4, 1, 2, [0.0 0.0 0.0]; 'C1p_C2p_C3p_H1p', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C1p_C2p_H1p_H2pp', 3, 1, 2, 4, [0.0 0.0 4.05]; 'C1p_C2_H1p_N1', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C1p_C6_H1p_N1', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C2p_C3p_C4p_H2pp', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C2_H22_N1_N2', 3, 1, 4, 2, [0.0 0.0 0.0]; 'C4_C5_C8_N9', 3, 4, 1, 2, [0.0 0.0 0.0]; 'C4_C5_N7_N9', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C1p_C2p_H2pp_N9', 4, 1, 2, 3, [0.0 0.0 0.0]; 'C1p_C2p_C8_N9', 3, 4, 1, 2, [0.0 0.0 0.0]; 'C1p_C2p_C4_N9', 3, 4, 1, 2, [0.0 0.0 0.0]; 'C1p_C8_H1p_N9', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C1p_C4_H1p_N9', 2, 4, 1, 3, [0.0 0.0 0.0]; 'C4_C8_N7_N9', 3, 2, 4, 1, [0.0 0.0 0.0]; 'C2p_C3p_H2p1_H3p', 4, 2, 1, 3, [0.0 0.0 0.0]; 'C1p_C2p_H2p1_N1', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C1p_C2p_H1p_H2p1' 3, 1, 2, 4, [0.0 0.0 4.05]; 'C2p_C3p_C4p_H2p1', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C3p_C4p_C5p_H5p2', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C3p_C4p_C5p_H5p1', 4, 3, 2, 1, [0.0 0.0 0.0]; 'C4p_C5p_H4p_H5p2', 4, 2, 1, 3, [0.0 0.0 10.42]; 'C1p_C2p_H2p1_N9', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C4p_C5p_H4p_H5p1', 4, 2, 1, 3, [0.0 0.0 10.42]; }; % Exception list for five-membered rings allowed_collision_list={'C4_C5_C6_N1','C4_C5_N7_N9','C1p_C4_H1p_N9'}; % Loop over subgraphs disp(' '); disp('############# THREE-BOND J-COUPLING SUMMARY ###############'); for n=1:size(subgraphs,1) % Extract labels, residues and numbers spin_labels=pdb_id(subgraphs(n,:)); spin_numbers=numbers(subgraphs(n,:)); spin_resnames=nuc_typ(subgraphs(n,:)); spin_resnums=nuc_num(subgraphs(n,:)); % Index the spins [spin_labels,index]=sort(spin_labels); spin_numbers=spin_numbers(index); spin_resnames=spin_resnames(index); spin_resnums=spin_resnums(index); % Consult the database if numel(spin_labels)==1 % Inform the user if no J-coupling found disp(['WARNING: solitary spin detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}]); elseif numel(spin_labels)==2 % Inform the user if no J-coupling found disp(['WARNING: isolated spin pair detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1} ' and ' ... spin_resnames{2} '(' num2str(spin_resnums(2)) '):' spin_labels{2}]); elseif numel(spin_labels)==3 % Inform the user if no J-coupling found disp(['WARNING: isolated spin triad detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1} ', '... spin_resnames{2} '(' num2str(spin_resnums(2)) '):' spin_labels{2} ' and '... spin_resnames{3} '(' num2str(spin_resnums(3)) '):' spin_labels{3}]); else % Assemble specifiction string spec_string=quads_database(strcmp([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4}],quads_database(:,1)),:); % Complain if nothing found if isempty(spec_string) disp(['WARNING: unknown atom quad or unphysical proximity, ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4} ' in residues '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) '), '... spin_resnames{4} '(' num2str(spin_resnums(4)) ')']); elseif size(spec_string,1)>1 % Complain if multiple records found error([spec_string{1} ' coupling has been specified multiple times in the coupling database.']); else % Extract spin numbers spin_a=spin_numbers(spec_string{2}); spin_b=spin_numbers(spec_string{3}); spin_c=spin_numbers(spec_string{4}); spin_d=spin_numbers(spec_string{5}); % Get Karplus coefficients A=spec_string{6}(1); B=spec_string{6}(2); C=spec_string{6}(3); % Get dihedral angle theta=dihedral(coords{spin_a},coords{spin_b},coords{spin_c},coords{spin_d}); % Assign the J-coupling if (~isempty(jmatrix{spin_a,spin_d}))&&(~ismember([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4}],allowed_collision_list)) % Complain and bomb out error(['atom quad: ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4} ' in residues '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) '), '... spin_resnames{4} '(' num2str(spin_resnums(4)) ') collides with other data.']); else % Write the array jmatrix{spin_a,spin_d}=A*cosd(theta)^2+B*cosd(theta)+C; % Inform the user disp(['Estimated three-bond J-coupling from ' pad([nuc_typ{spin_a} '(' num2str(nuc_num(spin_a)) '):' pdb_id{spin_a}],19) ' to '... pad([nuc_typ{spin_d} '(' num2str(nuc_num(spin_d)) '):' pdb_id{spin_d}],19) ' ' pad(num2str(jmatrix{spin_a,spin_d},'%5.1f'),6,'left') ' Hz']); end end end end end % Consistency enforcement function grumble(nuc_num,nuc_typ,pdb_id,coords) if ~isnumeric(nuc_num) error('nuc_num must be a vector of positive integers.'); end if ~iscell(nuc_typ) error('nuc_typ must be a cell array of strings.'); end if ~iscell(pdb_id) error('pdb_id must be a cell array of strings.'); end if ~iscell(coords) error('coords must be a cell array of 3-vectors.'); end if (numel(nuc_num)~=numel(nuc_typ))||... (numel(nuc_typ)~=numel(pdb_id))||... (numel(pdb_id)~=numel(coords)) error('all four inputs must have the same number of elements.'); end end % It's a terrible thing, I think, in life to wait until you are % ready. I have this feeling that actually no one is ever ready % to do anything. There is almost no such thing as ready. There % is only now. % % Hugh Laurie
github
tsajed/nmr-pred-master
read_bmrb.m
.m
nmr-pred-master/spinach/etc/read_bmrb.m
1,506
utf_8
9db070c1569393233d092fcb8cb1e771
% This function reads BMRB files. % % <http://spindynamics.org/wiki/index.php?title=Read_bmrb.m> function [aa_num,aa_typ,pdb_id,chemsh]=read_bmrb(bmrb_file_name) % Check consistency grumble(bmrb_file_name); % Open the BMRB file file_id=fopen(bmrb_file_name,'r'); % Get the outputs started aa_num=[]; aa_typ={}; pdb_id={}; chemsh=[]; % Parse the BMRB file while ~feof(file_id) data_line=fgetl(file_id); if ~isempty(data_line) parsed_string=textscan(data_line,'%f %f %s %s %s %f %f %f','delimiter',' ','MultipleDelimsAsOne',1); if all(~cellfun(@isempty,parsed_string)) aa_num(end+1)=parsed_string{2}; %#ok<AGROW> aa_typ{end+1}=parsed_string{3}{1}; %#ok<AGROW> pdb_id{end+1}=parsed_string{4}{1}; %#ok<AGROW> chemsh(end+1)=parsed_string{6}; %#ok<AGROW> end end end % Capitalize amino acid type specifications for n=1:numel(aa_typ) aa_typ{n}=upper(aa_typ{n}); %#ok<AGROW> end % Make outputs column vectors aa_num=aa_num'; aa_typ=aa_typ'; pdb_id=pdb_id'; chemsh=chemsh'; % Close the BMRB file fclose(file_id); % Check for empty returns if isempty(chemsh) error('BMRB file could not be parsed - the data format is not canonical.'); end end % Consistency enforcement function grumble(bmrb_file_name) if ~ischar(bmrb_file_name) error('bmrb_file_name must be a character string.'); end end % If it's not true, it's well invented. % % Dante
github
tsajed/nmr-pred-master
gparse.m
.m
nmr-pred-master/spinach/etc/gparse.m
11,883
utf_8
40b0d3197608f1798482b3597c8a2952
% A parser for Gaussian03 and Gaussian09 calculation logs. % % <http://spindynamics.org/wiki/index.php?title=Gparse.m> function props=gparse(filename,options) % Read the file file_id=fopen(filename,'r'); g03_output=textscan(file_id,'%s','delimiter','\n'); fclose(file_id); g03_output=g03_output{1}; % Deblank all lines for n=1:numel(g03_output), g03_output(n)=deblank(g03_output(n)); end % Refuse to process files without #p option for n=1:numel(g03_output) current_line=char(g03_output(n)); if (numel(current_line)>=2)&&strcmp(current_line(1:2),'# ') error('This Gaussian log has the detailed printing option switched off. Re-run with #p in the route line.'); end end % Set the default error flag props.error=0; % Set the default complete flag props.complete=0; % Parse the file for n=1:length(g03_output) % Read the input orientation and atomic numbers if strcmp(g03_output(n),'Input orientation:') k=n+5; m=1; while ~strcmp(deblank(g03_output(k)),'---------------------------------------------------------------------') S=eval(['[' char(g03_output(k)) ']']); atoms(m,:)=S(4:6); atomic_numbers(m)=S(2); k=k+1; m=m+1; %#ok<AGROW> end natoms=m-1; props.inp_geom=atoms; props.natoms=natoms; disp('Gaussian import: found input orientation.'); end % Read the standard orientation and atomic numbers if strcmp(g03_output(n),'Standard orientation:') k=n+5; m=1; while ~strcmp(deblank(g03_output(k)),'---------------------------------------------------------------------') S=eval(['[' char(g03_output(k)) ']']); atoms(m,:)=S(4:6); atomic_numbers(m)=S(2); k=k+1; m=m+1; end natoms=m-1; props.std_geom=atoms; props.natoms=natoms; disp('Gaussian import: found standard orientation.'); end % Read the SCF energy current_line=char(g03_output(n)); if length(current_line)>10 && strcmp(current_line(1:9),'SCF Done:') scan_data=textscan(current_line,'SCF Done: %s = %f','Delimiter',' ','MultipleDelimsAsOne',1); props.method=char(scan_data{1}); props.method=props.method(3:(end-1)); props.energy=scan_data{2}; disp('Gaussian import: found SCF energy.'); end % Read isotropic hyperfine couplings if strcmp(g03_output(n),'Isotropic Fermi Contact Couplings') props.hfc.iso=zeros(natoms,1); for k=1:natoms S=char(g03_output(n+1+k)); S=eval(['[' S(20:end) ']']); props.hfc.iso(k)=S(3); end disp('Gaussian import: found isotropic hyperfine couplings.'); end % Read and symmetrize anisotropic hyperfine couplings if strcmp(g03_output(n),'Anisotropic Spin Dipole Couplings in Principal Axis System') props.hfc.full.eigvals=cell(natoms,1); props.hfc.full.eigvecs=cell(natoms,1); props.hfc.full.matrix=cell(natoms,1); for k=1:natoms baa=g03_output(n+4*k+1); baa=char(baa); baa=eval(['[' baa(4:end) ']']); bbb=g03_output(n+4*k+2); bbb=char(bbb); bbb=eval(['[' bbb(15:end) ']']); bcc=g03_output(n+4*k+3); bcc=char(bcc); bcc=eval(['[' bcc(4:end) ']']); props.hfc.full.eigvals{k}=[baa(3) bbb(3) bcc(3)]+props.hfc.iso(k); props.hfc.full.eigvecs{k}=[baa(5:7)' bbb(5:7)' bcc(5:7)']; props.hfc.full.matrix{k}=props.hfc.full.eigvecs{k}*diag(props.hfc.full.eigvals{k})*props.hfc.full.eigvecs{k}'; if (~exist('options','var'))||(~ismember('hfc_nosymm',options)) props.hfc.full.matrix{k}=(props.hfc.full.matrix{k}+props.hfc.full.matrix{k}')/2; end end disp('Gaussian import: found anisotropic hyperfine couplings.'); end % Read and symmetrize the g-tensor (Gaussian03 for Unix) if strcmp(g03_output(n),'g tensor [g = g_e + g_RMC + g_DC + g_OZ/SOC]:') line1=char(deblank(g03_output(n+1))); line2=char(deblank(g03_output(n+2))); line3=char(deblank(g03_output(n+3))); g=eval(['[' line1(5:18) ' ' line1(26:39) ' ' line1(46:60) '; '... line2(5:18) ' ' line2(26:39) ' ' line2(46:60) '; '... line3(5:18) ' ' line3(26:39) ' ' line3(46:60) ']']); if (~exist('options','var'))||(~ismember('g_nosymm',options)) g=(g+g')/2; end [V,D]=eig(g); props.g_tensor.eigvecs=V; props.g_tensor.eigvals=diag(D)'; props.g_tensor.matrix=g; disp('Gaussian import: found g-tensor.'); end % Read and symmetrize the g-tensor (Gaussian03 for Windows) if strcmp(g03_output(n),'g tensor (ppm):') line1=char(deblank(g03_output(n+1))); line2=char(deblank(g03_output(n+2))); line3=char(deblank(g03_output(n+3))); g=eval(['[' line1(4:15) ' ' line1(23:35) ' ' line1(42:54) '; '... line2(4:15) ' ' line2(23:35) ' ' line2(42:54) '; '... line3(4:15) ' ' line3(23:35) ' ' line3(42:54) ']']); if (~exist('options','var'))||(~ismember('g_nosymm',options)) g=(g+g')/2; end [V,D]=eig(g); props.g_tensor.eigvecs=V; props.g_tensor.eigvals=diag(D)'; props.g_tensor.matrix=g; disp('Gaussian import: found g-tensor.'); end % Read and symmetrize chemical shielding tensors if strcmp(g03_output(n),'SCF GIAO Magnetic shielding tensor (ppm):')||strcmp(g03_output(n),'Magnetic shielding (ppm):') cst=cell(natoms,1); for k=1:natoms line1=char(g03_output(n+5*k-3)); line2=char(g03_output(n+5*k-2)); line3=char(g03_output(n+5*k-1)); cst{k}=[eval(['[' line1(4:14) ' ' line1(21:31) ' ' line1(38:48) ']']); eval(['[' line2(4:14) ' ' line2(21:31) ' ' line2(38:48) ']']); eval(['[' line3(4:14) ' ' line3(21:31) ' ' line3(38:48) ']'])]; if (~exist('options','var'))||(~ismember('cst_nosymm',options)) cst{k}=(cst{k}+cst{k}')/2; end end props.cst=cst; disp('Gaussian import: found chemical shielding tensors.'); end % Read scalar couplings if strcmp(g03_output(n),'Total nuclear spin-spin coupling J (Hz):') j_couplings=zeros(natoms,ceil(natoms/5)*5); for k=1:ceil(natoms/5) lines_to_read=natoms-(k-1)*5; current_block=zeros(natoms,5); for m=(n+2):(n+1+lines_to_read) current_line=eval(['[' char(g03_output(m)) ']']); current_block(current_line(1),1:(length(current_line)-1))=current_line(2:end); end j_couplings(:,(5*(k-1)+1):(5*k))=current_block; n=n+lines_to_read+1; %#ok<FXSET> end j_couplings=j_couplings(1:natoms,1:natoms); j_couplings=j_couplings+j_couplings'; props.j_couplings=j_couplings; disp('Gaussian import: found isotropic J-couplings.'); end % Read spin-rotation couplings if strcmp(g03_output(n),'nuclear spin - molecular rotation tensor [C] (MHz):') props.srt=cell(natoms,1); for k=1:natoms line3=char(g03_output(n+4*k)); line2=char(g03_output(n+4*k-1)); line1=char(g03_output(n+4*k-2)); line0=char(g03_output(n+4*k-3)); atom_num=regexp(line0,'^[0-9]*','match'); atom_num=eval(atom_num{1}); props.srt{atom_num}=[eval(['[' line1(4:14) ' ' line1(21:31) ' ' line1(38:48) ']']); eval(['[' line2(4:14) ' ' line2(21:31) ' ' line2(38:48) ']']); eval(['[' line3(4:14) ' ' line3(21:31) ' ' line3(38:48) ']'])]*1e6; if strcmp(g03_output(n+4*k+1),'Dipole moment (Debye):'), break; end if strcmp(g03_output(n+4*k+1),'Nuclear quadrupole coupling constants [Chi] (MHz):'), break; end end disp('Gaussian import: found nuclear spin-rotation tensors.'); end % Read quadrupole couplings and kill their trace if strcmp(g03_output(n),'Nuclear quadrupole coupling constants [Chi] (MHz):') props.nqi=cell(natoms,1); for k=1:natoms line3=char(g03_output(n+4*k)); line2=char(g03_output(n+4*k-1)); line1=char(g03_output(n+4*k-2)); line0=char(g03_output(n+4*k-3)); atom_num=regexp(line0,'^[0-9]*','match'); atom_num=eval(atom_num{1}); props.nqi{atom_num}=[eval(['[' line1(4:14) ' ' line1(21:31) ' ' line1(38:48) ']']); eval(['[' line2(4:14) ' ' line2(21:31) ' ' line2(38:48) ']']); eval(['[' line3(4:14) ' ' line3(21:31) ' ' line3(38:48) ']'])]*1e6; props.nqi{atom_num}=props.nqi{atom_num}-eye(3)*trace(props.nqi{atom_num})/3; if strcmp(g03_output(n+4*k+1),'Dipole moment (Debye):'), break; end end disp('Gaussian import: found nuclear quadrupole tensors.'); end % Read magnetic susceptibility tensor (GIAO) if strcmp(g03_output(n),'Magnetic susceptibility tensor (cgs-ppm):') line1=char(g03_output(n+1)); line2=char(g03_output(n+2)); line3=char(g03_output(n+3)); props.chi=[eval(['[' line1(4:19) ' ' line1(25:40) ' ' line1(46:end) ']']); eval(['[' line2(4:19) ' ' line2(25:40) ' ' line2(46:end) ']']); eval(['[' line3(4:19) ' ' line3(25:40) ' ' line3(46:end) ']'])]; props.chi=cgsppm2ang(props.chi); disp('Gaussian import: found magnetic susceptibility.'); end % Read magnetic susceptibility tensor (CSGT) if strcmp(g03_output(n),'Magnetic susceptibility (cgs-ppm):') line1=char(g03_output(n+2)); line2=char(g03_output(n+3)); line3=char(g03_output(n+4)); props.chi=[eval(['[' line1(4:14) ' ' line1(21:31) ' ' line1(38:48) ']']); eval(['[' line2(4:14) ' ' line2(21:31) ' ' line2(38:48) ']']); eval(['[' line3(4:14) ' ' line3(21:31) ' ' line3(38:48) ']'])]; props.chi=cgsppm2ang(props.chi); disp('Gaussian import: found magnetic susceptibility.'); end % Read Gibbs free energy if (numel(g03_output{n})>43)&&strcmp(g03_output{n}(1:43),'Sum of electronic and thermal Free Energies') props.gibbs=eval(g03_output{n}(45:end)); disp('Gaussian import: found Gibbs free energy.'); end % Check for error flags if (numel(g03_output{n})>17)&&strcmp(g03_output{n}(1:17),'Error termination') props.error=1; disp('Gaussian import: error message detected.'); end % Check for incomplete calculations if (numel(g03_output{n})>18)&&strcmp(g03_output{n}(1:18),'Normal termination') props.complete=1; end if (numel(g03_output{n})>24)&&strcmp(g03_output{n}(1:24),'Entering Gaussian System') props.complete=0; end end % Assign atomic symbols periodic_table={'H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar',... 'K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br',... 'Kr','Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te',... 'I','Xe','Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm',... 'Yb','Lu','Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn',... 'Fr','Ra','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr',... 'Rf','Db','Sg','Bh','Hs','Mt','Ds','Rg'}; if exist('atomic_numbers','var') props.symbols=periodic_table(atomic_numbers); props.atomic_numbers=atomic_numbers; end % Assign source information props.filename=filename; end % Moral indignation is jealousy with a halo. % % H.G. Wells
github
tsajed/nmr-pred-master
read_pdb_pro.m
.m
nmr-pred-master/spinach/etc/read_pdb_pro.m
2,872
utf_8
525d354869dff389bc59cb97e181f54f
% Reads protein PDB data. % % <http://spindynamics.org/wiki/index.php?title=Read_pdb_pro.m> function [aa_num,aa_typ,pdb_id,coords]=read_pdb_pro(pdb_file_name,instance) % Check consistency grumble(pdb_file_name,instance); % Open the PDB file file_id=fopen(pdb_file_name,'r'); % Scroll to the selected structure while ~feof(file_id) parsed_string=textscan(fgetl(file_id),'MODEL %d','delimiter',' ','MultipleDelimsAsOne',1); if parsed_string{1}==instance disp(['Reading structure ' num2str(instance) ' from ' pdb_file_name '...' ]); break; end end % Get the outputs started aa_num=[]; aa_typ={}; pdb_id={}; coords={}; % Parse the PDB file while ~feof(file_id) data_line=fgetl(file_id); if (numel(data_line)>=6)&&strcmp('ENDMDL',data_line(1:6)), break; end if ~isempty(data_line) parsed_string=textscan(data_line,'ATOM %f %s %s %s %f %f %f %f %f %f','delimiter',' ','MultipleDelimsAsOne',1); if all(~cellfun(@isempty,parsed_string)) aa_num(end+1)=parsed_string{5}; %#ok<AGROW> aa_typ{end+1}=parsed_string{3}{1}; %#ok<AGROW> pdb_id{end+1}=parsed_string{2}{1}; %#ok<AGROW> coords{end+1}=[parsed_string{6:8}]; %#ok<AGROW> end end end % Capitalize amino acid type specifications for n=1:numel(aa_typ) aa_typ{n}=upper(aa_typ{n}); %#ok<AGROW> end % Make outputs column vectors aa_num=aa_num'; aa_typ=aa_typ'; pdb_id=pdb_id'; coords=coords'; % Close the PDB file fclose(file_id); end % Consistency enforcement function grumble(pdb_file_name,instance) if ~ischar(pdb_file_name) error('pdb_file_name must be a character string.'); end if (~isnumeric(instance))||(~isreal(instance))||... (instance<1)||(mod(instance,1)~=0) error('instance must be a positive real integer.'); end end % Heartless sterility, obliteration of all melody, all tonal charm, all % music... This revelling in the destruction of all tonal essence, raging % satanic fury in the orchestra, this demoniacal, lewd caterwauling, % scandal-mongering, gun-toting music, with an orchestral accompaniment % slapping you in the face... Hence, the secret fascination that makes it % the darling of feeble-minded royalty... of the court monkeys covered with % reptilian slime, and of the blase hysterical female court parasites who % need this galvanic stimulation by massive instrumental treatment to throw % their pleasure-weary frog-legs into violent convulsion... the diabolical % din of this pig-headed man, stuffed with brass and sawdust, inflated, in % an insanely destructive self-aggrandizement, by Mephistopheles' mephitic % and most venomous hellish miasma, into Beelzebub's Court Composer and % General Director of Hell's Music - Wagner! % % J.L. Klein, "Geschichte des Dramas", 1871.
github
tsajed/nmr-pred-master
cst_display.m
.m
nmr-pred-master/spinach/etc/cst_display.m
4,512
utf_8
511a7e959a0f8ca32ef4b579ddebcafd
% Ellipsoid plots of chemical shielding tensors and their eigensystems. % % <http://spindynamics.org/wiki/index.php?title=Cst_display.m> function cst_display(props,atoms,scaling_factor,conmatrix) % Check consistency grumble(props,atoms,scaling_factor,conmatrix); % Set up graphics figure(); hold on; colormap hot; opengl software; light('Position',[-2,2,20]); light('Position',[10,10,10]); % Draw the molecule molplot(props.std_geom,conmatrix); % Get a unit sphere k=4; n=2^k-1; theta=pi*(-n:2:n)/n; phi=(pi/2)*(-n:2:n)'/n; X=cos(phi)*cos(theta); Y=cos(phi)*sin(theta); Z=sin(phi)*ones(size(theta)); % Loop over atoms for n=1:props.natoms % Ignore atoms that are not on the user-supplied list if ismember(props.symbols{n},atoms) % Diagonalize the shielding tensor [eigvecs,eigvals]=eig(props.cst{n}); eigvals=diag(eigvals); % Do not plot tensors smaller than 0.1 ppm if norm(eigvals)>0.1 % Stretch and scale sphere vertex coordinates coords=[reshape(X*eigvals(1)*scaling_factor,1,length(phi)*length(theta));... reshape(Y*eigvals(2)*scaling_factor,1,length(phi)*length(theta));... reshape(Z*eigvals(3)*scaling_factor,1,length(phi)*length(theta))]; % Rotate sphere vertex coordinates coords=eigvecs*coords; % Fold back sphere vertex coordinates Xd=reshape(coords(1,:),length(phi),length(theta)); Yd=reshape(coords(2,:),length(phi),length(theta)); Zd=reshape(coords(3,:),length(phi),length(theta)); % Color vertices by amplitude Cd=sqrt(Xd.^2+Yd.^2+Zd.^2); % Translate vertices Xd=Xd+props.std_geom(n,1); Yd=Yd+props.std_geom(n,2); Zd=Zd+props.std_geom(n,3); % Draw the surface surf(Xd,Yd,Zd,Cd,'FaceAlpha',0.5,'EdgeAlpha',0.1); % Scale eigenvectors vector_a=eigvecs(:,1)*eigvals(1)*scaling_factor; vector_b=eigvecs(:,2)*eigvals(2)*scaling_factor; vector_c=eigvecs(:,3)*eigvals(3)*scaling_factor; % Colour eigenvectors col_a='r-'; col_b='r-'; col_c='r-'; if eigvals(1)<0, col_a='b-'; end if eigvals(2)<0, col_b='b-'; end if eigvals(3)<0, col_c='b-'; end % Draw eigenvectors plot3([props.std_geom(n,1)-vector_a(1) props.std_geom(n,1)+vector_a(1)],... [props.std_geom(n,2)-vector_a(2) props.std_geom(n,2)+vector_a(2)],... [props.std_geom(n,3)-vector_a(3) props.std_geom(n,3)+vector_a(3)],col_a,'LineWidth',1); plot3([props.std_geom(n,1)-vector_b(1) props.std_geom(n,1)+vector_b(1)],... [props.std_geom(n,2)-vector_b(2) props.std_geom(n,2)+vector_b(2)],... [props.std_geom(n,3)-vector_b(3) props.std_geom(n,3)+vector_b(3)],col_b,'LineWidth',1); plot3([props.std_geom(n,1)-vector_c(1) props.std_geom(n,1)+vector_c(1)],... [props.std_geom(n,2)-vector_c(2) props.std_geom(n,2)+vector_c(2)],... [props.std_geom(n,3)-vector_c(3) props.std_geom(n,3)+vector_c(3)],col_c,'LineWidth',1); end end end % Tidy up the picture axis square; axis tight; axis equal; set(gca,'Projection','perspective'); box on; grid on; end % Consistency enforcement function grumble(props,atoms,scaling_factor,conmatrix) if ~isfield(props,'std_geom') error('props structure does not contain std_geom field with atomic coordinates.'); end if ~isfield(props,'cst') error('props structure does not contain cst field with chemical shielding tensors.'); end if ~iscell(atoms) error('atoms parameter must be a cell array of character strings.'); end if (~isnumeric(scaling_factor))||(~isreal(scaling_factor)) error('scaling_factor must be a real number.'); end if ~isempty(conmatrix) if ~all(size(conmatrix)==[size(std_geom,1) size(std_geom,1)]) error('both dimensions of conmatrix must be equal to the number of atoms in the system.'); end end end % I'll be more enthusiastic about encouraging thinking outside the box when % there's evidence of any thinking going on inside it. % % Terry Pratchett
github
tsajed/nmr-pred-master
hfc_display.m
.m
nmr-pred-master/spinach/etc/hfc_display.m
4,543
utf_8
a50d0d45bec27c2e55cfe2c48509826f
% Ellipsoid plots of hyperfine coupling tensors. % % <http://spindynamics.org/wiki/index.php?title=Hfc_display.m> function hfc_display(props,atoms,scaling_factor,conmatrix) % Set up graphics figure(); clf reset; hold on; colormap hot; opengl software; light('Position',[-2,2,20]); light('Position',[10,10,10]); % Draw the molecule molplot(props.std_geom,conmatrix); % Get a unit sphere k=4; n=2^k-1; theta=pi*(-n:2:n)/n; phi=(pi/2)*(-n:2:n)'/n; X=cos(phi)*cos(theta); Y=cos(phi)*sin(theta); Z=sin(phi)*ones(size(theta)); % Loop over atoms for n=1:props.natoms % Ignore atoms that are not on the user-supplied list if ismember(props.symbols{n},atoms) % Do not plot tensors smaller than 0.1 Gauss if norm(props.hfc.full.eigvals{n})>0.1 % Stretch and scale sphere vertex coordinates coords=[reshape(X*props.hfc.full.eigvals{n}(1)*scaling_factor,1,length(phi)*length(theta));... reshape(Y*props.hfc.full.eigvals{n}(2)*scaling_factor,1,length(phi)*length(theta));... reshape(Z*props.hfc.full.eigvals{n}(3)*scaling_factor,1,length(phi)*length(theta))]; % Rotate sphere vertex coordinates coords=props.hfc.full.eigvecs{n}*coords; % Fold back sphere vertex coordinates Xd=reshape(coords(1,:),length(phi),length(theta)); Yd=reshape(coords(2,:),length(phi),length(theta)); Zd=reshape(coords(3,:),length(phi),length(theta)); % Color vertices by amplitude Cd=sqrt(Xd.^2+Yd.^2+Zd.^2); % Translate vertices Xd=Xd+props.std_geom(n,1); Yd=Yd+props.std_geom(n,2); Zd=Zd+props.std_geom(n,3); % Draw the surface surf(Xd,Yd,Zd,Cd,'FaceAlpha',0.5,'EdgeAlpha',0.1); % Scale eigenvectors vector_a=props.hfc.full.eigvecs{n}(:,1)*props.hfc.full.eigvals{n}(1)*scaling_factor; vector_b=props.hfc.full.eigvecs{n}(:,2)*props.hfc.full.eigvals{n}(2)*scaling_factor; vector_c=props.hfc.full.eigvecs{n}(:,3)*props.hfc.full.eigvals{n}(3)*scaling_factor; % Color eigenvectors col_a='r-'; col_b='r-'; col_c='r-'; if props.hfc.full.eigvals{n}(1)<0, col_a='b-'; end if props.hfc.full.eigvals{n}(2)<0, col_b='b-'; end if props.hfc.full.eigvals{n}(3)<0, col_c='b-'; end % Draw eigenvectors plot3([props.std_geom(n,1)-vector_a(1) props.std_geom(n,1)+vector_a(1)],... [props.std_geom(n,2)-vector_a(2) props.std_geom(n,2)+vector_a(2)],... [props.std_geom(n,3)-vector_a(3) props.std_geom(n,3)+vector_a(3)],col_a,'LineWidth',1); plot3([props.std_geom(n,1)-vector_b(1) props.std_geom(n,1)+vector_b(1)],... [props.std_geom(n,2)-vector_b(2) props.std_geom(n,2)+vector_b(2)],... [props.std_geom(n,3)-vector_b(3) props.std_geom(n,3)+vector_b(3)],col_b,'LineWidth',1); plot3([props.std_geom(n,1)-vector_c(1) props.std_geom(n,1)+vector_c(1)],... [props.std_geom(n,2)-vector_c(2) props.std_geom(n,2)+vector_c(2)],... [props.std_geom(n,3)-vector_c(3) props.std_geom(n,3)+vector_c(3)],col_c,'LineWidth',1); end end end % Tidy up the picture axis square; axis tight; axis equal; set(gca,'Projection','perspective'); box on; grid on; end % The record for the shortest ever postdoc term in IK's group belongs % to Gaby Slavcheva - 6 hours. She had turned up on a Monday morning, % went through a tour of the lab, a tour of the computing systems and % an introduction to the SVN repositories that the group operates. IK % explained that the repositories keep track of everyone's contributi- % on to every project in a rigorous and objective way, making it easy % to attribute credit, blame and to decide the author list of each pa- % per. Gaby resigned her post that same evening, citing "draconian re- % strictions" on her "academic freedom", and claiming two months' pay % for "redundancy" from Southampton's hapless HR service. % % IK did not object. Last thing he heard many years down the line was % that, with over 100 peer-reviewed papers and at the age of 56, Gaby % was a postdoc at the University of Bath.
github
tsajed/nmr-pred-master
oparse.m
.m
nmr-pred-master/spinach/etc/oparse.m
3,011
utf_8
d644fff672c2bdc2ae87f74af0784137
% A parser for ORCA logs. % % <http://spindynamics.org/wiki/index.php?title=Oparse.m> function props=oparse(file_name) % Check consistency grumble(file_name); % Read the file file_id=fopen(file_name,'r'); orca_log=textscan(file_id,'%s','delimiter','\n'); fclose(file_id); orca_log=orca_log{1}; props.filename=file_name; % Deblank all lines for n=1:numel(orca_log), orca_log(n)=deblank(orca_log(n)); end % Parse the file for n=1:length(orca_log) % Read the input orientation and atomic symbols if strcmp(orca_log{n},'CARTESIAN COORDINATES (ANGSTROEM)') k=n+2; m=1; while ~isempty(orca_log{k}) S=textscan(orca_log{k},'%s %f %f %f'); props.symbols{m}=S{1}{1}; props.std_geom(m,:)=[S{2:4}]; k=k+1; m=m+1; end props.natoms=m-1; disp('ORCA import: found atomic coordinates.'); end % Read the g-tensor if strcmp(orca_log{n},'The g-matrix:') props.g_tensor.matrix=zeros(3,3); S=textscan(orca_log{n+1},'%f %f %f'); props.g_tensor.matrix(1,:)=S{1:3}; S=textscan(orca_log{n+2},'%f %f %f'); props.g_tensor.matrix(2,:)=S{1:3}; S=textscan(orca_log{n+3},'%f %f %f'); props.g_tensor.matrix(3,:)=S{1:3}; props.g_tensor.matrix=(props.g_tensor.matrix+... props.g_tensor.matrix')/2; disp('ORCA import: found the g-tensor.'); end if strfind(orca_log{n},'Nucleus ')==1 atom=textscan(orca_log{n},'%*s %f%*s'); idx=atom{:}(1)+1; k=n+1; while isempty(strfind(orca_log{k},'Nucleus '))&&k<length(orca_log) k=k+1; if strcmp(orca_log{k},'Raw HFC matrix (all values in MHz):')==1 S=textscan(orca_log{k+2},'%f %f %f'); props.hfc.full.matrix{idx}(1,:)=[S{1} S{2} S{3}]; S=textscan(orca_log{k+3},'%f %f %f'); props.hfc.full.matrix{idx}(2,:)=[S{1} S{2} S{3}]; S=textscan(orca_log{k+4},'%f %f %f'); props.hfc.full.matrix{idx}(3,:)=[S{1} S{2} S{3}]; props.hfc.full.matrix{idx}=mhz2gauss(props.hfc.full.matrix{idx}); [A,B]=eig(props.hfc.full.matrix{idx}); props.hfc.full.eigvals{idx}=diag(B); props.hfc.full.eigvecs{idx}=A; end if strcmp(orca_log{k},'Raw EFG matrix (all values in a.u.**-3):')==1 S=textscan(orca_log{k+1},'%f %f %f'); props.efg{idx}(1,:)=[S{1} S{2} S{3}]; S=textscan(orca_log{k+2},'%f %f %f'); props.efg{idx}(2,:)=[S{1} S{2} S{3}]; S=textscan(orca_log{k+3},'%f %f %f'); props.efg{idx}(3,:)=[S{1} S{2} S{3}]; end end end end end % Consistency enforcement function grumble(file_name) if ~ischar(file_name) error('file_name must be a character string.'); end end % I can't think that it would be terrible of me to say - and it % is occasionally true - that I need physics more than friends. % % J. Robert Oppenheimer
github
tsajed/nmr-pred-master
protein.m
.m
nmr-pred-master/spinach/etc/protein.m
12,478
utf_8
00ed6a47c240f3078156f9a6da717d42
% Protein data import function. % % <http://spindynamics.org/wiki/index.php?title=Protein.m> function [sys,inter]=protein(pdb_file,bmrb_file,options) % Check consistency grumble(pdb_file,bmrb_file,options); % Parse the PDB file [pdb_aa_num,pdb_aa_typ,pdb_atom_id,pdb_coords]=read_pdb_pro(pdb_file,options.pdb_mol); % Parse the BMRB file [bmrb_aa_num,bmrb_aa_typ,bmrb_atom_id,bmrb_chemsh]=read_bmrb(bmrb_file); % Remove oxygens, sulphurs and terminal atoms kill_mask=ismember(pdb_atom_id,{'O','OE','OE1','OE2','OD1','OD2','OG','OG1','HG1',... 'OG2','OH','HH','SD','SG','OXT','O''','O'''''}); pdb_aa_num(kill_mask)=[]; pdb_atom_id(kill_mask)=[]; pdb_aa_typ(kill_mask)=[]; pdb_coords(kill_mask)=[]; disp('WARNING: oxygen, sulphur, and OH protons will not appear in the simulation.'); % Match chemical shifts pdb_chemsh=cell(numel(pdb_atom_id),1); disp(' '); disp('############# CHEMICAL SHIFT IMPORT SUMMARY ###############'); for n=1:numel(pdb_atom_id) % Pull the current amino acid from BMRB select_mask=(bmrb_aa_num==pdb_aa_num(n)); bmrb_atoms=bmrb_atom_id(select_mask); bmrb_shifts=bmrb_chemsh(select_mask); % Make sure amino acid types match if ~all(strcmp(pdb_aa_typ{n},bmrb_aa_typ(select_mask))) disp(pdb_aa_typ{n}); disp(bmrb_aa_typ(select_mask)); error('Amino acid type mismatch between PDB and BMRB files.'); end % Ugly heuristics (sorry!) to match PDB and BMRB data if ismember(pdb_atom_id{n},bmrb_atoms) pdb_chemsh{n}=bmrb_shifts(strcmp(pdb_atom_id{n},bmrb_atoms)); disp(['Imported chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif strcmp(pdb_atom_id{n},'N')&&(pdb_aa_num(n)==1) disp(['WARNING: N-terminal NH2 group of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); elseif ismember(pdb_atom_id{n},{'HG'})&&ismember(pdb_aa_typ(n),{'SER'}) disp(['WARNING: OH group of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); elseif ismember(pdb_atom_id{n},{'HG1'})&&ismember(pdb_aa_typ(n),{'THR'}) disp(['WARNING: OH group of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); elseif ismember(pdb_atom_id{n},{'HB3'})&&ismember('HB2',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'MET','GLU','GLN','LYS','LEU','SER','HIS','ARG'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HB2',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HB1','HB2','HB3'})&&ismember('HB',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'ALA'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HB',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HG21','HG22','HG23','HG1','HG3'})&&ismember('HG2',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'ILE','THR','VAL','GLU','LYS','PRO','GLN','ARG'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HG2',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HG11','HG12','HG13','HG2','HG3'})&&ismember('HG1',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'VAL'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HG1',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HG13'})&&ismember('HG12',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'ILE'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HG12',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HD11','HD12','HD13','HD2','HD3'})&&ismember('HD1',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'ILE','LEU'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HD1',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HD21','HD22','HD23','HD1','HD3'})&&ismember('HD2',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'LYS','LEU','PRO','ARG'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HD2',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HE3'})&&ismember('HE2',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'LYS'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HE2',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HE1','HE2','HE3'})&&ismember('HE',bmrb_atoms)&&ismember(pdb_aa_typ{n},{'MET'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HE',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'CD2'})&&ismember('CD1',bmrb_atoms)&&ismember(pdb_aa_typ(n),{'PHE','TYR'}) pdb_chemsh{n}=bmrb_shifts(strcmp('CD1',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'CE2'})&&ismember('CE1',bmrb_atoms)&&ismember(pdb_aa_typ(n),{'PHE','TYR'}) pdb_chemsh{n}=bmrb_shifts(strcmp('CE1',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HD2'})&&ismember('HD1',bmrb_atoms)&&ismember(pdb_aa_typ(n),{'PHE','TYR'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HD1',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HE2'})&&ismember('HE1',bmrb_atoms)&&ismember(pdb_aa_typ(n),{'PHE','TYR'}) pdb_chemsh{n}=bmrb_shifts(strcmp('HE1',bmrb_atoms)); disp(['WARNING: replicated chemical shift for ' pad([pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ':'],15,'right') pad(num2str(pdb_chemsh{n},'%6.3f'),6,'left') ' ppm']); elseif ismember(pdb_atom_id{n},{'HH'})&&ismember(pdb_aa_typ(n),{'TYR'}) disp(['WARNING: OH group of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); elseif ismember(pdb_atom_id{n},{'HD1'})&&ismember(pdb_aa_typ(n),{'HIS'}) disp(['WARNING: ring NH group of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); elseif ismember(pdb_atom_id{n},{'NZ','HZ1','HZ2','HZ3'})&&ismember(pdb_aa_typ(n),{'LYS'}) disp(['WARNING: side chain NH3+ group of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); elseif ismember(pdb_atom_id{n},{'NE','CZ','NH1','NH2','HE','HH11','HH12','HH21','HH22'})&&ismember(pdb_aa_typ(n),{'ARG'}) disp(['WARNING: side chain nitrogen block of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')' ' ignored.']); end end % Estimate J-couplings scalar_couplings=guess_j_pro(pdb_aa_num,pdb_aa_typ,pdb_atom_id,pdb_coords); % Estimate chemical shielding anisotropies CSAs=guess_csa_pro(pdb_aa_num,pdb_atom_id,pdb_coords); % Assign isotopes and labels isotopes=cell(1,numel(pdb_atom_id)); for n=1:numel(pdb_atom_id) switch pdb_atom_id{n}(1) case 'H' isotopes{n}='1H'; case 'C' isotopes{n}='13C'; case 'N' isotopes{n}='15N'; otherwise error('unknown atom type.'); end end % Process atom selection specification if isnumeric(options.select) % Numeric selection needs no special processing elseif strcmp(options.select,'backbone') % Import backbone up to CB and HB subset=ismember(pdb_atom_id,{'H','N','C','CA','HA','CB','HB','HB1','HB2','HB3'}); elseif strcmp(options.select,'backbone-minimal') % Import minimal backbone subset=ismember(pdb_atom_id,{'H','N','C','CA','HA'}); elseif strcmp(options.select,'backbone-hsqc') % Import backbone up to CB and HB and also ASN and GLN amide groups subset=ismember(pdb_atom_id,{'H','N','C','CA','HA','NE2','HE21','HE22','CD','CG',... 'ND2','HD21','HD22','CB','HB','HB1','HB2','HB3'}); elseif strcmp(options.select,'all') % Import everything subset=true(size(pdb_atom_id)); else % Complain and bomb out error('incorrect subset selection specification.'); end % Find missing chemical shifts missing_shifts=find(cellfun(@isempty,pdb_chemsh))'; disp(' '); disp('############# SUMMARY OF MISSING ASSIGNMENTS ###############'); % Process unassigned chemical shifts if strcmp(options.noshift,'keep') % Put unassigned spins between -1.0 and 0.0 ppm erzatz_shifts=linspace(-1,0,numel(missing_shifts)); for n=1:numel(missing_shifts) disp(['Missing assignment of ' pdb_aa_typ{missing_shifts(n)} '(' num2str(pdb_aa_num(missing_shifts(n)))... ')-' pdb_atom_id{missing_shifts(n)} ': the spin is placed at ' num2str(erzatz_shifts(n)) ' ppm.']); pdb_chemsh{missing_shifts(n)}=erzatz_shifts(n); end elseif strcmp(options.noshift,'delete') % Delete unassigned spins for n=missing_shifts disp(['Missing assignment of ' pdb_aa_typ{n} '(' num2str(pdb_aa_num(n)) ')-' pdb_atom_id{n} ... ': the atom will not appear in the simulation.']); end subset=subset&(~cellfun(@isempty,pdb_chemsh)); else % Complain and bomb out error('incorrect value of options.noshift parameter.'); end % Apply the selection sys.isotopes=isotopes(subset); sys.labels=pdb_atom_id(subset)'; inter.zeeman.scalar=pdb_chemsh(subset)'; inter.zeeman.matrix=CSAs(subset)'; inter.coupling.scalar=scalar_couplings(subset,subset); inter.coordinates=pdb_coords(subset); end % Consistency enforcement function grumble(pdb_file,bmrb_file,options) if ~ischar(pdb_file) error('pdb_file must be a character string specifying a file name.'); end if ~ischar(bmrb_file) error('bmrb_file must be a character string specifying a file name.'); end if ~isfield(options,'select') error('options.select switch must be specfied.'); elseif (~isnumeric(options.select))&&(~ismember(options.select,{'all','backbone','backbone-hsqc','backbone-minimal'})) error('invalid value for options.select, please refer to the manual.'); end if ~isfield(options,'pdb_mol') error('options.pdb_mol switch must be specfied.'); elseif (~isnumeric(options.pdb_mol)) error('invalid value for options.pdb_mol, please refer to the manual.'); end if ~isfield(options,'noshift') error('options.noshift switch must be specfied.'); elseif (~isnumeric(options.noshift))&&(~ismember(options.noshift,{'keep','delete'})) error('invalid value for options.noshift, please refer to the manual.'); end end % We saw that we'd been given a law to live by, a moral law, they called % it, which punished those who observed it -- for observing it. The more % you tried to live up to it, the more you suffered; the more you cheated % it, the bigger reward you got. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
guess_j_pro.m
.m
nmr-pred-master/spinach/etc/guess_j_pro.m
43,552
utf_8
14f3a65cfff1df052e1f7bac2961da02
% Assigns J-couplings from literature values and Karplus curves. % % <http://spindynamics.org/wiki/index.php?title=Guess_j_pro.m> function jmatrix=guess_j_pro(aa_num,aa_typ,pdb_id,coords) % Check consistency grumble(aa_num,aa_typ,pdb_id,coords); % Preallocate the answer jmatrix=cell(numel(coords),numel(coords)); % Number the atoms numbers=1:numel(coords); % Determine the connectivity graph proxmatrix=false(numel(coords),numel(coords)); for n=1:numel(coords) for k=1:numel(coords) if (norm(coords{n}-coords{k},2)<1.60), proxmatrix(n,k)=1; end end end % Get all connected subgraphs up to size 2 subgraphs=dfpt(sparse(proxmatrix),2); % Set generic coupling values J_NH=-90.0; J_CN=-15.0; J_CH=140.0; J_CC=35.0; % Spec all ordered connected pairs pairs_database={... % Backbone has specific numbers 'CA_CB' , +35.0; 'CA_HA' , +140.0; 'CA_N' , -11.0; 'C_CA' , +55.0; 'C_N' , -15.0; 'H_N' , -90.0; % The rest is generic 'CA_HA2' , J_CH; 'CA_HA3' , J_CH; 'CB_CG' , J_CC; 'CB_CG1' , J_CC; 'CB_CG2' , J_CC; 'CB_HB' , J_CH; 'CB_HB1' , J_CH; 'CB_HB2' , J_CH; 'CB_HB3' , J_CH; 'CD1_CE1' , J_CC; 'CD1_CG' , J_CC; 'CD1_CG1' , J_CC; 'CD1_HD1' , J_CH; 'CD1_HD11' , J_CH; 'CD1_HD12' , J_CH; 'CD1_HD13' , J_CH; 'CD1_NE1' , J_CN; 'CD2_CE2' , J_CC; 'CD2_CG' , J_CC; 'CD2_HD2' , J_CH; 'CD2_HD21' , J_CH; 'CD2_CE3' , J_CC; 'CD2_HD22' , J_CH; 'CD2_HD23' , J_CH; 'CD2_NE2' , J_CN; 'CD_CE' , J_CC; 'CE2_NE1' , J_CN; 'CD_CG' , J_CC; 'CD_HD2' , J_CH; 'CD_HD3' , J_CH; 'CD_N' , J_CN; 'HE1_NE1' , J_NH; 'CD_NE2' , J_CN; 'CE1_CZ' , J_CC; 'CE1_HE1' , J_CH; 'CE1_ND1' , J_CN; 'CE2_CZ2' , J_CC; 'CE1_NE2' , J_CN; 'CE2_CZ' , J_CC; 'CE2_HE2' , J_CH; 'CE_HE1' , J_CH; 'CE3_CZ3' , J_CC; 'CE_HE2' , J_CH; 'CE_HE3' , J_CH; 'CG1_HG11' , J_CH; 'CG1_HG12' , J_CH; 'CE3_HE3' , J_CH; 'CG1_HG13' , J_CH; 'CG2_HG21' , J_CH; 'CG2_HG22' , J_CH; 'CG2_HG23' , J_CH; 'CH2_CZ2' , J_CC; 'CG_HG' , J_CH; 'CH2_HH2' , J_CH; 'CG_HG2' , J_CH; 'CG_HG3' , J_CH; 'CG_ND1' , J_CN; 'CG_ND2' , J_CN; 'CZ_HZ' , J_CH; 'HD21_ND2' , J_NH; 'HD22_ND2' , J_NH; 'CZ3_HZ3' , J_CH; 'HE21_NE2' , J_NH; 'HE22_NE2' , J_NH; 'HH22_NH2' , J_NH; 'HH21_NH2' , J_NH; 'CH2_CZ3' , J_CC; 'HH12_NH1' , J_NH; 'HH11_NH1' , J_NH; 'CZ_NH2' , J_CN; 'CZ_NH1' , J_CN; 'CZ2_HZ2' , J_CH; 'CZ_NE' , J_CN; 'HE_NE' , J_NH; 'CD_NE' , J_CN; 'HZ3_NZ' , J_NH; 'HZ2_NZ' , J_NH; 'HZ1_NZ' , J_NH; 'CE_NZ' , J_CN; 'HD1_ND1' , J_NH; 'H_H' , 0.00; 'H1_N' , J_NH; 'H2_N' , J_NH; 'H3_N' , J_NH; 'CH2_HH2' , J_CH; 'CZ3_HZ3' , J_CH; 'CH2_CZ3' , J_CH; 'CZ2_HZ2' , J_CH; 'CH2_CZ2' , J_CH; 'CE3_HE3' , J_CH; 'CE3_CZ3' , J_CC; 'CE2_CZ2' , J_CC; 'HE1_NE1' , J_NH; 'CE2_NE1' , J_CN; 'CD2_CE3' , J_CC; 'CD1_NE1' , J_CN}; % Loop over subgraphs disp(' '); disp('############# ONE-BOND J-COUPLING SUMMARY ###############'); for n=1:size(subgraphs,1) % Extract labels, residues and numbers spin_labels=pdb_id(subgraphs(n,:)); spin_numbers=numbers(subgraphs(n,:)); spin_resnames=aa_typ(subgraphs(n,:)); spin_resnums=aa_num(subgraphs(n,:)); % Index the spins [spin_labels,index]=sort(spin_labels); spin_numbers=spin_numbers(index); spin_resnames=spin_resnames(index); spin_resnums=spin_resnums(index); % Consult the database if numel(spin_labels)==1 % Inform the user about solitary spins disp(['WARNING: solitary spin detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}]); else % Build specification string spec_string=pairs_database(strcmp([spin_labels{1} '_' spin_labels{2}],pairs_database(:,1)),:); % Assign the coupling if isempty(spec_string) % Complain if nothing found disp(['WARNING: unknown atom pair or unphysical proximity, ' spin_labels{1} '_' spin_labels{2} ' in residues ' spin_resnames{1}... '(' num2str(spin_resnums(1)) '), ' spin_resnames{2} '(' num2str(spin_resnums(2)) ')']); elseif size(spec_string,1)>1 % Complain if multiple records found error([spec_string{1} ' coupling has been specified multiple times in the coupling database.']); else % Write the array jmatrix{spin_numbers(1),spin_numbers(2)}=spec_string{2}; % Report to the user disp(['Estimated one-bond J-coupling from ' pad([spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}],19) ' to ' ... pad([spin_resnames{2} '(' num2str(spin_resnums(2)) '):' spin_labels{2}],19) ' ' ... pad(num2str(spec_string{2},'%5.1f'),6,'left') ' Hz']); end end end % Get all connected subgraphs up to size 3 subgraphs=dfpt(sparse(proxmatrix),3); % Set generic coupling values J_CCC=-1.2; % Zenawi's DFT J_CCH=0; % Literature reference J_CCN=7.0; % Zenawi's DFT J_HCH=-12.0; % Literature reference J_HNH=-1.5; % Zenawi's DFT J_NCN=0; % Literature reference J_NCH=0; % Literature reference J_CNH=0; % Literature reference J_CNC=0; % Literature reference % Spec all ordered connected triples (sorted atoms, bonding order, coupling from atom 1 to atom 3) triples_database={... % Backbone has specific numbers 'C_CA_CB', 1, 2, 3, 0.0; 'C_CA_HA', 1, 2, 3, -5.0; 'C_CA_HA2', 1, 2, 3, -5.0; 'C_CA_HA3', 1, 2, 3, -5.0; 'C_CA_N', 2, 1, 3, 7.0; 'C_CD_N', 1, 3, 2, 0.0; 'C_H_N', 1, 3, 2, 0.0; 'CA_CB_HA', 2, 1, 3, 0.0; 'CA_CB_N', 2, 1, 3, 11.0; 'CA_H_N', 1, 3, 2, 0.0; 'CA_HA_N', 2, 1, 3, 0.0; 'CA_HA2_HA3', 2, 1, 3, -12.0; 'CA_HA2_N', 2, 1, 3, 0.0; 'CA_HA3_N', 2, 1, 3, 0.0; 'CA_CD_N', 1, 3, 2, 0.0; % Everything else is generic 'CA_CB_CG', 1, 2, 3, -1.2; 'CA_CB_CG1', 1, 2, 3, -1.2; 'CA_CB_CG2', 1, 2, 3, J_CCC; 'CA_CB_HB', 1, 2, 3, J_CCH; 'CA_CB_HB1', 1, 2, 3, -7.5; 'CA_CB_HB2', 1, 2, 3, -4.2; 'CA_CB_HB3', 1, 2, 3, -2.2; 'CB_CD_CG', 1, 3, 2, J_CCC; 'CB_CD1_CG', 1, 3, 2, J_CCC; 'CB_CD1_CG1', 1, 3, 2, J_CCC; 'CB_CD2_CG', 1, 3, 2, J_CCC; 'CB_CG_HB2', 2, 1, 3, J_CCH; 'CB_CG_HB3', 2, 1, 3, J_CCH; 'CB_CG_HG', 1, 2, 3, J_CCH; 'CB_CG_HG2', 1, 2, 3, J_CCH; 'CB_CG_HG3', 1, 2, 3, J_CCH; 'CB_CG_ND1', 1, 2, 3, J_CCN; 'CB_CG_ND2', 1, 2, 3, J_CCN; 'CB_CG1_CG2', 2, 1, 3, J_CCC; 'CB_CG1_HB', 2, 1, 3, J_CCH; 'CB_CG1_HG11', 1, 2, 3, J_CCH; 'CB_CG1_HG12', 1, 2, 3, J_CCH; 'CB_CG1_HG13', 1, 2, 3, J_CCH; 'CB_CG2_HB', 2, 1, 3, J_CCH; 'CB_CG2_HG21', 1, 2, 3, J_CCH; 'CB_CG2_HG22', 1, 2, 3, J_CCH; 'CB_CG2_HG23', 1, 2, 3, J_CCH; 'CB_HB1_HB2', 2, 1, 3, J_HCH; 'CB_HB1_HB3', 2, 1, 3, J_HCH; 'CB_HB2_HB3', 2, 1, 3, J_HCH; 'CD_CE_CG', 2, 1, 3, J_CCC; 'CD_CE_HD2', 2, 1, 3, J_CCH; 'CD_CE_HD3', 2, 1, 3, J_CCH; 'CD_CE_HE2', 1, 2, 3, J_CCH; 'CD_CE_HE3', 1, 2, 3, J_CCH; 'CD_CG_HD2', 2, 1, 3, J_CCH; 'CD_CG_HD3', 2, 1, 3, J_CCH; 'CD_CG_HG2', 1, 2, 3, J_CCH; 'CD_CG_HG3', 1, 2, 3, J_CCH; 'CD_CG_N', 2, 1, 3, J_CCN; 'CD_CG_NE2', 2, 1, 3, J_CCN; 'CD_HD2_HD3', 2, 1, 3, J_HCH; 'CD_HD2_N', 2, 1, 3, J_NCH; 'CD_HD3_N', 2, 1, 3, J_NCH; 'CD_HE21_NE2', 1, 3, 2, J_CNH; 'CD_HE22_NE2', 1, 3, 2, J_CNH; 'CD1_CD2_CG', 1, 3, 2, J_CCC; 'CD1_CE1_CG', 2, 1, 3, J_CCC; 'CD1_CE1_CZ', 1, 2, 3, J_CCC; 'CD1_CE1_HD1', 2, 1, 3, J_CCH; 'CD1_CE1_HE1', 1, 2, 3, J_CCH; 'CD1_CG_HD1', 2, 1, 3, J_CCH; 'CD1_CG_HD11', 2, 1, 3, J_CCH; 'CD1_CG_HD12', 2, 1, 3, J_CCH; 'CD1_CG_HD13', 2, 1, 3, J_CCH; 'CD1_CG_HG', 1, 2, 3, J_CCH; 'CD1_CG1_HD11', 2, 1, 3, J_CCH; 'CD1_CG1_HD12', 2, 1, 3, J_CCH; 'CD1_CG1_HD13', 2, 1, 3, J_CCH; 'CD1_CG1_HG12', 1, 2, 3, J_CCH; 'CD1_CG1_HG13', 1, 2, 3, J_CCH; 'CD1_HD11_HD12', 2, 1, 3, J_HCH; 'CD1_HD11_HD13', 2, 1, 3, J_HCH; 'CD1_HD12_HD13', 2, 1, 3, J_HCH; 'CD2_CE2_CE3', 1, 2, 3, J_CCC; 'CD2_CE1_NE2', 1, 3, 2, J_CNC; 'CD2_CE2_CG', 2, 1, 3, J_CCC; 'CD2_CE2_CZ', 1, 2, 3, J_CCC; 'CD2_CE2_HD2', 2, 1, 3, J_CCH; 'CD2_CE2_CE3', 1, 2, 3, J_CCC; 'CD2_CE2_HE2', 1, 2, 3, J_CCH; 'CD2_CG_HD2', 2, 1, 3, J_CCH; 'CD2_CG_HD21', 2, 1, 3, J_CCH; 'CD2_CG_HD22', 2, 1, 3, J_CCH; 'CD2_CE2_CZ2', 1, 2, 3, J_CCC; 'CD2_CG_HD23', 2, 1, 3, J_CCH; 'CD2_CG_HG', 1, 2, 3, J_CCH; 'CD2_CG_ND1', 1, 2, 3, J_CCN; 'CD2_CG_NE2', 2, 1, 3, J_CCN; 'CD2_CE3_CZ3', 1, 2, 3, J_CCC; 'CD2_HD2_NE2', 2, 1, 3, J_NCH; 'CD2_HD21_HD22', 2, 1, 3, J_HCH; 'CD2_HD21_HD23', 2, 1, 3, J_HCH; 'CD2_HD22_HD23', 2, 1, 3, J_HCH; 'CD2_CE3_HE3', 1, 2, 3, J_CCH; 'CE_HE1_HE2', 2, 1, 3, J_HCH; 'CE_HE1_HE3', 2, 1, 3, J_HCH; 'CE_HE2_HE3', 2, 1, 3, J_HCH; 'CE1_CE2_CZ', 1, 3, 2, J_CCC; 'CE2_CZ2_NE1', 1, 2, 3, J_CCN; 'CE1_CG_ND1', 1, 3, 2, J_CNC; 'CE1_CZ_HE1', 2, 1, 3, J_CCH; 'CE1_CZ_HZ', 1, 2, 3, J_CCH; 'CE1_HE1_ND1', 2, 1, 3, J_NCH; 'CE2_HE1_NE1', 1, 3, 2, J_CNH; 'CE1_HE1_NE2', 2, 1, 3, J_NCH; 'CE1_ND1_NE2', 2, 1, 3, J_NCN; 'CE2_CZ_HE2', 2, 1, 3, J_CCH; 'CE2_CZ_HZ', 1, 2, 3, J_CCH; 'CE2_CH2_CZ2', 1, 2, 3, J_CCC; 'CG_HD21_ND2', 1, 3, 2, J_CNH; 'CG_HD22_ND2', 1, 3, 2, J_CNH; 'CG_HG2_HG3', 2, 1, 3, J_HCH; 'CG1_HG11_HG12', 2, 1, 3, J_HCH; 'CE2_CZ2_HZ2', 1, 2, 3, J_CCH; 'CG1_HG11_HG13', 2, 1, 3, J_HCH; 'CG1_HG12_HG13', 2, 1, 3, J_HCH; 'CG2_HG21_HG22', 2, 1, 3, J_HCH; 'CG2_HG21_HG23', 2, 1, 3, J_HCH; 'CE3_CH2_CZ3', 1, 2, 3, J_CCC; 'CG2_HG22_HG23', 2, 1, 3, J_HCH; 'HD21_HD22_ND2', 1, 3, 2, J_HNH; 'HE21_HE22_NE2', 1, 3, 2, J_HNH; 'HH21_HH22_NH2', 1, 3, 2, J_HNH; 'CE3_CZ3_HE3', 1, 2, 3, J_CCH; 'HH11_HH12_NH1', 1, 3, 2, J_HNH; 'CZ_HH22_NH2', 1, 3, 2, J_CNH; 'CZ_HH21_NH2', 1, 3, 2, J_CNH; 'CZ_NH1_NH2', 2, 1, 3, J_NCN; 'CE3_CZ3_HZ3', 1, 2, 3, J_CCH; 'CZ_HH12_NH1', 1, 3, 2, J_CNH; 'CZ_HH11_NH1', 1, 3, 2, J_CNH; 'CZ_NE_NH2', 2, 1, 3, J_NCN; 'CZ_NE_NH1', 2, 1, 3, J_NCN; 'CH2_CZ2_CZ3', 1, 2, 3, J_CCC; 'CZ_HE_NE', 1, 3, 2, J_CNH; 'CD_CZ_NE', 1, 3, 2, J_CNC; 'CD_HE_NE', 1, 3, 2, J_CNH; 'CD_HD3_NE', 2, 1, 3, J_NCH; 'CH2_CZ2_HZ2', 1, 2, 3, J_CCH; 'CD_HD2_NE', 2, 1, 3, J_NCH; 'CD_CG_NE', 2, 1, 3, J_CCN; 'HZ2_HZ3_NZ' 1, 3, 2, J_HNH; 'HZ1_HZ3_NZ', 1, 3, 2, J_HNH; 'CH2_CZ2_HH2', 1, 2, 3, J_CCH; 'HZ1_HZ2_NZ', 1, 3, 2, J_HNH; 'CE_HZ3_NZ', 1, 3, 2, J_CNH; 'CE_HZ2_NZ', 1, 3, 2, J_CNH; 'CE_HZ1_NZ', 1, 3, 2, J_CNH; 'CH2_CZ3_HZ3', 1, 2, 3, J_CCH; 'CE_HE3_NZ', 2, 1, 3, J_NCH; 'CE_HE2_NZ', 2, 1, 3, J_NCH; 'CD_CE_NZ', 1, 2, 3, J_CCN; 'CE1_HD1_ND1', 1, 3, 2, J_CNH; 'CH2_CZ3_HH2', 1, 2, 3, J_CCH; 'CG_HD1_ND1', 1, 3, 2, J_CNH; 'H_H_N', 1, 3, 2, J_HNH; 'H2_H3_N', 1, 3, 2, J_HNH; 'H1_H2_N', 1, 3, 2, J_HNH; 'H1_H3_N', 1, 3, 2, J_HNH; 'CA_H1_N', 1, 3, 2, J_CNH; 'CA_H2_N', 1, 3, 2, J_CNH; 'CA_H3_N', 1, 3, 2, J_CNH; % Tryptophan side chain (GIAO DFT M06/cc-pVTZ data in PCM water) 'CH2_CZ3_HH2', 2, 1, 3, -1.82; 'CH2_CZ3_HZ3', 1, 2, 3, -1.13; 'CH2_CZ2_HH2', 2, 1, 3, -2.82; 'CH2_CZ2_HZ2', 1, 2, 3, -3.81; 'CH2_CZ2_CZ3', 2, 1, 3, -3.59; 'CE3_CZ3_HZ3', 1, 2, 3, -2.22; 'CE3_CZ3_HE3', 2, 1, 3, -3.50; 'CE3_CH2_CZ3', 1, 3, 2, -3.38; 'CE2_CZ2_HZ2', 1, 2, 3, -3.47; 'CE2_CH2_CZ2', 1, 3, 2, -1.27; 'CE2_HE1_NE1', 1, 3, 2, 2.36; 'CE2_CZ2_NE1', 2, 1, 3, 0.72; 'CD2_CE3_HE3', 1, 2, 3, -1.35; 'CD2_CE3_CZ3', 1, 2, 3, -2.69; 'CD2_CE2_CZ2', 1, 2, 3, 0.26; 'CD2_CE2_CE3', 2, 1, 3, 0.61; 'CD2_CE2_NE1', 1, 2, 3, 3.55; 'CD1_HE1_NE1', 1, 3, 2, 3.38; 'CD1_HD1_NE1', 2, 1, 3, 2.72; 'CD1_CE2_NE1', 1, 3, 2, 5.55; 'CD2_CE3_CG', 3, 1, 2, 1.08; 'CD1_CG_NE1', 2, 1, 3, 2.30}; % Collision detection exceptions (HIS and PRO, where two-bond and three-bond couplings collide) allowed_collision_list={'H_H_N'}; % Loop over subgraphs disp(' '); disp('############# TWO-BOND J-COUPLING SUMMARY ###############'); for n=1:size(subgraphs,1) % Extract labels, residues and numbers spin_labels=pdb_id(subgraphs(n,:)); spin_numbers=numbers(subgraphs(n,:)); spin_resnames=aa_typ(subgraphs(n,:)); spin_resnums=aa_num(subgraphs(n,:)); % Index the spins [spin_labels,index]=sort(spin_labels); spin_numbers=spin_numbers(index); spin_resnames=spin_resnames(index); spin_resnums=spin_resnums(index); % Consult the database if numel(spin_labels)==1 % Inform the user about solitary spins disp(['WARNING: solitary spin detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}]); elseif numel(spin_labels)==2 % Inform the user about isolated pairs disp(['WARNING: isolated spin pair detected, ' spin_resnames{1} ':' spin_labels{1} ' and ' spin_resnames{2} ':' spin_labels{2}]); else % Build the specification string spec_string=triples_database(strcmp([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3}],triples_database(:,1)),:); % Assign the coupling if isempty(spec_string) % Inform the user about missing data disp(['WARNING: unknown atom triple or unphysical proximity, ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} ' in amino acids '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) ')']); elseif size(spec_string,1)>1 % Complain if multiple records found error([spec_string{1} ' coupling has been specified multiple times in the coupling database.']); else % Extract spin numbers spin_a=spin_numbers(spec_string{2}); spin_b=spin_numbers(spec_string{3}); spin_c=spin_numbers(spec_string{4}); % Match bonding pattern if proxmatrix(spin_a,spin_b)&&proxmatrix(spin_b,spin_c) % Check for collisions if (~isempty(jmatrix{spin_a,spin_c}))&&(~ismember([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3}],allowed_collision_list)) % Complain and bomb out error(['Atom triple: ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} ' in amino acids '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) ' collides with other data.']); else % Write the array jmatrix{spin_a,spin_c}=spec_string{5}; end % Inform the user disp(['Estimated two-bond J-coupling from ' pad([aa_typ{spin_a} '(' num2str(aa_num(spin_a)) '):' pdb_id{spin_a}],19) ' to '... pad([aa_typ{spin_c} '(' num2str(aa_num(spin_c)) '):' pdb_id{spin_c}],19) ' '... pad(num2str(jmatrix{spin_a,spin_c},'%5.1f'),6,'left') ' Hz']); end end end end % Get all connected subgraphs up to size 4 subgraphs=dfpt(sparse(proxmatrix),4); % Remove T-shaped subgraphs kill_mask=false(size(subgraphs,1),1); for n=1:size(subgraphs,1) if any(sum(proxmatrix(subgraphs(n,:),subgraphs(n,:)))==4) kill_mask(n)=true(); end end subgraphs(kill_mask,:)=[]; % Generic Karplus coefficients J_CCCC_AL=[4.48 0.18 -0.57]; % Aliphatic C-C-C-C from http://dx.doi.org/10.1016/j.carres.2007.02.023 J_CCCH_AL=[3.83 -0.90 3.81]; % Aliphatic C-C-C-H from http://onlinelibrary.wiley.com/doi/10.1002/anie.198204491/pdf J_HCCH_AL=[4.22 -0.50 4.50]; % Aliphatic H-C-C-H from http://pubs.acs.org/doi/abs/10.1021/ja00901a059 J_CCCC_AR=[0.00 0.00 5.00]; % Aromatic C-C-C-C from [literature reference] J_CCCH_AR=[0.00 0.00 8.20]; % Aromatic C-C-C-H from [literature reference] J_HCCH_AR=[0.00 0.00 10.2]; % Aromatic H-C-C-H from [literature reference] % List of ordered connected quads (sorted atoms, bonding order, Karplus coefficients) quads_database={... % Backbone and its vicinity 'CA_CB_CG1_HA', 4, 1, 2, 3, [7.10 -1.00 0.70]; % Vuister, G. W. "J-couplings. Measurement and Usage in Structure Determination." [chi1 side-chain] 'CA_CB_CG2_HA', 4, 1, 2, 3, [7.10 -1.00 0.70]; % Vuister, G. W. "J-couplings. Measurement and Usage in Structure Determination." [chi1 side-chain] 'CA_CB_CG_H', 1, 2, 3, 4, [4.03 -0.87 4.50]; % http://dx.doi.org/10.1002/mrc.1260280513 chi2 ??? need to look at it later. 'CA_CB_CG1_HA', 4, 1, 2, 3, [10.2 -1.30 0.20]; % http://dx.doi.org/10.1021/bi00585a003 (checked) 'CA_CB_CG2_HA', 4, 1, 2, 3, [10.2 -1.30 0.20]; % http://dx.doi.org/10.1021/bi00585a003 (checked) 'CA_CB_CG1_HA', 4, 1, 2, 3, [10.2 -1.30 0.20]; % A. DeMarco and M. Llinas, Biochemistry 18, 3846 (1979) [chi1 side-chain] (checked) 'CA_CB_CG2_HA', 4, 1, 2, 3, [10.2 -1.30 0.20]; % A. DeMarco and M. Llinas, Biochemistry 18, 3846 (1979) [chi1 side-chain] (checked) 'CA_CB_CG_HA', 4, 1, 2, 3, [10.2 -1.30 0.20]; % A. DeMarco and M. Llinas, Biochemistry 18, 3846 (1979) [chi1 side-chain] (checked) 'C_CA_CB_CG', 1, 2, 3, 4, [3.42 -0.59 0.17]; % http://pubs.acs.org/doi/pdf/10.1021/ja029972s [chi1 side-chain] (checked) 'C_CA_CB_CG1', 1, 2, 3, 4, [3.42 -0.59 0.17]; % http://pubs.acs.org/doi/pdf/10.1021/ja029972s [chi1 side-chain] (checked) 'C_CA_CB_CG2', 1, 2, 3, 4, [3.30 -0.51 0.04]; % http://pubs.acs.org/doi/pdf/10.1021/ja029972s [chi1 side-chain] (checked) 'CA_CB_CG_N', 4, 1, 2, 3, [2.64 0.26 -0.22]; % http://pubs.acs.org/doi/pdf/10.1021/ja029972s [chi1 side-chain] (checked) 'CA_CB_CG1_N', 4, 1, 2, 3, [2.22 0.25 -0.06]; % http://pubs.acs.org/doi/pdf/10.1021/ja029972s [chi1 side-chain] (checked) 'CA_CB_CG2_N', 4, 1, 2, 3, [2.01 0.21 -0.12]; % http://pubs.acs.org/doi/pdf/10.1021/ja029972s [chi1 side-chain] (checked) 'C_CA_CB_HB3', 1, 2, 3, 4, [7.2 -2.04 0.60]; % http://pubs.acs.org/doi/pdf/10.1021/ja00528a004 [chi1 side-chain] (checked) 'C_CA_CB_HB2', 1, 2, 3, 4, [7.2 -2.04 0.60]; % http://pubs.acs.org/doi/pdf/10.1021/ja00528a004 [chi1 side-chain] (checked) 'C_CA_CB_HB1', 1, 2, 3, 4, [7.2 -2.04 0.60]; % http://pubs.acs.org/doi/pdf/10.1021/ja00528a004 [chi1 side-chain] (checked) 'C_CA_CB_HB', 1, 2, 3, 4, [7.2 -2.04 0.60]; % http://pubs.acs.org/doi/pdf/10.1021/ja00528a004 [chi1 side-chain] (checked) 'CA_CB_HA_HB', 3, 1, 2, 4, [ 9.5 -1.60 1.80]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HA_HB1', 3, 1, 2, 4, [ 9.5 -1.60 1.80]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HA_HB2', 3, 1, 2, 4, [ 9.5 -1.60 1.80]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HA_HB3', 3, 1, 2, 4, [ 9.5 -1.60 1.80]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HB1_N', 4, 1, 2, 3, [-4.40 1.20 0.10]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HB2_N', 4, 1, 2, 3, [-4.40 1.20 0.10]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HB3_N', 4, 1, 2, 3, [-4.40 1.20 0.10]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_CB_HB_N', 4, 1, 2, 3, [-4.40 1.20 0.10]; % http://dx.doi.org/10.1006/jmbi.1998.1911 [chi1 side-chain] (checked) 'CA_H_HA3_N', 2, 4, 1, 3, [6.51 -1.76 1.60]; % http://dx.doi.org/10.1021/ja00070a024 [backbone phi] (checked) 'CA_H_HA_N', 2, 4, 1, 3, [6.51 -1.76 1.60]; % http://dx.doi.org/10.1021/ja00070a024 [backbone phi] (checked) 'CA_H_HA2_N', 2, 4, 1, 3, [6.51 -1.76 1.60]; % http://dx.doi.org/10.1021/ja00070a024 [backbone phi] (checked) 'CA_CB_H_N', 3, 4, 1, 2, [3.06 -0.074 0.13]; % http://pubs.acs.org/doi/pdf/10.1021/ja970067v [backbone phi] (checked) 'C_CA_H_N', 1, 2, 4, 3, [4.29 -1.01 0.00]; % http://pubs.acs.org/doi/pdf/10.1021/ja001798p [backbone phi] (checked) 'C_CA_HA2_N', 1, 4, 2, 3, [3.72 -2.18 1.28]; % http://pubs.acs.org/doi/pdf/10.1021/ja001798p [backbone phi] (checked) 'C_CA_HA3_N', 1, 4, 2, 3, [3.72 -2.18 1.28]; % http://pubs.acs.org/doi/pdf/10.1021/ja001798p [backbone phi] (checked) 'C_CA_HA_N', 1, 4, 2, 3, [3.72 -2.18 1.28]; % http://pubs.acs.org/doi/pdf/10.1021/ja001798p [backbone phi] (checked) 'C_CA_CB_N', 1, 4, 2, 3, [1.59 -0.67 0.27]; % http://spin.niddk.nih.gov/bax/lit/508/244.pdf [backbone phi] (checked) 'C_C_CA_N', 1, 4, 3, 2, [1.33 -0.88 0.06]; % http://pubs.acs.org/doi/pdf/10.1021/ja9616239 [backbone phi] (checked) 'C_CB_CA_N', 1, 4, 3, 2, [1.59 -0.67 0.27]; % http://spin.niddk.nih.gov/bax/lit/508/244.pdf [backbone phi] (checked) 'C_CA_HA2_N', 4, 1, 2, 3, [-0.88 -0.61 -0.27]; % http://pubs.acs.org/doi/pdf/10.1021/ja00111a021 [backbone psi] (checked) 'C_CA_HA3_N', 4, 1, 2, 3, [-0.88 -0.61 -0.27]; % http://pubs.acs.org/doi/pdf/10.1021/ja00111a021 [backbone psi] (checked) 'C_CA_HA_N', 4, 1, 2, 3, [-0.88 -0.61 -0.27]; % http://pubs.acs.org/doi/pdf/10.1021/ja00111a021 [backbone psi] (checked) 'C_CA_N_N', 3, 2, 1, 4, [0.0 0.0 0.0]; % To be filled in 'C_CA_N_N', 4, 2, 1, 3, [0.0 0.0 0.0]; % To be filled in 'C_CB_CA_N', 4, 1, 3, 2, [0.0 0.0 0.0]; % To be filled in 'C_CA_CA_N', 2, 1, 4, 3, [0.0 0.0 0.0]; % To be filled in % Histidine ring (GIAO DFT M06/cc-pVTZ) 'CD2_CG_HD2_ND1', 3, 1, 2, 4, [0.0 0.0 2.8]; 'CD2_CG_ND1_NE2', 4, 1, 2, 3, [0.0 0.0 0.0]; 'CB_CG_HB2_ND1', 3, 1, 2, 4, [0.0 0.0 0.0]; 'CB_CG_HB3_ND1', 3, 1, 2, 4, [0.0 0.0 0.0]; 'CB_CE1_CG_ND1', 1, 3, 4, 2, [0.0 0.0 2.3]; 'CD2_CE1_HE1_NE2', 3, 2, 4, 1, [0.0 0.0 4.9]; 'CD2_CE1_HD2_NE2', 3, 1, 4, 2, [0.0 0.0 6.6]; 'CD2_CE1_CG_NE2', 3, 1, 4, 2, [0.0 0.0 1.0]; 'CD2_CE1_ND1_NE2', 1, 4, 2, 3, [0.0 0.0 0.0]; 'CD2_CE1_CG_ND1', 1, 3, 4, 2, [0.0 0.0 3.4]; 'CE1_CG_HE1_ND1', 3, 1, 4, 2, [0.0 0.0 7.0]; 'CE1_CG_ND1_NE2', 2, 3, 1, 4, [0.0 0.0 1.4]; 'CA_CB_CG_ND1', 1, 2, 3, 4, [0.0 0.0 1.0]; 'CB_CD2_CG_NE2', 1, 3, 2, 4, [0.0 0.0 0.0]; 'CE1_HD1_HE1_ND1', 2, 4, 1, 3, [0.0 0.0 3.9]; 'CE1_HD1_ND1_NE2', 2, 3, 1, 4, [0.0 0.0 3.3]; 'CD2_CG_HD1_ND1', 3, 4, 2, 1, [0.0 0.0 6.1]; 'CB_CG_HD1_ND1', 3, 4, 2, 1, [0.0 0.0 1.0]; % Proline ring (GIAO DFT M06/cc-pVTZ) 'CA_CD_HA_N', 3, 1, 4, 2, [0.0 0.0 0.0]; 'CA_CD_HD2_N', 1, 4, 2, 3, [0.0 0.0 2.5]; 'CA_CD_HD3_N', 1, 4, 2, 3, [0.0 0.0 2.5]; 'CA_CD_CG_N', 1, 4, 2, 3, [0.0 0.0 0.0]; 'CD_CG_HG2_N', 3, 2, 1, 4, [0.0 0.0 0.0]; 'CD_CG_HG3_N', 3, 2, 1, 4, [0.0 0.0 0.0]; 'C_CD_CG_N', 1, 4, 2, 3, [0.0 0.0 2.5]; 'C_CA_CD_N', 1, 2, 4, 3, [0.0 0.0 1.1]; 'C_CD_HD2_N', 1, 4, 2, 3, [0.0 0.0 1.0]; 'C_CD_HD3_N', 1, 4, 2, 3, [0.0 0.0 1.0]; 'CA_CB_CD_N', 2, 1, 4, 3, [0.0 0.0 0.0]; 'CB_CD_CG_N', 4, 2, 3, 1, [0.0 0.0 1.1]; % Generic aliphatics 'CA_CB_CD1_CG', 1, 2, 4, 3, J_CCCC_AL; 'CA_CB_CD1_CG1', 1, 2, 4, 3, J_CCCC_AL; 'CA_CB_CD2_CG', 1, 2, 4, 3, J_CCCC_AL; 'CA_CB_CD_CG', 1, 2, 4, 3, J_CCCC_AL; 'CA_CB_CG2_HG21', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG_HG3', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG1_HG11', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG1_HG12', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG1_HG13', 1, 2, 3, 4, J_CCCH_AL; 'CD2_CG_HD21_HG', 4, 2, 1, 3, J_HCCH_AL; 'CA_CB_CG2_HG22', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG2_HG23', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG_HG', 1, 2, 3, 4, J_CCCH_AL; 'CA_CB_CG_HG2', 1, 2, 3, 4, J_CCCH_AL; 'CD_CG_HD3_HG2', 4, 2, 1, 3, J_HCCH_AL; 'CB_CD1_CG1_HD11', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD1_CG1_CG2', 2, 3, 1, 4, J_CCCC_AL; 'CB_CD1_CG1_HB', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD1_CG1_HD12', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD1_CG1_HD13', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD1_CG_HB2', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD1_CG_HB3', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD1_CG_HD1', 1, 2, 3, 4, J_CCCH_AL; 'CB_CD1_CG_HD11', 1, 2, 3, 4, J_CCCH_AL; 'CB_CD1_CG_HD12', 1, 2, 3, 4, J_CCCH_AL; 'CB_CD1_CG_HD13', 1, 2, 3, 4, J_CCCH_AL; 'CB_CD2_CE2_CG', 1, 4, 2, 3, J_CCCC_AL; 'CB_CD2_CG_HB2', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD2_CG_HB3', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD2_CG_HD2', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD2_CG_HD21', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD2_CG_HD22', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD2_CG_HD23', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD_CG_HD3', 1, 3, 2, 4, J_CCCH_AL; 'CB_CD_CE_CG', 1, 4, 2, 3, J_CCCC_AL; 'CB_CD_CG_HB2', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD_CG_HB3', 4, 1, 3, 2, J_CCCH_AL; 'CB_CD_CG_HD2', 1, 3, 2, 4, J_CCCH_AL; 'CB_CG1_CG2_HG11', 4, 2, 1, 3, J_CCCH_AL; 'CB_CG1_CG2_HG12', 4, 2, 1, 3, J_CCCH_AL; 'CB_CG1_CG2_HG13', 4, 2, 1, 3, J_CCCH_AL; 'CB_CG1_CG2_HG21', 4, 3, 1, 2, J_CCCH_AL; 'CB_CG1_CG2_HG22', 4, 3, 1, 2, J_CCCH_AL; 'CB_CG1_CG2_HG23', 4, 3, 1, 2, J_CCCH_AL; 'CB_CG1_HB_HG11', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG1_HB_HG12', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG1_HB_HG13', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG2_HB_HG21', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG2_HB_HG22', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG2_HB_HG23', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG_HB2_HG', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG_HB2_HG2', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG_HB2_HG3', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG_HB3_HG', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG_HB3_HG2', 4, 2, 1, 3, J_HCCH_AL; 'CB_CG_HB3_HG3', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CD2_CG_HD1', 4, 1, 3, 2, J_CCCH_AL; 'CD1_CD2_CG_HD11', 4, 1, 3, 2, J_CCCH_AL; 'CD1_CD2_CG_HD12', 4, 1, 3, 2, J_CCCH_AL; 'CD1_CD2_CG_HD13', 4, 1, 3, 2, J_CCCH_AL; 'CD1_CD2_CG_HD2', 4, 2, 3, 1, J_CCCH_AL; 'CD1_CD2_CG_HD21', 4, 2, 3, 1, J_CCCH_AL; 'CD1_CD2_CG_HD22', 4, 2, 3, 1, J_CCCH_AL; 'CD1_CD2_CG_HD23', 4, 2, 3, 1, J_CCCH_AL; 'CD1_CD2_CE1_CG', 3, 1, 4, 2, J_CCCC_AL; 'CD1_CD2_CE2_CG', 1, 4, 2, 3, J_CCCC_AL; 'CD1_CG1_HD11_HG12', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG1_HD11_HG13', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG1_HD12_HG12', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG1_HD12_HG13', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG1_HD13_HG12', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG1_HD13_HG13', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG_HD11_HG', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG_HD12_HG', 4, 2, 1, 3, J_HCCH_AL; 'CD1_CG_HD13_HG', 4, 2, 1, 3, J_HCCH_AL; 'CD_CG_HD3_HG3', 4, 2, 1, 3, J_HCCH_AL; 'CD2_CG_HD22_HG', 4, 2, 1, 3, J_HCCH_AL; 'CD2_CG_HD23_HG', 4, 2, 1, 3, J_HCCH_AL; 'CD_CE_CG_HE2', 4, 2, 1, 3, J_CCCH_AL; 'CD_CE_CG_HE3', 4, 2, 1, 3, J_CCCH_AL; 'CD_CE_CG_HG2', 4, 3, 1, 2, J_CCCH_AL; 'CD_CE_CG_HG3', 4, 3, 1, 2, J_CCCH_AL; 'CD_CE_HD2_HE2', 4, 2, 1, 3, J_HCCH_AL; 'CD_CE_HD2_HE3', 4, 2, 1, 3, J_HCCH_AL; 'CD_CE_HD3_HE2', 4, 2, 1, 3, J_HCCH_AL; 'CD_CE_HD3_HE3', 4, 2, 1, 3, J_HCCH_AL; 'CD_CG_HD2_HG2', 4, 2, 1, 3, J_HCCH_AL; 'CD_CG_HD2_HG3', 4, 2, 1, 3, J_HCCH_AL; % Generic aromatics 'CE1_CE2_CZ_HE1', 4, 1, 3, 2, J_CCCH_AR; 'CE1_CE2_CZ_HE2', 4, 2, 3, 1, J_CCCH_AR; 'CE1_CZ_HE1_HZ', 4, 2, 1, 3, J_HCCH_AR; 'CE2_CZ_HE2_HZ', 4, 2, 1, 3, J_HCCH_AR 'CD2_CE2_CG_CZ', 3, 1, 2, 4, J_CCCC_AR; 'CB_CD1_CE1_CG', 1, 4, 2, 3, J_CCCC_AR; 'CD2_CE1_CE2_CZ', 1, 3, 4, 2, J_CCCC_AR; 'CD1_CE1_CG_CZ', 3, 1, 2, 4, J_CCCC_AR; 'CD1_CE1_CG_HE1', 4, 2, 1, 3, J_CCCH_AR; 'CD1_CE1_CZ_HD1', 4, 1, 2, 3, J_CCCH_AR; 'CD1_CE1_CZ_HZ', 4, 3, 2, 1, J_CCCH_AR; 'CD2_CE2_CG_HE2', 4, 2, 1, 3, J_CCCH_AR; 'CD2_CE2_CZ_HD2', 4, 1, 2, 3, J_CCCH_AR; 'CD2_CE2_CZ_HZ', 4, 3, 2, 1, J_CCCH_AR; 'CD2_CE2_HD2_HE2', 3, 1, 2, 4, J_HCCH_AR; 'CD1_CE1_HD1_HE1', 3, 1, 2, 4, J_HCCH_AR; 'CD1_CE1_CE2_CZ', 1, 2, 4, 3, J_CCCC_AR; % Generic amides 'CB_CG_HB2_ND2', 3, 1, 2, 4, [3.1 -0.6 0.4]; % http://dx.doi.org/10.1016/j.carres.2007.02.023 'CB_CG_HB3_ND2', 3, 1, 2, 4, [3.1 -0.6 0.4]; % http://dx.doi.org/10.1016/j.carres.2007.02.023 'CB_CG_HD21_ND2', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CB_CG_HD22_ND2', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HE21_NE2', 3, 4, 1, 2, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HE22_NE2', 3, 4, 1, 2, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HG2_NE2', 3, 2, 1, 4, [3.1 -0.6 0.4]; % http://dx.doi.org/10.1016/j.carres.2007.02.023 'CB_CD_CG_NE2', 1, 3, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_CB_CG_ND2', 1, 2, 3, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HG3_NE2', 3, 2, 1, 4, [3.1 -0.6 0.4]; % http://dx.doi.org/10.1016/j.carres.2007.02.023 % Extra parameters highlighted by the Boston visit 'CZ_HH22_NH1_NH2', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH21_NH1_NH2', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH12_NH1_NH2', 2, 3, 1, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH11_NH1_NH2', 2, 3, 1, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH22_NE_NH2', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH21_NE_NH2', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH12_NE_NH1', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HH11_NE_NH1', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HE_NE_NH2', 2, 3, 1, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CZ_HE_NE_NH1', 2, 3, 1, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CZ_NE_NH2', 1, 3, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CZ_NE_NH1', 1, 3, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CZ_HD3_NE', 3, 1, 4, 2, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CZ_HD2_NE', 3, 1, 4, 2, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_HD3_HE_NE', 2, 1, 4, 3, [4.22 -0.50 4.50]; % Tentative, needs checking 'CD_HD2_HE_NE', 2, 1, 4, 3, [4.22 -0.50 4.50]; % Tentative, needs checking 'CD_CG_CZ_NE', 2, 1, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HE_NE', 2, 1, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HG3_NE', 3, 2, 1, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CG_HG2_NE', 3, 2, 1, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CB_CD_CG_NE', 1, 3, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CE_HE3_HZ3_NZ', 2, 1, 4, 3, [6.51 -1.76 1.60]; % Tentative, needs checking 'CE_HE2_HZ3_NZ', 2, 1, 4, 3, [6.51 -1.76 1.60]; % Tentative, needs checking 'CE_HE3_HZ2_NZ', 2, 1, 4, 3, [6.51 -1.76 1.60]; % Tentative, needs checking 'CE_HE2_HZ2_NZ', 2, 1, 4, 3, [6.51 -1.76 1.60]; % Tentative, needs checking 'CE_HE3_HZ1_NZ', 2, 1, 4, 3, [6.51 -1.76 1.60]; % Tentative, needs checking 'CE_HE2_HZ1_NZ', 2, 1, 4, 3, [6.51 -1.76 1.60]; % Tentative, needs checking 'CD_CE_HZ3_NZ', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CE_HZ2_NZ', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CE_HZ1_NZ', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CE_HD3_NZ', 3, 1, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CE_HD2_NZ', 3, 1, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CD_CE_CG_NZ', 3, 1, 2, 4, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_H3_HA_N', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_H2_HA_N', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_H1_HA_N', 2, 4, 1, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_CB_H3_N', 2, 1, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_CB_H2_N', 2, 1, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'CA_CB_H1_N', 2, 1, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'C_CA_H3_N', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'C_CA_H2_N', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking 'C_CA_H1_N', 1, 2, 4, 3, [0.0 0.0 0.0]; % Tentative, needs checking % Tryptophan side chain (GIAO DFT M06/cc-pVTZ data in PCM water) 'CH2_CZ3_HH2_HZ3' 3, 1, 2, 4, [0.0 0.0 9.41]; 'CH2_CZ2_HH2_HZ2' 3, 1, 2, 4, [0.0 0.0 10.87]; 'CH2_CZ2_CZ3_HZ3' 2, 1, 3, 4, [0.0 0.0 8.31]; 'CH2_CZ2_CZ3_HZ2' 3, 1, 2, 4, [0.0 0.0 7.63]; 'CE3_CZ3_HE3_HZ3' 3, 1, 2, 4, [0.0 0.0 11.09]; 'CE3_CH2_CZ3_HH2' 1, 3, 2, 4, [0.0 0.0 8.12]; 'CE3_CH2_CZ3_HE3' 2, 3, 1, 4, [0.0 0.0 8.56]; 'CE3_CH2_CZ2_CZ3' 1, 4, 2, 3, [0.0 0.0 8.07]; 'CE2_CH2_CZ2_HH2' 1, 3, 2, 4, [0.0 0.0 9.67]; 'CE2_CH2_CZ2_CZ3' 1, 3, 2, 4, [0.0 0.0 10.44]; 'CE2_CZ2_HZ2_NE1' 4, 1, 2, 3, [0.0 0.0 1.36]; 'CE2_CZ2_HE1_NE1' 2, 1, 4, 3, [0.0 0.0 1.31]; 'CE2_CH2_CZ2_NE1' 2, 3, 1, 4, [0.0 0.0 1.48]; 'CD2_CE3_CZ3_HZ3' 1, 2, 3, 4, [0.0 0.0 8.32]; 'CD2_CE3_CH2_CZ3' 1, 2, 4, 3, [0.0 0.0 8.85]; 'CD2_CE2_CZ2_HZ2' 1, 2, 3, 4, [0.0 0.0 5.17]; 'CD2_CE2_CH2_CZ2' 1, 2, 4, 3, [0.0 0.0 8.85]; 'CD2_CE2_CE3_HE3' 2, 1, 3, 4, [0.0 0.0 7.92]; 'CD2_CE2_CE3_CZ3' 2, 1, 3, 4, [0.0 0.0 10.44]; 'CD2_CE2_CE3_CZ2' 3, 1, 2, 4, [0.0 0.0 8.07]; 'CD2_CE2_HE1_NE1' 1, 2, 4, 3, [0.0 0.0 6.80]; 'CD2_CE2_CE3_NE1' 3, 1, 2, 4, [0.0 0.0 1.01]; 'CD1_HD1_HE1_NE1' 2, 1, 4, 3, [0.0 0.0 3.64]; 'CD1_CE2_HD1_NE1' 2, 4, 1, 3, [0.0 0.0 6.87]; 'CD1_CE2_CZ2_NE1' 3, 2, 4, 1, [0.0 0.0 2.34]; 'CD1_CD2_CE2_NE1' 2, 3, 4, 1, [0.0 0.0 2.29]; 'CD2_CE3_CG_HE3' 3, 1, 2, 4, [0.0 0.0 4.04]; 'CD2_CE3_CG_CZ3' 3, 1, 2, 4, [0.0 0.0 4.69]; 'CD2_CE2_CG_CZ2' 3, 1, 2, 4, [0.0 0.0 2.56]; 'CD2_CE2_CG_NE1' 3, 1, 2, 4, [0.0 0.0 2.30]; 'CD1_CG_HE1_NE1' 2, 1, 4, 3, [0.0 0.0 5.75]; 'CD1_CE2_CG_NE1' 3, 1, 4, 2, [0.0 0.0 3.34]; 'CD1_CD2_CE3_CG' 1, 4, 2, 3, [0.0 0.0 5.66]; 'CD1_CD2_CG_NE1' 2, 3, 1, 4, [0.0 0.0 3.54]; 'CB_CD2_CE3_CG' 1, 4, 2, 3, [0.0 0.0 1.70]; 'CB_CD1_CG_NE1' 1, 3, 2, 4, [0.0 0.0 1.21]; }; % Collision detection exceptions (TRP, HIS and PRO, where two-bond and three-bond couplings collide) allowed_collision_list={'CD2_CE1_ND1_NE2','CE1_CG_ND1_NE2','CD2_CE1_CG_ND1','CD1_CE1_CG_CZ',... 'CD1_CD2_CE2_CG','CA_CB_CD_CG','CA_CD_CG_N','CA_CB_CD_N','CD2_CE1_CG_NE2',... 'CD2_CE2_CH2_CZ2','CD2_CE2_CE3_CZ3','CD1_CE2_CG_NE1','CA_CB_CG2_HA',... 'CA_CB_CG1_HA'}; % Loop over subgraphs disp(' '); disp('############# THREE-BOND J-COUPLING SUMMARY ###############'); for n=1:size(subgraphs,1) % Extract labels, residues and numbers spin_labels=pdb_id(subgraphs(n,:)); spin_numbers=numbers(subgraphs(n,:)); spin_resnames=aa_typ(subgraphs(n,:)); spin_resnums=aa_num(subgraphs(n,:)); % Index the spins [spin_labels,index]=sort(spin_labels); spin_numbers=spin_numbers(index); spin_resnames=spin_resnames(index); spin_resnums=spin_resnums(index); % Consult the database if numel(spin_labels)==1 % Inform the user if no J-coupling found disp(['WARNING: solitary spin detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1}]); elseif numel(spin_labels)==2 % Inform the user if no J-coupling found disp(['WARNING: isolated spin pair detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1} ' and ' ... spin_resnames{2} '(' num2str(spin_resnums(2)) '):' spin_labels{2}]); elseif numel(spin_labels)==3 % Inform the user if no J-coupling found disp(['WARNING: isolated spin triad detected, ' spin_resnames{1} '(' num2str(spin_resnums(1)) '):' spin_labels{1} ', '... spin_resnames{2} '(' num2str(spin_resnums(2)) '):' spin_labels{2} ' and '... spin_resnames{3} '(' num2str(spin_resnums(3)) '):' spin_labels{3}]); else % Assemble specifiction string spec_strings=quads_database(strcmp([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4}],quads_database(:,1)),:); % Complain if nothing found if isempty(spec_strings) disp(['WARNING: unknown atom quad or unphysical proximity, ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4} ' in amino acids '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) '), '... spin_resnames{4} '(' num2str(spin_resnums(4)) ')']); else % Loop over specifications for k=1:size(spec_strings,1) % Extract spin numbers spin_a=spin_numbers(spec_strings{k,2}); spin_b=spin_numbers(spec_strings{k,3}); spin_c=spin_numbers(spec_strings{k,4}); spin_d=spin_numbers(spec_strings{k,5}); % Match bonding pattern if proxmatrix(spin_a,spin_b)&&proxmatrix(spin_b,spin_c)&&proxmatrix(spin_c,spin_d) % Get Karplus coefficients A=spec_strings{k,6}(1); B=spec_strings{k,6}(2); C=spec_strings{k,6}(3); % Get dihedral angle theta=dihedral(coords{spin_a},coords{spin_b},coords{spin_c},coords{spin_d}); % Assign the J-coupling if (~isempty(jmatrix{spin_a,spin_d}))&&(~ismember([spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4}],allowed_collision_list)) % Complain and bomb out error(['atom quad: ' spin_labels{1} '_' spin_labels{2} '_' spin_labels{3} '_' spin_labels{4} ' in amino acids '... spin_resnames{1} '(' num2str(spin_resnums(1)) '), '... spin_resnames{2} '(' num2str(spin_resnums(2)) '), '... spin_resnames{3} '(' num2str(spin_resnums(3)) '), '... spin_resnames{4} '(' num2str(spin_resnums(4)) ') collides with other data.']); else % Write the array jmatrix{spin_a,spin_d}=A*cosd(theta)^2+B*cosd(theta)+C; % Inform the user disp(['Estimated three-bond J-coupling from ' pad([aa_typ{spin_a} '(' num2str(aa_num(spin_a)) '):' pdb_id{spin_a}],19) ' to '... pad([aa_typ{spin_d} '(' num2str(aa_num(spin_d)) '):' pdb_id{spin_d}],19) ' '... pad(num2str(jmatrix{spin_a,spin_d},'%5.1f'),6,'left') ' Hz']); end end end end end end end % Consistency enforcement function grumble(aa_num,aa_typ,pdb_id,coords) if ~isnumeric(aa_num) error('aa_num must be a vector of positive integers.'); end if ~iscell(aa_typ) error('aa_typ must be a cell array of strings.'); end if ~iscell(pdb_id) error('pdb_id must be a cell array of strings.'); end if ~iscell(coords) error('coords must be a cell array of 3-vectors.'); end if (numel(aa_num)~=numel(aa_typ))||... (numel(aa_typ)~=numel(pdb_id))||... (numel(pdb_id)~=numel(coords)) error('all four inputs must have the same number of elements.'); end end % Niels Bohr, on Dirac's equation: % % "Simply put an explanation of the theory on a poster, tack it up on a tree % in the jungle, and any elephant (a beast noted for its wisdom) that passed % by would immediately become so engrossed trying to figure it out that it % could be packed up and delivered to the Copenhagen Zoo before it realized % anything had happened."
github
tsajed/nmr-pred-master
ocparse.m
.m
nmr-pred-master/spinach/etc/ocparse.m
1,903
utf_8
4c4c8607b6468e09df40c3b31e69d269
% ORCA cube file parser. Extracts the normalised probability density and % the associated metric information from ORCA cube files. Syntax: % % [density,ext,dx,dy,dz]=ocparse(filename) % % Outputs: % % density - probability density cube with dimensions % ordered as [X Y Z] % % ext - grid extents in Angstrom, ordered as % [xmin xmax ymin ymax zmin zmax] % % dx,dy,dz - grid steps in the three directions, Angstrom % % [email protected] % [email protected] function [density,ext,dx,dy,dz]=ocparse(filename,pad_factor) % Inform the user disp('Parsing ORCA cube...'); % Parse the file A=importdata(filename); % Get the number of points along [x y z] npts=str2num(A.textdata{2}); %#ok<ST2NM> % Make the probability density cube density=reshape(abs(A.data),npts(2),npts(3),npts(1)); density=permute(density,[2 3 1]); % Get the corner coordinates corner_xyz=str2num(A.textdata{3}); %#ok<ST2NM> % Get the grid spacing vector dxdydz=str2num(A.textdata{4}); %#ok<ST2NM> dx=dxdydz(1); dy=dxdydz(2); dz=dxdydz(3); % Integrate and normalise probability density total_prob=simps(simps(simps(density)))*dx*dy*dz; density=density/total_prob; % Compute grid extents ext=[corner_xyz(1) (corner_xyz(1)+(npts(1)-1)*dx)... corner_xyz(2) (corner_xyz(2)+(npts(2)-1)*dy)... corner_xyz(3) (corner_xyz(3)+(npts(3)-1)*dz)]; % Pad the density with zeros density=padarray(density,pad_factor*size(density),0,'both'); ext=(2*pad_factor+1)*ext; end % There is a cult of ignorance in the United States, and there % has always been. The strain of anti-intellectualism has been % a constant thread winding its way through our political and % cultural life, nurtured by the false notion that democracy % means that 'my ignorance is just as good as your knowledge'. % % Isaac Asimov
github
tsajed/nmr-pred-master
write_movie.m
.m
nmr-pred-master/spinach/interfaces/write_movie.m
501
utf_8
7cd0058285259cf5914ed341292b8b1f
% Orbits the camera around a 3D plot and writes a movie. % % [email protected] function write_movie(file_name) % Open the video writer object writerObj=VideoWriter(file_name,'MPEG-4'); open(writerObj); % Orbit the camera for n=1:360 % Grab the frame writeVideo(writerObj,getframe(gcf)); pause(0.05); camorbit(1,0); end % Close the writer object close(writerObj); end % Love is [...] friendship inspired by beauty. % % Marcus Tullius Cicero
github
tsajed/nmr-pred-master
assume.m
.m
nmr-pred-master/spinach/kernel/assume.m
22,636
utf_8
2293a974f8af42896f8756162a65df48
% Sets case-specific assumptions for various simulation contexts. This % function determines the behaviour of the Hamiltonian generation func- % tion and should be called before the Hamiltonian is requested. % % The function text is self-explanatory -- interaction strength parame- % ters are set in each section according to the physical requirements % of each specific simulation context. Syntax: % % spin_system=assume(spin_system,assumptions,retention) % % where assumptions may be set to 'nmr' (high-field NMR), 'esr' (elec- % tron rotating frame ESR), 'deer' (DEER spectroscopy), and some other % more specialized assumption sets used by other Spinach functions. % % The retention argument may be set to 'zeeman' (in which case all spin- % spin couplings are ignored) or 'couplings' (in which case all Zeeman % interactions are ignored). % % [email protected] function spin_system=assume(spin_system,assumptions,retention) % Check consistency if nargin==2 grumble(assumptions); elseif nargin==3 grumble(assumptions,retention); else error('incorrect number of input arguments.'); end % Report to the user report(spin_system,['working assumptions for coherent Hamiltonian set to "' assumptions '".']); % Preallocate the arrays spin_system.inter.zeeman.strength=cell(1,spin_system.comp.nspins); spin_system.inter.coupling.strength=cell(spin_system.comp.nspins); % Set the approximations switch assumptions case {'nmr'} % Do the reporting report(spin_system,'rotating frame approximation for electrons.'); report(spin_system,'rotating frame approximation for nuclei.'); report(spin_system,'secular terms for electron Zeeman interactions.'); report(spin_system,'secular terms for nuclear Zeeman interactions.'); report(spin_system,'secular coupling terms for spins belonging to the same species.'); report(spin_system,'weak coupling terms for spins belonging to different species.'); report(spin_system,'secular coupling terms for quadratic couplings.'); % Process Zeeman interactions for n=1:spin_system.comp.nspins % All Zeeman interactions should be secular spin_system.inter.zeeman.strength{n}='secular'; end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n},spin_system.comp.isotopes{k}) % Couplings between spins of the same type should be secular spin_system.inter.coupling.strength{n,k}='secular'; else % Couplings between spins of different types should be weak spin_system.inter.coupling.strength{n,k}='weak'; end end end case {'esr'} % Do the reporting report(spin_system,'rotating frame approximation for electrons.'); report(spin_system,'laboratory frame simulation for nuclei.'); report(spin_system,'secular terms for electron Zeeman interactions.'); report(spin_system,'all terms for nuclear Zeeman interactions.'); report(spin_system,'secular terms for inter-electron couplings.'); report(spin_system,'secular terms for electron zero-field splittings.'); report(spin_system,'weak and pseudosecular terms for hyperfine couplings.'); report(spin_system,'all terms for inter-nuclear couplings.'); report(spin_system,'all terms for nuclear quadrupolar couplings.'); % Process Zeeman interactions for n=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n}(1),'E') % Electron Zeeman interactions should be secular spin_system.inter.zeeman.strength{n}='secular'; else % Full Zeeman tensors should be used for nuclei spin_system.inter.zeeman.strength{n}='full'; end end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n}(1),'E')&&(~strcmp(spin_system.comp.isotopes{k}(1),'E')) % Couplings from electrons to nuclei should be left-secular spin_system.inter.coupling.strength{n,k}='z*'; elseif strcmp(spin_system.comp.isotopes{k}(1),'E')&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Couplings from nuclei to electrons should be right-secular spin_system.inter.coupling.strength{n,k}='*z'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E')) % Couplings between electrons should be secular spin_system.inter.coupling.strength{n,k}='secular'; else % Couplings between nuclei should be strong spin_system.inter.coupling.strength{n,k}='strong'; end end end case {'deer'} % Do the reporting report(spin_system,'rotating frame approximation for electrons.'); report(spin_system,'laboratory frame simulation for nuclei.'); report(spin_system,'secular terms for electron Zeeman interactions.'); report(spin_system,'all terms for nuclear Zeeman interactions.'); report(spin_system,'weak terms for inter-electron couplings.'); report(spin_system,'secular terms for electron zero-field splittings.'); report(spin_system,'secular and pseudosecular terms for hyperfine couplings.'); report(spin_system,'all terms for inter-nuclear couplings.'); report(spin_system,'all terms for nuclear quadrupolar couplings.'); % Process Zeeman interactions for n=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n}(1),'E') % Electron Zeeman interactions should be secular spin_system.inter.zeeman.strength{n}='secular'; else % Full Zeeman tensors should be used for nuclei spin_system.inter.zeeman.strength{n}='full'; end end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n}(1),'E')&&(~strcmp(spin_system.comp.isotopes{k}(1),'E')) % Couplings from electron to nucleus should be left-secular spin_system.inter.coupling.strength{n,k}='z*'; elseif strcmp(spin_system.comp.isotopes{k}(1),'E')&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Couplings from nucleus to electron should be right-secular spin_system.inter.coupling.strength{n,k}='*z'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E'))&&(n~=k) % Couplings between different electrons should be weak spin_system.inter.coupling.strength{n,k}='weak'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E'))&&(n==k) % Quadratic couplings on each electron should be secular spin_system.inter.coupling.strength{n,k}='secular'; else % Couplings between nuclei should be strong spin_system.inter.coupling.strength{n,k}='strong'; end end end case {'labframe'} % Do the reporting report(spin_system,'laboratory frame simulation for electrons.'); report(spin_system,'laboratory frame simulation for nuclei.'); report(spin_system,'all terms for electron Zeeman interactions.'); report(spin_system,'all terms for nuclear Zeeman interactions.'); report(spin_system,'all terms for all couplings.'); % Process Zeeman interactions for n=1:spin_system.comp.nspins % Full Zeeman tensors should be used for all spins spin_system.inter.zeeman.strength{n}='full'; end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins % Full coupling tensors should be used for all spins spin_system.inter.coupling.strength{n,k}='strong'; end end case {'quad-only'} % Do the reporting report(spin_system,'laboratory frame ZFS for electrons.'); report(spin_system,'laboratory frame quadrupolar couplings for nuclei.'); report(spin_system,'all other interactions ignored.'); % Ignore all Zeeman interactions for n=1:spin_system.comp.nspins spin_system.inter.zeeman.strength{n}='ignore'; end % Process couplings for n=1:spin_system.comp.nspins % Ignore all spin-spin couplings for k=1:spin_system.comp.nspins spin_system.inter.coupling.strength{n,k}='ignore'; end % Keep lab frame quadratic couplings spin_system.inter.coupling.strength{n,n}='strong'; end case {'deer-labframe'} % Do the reporting report(spin_system,'laboratory frame simulation for electrons.'); report(spin_system,'laboratory frame simulation for nuclei.'); report(spin_system,'all terms for electron Zeeman interactions.'); report(spin_system,'all terms for nuclear Zeeman interactions.'); report(spin_system,'weak terms for inter-electron couplings.'); report(spin_system,'all terms for all other couplings.'); % Process Zeeman interactions for n=1:spin_system.comp.nspins % Full Zeeman tensors should be used for all spins spin_system.inter.zeeman.strength{n}='full'; end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E'))&&(n~=k) % Couplings between different electrons should be weak spin_system.inter.coupling.strength{n,k}='weak'; else % All other couplings should be strong spin_system.inter.coupling.strength{n,k}='strong'; end end end case {'se_dnp_h+'} % Do the reporting report(spin_system,'H+ part of the solid effect DNP Hamiltonian.'); report(spin_system,'keeping EzNp parts of electron-nuclear couplings.'); report(spin_system,'keeping T(2,+1) parts of inter-nuclear couplings.'); report(spin_system,'all inter-electron interactions ignored.'); report(spin_system,'all quadratic interactions ignored.'); report(spin_system,'all Zeeman interactions ignored.'); % Ignore all Zeeman interactions for n=1:spin_system.comp.nspins spin_system.inter.zeeman.strength{n}='ignore'; end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if n==k % Ignore quadratic couplings spin_system.inter.coupling.strength{n,k}='ignore'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(~strcmp(spin_system.comp.isotopes{k}(1),'E')) % Keep EzN+ for electron-nuclear couplings spin_system.inter.coupling.strength{n,k}='z+'; elseif strcmp(spin_system.comp.isotopes{k}(1),'E')&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Keep N+Ez for nuclear-electron couplings spin_system.inter.coupling.strength{n,k}='+z'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E')) % Ignore couplings between electrons spin_system.inter.coupling.strength{n,k}='ignore'; elseif (~strcmp(spin_system.comp.isotopes{k}(1),'E'))&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Keep the T(2,+1) component of inter-nuclear couplings spin_system.inter.coupling.strength{n,k}='T(2,+1)'; end end end case {'se_dnp_h-'} % Do the reporting report(spin_system,'H- part of the solid effect DNP Hamiltonian.'); report(spin_system,'keeping EzNm parts of electron-nuclear couplings.'); report(spin_system,'keeping T(2,-1) parts of inter-nuclear couplings.'); report(spin_system,'all inter-electron interactions ignored.'); report(spin_system,'all quadratic interactions ignored.'); report(spin_system,'all Zeeman interactions ignored.'); % Ignore all Zeeman interactions for n=1:spin_system.comp.nspins spin_system.inter.zeeman.strength{n}='ignore'; end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if n==k % Ignore quadratic couplings spin_system.inter.coupling.strength{n,k}='ignore'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(~strcmp(spin_system.comp.isotopes{k}(1),'E')) % Keep EzN+ for electron-nuclear couplings spin_system.inter.coupling.strength{n,k}='z-'; elseif strcmp(spin_system.comp.isotopes{k}(1),'E')&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Keep N+Ez for nuclear-electron couplings spin_system.inter.coupling.strength{n,k}='-z'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E')) % Ignore couplings between electrons spin_system.inter.coupling.strength{n,k}='ignore'; elseif (~strcmp(spin_system.comp.isotopes{k}(1),'E'))&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Keep the T(2,-1) component of inter-nuclear couplings spin_system.inter.coupling.strength{n,k}='T(2,-1)'; end end end case {'se_dnp_h0'} % Do the reporting report(spin_system,'H0 part of the solid effect DNP Hamiltonian.'); report(spin_system,'keeping EzNz parts of electron-nuclear couplings.'); report(spin_system,'keeping secular parts of inter-nuclear couplings.'); report(spin_system,'all inter-electron interactions ignored.'); report(spin_system,'all quadratic interactions ignored.'); report(spin_system,'all Zeeman interactions ignored.'); % Ignore all Zeeman interactions for n=1:spin_system.comp.nspins spin_system.inter.zeeman.strength{n}='ignore'; end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if n==k % Ignore quadratic couplings spin_system.inter.coupling.strength{n,k}='ignore'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(~strcmp(spin_system.comp.isotopes{k}(1),'E')) % Keep EzN+ for electron-nuclear couplings spin_system.inter.coupling.strength{n,k}='zz'; elseif strcmp(spin_system.comp.isotopes{k}(1),'E')&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Keep N+Ez for nuclear-electron couplings spin_system.inter.coupling.strength{n,k}='zz'; elseif strcmp(spin_system.comp.isotopes{n}(1),'E')&&(strcmp(spin_system.comp.isotopes{k}(1),'E')) % Ignore couplings between electrons spin_system.inter.coupling.strength{n,k}='ignore'; elseif (~strcmp(spin_system.comp.isotopes{k}(1),'E'))&&(~strcmp(spin_system.comp.isotopes{n}(1),'E')) % Keep the T(2,-1) component of inter-nuclear couplings spin_system.inter.coupling.strength{n,k}='secular'; end end end case 'qnmr' % Do the reporting report(spin_system,'rotating frame approximation for S=1/2 nuclei.'); report(spin_system,'laboratory frame simulation for S>1/2 nuclei.'); report(spin_system,'electrons disallowed by the approximation.'); report(spin_system,'secular Zeeman terms for S=1/2 nuclei.'); report(spin_system,'all Zeeman terms for S>1/2 nuclei.'); report(spin_system,'secular terms for couplings between S=1/2 nuclei.'); report(spin_system,'weak and pseudosecular terms for couplings between S=1/2 and S>1/2 nuclei.'); report(spin_system,'all terms for couplings between S>1/2 nuclei.'); report(spin_system,'all terms for nuclear quadrupolar couplings.'); % Process Zeeman interactions for n=1:spin_system.comp.nspins % Check for electrons if strcmp(spin_system.comp.isotopes{n}(1),'E') error('electrons are not permitted in overtone NMR simuilations.'); end % Assign strength parameters if spin_system.comp.mults(n)==2 % S=1/2 Zeeman interactions should be secular spin_system.inter.zeeman.strength{n}='secular'; else % All other Zeeman interactions should be strong spin_system.inter.zeeman.strength{n}='full'; end end % Process couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins % Assign strength parameters if (spin_system.comp.mults(n)==2)&&(spin_system.comp.mults(k)>2) % Couplings from S=1/2 to S>1/2 nuclei should be left-secular spin_system.inter.coupling.strength{n,k}='z*'; elseif (spin_system.comp.mults(n)>2)&&(spin_system.comp.mults(k)==2) % Couplings from S>1/2 to S=1/2 nuclei should be right-secular spin_system.inter.coupling.strength{n,k}='*z'; elseif (spin_system.comp.mults(n)==2)&&(spin_system.comp.mults(k)==2) % Couplings between S=1/2 nuclei should be secular spin_system.inter.coupling.strength{n,k}='secular'; else % Couplings between S>1/2 nuclei should be strong spin_system.inter.coupling.strength{n,k}='strong'; end end end otherwise % Complain and bomb out error('unrecognized assumption set.') end % Choose the terms to retain if exist('retention','var')&&strcmp(retention,'couplings') for n=1:spin_system.comp.nspins spin_system.inter.zeeman.strength{n}='ignore'; end report(spin_system,'WARNING - all Zeeman interactions will be ignored.'); elseif exist('retention','var')&&strcmp(retention,'zeeman') for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins spin_system.inter.coupling.strength{n,k}='ignore'; end end report(spin_system,'WARNING - all couplings will be ignored.'); end end % Consistency enforcement function grumble(assumptions,retention) if ~ischar(assumptions) error('assumptions argument muct be a character string.'); end if exist('retention','var')&&(~ischar(retention)) error('retention argument must be a character string.'); end end % Humanity has advanced, when it has advanced, not because it has % been sober, responsible, and cautious, but because it has been % playful, rebellious, and immature. % % Tom Robbins
github
tsajed/nmr-pred-master
execute.m
.m
nmr-pred-master/spinach/kernel/execute.m
2,315
utf_8
707e4338d2a351b55fcbd04cc0d08cca
% Applies an event sequence to a state vector. Not very sophisticated % or efficient at the moment, further improvements to come. Syntax: % % rho=execute(spin_system,operators,durations,rho) % % where operators is a cell array of Hamiltonians or Liouvilians and % durations is a vector of times for which they act. The events are % executed chronologically from left to right. % % [email protected] function rho=execute(spin_system,operators,durations,rho) % Check consistency grumble(operators,durations); % Apply the event sequence for n=1:numel(operators) % Estimate the number of steps [timestep,nsteps]=stepsize(operators{n},durations(n)); % Decide how to proceed if nsteps < 10 % For short time steps use Krylov propagation rho=step(spin_system,operators{n},rho,durations(n)); else % For long time steps use the evolution function rho=evolution(spin_system,operators{n},[],rho,timestep,nsteps,'final'); end end end % Consistency enforcement function grumble(operators,durations) if (~iscell(operators))||isempty(operators)||(~isrow(operators)) error('operators array must be a row cell array of matrices.'); end if (~isnumeric(durations))||(~isrow(durations))||any(durations<=0) error('durations array must be a row vector of positive numbers.'); end if numel(operators)~=numel(durations) error('operators and durations arrays must have the same number of elements.'); end end % In 1929, malaria caused by Plasmodium falciparum broke out in downtown % Cairo, Egypt, due to needle sharing by local drug addicts. By the late % 1930-es a similar heroin-driven malaria epidemic was spreading through % New York City. Six percent of New York City prison inmates at the time % had signs of malaria infection - all of them injecting drug users. One % hundred and thirty-six New Yorkers died of malaria during the period, % none of them had been bitten by mosquitoes. The epidemic stopped when % the heroin retailers, concerned about losing their customers, started % adding quinine to their cut heroin. % % D.P. Levine and J.D. Sobel, "Infections in Intravenous Drug Abusers", % Oxford University Press, 1991.
github
tsajed/nmr-pred-master
step.m
.m
nmr-pred-master/spinach/kernel/step.m
5,336
utf_8
1af6dd98005186946f9b8d5c0e1bd018
% Propagation step function. Uses Krylov propagation and sparse exponenti- % ation where appropriate. Syntax: % % rho=step(spin_system,L,rho,time_step) % % Arguments: % % L - Liouvillian or Hamiltonian to be used for propagation % % rho - state vector or density matrix to be propagated % % time_step - length of the time step to take % % Note: the peculiar sequence of algebraic operations in the Krylov proce- % dure is designed to minimize the memory footprint. % % [email protected] % [email protected] function rho=step(spin_system,L,rho,time_step) % Check consistency grumble(L,time_step); % Decide how to proceed switch spin_system.bas.formalism case {'sphten-liouv','zeeman-liouv'} % Decide how to proceed if ismember('expv',spin_system.sys.disable)||... (size(L,1)<spin_system.tols.small_matrix) % Use Matlab's expm if the user insists rho=expm(-1i*L*time_step)*rho; else % Estimate the norm of the i*L*dt matrix norm_mat=norm(L,1)*abs(time_step); % Determine the number of time steps nsteps=ceil(norm_mat/5); % Warn the user if the number is too large if nsteps>100 report(spin_system,['WARNING: ' num2str(nsteps) ' substeps required, consider using evolution() here.']); end % Run codistributed if appropriate if (size(rho,2)>1)&&(~isworkernode)&&... (~ismember('gpu',spin_system.sys.enable)) spmd % Create codistributor object codist=codistributor1d(2); % Distribute the state vector stack rho=codistributed(rho,codist); % Get local part rho_local=getLocalPart(rho); % Estimate the scaling coefficient scaling=max([1 norm(rho_local,1)]); % Scale the vector and make it full rho_local=full(rho_local/scaling); % Run the Krylov procedure for n=1:nsteps next_term=rho_local; k=1; while nnz(abs(next_term)>eps)>0 next_term=-1i*(L*next_term)*time_step/(k*nsteps); rho_local=rho_local+next_term; k=k+1; end end % Scale the vector back rho_local=rho_local*scaling; end % Gather the array rho=[rho_local{:}]; else % Estimate the scaling coefficient scaling=max([1 norm(rho,1)]); % Scale the vector and make it full rho=full(rho/scaling); % Move to GPU if needed if ismember('gpu',spin_system.sys.enable) L=gpuArray(L); rho=gpuArray(rho); end % Run the Krylov procedure for n=1:nsteps next_term=rho; k=1; while nnz(abs(next_term)>eps)>0 next_term=-1i*(time_step/(k*nsteps))*(L*next_term); rho=rho+next_term; k=k+1; end end % Scale the vector back rho=gather(rho)*scaling; end end case 'zeeman-hilb' % Decide the propagator calculation method if size(L,1)>spin_system.tols.small_matrix % For large matrices and tensor trains use Spinach propagator module P=propagator(spin_system,L,time_step); else % For small matrices use Matlab's expm P=expm(-1i*L*time_step); end % Perform the propagation step if iscell(rho) parfor n=1:numel(rho) rho{n}=P*rho{n}*P'; end else rho=P*rho*P'; end otherwise % Complain and bomb out error('unknown formalism specification.'); end end % Consistency enforcement function grumble(L,time_step) if (~isnumeric(L))||(~isnumeric(time_step)) error('L and time_step must be numeric.'); end if ~isscalar(time_step) error('timestep must be a scalar.'); end end % Evans boldly put 50 atm of ethylene in a cell with 25 atm of oxygen. The % apparatus subsequently blew up, but luckily not before he had obtained % the spectra shown in Figure 8. % % A.J. Mehrer and R.S. Mulliken, Chem. Rev. 69 (1969) 639-656.
github
tsajed/nmr-pred-master
relaxation.m
.m
nmr-pred-master/spinach/kernel/relaxation.m
29,210
utf_8
1c4a5af71f148ab358fa540c512b7035
% The relaxation superoperator. All options are set during the call to % create.m function. Syntax: % % R=relaxation(spin_system,euler_angles) % % where euler_angles should be used for solid state systems in which % the thermal equilibrium state is orientation-dependent. % % Further information is available in the following papers: % % http://dx.doi.org/10.1016/j.jmr.2010.12.004 (Redfield) % http://dx.doi.org/10.1002/mrc.1242 (Lindblad) % http://dx.doi.org/10.1007/s00723-012-0367-0 (Nottingham DNP) % http://dx.doi.org/10.1039/c2cp42897k (Weizmann DNP) % % Note: Nottingham relaxation theory is only applicable to cross effect % DNP systems and Weizmann relaxation theory to solid effect and % cross effect DNP systems. % % Note: The function has been written for minimal memory footprint and % performs aggressive memory recycling. Relaxation superoperator dimen- % sions in excess of 1,000,000 are in practice feasible. % % [email protected] % [email protected] function R=relaxation(spin_system,euler_angles) % Set defaults spin_system=defaults(spin_system); % Check consistency grumble(spin_system); % Get the matrix going R=mprealloc(spin_system,0); % Do nothing if none specified if isempty(spin_system.rlx.theories) % Update the user report(spin_system,'relaxation superoperator set to zero.'); % Exit the function return; end % Add damping terms if ismember('damp',spin_system.rlx.theories) % Set up damping switch spin_system.bas.formalism case {'zeeman-hilb'} % Update the user report(spin_system,['isotropic damping at ' num2str(spin_system.rlx.damp_rate) ' Hz for all states.']); % Damp everything at the rate specified R=R-(spin_system.rlx.damp_rate/2)*unit_oper(spin_system); case {'zeeman-liouv','sphten-liouv'} % Update the user report(spin_system,['isotropic damping at ' num2str(spin_system.rlx.damp_rate) ' Hz for all states except the unit state.']); % Damp everything at the rate specified R=R-spin_system.rlx.damp_rate*unit_oper(spin_system); % Make sure the unit state is not damped U=unit_state(spin_system); R=R-(U'*R*U)*(U*U'); end % Inform the user report(spin_system,'isotropic damping terms have been incorporated.'); end % Add H-strain terms if ismember('hstrain',spin_system.rlx.theories) % Compute the damp rate for the current orientation n=euler2dcm(euler_angles(1),euler_angles(2),euler_angles(3))*[0; 0; 1]; hstrain_rates=sqrt(sum((spin_system.rlx.hstrain_rates.^2)*(n.^2))); % Set up damping switch spin_system.bas.formalism case {'zeeman-hilb'} % Update the user report(spin_system,['anisotropic damping at ' num2str(spin_system.rlx.damp_rate) ' Hz for all states.']); % Damp everything at the rate specified R=R-(hstrain_rates/2)*unit_oper(spin_system); case {'zeeman-liouv','sphten-liouv'} % Update the user report(spin_system,['anisotropic damping at ' num2str(spin_system.rlx.damp_rate) ' Hz for all states except the unit state.']); % Damp everything at the rate specified R=R-hstrain_rates*unit_oper(spin_system); % Make sure the unit state is not damped U=unit_state(spin_system); R=R-(U'*R*U)*(U*U'); end % Inform the user report(spin_system,'anisotropic damping terms have been incorporated.'); end % Add T1/T2 terms if ismember('t1_t2',spin_system.rlx.theories) % Update the user report(spin_system,'extended T1,T2 relaxation theory with user-supplied R1 and R2 rates.'); % Prealocate the relaxation rate array matrix_dim=size(spin_system.bas.basis,1); relaxation_rates=zeros(matrix_dim,1); % Compute the ranks and projections [L,M]=lin2lm(spin_system.bas.basis); % Extract rates r1_rates=spin_system.rlx.r1_rates; r2_rates=spin_system.rlx.r2_rates; % Inspect every state and assign the relaxation rate parfor n=1:matrix_dim % Copy rate vectors to nodes local_r1_rates=r1_rates; local_r2_rates=r2_rates; % Spins in unit state do not contribute mask=(L(n,:)~=0); % Spins in longitudinal states contribute their R1 r1_spins=(~logical(M(n,:)))&mask; r1_sum=sum(local_r1_rates(r1_spins)); % Spins in transverse states contribute their R2 r2_spins=(logical(M(n,:)))&mask; r2_sum=sum(local_r2_rates(r2_spins)); % Total relaxation rate for the state relaxation_rates(n)=r1_sum+r2_sum; end % Deallocate the rank and projection arrays clear('L','M'); % Form the relaxation superoperator R=R-spdiags(relaxation_rates,0,matrix_dim,matrix_dim); % Inform the user report(spin_system,'extended T1,T2 terms have been incorporated.'); end % Add Redfield terms if ismember('redfield',spin_system.rlx.theories)&&(norm(spin_system.rlx.tau_c)>0) % Update the user report(spin_system,'Redfield theory with user-supplied anisotropies and correlation times.'); % Get the rotational basis, including the non-secular terms report(spin_system,'computing the lab frame Hamiltonian superoperator...'); [L0,Q]=hamiltonian(assume(spin_system,'labframe')); % Kill the terms in the static Liouvillian that are irrelevant on the time scale of the integration timescale=max(spin_system.rlx.tau_c)*log(1/spin_system.tols.rlx_integration); L0=clean_up(spin_system,L0,spin_system.tols.rlx_integration/timescale); % Run the calculation in parallel report(spin_system,'codistributing Hamiltonian components...'); spmd % Distribute the work kmpq=codistributed(1:625,codistributor1d(2)); % Preallocate local answer R_loc=mprealloc(spin_system,10); % Loop over the local multi-index array for kmpq_local=getLocalPart(kmpq) % Extract indices [k,m,p,q]=ind2sub([5 5 5 5],kmpq_local); % Get decay weights and rates for correlation function [weights,rates]=corrfun(spin_system,k,m,p,q); % Loop over correlation function exponentials for j=1:numel(weights) % Compute the term in the rotational expansion sum if significant(Q{k,m},eps)&&significant(Q{p,q},eps)&&significant(weights(j),eps) % Inform the user report(spin_system,['integrating spherical component k=' num2str(3-k,'%+d') ', m=' num2str(3-m,'%+d') ... ', p=' num2str(3-p,'%+d') ', q=' num2str(3-q,'%+d') '...']); % Set the upper integration limit according to the accuracy goal upper_limit=-1.5*(1/rates(j))*log(1/spin_system.tols.rlx_integration); % Compute the integral using the auxiliary matrix method R_loc=R_loc-weights(j)*Q{k,m}*expmint(spin_system,L0,Q{p,q}',L0-1i*rates(j)*speye(size(L0)),upper_limit); end end end end % Deallocate variables clear('Q','L0'); % Gather data from the nodes report(spin_system,'gathering data from the nodes...'); for n=1:numel(R_loc), R=R+R_loc{n}; R_loc{n}=[]; end % Update the user report(spin_system,'Redfield theory terms have been incorporated.'); end % Add Lindblad terms if ismember('lindblad',spin_system.rlx.theories) % Update the user report(spin_system,'Lindblad theory with user-supplied R1 and R2 rates.'); % Loop over spins for n=1:spin_system.comp.nspins % Get the basic superoperators Lp_left=operator(spin_system,{'L+'},{n},'left'); Lp_right=operator(spin_system,{'L+'},{n},'right'); Lm_left=operator(spin_system,{'L-'},{n},'left'); Lm_right=operator(spin_system,{'L-'},{n},'right'); Lz_left=operator(spin_system,{'Lz'},{n},'left'); Lz_right=operator(spin_system,{'Lz'},{n},'right'); % Get the rates Rpm=spin_system.rlx.lind_r1_rates(n)/4; Rmp=spin_system.rlx.lind_r1_rates(n)/4; Rzz=spin_system.rlx.lind_r2_rates(n)-... spin_system.rlx.lind_r1_rates(n)/2; % Build the superoperator R=R+Rpm*(2*Lp_left*Lm_right-Lm_left*Lp_left-Lp_right*Lm_right)+... Rmp*(2*Lm_left*Lp_right-Lp_left*Lm_left-Lm_right*Lp_right)+... Rzz*(2*Lz_left*Lz_right-Lz_left*Lz_left-Lz_right*Lz_right); end % Inform the user report(spin_system,'Lindblad theory terms have been incorporated.'); end % Add Weizmann DNP theory terms if ismember('weizmann',spin_system.rlx.theories) % Update the user report(spin_system,'Weizmann DNP theory with user-supplied R1e, R2e, R1n, R2n, R1d and R2d rates.'); % Get electron superoperators Ep_L=operator(spin_system,'L+','electrons','left'); Ep_R=operator(spin_system,'L+','electrons','right'); Em_L=operator(spin_system,'L-','electrons','left'); Em_R=operator(spin_system,'L-','electrons','right'); Ez_L=operator(spin_system,'Lz','electrons','left'); Ez_R=operator(spin_system,'Lz','electrons','right'); % Get electron rates Rpm=spin_system.rlx.weiz_r1e/4; Rmp=spin_system.rlx.weiz_r1e/4; Rzz=spin_system.rlx.weiz_r2e-... spin_system.rlx.weiz_r1e/2; % Add Lindblad type terms R=R+Rpm*(2*Ep_L*Em_R-Em_L*Ep_L-Ep_R*Em_R)+... Rmp*(2*Em_L*Ep_R-Ep_L*Em_L-Em_R*Ep_R)+... Rzz*(2*Ez_L*Ez_R-Ez_L*Ez_L-Ez_R*Ez_R); % Get nuclear superoperators Np_L=operator(spin_system,'L+','nuclei','left'); Np_R=operator(spin_system,'L+','nuclei','right'); Nm_L=operator(spin_system,'L-','nuclei','left'); Nm_R=operator(spin_system,'L-','nuclei','right'); Nz_L=operator(spin_system,'Lz','nuclei','left'); Nz_R=operator(spin_system,'Lz','nuclei','right'); % Get nuclear rates Rpm=spin_system.rlx.weiz_r1n/4; Rmp=spin_system.rlx.weiz_r1n/4; Rzz=spin_system.rlx.weiz_r2n-... spin_system.rlx.weiz_r1n/2; % Add Lindblad type terms R=R+Rpm*(2*Np_L*Nm_R-Nm_L*Np_L-Np_R*Nm_R)+... Rmp*(2*Nm_L*Np_R-Np_L*Nm_L-Nm_R*Np_R)+... Rzz*(2*Nz_L*Nz_R-Nz_L*Nz_L-Nz_R*Nz_R); % Add dipolar cross-relaxation terms for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins % Process longitudinal terms if spin_system.rlx.weiz_r1d(n,k)~=0 % Generate flip-flop superoperator FF_L=operator(spin_system,{'L+','L-'},{n,k},'left')+... operator(spin_system,{'L-','L+'},{n,k},'left'); FF_R=operator(spin_system,{'L+','L-'},{n,k},'right')+... operator(spin_system,{'L-','L+'},{n,k},'right'); % Add Lindblad type term R=R+spin_system.rlx.weiz_r1d(n,k)*(2*FF_L*FF_R-FF_L*FF_L-FF_R*FF_R)/2; end % Process transverse terms if spin_system.rlx.weiz_r2d(n,k)~=0 % Generate ZZ superoperator ZZ_L=operator(spin_system,{'Lz','Lz'},{n,k},'left'); ZZ_R=operator(spin_system,{'Lz','Lz'},{n,k},'right'); % Add Lindblad type term R=R+spin_system.rlx.weiz_r2d(n,k)*(2*ZZ_L*ZZ_R-ZZ_L*ZZ_L-ZZ_R*ZZ_R)/2; end end end % Inform the user report(spin_system,'Weizmann DNP relaxation theory terms have been incorporated.'); end % Add Nottingham DNP theory terms if ismember('nottingham',spin_system.rlx.theories) % Update the user report(spin_system,'Nottingham DNP theory with user-supplied R1e, R1n, R2e and R2n rates.'); % Set shorthands r1e=spin_system.rlx.nott_r1e; r2e=spin_system.rlx.nott_r2e; r1n=spin_system.rlx.nott_r1n; r2n=spin_system.rlx.nott_r2n; % Find electrons electrons=find(strcmp('E',spin_system.comp.isotopes)); % Get basic electron operators S1p=operator(spin_system,{'L+'},{electrons(1)}); S1z=operator(spin_system,{'Lz'},{electrons(1)}); S2p=operator(spin_system,{'L+'},{electrons(2)}); S2z=operator(spin_system,{'Lz'},{electrons(1)}); S1zS2z=operator(spin_system,{'Lz','Lz'},{electrons(1),electrons(2)}); S1zS2p=operator(spin_system,{'Lz','L+'},{electrons(1),electrons(2)}); S1pS2z=operator(spin_system,{'L+','Lz'},{electrons(1),electrons(2)}); % Form component operators O11=0.5*(+S1z+S2z)+S1zS2z; O12=0.5*S2p+S1zS2p; O22=0.5*(+S1z-S2z)-S1zS2z; O13=0.5*S1p+S1pS2z; O33=0.5*(-S1z+S2z)-S1zS2z; O24=0.5*S1p-S1pS2z; O44=0.5*(-S1z-S2z)+S1zS2z; O34=0.5*S2p-S1zS2p; % Build the electron part of the relaxation superoperator R=-0.25*r1e*(O12*O12' + O12'*O12 - O11*O11 - O22*O22 + O13*O13' + O13'*O13 - O11*O11 - O33*O33 +... O24*O24' + O24'*O24 - O22*O22 - O44*O44 + O34*O34' + O34'*O34 - O33*O33 - O44*O44)+... 0.5*(r2e*(O11*O22 + O22*O11 + O11*O33 + O33*O11 + O44*O22 + O22*O44 + O33*O44 + O44*O33)+... r2n*(O11*O44 + O44*O11 + O22*O33 + O33*O22)); % Find nuclei nuclei=find(~cellfun(@(x)strncmp(x,'E',1),spin_system.comp.isotopes)); % Loop over nuclei for n=nuclei % Get basic nuclear operators Iz=operator(spin_system,{'Lz'},{n}); Ip=operator(spin_system,{'L+'},{n}); % Build the nuclear part of the relaxation superoperator R=R-0.25*r1n*(Ip*Ip'+Ip'*Ip)-r2n*Iz*Iz; end % Inform the user report(spin_system,'Nottingham DNP relaxation theory terms have been incorporated.'); end % Add scalar relaxation of the first kind if ismember('SRFK',spin_system.rlx.theories)&&... (spin_system.rlx.srfk_tau_c>0) % Inform the user report(spin_system,'scalar relaxation of the first kind...'); % Set local assumptions spin_system_local=assume(spin_system,spin_system.rlx.srfk_assume); % Get the background Hamiltonian H0=hamiltonian(spin_system_local); % Set local assumptions spin_system_local=assume(spin_system,spin_system.rlx.srfk_assume,'couplings'); % Replace couplings with their modulation depths [rows,cols]=find(~cellfun(@isempty,spin_system.rlx.srfk_mdepth)); spin_system_local.inter.coupling.matrix=cell(size(spin_system.inter.coupling.matrix)); for n=1:numel(rows) spin_system_local.inter.coupling.matrix{rows(n),cols(n)}=... 2*pi*eye(3)*spin_system.rlx.srfk_mdepth{rows(n),cols(n)}; end % Get the modulated coupling Hamiltonian H1=hamiltonian(spin_system_local); % Set the upper integration limit according to the accuracy goal upper_limit=2*spin_system.rlx.srfk_tau_c*log(1/spin_system.tols.rlx_integration); % Kill the terms in H0 that are irrelevant on the time scale of the integration H0=clean_up(spin_system,H0,1e-2/upper_limit); % Take the integral using the auxiliary matrix exponential technique report(spin_system,'integrating the SRFK component...'); decay_rate=-1/spin_system.rlx.srfk_tau_c; R=R-H1*expmint(spin_system,H0,H1',H0-1i*decay_rate*speye(size(H0)),upper_limit); % Deallocate variables clear('H0','H1','spin_system_local'); % Inform the user report(spin_system,'SRFK terms have been incorporated.'); end % Add scalar relaxation of the second kind if ismember('SRSK',spin_system.rlx.theories) % Inform the user report(spin_system,'scalar relaxation of the second kind...'); % Preallocate the answers R1=zeros(spin_system.comp.nspins); R2=zeros(spin_system.comp.nspins); % Loop over pairs of spins for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins % Determine the J-coupling J=0; if ~isempty(spin_system.inter.coupling.matrix{n,k}) J=J+trace(spin_system.inter.coupling.matrix{n,k})/3; end if ~isempty(spin_system.inter.coupling.matrix{k,n}) J=J+trace(spin_system.inter.coupling.matrix{k,n})/3; end % Only process heteronuclear pairs if (~strcmp(spin_system.comp.isotopes{n},spin_system.comp.isotopes{k}))&&(n>k)&&(abs(J)>0) % Find relaxation rates for the spins in question Lz_n=state(spin_system,{'Lz'},{n}); Lz_n=Lz_n/norm(Lz_n); Lp_n=state(spin_system,{'L+'},{n}); Lp_n=Lp_n/norm(Lp_n); R1n=-Lz_n'*R*Lz_n; R2n=-Lp_n'*R*Lp_n; Lz_k=state(spin_system,{'Lz'},{k}); Lz_k=Lz_k/norm(Lz_k); Lp_k=state(spin_system,{'L+'},{k}); Lp_k=Lp_k/norm(Lp_k); R1k=-Lz_k'*R*Lz_k; R2k=-Lp_k'*R*Lp_k; % Find multiplicities In=spin_system.comp.mults(n); Ik=spin_system.comp.mults(k); % Find frequency difference delta_omega=spin_system.inter.basefrqs(n)-spin_system.inter.basefrqs(k); % Compute Abragam's expressions R1(n)=R1(n)+(8/3)*(J^2)*Ik*(Ik+1)*(R2k/(R2k^2+delta_omega^2)); R1(k)=R1(k)+(8/3)*(J^2)*In*(In+1)*(R2n/(R2n^2+delta_omega^2)); R2(n)=R2(n)+(4/3)*(J^2)*Ik*(Ik+1)*(1/R1k+R2k/(R2k^2+delta_omega^2)); R2(k)=R2(k)+(4/3)*(J^2)*Ik*(In+1)*(1/R1n+R2n/(R2n^2+delta_omega^2)); end end end % Clone the spin system structure spin_system_local=spin_system; spin_system_local.rlx.theories={'t1_t2'}; spin_system_local.rlx.r1_rates=R1; spin_system_local.rlx.r2_rates=R2; % Issue a recursive call for SRSK report(spin_system,'recursive call for SRSK relaxation terms...'); R=R+relaxation(spin_system_local); % Inform the user report(spin_system,'SRSK relaxation theory terms have been incorporated.'); end % Print matrix density statistics report(spin_system,['full relaxation superoperator density ' num2str(100*nnz(R)/numel(R))... '%, nnz ' num2str(nnz(R)) ', sparsity ' num2str(issparse(R))]); % Decide the fate of dynamic frequency shifts switch spin_system.rlx.dfs case 'keep' % Do nothing and inform the user report(spin_system,'dynamic frequency shifts have been kept.'); case 'ignore' % Kill the dynamic frequency shifts R=real(R); % Inform the user report(spin_system,'dynamic frequency shifts have been ignored.'); otherwise % Complain and bomb out error('invalid value of the inter.rlx_dfs parameter.'); end % Decide the fate of the off-diagonal components switch spin_system.rlx.keep case 'diagonal' % Pull out the diagonal R=diag(diag(R)); % Inform the user report(spin_system,'all cross-relaxation terms have been ignored.'); case 'kite' % Refuse to process inappropriate cases if ~strcmp(spin_system.bas.formalism,'sphten-liouv') error('kite option is only available for sphten-liouv formalism.'); end % Compile the index of all longitudinal spin orders [~,M]=lin2lm(spin_system.bas.basis); long_states=find(sum(abs(M),2)==0); % Index the relaxation superoperator [rows,cols,vals]=find(R); % Keep self-relaxation and longitudinal cross-relaxation terms vals=vals.*((ismember(rows,long_states)&ismember(cols,long_states))|(rows==cols)); % Recompose the relaxation superoperator R=sparse(rows,cols,vals,length(R),length(R)); clear('rows','cols','vals'); % Inform the user report(spin_system,'transverse cross-relaxation terms have been ignored.'); case 'secular' % Refuse to process inappropriate cases if ~strcmp(spin_system.bas.formalism,'sphten-liouv') error('secular option is only available for sphten-liouv formalism.'); end % Compute state carrier frequencies [~,M]=lin2lm(spin_system.bas.basis); matrix_dim=size(spin_system.bas.basis,1); frequencies=sum(repmat(spin_system.inter.basefrqs,matrix_dim,1).*M,2); % Index the relaxation superoperator [rows,cols,vals]=find(R); % Set the initial keep mask keep_mask=false(size(vals)); % Loop over unique frequencies for omega=unique(frequencies)' % Find the states having the current frequency current_frq_group=find(frequencies==omega); % Update the keep mask keep_mask=keep_mask|(ismember(rows,current_frq_group)&... ismember(cols,current_frq_group)); end % Recompose the relaxation superoperator R=sparse(rows,cols,vals.*keep_mask,length(R),length(R)); clear('rows','cols','vals'); % Inform the user report(spin_system,'non-secular cross-relaxation terms have been ignored.'); case 'labframe' % Inform the user report(spin_system,'returning complete relaxation superoperator (lab frame simulations only).'); end % Print matrix density statistics report(spin_system,['final relaxation superoperator density ' num2str(100*nnz(R)/numel(R))... '%, nnz(R)=' num2str(nnz(R)) ', sparsity ' num2str(issparse(R))]); % Choose the thermalization model switch spin_system.rlx.equilibrium case 'zero' % Do nothing and inform the user report(spin_system,'WARNING - the spin system will relax to the all-zero state.'); case 'levante' % Inform the user report(spin_system,'the system will relax to thermal equilibrium (Levante-Ernst formalism).'); % Use Levante-Ernst thermalization if exist('euler_angles','var') [H,Q]=hamiltonian(assume(spin_system,'labframe'),'left'); R(:,1)=-R*equilibrium(spin_system,H,Q,euler_angles); report(spin_system,'equilibrium state was computed using anisotropic Hamiltonian at'); report(spin_system,['alpha=' num2str(euler_angles(1)) ', beta=' num2str(euler_angles(2)) ', gamma=' num2str(euler_angles(3))]); else H=hamiltonian(assume(spin_system,'labframe'),'left'); R(:,1)=-R*equilibrium(spin_system,H); report(spin_system,'equilibrium state was computed using isotropic Hamiltonian.'); end case 'dibari' % Inform the user report(spin_system,'the system will relax to thermal equilibrium (DiBari-Levitt formalism).'); % Get the temperature factor beta=spin_system.tols.hbar/(spin_system.tols.kbol*spin_system.rlx.temperature); % Use DiBari-Levitt thermalization if exist('euler_angles','var') [H,Q]=hamiltonian(assume(spin_system,'labframe'),'right'); R=R*propagator(spin_system,H+orientation(Q,euler_angles),1i*beta); report(spin_system,'equilibrium state was computed using anisotropic Hamiltonian at'); report(spin_system,['alpha=' num2str(euler_angles(1)) ', beta=' num2str(euler_angles(2)) ', gamma=' num2str(euler_angles(3))]); else H=hamiltonian(assume(spin_system,'labframe'),'right'); R=R*propagator(spin_system,H,1i*beta); report(spin_system,'equilibrium state was computed using isotropic Hamiltonian.'); end otherwise % Complain and bomb out error('unknown equilibrium specification.'); end % Perform final clean-up R=clean_up(spin_system,R,spin_system.tols.liouv_zero); end % Default option values function spin_system=defaults(spin_system) if ~isfield(spin_system.rlx,'equilibrium') report(spin_system,'relaxation destination not specified, assuming zero.'); spin_system.rlx.equilibrium='zero'; end if ~isfield(spin_system.rlx,'dfs') report(spin_system,'dynamic frequency shift policy not specified, DFS will be ignored.'); spin_system.rlx.dfs='ignore'; end end % Consistency enforcement function grumble(spin_system) if ~isfield(spin_system,'rlx') error('relaxation data (.rlx) is missing from the spin_system structure.'); end if ~isfield(spin_system.rlx,'theories') error('relaxation data (.rlx.theories) is missing from the spin_system structure.'); end if ~iscell(spin_system.rlx.theories)||any(~cellfun(@ischar,spin_system.rlx.theories)) error('spin_system.rlx.theories must be a cell array of character strings.'); end for n=1:numel(spin_system.rlx.theories) if ~ismember(spin_system.rlx.theories{n},{'none','damp','hstrain','t1_t2','SRSK','SRFK'... 'redfield','lindblad','nottingham','weizmann'}) error('unrecognised relaxation theory specification.'); end end if ( ismember('t1_t2',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv'})) error('extended T1,T2 relaxation theory is only available for sphten-liouv formalism.'); end if ( ismember('redfield',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})) error('Redfield relaxation theory is only available in Liouville space.'); end if ( ismember('lindblad',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})) error('Lindblad relaxation theory is only available in Liouville space.'); end if ( ismember('nottingham',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})) error('Nottingham relaxation theory is only available in Liouville space.'); end if ( ismember('weizmann',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})) error('Weizmann relaxation theory is only available in Liouville space.'); end if ( ismember('SRFK',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})) error('SRFK relaxation theory is only available in Liouville space.'); end if ( ismember('SRSK',spin_system.rlx.theories))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})) error('SRSK relaxation theory is only available in Liouville space.'); end if ( strcmp(spin_system.rlx.equilibrium,'levante'))&&... (~strcmp(spin_system.bas.formalism,'sphten-liouv')) error('Levante-Ernst thermalization is only available for sphten-liouv formalism.'); end if (strcmp(spin_system.rlx.equilibrium,'dibari'))&&... (spin_system.rlx.temperature==0) error('DiBari-Levitt thermalization cannot be used with the high-temperature approximation.') end end % There are horrible people who, instead of solving a problem, tangle it up % and make it harder to solve for anyone who wants to deal with it. Whoever % does not know how to hit the nail on the head should be asked not to hit % it at all. % % Friedrich Nietzsche
github
tsajed/nmr-pred-master
state.m
.m
nmr-pred-master/spinach/kernel/state.m
5,293
utf_8
65400ecadbbdef5c48ef7758937b9103
% State operators (Hilbert space) and state vectors (Liouville space). % % <http://spindynamics.org/wiki/index.php?title=State.m> function rho=state(spin_system,states,spins,method) % Validate the input grumble(spin_system,states,spins); % Default is to use consistent state norms if ~exist('method','var'), method='exact'; end % Decide how to proceed switch spin_system.bas.formalism case 'sphten-liouv' % Choose the state vector generation methos switch method case 'cheap' % Parse the specification [opspecs,coeffs]=human2opspec(spin_system,states,spins); % Compute correlation orders correlation_orders=sum(logical(spin_system.bas.basis),2); % Get the state vector by searching the state list rho=spalloc(size(spin_system.bas.basis,1),1,numel(opspecs)); parfor n=1:numel(opspecs) %#ok<*PFBNS> % Find states with the same correlation order possibilities=(correlation_orders==nnz(opspecs{n})); % Pin down the required state for k=find(opspecs{n}) possibilities=and(possibilities,spin_system.bas.basis(:,k)==opspecs{n}(k)); end % Double-check if nnz(possibilities)>1 error('basis descriptor ambiguity detected.'); elseif nnz(possibilities)<1 error('the requested state is not present in the basis.'); end % Add to the total rho=rho+coeffs(n)*sparse(possibilities); end case 'exact' % Apply a left side product superoperator to the unit state rho=operator(spin_system,states,spins,'left')*unit_state(spin_system); case 'chem' % Parse the specification [opspecs,coeffs]=human2opspec(spin_system,states,spins); % Preallocate the state vector rho=spalloc(size(spin_system.bas.basis,1),1,0); % Sum the states with concentrations for n=1:numel(opspecs) % Identify active spins active_spins=find(opspecs{n}); % Find out which chemical species they are in species=true(1,numel(spin_system.chem.parts)); for k=1:numel(active_spins) species=species&cellfun(@(x)ismember(active_spins(k),x),spin_system.chem.parts); end % Check state validity if nnz(species)~=1 error('the spin state requested crosses chemical species boundaries.'); end % Adjust the coefficient coeffs(n)=coeffs(n)*spin_system.chem.concs(species); % Get the state vector rho=rho+coeffs(n)*p_superop(spin_system,opspecs{n},'left')*unit_state(spin_system); end otherwise % Complain and bomb out error('unknown state generation method.'); end case 'zeeman-liouv' % Apply a left side product superoperator to the unit state rho=operator(spin_system,states,spins,'left')*unit_state(spin_system); case 'zeeman-hilb' % Generate a Hilbert space operator rho=operator(spin_system,states,spins); % Match normalization to Liouville space rho=rho./sqrt(size(rho,1)); otherwise % Complain and bomb out error('unknown formalism specification.'); end end % Input validation function function grumble(spin_system,states,spins) if ~isfield(spin_system,'bas') error('basis set information is missing, run basis() before calling this function.'); end if (~(ischar(states)&&ischar(spins)))&&... (~(iscell(states)&&iscell(spins)))&&... (~(ischar(states)&&isnumeric(spins))) error('invalid state specification.'); end if iscell(states)&&iscell(spins)&&(numel(states)~=numel(spins)) error('spins and operators cell arrays should have the same number of elements.'); end if iscell(states)&&any(~cellfun(@ischar,states)) error('all elements of the operators cell array should be strings.'); end if iscell(spins)&&any(~cellfun(@isnumeric,spins)) error('all elements of the spins cell array should be integer numbers.'); end end % It worked. % % J. Robert Oppenheimer (after witnessing the first atomic detonation)
github
tsajed/nmr-pred-master
krylov.m
.m
nmr-pred-master/spinach/kernel/krylov.m
9,035
utf_8
39d4c50f6ad537a593fcb4dd160b1260
% Krylov propagation function. Avoids matrix exponentiation, but can be % slow. Should be used when the Liouvillian exponential does not fit in- % to the system memory, but the Liouvillian itself does. Syntax: % % answer=krylov(spin_system,L,coil,rho,time_step,nsteps,output) % % Arguments for Liouville space calculations: % % L - the Liouvillian to be used during evolution % % rho - the initial state vector or a horizontal stack thereof % % output - a string giving the type of evolution that is required % % 'final' - returns the final state vector or a horizontal % stack thereof. % % 'trajectory' - returns the stack of state vectors giving % the trajectory of the system starting from % rho with the user-specified number of steps % and step length. % % 'total' - returns the integral of the observable trace % from the simulation start to infinity. This % option requires the presence of relaxation. % % 'refocus' - evolves the first vector for zero steps, % second vector for one step, third vector for % two steps, etc., consistent with the second % stage of evolution in the indirect dimension % after a refocusing pulse. % % 'observable' - returns the time dynamics of an observable % as a vector (if starting from a single ini- % tial state) or a matrix (if starting from a % stack of initial states). % % 'multichannel' - returns the time dynamics of several % observables as rows of a matrix. Note % that destination state screening may be % less efficient when there are multiple % destinations to screen against. % % coil - the detection state, used when 'observable' is specified as % the output option. If 'multichannel' is selected, the coil % should contain multiple columns corresponding to individual % observable vectors. % % This function does not support Hilber space formalisms. % % [email protected] function answer=krylov(spin_system,L,coil,rho,timestep,nsteps,output) % Check consistency grumble(L,coil,rho,timestep,nsteps,output); % Inform the user about matrix densities report(spin_system,['Liouvillian dimension ' num2str(size(L,1)) ', nnz ' num2str(nnz(L)) ... ', density ' num2str(100*nnz(L)/numel(L)) '%, sparsity ' num2str(issparse(L))]); % Estimate the norm of i*L*dt norm_mat=norm(L,1)*abs(timestep); % Inform the user about the norm report(spin_system,['norm of i*L*dt: ' num2str(norm_mat)]); % Determine the number of substeps nsubsteps=ceil(norm_mat); % Inform the user about the schedule report(spin_system,['taking ' num2str(nsteps) ' Krylov steps with '... num2str(nsubsteps) ' substeps each.']); % Warn about silly calls if nsubsteps>100 report(spin_system,'WARNING - the number of substeps is large, consider using evolution() here.'); end % Estimate the scaling coefficient scaling=max([1 norm(rho,1)]); % Scale the vector rho=rho/scaling; % Compute the generator matrix A=-1i*L*(timestep/nsubsteps); % Upload data to GPU or optimise layout if ismember('gpu',spin_system.sys.enable) A=gpuArray(A); rho=gpuArray(full(rho)); coil=gpuArray(coil); location='GPU'; else location='CPU'; rho=full(rho); end % Decide the output type switch output case 'final' % Loop over steps for n=1:nsteps % Inform the user report(spin_system,[location ' Krylov step ' num2str(n) ' out of ' num2str(nsteps) '...']); % Loop over substeps for k=1:nsubsteps % Taylor series next_term=rho; m=1; while nnz(abs(next_term)>eps)>0 next_term=(A*next_term)*(1/m); rho=rho+next_term; m=m+1; end end end % Assign the answer answer=gather(rho); case 'trajectory' % Preallocate the answer and set the starting point answer=zeros(size(rho,1),nsteps+1); answer(:,1)=gather(rho); % Loop over steps for n=1:nsteps % Inform the user report(spin_system,[location ' Krylov step ' num2str(n) ' out of ' num2str(nsteps) '...']); % Loop over substeps for k=1:nsubsteps % Taylor series next_term=rho; m=1; while nnz(abs(next_term)>eps)>0 next_term=(A*next_term)*(1/m); rho=rho+next_term; m=m+1; end end % Assign the answer answer(:,n+1)=gather(rho); end case 'refocus' % Loop over steps for n=2:size(rho,2) % Inform the user report(spin_system,[location ' Krylov step ' num2str(n) ' out of ' num2str(nsteps) '...']); % Loop over substeps for k=1:nsubsteps % Taylor series next_term=rho(:,n:end); m=1; while nnz(abs(next_term)>eps)>0 next_term=(A*next_term)*(1/m); rho(:,n:end)=rho(:,n:end)+next_term; m=m+1; end end end % Assign the answer answer=gather(rho); case 'observable' % Preallocate the answer answer=zeros(nsteps+1,size(rho,2)); % Set the initial point answer(1,:)=gather(coil'*rho); % Loop over steps for n=1:nsteps % Inform the user report(spin_system,[location ' Krylov step ' num2str(n) ' out of ' num2str(nsteps) '...']); % Loop over substeps for k=1:nsubsteps % Taylor series next_term=rho; m=1; while nnz(abs(next_term)>eps)>0 next_term=(A*next_term)*(1/m); rho=rho+next_term; m=m+1; end end % Assign the answer answer(n+1,:)=gather(coil'*rho); end case 'multichannel' % Preallocate the answer answer=zeros(size(coil,2),nsteps+1); % Set the initial point answer(:,1)=answer(:,1)+gather(coil'*rho); % Loop over steps for n=1:nsteps % Inform the user report(spin_system,[location ' Krylov step ' num2str(n) ' out of ' num2str(nsteps) '...']); % Loop over substeps for k=1:nsubsteps % Taylor series next_term=rho; m=1; while nnz(abs(next_term)>eps)>0 next_term=(A*next_term)*(1/m); rho=rho+next_term; m=m+1; end end % Assign the answer answer(:,n+1)=gather(coil'*rho); end otherwise error('unknown output option.'); end end % Consistency enforcement function grumble(L,coil,rho,timestep,nsteps,output) if ~isnumeric(L) error('Liouvillian must be numeric.'); end if ~isnumeric(coil) error('coil argument must be numeric.'); end if (~isnumeric(rho))&&(~iscell(rho)) error('rho argument must either be numeric or a cell array'); end if ~isnumeric(timestep) error('timestep argument must be numeric.'); end if ~isnumeric(nsteps) error('nsteps must be numeric.'); end if (~ischar(output))||(~ismember(output,{'observable','final',... 'trajectory','total','multichannel','refocus'})) error('observable argument must be a valid character string.'); end end % Health and Safety were a pair of rats that lived in % the shrubbery in front of the Southampton Chemistry % building. The little beasts have died of old age.
github
tsajed/nmr-pred-master
stateinfo.m
.m
nmr-pred-master/spinach/kernel/stateinfo.m
2,008
utf_8
d0fad609ddeb1759df04280a957482fb
% Prints the state vector norm and the list of the most populated basis % states in the order of decreasing population. Syntax: % % stateinfo(spin_system,rho,npops) % Parameters: % % rho - state vector % % npops - number of largest populations to print % % Note: this function requires a spherical tensor basis set. % % [email protected] % [email protected] function stateinfo(spin_system,rho,npops) % Check consistency grumble(spin_system,rho,npops); % Report the state vector norm report(spin_system,['state vector 2-norm: ' num2str(norm(rho,2))]); % Locate npops most populated states and sort by amplitude [~,sorting_index]=sort(abs(rho),1,'descend'); largest_elemts=rho(sorting_index(1:npops)); largest_states=spin_system.bas.basis(sorting_index(1:npops),:); % Print the states and their populations report(spin_system,[num2str(npops) ' most populated basis states (state, coeff, number)']); for n=1:npops state_string=cell(1,spin_system.comp.nspins); for k=1:spin_system.comp.nspins [l,m]=lin2lm(largest_states(n,k)); if l==0 state_string{k}=' .... '; else state_string{k}=[' (' num2str(l,'%d') ',' num2str(m,'%+d') ') ']; end end disp([cell2mat(state_string) ' ' num2str(largest_elemts(n),'%+5.3e') ' ' num2str(sorting_index(n))]); end end % Consistency enforcement function grumble(spin_system,rho,npops) if ~ismember(spin_system.bas.formalism,{'sphten-liouv'}) error('state analysis is only available for sphten-liouv formalism.'); end if (~isnumeric(rho))||(~iscolumn(rho)) error('rho parameter must be a column vector.'); end if (~isnumeric(npops))||(~isscalar(npops))||(~isreal(npops))||... (npops<1)||(mod(npops,1)~=0) error('pops parameter must be a positive real integer.'); end end % "One man with a dream will beat a hundred men with a grudge." % % A Russian saying
github
tsajed/nmr-pred-master
evolution.m
.m
nmr-pred-master/spinach/kernel/evolution.m
39,585
utf_8
5015230a6b7861d68eaaaaad05dd6e63
% Time evolution function. Performs all types of time propagation with % automatic trajectory level state space restriction. Syntax: % % answer=evolution(spin_system,L,coil,rho,timestep,... % nsteps,output,destination) % % Arguments for Liouville space calculations: % % L - the Liouvillian to be used during evolution % % rho - the initial state vector or a horizontal stack thereof % % output - a string giving the type of evolution that is required % % 'final' - returns the final state vector or a horizontal % stack thereof. % % 'trajectory' - returns the stack of state vectors giving % the trajectory of the system starting from % rho with the user-specified number of steps % and step length. % % 'total' - returns the integral of the observable trace % from the simulation start to infinity. This % option requires the presence of relaxation. % % 'refocus' - evolves the first vector for zero steps, % second vector for one step, third vector for % two steps, etc., consistent with the second % stage of evolution in the indirect dimension % after a refocusing pulse. % % 'observable' - returns the time dynamics of an observable % as a vector (if starting from a single ini- % tial state) or a matrix (if starting from a % stack of initial states). % % 'multichannel' - returns the time dynamics of several % observables as rows of a matrix. Note % that destination state screening may be % less efficient when there are multiple % destinations to screen against. % % coil - the detection state, used when 'observable' is specified as % the output option. If 'multichannel' is selected, the coil % should contain multiple columns corresponding to individual % observable vectors. % % destination - (optional) the state to be used for destination state % screening. % % Arguments for Hilbert space calculations: % % L - Hamiltonian matrix % % coil - observable operator (if any) % % rho - initial density matrix % % timestep - duration of a single time step (seconds) % % nsteps - number of steps to take % % output - a string giving the type of evolution that is required % % 'final' - returns the final density matrix. % % 'trajectory' - returns a cell array of density matrices % giving the trajectory of the system star- % ting from rho with the user-specified num- % ber of steps and step length. % % 'refocus' - evolves the first matrix for zero steps, % second matrix for one step, third matrix for % two steps, etc., consistent with the second % stage of evolution in the indirect dimension % after a refocusing pulse. % % 'observable' - returns the time dynamics of an observable % as a vector. % % destination - this argument is ignored. % % Calculation of final states and observables in Hilbert space is parallel- % ized and tested all the way to 128-core (16 nodes, 8 cores each) configu- % rations. Parallelization of the trajectory calculation does not appear to % yield any benefits due to large amount of inter-thread communication. % % See http://dx.doi.org/10.1063/1.3679656 for further information. % % [email protected] % [email protected] % [email protected] function answer=evolution(spin_system,L,coil,rho,timestep,nsteps,output,destination) % Check consistency grumble(L,coil,rho,timestep,nsteps,output); % Decide how to proceed switch spin_system.bas.formalism case {'sphten-liouv','zeeman-liouv'} % Decide whether to normalize the coils if ~isempty(coil) if ismember('norm_coil',spin_system.sys.disable) report(spin_system,'coils have not been normalized.'); else for n=1:size(coil,2) coil(:,n)=coil(:,n)/norm(coil(:,n)); end report(spin_system,'coils have been normalized.'); end end % Apply trajectory-level reduction algorithms report(spin_system,'trying to reduce the problem dimension...'); % Decide the screening algorithm if ismember('dss',spin_system.sys.disable) % If DSS is disabled, run forward reduction report(spin_system,'WARNING - destination state screening is disabled.'); projectors=reduce(spin_system,L,rho); elseif exist('destination','var')&&(~isempty(destination)) % If destination state is supplied, use it for DSS report(spin_system,'destination state screening using supplied state.'); projectors=reduce(spin_system,L',destination); elseif ismember(output,{'observable'}) % If coil state is supplied, use it for DSS report(spin_system,'destination state screening using coil state.'); projectors=reduce(spin_system,L',coil); else % Default to the usual forward screening report(spin_system,'destination state screening is not applicable.'); projectors=reduce(spin_system,L,rho); end % Run the evolution switch output case 'final' % Create arrays of projections nsubs=numel(projectors); L_sub=cell(nsubs,1); rho_sub=cell(nsubs,1); local_answers=cell(nsubs,1); report(spin_system,'splitting the space...'); for sub=1:nsubs L_sub{sub}=projectors{sub}'*L*projectors{sub}; rho_sub{sub}=projectors{sub}'*rho; end % Loop in parallel over independent subspaces parfor sub=1:nsubs % Inform the user report(spin_system,['evolving subspace ' num2str(sub) ' of ' num2str(nsubs) '...']); % Grab local copies L_loc=L_sub{sub}; rho_loc=rho_sub{sub}; proj_loc=projectors{sub}; % Propagate the system if ((nnz(L_loc)<spin_system.tols.krylov_switchover)||... ismember('krylov',spin_system.sys.disable))&&... (~ismember('krylov',spin_system.sys.enable)) % Get the exponential propagator report(spin_system,'building the propagator...'); P=propagator(spin_system,L_loc,timestep); % Move to GPU or optimise layout if ismember('gpu',spin_system.sys.enable) rho_loc=gpuArray(full(rho_loc)); P=gpuArray(P); report(spin_system,'propagating the system on GPU...'); else rho_loc=full(rho_loc); report(spin_system,'propagating the system on CPU...'); end % Propagate the system for n=1:nsteps rho_loc=P*rho_loc; end % Gather the answer rho_loc=gather(rho_loc); else % For very large subspaces use Krylov propagation report(spin_system,'large Liouvillian, propagating using Krylov algorithm... '); rho_loc=krylov(spin_system,L_loc,[],rho_loc,timestep,nsteps,'final'); end % Project back into the full space rho_loc=clean_up(spin_system,rho_loc,spin_system.tols.zte_tol); local_answers{sub}=proj_loc*sparse(rho_loc); % Deallocate memory in a transparent way rho_loc=[]; L_loc=[]; proj_loc=[]; P=[]; %#ok<NASGU> % Update the user report(spin_system,'propagation finished.'); end % Sum up the results (no clean-up needed) report(spin_system,'gathering data from the nodes...'); answer=spalloc(size(rho,1),size(rho,2),0); for sub=1:numel(projectors) answer=answer+local_answers{sub}; local_answers{sub}=[]; end report(spin_system,'data retrieval finished.'); case 'total' % Create arrays of projections nsubs=numel(projectors); L_sub=cell(nsubs,1); rho_sub=cell(nsubs,1); coil_sub=cell(nsubs,1); report(spin_system,'splitting the space...'); for sub=1:nsubs L_sub{sub}=projectors{sub}'*L*projectors{sub}; rho_sub{sub}=full(projectors{sub}'*rho); coil_sub{sub}=projectors{sub}'*coil; end % Start with zero answer=0; % Loop in parallel over independent subspaces parfor sub=1:numel(projectors) % Inform the user report(spin_system,['evolving subspace ' num2str(sub) ' of ' num2str(nsubs) '...']); % Compute the integral report(spin_system,'integrating the trajectory...'); answer_loc=real(coil_sub{sub}'*((1i*L_sub{sub})\rho_sub{sub})); % Add the subspace to the total answer=answer+answer_loc; % Update the user report(spin_system,'integration finished.'); end % Make sure a full array is returned answer=full(answer); case 'trajectory' % Create arrays of projections nsubs=numel(projectors); L_sub=cell(nsubs,1); rho_sub=cell(nsubs,1); local_answers=cell(nsubs,1); report(spin_system,'splitting the space...'); for sub=1:nsubs L_sub{sub}=projectors{sub}'*L*projectors{sub}; rho_sub{sub}=projectors{sub}'*rho; end % Loop in parallel over independent subspaces parfor sub=1:nsubs % Inform the user report(spin_system,['evolving subspace ' num2str(sub) ' of ' num2str(nsubs) '...']); % Grab local copies L_loc=L_sub{sub}; rho_loc=rho_sub{sub}; proj_loc=projectors{sub}; % Propagate the system if ((nnz(L_loc)<spin_system.tols.krylov_switchover)||... ismember('krylov',spin_system.sys.disable))&&... (~ismember('krylov',spin_system.sys.enable)) % Get the exponential propagator report(spin_system,'building the propagator...'); P=propagator(spin_system,L_loc,timestep); % Move to GPU or optimise layout if ismember('gpu',spin_system.sys.enable) rho_loc=gpuArray(full(rho_loc)); P=gpuArray(P); answer=zeros(size(rho_loc,1),nsteps+1,'gpuArray'); report(spin_system,'propagating the system on GPU...'); else rho_loc=full(rho_loc); answer=zeros(size(rho_loc,1),nsteps+1); report(spin_system,'propagating the system on CPU...'); end % Set the starting point answer(:,1)=rho_loc; % Propagate the system for n=1:nsteps answer(:,n+1)=P*answer(:,n); end % Gather the answer answer=gather(answer); else % For very large subspaces use Krylov propagation report(spin_system,'large Liouvillian, propagating using Krylov algorithm... '); answer=krylov(spin_system,L_loc,[],rho_loc,timestep,nsteps,'trajectory') end % Project back into the full space answer=clean_up(spin_system,answer,spin_system.tols.zte_tol); local_answers{sub}=proj_loc*sparse(answer); % Deallocate memory in a transparent way rho_loc=[]; L_loc=[]; proj_loc=[]; P=[]; answer=[]; %#ok<NASGU> % Update the user report(spin_system,'propagation finished.'); end % Sum up the results (no clean-up needed) report(spin_system,'gathering data from the nodes...'); answer=spalloc(size(rho,1),nsteps+1,0); for sub=1:numel(projectors) answer=answer+local_answers{sub}; local_answers{sub}=[]; end report(spin_system,'data retrieval finished.'); case 'refocus' % Create arrays of projections nsubs=numel(projectors); L_sub=cell(nsubs,1); rho_sub=cell(nsubs,1); local_answers=cell(nsubs,1); report(spin_system,'splitting the space...'); for sub=1:nsubs L_sub{sub}=projectors{sub}'*L*projectors{sub}; rho_sub{sub}=projectors{sub}'*rho; end % Loop over independent subspaces parfor sub=1:nsubs % Inform the user report(spin_system,['evolving subspace ' num2str(sub) ' of ' num2str(nsubs) '...']); % Grab local copies L_loc=L_sub{sub}; rho_loc=rho_sub{sub}; proj_loc=projectors{sub}; % Propagate the system if ((nnz(L_loc)<spin_system.tols.krylov_switchover)||... ismember('krylov',spin_system.sys.disable))&&... (~ismember('krylov',spin_system.sys.enable)) % Get the exponential propagator report(spin_system,'building the propagator...'); P=propagator(spin_system,L_loc,timestep); % Move to GPU or optimise layout if ismember('gpu',spin_system.sys.enable) rho_loc=gpuArray(full(rho_loc)); P=gpuArray(P); report(spin_system,'propagating the system on GPU...'); else rho_loc=full(rho_loc); report(spin_system,'propagating the system on CPU...'); end % Propagate the system for n=2:size(rho_loc,2) rho_loc(:,n:end)=P*rho_loc(:,n:end); end % Gather the answer rho_loc=gather(rho_loc); else % For very large subspaces use Krylov propagation report(spin_system,'large Liouvillian, propagating using Krylov algorithm... '); rho_loc=krylov(spin_system,L_loc,[],rho_loc,timestep,'refocus'); end % Project back into the full space rho_loc=clean_up(spin_system,rho_loc,spin_system.tols.zte_tol); local_answers{sub}=proj_loc*sparse(rho_loc); % Deallocate memory in a transparent way rho_loc=[]; L_loc=[]; proj_loc=[]; P=[]; %#ok<NASGU> % Update the user report(spin_system,'propagation finished.'); end % Sum up the results (no clean-up needed) report(spin_system,'gathering data from the nodes...'); answer=spalloc(size(rho,1),nsteps+1,0); for sub=1:numel(projectors) answer=answer+local_answers{sub}; local_answers{sub}=[]; end report(spin_system,'data retrieval finished.'); case 'observable' % Create arrays of projections nsubs=numel(projectors); L_sub=cell(nsubs,1); rho_sub=cell(nsubs,1); coil_sub=cell(nsubs,1); report(spin_system,'splitting the space...'); for sub=1:nsubs L_sub{sub}=projectors{sub}'*L*projectors{sub}; rho_sub{sub}=projectors{sub}'*rho; coil_sub{sub}=projectors{sub}'*coil; end % Preallocate the answer answer=zeros(nsteps+1,size(rho,2)); % Loop over independent subspaces parfor sub=1:nsubs % Inform the user report(spin_system,['evolving subspace ' num2str(sub) ' of ' num2str(nsubs) '...']); % Grab local copies L_loc=L_sub{sub}; rho_loc=rho_sub{sub}; coil_loc=coil_sub{sub}; % Preallocate the local answer answer_loc=zeros(nsteps+1,size(rho_loc,2)); % The first point does not require propagation answer_loc(1,:)=answer_loc(1,:)+coil_loc'*rho_loc; % Propagate the system if ((nnz(L_loc)<spin_system.tols.krylov_switchover)||... ismember('krylov',spin_system.sys.disable))&&... (~ismember('krylov',spin_system.sys.enable)) % Get the exponential propagator report(spin_system,'building the propagator...'); P=propagator(spin_system,L_loc,timestep); % Move to GPU or optimise layout if ismember('gpu',spin_system.sys.enable) rho_loc=gpuArray(full(rho_loc)); coil_loc=gpuArray(full(coil_loc)); P=gpuArray(P); report(spin_system,'propagating the system on GPU...'); else rho_loc=full(rho_loc); coil_loc=full(coil_loc); report(spin_system,'propagating the system on CPU...'); end % Propagate the system for n=1:nsteps rho_loc=P*rho_loc; answer_loc(n+1,:)=answer_loc(n+1,:)+gather(coil_loc'*rho_loc); end else % For very large subspaces use Krylov propagation report(spin_system,'large Liouvillian, propagating using Krylov algorithm... '); answer_loc=krylov(spin_system,L_loc,coil_loc,rho_loc,timestep,nsteps,'observable'); end % Add to the total answer=answer+answer_loc; % Deallocate memory in a transparent way rho_loc=[]; L_loc=[]; P=[]; answer_loc=[]; %#ok<NASGU> % Update the user report(spin_system,'propagation finished.'); end % Make sure a full array is returned answer=full(answer); case 'multichannel' % Create arrays of projections nsubs=numel(projectors); L_sub=cell(nsubs,1); rho_sub=cell(nsubs,1); coil_sub=cell(nsubs,1); report(spin_system,'splitting the space...'); for sub=1:nsubs L_sub{sub}=projectors{sub}'*L*projectors{sub}; rho_sub{sub}=projectors{sub}'*rho; coil_sub{sub}=projectors{sub}'*coil; end % Preallocate the answer answer=zeros(size(coil,2),nsteps+1); % Loop over independent subspaces parfor sub=1:length(projectors) % Inform the user report(spin_system,['evolving subspace ' num2str(sub) ' of ' num2str(numel(projectors)) '...']); % Grab local copies L_loc=L_sub{sub}; rho_loc=rho_sub{sub}; coil_loc=coil_sub{sub}; % Propagate the system if ((nnz(L_loc)<spin_system.tols.krylov_switchover)||... ismember('krylov',spin_system.sys.disable))&&... (~ismember('krylov',spin_system.sys.enable)) % Get the exponential propagator report(spin_system,'building the propagator...'); P=propagator(spin_system,L_loc,timestep); % Preallocate the local answer answer_loc=zeros(size(coil_loc,2),nsteps+1); % The first point does not require propagation answer_loc(:,1)=answer_loc(:,1)+coil_loc'*rho_loc; % Move to GPU or optimise layout if ismember('gpu',spin_system.sys.enable) rho_loc=gpuArray(full(rho_loc)); coil_loc=gpuArray(full(coil_loc)); P=gpuArray(P); report(spin_system,'propagating the system on GPU...'); else rho_loc=full(rho_loc); coil_loc=full(coil_loc); report(spin_system,'propagating the system on CPU...'); end % Propagate the system for n=1:nsteps rho_loc=P*rho_loc; answer_loc(:,n+1)=answer_loc(:,n+1)+gather(coil_loc'*rho_loc); end else % For very large subspaces use Krylov propagation report(spin_system,'large Liouvillian, propagating using Krylov algorithm... '); answer_loc=krylov(spin_system,L_loc,coil_loc,rho_loc,timestep,nsteps,'multichannel'); end % Add to the total answer=answer+answer_loc; % Deallocate memory in a transparent way rho_loc=[]; L_loc=[]; P=[]; answer_loc=[]; %#ok<NASGU> % Update the user report(spin_system,'propagation finished.'); end % Make sure a full array is returned answer=full(answer); otherwise error('invalid output option.'); end case 'zeeman-hilb' % Decide whether to normalize the coils if ~isempty(coil) if ismember('norm_coil',spin_system.sys.disable) report(spin_system,'coil has not been normalized.'); else coil=coil/norm(coil,'fro'); report(spin_system,'coil has been normalized.'); end end % Run the evolution switch output case 'final' % Decide how to proceed switch spin_system.bas.approximation case 'none' % Compute the exponential propagator P=propagator(spin_system,L,timestep); % Report to the user report(spin_system,'propagating the system...'); % Decide parallelization style if iscell(rho) % Run in parallel over cells parfor k=1:numel(rho) for n=1:nsteps rho{k}=P*rho{k}*P' end end % Return the result answer=rho; else % If inside a parallel loop, avoid spmd if isworkernode % Propagate vectors and covectors for n=1:nsteps rho=P*rho*P'; end % Return the result answer=rho; else % Create covector array cov=speye(size(rho)); % Run in parallel over columns spmd % Slice density matrix and covectors codist=codistributor('1d',2); rho=codistributed(rho,codist); cov=codistributed(cov,codist); % Propagate vectors and covectors for n=1:nsteps rho=P*rho; cov=P*cov; end end % Return the result answer=gather(rho)*gather(cov)'; end end % Report to the user report(spin_system,'propagation finished.'); otherwise % Complain and bomb out error('unrecognised approximation specification.'); end case 'observable' % Decide how to proceed switch spin_system.bas.approximation case 'none' % Compute the exponential propagator P=propagator(spin_system,L,timestep); % Report to the user report(spin_system,'propagating the system...'); % If a stack is received, run 2D acquisition if iscell(rho) % Preallocate the answer answer=zeros(nsteps+1,numel(rho)); % Loop over the elements of the stack parfor k=1:numel(rho) % Grab a local copy rho_local=rho{k}; % Loop over time steps for n=1:(nsteps+1) % Compute the observable answer(n,k)=hdot(coil,rho_local); % Step forward rho_local=P*rho_local*P'; end end % If inside a parallel loop, avoid spmd elseif isworkernode % Preallocate the answer answer=zeros(nsteps+1,1); % Loop over time steps for n=1:(nsteps+1) % Compute the observable answer(n)=hdot(coil,rho); % Step forward rho=P*rho*P'; end % Otherwise use Kuprov-Edwards parallel split else % Create covector array cov=speye(size(rho)); % Parallel processing spmd % Slice density matrix and covectors codist=codistributor('1d',2); rho=codistributed(rho,codist); cov=codistributed(cov,codist); % Localize the problem rho_local=getLocalPart(rho); cov_local=getLocalPart(cov); fid_local=zeros(nsteps+1,1); % Loop over time steps for n=1:(nsteps+1) % Write local fid fid_local(n)=hdot(coil*cov_local,rho_local); % Step forward on rho and cov rho_local=P*rho_local; cov_local=P*cov_local; end % Collect the results answer=gplus(fid_local,1); end % Return the result answer=answer{1}; end % Report to the user report(spin_system,'propagation finished.'); otherwise % Complain and bomb out error('unrecognised approximation specification.'); end % Make sure a full array is returned answer=full(answer); case 'trajectory' % Decide how to proceed switch spin_system.bas.approximation case 'none' % Compute the exponential propagator P=propagator(spin_system,L,timestep); % Preallocate the answer answer=cell(1,nsteps+1); % Compute the trajectory report(spin_system,'propagating the system...'); for n=1:(nsteps+1) answer{n}=rho; rho=P*rho*P'; end report(spin_system,'propagation finished.'); otherwise % Complain and bomb out error('unrecognised approximation specification.'); end case 'refocus' % Decide how to proceed switch spin_system.bas.approximation case 'none' % Compute the exponential propagator P=propagator(spin_system,L,timestep); % Propagate the system report(spin_system,'propagating the system...'); parfor k=2:numel(rho) % Grab a local copy rho_local=rho{k}; % Propagate local copy for n=2:k rho_local=P*rho_local*P'; end % Return local copy rho{k}=rho_local; end answer=rho; report(spin_system,'propagation finished.'); otherwise % Complain and bomb out error('unrecognised approximation specification.'); end otherwise % Complain and bomb out error('unknown evolution option for zeeman-hilb formalism.'); end otherwise % Complain and bomb out error('unknown formalism specification.'); end end % Consistency enforcement function grumble(L,coil,rho,timestep,nsteps,output) if ~isnumeric(L) error('Liouvillian must be numeric.'); end if ~isnumeric(coil) error('coil argument must be numeric.'); end if (~isnumeric(rho))&&(~iscell(rho)) error('rho argument must either be numeric or a cell array'); end if ~isnumeric(timestep) error('timestep argument must be numeric.'); end if ~isnumeric(nsteps) error('nsteps must be numeric.'); end if (~ischar(output))||(~ismember(output,{'observable','final',... 'trajectory','total','multichannel','refocus'})) error('observable argument must be a valid character string.'); end end % Degrees of ability vary, but the basic principle remains the same: the % degree of a man's independence, initiative and personal love for his work % determines his talent as a worker and his worth as a man. Independence is % the only gauge of human virtue and value. What a man is and makes of him- % self; not what he has or hasn't done for others. There is no substitute % for personal dignity. There is no standard of personal dignity except % independence. % % Ayn Rand, "The Fountainhead"
github
tsajed/nmr-pred-master
hamiltonian.m
.m
nmr-pred-master/spinach/kernel/hamiltonian.m
33,597
utf_8
45431ad588a9b53651e7adf0d3d0bff5
% Hamiltonian operator / superoperator and its rotational decomposition. % Descriptor and operator generation is parallelized. Syntax: % % [H,Q]=hamiltonian(spin_system,operator_type) % % In Liouville space calculations, operator_type can be set to: % % 'left' - produces left side product superoperator % % 'right' - produces right side product superoperator % % 'comm' - produces commutation superoperator (default) % % 'acomm' - produces anticommutation superoperator % % In Hilbert space calculations operator_type parameter is ignored. % % Outputs: % H - isotropic part % % Q - twenty-five matrices giving irreducible % components of the anisotropic part % % Note: this function returns the full rotational basis that contains % information about all orientations. Use orientation.m to gene- % rate the Hamiltonian at a specific orientation. % % [email protected] % [email protected] % [email protected] % [email protected] function [H,Q]=hamiltonian(spin_system,operator_type) % Check consistency grumble(spin_system); % Set the default for the type if ~exist('operator_type','var'), operator_type='comm'; end % Decide if the Q part is required build_aniso=(nargout>1); % Inform the user report(spin_system,'building Hamiltonian descriptor...'); % Preallocate spin indices spin_L=zeros(spin_system.comp.nspins,8); spin_S=zeros(spin_system.comp.nspins,8); % Preallocate operator specifications oper_L(1:spin_system.comp.nspins,1:8)={'E'}; oper_S(1:spin_system.comp.nspins,1:8)={'E'}; % Preallocate isotropic Hamiltonian coefficients H_coeff=zeros(spin_system.comp.nspins,8); % Preallocate spherical tensor coefficients T_coeff=zeros(spin_system.comp.nspins,8,5); % Preallocate ireducible components irrcomp=zeros(spin_system.comp.nspins,8,5); % Process Zeeman interactions for n=1:spin_system.comp.nspins % Write the isotropic part switch spin_system.inter.zeeman.strength{n} case {'full','z_full'} % Add the carrier frequency zeeman_iso=trace(spin_system.inter.zeeman.matrix{n})/3+... spin_system.inter.basefrqs(n); % Update the Hamiltonian if significant(zeeman_iso,spin_system.tols.inter_cutoff) % Inform the user report(spin_system,['complete isotropic Zeeman interaction for spin ' num2str(n) '...']); report(spin_system,[' (Lz) x ' num2str(zeeman_iso/(2*pi)) ' Hz']); % Update the Hamiltonian descriptor spin_L(n,2)=n; oper_L(n,2)={'Lz'}; H_coeff(n,2)=zeeman_iso; end case {'secular','z_offs'} % Skip the carrier frequency zeeman_iso=trace(spin_system.inter.zeeman.matrix{n})/3; % Update the Hamiltonian if significant(zeeman_iso,spin_system.tols.inter_cutoff) % Inform the user report(spin_system,['offset isotropic Zeeman interaction for spin ' num2str(n) '...']); report(spin_system,[' (Lz) x ' num2str(zeeman_iso/(2*pi)) ' Hz']); % Update the Hamiltonian descriptor spin_L(n,2)=n; oper_L(n,2)={'Lz'}; H_coeff(n,2)=zeeman_iso; end case {'ignore','+','-'} % Inform the user report(spin_system,['isotropic Zeeman interaction ignored for spin ' num2str(n) '.']); otherwise % Bomb out with unexpected strength parameters error(['unknown strength specification for the Zeeman interaction of spin ' num2str(spin_L)]); end % Process anisotropic part if required if build_aniso % Get second rank spherical tensor components [~,~,phi_zeeman]=mat2sphten(spin_system.inter.zeeman.matrix{n}); % Process Zeeman interactions if significant(phi_zeeman,spin_system.tols.inter_cutoff) % Store coefficients for k=1:3, irrcomp(n,k,:)=phi_zeeman; end % Write irreducible spherical tensors switch spin_system.inter.zeeman.strength{n} case 'full' % Inform the user report(spin_system,['complete anisotropic Zeeman interaction for spin ' num2str(n) '...']); report(spin_system,[' -0.5*(Lp) x ' num2str(phi_zeeman(2)/(2*pi)) ' Hz']); report(spin_system,[' sqrt(2/3)*(Lz) x ' num2str(phi_zeeman(3)/(2*pi)) ' Hz']); report(spin_system,[' 0.5*(Lm) x ' num2str(phi_zeeman(4)/(2*pi)) ' Hz']); % Prepare spherical tensor descriptors spin_L(n,1)=n; oper_L(n,1)={'L+'}; T_coeff(n,1,2)=-0.5; spin_L(n,2)=n; oper_L(n,2)={'Lz'}; T_coeff(n,2,3)=sqrt(2/3); spin_L(n,3)=n; oper_L(n,3)={'L-'}; T_coeff(n,3,4)=+0.5; case {'secular','z_full','z_offs'} % Inform the user report(spin_system,['Z part of the anisotropic Zeeman interaction for spin ' num2str(n) '...']); report(spin_system,[' sqrt(2/3)*(Lz) x ' num2str(phi_zeeman(3)/(2*pi)) ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2)=n; oper_L(n,2)={'Lz'}; T_coeff(n,2,3)=sqrt(2/3); case '+' % Inform the user report(spin_system,['"+" part of the anisotropic Zeeman interaction for spin ' num2str(n) '...']); report(spin_system,[' -0.5*(Lp) x ' num2str(phi_zeeman(2)/(2*pi)) ' Hz']); % Prepare spherical tensor descriptors spin_L(n,1)=n; oper_L(n,1)={'L+'}; T_coeff(n,1,2)=-0.5; case '-' % Inform the user report(spin_system,['"-" part of the anisotropic Zeeman interaction for spin ' num2str(n) '...']); report(spin_system,[' 0.5*(Lm) x ' num2str(phi_zeeman(4)/(2*pi)) ' Hz']); % Prepare spherical tensor descriptors spin_L(n,3)=n; oper_L(n,3)={'L-'}; T_coeff(n,3,4)=+0.5; case 'ignore' % Inform the user report(spin_system,['anisotropic Zeeman interaction ignored for spin ' num2str(n) '.']); otherwise % Bomb out with unexpected strength parameters error(['unknown Zeeman interaction strength specification for spin ' num2str(n) '.']); end end % Get second rank spherical tensor components [~,~,phi_quad]=mat2sphten(spin_system.inter.coupling.matrix{n,n}); % Process quadrupolar interactions if significant(phi_quad,spin_system.tols.inter_cutoff) % Store coefficients for k=4:8, irrcomp(n,k,:)=phi_quad; end % Process the coupling switch spin_system.inter.coupling.strength{n,n} case 'strong' % Inform the user report(spin_system,['complete quadratic coupling for spin ' num2str(n) '...']); report(spin_system,[' T(2,+2) x ' num2str(phi_quad(1)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' T(2,+1) x ' num2str(phi_quad(2)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' T(2, 0) x ' num2str(phi_quad(3)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' T(2,-1) x ' num2str(phi_quad(4)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' T(2,-2) x ' num2str(phi_quad(5)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,4)=n; oper_L(n,4)={'T2,+2'}; T_coeff(n,4,1)=1; spin_L(n,5)=n; oper_L(n,5)={'T2,+1'}; T_coeff(n,5,2)=1; spin_L(n,6)=n; oper_L(n,6)={'T2,0'}; T_coeff(n,6,3)=1; spin_L(n,7)=n; oper_L(n,7)={'T2,-1'}; T_coeff(n,7,4)=1; spin_L(n,8)=n; oper_L(n,8)={'T2,-2'}; T_coeff(n,8,5)=1; case {'secular','T2,0'} % Inform the user report(spin_system,['secular part of the quadratic coupling for spin ' num2str(n) '...']); report(spin_system,[' T(2, 0) x ' num2str(phi_quad(3)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,6)=n; oper_L(n,6)={'T2,0'}; T_coeff(n,6,3)=1; case {'T2,+2'} % Inform the user report(spin_system,['T(2,+2) part of the quadratic coupling for spin ' num2str(n) '...']); report(spin_system,[' T(2,+2) x ' num2str(phi_quad(1)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,4)=n; oper_L(n,4)={'T2,+2'}; T_coeff(n,4,1)=1; case {'T2,-2'} % Inform the user report(spin_system,['T(2,-2) part of the quadratic coupling for spin ' num2str(n) '...']); report(spin_system,[' T(2,-2) x ' num2str(phi_quad(5)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,8)=n; oper_L(n,8)={'T2,-2'}; T_coeff(n,8,5)=1; case {'T2,+1'} % Inform the user report(spin_system,['T(2,+1) part of the quadratic coupling for spin ' num2str(n) '...']); report(spin_system,[' T(2,+1) x ' num2str(phi_quad(2)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,5)=n; oper_L(n,5)={'T2,+1'}; T_coeff(n,5,2)=1; case {'T2,-1'} % Inform the user report(spin_system,['T(2,-1) part of the quadratic coupling for spin ' num2str(n) '...']); report(spin_system,[' T(2,-1) x ' num2str(phi_quad(4)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,7)=n; oper_L(n,7)={'T2,-1'}; T_coeff(n,7,4)=1; case 'ignore' % Inform the user report(spin_system,['quadratic coupling ignored for spin ' num2str(n) '.']); otherwise % Bomb out with unexpected strength parameters error(['unknown strength specification for the quadratic coupling of spin ' num2str(n)]); end end end end % Pack single-spin descriptor table D1=table(reshape(spin_L,[8*spin_system.comp.nspins 1]),reshape(spin_S,[8*spin_system.comp.nspins 1]),... reshape(oper_L,[8*spin_system.comp.nspins 1]),reshape(oper_S,[8*spin_system.comp.nspins 1]),... reshape(H_coeff,[8*spin_system.comp.nspins 1]),reshape(T_coeff,[8*spin_system.comp.nspins 5]),... reshape(irrcomp,[8*spin_system.comp.nspins 5]),'VariableNames',{'L','S','opL','opS','H','T','phi'}); % Kill insignificant rows tol1=spin_system.tols.inter_cutoff; tol2=eps; D1((abs(D1.H)<tol1)&((sum(abs(D1.phi),2)<tol1)|(sum(abs(D1.T),2)<tol2)),:)=[]; % Clean up variables for re-use clear('spin_L','spin_S','oper_L','oper_S','H_coeff','T_coeff','irrcomp'); % Discover significant bilinear couplings and build interacting spin pair list [L,S]=find(cellfun(@norm,spin_system.inter.coupling.matrix)>spin_system.tols.inter_cutoff); quad_couplings=(L==S); L(quad_couplings)=[]; S(quad_couplings)=[]; pair_list=[L S]; if isempty(pair_list), pair_list=[]; end % Preallocate spin indices spin_L=zeros(size(pair_list,1),3,3); spin_S=zeros(size(pair_list,1),3,3); % Preallocate operator specifications oper_L(1:size(pair_list,1),1:3,1:3)={'E'}; oper_S(1:size(pair_list,1),1:3,1:3)={'E'}; % Preallocate isotropic Hamiltonian coefficients H_coeff=zeros(size(pair_list,1),3,3); % Preallocate spherical tensor coefficients T_coeff=zeros(size(pair_list,1),3,3,5); % Preallocate ireducible components irrcomp=zeros(size(pair_list,1),3,3,5); % Loop over the pair list for n=1:size(pair_list,1) % Extract spin numbers L=pair_list(n,1); S=pair_list(n,2); % Get the isotropic coupling constant coupling_iso=trace(spin_system.inter.coupling.matrix{L,S})/3; % Check if the coupling is significant if significant(coupling_iso,spin_system.tols.inter_cutoff) % Process the coupling switch spin_system.inter.coupling.strength{L,S} case {'strong','secular'} % Inform the user report(spin_system,['complete isotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' (LxSx+LySy+LzSz) x ' num2str(coupling_iso/(2*pi)) ' Hz']); % Update the Hamiltonian descriptor spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; H_coeff(n,2,2)=coupling_iso; spin_L(n,1,3)=L; spin_S(n,1,3)=S; oper_L(n,1,3)={'L+'}; oper_S(n,1,3)={'L-'}; H_coeff(n,1,3)=coupling_iso/2; spin_L(n,3,1)=L; spin_S(n,3,1)=S; oper_L(n,3,1)={'L-'}; oper_S(n,3,1)={'L+'}; H_coeff(n,3,1)=coupling_iso/2; case {'weak','z*','*z','zz'} % Inform the user report(spin_system,['(z,z) part of the isotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' (LzSz) x ' num2str(coupling_iso/(2*pi)) ' Hz']); % Update the Hamiltonian descriptor spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; H_coeff(n,2,2)=coupling_iso; case {'+-'} % Inform the user report(spin_system,['(+,-) part of the isotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LpSm) x ' num2str(coupling_iso/(2*pi)) ' Hz']); % Update the Hamiltonian descriptor spin_L(n,1,3)=L; spin_S(n,1,3)=S; oper_L(n,1,3)={'L+'}; oper_S(n,1,3)={'L-'}; H_coeff(n,1,3)=coupling_iso/2; case {'-+'} % Inform the user report(spin_system,['(-,+) part of the isotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LmSp) x ' num2str(coupling_iso/(2*pi)) ' Hz']); % Update the Hamiltonian descriptor spin_L(n,3,1)=L; spin_S(n,3,1)=S; oper_L(n,3,1)={'L-'}; oper_S(n,3,1)={'L+'}; H_coeff(n,3,1)=coupling_iso/2; case {'ignore','z+','z-','+z','-z','++','--','T2,0','T(2,+1)','T(2,-1)','T(2,+2)','T(2,-2)'} % Inform the user report(spin_system,['isotropic coupling ignored for spins ' num2str(L) ',' num2str(S) '.']); otherwise % Bomb out with unexpected strength parameters error(['unknown strength specification for the bilinear coupling between spins ' num2str(L) ' and ' num2str(S)]); end end % Process anisotropic part if required if build_aniso % Get second rank spherical tensor components [~,~,phi_coupling]=mat2sphten(spin_system.inter.coupling.matrix{L,S}); % Check if it is significant if significant(phi_coupling,spin_system.tols.inter_cutoff) % Store coefficients for k=1:3, for m=1:3, irrcomp(n,k,m,:)=phi_coupling; end; end % Write irreducible spherical tensors switch spin_system.inter.coupling.strength{L,S} case 'strong' % Inform the user report(spin_system,['complete anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LpSp) x ' num2str(phi_coupling(1)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' -0.5*(LzSp+LpSz) x ' num2str(phi_coupling(2)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' sqrt(2/3)*(LzSz-0.25*(LpSm+LmSp)) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' 0.5*(LzSm+LmSz) x ' num2str(phi_coupling(4)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' 0.5*(LmSm) x ' num2str(phi_coupling(5)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; T_coeff(n,2,2,3)=+sqrt(2/3); spin_L(n,1,3)=L; spin_S(n,1,3)=S; oper_L(n,1,3)={'L+'}; oper_S(n,1,3)={'L-'}; T_coeff(n,1,3,3)=-sqrt(2/3)/4; spin_L(n,3,1)=L; spin_S(n,3,1)=S; oper_L(n,3,1)={'L-'}; oper_S(n,3,1)={'L+'}; T_coeff(n,3,1,3)=-sqrt(2/3)/4; spin_L(n,2,1)=L; spin_S(n,2,1)=S; oper_L(n,2,1)={'Lz'}; oper_S(n,2,1)={'L+'}; T_coeff(n,2,1,2)=-1/2; spin_L(n,1,2)=L; spin_S(n,1,2)=S; oper_L(n,1,2)={'L+'}; oper_S(n,1,2)={'Lz'}; T_coeff(n,1,2,2)=-1/2; spin_L(n,2,3)=L; spin_S(n,2,3)=S; oper_L(n,2,3)={'Lz'}; oper_S(n,2,3)={'L-'}; T_coeff(n,2,3,4)=+1/2; spin_L(n,3,2)=L; spin_S(n,3,2)=S; oper_L(n,3,2)={'L-'}; oper_S(n,3,2)={'Lz'}; T_coeff(n,3,2,4)=+1/2; spin_L(n,1,1)=L; spin_S(n,1,1)=S; oper_L(n,1,1)={'L+'}; oper_S(n,1,1)={'L+'}; T_coeff(n,1,1,1)=+1/2; spin_L(n,3,3)=L; spin_S(n,3,3)=S; oper_L(n,3,3)={'L-'}; oper_S(n,3,3)={'L-'}; T_coeff(n,3,3,5)=+1/2; case 'z*' % Inform the user report(spin_system,['(z,*) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.5*(LzSp) x ' num2str(phi_coupling(2)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' sqrt(2/3)*(LzSz) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' 0.5*(LzSm) x ' num2str(phi_coupling(4)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; T_coeff(n,2,2,3)=+sqrt(2/3); spin_L(n,2,1)=L; spin_S(n,2,1)=S; oper_L(n,2,1)={'Lz'}; oper_S(n,2,1)={'L+'}; T_coeff(n,2,1,2)=-1/2; spin_L(n,2,3)=L; spin_S(n,2,3)=S; oper_L(n,2,3)={'Lz'}; oper_S(n,2,3)={'L-'}; T_coeff(n,2,3,4)=+1/2; case '*z' % Inform the user report(spin_system,['(*,z) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.5*(LpSz) x ' num2str(phi_coupling(2)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' sqrt(2/3)*(LzSz) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); report(spin_system,[' 0.5*(LmSz) x ' num2str(phi_coupling(4)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; T_coeff(n,2,2,3)=+sqrt(2/3); spin_L(n,1,2)=L; spin_S(n,1,2)=S; oper_L(n,1,2)={'L+'}; oper_S(n,1,2)={'Lz'}; T_coeff(n,1,2,2)=-1/2; spin_L(n,3,2)=L; spin_S(n,3,2)=S; oper_L(n,3,2)={'L-'}; oper_S(n,3,2)={'Lz'}; T_coeff(n,3,2,4)=+1/2; case {'secular','T2,0'} % Inform the user report(spin_system,['secular part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' sqrt(2/3)*(LzSz-0.25*(LpSm+LmSp)) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; T_coeff(n,2,2,3)=+sqrt(2/3); spin_L(n,1,3)=L; spin_S(n,1,3)=S; oper_L(n,1,3)={'L+'}; oper_S(n,1,3)={'L-'}; T_coeff(n,1,3,3)=-sqrt(2/3)/4; spin_L(n,3,1)=L; spin_S(n,3,1)=S; oper_L(n,3,1)={'L-'}; oper_S(n,3,1)={'L+'}; T_coeff(n,3,1,3)=-sqrt(2/3)/4; case {'weak','zz'} % Inform the user report(spin_system,['(z,z) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' sqrt(2/3)*(LzSz) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,2)=L; spin_S(n,2,2)=S; oper_L(n,2,2)={'Lz'}; oper_S(n,2,2)={'Lz'}; T_coeff(n,2,2,3)=+sqrt(2/3); case 'z+' % Inform the user report(spin_system,['(z,+) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.5*(LzSp) x ' num2str(phi_coupling(2)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,1)=L; spin_S(n,2,1)=S; oper_L(n,2,1)={'Lz'}; oper_S(n,2,1)={'L+'}; T_coeff(n,2,1,2)=-1/2; case '+z' % Inform the user report(spin_system,['(+,z) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.5*(LpSz) x ' num2str(phi_coupling(2)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,1,2)=L; spin_S(n,1,2)=S; oper_L(n,1,2)={'L+'}; oper_S(n,1,2)={'Lz'}; T_coeff(n,1,2,2)=-1/2; case 'T(2,+1)' % Inform the user report(spin_system,['T(2,+1) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.5*(LpSz+LzSp) x ' num2str(phi_coupling(2)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,1)=L; spin_S(n,2,1)=S; oper_L(n,2,1)={'Lz'}; oper_S(n,2,1)={'L+'}; T_coeff(n,2,1,2)=-1/2; spin_L(n,1,2)=L; spin_S(n,1,2)=S; oper_L(n,1,2)={'L+'}; oper_S(n,1,2)={'Lz'}; T_coeff(n,1,2,2)=-1/2; case 'z-' % Inform the user report(spin_system,['(z,-) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LzSm) x ' num2str(phi_coupling(4)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,3)=L; spin_S(n,2,3)=S; oper_L(n,2,3)={'Lz'}; oper_S(n,2,3)={'L-'}; T_coeff(n,2,3,4)=+1/2; case '-z' % Inform the user report(spin_system,['(-,z) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LmSz) x ' num2str(phi_coupling(4)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,3,2)=L; spin_S(n,3,2)=S; oper_L(n,3,2)={'L-'}; oper_S(n,3,2)={'Lz'}; T_coeff(n,3,2,4)=+1/2; case 'T(2,-1)' % Inform the user report(spin_system,['T(2,-1) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LmSz+LzSm) x ' num2str(phi_coupling(4)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,2,3)=L; spin_S(n,2,3)=S; oper_L(n,2,3)={'Lz'}; oper_S(n,2,3)={'L-'}; T_coeff(n,2,3,4)=+1/2; spin_L(n,3,2)=L; spin_S(n,3,2)=S; oper_L(n,3,2)={'L-'}; oper_S(n,3,2)={'Lz'}; T_coeff(n,3,2,4)=+1/2; case '+-' % Inform the user report(spin_system,['(+,-) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.25*sqrt(2/3)*(LpSm) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,1,3)=L; spin_S(n,1,3)=S; oper_L(n,1,3)={'L+'}; oper_S(n,1,3)={'L-'}; T_coeff(n,1,3,3)=-sqrt(2/3)/4; case '-+' % Inform the user report(spin_system,['(-,+) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' -0.25*sqrt(2/3)*(LmSp) x ' num2str(phi_coupling(3)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,3,1)=L; spin_S(n,3,1)=S; oper_L(n,3,1)={'L-'}; oper_S(n,3,1)={'L+'}; T_coeff(n,3,1,3)=-sqrt(2/3)/4; case {'++','T2,+2'} % Inform the user report(spin_system,['(+,+) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LpSp) x ' num2str(phi_coupling(1)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,1,1)=L; spin_S(n,1,1)=S; oper_L(n,1,1)={'L+'}; oper_S(n,1,1)={'L+'}; T_coeff(n,1,1,1)=+1/2; case {'--','T2,-2'} % Inform the user report(spin_system,['(-,-) part of the anisotropic coupling for spins ' num2str(L) ',' num2str(S) '...']); report(spin_system,[' 0.5*(LmSm) x ' num2str(phi_coupling(5)/(2*pi),'%+0.5e') ' Hz']); % Prepare spherical tensor descriptors spin_L(n,3,3)=L; spin_S(n,3,3)=S; oper_L(n,3,3)={'L-'}; oper_S(n,3,3)={'L-'}; T_coeff(n,3,3,5)=+1/2; case 'ignore' % Inform the user report(spin_system,['anisotropic coupling ignored for spins ' num2str(L) ',' num2str(S) '.']); otherwise % Bomb out with unexpected strength parameters error(['unknown strength specification for the bilinear coupling between spins ' num2str(L) ' and ' num2str(S)]); end end end end % Pack two-spin descriptor table D2=table(reshape(spin_L, [9*size(pair_list,1) 1]),reshape(spin_S, [9*size(pair_list,1) 1]),... reshape(oper_L, [9*size(pair_list,1) 1]),reshape(oper_S, [9*size(pair_list,1) 1]),... reshape(H_coeff,[9*size(pair_list,1) 1]),reshape(T_coeff,[9*size(pair_list,1) 5]),... reshape(irrcomp,[9*size(pair_list,1) 5]),'VariableNames',{'L','S','opL','opS','H','T','phi'}); % Kill insignificant rows tol1=spin_system.tols.inter_cutoff; tol2=eps; D2((abs(D2.H)<tol1)&((sum(abs(D2.phi),2)<tol1)|(sum(abs(D2.T),2)<tol2)),:)=[]; % Merge descriptors and clean up descr=[D1; D2]; clear('D1','D2'); nterms=size(descr,1); clear('spin_L','spin_S','oper_L','oper_S','H_coeff','T_coeff','irrcomp'); report(spin_system,[num2str(nterms) ' unique operators in the Hamiltonian descriptor.']); % Balance the descriptor report(spin_system,'balancing descriptor for parallel processing...'); descr=descr(randperm(size(descr,1)),:); % Build the Hamiltonian report(spin_system,'building the Hamiltonian...'); spmd % Localize the problem at the nodes partition=codistributor1d.defaultPartition(nterms); codistrib=codistributor1d(1,partition,[nterms 1]); local_terms=getLocalPart(codistributed((1:nterms)',codistrib)); % Preallocate the local Hamiltonian H=0*unit_oper(spin_system); if build_aniso Q=cell(5,5); for m=1:5 for k=1:5 Q{k,m}=0*unit_oper(spin_system); end end end % Build the local Hamiltonian for n=local_terms' % Compute operator from the specification if descr.S(n)==0 oper=operator(spin_system,descr.opL(n),{descr.L(n)},operator_type); else oper=operator(spin_system,[descr.opL(n),descr.opS(n)],{descr.L(n),descr.S(n)},operator_type); end % Add to relevant local arrays H=H+descr.H(n)*oper; if build_aniso for m=1:5 for k=1:5 if abs(descr.T(n,k)*descr.phi(n,m))>spin_system.tols.inter_cutoff Q{k,m}=Q{k,m}+descr.T(n,k)*descr.phi(n,m)*oper; end end end end end % Collect the result H=gplus(H,1); if build_aniso, Q=gplus(Q,1); end end % Retrieve the result H=H{1}; if build_aniso, Q=Q{1}; end % Clean up the result H=clean_up(spin_system,H,spin_system.tols.liouv_zero); if build_aniso for m=1:5 for k=1:5 Q{k,m}=clean_up(spin_system,Q{k,m},spin_system.tols.liouv_zero); end end end % Remind the user about the anisotropic part if ~build_aniso report(spin_system,'WARNING - only the isotropic part has been returned.'); end end % Consistency enforcement function grumble(spin_system) if ~isfield(spin_system,'bas') error('basis set information is missing, run basis() before calling this function.'); end if (~isfield(spin_system.inter.coupling,'strength'))||... (~isfield(spin_system.inter.zeeman,'strength')) error('assumption information is missing, run assume() before calling this function.'); end end % IK's favourite composer is Jeremy Soule -- much of Spinach % coding was done with Skyrim, Guild Wars and Oblivion sound- % tracks in the background. It is the sign of the times that % a worthy successor to Ennio Morricone has emerged from the % unlikeliest of locations: videogame music.
github
tsajed/nmr-pred-master
orientation.m
.m
nmr-pred-master/spinach/kernel/orientation.m
1,945
utf_8
d225044f72eed3cbc2036cc373a68f1b
% Anisotropic part of the Hamiltonian for a specific spin system % orientation. Syntax: % % H=orientation(Q,euler_angles) % % Arguments: % % Q - rotational basis as returned by hamiltonian % function. % % euler_angles - a 1x3 vector or a vertical stack of 1x3 % vectors specifying Euler angles (radians) % relative to the input orientation. % % Output: % % H - anisotropic part of the Hamiltonian commutation % superoperator (or a cell array thereof) for the % specified Euler angles. % % This function may be used in both Hilbert and Liouville space % because the H -> [H, ] adjoint map is linear. % % [email protected] function H=orientation(Q,euler_angles) % Check consistency grumble(Q,euler_angles); % Determine problem dimension n_orientations=size(euler_angles,1); % Preallocate the result array H=cell(n_orientations,1); for n=1:n_orientations H{n}=0*Q{1,1}; end % Compute Wigner matrices D=cell(n_orientations,1); for n=1:n_orientations D{n}=euler2wigner(euler_angles(n,1),... euler_angles(n,2),... euler_angles(n,3)); end % Compute Hamiltonian operators for n=1:n_orientations for k=1:5 for m=1:5 H{n}=H{n}+(D{n}(k,m))*Q{k,m}; end end H{n}=(H{n}+H{n}')/2; end % If there is only one operator to return, remove the cell if numel(H)==1, H=H{1}; end end % Consistency enforcement function grumble(Q,euler_angles) if (~iscell(Q))||any(size(Q)~=[5 5]) error('Q parameter must be a 5x5 cell array of matrices.'); end if (~isnumeric(euler_angles))||(size(euler_angles,2)~=3) error('Euler angles must be supplied as a row vector or a vertical stack thereof.') end end % 1f y0u c4n r34d 7h15, y0u r34||y n33d 70 637 |41d
github
tsajed/nmr-pred-master
splice.m
.m
nmr-pred-master/spinach/kernel/splice.m
4,118
utf_8
765f21f9b3ef8b6b23220e95dedbb5bd
% Merges timing tables of pulse sequence channels. Both timing tables % should be given as row arrays of the following structure: % % A={A_1 A_2 ... A_n}; dtA=[dt_1 dt_2 ... dt_n]; % % where A_k is a spin operator and dt_k is the time for which it acts. % The sequence is assumed to be executed chronologically from left to % right. The two event sequences can be aligned left, right or centre % with respect to one another. Syntax: % % [C,dtC]=splice(A,dtA,B,dtB,alignment) % % [email protected] function [C,dtC]=splice(A,dtA,B,dtB,alignment) % Check consistency grumble(A,dtA,B,dtB,alignment); % Determine problem dimension dim=size(A{1},1); % Set the alignment type switch alignment case 'left' % Find event edges tA_edges=[0 cumsum(dtA)]; tB_edges=[0 cumsum(dtB)]; % Pad the shorter sequence with zero operators if max(tA_edges)<max(tB_edges), A=[A {spalloc(dim,dim,0)}]; end if max(tA_edges)>max(tB_edges), B=[B {spalloc(dim,dim,0)}]; end % Build new timing diagram tC_edges=unique([tA_edges tB_edges]); % Build new operator list C=cell(1,numel(tC_edges)-1); for n=1:numel(C) % Find values of A and B in the current period current_time=(tC_edges(n)+tC_edges(n+1))/2; A_part=A(find(tA_edges<current_time,1,'last')); B_part=B(find(tB_edges<current_time,1,'last')); % Assign the result if isempty(A_part), A_part={spalloc(dim,dim,0)}; end if isempty(B_part), B_part={spalloc(dim,dim,0)}; end C{n}=A_part{1}+B_part{1}; end % Compute new time increments dtC=diff(tC_edges); case 'right' % Reverse the inputs A=flip(A); dtA=flip(dtA); B=flip(B); dtB=flip(dtB); % Perform left-aligned splice [C,dtC]=splice(A,dtA,B,dtB,'left'); % Reverse the output C=flip(C); dtC=flip(dtC); case 'centre' % Find event edges tA_right=cumsum(dtA); tB_right=cumsum(dtB); % Pad the shorter sequence with zero operators if tA_right(end)<tB_right(end) dtA=[(tB_right(end)-tA_right(end))/2 dtA]; A=[{spalloc(dim,dim,0)} A]; elseif tA_right(end)>tB_right(end) dtB=[(tA_right(end)-tB_right(end))/2 dtB]; B=[{spalloc(dim,dim,0)} B]; end % Perform left-aligned splice [C,dtC]=splice(A,dtA,B,dtB,'left'); otherwise % Complain and bomb out error('unknown alignment type.'); end end % Consistency enforcement function grumble(A,dtA,B,dtB,alignment) if (~iscell(A))||(~iscell(B))||isempty(A)||isempty(B)||(~isrow(A))||(~isrow(B)) error('A and B arguments must be row cell arrays of matrices.'); end if (~all(cellfun(@issparse,A)))||(~all(cellfun(@issparse,B))) error('all elements of A and B must be sparse.'); end if (~isnumeric(dtA))||(~isnumeric(dtB))||(~isrow(dtA))||(~isrow(dtB))||any(dtA<=0)||any(dtB<=0) error('dtA and dtB arguments must be row vectors of positive numbers.'); end if ~ischar(alignment) error('the alignment argument must be a character string.'); end end % The JEOL Student Prize, awarded at the annual conferences of the Royal Society % of Chemistry ESR Group, had one winner in its history who got the Prize before % she even started talking. As the laptop was being connected to the projection % system and the usual technology gremlins refused to work, Petra Luders uncere- % moniously pushed aside the lost-looking IT guy and got the thing to work in a % few keystrokes on what appeared to be a Linux system. "And here's our winner" % thought every Committee member with a quiet smile. The science and the presen- % tation easily outshined every other competitor - Ms Luders got her JEOL Medal.
github
tsajed/nmr-pred-master
rotframe.m
.m
nmr-pred-master/spinach/kernel/rotframe.m
2,062
utf_8
e115fa73c9e879a9753f418c8537ee1a
% Rotating frame transformation with respect to a specified % group of spins to specified order in perturbation theory. % Syntax: % % H=rotframe(spin_system,H0,H,isotope,order) % % Parameters: % % H0 - carrier Hamiltonian with respect to which the % rotating frame transformation is to be done % % H - laboratory frame Hamiltonian H0+H1 that is to % be transformed into the rotating frame % % isotope - string, such as '1H', specifying the spins % with respect to which the transformation is % being computed % % order - perturbation theory order in the rotating % frame transformation % % [email protected] function Hr=rotframe(spin_system,H0,H,isotope,order) % Check consistency grumble(H0,H,order); % Compute the period switch spin_system.bas.formalism case {'zeeman-liouv','sphten-liouv'} % Liouville space period for H0 T=-2*pi/(spin(isotope)*spin_system.inter.magnet); case {'zeeman-hilb'} % Hilbert space period for H0 T=-4*pi/(spin(isotope)*spin_system.inter.magnet); end % Run the interaction representation transformation Hr=intrep(spin_system,H0,H,T,order); end % Consistency enforcement function grumble(H0,H,order) if (~ishermitian(H))||(~ishermitian(H0)) error('both H and C must be Hermitian.'); end if ((~isreal(order))||(order<1)||(mod(order,1)~=0))&&(~isinf(order)) error('unsupported rotating frame transformation theory order.'); end end % Finally, I acknowledge the financial support of EPSRC in its best, % that is, the responsive mode. This Nobel Prize would be absolutely % impossible without this mode. [...] However, I can offer no nice % words for the EU Framework Programmes which, except for the Europe- % an Research Council, can be praised only by europhobes for discre- % diting the whole idea of an effectively working Europe. % % Andre Geim's Nobel Lecture, 2010
github
tsajed/nmr-pred-master
average.m
.m
nmr-pred-master/spinach/kernel/average.m
9,900
utf_8
b95fad736487064601cfde341ec9859b
% Average Hamiltonian theories under Zeeman interaction rotating frame % transformations. Syntax: % % H=average(spin_system,Hp,H0,Hm,omega,theory) % % Parameters: % % Hp - the part of the rotating frame Hamiltonian that has positive % frequency under the rotating frame transformation % % H0 - the part of the rotating frame Hamiltonian that has zero % frequency under the rotating frame transformation % % Hm - the part of the rotating frame Hamiltonian that has negative % frequency under the rotating frame transformation % % omega - the frequency of the rotating frame transformation, rad/s % % theory - the level of the average Hamiltonian theory: % % 'ah_first_order' - first order in Waugh theory % % 'ah_second_order' - second order in Waugh theory % % 'ah_third_order' - third order in Waugh theory % % 'matrix_log' - exact algorithm (very expensive, % uses dense matrix algebra) % % 'kb_first_order' - first order in Krylov-Bogolyubov % theory (DNP experiments only) % % 'kb_second_order' - second order in Krylov-Bogolyubov % theory (DNP experiments only) % % 'kb_second_order' - third order in Krylov-Bogolyubov % theory (DNP experiments only) % % Note: Krylov-Bogolyubov averging theory as applied to DNP systems is % described in detail here: % % http://dx.doi.org/10.1039/C2CP23233B % http://dx.doi.org/10.1007/s00723-012-0367-0 % % [email protected] % [email protected] % [email protected] function H=average(spin_system,Hp,H0,Hm,omega,theory) % Check consistency grumble(Hp,H0,Hm,omega,theory); % Print diagnostics report(spin_system,['H+ 1-norm: ' num2str(norm(Hp,1))]); report(spin_system,['H0 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['H- 1-norm: ' num2str(norm(Hm,1))]); report(spin_system,['frequency denominator ' num2str(omega/(2*pi)) ' Hz']); % Run the averaging switch theory case 'kb_first_order' H1=+(1/omega^1)*(Hp*Hm-Hm*Hp); H=H0+H1; report(spin_system,['Krylov-Bogolyubov 0 order 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['Krylov-Bogolyubov 1 order 1-norm: ' num2str(norm(H1,1))]); case 'kb_second_order' H1=+(1/omega^1)*(Hp*Hm-Hm*Hp); H2=-(1/omega^2)*(Hp*(Hm*H0-H0*Hm)+Hm*(Hp*H0-H0*Hp)); H=H0+H1+H2; report(spin_system,['Krylov-Bogolyubov 0 order 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['Krylov-Bogolyubov 1 order 1-norm: ' num2str(norm(H1,1))]); report(spin_system,['Krylov-Bogolyubov 2 order 1-norm: ' num2str(norm(H2,1))]); case 'kb_third_order' H1=+(1/omega^1)*(Hp*Hm-Hm*Hp); H2=-(1/omega^2)*(Hp*(Hm*H0-H0*Hm)+Hm*(Hp*H0-H0*Hp)); H3=+(1/omega^3)*(0.5*(Hm*Hm*Hp*Hp-Hp*Hp*Hm*Hm)+... (Hp*Hm+Hm*Hp)*(Hp*Hm-Hm*Hp)+... Hp*(H0*(Hm*H0-H0*Hm)-(Hm*H0-H0*Hm)*H0)-... Hm*(H0*(Hp*H0-H0*Hp)-(Hp*H0-H0*Hp)*H0)); H=H0+H1+H2+H3; report(spin_system,['Krylov-Bogolyubov 0 order 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['Krylov-Bogolyubov 1 order 1-norm: ' num2str(norm(H1,1))]); report(spin_system,['Krylov-Bogolyubov 2 order 1-norm: ' num2str(norm(H2,1))]); report(spin_system,['Krylov-Bogolyubov 3 order 1-norm: ' num2str(norm(H3,1))]); case 'ah_first_order' H1=-(1/omega)*(H0*Hm-H0*Hp-Hm*H0+Hm*Hp+Hp*H0-Hp*Hm); H=H0+H1; report(spin_system,['average Hamiltonian 0 order 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['average Hamiltonian 1 order 1-norm: ' num2str(norm(H1,1))]); case 'ah_second_order' H1=-(1/omega^1)*(H0*Hm-H0*Hp-Hm*H0+Hm*Hp+Hp*H0-Hp*Hm); H2=-(1/omega^2)*(2*H0*H0*Hm + 2*H0*H0*Hp - 4*H0*Hm*H0 - 1*H0*Hm*Hm + 2*H0*Hm*Hp - ... 4*H0*Hp*H0 + 2*H0*Hp*Hm - 1*H0*Hp*Hp + 2*Hm*H0*H0 + 2*Hm*H0*Hm - ... 4*Hm*H0*Hp - 1*Hm*Hm*H0 + 2*Hm*Hm*Hp + 2*Hm*Hp*H0 - 4*Hm*Hp*Hm + ... 2*Hm*Hp*Hp + 2*Hp*H0*H0 - 4*Hp*H0*Hm + 2*Hp*H0*Hp + 2*Hp*Hm*H0 + ... 2*Hp*Hm*Hm - 4*Hp*Hm*Hp - 1*Hp*Hp*H0 + 2*Hp*Hp*Hm)/2; H=H0+H1+H2; report(spin_system,['average Hamiltonian 0 order 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['average Hamiltonian 1 order 1-norm: ' num2str(norm(H1,1))]); report(spin_system,['average Hamiltonian 2 order 1-norm: ' num2str(norm(H2,1))]); case 'ah_third_order' H1=-(1/omega^1)*(H0*Hm-H0*Hp-Hm*H0+Hm*Hp+Hp*H0-Hp*Hm); H2=-(1/omega^2)*(2*H0*H0*Hm + 2*H0*H0*Hp - 4*H0*Hm*H0 - 1*H0*Hm*Hm + 2*H0*Hm*Hp - ... 4*H0*Hp*H0 + 2*H0*Hp*Hm - 1*H0*Hp*Hp + 2*Hm*H0*H0 + 2*Hm*H0*Hm - ... 4*Hm*H0*Hp - 1*Hm*Hm*H0 + 2*Hm*Hm*Hp + 2*Hm*Hp*H0 - 4*Hm*Hp*Hm + ... 2*Hm*Hp*Hp + 2*Hp*H0*H0 - 4*Hp*H0*Hm + 2*Hp*H0*Hp + 2*Hp*Hm*H0 + ... 2*Hp*Hm*Hm - 4*Hp*Hm*Hp - 1*Hp*Hp*H0 + 2*Hp*Hp*Hm)/2; H3=+(1/omega^3)*(12*H0*H0*H0*Hm - 12*H0*H0*H0*Hp - 36*H0*H0*Hm*H0 - 9*H0*H0*Hm*Hm + ... 12*H0*H0*Hm*Hp + 36*H0*H0*Hp*H0 - 12*H0*H0*Hp*Hm + 9*H0*H0*Hp*Hp + ... 36*H0*Hm*H0*H0 + 18*H0*Hm*H0*Hm - 36*H0*Hm*H0*Hp + 2*H0*Hm*Hm*Hm + ... 18*H0*Hm*Hm*Hp + 12*H0*Hm*Hp*H0 - 36*H0*Hm*Hp*Hm - 36*H0*Hp*H0*H0 + ... 36*H0*Hp*H0*Hm - 18*H0*Hp*H0*Hp - 12*H0*Hp*Hm*H0 + 36*H0*Hp*Hm*Hp - ... 18*H0*Hp*Hp*Hm - 2*H0*Hp*Hp*Hp - 12*Hm*H0*H0*H0 + 36*Hm*H0*H0*Hp - ... 18*Hm*H0*Hm*H0 - 6*Hm*H0*Hm*Hm - 36*Hm*H0*Hp*H0 + 36*Hm*H0*Hp*Hm - ... 18*Hm*H0*Hp*Hp + 9*Hm*Hm*H0*H0 + 6*Hm*Hm*H0*Hm - 18*Hm*Hm*H0*Hp - ... 2*Hm*Hm*Hm*H0 + 6*Hm*Hm*Hm*Hp - 18*Hm*Hm*Hp*Hm + 18*Hm*Hm*Hp*Hp + ... 12*Hm*Hp*H0*H0 - 36*Hm*Hp*H0*Hm + 36*Hm*Hp*Hm*H0 + 18*Hm*Hp*Hm*Hm - ... 36*Hm*Hp*Hm*Hp + 18*Hm*Hp*Hp*H0 + 6*Hm*Hp*Hp*Hp + 12*Hp*H0*H0*H0 - ... 36*Hp*H0*H0*Hm + 36*Hp*H0*Hm*H0 + 18*Hp*H0*Hm*Hm - 36*Hp*H0*Hm*Hp + ... 18*Hp*H0*Hp*H0 + 6*Hp*H0*Hp*Hp - 12*Hp*Hm*H0*H0 + 36*Hp*Hm*H0*Hp - ... 18*Hp*Hm*Hm*H0 - 6*Hp*Hm*Hm*Hm - 36*Hp*Hm*Hp*H0 + 36*Hp*Hm*Hp*Hm - ... 18*Hp*Hm*Hp*Hp - 9*Hp*Hp*H0*H0 + 18*Hp*Hp*H0*Hm - 6*Hp*Hp*H0*Hp - ... 18*Hp*Hp*Hm*Hm + 18*Hp*Hp*Hm*Hp + 2*Hp*Hp*Hp*H0 - 6*Hp*Hp*Hp*Hm)/12; H=H0+H1+H2+H3; report(spin_system,['average Hamiltonian 0 order 1-norm: ' num2str(norm(H0,1))]); report(spin_system,['average Hamiltonian 1 order 1-norm: ' num2str(norm(H1,1))]); report(spin_system,['average Hamiltonian 2 order 1-norm: ' num2str(norm(H2,1))]); report(spin_system,['average Hamiltonian 3 order 1-norm: ' num2str(norm(H3,1))]); case 'matrix_log' % Number of points nslices=16; % Set up the time grid time_grid=linspace(0,2*pi/omega,nslices+1); time_step=time_grid(2); % Start with a unit propagator P=eye(size(H0)); % Multiply up the slices report(spin_system,'multiplying up slices...'); parfor n=1:nslices report(spin_system,['slice ' num2str(n) ' out of ' num2str(nslices) '...']); P=propagator(spin_system,(H0+exp(+1i*omega*(time_grid(n)+time_step/2))*Hp+... exp(-1i*omega*(time_grid(n)+time_step/2))*Hm),time_step)*P; end % Take the matrix log report(spin_system,'computing matrix logarithm...'); H=clean_up(spin_system,1i*(omega/(2*pi))*logm(P),spin_system.tols.liouv_zero); % Report to the user report(spin_system,['average Hamiltonian dimension ' num2str(size(H,1))... ', nnz ' num2str(nnz(H)) ', density ' num2str(100*nnz(H)/numel(H))... '%, 1-norm ' num2str(norm(H,1)) ', sparsity ' num2str(issparse(H))]); otherwise error('unknown theory specification.'); end % Clean up the result H=clean_up(spin_system,H,spin_system.tols.liouv_zero); % Force the result into sparse format H=sparse(H); end % Consistency enforcement function grumble(Hp,H0,Hm,omega,theory) if (~isnumeric(Hp))||(~isnumeric(H0))||(~isnumeric(Hm))||... (~ismatrix(Hp))||(~ismatrix(H0))||(~ismatrix(Hm)) error('the three Hamiltonian components must be matrices.'); end if any(size(Hp)~=size(H0))||any(size(H0)~=size(Hm)) error('dimensions of the three Hamiltonian components must be the same.'); end if (~isnumeric(omega))||(~isreal(omega))||(~isscalar(omega)) error('omega parameter must be a real number.'); end if ~ischar(theory) error('theory parameter must be a character string.'); end end % I save about twenty drafts - that's ten meg of disc space - and the last % one contains all the final alterations. Once it has been printed out and % received by the publishers, there's a cry here of "Tough shit, literary % researchers of the future, try getting a proper job!" and the rest are % wiped. % % Terry Pratchett
github
tsajed/nmr-pred-master
carrier.m
.m
nmr-pred-master/spinach/kernel/carrier.m
1,110
utf_8
aa5ea9c3a4ec0a4f321d12e31567ceb6
% Returns the "carrier" Hamiltonian - the part of the Zeeman % interaction Hamiltonian that corresponds to all particles % having the Zeeman frequency prescribed by their magnetogy- % ric ratio and the magnet field specified by the user. This % Hamiltonian is frequently used in rotating frame transfor- % mations and average Hamiltonian theories. Syntax: % % H=carrier(spin_system,spins) % % [email protected] function H=carrier(spin_system,spins) % Preallocate the answer H=mprealloc(spin_system,1); % Find the spins if strcmp(spins,'all') spin_index=1:spin_system.comp.nspins; else spin_index=find(strcmp(spins,spin_system.comp.isotopes)); end % Compute the answer for n=1:numel(spin_index) %#ok<*PFBNS> if significant(spin_system.inter.basefrqs(spin_index(n)),spin_system.tols.liouv_zero) H=H+spin_system.inter.basefrqs(spin_index(n))*operator(spin_system,{'Lz'},{spin_index(n)}); end end % Clean up the answer H=clean_up(spin_system,(H+H')/2,spin_system.tols.liouv_zero); end % Atelophobia - (n.) fear of imperfection
github
tsajed/nmr-pred-master
decouple.m
.m
nmr-pred-master/spinach/kernel/decouple.m
3,030
utf_8
7872a92a90308c8b6b7282e230084a90
% Obliterates all interactions and populations in the subspace of states % that involve user-specified spins in any way. The specified spins would % not contribute to the system dynamics until the Liouvillian is rebuilt % from scratch. Syntax: % % [L,rho]=decouple(spin_system,L,rho,spins) % % spins: spins to be wiped, specified either by name, such as '13C', % or by a list of numbers, such as [1 2 3]. % % L: Liouvillian superoperator % % rho: state vector or a horizontal stack thereof % % Note: this function is an analytical equivalent of a running decoupling % pulse sequence on the specified spins. % % Note: this function requires sphten-liouv formalism. % % [email protected] function [L,rho]=decouple(spin_system,L,rho,spins) % Return if the spin list is empty if isempty(spins), return; end % Check consistency grumble(spin_system,L,rho,spins); % Find the nuclei to be decoupled if isnumeric(spins) dec_mask=false(1,spin_system.comp.nspins); dec_mask(spins)=true; else dec_mask=ismember(spin_system.comp.isotopes,spins); end % Inform the user report(spin_system,[num2str(nnz(dec_mask)) ' spins to be frozen and depopulated.']); % Get the list of states to be wiped zero_mask=(sum(spin_system.bas.basis(:,dec_mask),2)~=0); % Inform the user report(spin_system,['zeroing ' num2str(nnz(zero_mask)) ' rows and columns in the Liouvillian.']); % Zero the corresponding rows and columns of the Liouvillian L(zero_mask,:)=0; L(:,zero_mask)=0; % Zero the corresponding rows of the state vector stack if nargout==2 report(spin_system,['zeroing ' num2str(nnz(zero_mask)) ' rows in the state vector.']); rho(zero_mask,:)=0; end end % Consistency enforcement function grumble(spin_system,L,rho,spins) if ~ismember(spin_system.bas.formalism,{'sphten-liouv'}) error('analytical decoupling is only available for sphten-liouv formalism.'); end if (~isempty(rho))&&(size(L,2)~=size(rho,1)) error('matrix dimensions of L and rho must agree.'); end if size(L,1)~=size(L,2) error('Liouvillian must be a square matrix.'); end if (~isnumeric(spins))&&(~iscell(spins)) error('spins parameter must either be a list of numbers or a cell array of strings.'); end if iscell(spins)&&any(~ismember(spins,spin_system.comp.isotopes)) error('the system does not contain the spins specified.'); end if isnumeric(spins)&&(size(spins,1)~=1) error('if spins are specified by number, a row vector of numbers must be used.'); end if isnumeric(spins)&&(max(spins)>spin_system.comp.nspins) error('the spin number specified is greater than the number of spins in the system.'); end if isnumeric(spins)&&(any(~isreal(spins))||any(spins<1)) error('spin numbers must be real positive integers.'); end end % It's not worth doing something unless you were doing something that % someone, somewere, would much rather you weren't doing. % % Terry Pratchett
github
tsajed/nmr-pred-master
singlet.m
.m
nmr-pred-master/spinach/kernel/singlet.m
1,357
utf_8
c7fd78a536cdee077971bd06c921bfed
% Returns a two-spin singlet state. Syntax: % % rho=singlet(spin_system,spin_a,spin_b) % % Arguments: % % spin_a - the number of the first spin in the singlet state % % spin_b - the number of the second spin in the singlet state % % [email protected] function rho=singlet(spin_system,spin_a,spin_b) % Check consistency grumble(spin_system,spin_a,spin_b); % Build the component operators unit=state(spin_system,{'E' ,'E' },{spin_a,spin_b},'exact'); LzSz=state(spin_system,{'Lz','Lz'},{spin_a,spin_b},'exact'); LmSp=state(spin_system,{'L-','L+'},{spin_a,spin_b},'exact'); LpSm=state(spin_system,{'L+','L-'},{spin_a,spin_b},'exact'); % Build the singlet state rho=unit/4-(LzSz+0.5*(LpSm+LmSp)); end % Consistency enforcement function grumble(spin_system,spin_a,spin_b) if (~isnumeric(spin_a))||(~isnumeric(spin_b))||(~isscalar(spin_a))||... (~isscalar(spin_b))||(mod(spin_a,1)~=0)||(mod(spin_b,1)~=0)||... (spin_a<1)||(spin_b<1)||(spin_a==spin_b) error('spin_a and spin_b must be different positive real integers.'); end if (spin_a>spin_system.comp.nspins)||(spin_b>spin_system.comp.nspins) error('spin_a and spin_b must be smaller or equal to the number of spins in the system.'); end end % Physics is, hopefully, simple. Physicists are not. % % Edward Teller
github
tsajed/nmr-pred-master
create.m
.m
nmr-pred-master/spinach/kernel/create.m
66,689
utf_8
9d8a27fd29231970b6edabf2bc1145fd
% Spin system and interaction specification. % % <http://spindynamics.org/wiki/index.php?title=Spin_system_specification> function spin_system=create(sys,inter) % Close all open files fclose('all'); % Locate the root and run sanity checks if isempty(which('existentials')) % Tell the user to RTFM error(['paths have not been correctly set - please follow installation '... 'instructions (make sure you had included the subdirectories).']); else % Set the root directory root_dir=which('existentials'); spin_system.sys.root_dir=root_dir(1:end-32); % Run existential checks existentials(); end % Validate input grumble(sys,inter); % Decide output destination if isfield(sys,'output')&&strcmp(sys.output,'hush') % Hush the output spin_system.sys.output='hush'; elseif (~isfield(sys,'output'))||strcmp(sys.output,'console') % Print to the console spin_system.sys.output=1; else % Print to a user-specified file spin_system.sys.output=fopen(sys.output,'a'); end % Decide scratch destination if isfield(sys,'scratch') % Scratch to a user-specified directory spin_system.sys.scratch=sys.scratch; else % Scratch to the default directory spin_system.sys.scratch=[spin_system.sys.root_dir '/scratch']; end % Show version banner banner(spin_system,'version_banner'); % Internal algorithms to disable if isfield(sys,'disable') % Absorb user-specified values spin_system.sys.disable=sys.disable; else % Disable nothing by default spin_system.sys.disable={}; end % Internal algorithms to enable if isfield(sys,'enable') % Absorb user-specified values spin_system.sys.enable=sys.enable; else % Enable nothing by default spin_system.sys.enable={}; end % Cut-offs and tolerances spin_system=tolerances(spin_system,sys); % Disabled features report if ~isempty(spin_system.sys.disable) report(spin_system,'WARNING: the following functionality is disabled'); if ismember('pt',spin_system.sys.disable), report(spin_system,' > automatic detection of non-interacting subspaces'); end if ismember('symmetry',spin_system.sys.disable), report(spin_system,' > permutation symmetry factorization'); end if ismember('krylov',spin_system.sys.disable), report(spin_system,' > Krylov propagation inside evolution() function'); end if ismember('clean-up',spin_system.sys.disable), report(spin_system,' > sparse array clean-up'); end if ismember('dss',spin_system.sys.disable), report(spin_system,' > destination state screening inside evolution() function'); end if ismember('expv',spin_system.sys.disable), report(spin_system,' > Krylov propagation inside step() function'); end if ismember('trajlevel',spin_system.sys.disable), report(spin_system,' > trajectory analysis inside evolution() function'); end if ismember('merge',spin_system.sys.disable), report(spin_system,' > small subspace merging in the evolution() function'); end if ismember('norm_coil',spin_system.sys.disable), report(spin_system,' > coil normalization in the evolution() function'); end if ismember('colorbar',spin_system.sys.disable), report(spin_system,' > colorbar drawing by plotting utilities'); end end % Enabled features report if ~isempty(spin_system.sys.enable) report(spin_system,'WARNING: the following functionality is enabled'); if ismember('gpu',spin_system.sys.enable), report(spin_system,' > GPU arithmetic'); end if ismember('caching',spin_system.sys.enable), report(spin_system,' > propagator caching'); end if ismember('greedy',spin_system.sys.enable), report(spin_system,' > greedy parallelisation'); end if ismember('xmemlist',spin_system.sys.enable), report(spin_system,' > state-cluster cross-membership list generation'); end if ismember('paranoia',spin_system.sys.enable), report(spin_system,' > paranoid accuracy settings'); end end % Control greedy parallelisation warning('off','MATLAB:maxNumCompThreads:Deprecated'); if ismember('greedy',spin_system.sys.enable) spmd warning('off','MATLAB:maxNumCompThreads:Deprecated'); maxNumCompThreads(feature('numcores')); end maxNumCompThreads(feature('numcores')); else spmd warning('off','MATLAB:maxNumCompThreads:Deprecated'); maxNumCompThreads(1); end maxNumCompThreads(feature('numcores')); end % Switch opengl to software on PCs if ispc, opengl('software'); end % GPU devices if ismember('gpu',spin_system.sys.enable) % Inform the user report(spin_system,'looking for supported GPU devices...'); % See what user says if isfield(sys,'gpuids') % Absorb user-specified values spin_system.sys.gpuids=sys.gpuids; else % Query the system spin_system.sys.gpuids=1:gpuDeviceCount; end % Clean up and inform the user if isempty(spin_system.sys.gpuids) spin_system.sys.enable=setdiff(spin_system.sys.enable,{'gpu'}); report(spin_system,'WARNING - no CUDA capable GPUs detected'); else report(spin_system,['GPU devices to be used ' num2str(spin_system.sys.gpuids)]); end else % Set GPU devices to none spin_system.sys.gpuids=[]; end % Spin system banner banner(spin_system,'spin_system_banner'); % Number and types of spins spin_system.comp.isotopes=sys.isotopes; spin_system.comp.nspins=numel(spin_system.comp.isotopes); % Text labels for spins if isfield(sys,'labels') % Get labels from the user spin_system.comp.labels=sys.labels; else % Set labels to empty spin_system.comp.labels=cell(spin_system.comp.nspins,1); end % Multiplicities and magnetogyric ratios spin_system.comp.mults=zeros(1,spin_system.comp.nspins); spin_system.inter.gammas=zeros(1,spin_system.comp.nspins); for n=1:spin_system.comp.nspins [spin_system.inter.gammas(n),spin_system.comp.mults(n)]=spin(sys.isotopes{n}); end report(spin_system,['a total of ' num2str(spin_system.comp.nspins) ' particles in the simulation, of which '... num2str(nnz(spin_system.comp.mults==1)) ' have a zero spin.']); % Order matrix if isfield(inter,'order_matrix') spin_system.inter.order_matrix=inter.order_matrix; else spin_system.inter.order_matrix=zeros(3); end % Primary magnet spin_system.inter.magnet=sys.magnet; report(spin_system,['magnetic induction of ' num2str(spin_system.inter.magnet,'%0.5g') ' Tesla ('... num2str(-1e-6*spin_system.inter.magnet*spin('1H')/(2*pi),'%0.5g') ' MHz proton frequency, '... num2str(-1e-9*spin_system.inter.magnet*spin('E' )/(2*pi),'%0.5g') ' GHz electron frequency).']); % Compute carrier frequencies spin_system.inter.basefrqs=-spin_system.inter.gammas*spin_system.inter.magnet; % Preallocate Zeeman tensor array spin_system.inter.zeeman.matrix=mat2cell(zeros(3*spin_system.comp.nspins,3),3*ones(spin_system.comp.nspins,1)); % Process Zeeman interactions if isfield(inter,'zeeman') % Absorb eigenvalues and Euler angles if isfield(inter.zeeman,'eigs') for n=1:spin_system.comp.nspins if significant(inter.zeeman.eigs{n},0) if (~isfield(inter.zeeman,'euler'))||isempty(inter.zeeman.euler{n}) S=eye(3,3); else S=euler2dcm(inter.zeeman.euler{n}); end spin_system.inter.zeeman.matrix{n}=spin_system.inter.zeeman.matrix{n}+S*diag(inter.zeeman.eigs{n})*transpose(S); end end end % Absorb tensors if isfield(inter.zeeman,'matrix') for n=1:spin_system.comp.nspins if significant(inter.zeeman.matrix{n},0) spin_system.inter.zeeman.matrix{n}=spin_system.inter.zeeman.matrix{n}+inter.zeeman.matrix{n}; end end end % Absorb scalars if isfield(inter.zeeman,'scalar') for n=1:spin_system.comp.nspins if significant(inter.zeeman.scalar{n},0) spin_system.inter.zeeman.matrix{n}=spin_system.inter.zeeman.matrix{n}+eye(3)*inter.zeeman.scalar{n}; end end end % Report back to the user summary(spin_system,'zeeman','summary of Zeeman interactions as supplied (ppm for nuclei, g-tensor for electrons)'); % Convert to angular frequencies for n=1:spin_system.comp.nspins switch spin_system.comp.isotopes{n}(1) case 'E' % For electrons, assume that the g-factor is given and compute the offset from the free electron g-factor spin_system.inter.zeeman.matrix{n}=(spin_system.inter.zeeman.matrix{n}-eye(3)*spin_system.tols.freeg)*(spin_system.inter.basefrqs(n)/spin_system.tols.freeg); otherwise % For nuclei, assume that the chemical shift is given and compute the corresponding offset spin_system.inter.zeeman.matrix{n}=(1e-6)*spin_system.inter.zeeman.matrix{n}*spin_system.inter.basefrqs(n); end end % Clean up the result for n=1:spin_system.comp.nspins if negligible(spin_system.inter.zeeman.matrix{n},spin_system.tols.inter_cutoff)||(spin(spin_system.comp.isotopes{n})==0) spin_system.inter.zeeman.matrix{n}=[]; end end else % Warn the user that Zeeman tensors have not been found report(spin_system,'WARNING - no Zeeman interactions supplied, magnet frequencies assumed.'); end % Absorb reaction rates if isfield(inter,'chem')&&... isfield(inter.chem,'parts')&&... isfield(inter.chem,'rates')&&... isfield(inter.chem,'concs') % Assign the data structure spin_system.chem.parts=inter.chem.parts; spin_system.chem.rates=inter.chem.rates; spin_system.chem.concs=inter.chem.concs; else % No chemical reactions and unit concentration spin_system.chem.parts={(1:spin_system.comp.nspins)}; spin_system.chem.rates=0; spin_system.chem.concs=1; end % Absorb magnetization flux rates if isfield(inter,'chem')&&... isfield(inter.chem,'flux_rate')&&... isfield(inter.chem,'flux_type') % Assign the data structure spin_system.chem.flux_rate=inter.chem.flux_rate; spin_system.chem.flux_type=inter.chem.flux_type; else % No magnetization fluxes spin_system.chem.flux_rate=spalloc(spin_system.comp.nspins,spin_system.comp.nspins,0); spin_system.chem.flux_type='intramolecular'; end % Report back to the user summary(spin_system,'chemistry','chemical process summary'); % Preallocate coupling tensor array report(spin_system,'initializing interaction arrays...'); spin_system.inter.coupling.matrix=mat2cell(zeros(3*spin_system.comp.nspins),3*ones(spin_system.comp.nspins,1),3*ones(spin_system.comp.nspins,1)); % Process coordinates if isfield(inter,'coordinates') % Absorb coordinates into data structure spin_system.inter.coordinates=inter.coordinates; % Report back to the user summary(spin_system,'coordinates','atomic coordinates (Angstrom)'); % Process periodic boundary conditions if isfield(inter,'pbc') % Absorb translation vectors into the data structure spin_system.inter.pbc=inter.pbc; % Report back to the user summary(spin_system,'pbc','PBC translation vectors (Angstrom)'); else % Write an empty array spin_system.inter.pbc={}; % Report back to the user report(spin_system,'periodic boundary conditions not specified, assuming a standalone spin system.'); end % Call dipolar coupling module spin_system=dipolar(spin_system); else % Warn the user that coordinates have not been found report(spin_system,'WARNING - no coordinates given, point dipolar interactions assumed to be zero.'); % Set an empty coordinate array spin_system.inter.coordinates=cell(spin_system.comp.nspins,1); % Set proximity matrix to isolated spins spin_system.inter.proxmatrix=speye(spin_system.comp.nspins,spin_system.comp.nspins); end % Absorb user-specified couplings if isfield(inter,'coupling') % Inform the user report(spin_system,'processing coupling data...'); % Absorb eigenvalues and Euler angles if isfield(inter.coupling,'eigs') [rows,cols,~]=find(cellfun(@norm,inter.coupling.eigs)>spin_system.tols.inter_cutoff); for n=1:numel(rows) if isempty(inter.coupling.euler{rows(n),cols(n)}) S=eye(3,3); else S=euler2dcm(inter.coupling.euler{rows(n),cols(n)}); end spin_system.inter.coupling.matrix{rows(n),cols(n)}=... spin_system.inter.coupling.matrix{rows(n),cols(n)}+2*pi*S*diag(inter.coupling.eigs{rows(n),cols(n)})*S'; end end % Absorb coupling tensors if isfield(inter.coupling,'matrix') [rows,cols,~]=find(cellfun(@norm,inter.coupling.matrix)>spin_system.tols.inter_cutoff); for n=1:numel(rows) spin_system.inter.coupling.matrix{rows(n),cols(n)}=... spin_system.inter.coupling.matrix{rows(n),cols(n)}+2*pi*inter.coupling.matrix{rows(n),cols(n)}; end end % Absorb scalar couplings if isfield(inter.coupling,'scalar') [rows,cols,~]=find(cellfun(@norm,inter.coupling.scalar)>spin_system.tols.inter_cutoff); for n=1:numel(rows) spin_system.inter.coupling.matrix{rows(n),cols(n)}=... spin_system.inter.coupling.matrix{rows(n),cols(n)}+2*pi*eye(3)*inter.coupling.scalar{rows(n),cols(n)}; end end else % Warn the user that couplings have not been found report(spin_system,'WARNING - no couplings given, zeros assumed.'); end % Order up coupling tensors [rows,cols,~]=find(cellfun(@norm,spin_system.inter.coupling.matrix)>0); for n=1:numel(rows) if rows(n)>cols(n) spin_system.inter.coupling.matrix{cols(n),rows(n)}=... spin_system.inter.coupling.matrix{cols(n),rows(n)}+spin_system.inter.coupling.matrix{rows(n),cols(n)}; spin_system.inter.coupling.matrix{rows(n),cols(n)}=zeros(3); end end % Clean up the result for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if negligible(spin_system.inter.coupling.matrix{n,k},spin_system.tols.inter_cutoff)||... (spin(spin_system.comp.isotopes{n})==0)||(spin(spin_system.comp.isotopes{k})==0) spin_system.inter.coupling.matrix{n,k}=[]; end end end % Check for inter-subsystem couplings for n=1:numel(spin_system.chem.parts) for k=1:numel(spin_system.chem.parts) if (n~=k) coupling_block=spin_system.inter.coupling.matrix(spin_system.chem.parts{n},spin_system.chem.parts{k}); if ~all(cellfun(@isempty,coupling_block(:))) error('couplings detected between spins in different chemical species.'); end end end end % Report back to the user summary(spin_system,'couplings','summary of spin-spin couplings (angular frequencies)'); % Temperature if ~isfield(inter,'temperature') % High-temperature approximation inter.temperature=[]; % Print a warning to the user report(spin_system,'WARNING - high-temperature approximation'); else % Absorb the temperature specified spin_system.rlx.temperature=inter.temperature; % Report back to the user report(spin_system,['spin temperature: ' num2str(spin_system.rlx.temperature) ' Kelvin']); end % Relaxation superoperator if isfield(inter,'relaxation') spin_system.rlx.theories=inter.relaxation; for n=1:numel(spin_system.rlx.theories) report(spin_system,['relaxation theory ' num2str(n) ': ' spin_system.rlx.theories{n}]); end else spin_system.rlx.theories={}; report(spin_system,'WARNING - no relaxation theory specified'); end % Rotational correlation times if isfield(inter,'tau_c') spin_system.rlx.tau_c=inter.tau_c; report(spin_system,['rotational correlation time(s): ' num2str(spin_system.rlx.tau_c) ' seconds']); else spin_system.rlx.tau_c=0; end % Terms to keep in the relaxation superoperator if ~isempty(spin_system.rlx.theories) spin_system.rlx.keep=inter.rlx_keep; report(spin_system,['terms to keep in the relaxation superoperator: ' spin_system.rlx.keep]); end % The fate of the dynamic frequency shift if isfield(inter,'rlx_dfs') spin_system.rlx.dfs=inter.rlx_dfs; else spin_system.rlx.dfs='ignore'; end if ~isempty(spin_system.rlx.theories) report(spin_system,['action to take on dynamic frequency shifts: ' spin_system.rlx.dfs]); end % SRFK correlation time if isfield(inter,'srfk_tau_c') spin_system.rlx.srfk_tau_c=inter.srfk_tau_c; else spin_system.rlx.srfk_tau_c=0; end if ismember('SRFK',spin_system.rlx.theories) report(spin_system,['SRFK correlation time: ' num2str(spin_system.rlx.srfk_tau_c) ' seconds']); end % SRFK assumptions if isfield(inter,'srfk_assume') spin_system.rlx.srfk_assume=inter.srfk_assume; else spin_system.rlx.srfk_assume=''; end if ismember('SRFK',spin_system.rlx.theories) report(spin_system,['SRFK Hamiltonian assumptions: ' spin_system.rlx.srfk_assume]); end % SRFK modulation depths if isfield(inter,'srfk_mdepth') spin_system.rlx.srfk_mdepth=inter.srfk_mdepth; else spin_system.rlx.srfk_mdepth=[]; end if ismember('SRFK',spin_system.rlx.theories)&&(~isempty(spin_system.rlx.srfk_mdepth)) for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if ~isempty(spin_system.rlx.srfk_mdepth{n,k}) report(spin_system,['SRFK modulation depth for spins ' ... num2str(n) ',' num2str(k) ': ' ... num2str(spin_system.rlx.srfk_mdepth{n,k}) ' Hz']); end end end end % Equilibrium state if ~isempty(spin_system.rlx.theories) % Absorb user setting spin_system.rlx.equilibrium=inter.equilibrium; % Print back the notice report(spin_system,['thermalisation method: ' spin_system.rlx.equilibrium]); end % Isotropic damping if isfield(inter,'damp_rate') spin_system.rlx.damp_rate=inter.damp_rate; report(spin_system,['isotropic damping rate: ' num2str(spin_system.rlx.damp_rate) ' Hz.']); else spin_system.rlx.damp_rate=[]; end % Anisotropic damping if isfield(inter,'hstrain_rates') spin_system.rlx.hstrain_rates=inter.hstrain_rates; report(spin_system,['anisotropic damping rates: ' num2str(spin_system.rlx.hstrain_rates) ' Hz.']); else spin_system.rlx.hstrain_rates=[]; end % User-supplied R1 relaxation rates for T1/T2 model if isfield(inter,'r1_rates') spin_system.rlx.r1_rates=inter.r1_rates; else spin_system.rlx.r1_rates=[]; end % User-supplied R2 relaxation rates for T1/T2 model if isfield(inter,'r2_rates') spin_system.rlx.r2_rates=inter.r2_rates; else spin_system.rlx.r2_rates=[]; end % User-supplied R1 relaxation rates for Lindblad theory if isfield(inter,'lind_r1_rates') spin_system.rlx.lind_r1_rates=inter.lind_r1_rates; else spin_system.rlx.lind_r1_rates=[]; end % User-supplied R2 relaxation rates for Lindblad theory if isfield(inter,'lind_r2_rates') spin_system.rlx.lind_r2_rates=inter.lind_r2_rates; else spin_system.rlx.lind_r2_rates=[]; end % User-supplied Weizmann R1e relaxation rates if isfield(inter,'weiz_r1e') spin_system.rlx.weiz_r1e=inter.weiz_r1e; else spin_system.rlx.weiz_r1e=[]; end % User-supplied Nottingham R1e relaxation rates if isfield(inter,'nott_r1e') spin_system.rlx.nott_r1e=inter.nott_r1e; else spin_system.rlx.nott_r1e=[]; end % User-supplied Weizmann R1n relaxation rates if isfield(inter,'weiz_r1n') spin_system.rlx.weiz_r1n=inter.weiz_r1n; else spin_system.rlx.weiz_r1n=[]; end % User-supplied Nottingham R1n relaxation rates if isfield(inter,'nott_r1n') spin_system.rlx.nott_r1n=inter.nott_r1n; else spin_system.rlx.nott_r1n=[]; end % User-supplied Weizmann R1d relaxation rates if isfield(inter,'weiz_r1d') spin_system.rlx.weiz_r1d=inter.weiz_r1d; else spin_system.rlx.weiz_r1d=[]; end % User-supplied Weizmann R2e relaxation rates if isfield(inter,'weiz_r2e') spin_system.rlx.weiz_r2e=inter.weiz_r2e; else spin_system.rlx.weiz_r2e=[]; end % User-supplied Nottingham R2e relaxation rates if isfield(inter,'nott_r2e') spin_system.rlx.nott_r2e=inter.nott_r2e; else spin_system.rlx.nott_r2e=[]; end % User-supplied Weizmann R2n relaxation rates if isfield(inter,'weiz_r2n') spin_system.rlx.weiz_r2n=inter.weiz_r2n; else spin_system.rlx.weiz_r2n=[]; end % User-supplied Nottingham R2n relaxation rates if isfield(inter,'nott_r2n') spin_system.rlx.nott_r2n=inter.nott_r2n; else spin_system.rlx.nott_r2n=[]; end % User-supplied Weizmann R2d relaxation rates if isfield(inter,'weiz_r2d') spin_system.rlx.weiz_r2d=inter.weiz_r2d; else spin_system.rlx.weiz_r2d=[]; end % Report relaxation rates back to the user if isfield(inter,'r1_rates')&&isfield(inter,'r2_rates') summary(spin_system,'rlx_rates_t1_t2','relaxation rates (Hz) for T1/T2 theory'); end if isfield(inter,'lind_r1_rates')&&isfield(inter,'lind_r2_rates') summary(spin_system,'rlx_rates_lindblad','relaxation rates (Hz) for Lindblad theory'); end if isfield(inter,'nott_r1e')&&isfield(inter,'nott_r2e')&&... isfield(inter,'nott_r1n')&&isfield(inter,'nott_r2n') summary(spin_system,'rlx_rates_nott','relaxation rates (Hz) for Nottingham DNP theory'); end if isfield(inter,'weiz_r1e')&&isfield(inter,'weiz_r2e')&&... isfield(inter,'weiz_r1n')&&isfield(inter,'weiz_r2n')&&... isfield(inter,'weiz_r1d')&&isfield(inter,'weiz_r2d') summary(spin_system,'rlx_rates_weiz','relaxation rates (Hz) for Weizmann DNP theory'); end % Absorb radical recombination parameters if isfield(inter,'chem')&&isfield(inter.chem,'rp_theory') % Absorb theory spin_system.chem.rp_theory=inter.chem.rp_theory; report(spin_system,['radical recombination theory set to ' spin_system.chem.rp_theory]); % Absorb spins spin_system.chem.rp_electrons=inter.chem.rp_electrons; report(spin_system,['recombining electrons at positions ' num2str(spin_system.chem.rp_electrons)]); % Absorb rates spin_system.chem.rp_rates=inter.chem.rp_rates; report(spin_system,['singlet recombination rate ' num2str(spin_system.chem.rp_rates(1)) ' Hz.']); report(spin_system,['triplet recombination rate ' num2str(spin_system.chem.rp_rates(2)) ' Hz.']); else spin_system.chem.rp_theory=''; spin_system.chem.rp_electrons=[]; spin_system.chem.rp_rates=[]; end end % Input validation function function grumble(sys,inter) % Check Matlab component versions if verLessThan('matlab','9.0') error('Spinach requires 64-bit Matlab R2016a or later.'); end if verLessThan('distcomp','6.8') error('Spinach requires Matlab Parallel Computing Toolbox version 6.8 or later.'); end if verLessThan('optim','7.4') error('Spinach requires Matlab Optimization Toolbox version 7.4 or later.'); end % Check the output switch if isfield(sys,'output') if ~ischar(sys.output) error('sys.output must be a character string.'); end end % Check the scratch folder if isfield(sys,'scratch') if ~ischar(sys.scratch) error('sys.scratch must be a character string.'); end if ~exist(sys.scratch,'dir') error('the specified scratch directory does not exist.'); end end % Check the disable switch if isfield(sys,'disable') if (~iscell(sys.disable))||any(~cellfun(@ischar,sys.disable)) error('sys.disable must be a cell array of strings.'); end if any(~ismember(sys.disable,{'zte','pt','symmetry','krylov','clean-up','dss','expv','trajlevel','merge','norm_coil','colorbar'})) error(['allowed values for sys.disable are ''zte'', ''pt'', ''symmetry'', ''krylov'', ''clean-up'','... ' ''dss'', ''expv'', ''merge'', ''colorbar'', ''norm_coil'' and ''trajlevel''.']); end end % Check the enable switch if isfield(sys,'enable') if (~iscell(sys.enable))||any(~cellfun(@ischar,sys.enable)) error('sys.enable must be a cell array of strings.'); end if any(~ismember(sys.enable,{'gpu','caching','xmemlist','greedy','paranoia','cowboy'})) error('allowed values for sys.enable are ''gpu'', ''xmemlist'', ''greedy'', ''paranoia'', ''cowboy'' and ''caching''.'); end end % Check GPU parameters if isfield(sys,'gpuids') % Check the specification if ~isnumeric(sys.gpuids)||any(mod(sys.gpuids,1)~=0) error('sys.gpuids must be a vector of integers.'); end % Check if the devices are there if any(sys.gpuids>gpuDeviceCount) error('GPU device with the specified ID does not exist.'); end end % Check isotopes variable if ~isfield(sys,'isotopes') error('sys.isotopes subfield must be present.'); elseif isempty(sys.isotopes) error('sys.isotopes cell array cannot be empty.'); elseif ~iscell(sys.isotopes) error('sys.isotopes must be a cell array.'); elseif ~all(cellfun(@ischar,sys.isotopes)) error('all elements of sys.isotopes cell array must be character strings.'); end % Check labels variable if isfield(sys,'labels') if ~iscell(sys.labels) error('sys.labels must be a cell array.'); elseif isempty(sys.labels) error('sys.labels cell array cannot be empty.'); elseif ~all(cellfun(@ischar,sys.labels)) error('all elements of sys.labels cell array must be character strings.'); elseif numel(sys.labels)~=numel(sys.isotopes) error('the length of sys.labels must be the same as the length of sys.isotopes.'); end end % Check the order matrix if isfield(inter,'order_matrix') % Make sure we have a 3x3 matrix if (~isnumeric(inter.order_matrix))||(~ismatrix(inter.order_matrix))||... (any(size(inter.order_matrix)~=[3 3]))||(~isreal(inter.order_matrix)) error('inter.order_matrix must be a 3x3 matrix of real numbers.'); end % Make sure the matrix is traceless if trace(inter.order_matrix)>10*eps() error('inter.order_matrix must be traceless.'); end % Make sure the matrix is symmetric if norm(inter.order_matrix-transpose(inter.order_matrix))>10*eps() error('inter.order_matrix must be symmetric.'); end end % Check magnet induction if ~isfield(sys,'magnet') error('magnet induction must be specified in sys.magnet varaible.'); else if (~isnumeric(sys.magnet))||(~isreal(sys.magnet))||(numel(sys.magnet)~=1) error('sys.magnet must be a real number.'); end end % Check Zeeman interactions if isfield(inter,'zeeman') % Check eigenvalues / Euler angles specification if isfield(inter.zeeman,'eigs') % Check type if (~iscell(inter.zeeman.eigs))||any(~cellfun(@isnumeric,inter.zeeman.eigs)) error('inter.zeeman.eigs must be a cell array of empty vectors or 1x3 vectors.'); end % Check dimensions if numel(inter.zeeman.eigs)~=numel(sys.isotopes) error('the number of elements in inter.zeeman.eigs must match the number of spins.'); end % Make sure eulers exist if ~isfield(inter.zeeman,'euler') error('inter.zeeman.euler variable must be set together with inter.zeeman.eigs.'); end % Make sure eulers are cells if (~iscell(inter.zeeman.euler))||any(~cellfun(@isnumeric,inter.zeeman.euler)) error('inter.zeeman.euler must be a cell array of empty vectors or 1x3 vectors.'); end % Make sure eulers have the correct length if ~all(size(inter.zeeman.eigs)==size(inter.zeeman.euler)) error('inter.zeeman.eigs and inter.zeeman.euler variables must have the same dimension.'); end % Make sure all non-empty elements are real 1x3 vectors for n=1:numel(sys.isotopes) % For eigenvalues if ~isempty(inter.zeeman.eigs{n}) if (~all(size(inter.zeeman.eigs{n})==[1 3]))||... (~isnumeric(inter.zeeman.eigs{n}))||... (~isreal(inter.zeeman.eigs{n})) error('non-empty elements of inter.zeeman.eigs must be real 1x3 vectors.'); end end % For Euler angles if ~isempty(inter.zeeman.euler{n}) if (~all(size(inter.zeeman.euler{n})==[1 3]))||... (~isnumeric(inter.zeeman.euler{n}))||... (~isreal(inter.zeeman.euler{n})) error('non-empty elements of inter.zeeman.euler must be real 1x3 vectors.'); end end % For simultaneity if (isempty(inter.zeeman.eigs{n})&&(~isempty(inter.zeeman.euler{n})))||... (isempty(inter.zeeman.euler{n})&&(~isempty(inter.zeeman.eigs{n}))) error('inter.zeeman.eigs and inter.zeeman.euler must have identical non-empty cell patterns.'); end end end % Check matrix specification if isfield(inter.zeeman,'matrix') % Check type if ~iscell(inter.zeeman.matrix) error('inter.zeeman.matrix must be a cell array of empty matrices or 3x3 matrices.'); elseif size(inter.zeeman.matrix,1)~=1 error('inter.zeeman.matrix cell array must have dimension 1 x nspins.'); elseif ~all(cellfun(@isnumeric,inter.zeeman.matrix)) error('all elements of inter.zeeman.matrix cell array must be numeric.'); end % Check length if numel(inter.zeeman.matrix)~=numel(sys.isotopes) error('the number of elements in the inter.zeeman.matrix array should match the number of spins.'); end % Make sure all non-empty elements are real 3x3 matrices for n=1:numel(sys.isotopes) if ~isempty(inter.zeeman.matrix{n}) if (~all(size(inter.zeeman.matrix{n})==[3 3]))||... (~isnumeric(inter.zeeman.matrix{n}))||... (~isreal(inter.zeeman.matrix{n})) error('non-empty elements of inter.zeeman.matrix must be real 3x3 matrices.'); end end end end % Check scalars if isfield(inter.zeeman,'scalar') % Check type if ~iscell(inter.zeeman.scalar)||any(~cellfun(@isnumeric,inter.zeeman.scalar)) error('inter.zeeman.scalar must be a cell array of empty matrices or 1x1 matrices.'); end % Check length if numel(inter.zeeman.scalar)~=numel(sys.isotopes) error('the number of elements in the inter.zeeman.scalar array should match the number of spins.'); end % Make sure all non-empty elements are real numbers for n=1:numel(sys.isotopes) if ~isempty(inter.zeeman.scalar{n}) if (numel(inter.zeeman.scalar{n})~=1)||... (~isnumeric(inter.zeeman.scalar{n}))||... (~isreal(inter.zeeman.scalar{n})) error('non-empty elements of inter.zeeman.scalar must be numbers.'); end end end end end % Check coordinates if isfield(inter,'coordinates') % Check type if ~iscell(inter.coordinates)||any(~cellfun(@isnumeric,inter.coordinates)) error('inter.coordinates must be a cell array of empty vectors or 1x3 vectors.'); end % Check size if numel(inter.coordinates)~=numel(sys.isotopes) error('the number of elements in inter.coordinates must match the number of spins.') end % Check contents for n=1:numel(sys.isotopes) % Make sure we have real 3-vectors if ~isempty(inter.coordinates{n}) if (~all(size(inter.coordinates{n})==[1 3]))||... (~isnumeric(inter.coordinates{n}))||... (~isreal(inter.coordinates{n})) error('non-empty elements of inter.coordinates must be real 1x3 vectors.'); end end end end % Check periodic boundary conditions if isfield(inter,'pbc') % Check type if ~iscell(inter.pbc)||any(~cellfun(@isvector,inter.pbc)) error('inter.pbc must be a cell array of row vectors.'); end % Check element numbers if ~ismember(numel(inter.pbc),[0 1 2 3]) error('inter.pbc cell array must have zero, one, two or three row vectors as elements.'); end % Check vector dimensions for n=1:numel(inter.pbc) if (~all(size(inter.pbc{n})==[1 3]))||(~isreal(inter.pbc{n})) error('all elements of inter.pbc.cell array must be row vectors with three real elements.'); end end % Check linear independence if ((numel(inter.pbc)==2)&&rank([inter.pbc{1}; inter.pbc{2}],1e-3)<2)||... ((numel(inter.pbc)==3)&&rank([inter.pbc{1}; inter.pbc{2}; inter.pbc{3}],1e-3)<3) error('the vectors supplied in inter.pbc must be lineary independent.'); end end % Check couplings if isfield(inter,'coupling') % Check eigenvalues / Euler angles specification if isfield(inter.coupling,'eigs') % Check type if (~iscell(inter.coupling.eigs))||any(any(~cellfun(@isnumeric,inter.coupling.eigs))) error('inter.coupling.eigs must be a cell array of empty vectors or 1x3 vectors.'); end % Check dimensions if ~all(size(inter.coupling.eigs)==[numel(sys.isotopes) numel(sys.isotopes)]) error('both dimensions of inter.coupling.eigs must match the number of spins.'); end % Check quadratic couplings for n=1:numel(sys.isotopes) [~,mult]=spin(sys.isotopes{n}); if (norm(inter.coupling.eigs{n,n})>0)&&(mult<3) error('quadratic couplings cannot be specified for spin-1/2 particles.'); elseif abs(sum(inter.coupling.eigs{n,n}))>1e-6 error('quadratic couplings cannot have a non-zero trace.'); end end % Make sure eulers exist if ~isfield(inter.coupling,'euler') error('inter.coupling.euler array must be set together with inter.coupling.eigs.'); end % Make sure eulers are cells if ~iscell(inter.coupling.euler)||any(any(~cellfun(@isnumeric,inter.coupling.euler))) error('inter.coupling.euler must be a cell array of empty vectors or 1x3 vectors.'); end % Make sure eulers have the correct length if ~all(size(inter.coupling.eigs)==size(inter.coupling.euler)) error('inter.coupling.eigs and inter.coupling.euler arrays must have the same dimension.'); end % Make sure all non-empty elements are real 1x3 vectors for n=1:numel(sys.isotopes) for k=1:numel(sys.isotopes) % For eigenvalues if ~isempty(inter.coupling.eigs{n,k}) if (~all(size(inter.coupling.eigs{n,k})==[1 3]))||... (~isnumeric(inter.coupling.eigs{n,k}))||... (~isreal(inter.coupling.eigs{n,k})) error('non-empty elements of inter.coupling.eigs must be real 1x3 vectors.'); end end % For Euler angles if ~isempty(inter.coupling.euler{n,k}) if (~all(size(inter.coupling.euler{n,k})==[1 3]))||... (~isnumeric(inter.coupling.euler{n,k}))||... (~isreal(inter.coupling.euler{n,k})) error('non-empty elements of inter.coupling.euler must be real 1x3 vectors.'); end end % For simultaneity if (isempty(inter.coupling.eigs{n,k})&&(~isempty(inter.coupling.euler{n,k})))||... (isempty(inter.coupling.euler{n,k})&&(~isempty(inter.coupling.eigs{n,k}))) error('inter.coupling.eigs and inter.coupling.euler must have identical non-empty cell patterns.'); end end end end % Check matrix specification if isfield(inter.coupling,'matrix') % Check type if ~iscell(inter.coupling.matrix)||any(any(~cellfun(@isnumeric,inter.coupling.matrix))) error('inter.coupling.matrix must be a cell array of empty matrices or 3x3 matrices.'); end % Check dimensions if ~all(size(inter.coupling.matrix)==[numel(sys.isotopes) numel(sys.isotopes)]) error('both dimensions of inter.coupling.matrix cell array should match the number of spins.'); end % Check quadratic couplings for n=1:numel(sys.isotopes) [~,mult]=spin(sys.isotopes{n}); if (norm(inter.coupling.matrix{n,n})>0)&&(mult<3) error('quadratic couplings cannot be specified for spin-1/2 particles.'); elseif abs(trace(inter.coupling.matrix{n,n}))>1e-6 error('quadratic couplings cannot have a non-zero trace.'); end end % Make sure all non-empty elements are real 3x3 matrices for n=1:numel(sys.isotopes) for k=1:numel(sys.isotopes) if ~isempty(inter.coupling.matrix{n,k}) if (~all(size(inter.coupling.matrix{n,k})==[3 3]))||... (~isnumeric(inter.coupling.matrix{n,k}))||... (~isreal(inter.coupling.matrix{n,k})) error('non-empty elements of inter.coupling.matrix must be real 3x3 matrices.'); end end end end end % Check scalars if isfield(inter.coupling,'scalar') % Check type if ~iscell(inter.coupling.scalar)||any(any(~cellfun(@isnumeric,inter.coupling.scalar))) error('inter.coupling.scalar must be a cell array of empty matrices or 1x1 matrices.'); end % Check dimensions if ~all(size(inter.coupling.scalar)==[numel(sys.isotopes) numel(sys.isotopes)]) error('both dimensions of inter.coupling.scalar array should match the number of spins.'); end % Make sure all non-empty elements are real numbers if any(nonzeros(cellfun(@numel,inter.coupling.scalar))~=1)||... any(nonzeros(~cellfun(@isnumeric,inter.coupling.scalar)))||... any(nonzeros(~cellfun(@isreal,inter.coupling.scalar))) error('non-empty elements of inter.coupling.scalar must be real numbers.'); end % Disallow quadratic scalar couplings for n=1:numel(sys.isotopes) if norm(inter.coupling.scalar{n,n})~=0 error('scalar couplings cannot be quadratic.'); end end end end % Check temperature - negative and complex values allowed if isfield(inter,'temperature')&&(~isempty(inter.temperature)) % Check type and dimension if (~isnumeric(inter.temperature))||(numel(inter.temperature)~=1) error('inter.tempearture must be a number.'); end end % Check relaxation theory if isfield(inter,'relaxation') % Check type if (~iscell(inter.relaxation))||any(~cellfun(@ischar,inter.relaxation)) error('inter.relaxation must be a cell array of strings.'); end % Check relaxation theories if ~all(ismember(inter.relaxation,{'damp','hstrain','t1_t2','redfield','lindblad',... 'nottingham','weizmann','SRFK','SRSK'})) error('unrecognised relaxation theory specification.'); end % Enforce term retention policy specification if ~isfield(inter,'rlx_keep') error('relaxation superoperator term retention policy must be specified in inter.rlx_keep field.'); end % Enforce relaxation destination if ~isfield(inter,'equilibrium') error('relaxation destination must be specified in inter.equilibrium variable.'); end % Enforce correlation time with Redfield theory if ismember('redfield',inter.relaxation)&&(~isfield(inter,'tau_c')) error('correlation time(s) must be specified with Redfield theory.'); end % Enforce damping rate with isotropic damping if ismember('damp',inter.relaxation)&&(~isfield(inter,'damp_rate')) error('damping rate must be specified with non-selective damping.'); end % Enforce damping rate with anisotropic damping if ismember('hstrain',inter.relaxation)&&(~isfield(inter,'hstrain_rates')) error('damping rates must be specified with anisotropic damping.'); end % Enforce R1 and R2 rates with T1,T2 approximation if ismember('t1_t2',inter.relaxation)&&((~isfield(inter,'r1_rates'))||(~isfield(inter,'r2_rates'))) error('R1 and R2 rates must be specified with extended T1,T2 relaxation theory.'); end % Enforce R1 and R2 rates with Lindblad theory if ismember('lindblad',inter.relaxation)&&((~isfield(inter,'lind_r1_rates'))||(~isfield(inter,'lind_r2_rates'))) error('R1 and R2 rates must be specified with Lindblad relaxation theory.'); end % Enforce R1e, R2e, R1n and R2n rates with Nottingham DNP theory if ismember('nottingham',inter.relaxation)&&... ((~isfield(inter,'nott_r1e'))||(~isfield(inter,'nott_r2e'))||... (~isfield(inter,'nott_r1n'))||(~isfield(inter,'nott_r2n'))) error(['R1e, R2e, R1n and R2n rates must be specified with '... 'Nottingham DNP relaxation theory.']); end % Enforce R1e, R2e, R1n and R2n rates with Weizmann DNP theory if ismember('weizmann',inter.relaxation)&&... ((~isfield(inter,'weiz_r1e'))||(~isfield(inter,'weiz_r2e'))||... (~isfield(inter,'weiz_r1n'))||(~isfield(inter,'weiz_r2n'))) error(['R1e, R2e, R1n and R2n rates must be specified with '... 'Weizmann DNP relaxation theory.']); end % Enforce R1d and R2d with Weizmann DNP theory if ismember('weizmann',inter.relaxation)&&... ((~isfield(inter,'weiz_r1d'))||(~isfield(inter,'weiz_r2d'))) error('R1d and R2d rates must be specified with Weizmann DNP relaxation theory.'); end % Enforce two electrons with Nottingham DNP theory if ismember('nottingham',inter.relaxation)&&(nnz(strcmp('E',sys.isotopes))~=2) error('Nottingham DNP relaxation theory requires two electrons.'); end % Enforce correlation time with SRFK if ismember('SRFK',inter.relaxation)&&(~isfield(inter,'srfk_tau_c')) error('SRFK requires modulation correlation time to be specified in inter.srfk_tau_c variable.'); end % Enforce modulation depth with SRFK if ismember('SRFK',inter.relaxation)&&(~isfield(inter,'srfk_mdepth')) error('SRFK requires modulation depths to be specified in inter.srfk_mdepth variable.'); end % Enforce specific assumptions with SRFK if ismember('SRFK',inter.relaxation)&&(~isfield(inter,'srfk_assume')) error('SRFK requires assumptions to be specified in inter.srfk_assume variable.'); end end % Check rotational correlation time if isfield(inter,'tau_c') % Check type and dimension if (~isnumeric(inter.tau_c))||(numel(inter.tau_c)>3)||(numel(inter.tau_c)==0) error('inter.tau_c must be a vector of size 1, 2 or 3.'); end % Check value if (~isreal(inter.tau_c))||any(inter.tau_c<0) error('inter.tau_c must have non-negative real elements.'); end % Enforce Redfield theory if tau_c is specified if (~isfield(inter,'relaxation'))||(~ismember('redfield',inter.relaxation)) error('inter.tau_c requires Redfield relaxation theory.'); end end % Check SRFK correlation time if isfield(inter,'srfk_tau_c') % Check type and dimension if (~isnumeric(inter.srfk_tau_c))||(~isscalar(inter.srfk_tau_c))||(~isreal(inter.tau_c))||(inter.tau_c<0) error('inter.srfk_tau_c must be a non-negative real number.'); end % Enforce SRFK theory if srfk_tau_c is specified if (~isfield(inter,'relaxation'))||(~ismember('SRFK',inter.relaxation)) error('inter.srfk_tau_c requires SRFK relaxation theory.'); end end % Check term retention if isfield(inter,'rlx_keep') % Check type if ~ischar(inter.rlx_keep) error('inter.rlx_keep must be a string.'); end % Check contents if ~ismember(inter.rlx_keep,{'diagonal','kite','secular','labframe'}) error('allowed values for inter.rlx_keep are ''diagonal'', ''kite'', ''secular'' and ''labframe''.'); end end % Check dynamic frequency shift retention if isfield(inter,'rlx_dfs') % Check type if ~ischar(inter.rlx_dfs) error('inter.rlx_dfs must be a string.'); end % Check contents if ~ismember(inter.rlx_dfs,{'keep','ignore'}) error('allowed values for inter.rlx_dfs are ''keep'' and ''ignore''.'); end end % Check SRFK assumptions if isfield(inter,'srfk_assume') % Check type if ~ischar(inter.srfk_assume) error('inter.srfk_assume must be a string.'); end % Enforce SRFK if SRFK assumptions are specified if (~isfield(inter,'relaxation'))||(~ismember('SRFK',inter.relaxation)) error('inter.srfk_assume requires SRFK relaxation theory.'); end end % Check SRFK modulation depths if isfield(inter,'srfk_mdepth') % Check type if (~iscell(inter.srfk_mdepth))||(~all(cellfun(@isnumeric,inter.srfk_mdepth(:)))) error('inter.srfk_mdepth must be a cell array of empty matrices or scalars.'); end % Check dimensions if ~all(size(inter.srfk_mdepth)==[numel(sys.isotopes) numel(sys.isotopes)]) error('both dimensions of inter.srfk_mdepth array should match the number of spins.'); end % Make sure all non-empty elements are non-negative real numbers [rows,cols]=find(~cellfun(@isempty,inter.srfk_mdepth)); for n=1:numel(rows) if (~isreal(inter.srfk_mdepth{rows(n),cols(n)}))||(inter.srfk_mdepth{rows(n),cols(n)}<0) error('non-empty elements of inter.srfk_mdepth must be non-negative real numbers.'); end end % Disallow quadratic scalar couplings for n=1:numel(sys.isotopes) if norm(inter.srfk_mdepth{n,n})~=0 error('scalar couplings cannot be quadratic.'); end end % Enforce SRFK if SRFK modulation depths are specified if (~isfield(inter,'relaxation'))||(~ismember('SRFK',inter.relaxation)) error('inter.srfk_mdepth requires SRFK relaxation theory.'); end end % Check equilibrium switch if isfield(inter,'equilibrium') % Check type if ~ischar(inter.equilibrium) error('inter.equilibrium must be a string.'); end % Check contents if ~ismember(inter.equilibrium,{'zero','levante','dibari'}) error('allowed values for inter.equilibrium are ''zero'', ''levante'' and ''dibari''.'); end end % Check isotropic damping rate if isfield(inter,'damp_rate') % Check value if (~isnumeric(inter.damp_rate))||(numel(inter.damp_rate)~=1)||... (~isreal(inter.damp_rate))||(inter.damp_rate<0) error('inter.damp_rate must be a non-negative real number.'); end % Enforce isotropic damping if damp_rate is specified if ~ismember('damp',inter.relaxation) error('inter.damp_rate can only be specified with damp relaxation theory.'); end end % Check anisotropic damping rates if isfield(inter,'hstrain_rates') % Check values if (~isnumeric(inter.hstrain_rates))||(numel(inter.hstrain_rates)~=3)||... (~isreal(inter.hstrain_rates))||any(inter.hstrain_rates<0) error('inter.hstrain_rates must contain three non-negative real numbers.'); end % Enforce anisotropic damping if damp_rate is specified if ~ismember('hstrain',inter.relaxation) error('inter.hstrain_rates can only be specified with damp relaxation theory.'); end end % Check R1 rates for T1/T2 if isfield(inter,'r1_rates') % Check type and values if (~isvector(inter.r1_rates))||(~isnumeric(inter.r1_rates))||... any(inter.r1_rates<0)||any(~isreal(inter.r1_rates)) error('inter.r1_rates must be a vector of positive real numbers.'); end % Check dimension if numel(inter.r1_rates)~=numel(sys.isotopes) error('the number of elements in inter.r1_rates must be equal to the number of spins.'); end % Enforce T1,T2 theory if inter.r1_rates rates are specified if ~ismember('t1_t2',inter.relaxation) error('inter.r1_rates can only be specified with T1,T2 relaxation theory.'); end end % Check R1 rates for Lindblad if isfield(inter,'lind_r1_rates') % Check type and values if (~isvector(inter.lind_r1_rates))||(~isnumeric(inter.lind_r1_rates))||... any(inter.lind_r1_rates<0)||any(~isreal(inter.lind_r1_rates)) error('inter.lind_r1_rates must be a vector of positive real numbers.'); end % Check dimension if numel(inter.lind_r1_rates)~=numel(sys.isotopes) error('the number of elements in inter.lind_r1_rates must be equal to the number of spins.'); end % Enforce Lindblad theory if inter.lind_r1_rates rates are specified if ~ismember('lindblad',inter.relaxation) error('inter.lind_r1_rates can only be specified with Lindblad relaxation theory.'); end end % Check R2 rates for T1/T2 if isfield(inter,'r2_rates') % Check type and values if (~isvector(inter.r2_rates))||(~isnumeric(inter.r2_rates))||... any(inter.r2_rates<0)||any(~isreal(inter.r2_rates)) error('inter.r2_rates must be a vector of positive real numbers.'); end % Check dimension if numel(inter.r2_rates)~=numel(sys.isotopes) error('the number of elements in inter.r2_rates must be equal to the number of spins.'); end % Enforce T1,T2 theory if inter.r2_rates rates are specified if ~ismember('t1_t2',inter.relaxation) error('inter.r2_rates can only be specified with T1,T2 relaxation theory.'); end end % Check R2 rates for Lindblad if isfield(inter,'lind_r2_rates') % Check type and values if (~isvector(inter.lind_r2_rates))||(~isnumeric(inter.lind_r2_rates))||... any(inter.lind_r2_rates<0)||any(~isreal(inter.lind_r2_rates)) error('inter.lind_r2_rates must be a vector of positive real numbers.'); end % Check dimension if numel(inter.lind_r2_rates)~=numel(sys.isotopes) error('the number of elements in inter.lind_r2_rates must be equal to the number of spins.'); end % Enforce Lindblad theory if inter.lind_r2_rates rates are specified if ~ismember('lindblad',inter.relaxation) error('inter.lind_r2_rates can only be specified with Lindblad relaxation theory.'); end end % Check R1e rate for Weizmann DNP theory if isfield(inter,'weiz_r1e') % Check type and value if (~isnumeric(inter.weiz_r1e))||any(inter.weiz_r1e<0)||any(~isreal(inter.weiz_r1e)) error('inter.weiz_r1e must be a positive real number.'); end % Check dimension if numel(inter.weiz_r1e)~=1 error('inter.weiz_r1e must have a single element.'); end % Enforce Weizmann theory if inter.weiz_r1e is specified if ~ismember('weizmann',inter.relaxation) error('inter.weiz_r1e can only be specified with Weizmann DNP relaxation theory.'); end end % Check R1e rate for Nottingham DNP theory if isfield(inter,'nott_r1e') % Check type and value if (~isnumeric(inter.nott_r1e))||any(inter.nott_r1e<0)||any(~isreal(inter.nott_r1e)) error('inter.nott_r1e must be a positive real number.'); end % Check dimension if numel(inter.nott_r1e)~=1 error('inter.nott_r1e must have a single element.'); end % Enforce Nottingham theory if inter.weiz_r1e is specified if ~ismember('nottingham',inter.relaxation) error('inter.nott_r1e can only be specified with Nottingham DNP relaxation theory.'); end end % Check R2e rate for Weizmann DNP theory if isfield(inter,'weiz_r2e') % Check type and value if (~isnumeric(inter.weiz_r2e))||any(inter.weiz_r2e<0)||any(~isreal(inter.weiz_r2e)) error('inter.weiz_r2e must be a positive real number.'); end % Check dimension if numel(inter.weiz_r2e)~=1 error('inter.weiz_r1e must have a single element.'); end % Enforce Weizmann theory if inter.weiz_r2e is specified if ~ismember('weizmann',inter.relaxation) error('inter.weiz_r2e can only be specified with Weizmann DNP relaxation theory.'); end end % Check R2e rate for Nottingham DNP theory if isfield(inter,'nott_r2e') % Check type and value if (~isnumeric(inter.nott_r2e))||any(inter.nott_r2e<0)||any(~isreal(inter.nott_r2e)) error('inter.nott_r2e must be a positive real number.'); end % Check dimension if numel(inter.nott_r2e)~=1 error('inter.nott_r2e must have a single element.'); end % Enforce Nottingham theory if inter.weiz_r1e is specified if ~ismember('nottingham',inter.relaxation) error('inter.nott_r2e can only be specified with Nottingham DNP relaxation theory.'); end end % Check R1n rate for Weizmann DNP theory if isfield(inter,'weiz_r1n') % Check type and value if (~isnumeric(inter.weiz_r1n))||any(inter.weiz_r1n<0)||any(~isreal(inter.weiz_r1n)) error('inter.weiz_r1n must be a positive real number.'); end % Check dimension if numel(inter.weiz_r1n)~=1 error('inter.weiz_r1n must have a single element.'); end % Enforce Weizmann theory if inter.weiz_r1n is specified if ~ismember('weizmann',inter.relaxation) error('inter.weiz_r1n can only be specified with Weizmann DNP relaxation theory.'); end end % Check R1n rate for Nottingham DNP theory if isfield(inter,'nott_r1n') % Check type and value if (~isnumeric(inter.nott_r1n))||any(inter.nott_r1n<0)||any(~isreal(inter.nott_r1n)) error('inter.nott_r1n must be a positive real number.'); end % Check dimension if numel(inter.nott_r1n)~=1 error('inter.nott_r1n must have a single element.'); end % Enforce Nottingham theory if inter.weiz_r1n is specified if ~ismember('nottingham',inter.relaxation) error('inter.nott_r1n can only be specified with Nottingham DNP relaxation theory.'); end end % Check R2n rate for Weizmann DNP theory if isfield(inter,'weiz_r2n') % Check type and value if (~isnumeric(inter.weiz_r2n))||any(inter.weiz_r2n<0)||any(~isreal(inter.weiz_r2n)) error('inter.weiz_r2n must be a positive real number.'); end % Check dimension if numel(inter.weiz_r2n)~=1 error('inter.weiz_r1e must have a single element.'); end % Enforce Weizmann theory if inter.weiz_r2n is specified if ~ismember('weizmann',inter.relaxation) error('inter.weiz_r2n can only be specified with Weizmann DNP relaxation theory.'); end end % Check R2n rate for Nottingham DNP theory if isfield(inter,'nott_r2n') % Check type and value if (~isnumeric(inter.nott_r2n))||any(inter.nott_r2n<0)||any(~isreal(inter.nott_r2n)) error('inter.nott_r2n must be a positive real number.'); end % Check dimension if numel(inter.nott_r2n)~=1 error('inter.nott_r2n must have a single element.'); end % Enforce Nottingham theory if inter.weiz_r1e is specified if ~ismember('nottingham',inter.relaxation) error('inter.nott_r2n can only be specified with Nottingham DNP relaxation theory.'); end end % Check R1d rates for Weizmann DNP theory if isfield(inter,'weiz_r1d') % Check type and values if (~isnumeric(inter.weiz_r1d))||any(inter.weiz_r1d(:)<0)||(~isreal(inter.weiz_r1d)) error('inter.weiz_r1d must be a matrix of non-negative real numbers.'); end % Check dimension if any(size(inter.weiz_r1d)~=[numel(sys.isotopes) numel(sys.isotopes)]) error('both dimensions of inter.weiz_r1d must be equal to the number of spins.'); end % Enforce Weizmann theory if inter.weiz_r1d rates are specified if ~strcmp(inter.relaxation,'weizmann') error('inter.weiz_r1d can only be specified with Weizmann DNP relaxation theory.'); end end % Check R2d rates if isfield(inter,'weiz_r2d') % Check type and values if (~isnumeric(inter.weiz_r2d))||any(inter.weiz_r2d(:)<0)||(~isreal(inter.weiz_r2d)) error('inter.weiz_r2d must be a matrix of non-negative real numbers.'); end % Check dimension if any(size(inter.weiz_r2d)~=[numel(sys.isotopes) numel(sys.isotopes)]) error('both dimensions of inter.weiz_r2d must be equal to the number of spins.'); end % Enforce Weizmann theory if R2d rates are specified if ~strcmp(inter.relaxation,'weizmann') error('inter.weiz_r2d can only be specified with Weizmann DNP relaxation theory.'); end end % Check chemical kinetics if isfield(inter,'chem') % Check reaction specifications if isfield(inter.chem,'parts')&&(~isfield(inter.chem,'rates')) error('reaction rates (inter.chem.rates) must be provided.'); elseif isfield(inter.chem,'rates')&&(~isfield(inter.chem,'parts')) error('subsystem identifiers (inter.chem.parts) must be provided.'); elseif isfield(inter.chem,'rates')&&(~isfield(inter.chem,'concs')) error('initial concentrations (inter.chem.concs) must be provided.'); elseif isfield(inter.chem,'concs')&&(~isfield(inter.chem,'rates')) error('reaction rates (inter.chem.rates) must be provided.'); end % Check chemical species specification if isfield(inter.chem,'parts') if ~iscell(inter.chem.parts)||(~all(cellfun(@isvector,inter.chem.parts))) error('inter.chem.parts must be a cell array of vectors.'); end for n=1:numel(inter.chem.parts) for k=1:numel(inter.chem.parts) if (n~=k)&&(~isempty(intersect(inter.chem.parts{n},inter.chem.parts{k}))) error('a given spin can only belong to one chemical subsystem in inter.chem.parts variable.'); end end if any(inter.chem.parts{n}<1)||any(inter.chem.parts{n}>numel(sys.isotopes))||... any(mod(inter.chem.parts{n},1)~=0)||(numel(unique(inter.chem.parts{n}))~=numel(inter.chem.parts{n})) error('elements of inter.chem.parts must be vectors of unique positive integers not exceeding the total number of spins.'); end for k=1:numel(inter.chem.parts) if numel(inter.chem.parts{n})~=numel(inter.chem.parts{k}) error('all chemical subsystems must have the same number of spins.'); end end for k=1:numel(inter.chem.parts) for m=1:numel(inter.chem.parts{n}) if ~strcmp(sys.isotopes{inter.chem.parts{n}(m)},sys.isotopes{inter.chem.parts{k}(m)}) error('isotope sequences in all chemical subsystems must be the same.'); end end end end end % Check reaction rate matrix if isfield(inter.chem,'rates') if (~isnumeric(inter.chem.rates))||(~isreal(inter.chem.rates))||(size(inter.chem.rates,1)~=size(inter.chem.rates,2)) error('inter.chem.rates must be a real square matrix.'); end if any(size(inter.chem.rates)~=numel(inter.chem.parts)) error('both dimensions of inter.chem.rates matrix must be equal to the number of chemical subsystems.'); end end % Check initial concentrations if isfield(inter.chem,'concs') if (~isnumeric(inter.chem.concs))||(~isreal(inter.chem.concs))||any(inter.chem.concs(:)<0) error('inter.chem.concs must be a vector of non-negative real numbers.'); end if numel(inter.chem.concs)~=numel(inter.chem.parts) error('the number of initial concentrations must be equal to the number of chemical species.'); end end % Check flux specifications if isfield(inter.chem,'flux_rate')&&(~isfield(inter.chem,'flux_type')) error('flux type (inter.chem.flux_type) must be provided.'); elseif isfield(inter.chem,'flux_type')&&(~isfield(inter.chem,'flux_rate')) error('flux rates (inter.chem.flux_rate) must be provided.'); end % Check flux rate matrix if isfield(inter.chem,'flux_rate') if (~isnumeric(inter.chem.flux_rate))||(~isreal(inter.chem.flux_rate))||... (size(inter.chem.flux_rate,1)~=size(inter.chem.flux_rate,2)) error('inter.chem.flux_rate must be a real square matrix.'); end if any(size(inter.chem.flux_rate)~=numel(sys.isotopes)) error('both dimensions of inter.chem.flux_rate matrix must be equal to the number of spins.'); end end % Check flux type if isfield(inter.chem,'flux_type') if ~ischar(inter.chem.flux_type) error('inter.chem.flux_type must be a character string.'); end if ~ismember(inter.chem.flux_type,{'intermolecular','intramolecular'}) error('incorrect flux type specification.'); end end % Check radical pair kinetics if isfield(inter.chem,'rp_theory') if ~ischar(inter.chem.rp_theory) error('inter.chem.rp_theory must be a string.'); end if ~ismember(inter.chem.rp_theory,{'haberkorn','jones-hore','exponential'}) error('allowed values for inter.chem.rp_theory are ''exponential'', ''haberkorn'' and ''jones-hore''.'); end if (~isfield(inter.chem,'rp_electrons'))||(~isfield(inter.chem,'rp_rates')) error('inter.chem.rp_electrons and inter.chem.rp_rates must be specified alongside inter.chem.rp_theory parameter.'); end end if isfield(inter.chem,'rp_electrons') if (~isfield(inter.chem,'rp_theory'))||(~isfield(inter.chem,'rp_rates')) error('inter.chem.rp_theory and inter.chem.rp_rates must be specified alongside inter.chem.rp_electrons parameter.'); end if (~isnumeric(inter.chem.rp_electrons))||(numel(inter.chem.rp_electrons)~=2)||any(ceil(inter.chem.rp_electrons)~=floor(inter.chem.rp_electrons))||any(inter.chem.rp_electrons<1) error('inter.chem.rp_electrons must be a vector of two positive integers.'); end if any(inter.chem.rp_electrons>numel(sys.isotopes))||any(~cellfun(@(x)strcmp(x(1),'E'),sys.isotopes(inter.chem.rp_electrons))) error('at least one of the elements of inter.chem.rp_electrons does not refer to an electron.'); end end if isfield(inter.chem,'rp_rates') if (~isfield(inter.chem,'rp_theory'))||(~isfield(inter.chem,'rp_electrons')) error('inter.chem.rp_theory and inter.chem.rp_electrons must be specified alongside inter.chem.rp_rates parameter.'); end if (~isnumeric(inter.chem.rp_rates))||(numel(inter.chem.rp_rates)~=2)||(~isreal(inter.chem.rp_rates))||any(inter.chem.rp_rates<0) error('inter.chem.rp_rates must be a vector of two non-negative real numbers.'); end end end end % Those who beat their swords into plowshares will till % the soil for those who did not. % % Benjamin Franklin
github
tsajed/nmr-pred-master
spin.m
.m
nmr-pred-master/spinach/kernel/spin.m
33,566
utf_8
f7cdee02ee6b72e8e3619a7abc6b0029
% Database of multiplicities and magnetogyric ratios for sta- % ble and long-lived isotopes with non-zero spin. Syntax: % % [gamma,multiplicity]=spin(name) % % where the name of the isotope is given in the standard way, % e.g. 13C or 195Pt. High-spin electrons may be requested by % supplying 'E' followed by multiplicity - 'E3' would request % a spin-1 electron and so forth. % % Note: data with no source specified was sourced from Google % and should be double-checked before running producti- % on calculations. % % [email protected] % [email protected] % [email protected] function [gamma,multiplicity]=spin(name) if regexp(name,'^E\d') % Treat high-spin electrons as a special case multiplicity=str2double(name(2:end)); gamma=-1.760859708e11; % CODATA 2013 else % Other cases come from the database switch char(name) case 'G' % Ghost spin multiplicity=1; gamma=0; % Spin zero particle case 'E' % Electron multiplicity=2; gamma=-1.760859708e11; % CODATA 2013 case 'N' % Neutron multiplicity=2; gamma=-1.83247181e8; % http://dx.doi.org/10.1103/PhysRevC.63.037301 case 'M' % Muon multiplicity=2; gamma=-8.51615503e8; % CODATA 2010 case 'P' % Proton multiplicity=2; gamma= 2.675222005e8; % CODATA 2013 case '1H' multiplicity=2; gamma= 2.675222005e8; % CODATA 2013 case '2H' multiplicity=3; gamma= 4.10662791e7; % NMR Enc. 1996 case '3H' multiplicity=2; gamma= 2.85349779e8; % NMR Enc. 1996 case '3He' multiplicity=2; gamma=-2.03801587e8; % NMR Enc. 1996 case '4He' multiplicity=1; gamma=0; % Spin 0 nucleus case '6Li' multiplicity=3; gamma= 3.9371709e7; % NMR Enc. 1996 case '7Li' multiplicity=4; gamma= 1.03977013e8; % NMR Enc. 1996 case '9Be' multiplicity=4; gamma=-3.759666e7; % NMR Enc. 1996 case '10B' multiplicity=7; gamma= 2.8746786e7; % NMR Enc. 1996 case '11B' multiplicity=4; gamma= 8.5847044e7; % NMR Enc. 1996 case '12C' multiplicity=1; gamma=0; % Spin 0 nucleus case '13C' multiplicity=2; gamma= 6.728284e7; % NMR Enc. 1996 case '14N' multiplicity=3; gamma= 1.9337792e7; % NMR Enc. 1996 case '15N' multiplicity=2; gamma=-2.71261804e7; % NMR Enc. 1996 case '16O' multiplicity=1; gamma=0; % Spin 0 nucleus case '17O' multiplicity=6; gamma=-3.62808e7; % NMR Enc. 1996 case '18O' multiplicity=1; gamma=0; % Spin 0 nucleus case '19F' multiplicity=2; gamma= 2.518148e8; % NMR Enc. 1996 case '20Ne' multiplicity=1; gamma=0; % Spin 0 nucleus case '21Ne' multiplicity=4; gamma=-2.11308e7; % NMR Enc. 1996 case '22Ne' multiplicity=1; gamma=0; % Spin 0 nucleus case '23Na' multiplicity=4; gamma=7.0808493e7; % NMR Enc. 1996 case '24Mg' multiplicity=1; gamma=0; % Spin 0 nucleus case '25Mg' multiplicity=6; gamma=-1.63887e7; % NMR Enc. 1996 case '26Mg' multiplicity=1; gamma=0; % Spin 0 nucleus case '27Al' multiplicity=6; gamma=6.9762715e7; % NMR Enc. 1996 case '28Si' multiplicity=1; gamma=0; % Spin 0 nucleus case '29Si' multiplicity=2; gamma=-5.3190e7; % NMR Enc. 1996 case '30Si' multiplicity=1; gamma=0; % Spin 0 nucleus case '31P' multiplicity=2; gamma=10.8394e7; % NMR Enc. 1996 case '32S' multiplicity=1; gamma=0; % Spin 0 nucleus case '33S' multiplicity=4; gamma=2.055685e7; % NMR Enc. 1996 case '34S' multiplicity=1; gamma=0; % Spin 0 nucleus case '36S' multiplicity=1; gamma=0; % Spin 0 nucleus case '35Cl' multiplicity=4; gamma=2.624198e7; % NMR Enc. 1996 case '37Cl' multiplicity=4; gamma=2.184368e7; % NMR Enc. 1996 case '36Ar' multiplicity=1; gamma=0; % Spin 0 nucleus case '38Ar' multiplicity=1; gamma=0; % Spin 0 nucleus case '39Ar' multiplicity=8; gamma=-1.78e7; % Needs checking case '40Ar' multiplicity=1; gamma=0; % Spin 0 nucleus case '39K' multiplicity=4; gamma= 1.2500608e7; % NMR Enc. 1996 case '40K' multiplicity=9; gamma=-1.5542854e7; % NMR Enc. 1996 case '41K' multiplicity=4; gamma= 0.68606808e7; % NMR Enc. 1996 case '40Ca' multiplicity=1; gamma=0; % Spin 0 nucleus case '41Ca' multiplicity=8; gamma=-2.182305e7; % http://dx.doi.org/10.1103/PhysRevC.63.037301 case '42Ca' multiplicity=1; gamma=0; % Spin 0 nucleus case '43Ca' multiplicity=8; gamma=-1.803069e7; % NMR Enc. 1996 case '44Ca' multiplicity=1; gamma=0; % Spin 0 nucleus case '45Sc' multiplicity=8; gamma=6.5087973e7; % NMR Enc. 1996 case '46Ti' multiplicity=1; gamma=0; % Spin 0 nucleus case '47Ti' multiplicity=6; gamma=-1.5105e7; % NMR Enc. 1996 case '48Ti' multiplicity=1; gamma=0; % Spin 0 nucleus case '49Ti' multiplicity=8; gamma=-1.51095e7; % NMR Enc. 1996 case '50Ti' multiplicity=1; gamma=0; % Spin 0 nucleus case '50V' multiplicity=13; gamma=2.6706490e7; % NMR Enc. 1996 case '51V' multiplicity=8; gamma=7.0455117e7; % NMR Enc. 1996 case '52Cr' multiplicity=1; gamma=0; % Spin 0 nucleus case '53Cr' multiplicity=4; gamma=-1.5152e7; % NMR Enc. 1996 case '54Cr' multiplicity=1; gamma=0; % Spin 0 nucleus case '55Mn' multiplicity=6; gamma=6.6452546e7; % NMR Enc. 1996 case '54Fe' multiplicity=1; gamma=0; % Spin 0 nucleus case '56Fe' multiplicity=1; gamma=0; % Spin 0 nucleus case '57Fe' multiplicity=2; gamma=0.8680624e7; % NMR Enc. 1996 case '58Fe' multiplicity=1; gamma=0; % Spin 0 nucleus case '59Co' multiplicity=8; gamma=6.332e7; % NMR Enc. 1996 case '60Ni' multiplicity=1; gamma=0; % Spin 0 nucleus case '61Ni' multiplicity=4; gamma=-2.3948e7; % NMR Enc. 1996 case '62Ni' multiplicity=1; gamma=0; % Spin 0 nucleus case '64Ni' multiplicity=1; gamma=0; % Spin 0 nucleus case '63Cu' multiplicity=4; gamma=7.1117890e7; % NMR Enc. 1996 case '65Cu' multiplicity=4; gamma=7.60435e7; % NMR Enc. 1996 case '64Zn' multiplicity=1; gamma=0; % Spin 0 nucleus case '66Zn' multiplicity=1; gamma=0; % Spin 0 nucleus case '67Zn' multiplicity=6; gamma=1.676688e7; % NMR Enc. 1996 case '68Zn' multiplicity=1; gamma=0; % Spin 0 nucleus case '69Ga' multiplicity=4; gamma=6.438855e7; % NMR Enc. 1996 case '71Ga' multiplicity=4; gamma=8.181171e7; % NMR Enc. 1996 case '70Ge' multiplicity=1; gamma=0; % Spin 0 nucleus case '72Ge' multiplicity=1; gamma=0; % Spin 0 nucleus case '73Ge' multiplicity=10; gamma=-0.9722881e7; % NMR Enc. 1996 case '74Ge' multiplicity=1; gamma=0; % Spin 0 nucleus case '75As' multiplicity=4; gamma=4.596163e7; % NMR Enc. 1996 case '74Se' multiplicity=1; gamma=0; % Spin 0 nucleus case '76Se' multiplicity=1; gamma=0; % Spin 0 nucleus case '77Se' multiplicity=2; gamma=5.1253857e7; % NMR Enc. 1996 case '78Se' multiplicity=1; gamma=0; % Spin 0 nucleus case '79Br' multiplicity=4; gamma=6.725616e7; % NMR Enc. 1996 case '81Br' multiplicity=4; gamma=7.249776e7; % NMR Enc. 1996 case '80Kr' multiplicity=1; gamma=0; % Spin 0 nucleus case '82Kr' multiplicity=1; gamma=0; % Spin 0 nucleus case '83Kr' multiplicity=10; gamma=-1.03310e7; % NMR Enc. 1996 case '84Kr' multiplicity=1; gamma=0; % Spin 0 nucleus case '86Kr' multiplicity=1; gamma=0; % Spin 0 nucleus case '85Rb' multiplicity=6; gamma=2.5927050e7; % NMR Enc. 1996 case '87Rb' multiplicity=4; gamma=8.786400e7; % NMR Enc. 1996 case '84Sr' multiplicity=1; gamma=0; % Spin 0 nucleus case '86Sr' multiplicity=1; gamma=0; % Spin 0 nucleus case '87Sr' multiplicity=10; gamma=-1.1639376e7; % NMR Enc. 1996 case '88Sr' multiplicity=1; gamma=0; % Spin 0 nucleus case '89Y' multiplicity=2; gamma=-1.3162791e7; % NMR Enc. 1996 case '90Zr' multiplicity=1; gamma=0; % Spin 0 nucleus case '91Zr' multiplicity=6; gamma=-2.49743e7; % NMR Enc. 1996 case '92Zr' multiplicity=1; gamma=0; % Spin 0 nucleus case '94Zr' multiplicity=1; gamma=0; % Spin 0 nucleus case '93Nb' multiplicity=10; gamma=6.5674e7; % NMR Enc. 1996 case '92Mo' multiplicity=1; gamma=0; % Spin 0 nucleus case '94Mo' multiplicity=1; gamma=0; % Spin 0 nucleus case '95Mo' multiplicity=6; gamma=-1.7514e7; % Needs checking case '96Mo' multiplicity=1; gamma=0; % Spin 0 nucleus case '97Mo' multiplicity=6; gamma=-1.7884e7; % Needs checking case '98Mo' multiplicity=1; gamma=0; % Spin 0 nucleus case '99Tc' multiplicity=10; gamma=6.0503e7; % Needs checking case '96Ru' multiplicity=1; gamma=0; % Spin 0 nucleus case '98Ru' multiplicity=1; gamma=0; % Spin 0 nucleus case '99Ru' multiplicity=6; gamma=-1.2286e7; % Needs checking case '100Ru' multiplicity=1; gamma=0; % Spin 0 nucleus case '101Ru' multiplicity=6; gamma=-1.3773e7; % Needs checking case '102Ru' multiplicity=1; gamma=0; % Spin 0 nucleus case '104Ru' multiplicity=1; gamma=0; % Spin 0 nucleus case '103Rh' multiplicity=2; gamma=-0.8468e7; % NMR Enc. 1996 case '102Pd' multiplicity=1; gamma=0; % Spin 0 nucleus case '104Pd' multiplicity=1; gamma=0; % Spin 0 nucleus case '105Pd' multiplicity=6; gamma=-1.2305e7; % Needs checking case '106Pd' multiplicity=1; gamma=0; % Spin 0 nucleus case '108Pd' multiplicity=1; gamma=0; % Spin 0 nucleus case '110Pd' multiplicity=1; gamma=0; % Spin 0 nucleus case '107Ag' multiplicity=2; gamma=-1.0889181e7; % NMR Enc. 1996 case '109Ag' multiplicity=2; gamma=-1.2518634e7; % NMR Enc. 1996 case '106Cd' multiplicity=1; gamma=0; % Spin 0 nucleus case '108Cd' multiplicity=1; gamma=0; % Spin 0 nucleus case '110Cd' multiplicity=1; gamma=0; % Spin 0 nucleus case '111Cd' multiplicity=2; gamma=-5.6983131e7; % NMR Enc. 1996 case '112Cd' multiplicity=1; gamma=0; % Spin 0 nucleus case '113Cd' multiplicity=2; gamma=-5.9609153e7; % NMR Enc. 1996 case '114Cd' multiplicity=1; gamma=0; % Spin 0 nucleus case '116Cd' multiplicity=1; gamma=0; % Spin 0 nucleus case '113In' multiplicity=10; gamma=5.8845e7; % NMR Enc. 1996 case '115In' multiplicity=10; gamma=5.8972e7; % NMR Enc. 1996 case '112Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '114Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '115Sn' multiplicity=2; gamma=-8.8013e7; % NMR Enc. 1996 case '116Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '117Sn' multiplicity=2; gamma=-9.58879e7; % NMR Enc. 1996 case '118Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '119Sn' multiplicity=2; gamma=-10.0317e7; % NMR Enc. 1996 case '120Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '122Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '124Sn' multiplicity=1; gamma=0; % Spin 0 nucleus case '121Sb' multiplicity=6; gamma=6.4435e7; % NMR Enc. 1996 case '123Sb' multiplicity=8; gamma=3.4892e7; % NMR Enc. 1996 case '120Te' multiplicity=1; gamma=0; % Spin 0 nucleus case '122Te' multiplicity=1; gamma=0; % Spin 0 nucleus case '123Te' multiplicity=2; gamma=-7.059098e7; % NMR Enc. 1996 case '124Te' multiplicity=1; gamma=0; % Spin 0 nucleus case '125Te' multiplicity=2; gamma=-8.5108404e7; % NMR Enc. 1996 case '126Te' multiplicity=1; gamma=0; % Spin 0 nucleus case '128Te' multiplicity=1; gamma=0; % Spin 0 nucleus case '130Te' multiplicity=1; gamma=0; % Spin 0 nucleus case '127I' multiplicity=6; gamma=5.389573e7; % NMR Enc. 1996 case '124Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '126Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '128Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '129Xe' multiplicity=2; gamma=-7.452103e7; % NMR Enc. 1996 case '130Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '131Xe' multiplicity=4; gamma=2.209076e7; % NMR Enc. 1996 case '132Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '134Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '136Xe' multiplicity=1; gamma=0; % Spin 0 nucleus case '133Cs' multiplicity=8; gamma=3.5332539e7; % NMR Enc. 1996 case '130Ba' multiplicity=1; gamma=0; % Spin 0 nucleus case '132Ba' multiplicity=1; gamma=0; % Spin 0 nucleus case '134Ba' multiplicity=1; gamma=0; % Spin 0 nucleus case '135Ba' multiplicity=4; gamma=2.65750e7; % NMR Enc. 1996 case '136Ba' multiplicity=1; gamma=0; % Spin 0 nucleus case '137Ba' multiplicity=4; gamma=2.99295e7; % NMR Enc. 1996 case '138Ba' multiplicity=1; gamma=0; % Spin 0 nucleus case '138La' multiplicity=11; gamma=3.557239e7; % NMR Enc. 1996 case '139La' multiplicity=8; gamma=3.8083318e7; % NMR Enc. 1996 case '136Ce' multiplicity=1; gamma=0; % Spin 0 nucleus case '138Ce' multiplicity=1; gamma=0; % Spin 0 nucleus case '139Ce' multiplicity=6; gamma= 2.906e7; % Needs checking case '140Ce' multiplicity=1; gamma=0; % Spin 0 nucleus case '142Ce' multiplicity=1; gamma=0; % Spin 0 nucleus case '141Pr' multiplicity=6; gamma=8.1907e7; % NMR Enc. 1996 case '142Nd' multiplicity=1; gamma=0; % Spin 0 nucleus case '143Nd' multiplicity=8; gamma=-1.457e7; % NMR Enc. 1996 case '144Nd' multiplicity=1; gamma=0; % Spin 0 nucleus case '145Nd' multiplicity=8; gamma=-0.898e7; % NMR Enc. 1996 case '146Nd' multiplicity=1; gamma=0; % Spin 0 nucleus case '148Nd' multiplicity=1; gamma=0; % Spin 0 nucleus case '150Nd' multiplicity=1; gamma=0; % Spin 0 nucleus case '147Pm' multiplicity=8; gamma= 3.613e7; % NMR Enc. 1996 case '144Sm' multiplicity=1; gamma=0; % Spin 0 nucleus case '147Sm' multiplicity=8; gamma=-1.115e7; % NMR Enc. 1996 case '148Sm' multiplicity=1; gamma=0; % Spin 0 nucleus case '149Sm' multiplicity=8; gamma=-0.9192e7; % NMR Enc. 1996 case '150Sm' multiplicity=1; gamma=0; % Spin 0 nucleus case '152Sm' multiplicity=1; gamma=0; % Spin 0 nucleus case '154Sm' multiplicity=1; gamma=0; % Spin 0 nucleus case '151Eu' multiplicity=6; gamma=6.6510e7; % NMR Enc. 1996 case '153Eu' multiplicity=6; gamma=2.9369e7; % NMR Enc. 1996 case '152Gd' multiplicity=1; gamma=0; % Spin 0 nucleus case '154Gd' multiplicity=1; gamma=0; % Spin 0 nucleus case '155Gd' multiplicity=4; gamma=-0.82132e7; % NMR Enc. 1996 case '156Gd' multiplicity=1; gamma=0; % Spin 0 nucleus case '157Gd' multiplicity=4; gamma=-1.0769e7; % NMR Enc. 1996 case '158Gd' multiplicity=1; gamma=0; % Spin 0 nucleus case '160Gd' multiplicity=1; gamma=0; % Spin 0 nucleus case '159Tb' multiplicity=4; gamma=6.4306e7; % Needs checking case '156Dy' multiplicity=1; gamma=0; % Spin 0 nucleus case '158Dy' multiplicity=1; gamma=0; % Spin 0 nucleus case '160Dy' multiplicity=1; gamma=0; % Spin 0 nucleus case '161Dy' multiplicity=6; gamma=-0.9201e7; % NMR Enc. 1996 case '162Dy' multiplicity=1; gamma=0; % Spin 0 nucleus case '163Dy' multiplicity=6; gamma=1.289e7; % NMR Enc. 1996 case '164Dy' multiplicity=1; gamma=0; % Spin 0 nucleus case '165Ho' multiplicity=8; gamma=5.710e7; % NMR Enc. 1996 case '162Er' multiplicity=1; gamma=0; % Spin 0 nucleus case '164Er' multiplicity=1; gamma=0; % Spin 0 nucleus case '166Er' multiplicity=1; gamma=0; % Spin 0 nucleus case '167Er' multiplicity=8; gamma=-0.77157e7; % NMR Enc. 1996 case '168Er' multiplicity=1; gamma=0; % Spin 0 nucleus case '170Er' multiplicity=1; gamma=0; % Spin 0 nucleus case '169Tm' multiplicity=2; gamma=-2.218e7; % NMR Enc. 1996 case '168Yb' multiplicity=1; gamma=0; % Spin 0 nucleus case '170Yb' multiplicity=1; gamma=0; % Spin 0 nucleus case '171Yb' multiplicity=2; gamma=4.7288e7; % NMR Enc. 1996 case '172Yb' multiplicity=1; gamma=0; % Spin 0 nucleus case '173Yb' multiplicity=6; gamma=-1.3025e7; % NMR Enc. 1996 case '174Yb' multiplicity=1; gamma=0; % Spin 0 nucleus case '176Yb' multiplicity=1; gamma=0; % Spin 0 nucleus case '175Lu' multiplicity=8; gamma=3.0552e7; % NMR Enc. 1996 case '176Lu' multiplicity=15; gamma=2.1684e7; % NMR Enc. 1996 case '174Hf' multiplicity=1; gamma=0; % Spin 0 nucleus case '176Hf' multiplicity=1; gamma=0; % Spin 0 nucleus case '177Hf' multiplicity=8; gamma=1.086e7; % NMR Enc. 1996 case '178Hf' multiplicity=1; gamma=0; % Spin 0 nucleus case '179Hf' multiplicity=10; gamma=-0.6821e7; % NMR Enc. 1996 case '180Hf' multiplicity=1; gamma=0; % Spin 0 nucleus case '180Ta' multiplicity=1; gamma=0; % Spin 0 nucleus case '181Ta' multiplicity=8; gamma=3.2438e7; % NMR Enc. 1996 case '180W' multiplicity=1; gamma=0; % Spin 0 nucleus case '182W' multiplicity=1; gamma=0; % Spin 0 nucleus case '183W' multiplicity=2; gamma=1.1282403e7; % NMR Enc. 1996 case '184W' multiplicity=1; gamma=0; % Spin 0 nucleus case '186W' multiplicity=1; gamma=0; % Spin 0 nucleus case '185Re' multiplicity=6; gamma=6.1057e7; % NMR Enc. 1996 case '187Re' multiplicity=6; gamma=6.1682e7; % NMR Enc. 1996 case '184Os' multiplicity=1; gamma=0; % Spin 0 nucleus case '186Os' multiplicity=1; gamma=0; % Spin 0 nucleus case '187Os' multiplicity=2; gamma=0.6192895e7; % NMR Enc. 1996 case '188Os' multiplicity=1; gamma=0; % Spin 0 nucleus case '189Os' multiplicity=4; gamma=2.10713e7; % NMR Enc. 1996 case '190Os' multiplicity=1; gamma=0; % Spin 0 nucleus case '192Os' multiplicity=1; gamma=0; % Spin 0 nucleus case '191Ir' multiplicity=4; gamma=0.4812e7; % NMR Enc. 1996 case '193Ir' multiplicity=4; gamma=0.5227e7; % NMR Enc. 1996 case '190Pt' multiplicity=1; gamma=0; % Spin 0 nucleus case '192Pt' multiplicity=1; gamma=0; % Spin 0 nucleus case '194Pt' multiplicity=1; gamma=0; % Spin 0 nucleus case '195Pt' multiplicity=2; gamma=5.8385e7; % NMR Enc. 1996 case '196Pt' multiplicity=1; gamma=0; % Spin 0 nucleus case '198Pt' multiplicity=1; gamma=0; % Spin 0 nucleus case '197Au' multiplicity=4; gamma=0.473060e7; % NMR Enc. 1996 case '196Hg' multiplicity=1; gamma=0; % Spin 0 nucleus case '198Hg' multiplicity=1; gamma=0; % Spin 0 nucleus case '199Hg' multiplicity=2; gamma=4.8457916e7; % NMR Enc. 1996 case '200Hg' multiplicity=1; gamma=0; % Spin 0 nucleus case '201Hg' multiplicity=4; gamma=-1.788769e7; % NMR Enc. 1996 case '202Hg' multiplicity=1; gamma=0; % Spin 0 nucleus case '204Hg' multiplicity=1; gamma=0; % Spin 0 nucleus case '203Tl' multiplicity=2; gamma=15.5393338e7; % NMR Enc. 1996 case '205Tl' multiplicity=2; gamma=15.6921808e7; % NMR Enc. 1996 case '204Pb' multiplicity=1; gamma=0; % Spin 0 nucleus case '206Pb' multiplicity=1; gamma=0; % Spin 0 nucleus case '207Pb' multiplicity=2; gamma=5.58046e7; % NMR Enc. 1996 case '208Pb' multiplicity=1; gamma=0; % Spin 0 nucleus case '209Bi' multiplicity=10; gamma=4.3750e7; % NMR Enc. 1996 case '209Po' multiplicity=2; gamma= 7.4e7; % NMR Enc. 1996 case '227Ac' multiplicity=4; gamma= 3.5e7; % NMR Enc. 1996 case '229Th' multiplicity=6; gamma= 0.40e7; % NMR Enc. 1996 case '231Pa' multiplicity=4; gamma=3.21e7; % NMR Enc. 1996 case '235U' multiplicity=8; gamma=-0.4926e7; % Needs checking case '237Np' multiplicity=6; gamma=3.1e7; % NMR Enc. 1996 case '239Pu' multiplicity=2; gamma=0.972e7; % NMR Enc. 1996 case '241Am' multiplicity=6; gamma=1.54e7; % NMR Enc. 1996 case '243Am' multiplicity=6; gamma=1.54e7; % NMR Enc. 1996 case '247Cm' multiplicity=10; gamma=0.20e7; % NMR Enc. 1996 case {'210At', '222Rn', '223Fr', '226Ra', '247Bk', '251Cf', '252Es', '253Es', '257Fm', '258Md', '259No'} error([name ' - no data available in the current NMR literature.']); otherwise error([name ' - unknown isotope.']); end end end % I mean that there is no way to disarm any man except through guilt. % Through that which he himself has accepted as guilt. If a man has % ever stolen a dime, you can impose on him the punishment intended % for a bank robber and he will take it. He'll bear any form of mise- % ry, he'll feel that he deserves no better. If there's not enough % guilt in the world, we must create it. If we teach a man that it's % evil to look at spring flowers and he believes us and then does it, % we'll be able to do whatever we please with him. He won't defend % himself. He won't feel he's worth it. He won't fight. But save us % from the man who lives up to his own standards. Save us from the % man of clean conscience. He's the man who'll beat us. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
trajan.m
.m
nmr-pred-master/spinach/kernel/trajan.m
8,616
utf_8
cfdb63f08f3d1bcf49595de836bc1b19
% Trajectory analysis function. Plots the time dependence of the densi- % ty matrix norm, partitioned into user-specified property classes. % % Call syntax: % % trajan(spin_system,trajectory,property) % % Arguments: % % trajectory - a stack of state vectors of any length. The % number of rows in the trajectory array must % match the number of states in the basis. % % property - If set to 'correlation_order', returns the % time dependence of the total populations of % one-spin, two-spin, three-spin, etc. corre- % lations in the system. % % If set to 'coherence_order', returns the ti- % me dependence of different orders of coheren- % ce in the system, where a coherence order is % defined as the sum of projection quantum num- % bers in the spherical tensor representation % of each state. % % If set to 'total_each_spin', returns the ti- % me dependence of total state space populati- % on that involves each individual spin in the % system in any way (all local populations and % coherences of the spin as well as all of its % correlations to all third party spins). % % If set to 'local_each_spin', returns the ti- % me dependence of the population of the sub- % space of states that are local to each indi- % vidual spin and do not involve any correla- % tions to other spins in the system. % % If set to 'level_populations', returns the % populations of the Zeeman energy levels. % % The trajectory would usually come out of the evolution() run from a % given starting point under a given Liouvillian. % % Note: this function is only applicable to the trajectories recorded % in spherical tensor basis sets. % % [email protected] % [email protected] % [email protected] function trajan(spin_system,trajectory,property) % Check the input grumble(spin_system,trajectory); % Set the defaults if ~exist('property','var'), property='correlation_order'; end % Determine how to proceed switch property case 'correlation_order' % Determine the correlation order of each state correlation_orders=sum(logical(spin_system.bas.basis),2); % Find out which correlation orders are present unique_correlation_orders=unique(correlation_orders); % Preallocate the norm trajectory array result=zeros(numel(unique_correlation_orders),size(trajectory,2)); % Loop over the unique correlation orders that are present for n=1:numel(unique_correlation_orders) % Find the subspace of the given correlation order subspace_mask=(correlation_orders==unique_correlation_orders(n)); % Get the part of the trajectory belonging to the subspace subspace_trajectory=trajectory(subspace_mask,:); % Get the norm of the trajectory result(n,:)=sqrt(sum(subspace_trajectory.*conj(subspace_trajectory),1)); end % Create a legend legend_text=cell(numel(unique_correlation_orders),1); for n=1:numel(unique_correlation_orders) legend_text{n}=[num2str(unique_correlation_orders(n)) '-spin order']; end % Create an axis label label_text='correlation order amplitude'; case 'coherence_order' % Determine projection quantum numbers of the basis [~,M]=lin2lm(spin_system.bas.basis); % Determine the coherence order of each state coherence_orders=sum(M,2); % Find out which coherence orders are present unique_coherence_orders=unique(coherence_orders); % Preallocate the norm trajectory array result=zeros(numel(unique_coherence_orders),size(trajectory,2)); % Loop over the unique coherence orders that are present for n=1:numel(unique_coherence_orders) % Find the subspace of the given coherence order subspace_mask=(coherence_orders==unique_coherence_orders(n)); % Get the part of the trajectory belonging to the subspace subspace_trajectory=trajectory(subspace_mask,:); % Get the norm of the trajectory result(n,:)=sqrt(sum(subspace_trajectory.*conj(subspace_trajectory),1)); end % Create a legend legend_text=cell(numel(unique_coherence_orders),1); for n=1:numel(unique_coherence_orders) legend_text{n}=['coherence order ' num2str(unique_coherence_orders(n))]; end % Create an axis label label_text='coherence order amplitude'; case 'total_each_spin' % Preallocate the norm trajectory array result=zeros(spin_system.comp.nspins,size(trajectory,2)); % Loop over spins in the system for n=1:spin_system.comp.nspins % Find the subspace of states that involve the current spin subspace_mask=(spin_system.bas.basis(:,n)~=0); % Get the part of the trajectory belonging to the subspace subspace_trajectory=trajectory(subspace_mask,:); % Get the norm of the trajectory result(n,:)=sqrt(sum(subspace_trajectory.*conj(subspace_trajectory),1)); end % Create an axis label label_text='density touching each spin'; case 'local_each_spin' % Preallocate the norm trajectory array result=zeros(spin_system.comp.nspins,size(trajectory,2)); % Loop over spins in the system for n=1:spin_system.comp.nspins % Find the subspace of states that are local to current spin subspace_mask=(spin_system.bas.basis(:,n)~=0)&... (sum(spin_system.bas.basis,2)==spin_system.bas.basis(:,n)); % Get the part of the trajectory belonging to the subspace subspace_trajectory=trajectory(subspace_mask,:); % Get the norm of the trajectory result(n,:)=sqrt(sum(subspace_trajectory.*conj(subspace_trajectory),1)); end % Create an axis label label_text='density local to each spin'; case 'level_populations' % Move trajectory into the Zeeman basis set trajectory=sphten2zeeman(spin_system)*trajectory; % Find out the number of energy levels nlevels=sqrt(size(trajectory,1)); % Preallocate population dynamics array result=zeros(nlevels,size(trajectory,2)); % Extract the populations for n=1:size(trajectory,2) result(:,n)=real(diag(reshape(trajectory(:,n),[nlevels nlevels]))); end % Create an axis label label_text='energy level populations'; otherwise % Complain and bomb out error('unknown property.'); end % Do the plotting plot(result'); xlabel('time / points'); ylabel(label_text); axis tight; set(gca,'yscale','log'); if exist('legend_text','var') legend(legend_text,'Location','NorthEast'); end end % Consistency enforcement function grumble(spin_system,trajectory) if ~ismember(spin_system.bas.formalism,{'sphten-liouv'}) error('trajectory analysis is only available for sphten-liouv formalism.'); end if ~isnumeric(trajectory) error('trajectory should be an array of doubles.'); end if size(trajectory,1)~=size(spin_system.bas.basis,1) error('trajectory dimension should match basis dimension.'); end end % And this is the whole shabby secret: to some men, the sight of % an achievement is a reproach, a reminder that their own lives % are irrational, and that there is no loophole - no escape from % reason and reality. % % Ayn Rand
github
tsajed/nmr-pred-master
frqoffset.m
.m
nmr-pred-master/spinach/kernel/frqoffset.m
3,566
utf_8
98b35ea109750bbae94e2ee05571b05d
% Adds offset frequencies to the Hamiltonian. Syntax: % % H=frqoffset(spin_system,H,parameters) % % where H is the Hamiltonian and parameters should contain % the following subfields: % % parameters.spins - a cell array giving the % spins that the pulse sequence works on, in % the order of channels, e.g. {'1H','13C'} % % parameters.offset - a cell array giving % transmitter offsets on each of the spins % listed in parameters.spins array. % % If multiple channels operate on the same spins, the cor- % responding offsets must be the same. % % [email protected] function H=frqoffset(spin_system,H,parameters) % Check consistency grumble(spin_system,parameters); % See if there are multiple channels on the same spin [unique_spins,forward_index,backward_index]=unique(parameters.spins); % Decide how to proceed if numel(unique_spins)==numel(parameters.spins) % Simply apply the offsets for n=find(parameters.offset~=0) report(spin_system,['applying ' num2str(parameters.offset(n)) ' Hz Zeeman frequency offset to ' parameters.spins{n} '...']); H=H+2*pi*parameters.offset(n)*operator(spin_system,'Lz',parameters.spins{n}); end else % Get unique offsets unique_offsets=parameters.offset(forward_index); % Check offsets on duplicate channels if ~all(unique_offsets(backward_index)==parameters.offset) error('offsets on channels referring to the same spin must be the same.'); end % Apply the offsets for n=find(unique_offsets~=0) report(spin_system,['applying ' num2str(unique_offsets(n)) ' Hz Zeeman frequency offset to ' unique_spins{n} '...']); H=H+2*pi*unique_offsets(n)*operator(spin_system,'Lz',unique_spins{n}); end end end % Consistency enforcement function grumble(spin_system,parameters) if isempty(parameters.spins) error('parameters.spins variable cannot be empty.'); elseif ~iscell(parameters.spins) error('parameters.spins variable must be a cell array.'); elseif ~all(cellfun(@ischar,parameters.spins)) error('all elements of parameters.spins cell array must be strings.'); elseif any(~ismember(parameters.spins,spin_system.comp.isotopes)) error('parameters.spins refers to a spin that is not present in the system.'); end if isempty(parameters.offset) error('parameters.offset variable cannot be empty.'); elseif ~isnumeric(parameters.offset) error('parameters.offset variable must be an array of real numbers.'); elseif ~isfield(parameters,'spins') error('parameters.spins variable must be specified alongside parameters.offset variable.'); elseif numel(parameters.offset)~=numel(parameters.spins) error('parameters.offset variable must have the same number of elements as parameters.spins.'); end end % [...] this flaw was identified by the brilliant German philosopher % Friedrich Nietzsche who described it as "an inversion of morality" % whereby the weak, the poor, the meek, the oppressed and the wretch- % ed are virtuous and blessed by God whereas the strong, the wealthy, % the noble and the powerful are the immoral and damned by the venge- % ful almighty Yahweh for eternity. Nietzsche, with great insight and % perception, stated that Christianity would be abandoned en masse in % the twentieth century but that Westerners would still cling to this % inversion of morality. % % Anders Behring Breivik
github
tsajed/nmr-pred-master
homospoil.m
.m
nmr-pred-master/spinach/kernel/homospoil.m
2,499
utf_8
be97284024d04086a9e28d58d38f9c64
% Emulates a strong homospoil pulse - only zero-frequency states % survive the process. Syntax: % % rho=homospoil(spin_system,rho,zqc_flag) % % Parameters: % % rho - a state vector or a horizontal stack thereof % % zqc_flag - a flag controlling the fate of zero-quantum % coherences. If set to 'keep', causes ZQCs to % survive the process, approximating experimen- % tal behaviour. If set to 'destroy', wipes the % zero-quantum coherences - only the longitudi- % nal states survive the process. % % Note: this function is only available for sphten-liouv formalism. % % [email protected] function rho=homospoil(spin_system,rho,zqc_flag) % Check consistency grumble(spin_system,rho,zqc_flag) % Store dimension statistics spn_dim=size(spin_system.bas.basis,1); spc_dim=numel(rho)/spn_dim; problem_dims=size(rho); % Fold indirect dimensions rho=reshape(rho,[spn_dim spc_dim]); % Pull the projection information from the basis [~,M]=lin2lm(spin_system.bas.basis); % Filter the state vector switch zqc_flag case 'keep' % Find the states that have zero carrier frequency and kill everything else rho(abs(sum(repmat(spin_system.inter.basefrqs,size(spin_system.bas.basis,1),1).*M,2))>1e-6,:)=0; case 'destroy' % Find the longitudinal states and kill everything else rho(sum(abs(M),2)>0,:)=0; otherwise % Complain and bomb out error('unknown ZQC flag.'); end % Unfold indirect dimensions rho=reshape(rho,problem_dims); % Report overly destructive calls if norm(rho,1)<1e-10 report(spin_system,'WARNING - all magnetization appears to have been destroyed by this call.'); end end % Consistency enforcement function grumble(spin_system,rho,zqc_flag) if ~ismember(spin_system.bas.formalism,{'sphten-liouv'}) error('this function is only available for sphten-liouv formalism.'); end if ~isnumeric(rho) error('the state vector(s) must be numeric.'); end if ~ischar(zqc_flag) error('zqc_flag parameter must be a character string.'); end if ~ismember(zqc_flag,{'keep','destroy'}) error('the available values for zqc_flag are ''keep'' and ''destroy''.'); end end % Rocket science has been mythologized all out of proportion to % its true difficulty. % % John Carmack
github
tsajed/nmr-pred-master
basis.m
.m
nmr-pred-master/spinach/kernel/basis.m
25,413
utf_8
e849e7e3736fb8cf2344dbff1b2f1332
% Basis set control. This is the second mandatory function (after create.m) % that must be executed in every calculation to get the Spinach kernel go- % ing. See the Basis Selection section of the Spinach manual for the detail- % ed description of the various options. % % Note: it is very important that you understand the factors that influence % basis set selection in spin dynamics simulations -- see the following pa- % per for further details on the subject: % % http://link.aip.org/link/doi/10.1063/1.3624564 % % [email protected] function spin_system=basis(spin_system,bas) % Show the banner banner(spin_system,'basis_banner'); % Check the input grumble(spin_system,bas); % Report the basis to the user spin_system.bas.formalism=bas.formalism; switch spin_system.bas.formalism case 'zeeman-hilb' report(spin_system,'Zeeman basis set using Hilbert space matrix formalism.'); case 'zeeman-liouv' report(spin_system,'Zeeman basis set using Liouville space matrix formalism.'); case 'sphten-liouv' report(spin_system,'spherical tensor basis set using Liouville space matrix formalism.'); otherwise error('unrecognized formalism - see the basis preparation section of the manual.'); end % Save bas.approximation field to the spin_system spin_system.bas.approximation=bas.approximation; % Process spherical tensor basis sets if strcmp(spin_system.bas.formalism,'sphten-liouv') % Report approximation level to the user switch spin_system.bas.approximation case 'IK-0' report(spin_system,['IK-0 approximation - all correlations of all spins up to order ' num2str(bas.level)]); case 'IK-1' report(spin_system,['IK-1 approximation - spin correlations up to order ' num2str(bas.level) ' between directly coupled spins.']); report(spin_system,['IK-1 approximation - spin correlations up to order ' num2str(bas.space_level) ' between all spins within ' num2str(spin_system.tols.prox_cutoff) ' Angstrom of each other.']); case 'IK-2' report(spin_system, 'IK-2 approximation - spin correlations involving all nearest neighbours of each spin on the coupling graph.'); report(spin_system,['IK-2 approximation - spin correlations up to order ' num2str(bas.space_level) ' between all spins within ' num2str(spin_system.tols.prox_cutoff) ' Angstrom of each other.']); case 'ESR-1' report(spin_system, 'ESR-1 approximation - complete basis on all electrons.'); report(spin_system, 'ESR-1 approximation - zero-quantum basis on all nuclei.'); case 'ESR-2' report(spin_system, 'ESR-2 approximation - complete basis on all electrons.'); report(spin_system, 'ESR-2 approximation - complete basis on all nuclei with anisotropic HFC tensors.'); report(spin_system, 'ESR-2 approximation - zero-quantum basis on all nuclei with isotropic HFC tensors.'); case 'none' report(spin_system, 'complete basis set on all spins.'); otherwise error('unrecognized approximation level - see the basis set preparation manual.'); end % Run connectivity analysis if ismember(spin_system.bas.approximation,{'IK-1','IK-2'}) % Build connectivity and proximity matrices switch bas.connectivity case 'scalar_couplings' report(spin_system,'scalar couplings will be used to build the coupling graph.'); spin_system.inter.conmatrix=sparse(abs(cellfun(@trace,spin_system.inter.coupling.matrix)/3)>spin_system.tols.inter_cutoff); case 'full_tensors' report(spin_system,'full coupling tensors will be used to build the coupling graph.'); spin_system.inter.conmatrix=sparse(cellfun(@norm,spin_system.inter.coupling.matrix)>spin_system.tols.inter_cutoff); end report(spin_system,['coupling tensors with norm below ' num2str(spin_system.tols.inter_cutoff) ' rad/s will be ignored.']); % Make sure each spin is connected and proximate to itself spin_system.inter.conmatrix=spin_system.inter.conmatrix|speye(size(spin_system.inter.conmatrix)); spin_system.inter.proxmatrix=spin_system.inter.proxmatrix|speye(size(spin_system.inter.proxmatrix)); % Make sure connectivity and proximity are reciprocal spin_system.inter.conmatrix=spin_system.inter.conmatrix|transpose(spin_system.inter.conmatrix); spin_system.inter.proxmatrix=spin_system.inter.proxmatrix|transpose(spin_system.inter.proxmatrix); % Issue a report to the user report(spin_system,['connectivity matrix density ' num2str(100*nnz(spin_system.inter.conmatrix)/numel(spin_system.inter.conmatrix)) '%']); report(spin_system,['proximity matrix density ' num2str(100*nnz(spin_system.inter.proxmatrix)/numel(spin_system.inter.proxmatrix)) '%']); % Determine the number of independent subsystems n_subsystems=max(scomponents(spin_system.inter.conmatrix|spin_system.inter.proxmatrix)); % Print a notice to the user if n_subsystems>1 report(spin_system,['WARNING - the system contains ' num2str(n_subsystems) ' non-interacting subsystems.']); end end % Generate subgraphs for IK-0 basis if strcmp(spin_system.bas.approximation,'IK-0') % Find all possible groups of bas.level spins col_index=combnk(1:spin_system.comp.nspins,bas.level); % Get the number of groups ngroups=size(col_index,1); % Assign numbers to groups row_index=kron((1:ngroups)',ones(1,bas.level)); % Generate the subgraph list coupling_subgraphs=logical(sparse(row_index,col_index,ones(size(col_index)),ngroups,spin_system.comp.nspins)); report(spin_system,['' num2str(size(coupling_subgraphs,1)) ' subgraphs generated by combinatorial analysis.']); % Do not run proximity analysis proximity_subgraphs=[]; end % Generate subgraphs for IK-1 basis if strcmp(spin_system.bas.approximation,'IK-1') % Run connectivity analysis coupling_subgraphs=dfpt(spin_system.inter.conmatrix,bas.level); report(spin_system,['' num2str(size(coupling_subgraphs,1)) ' subgraphs generated from coupling data.']); % Run proximity analysis proximity_subgraphs=dfpt(spin_system.inter.proxmatrix,bas.space_level); report(spin_system,['' num2str(size(proximity_subgraphs,1)) ' subgraphs generated from proximity data.']); end % Generate subgraphs for IK-2 basis if strcmp(spin_system.bas.approximation,'IK-2') % Run connectivity analysis coupling_subgraphs=spin_system.inter.conmatrix; report(spin_system,['' num2str(size(coupling_subgraphs,1)) ' subgraphs generated from coupling data.']); % Run proximity analysis proximity_subgraphs=dfpt(spin_system.inter.proxmatrix,bas.space_level); report(spin_system,['' num2str(size(proximity_subgraphs,1)) ' subgraphs generated from proximity data.']); end % Build IK-0,1,2 basis sets if ismember(spin_system.bas.approximation,{'IK-0','IK-1','IK-2'}) % Include user-specified subgraphs if (~isfield(bas,'manual'))||isempty(bas.manual) manual_subgraphs=[]; else manual_subgraphs=bas.manual; report(spin_system,['added ' num2str(size(manual_subgraphs,1)) ' subgraphs specified by the user.']); end % Assemble the subgraph list subgraphs=[coupling_subgraphs; proximity_subgraphs; manual_subgraphs]; clear('coupling_subgraphs','proximity_subgraphs','manual_subgraphs'); % Prune subgraphs involving spin zero particles report(spin_system,'pruning subgraphs involving zero spin particles...'); subgraphs(:,spin_system.comp.mults==1)=0; % Remove identical subgraphs report(spin_system,'removing identical subgraphs...'); subgraphs=unique(subgraphs,'rows'); % Store subgraphs for future use spin_system.bas.subgraphs=logical(subgraphs); % Report back to the user subgraph_sizes=sum(subgraphs,2); for n=min(subgraph_sizes):max(subgraph_sizes) if nnz(subgraph_sizes==n)>0 report(spin_system,['generated ' num2str(nnz(subgraph_sizes==n)) ' subgraphs of size ' num2str(n)]); end end % Balance the subgraph list subgraphs=subgraphs(randperm(size(subgraphs,1)),:); % Populate the basis descriptor array report(spin_system,'building basis descriptor...'); spmd % Localize the problem at the nodes subgraphs=codistributed(subgraphs,codistributor('1d',1)); subgraphs_loc=getLocalPart(subgraphs); % Preallocate local basis descriptor array nstates=0; for n=1:size(subgraphs_loc,1) nstates=nstates+prod(spin_system.comp.mults(logical(subgraphs_loc(n,:))))^2; end basis_spec=spalloc(nstates,spin_system.comp.nspins,nstates*max(subgraph_sizes)); % Populate local basis descriptor array list_position=1; for n=1:size(subgraphs_loc,1) % Determine the total number of states in the current subgraph nstates=prod(spin_system.comp.mults(logical(subgraphs_loc(n,:))))^2; % Determine which spins belong to the current subgraph spins_involved=find(subgraphs_loc(n,:)); % Build the basis table for k=1:numel(spins_involved) basis_spec(list_position:(list_position+nstates-1),spins_involved(k))=... kron(kron(ones(prod(spin_system.comp.mults(spins_involved(1:(k-1))))^2,1),... (0:(spin_system.comp.mults(spins_involved(k))^2-1))'),... ones(prod(spin_system.comp.mults(spins_involved((k+1):end)))^2,1)); end list_position=list_position+nstates; end % Prune local basis descriptor array basis_spec=unique(basis_spec,'rows'); end % Pull the basis descriptor from the nodes try basis_spec=vertcat(basis_spec{:}); catch error('parpool appears to be stuck, check your parallel configuration.'); end end % Build ESR-1 basis set if strcmp(spin_system.bas.approximation,'ESR-1') % Prepare direct product components components=cell(1,spin_system.comp.nspins); for n=1:spin_system.comp.nspins if strcmp(spin_system.comp.isotopes{n}(1),'E') components{n}=(0:(spin_system.comp.mults(n)^2-1))'; report(spin_system,['ESR-1 approximation, complete basis set on spin ' num2str(n)]); else components{n}=((1:spin_system.comp.mults(n)).*((1:spin_system.comp.mults(n))-1))'; report(spin_system,['ESR-1 approximation, zero-quantum basis set on spin ' num2str(n)]); end end % Preallocate basis table basis_spec=zeros(prod(cellfun(@numel,components)),spin_system.comp.nspins); % Generate basis specification report(spin_system,'building basis descriptor...'); parfor n=1:spin_system.comp.nspins dimension_before=prod(cellfun(@numel,components(1:(n-1)))); %#ok<PFBNS> dimension_after=prod(cellfun(@numel,components((n+1):end))); basis_spec(:,n)=kron(kron(ones(dimension_before,1),... components{n}),ones(dimension_after,1)); end end % Process ESR-2 basis set if strcmp(spin_system.bas.approximation,'ESR-2') % Analyze coupling structure spins_with_full_basis=false(1,spin_system.comp.nspins); for n=1:spin_system.comp.nspins % Use complete basis set on anything that has an anisotropic coupling for k=1:spin_system.comp.nspins if (norm(spin_system.inter.coupling.matrix{n,k})>spin_system.tols.inter_cutoff)&&... norm(spin_system.inter.coupling.matrix{n,k}-eye(3)*trace(spin_system.inter.coupling.matrix{n,k})/3)>spin_system.tols.inter_cutoff spins_with_full_basis(n)=true(); spins_with_full_basis(k)=true(); end end % Use complete basis set on all electrons if strcmp(spin_system.comp.isotopes{n}(1),'E') spins_with_full_basis(n)=true(); end end % Prepare direct product components components=cell(1,spin_system.comp.nspins); for n=1:spin_system.comp.nspins if spins_with_full_basis(n) components{n}=(0:(spin_system.comp.mults(n)^2-1))'; report(spin_system,['ESR-2 approximation - complete basis set on spin ' num2str(n)]); else components{n}=((1:spin_system.comp.mults(n)).*((1:spin_system.comp.mults(n))-1))'; report(spin_system,['ESR-2 approximation - zero-quantum basis set on spin ' num2str(n)]); end end % Preallocate the basis table basis_spec=zeros(prod(cellfun(@numel,components)),spin_system.comp.nspins); % Generate the basis specification report(spin_system,'building basis descriptor...'); parfor n=1:spin_system.comp.nspins dimension_before=prod(cellfun(@numel,components(1:(n-1)))); %#ok<PFBNS> dimension_after=prod(cellfun(@numel,components((n+1):end))); basis_spec(:,n)=kron(kron(ones(dimension_before,1),... components{n}),ones(dimension_after,1)); end end % Process complete basis set if strcmp(spin_system.bas.approximation,'none') % Preallocate basis table basis_spec=zeros(prod(spin_system.comp.mults)^2,spin_system.comp.nspins); % Build basis table report(spin_system,'building basis descriptor...'); parfor k=1:spin_system.comp.nspins basis_spec(:,k)=kron(kron(ones(prod(spin_system.comp.mults(1:(k-1)))^2,1),... (0:(spin_system.comp.mults(k)^2-1))'),... ones(prod(spin_system.comp.mults((k+1):end))^2,1)); %#ok<PFBNS> end end % Apply coherence order filter if isfield(bas,'projections') % Inform the user report(spin_system,['applying coherence order filter with M=[' num2str(bas.projections) ']...']); % Compute coherence order for each basis element [~,M]=lin2lm(basis_spec); % Keep specified coherence orders and the unit state state_mask=false(size(basis_spec,1),1); state_mask(1)=true(); projection_numbers=sum(M,2); for n=bas.projections state_mask=state_mask|(projection_numbers==n); end basis_spec(~state_mask,:)=[]; end % Apply zero-quantum filter if isfield(bas,'longitudinals') % Start with empty mask state_mask=false(size(basis_spec,1),1); % Loop over the specified spins for n=1:numel(bas.longitudinals) % Inform the user report(spin_system,['applying longitudinal spin order filter on ' bas.longitudinals{n}]); % Kill the specified transverse states for k=find(strcmp(bas.longitudinals{n},spin_system.comp.isotopes)) % Analyze the basis [~,M]=lin2lm(basis_spec(:,k)); % Update the mask state_mask=or(state_mask,M~=0); end end % Kill the states basis_spec(state_mask,:)=[]; end % Remove spin correlations between chemical subsystems report(spin_system,'removing correlations between chemical reaction endpoints...'); for n=1:numel(spin_system.chem.parts) for k=1:numel(spin_system.chem.parts) if n~=k % Find states involving the first subsystem spins_a=spin_system.chem.parts{n}; states_a=logical(sum(basis_spec(:,spins_a),2)); % Find states involving the second subsystem spins_b=spin_system.chem.parts{k}; states_b=logical(sum(basis_spec(:,spins_b),2)); % Remove the intersection basis_spec(states_a&states_b,:)=[]; end end end % Write the final basis specification report(spin_system,'sorting the basis...'); spin_system.bas.basis=unique(basis_spec,'rows'); % Build state-cluster cross-membership list if needed if ismember('xmemlist',spin_system.sys.enable) % Report to the user report(spin_system,'building state-subgraph cross-membership list... '); % Localise variables basis_loc=spin_system.bas.basis; subgraphs_loc=spin_system.bas.subgraphs; % Preallocate the result nstates=size(basis_loc,1); nclusters=size(subgraphs_loc,1); xmemlist=spalloc(nstates,nclusters,ceil(nstates*nclusters/spin_system.comp.nspins)); % Run the matching parfor n=1:size(subgraphs_loc,1) xmemlist(:,n)=~any(basis_loc(:,~subgraphs_loc(n,:)),2); %#ok<SPRIX,PFBNS> end % Store the result spin_system.bas.xmemlist=xmemlist; end % Print the summary summary(spin_system,'basis'); % Run the symmetry treatment spin_system=symmetry(spin_system,bas); end % Process Hilbert space Zeeman basis if strcmp(spin_system.bas.formalism,'zeeman-hilb') % Preallocate basis set array spin_system.bas.basis=zeros(prod(spin_system.comp.mults),spin_system.comp.nspins); % Fill basis set array for n=1:spin_system.comp.nspins current_column=1; for k=1:spin_system.comp.nspins if n==k current_column=kron(current_column,(1:spin_system.comp.mults(k))'); else current_column=kron(current_column,ones(spin_system.comp.mults(k),1)); end end spin_system.bas.basis(:,n)=current_column; end % Run the symmetry treatment spin_system=symmetry(spin_system,bas); end end % Grumble function function grumble(spin_system,bas) % Check bas.formalism if ~isfield(bas,'formalism') error('basis specification in bas.formalism is required.'); elseif ~ischar(bas.formalism) error('bas.formalism must be a string.'); elseif ~ismember(bas.formalism,{'zeeman-hilb','zeeman-liouv','sphten-liouv'}) error('unrecognized formalism - see the basis preparation section of the manual.'); end % Check zeeman-hilb formalism options if strcmp(bas.formalism,'zeeman-hilb') % Check bas.approximation if ~isfield(bas,'approximation') error('approximation level must be specified in bas.approximation for zeeman-hilb formalism.'); elseif ~ischar(bas.approximation) error('bas.approximation must be a string.'); elseif ~ismember(bas.approximation,{'none'}) error('bas.approximation should be set to ''none'' in zeeman-hilb formalism.'); end end % Check zeeman-liouv formalism options if strcmp(bas.formalism,'zeeman-liouv') % Check bas.approximation if ~isfield(bas,'approximation') error('approximation level must be specified in bas.approximation for zeeman-liouv formalism.'); elseif ~ischar(bas.approximation) error('bas.approximation must be a string.'); elseif ~ismember(bas.approximation,{'none'}) error('bas.approximation should be set to ''none'' in zeeman-liouv formalism.'); end end % Check sphten-liouv formalism options if strcmp(bas.formalism,'sphten-liouv') % Check bas.approximation if ~isfield(bas,'approximation') error('approximation level must be specified in bas.approximation for sphten-liouv formalism.'); elseif ~ischar(bas.approximation) error('bas.approximation must be a string.'); elseif ~ismember(bas.approximation,{'IK-0','IK-1','IK-2','ESR-1','ESR-2','none'}) error('unrecognized approximation - see the basis preparation section of the manual.'); end % Check bas.connectivity if ismember(bas.approximation,{'IK-1','IK-2'}) if ~isfield(bas,'connectivity') error('connectivity type must be specified in bas.connectivity variable.'); elseif ~ischar(bas.connectivity) error('bas.connectivity must be a string.'); elseif ~ismember(bas.connectivity,{'scalar_couplings','full_tensors'}) error('unknown connectivity type - see the basis preparation section of the manual.'); end end % Check bas.level if ismember(bas.approximation,{'IK-0','IK-1'})&&(~isfield(bas,'level')) error('connectivity tracing depth must be specified in bas.level variable.'); end if isfield(bas,'level') if (~isnumeric(bas.level))||(~isscalar(bas.level))||(mod(bas.level,1)~=0)||(bas.level<1) error('bas.level must be a positive integer.'); end end % Check bas.space_level if ismember(bas.approximation,{'IK-1','IK-2'})&&(~isfield(bas,'space_level')) error('proximity tracing depth must be specified in bas.space_level variable.'); end if isfield(bas,'space_level') if (~isnumeric(bas.space_level))||(~isscalar(bas.space_level))||(mod(bas.space_level,1)~=0)||(bas.space_level<1) error('bas.space_level must be a positive integer.'); end end % Check bas.manual if isfield(bas,'manual') if (~islogical(bas.manual))&&(~isnumeric(bas.manual)) error('bas.manual must be a logical matrix.'); elseif size(bas.manual,2)~=spin_system.comp.nspins error('the number of rows in bas.manual must be equal to the number of spins in the system.') end end % Check bas.projections if isfield(bas,'projections') if (~isnumeric(bas.projections))||(~isrow(bas.projections))||any(mod(bas.projections,1)~=0) error('bas.projections must be a row vector of integers.'); end end % Check bas.longitudinals if isfield(bas,'longitudinals') if (~iscell(bas.longitudinals))||any(~cellfun(@ischar,bas.longitudinals)) error('bas.longitudinals must be a cell array of strings.'); end if any(~ismember(bas.longitudinals,spin_system.comp.isotopes)) error('bas.longitudinals refers to spins that are not present in the system.'); end end end % Disallow approximation options with exact formalism if ~ismember(bas.approximation,{'IK-0','IK-1','IK-2'}) if isfield(bas,'level')||isfield(bas,'space_level') error('bas.level and bas.space_level are only applicable to IK-0,1,2 basis sets.'); end end % Enforce sphten-liouv with projection selection if isfield(bas,'projections')&&(~strcmp(bas.formalism,'sphten-liouv')) error('bas.projections option is only available for sphten-liouv formalism.'); end % Enforce sphten-liouv with chemical exchange if (~isscalar(spin_system.chem.rates))&&(~strcmp(bas.formalism,'sphten-liouv')) error('chemical reaction modelling is only available for sphten-liouv formalism.'); end end % In 1969, Robert Rathbun Wilson, the US physicist who headed Fermilab, the world's % highest-energy particle accelerator laboratory, addressed the Congressional Joint % Committee on Atomic Energy. Rhode Island Senator John Pastore asked Wilson to spell % out what research into high-energy particle physics would do to improve the defence % of the United States. Wilson gave a reply that went down in scientific history. Fer- % milab, he said, had "nothing to do directly with defending our country, except to % make it worth defending". % % http://www.theregister.co.uk/2009/02/09/woudhuysen_energise_1/
github
tsajed/nmr-pred-master
spinlock.m
.m
nmr-pred-master/spinach/kernel/spinlock.m
1,521
utf_8
e73d0f4759754be56c7a5fc9c1bd979a
% Analytical approximation to a spin locking process. This function oblite- % rates all spin-spin correlations and all magnetization components other % than those along the indicated direction. Parameters: % % Lx - X magnetization operator on the spins that % should be locked % % Ly - Y magnetization operator on the spins that % should be locked % % rho - state vector or a bookshelf stack thereof % % direction - direction in which the spins should be lo- % cked, 'X' or 'Y'. % % The function destroys all magnetization except in the direction indicated, % but does not prevent its subsequent evolution. % % [email protected] function rho=spinlock(spin_system,Lx,Ly,rho,direction) switch direction case 'X' % Destroy everything except for X magnetization rho=step(spin_system,Ly,rho,pi/2); rho=homospoil(spin_system,rho,'destroy'); rho=step(spin_system,Ly,rho,-pi/2); case 'Y' % Destroy everything except for Y magnetization rho=step(spin_system,Lx,rho,pi/2); rho=homospoil(spin_system,rho,'destroy'); rho=step(spin_system,Lx,rho,-pi/2); otherwise % Complain and bomb out error('unrecognized spin locking direction.'); end end % To every dog - his bone and cage, % To every wolf - his teeth and rage. % % Victor Tsoy
github
tsajed/nmr-pred-master
lindbladian.m
.m
nmr-pred-master/spinach/kernel/lindbladian.m
1,460
utf_8
dca11201c0d29cbfc36031996ac2f53d
% Generates a Lindblad superoperator from user-specified left-side and % right-side product superoperators and calibrates it using the experi- % mental relaxation rate of a user-specified state. Syntax: % % R=lindbladian(A_left,A_right,rho,rlx_rate) % % where A_left is the left side product superoperator of the interacti- % on that is being modulated, A_right is the right side product super- % operator of the same interaction, rho is the state vector whose rela- % xation rate is known from the experiment and rlx_rate is that rate. % % [email protected] function R=lindbladian(A_left,A_right,rho,rlx_rate) % Check consistency grumble(A_left,A_right,rho,rlx_rate); % Generate a Lindbladian R=A_left*A_right'-(A_left'*A_left+A_right*A_right')/2; % Calibrate the Lindbladian rho=rho/norm(rho,2); R=-rlx_rate*R/(rho'*R*rho); end % Consistency enforcement function grumble(A_left,A_right,rho,rlx_rate) if (~isnumeric(A_left))||(~isnumeric(A_right))||... (~isnumeric(rho))||(~isnumeric(rlx_rate)) error('all inputs must be numeric.'); end if (~isnumeric(rlx_rate))||(~isscalar(rlx_rate))||... (~isreal(rlx_rate))||(nsteps<0) error('rlx_rate must be a non-negative real number.'); end end % Morality, it could be argued, represents the way that people % would like the world to work, wheareas economics represents % how it actually does work. % % Steven D. Levitt, "Freakonomics"
github
tsajed/nmr-pred-master
propagator.m
.m
nmr-pred-master/spinach/kernel/propagator.m
7,103
utf_8
228cd2cfd371fa8680d2b3d433160043
% Calculates exponential propagators. Syntax: % % P=propagator(spin_system,L,timestep) % % returns exp(-i*L*t). The following calculation methods are % supported: % % 'cpu' - Taylor series with scaling and squaring % on CPU, spmd parallel if possible % % 'gpu' - Taylor series with scaling and squaring % on GPU % % The propagator calculation method is chosen by setting the % sys.enable parameter during the call to create.m function. % % Notes: we did have Chebyshev and Newton series here at one % point, as well as the Pade method. None of them has % lived up to their marketing. % % [email protected] function P=propagator(spin_system,L,timestep) % Check consistency grumble(L,timestep); % Inform the user about matrix densities report(spin_system,['Liouvillian dimension ' num2str(size(L,1)) ', nnz ' num2str(nnz(L)) ... ', density ' num2str(100*nnz(L)/numel(L)) '%, sparsity ' num2str(issparse(L))]); % Set a shorthand for -i*L*dt A=-1i*L*timestep; % Fast bypass for small matrices if size(A,1)<spin_system.tols.small_matrix P=expm(full(A)); return; end % Check the cache if ismember('caching',spin_system.sys.enable)&&(size(A,1)>500) % Generate the cache record name filename=[spin_system.sys.scratch '/p_' md5_hash(A) '.mat']; % Try loading the cache record if exist(filename,'file') report(spin_system,'cache record found and used.'); load(filename,'P'); report(spin_system,['propagator dimension ' num2str(size(P,1)) ', nnz ' num2str(nnz(P))... ', density ' num2str(100*nnz(P)/numel(P)) '%, sparsity ' num2str(issparse(P))]); %#ok<NODEF> return; else report(spin_system,'cache record not found, computing from scratch...'); end end % Get the norm mat_norm=norm(A,1); % Warn the user if the norm is too big if mat_norm>1024 % If the user is really pushing it, take precautionary measures report(spin_system,'WARNING - the time step requested greatly exceeds the timescale of system dynamics.'); report(spin_system,'WARNING - exponentiation tolerance will be set to 1e-14.'); spin_system.tols.prop_chop=1e-14; elseif mat_norm>16 % Inform the user just in case report(spin_system,'WARNING - the time step requested exceeds the timescale of system dynamics.'); end % Determine scaling and squaring parameters n_squarings=max([0 ceil(log2(mat_norm))]); scaling_factor=2^n_squarings; report(spin_system,['scaling by ' num2str(scaling_factor) ' and squaring ' num2str(n_squarings) ' times.']); % Scale and clean up the matrix if scaling_factor>1, A=A/scaling_factor; end A=clean_up(spin_system,A,spin_system.tols.prop_chop); % Get the propagator if ismember('gpu',spin_system.sys.enable)&&(size(A,1)>500) % Run Taylor series procedure on the GPU A=gpuArray(A); P=speye(size(A)); next_term=gpuArray.speye(size(A)); n=1; while nnz(next_term)>0 % Compute the next term if issparse(A) next_term=(1/n)*A*next_term; else next_term=(1/n)*next_term*A; end % Eliminate small elements next_term=clean_up(spin_system,next_term,spin_system.tols.prop_chop); % Add to the total and increment the counter P=P+gather(next_term); n=n+1; end % Inform the user report(spin_system,['Taylor series converged on GPU in ' num2str(n) ' iterations.']); else % Run Taylor series procedure on the CPU P=speye(size(A)); next_term=P; n=1; while nnz(next_term)>0 % Compute the next term if issparse(A) next_term=(1/n)*A*next_term; else next_term=(1/n)*next_term*A; end % Eliminate small elements next_term=clean_up(spin_system,next_term,spin_system.tols.prop_chop); % Add to the total and increment the counter P=P+next_term; n=n+1; end % Inform the user report(spin_system,['Taylor series converged on CPU in ' num2str(n) ' iterations.']); end % Reclaim memory clear('A','next_term'); % Clean up the result P=clean_up(spin_system,P,spin_system.tols.prop_chop); % Run the squaring stage if n_squarings>0 % Run the appropriate squaring process if ismember('gpu',spin_system.sys.enable)&&(size(P,1)>500) % Move the array to GPU P=gpuArray(P); % Run the squaring on the GPU for n=1:n_squarings % Inform the user report(spin_system,['GPU squaring step ' num2str(n) '...']); % Square the propagator P=clean_up(spin_system,P*P,spin_system.tols.prop_chop); end elseif (~isworkernode)&&(nnz(P)>1e6)&&issparse(P) % Run codistributed CPU squaring spmd % Codistribute the propagator P=codistributed(P,codistributor2dbc()); % Run the squaring stage for n=1:n_squarings % Inform the user report(spin_system,['codistributed CPU squaring step ' num2str(n) '...']); % Square the propagator P=clean_up(spin_system,P*P,spin_system.tols.prop_chop); end end else % Run serial CPU squaring for n=1:n_squarings % Inform the user report(spin_system,['CPU squaring step ' num2str(n) '...']); % Square the propagator P=clean_up(spin_system,P*P,spin_system.tols.prop_chop); end end end % Gather the propagator P=gather(P); % Inform the user report(spin_system,['propagator dimension ' num2str(size(P,1)) ', nnz ' num2str(nnz(P))... ', density ' num2str(100*nnz(P)/numel(P)) '%, sparsity ' num2str(issparse(P))]); % Write the cache record if ismember('caching',spin_system.sys.enable)&&any(size(P)>500) % Save the propagator save(filename,'P'); report(spin_system,'cache record saved.'); end end % Consistency enforcement function grumble(L,timestep) if (~isnumeric(L))||(~isnumeric(timestep)) error('both L and timestep must be numeric.'); end if size(L,1)~=size(L,2) error('L argument must be a square matrix.'); end if ~isscalar(timestep) error('timestep must be a scalar.'); end end % To preserve one's mind intact through a modern college education is a % test of courage and endurance, but the battle is worth it and the sta- % kes are the highest possible to man: the survival of reason. % % Ayn Rand
github
tsajed/nmr-pred-master
kinetics.m
.m
nmr-pred-master/spinach/kernel/kinetics.m
9,090
utf_8
ab73d88d3360660aa7174960706cdba9
% Chemical kinetics superoperator. All adjustable parameters are specified % in the call to create.m function -- see the Input Preparation section of % Spinach manual. % % [email protected] % [email protected] % [email protected] function K=kinetics(spin_system) % Preallocate the answer K=0*unit_oper(spin_system); % Find chemical reactions [sources,destins,rates]=find(spin_system.chem.rates); % Loop over chemical reactions for n=1:numel(rates) % Refuse to process inappropriate cases if ~strcmp(spin_system.bas.formalism,'sphten-liouv') error('chemical reaction treatment is only available for sphten-liouv formalism.'); end % Get the spins involved source_spins=spin_system.chem.parts{sources(n)}; destin_spins=spin_system.chem.parts{destins(n)}; % Get the states involved source_states=logical(sum(spin_system.bas.basis(:,source_spins),2)); destin_states=logical(sum(spin_system.bas.basis(:,destin_spins),2)); % Make sure basis tables match if ~isequal(spin_system.bas.basis(source_states,source_spins),... spin_system.bas.basis(destin_states,destin_spins)) error('spin systems on either side of the reaction arrow have different topologies or basis sets.'); end % Move to integer indexing source_states=find(source_states); destin_states=find(destin_states); % Update the kinetics superoperator K=K+rates(n)*sparse(source_states,destin_states,ones(size(source_states)),size(K,1),size(K,2)); end % Find magnetization fluxes [source_spins,destin_spins,flux_rate]=find(spin_system.chem.flux_rate); % Process magnetization fluxes if ~isempty(flux_rate) % Refuse to process inappropriate cases if ~strcmp(spin_system.bas.formalism,'sphten-liouv') error('magnetization flux treatment is only available for sphten-liouv formalism.'); end % Index single- and multi-spin orders (sso and mso) sso_state_mask=(sum(logical(spin_system.bas.basis),2)==1); mso_state_mask=(sum(logical(spin_system.bas.basis),2)>1 ); % Decide how to proceed switch spin_system.chem.flux_type case 'intramolecular' report(spin_system,'intramolecular magnetization flux, correlations will be kept.'); case 'intermolecular' report(spin_system,'intermolecular magnetization flux, correlations will be damped.'); otherwise error('unrecognized magnetization flux type.') end % Loop over the fluxes for n=1:numel(flux_rate) % Find single-spin sources and destinations sso_source_state_mask=sso_state_mask&(spin_system.bas.basis(:,source_spins(n))~=0); sso_destin_state_mask=sso_state_mask&(spin_system.bas.basis(:,destin_spins(n))~=0); % Identify stationary states sso_static_state_mask=sso_source_state_mask&sso_destin_state_mask; sso_source_state_mask=xor(sso_source_state_mask,sso_static_state_mask); sso_destin_state_mask=xor(sso_destin_state_mask,sso_static_state_mask); % Make sure subspaces match if ~isequal(spin_system.bas.basis(sso_source_state_mask,source_spins),... spin_system.bas.basis(sso_destin_state_mask,destin_spins)) error('spin systems on either side of the reaction arrow have different topology or basis sets.'); end % Move to integer indexing sso_source_state_index=find(sso_source_state_mask); sso_destin_state_index=find(sso_destin_state_mask); % Update the kinetics superoperator K=K+flux_rate(n)*sparse(sso_destin_state_index,sso_source_state_index,ones(size(sso_source_state_index)),size(K,1),size(K,2)); K=K-flux_rate(n)*sparse(sso_source_state_index,sso_source_state_index,ones(size(sso_source_state_index)),size(K,1),size(K,2)); % Decide the fate of multi-spin orders switch spin_system.chem.flux_type case 'intramolecular' % Find multi-spin sources and destinations mso_source_state_mask=mso_state_mask&(spin_system.bas.basis(:,source_spins(n))~=0); mso_destin_state_mask=mso_state_mask&(spin_system.bas.basis(:,destin_spins(n))~=0); % Identify stationary states mso_static_state_mask=mso_source_state_mask&mso_destin_state_mask; mso_source_state_mask=xor(mso_source_state_mask,mso_static_state_mask); mso_destin_state_mask=xor(mso_destin_state_mask,mso_static_state_mask); % Make sure subspaces match if ~isequal(spin_system.bas.basis(mso_source_state_mask,source_spins),... spin_system.bas.basis(mso_destin_state_mask,destin_spins)) error('spin systems on either side of the reaction arrow have different topology or basis sets.'); end % Move to integer indexing mso_source_state_index=find(mso_source_state_mask); mso_destin_state_index=find(mso_destin_state_mask); % Update the kinetics superoperator K=K+flux_rate(n)*sparse(mso_destin_state_index,mso_source_state_index,ones(size(mso_source_state_index)),size(K,1),size(K,2)); K=K-flux_rate(n)*sparse(mso_source_state_index,mso_source_state_index,ones(size(mso_source_state_index)),size(K,1),size(K,2)); case 'intermolecular' % Find multi-spin sources mso_source_state_mask=mso_state_mask&(spin_system.bas.basis(:,source_spins(n))~=0); % Generate indices mso_source_state_index=find(mso_source_state_mask); % Update the kinetics superoperator K=K-flux_rate(n)*sparse(mso_source_state_index,mso_source_state_index,ones(size(mso_source_state_index)),size(K,1),size(K,2)); otherwise % Complain and bomb out error('unrecognized type of magnetization flux.'); end end end % Process radical pair recombination if (~isempty(spin_system.chem.rp_theory))&&... (~strcmp(spin_system.chem.rp_theory,'off')) % Refuse to process inappropriate cases if ~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'}) error('radical pair kinetics treatment is only available in Liouville space'); else report(spin_system,['generating kinetics superoperator using the ' spin_system.chem.rp_theory ' model...']); end % Get the singlet and triplet projector product superoperators unit=unit_oper(spin_system); LzSz_l=operator(spin_system,{'Lz','Lz'},num2cell(spin_system.chem.rp_electrons),'left'); LzSz_r=operator(spin_system,{'Lz','Lz'},num2cell(spin_system.chem.rp_electrons),'right'); LpSm_l=operator(spin_system,{'L+','L-'},num2cell(spin_system.chem.rp_electrons),'left'); LpSm_r=operator(spin_system,{'L+','L-'},num2cell(spin_system.chem.rp_electrons),'right'); LmSp_l=operator(spin_system,{'L-','L+'},num2cell(spin_system.chem.rp_electrons),'left'); LmSp_r=operator(spin_system,{'L-','L+'},num2cell(spin_system.chem.rp_electrons),'right'); singlet_l=unit/4-(LzSz_l+0.5*(LpSm_l+LmSp_l)); triplet_l=unit-singlet_l; singlet_r=unit/4-(LzSz_r+0.5*(LpSm_r+LmSp_r)); triplet_r=unit-singlet_r; % Assemble the recombination kinetics superoperator switch spin_system.chem.rp_theory case 'exponential' K=K-sum(spin_system.chem.rp_rates)*speye(size(K)); case 'haberkorn' K=K-0.5*(spin_system.chem.rp_rates(1)*(singlet_l+singlet_r)+spin_system.chem.rp_rates(2)*(triplet_l+triplet_r)); case 'jones-hore' K=K-sum(spin_system.chem.rp_rates)*unit+spin_system.chem.rp_rates(1)*triplet_l*triplet_r+spin_system.chem.rp_rates(2)*singlet_l*singlet_r; otherwise error('unknown radical pair kinetics model.'); end end end % The egoist is the absolute sense is not the man who sacrifices others. He % is the man who stands above the need of using others in any manner. He do- % es not function through them. He is not concerned with them in any primary % matter. Not in his aim, not in his motive, not in his thinking, not in his % desires, not in the source of his energy. He does not exist for any other % man - and he asks no other man to exist for him. This is the only form of % brotherhood and mutual respect possible between men. % % Ayn Rand, "The Fountainhead"
github
tsajed/nmr-pred-master
operator.m
.m
nmr-pred-master/spinach/kernel/operator.m
3,563
utf_8
232e3910e3f858f1c9cd5d85ce3e8b6d
% Hilbert space operators and Liouville space superoperators. % % <http://spindynamics.org/wiki/index.php?title=Operator.m> function A=operator(spin_system,operators,spins,operator_type) % Validate the input grumble(spin_system,operators,spins); % The default type is commutation superoperator if ~exist('operator_type','var'), operator_type='comm'; end % Parse the specification [opspecs,coeffs]=human2opspec(spin_system,operators,spins); % Decide how to proceed switch spin_system.bas.formalism case 'sphten-liouv' % Get the Liouville space superoperator local_answers=cell(numel(opspecs),1); parfor n=1:numel(opspecs) local_answers{n}=coeffs(n)*p_superop(spin_system,opspecs{n},operator_type); end A=spalloc(size(local_answers{1}(1),1),... size(local_answers{1}(2),2),... sum(cellfun(@nnz,local_answers))); for n=1:numel(opspecs) A=A+local_answers{n}; end case 'zeeman-hilb' % Get the Hilbert space operator local_answers=cell(numel(opspecs),1); parfor n=1:numel(opspecs) B=sparse(coeffs(n)); for k=1:numel(opspecs{n}) [L,M]=lin2lm(opspecs{n}(k)); ist=irr_sph_ten(spin_system.comp.mults(k),L); %#ok<PFBNS> B=kron(B,ist{L-M+1}); end local_answers{n}=B; end A=spalloc(size(local_answers{1}(1),1),... size(local_answers{1}(2),2),... sum(cellfun(@nnz,local_answers))); for n=1:numel(opspecs) A=A+local_answers{n}; end case 'zeeman-liouv' % Get the Liouville space superoperator local_answers=cell(numel(opspecs),1); parfor n=1:numel(opspecs) B=sparse(coeffs(n)); for k=1:numel(opspecs{n}) [L,M]=lin2lm(opspecs{n}(k)); ist=irr_sph_ten(spin_system.comp.mults(k),L); %#ok<PFBNS> B=kron(B,ist{L-M+1}); end local_answers{n}=hilb2liouv(B,operator_type); end A=spalloc(size(local_answers{1}(1),1),... size(local_answers{1}(2),2),... sum(cellfun(@nnz,local_answers))); for n=1:numel(opspecs) A=A+local_answers{n}; end otherwise % Complain and bomb out error('unknown operator type.'); end end % Input validation function function grumble(spin_system,operators,spins) if ~isfield(spin_system,'bas') error('basis set information is missing, run basis() before calling this function.'); end if (~(ischar(operators)&&ischar(spins)))&&... (~(iscell(operators)&&iscell(spins)))&&... (~(ischar(operators)&&isnumeric(spins))) error('invalid operator specification.'); end if iscell(operators)&&iscell(spins)&&(numel(operators)~=numel(spins)) error('spins and operators cell arrays should have the same number of elements.'); end if iscell(operators)&&any(~cellfun(@ischar,operators)) error('all elements of the operators cell array should be strings.'); end if iscell(spins)&&any(~cellfun(@isnumeric,spins)) error('all elements of the spins cell array should be integer numbers.'); end end % It is nice to know that the computer understands the problem. But I would % like to understand it too. % % Eugene Wigner
github
tsajed/nmr-pred-master
residual.m
.m
nmr-pred-master/spinach/kernel/residual.m
2,306
utf_8
caf9051ccf62a2197e7a144614af7573
% Sets up interaction tensors under partial ordering in a liquid % crystal with the user-supplied order matrix. All adjustable pa- % rameters are set during the call to create.m function. Syntax: % % spin_system=residual(spin_system) % % Note: this function is only applicable to high-field NMR. % % Note: the function overwrites the interaction tensors supplied % by the user. Relaxation superoperator, if required, must % be computed before this function is called. % % [email protected] % [email protected] function spin_system=residual(spin_system) % Check consistency grumble(spin_system); % Process Zeeman interactions for n=1:spin_system.comp.nspins if significant(spin_system.inter.zeeman.matrix{n},spin_system.tols.inter_cutoff) % Obtain isotropic part iso=eye(3)*trace(spin_system.inter.zeeman.matrix{n})/3; % Calculate residual order extra_zz=trace(spin_system.inter.order_matrix*(spin_system.inter.zeeman.matrix{n}-iso)); % Update Zeeman tensor spin_system.inter.zeeman.matrix{n}=iso+diag([-extra_zz/3 -extra_zz/3 2*extra_zz/3]); end end % Process spin-spin couplings for n=1:spin_system.comp.nspins for k=1:spin_system.comp.nspins if significant(spin_system.inter.coupling.matrix{n,k},spin_system.tols.inter_cutoff) % Obtain isotropic part iso=trace(spin_system.inter.coupling.matrix{n,k})*eye(3)/3; % Calculate residual order extra_zz=trace(spin_system.inter.order_matrix*(spin_system.inter.coupling.matrix{n,k}-iso)); % Update coupling tensor spin_system.inter.coupling.matrix{n,k}=iso+diag([-extra_zz/3 -extra_zz/3 2*extra_zz/3]); end end end % Report back to the user report(spin_system,'all interaction anisotropies have been replaced by their residuals.'); end % Consistency enforcement function grumble(spin_system) if ~isfield(spin_system.inter,'order_matrix') error('order matrix infomation is missing from the spin_system structure.'); end end % If I'd observed all the rules, I'd never have got anywhere. % % Marilyn Monroe
github
tsajed/nmr-pred-master
thermalize.m
.m
nmr-pred-master/spinach/kernel/thermalize.m
1,058
utf_8
0202b4d5a16beaabe415ea39be31f719
% Modifies a symmetric relaxation superoperator to relax the system % towards a user-specified state. Liouville space spherical tensor % formalism only. Syntax: % % R=thermalize(spin_system,R,rho) % % [email protected] function R=thermalize(spin_system,R,rho) if strcmp(spin_system.bas.formalism,'sphten-liouv') % Modify the relaxation superoperator R(1,1)=1; R(:,1)=-R*rho; else % Complain and bomb out error('this function is only available in sphten-liov formalism.'); end end % As for the review experience, remember that story about % Pavlov's dogs? Conditional reflexes and things. There's % a less well known experiment when dogs are punished and % rewarded in a way that's uncorrelated with what they do. % The dogs eventually develop schizophrenia... that's how % that review made me feel. % % (from IK's email to the project team, % after the final review meeting on an % EU grant, in which the outcomes were % praised by Brussels to high heaven)
github
tsajed/nmr-pred-master
trajsimil.m
.m
nmr-pred-master/spinach/kernel/trajsimil.m
5,910
utf_8
a3776b1fcac41800e2d9e696b6d9c9e2
% Computes trajectory similarity scores. Returns a function representing % "similarity" of the two state space trajectories at different points in % time. Trajectory must be supplied as nstates x nsteps matrix. Syntax: % % trajsimil(spin_system,trajectory_1,trajectory_2,method) % % Score functions: % % 'RSP' - running scalar product. Computes scalar products between the % corresponding vectors of the two trajectories. % % 'RDN' - running difference norm. The two trajectories are subtracted % and difference 2-norms returned. % % 'SG-' - prefix that switches on state grouping. T(l,m) and T(l,-m) % states of each spin (standalone or in direct products with % other operators) would be deemed equivalent. % % 'BSG-' - prefix that switches on broad state grouping. All states of % a given spin (standalone or in direct products with other % operators) would be deemed equivalent. % % The state grouping consists in summing the absolute squares of the co- % efficients to be grouped and taking the square root. % % Note: SG and BSG options of this function require the spherical tensor % basis set. % % [email protected] % [email protected] function score=trajsimil(spin_system,trajectory_1,trajectory_2,scorefcn) % Validate the input grumble(spin_system,trajectory_1,trajectory_2,scorefcn); % Run state grouping if strcmp(scorefcn(1:3),'SG-')||strcmp(scorefcn(1:3),'BSG') % Grab the description of the current basis state_list=spin_system.bas.basis; % Tell the user we're started report(spin_system,'collapsing equivalent subspaces...'); % Decide how to proceed if strcmp(scorefcn(1:3),'SG-') % Rename all T(l,-m) states into T(l,m) states [L,M]=lin2lm(state_list); state_list=lm2lin(L,abs(M)); % Update the method variable scorefcn=scorefcn(4:end); elseif strcmp(scorefcn(1:3),'BSG') % Rename all non-identity states into Lz state_list(state_list~=0)=2; % Update the method variable scorefcn=scorefcn(5:end); end % Index all unique and repeated states on the modified state list [grouped_state_list,index_forward,index_backward]=unique(state_list,'rows'); % Preallocate state-grouped trajectories grouped_trajectory_1=zeros(length(index_forward),size(trajectory_1,2)); grouped_trajectory_2=zeros(length(index_forward),size(trajectory_2,2)); % Group trajectory tracks corresponding to the states that are % flagged as identical in the indices (root-sum-square) for n=1:length(index_forward) grouped_trajectory_1(n,:)=sqrt(sum(abs(trajectory_1(index_backward==n,:)).^2,1)); grouped_trajectory_2(n,:)=sqrt(sum(abs(trajectory_2(index_backward==n,:)).^2,1)); end % Update the variables trajectory_1=grouped_trajectory_1; trajectory_2=grouped_trajectory_2; % Tell the user we're done report(spin_system,[num2str(size(state_list,1)) ' states collected into ' num2str(size(grouped_state_list,1)) ' groups.']); end % Preallocate the result array trajectory_length=size(trajectory_1,2); score=zeros(1,trajectory_length); % Compute the score function switch scorefcn case 'RSP' % Compute running scalar product scores for n=1:trajectory_length score(n)=dot(trajectory_1(:,n),trajectory_2(:,n)); end case 'RDN' % Compute running difference norm scores for n=1:trajectory_length score(n)=1-norm(trajectory_1(:,n)-trajectory_2(:,n))/2; end otherwise % Complain and bomb out error('unknown similarity score function.'); end end % Consistency enforcement function grumble(spin_system,trajectory_1,trajectory_2,scorefcn) if ~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'}) error('this function is only available for Liouville space formalisms.'); end if (strcmp(scorefcn(1:3),'SG-')||strcmp(scorefcn(1:3),'BSG'))&&... (~ismember(spin_system.bas.formalism,{'sphten-liouv'})) error('state grouping is only available for sphten-liouv formalism.'); end if any(size(trajectory_1)~=size(trajectory_2)) error('matrix dimensions of the two trajectories should match.'); end if (size(trajectory_1,1)~=size(spin_system.bas.basis,1))||... (size(trajectory_2,1)~=size(spin_system.bas.basis,1)) error('trajectory dimension should be equal to the basis set dimension.'); end if (~isnumeric(trajectory_1))||(~isnumeric(trajectory_2)) error('both trajectories should be arrays of doubles.'); end if ~ismember(scorefcn,{'RSP','RDN','SG-RSP','SG-RDN','BSG-RSP','BSG-RDN'}) error('available score functions are RSP, RDN, SG-RSP, SG-RDN, BSG-RSP, and BSG-RDN.'); end end % How would we look for a new law? In general we look for a new law by the % following process. First, we guess it. Then we... don't laugh. That's the % damned truth. Then we compute the consequences of the guess... to see if % this is right, to see if this law we guessed is right, to see what it % would imply. And then we compare those computation results to nature. Or % we say to compare it to experiment, or to experience. Compare it directly % with observations to see if it works. If it disagrees with experiment, % it's wrong. In that simple statement is the key to science. It doesn't % make a difference how beautiful your guess is. It doesn't make a diffe- % rence how smart you are, who made the guess or what his name is... If it % disagrees with experiment, it's wrong. That's all there is to it. % % Richard Feynman
github
tsajed/nmr-pred-master
correlation.m
.m
nmr-pred-master/spinach/kernel/correlation.m
2,846
utf_8
2e85e82540e5c585bc1fc973376c35fa
% Correlation order selection function -- keeps only the specified orders % of spin correlation in the state vector. Syntax: % % rho=correlation(spin_system,rho,correlation_orders,spins) % % Arguments: % % rho - a state vector or a horizontal stack thereof % % correlation_orders - a row vector of correlation orders to keep % % spins - which spins to count (e.g. '1H', '13C', 'all') % % [email protected] % [email protected] function rho=correlation(spin_system,rho,correlation_orders,spins) % Set the default to all spins if ~exist('spins','var'), spins='all'; end % Check consistency grumble(spin_system,rho,correlation_orders) % Store dimension statistics spn_dim=size(spin_system.bas.basis,1); spc_dim=numel(rho)/spn_dim; problem_dims=size(rho); % Fold indirect dimensions rho=reshape(rho,[spn_dim spc_dim]); % Parse the spin specification if ~isnumeric(spins) if strcmp(spins,'all') spins=1:length(spin_system.comp.isotopes); else spins=find(strcmp(spins,spin_system.comp.isotopes)); end end % Compute the order of correlation for each basis state correlation_orders_present=sum(logical(spin_system.bas.basis(:,spins)),2); % Wipe all correlation orders except those specified by the user state_mask=zeros(size(spin_system.bas.basis,1),1); for n=correlation_orders state_mask=state_mask|(correlation_orders_present==n); end % Apply the mask rho(~state_mask,:)=0; % Unfold indirect dimensions rho=reshape(rho,problem_dims); % Report overly destructive calls if norm(rho,1)<1e-10 report(spin_system,'WARNING - all magnetization appears to have been destroyed by this call.'); end end % Consistency enforcement function grumble(spin_system,rho,correlation_orders) if ~strcmp(spin_system.bas.formalism,'sphten-liouv') error('analytical correlation order selection is only available for sphten-liouv formalism.'); end if ~isnumeric(rho) error('the state vector(s) must be numeric.'); end if (~isnumeric(correlation_orders))||(~isvector(correlation_orders))||... any(correlation_orders<0)||any(mod(correlation_orders,1)~=0) error('correlation_orders parameter must be a vector of non-negative integers.'); end end % The first iteration of the Spin Dynamics course (http://spindynamics.org) % was so difficult that every single student has dropped out by about Lecture % 10. The rest of the course was read to Rusty, Dusty, Scratchy, Patchy and % Scruffy, the five plastic chairs in IK's Durham office - they made for an % excellent (if a bit shy so far as questions were concerned) audience. To % this day, the total number of students who verifiably understood the whole % of that course can be counted on the fingers of one hand.
github
tsajed/nmr-pred-master
stepsize.m
.m
nmr-pred-master/spinach/kernel/stepsize.m
1,987
utf_8
95cd54b97d90c922a925508e0b07cd84
% Optimal step for time propagation under a given Hamiltonian or a given % Liouvillian superoperator. The function uses the 1-norm (which is the % cheapest variety and the safest one in terms of matrix scaling). % % Syntax: [timestep,nsteps]=stepsize(L,interval) % % Parameters: % % L - Liouvillian operator or superoperator inder which the % evolution is taking place. % % interval - the total evolution time, must be specified if the op- % timal number of steps is also wanted in the output. % % Outputs: % % timestep - optimal time step % % nsteps - number of steps covering the interval, if the interval % was specified % % Note: if a zero Liouvillian is supplied, the function would return the % following values: timestep=0, nsteps=1 % % [email protected] function [timestep,nsteps]=stepsize(L,interval) % Catch incorrect calls if (nargin==1)&&(nargout==2) error('time interval is required to compute the number of steps.'); elseif (~isnumeric(L)) error('L must be numeric.'); elseif (nargin==2)&&((~isnumeric(interval))||(~isreal(interval))||(~isscalar(interval))) error('interval muust be a real number.'); end % Estimate the scaling coefficient scaling=max([1 norm(L,1)]); % Adapt to the output style switch nargout case 1 % Get the optimal time step timestep=1/scaling; case 2 % Get the optimal integer number of steps nsteps=ceil(abs(interval)*scaling); % Get the time step timestep=interval/nsteps; end end % Whenever anyone accuses some person of being 'unfeeling' he means that % that person is just. He means that that person has no causeless emotions % and will not grant him a feeling which he does not deserve... justice is % the opposite of charity. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
coherence.m
.m
nmr-pred-master/spinach/kernel/coherence.m
2,569
utf_8
0fee30c7e46dc64919bc2cc9f1691f15
% Coherence selection function. % % <http://spindynamics.org/wiki/index.php?title=Coherence.m> function rho=coherence(spin_system,rho,spec) % Check consistency grumble(spin_system,rho,spec); % Store dimension statistics spn_dim=size(spin_system.bas.basis,1); spc_dim=numel(rho)/spn_dim; problem_dims=size(rho); % Fold indirect dimensions rho=reshape(rho,[spn_dim spc_dim]); % Compute projection quantum numbers of basis states [~,M]=lin2lm(spin_system.bas.basis); % Preallocate state mask array state_mask=false(spn_dim,numel(spec)); % Loop over specifications for n=1:numel(spec) % Parse spin specification if ischar(spec{n}{1}) % Symbolic specification if strcmp(spec{n}{1},'all') spins=1:numel(spin_system.comp.isotopes); else spins=find(strcmp(spec{n}{1},spin_system.comp.isotopes)); end else % Specification by number spins=spec{n}{1}; end % Determine coherence order of each basis state coherence_orders_present=sum(M(:,spins),2); % Wipe all coherence orders except those specified by the user state_mask(:,n)=ismember(coherence_orders_present,spec{n}{2}); end % Intersect state masks state_mask=all(state_mask,2); % Apply the state mask rho(~state_mask,:)=0; % Unfold indirect dimensions rho=reshape(rho,problem_dims); % Report overly destructive calls if norm(rho,1)<1e-10 report(spin_system,'WARNING - all magnetization appears to have been destroyed by this call.'); end end % Consistency enforcement function grumble(spin_system,rho,spec) %#ok<INUSD> if ~strcmp(spin_system.bas.formalism,'sphten-liouv') error('analytical coherence order selection is only available for sphten-liouv formalism.'); end if ~isnumeric(rho) error('the state vector(s) must be numeric.'); end if mod(numel(rho),size(spin_system.bas.basis))~=0 error('the number of elements in rho must be a multiple of the dimension of the spin state space.'); end end % There was a time when men were afraid that somebody would reveal % some secret of theirs that was unknown to their fellows. Nowadays, % they're afraid that somebody will name what everybody knows. Have % you practical people ever thought that that's all it would take % to blast your whole, big, complex structure, with all your laws % and guns -- just somebody naming the exact nature of what it is % you're doing? % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
repulsion.m
.m
nmr-pred-master/spinach/kernel/grids/repulsion.m
3,473
utf_8
538e1a0c3c3f3c705c3cb1270630dafc
% Generates repulsion grids on a unit hypersphere. See the paper by % Bak and Nielsen (http://dx.doi.org/10.1006/jmre.1996.1087) to get % further information on the algorithm involved. Syntax: % % [alphas,betas,gammas,weights]=repulsion(npoints,ndims,niter) % % Parameters: % % npoints - number of points in the resulting spherical grid % % ndims - hypersphere dimension: 2 returns a single-angle % (beta) grid, 3 returns a two-angle grid (alpha, % beta), 4 returns a three-angle (alpha,beta,gam- % ma) spherical grid % % niter - number of repulsion interations (simple clipped % gradient descent at the moment) % % Outputs: % % alphas - alpha Euler angles of the grid, in radians, % zeros for single-angle grids % % betas - beta Euler angles of the grid, in radians % % gammas - gamma Euler angles of the grid, in radians, % zeros for two-angle grids % % weights - point weights of the grid % % Note: uniform weights are assigned at the moment, use the supp- % lied SHREWD function to generate optimal weights. % % [email protected] function [alphas,betas,gammas,weights]=repulsion(npoints,ndims,niter) % Check consistency grumble(npoints,ndims,niter); % Generate guess points R=rand(ndims,npoints)-0.5; % Start the repulsion loop for m=1:niter % Compute the forces F=zeros(size(R)); dots=R'*R; parfor n=1:npoints for k=1:npoints if n~=k distvec=(R(:,k)-R(:,n)); %#ok<PFBNS> distvec=distvec/norm(distvec); F(:,n)=F(:,n)+dots(n,k)*distvec; end end end % Apply the forces R_new=R-F/npoints; % Project points onto unit sphere R_new=R_new./kron(ones(ndims,1),sqrt(sum(R_new.^2,1))); % Report the difference disp(['Iteration ' num2str(m) ', maximum point displacement: ' num2str(max(sqrt(sum((R-R_new).^2,2))))]); % Close the loop R=R_new; end % Get points switch ndims case 2 % In 2D case return polar angles [phi,~]=cart2pol(R(1,:),R(2,:)); betas=phi'; alphas=0*betas; gammas=alphas; case 3 % In 3D case return spherical angles [phi,theta,~]=cart2sph(R(1,:),R(2,:),R(3,:)); betas=theta'+pi/2; alphas=phi'; gammas=0*alphas; case 4 % In 4D case return Euler angles [gammas,betas,alphas]=quat2angle(R','ZYZ'); end % Get weights weights=ones(npoints,1)/npoints; end % Consistency enforcement function grumble(npoints,ndims,niter) if (~isnumeric(npoints))||(~isreal(npoints))||(numel(npoints)~=1)||(npoints<1)||(mod(npoints,1)~=0) error('npoints must be a positive integer.'); end if (~isnumeric(niter))||(~isreal(niter))||(numel(niter)~=1)||(niter<1)||(mod(niter,1)~=0) error('niter must be a positive integer.'); end if (~isnumeric(ndims))||(~isreal(ndims))||(numel(ndims)~=1)||(~ismember(ndims,[2 3 4])) error('ndims must be 2, 3 or 4.'); end end % Let us beware of saying that there are laws in nature. There % are only necessities: there is nobody who commands, nobody % who obeys, nobody who trespasses. % % Friedrich Nietzsche
github
tsajed/nmr-pred-master
shrewd.m
.m
nmr-pred-master/spinach/kernel/grids/shrewd.m
2,339
utf_8
099331e118ef28cc811358b6503178f2
% Computes SHREWD weights for a given two- or three-angle spherical % grid. See the paper by Eden and Levitt for details on now the al- % gorithm works: http://dx.doi.org/10.1006/jmre.1998.1427 Syntax: % % weights=shrewd(alphas,betas,gammas,max_rank,max_error) % % Parameters: % % alphas - alpha Euler angles of the grid, in radians % % betas - beta Euler angles of the grid, in radians % % gammas - gamma Euler angles of the grid,in radians, % set to all-zeros for two-angle grids % % max_rank - maximum spherical rank to take into consi- % deration when minimizing residuals % % max_error - maximum residual absolute error per spheri- % cal function % % The output is a vector of grid weights for each [alpha beta gamma] % point supplied. % % Note: for a given arrangement of angles, this is the most consis- % tent weight selection procedure in the literature. % % [email protected] function weights=shrewd(alphas,betas,gammas,max_rank,max_error) % Decide the grid type if all(gammas==0) % Preallocate spherical harmonic matrix H=zeros(lm2lin(max_rank,-max_rank)+1,numel(alphas)); % Fill spherical harmonic matrix for k=1:numel(alphas) for l=0:max_rank D=wigner(l,alphas(k),betas(k),gammas(k)); for m=l:-1:-l H(lm2lin(l,m)+1,k)=D(l+1,l+m+1); end end end % Get the right hand side vector v=max_error*ones(lm2lin(max_rank,-max_rank)+1,1); v(1)=1-max_error; else % Preallocate Wigner function matrix H=zeros(lmn2lin(max_rank,-max_rank,-max_rank),numel(alphas)); % Fill Wigner function matrix for k=1:numel(alphas) for l=0:max_rank D=wigner(l,alphas(k),betas(k),gammas(k)); for m=l:-1:-l for n=l:-1:-l H(lmn2lin(l,m,n),k)=D(l+m+1,l+n+1); end end end end % Get the right hand side vector v=max_error*ones(lmn2lin(max_rank,-max_rank,-max_rank),1); v(1)=1-max_error; end % Compute the weights weights=real(H\v); weights=weights/sum(weights); end % A good theory explains a lot but postulates little. % % Richard Dawkins
github
tsajed/nmr-pred-master
grid_kron.m
.m
nmr-pred-master/spinach/kernel/grids/grid_kron.m
1,933
utf_8
90a14b2d08b8e62ae823a695b96a3246
% Spherical grid direct product. Tiles one grid using the rotations of % the other. Grids should be supplied using Euler angles in three col- % umns [alphas betas gammas] in radians. Syntax: % % [angles,weights]=grid_kron(angles1,weights1,angles2,weights2) % % Parameters: % % angles1 - angles of the first grid, as [alpha beta gamma], rad % % weights1 - weights of the first grid % % angles2 - angles of the second grid, as [alpha beta gamma], rad % % weights1 - weights of the second grid % % Outputs: % % angles - angles of the product grid, as [alpha beta gamma], rad % % weights - weights of the product grid % % [email protected] function [angles,weights]=grid_kron(angles1,weights1,angles2,weights2) % Convert both grids to quaternions quats1=angle2quat(angles1(:,1),angles1(:,2),angles1(:,3),'ZYZ'); quats2=angle2quat(angles2(:,1),angles2(:,2),angles2(:,3),'ZYZ'); % Build a table of quaternion products quats=[kron(quats1,ones(size(quats2,1),1)) kron(ones(size(quats1,1)),quats2)]; % Multiply up quaternions quats=[quats(:,1).*quats(:,5)-quats(:,2).*quats(:,6)-quats(:,3).*quats(:,7)-quats(:,4).*quats(:,8),... quats(:,1).*quats(:,6)+quats(:,2).*quats(:,5)+quats(:,3).*quats(:,8)-quats(:,4).*quats(:,7),... quats(:,1).*quats(:,7)-quats(:,2).*quats(:,8)+quats(:,3).*quats(:,5)+quats(:,4).*quats(:,6),... quats(:,1).*quats(:,8)+quats(:,2).*quats(:,7)-quats(:,3).*quats(:,6)+quats(:,4).*quats(:,5)]; % Convert quaternions into angles [alphas,betas,gammas]=quat2angle(quats,'ZYZ'); angles=real([alphas betas gammas]); % Tile the weights weights=kron(weights1,weights2); end % Dostoevsky's lack of taste, his monotonous dealings with persons % suffering with pre-Freudian complexes, the way he has of wallow- % ing in the tragic misadventures of human dignity -- all this is % difficult to admire. % % Vladimir Nabokov
github
tsajed/nmr-pred-master
gaussleg.m
.m
nmr-pred-master/spinach/kernel/grids/gaussleg.m
817
utf_8
9a921d02d31d116cc03d0d80493a2c52
% Computes Gauss-Legendre points and weights in [a,b] interval % with accuracy order n. % % [email protected] function [x,w]=gaussleg(a,b,n) % Initial guess for the nodes in [-1 1] x=cos((2*(0:n)'+1)*pi/(2*n+2))+(0.27/(n+1))*sin(pi*linspace(-1,1,n+1)'*n/(n+2)); % Newton-Raphson refinement V=zeros(n+1,n+2); prev_x=0; while max(abs(x-prev_x))>eps V(:,1)=1; V(:,2)=x; for k=2:(n+1) V(:,k+1)=((2*k-1)*x.*V(:,k)-(k-1)*V(:,k-1))/k; end dV=(n+2)*(V(:,n+1)-x.*V(:,n+2))./(1-x.^2); prev_x=x; x=x-V(:,n+2)./dV; end % Compute the weights w=(b-a)./((1-x.^2).*dV.^2)*((n+2)/(n+1))^2; % Map from [-1,1] to [a,b] x=(a*(1-x)+b*(1+x))/2; end % Life is a fountain of delight; but where the rabble also % drinks all wells are poisoned. % % Friedrich Nietzsche
github
tsajed/nmr-pred-master
grid_test.m
.m
nmr-pred-master/spinach/kernel/grids/grid_test.m
2,042
utf_8
f370fb0071661c47b7bcf44d41044696
% Plots grid integration quality as a function of spherical rank. The % quality is defined as the norm of the residual of spherical harmon- % ics or Wigner functions integrated using the grid provided. Syntax: % % grid_profile=grid_test(alphas,betas,gammas,weights,max_rank,sfun) % % Parameters: % % alphas - alpha Euler angles of the grid, in radians, % zeros for single-angle grids % % betas - beta Euler angles of the grid, in radians % % gammas - gamma Euler angles of the grid, in radians, % zeros for two-angle grids % % weights - point weights of the grid % % max_rank - maximum spherical rank to consider % % sfun - spherical function type: for three-angle % grids use 'D_lmn', for two-angle grids use % 'Y_lm', for single-angle grids use 'Y_l0'. % % The output is a vector of residual norms in each spherical rank. % % [email protected] function grid_profile=grid_test(alphas,betas,gammas,weights,max_rank,sfun) % Preallocate the answer grid_profile=zeros(max_rank+1,1); % Loop over spherical ranks for l=0:max_rank % Preallocate Wigner matrix D=zeros(2*l+1); % Loop over grid points parfor n=1:numel(alphas) D=D+weights(n)*wigner(l,alphas(n),betas(n),gammas(n)); end % Update grid profile if strcmp(sfun,'D_lmn') grid_profile(l+1)=norm(D)-krondelta(0,l); elseif strcmp(sfun,'Y_lm') grid_profile(l+1)=norm(D(l+1,:))-krondelta(0,l); elseif strcmp(sfun,'Y_l0') grid_profile(l+1)=norm(D(l+1,l+1))-krondelta(0,l); else error('unknown diagnostics function.'); end % Update the user disp(['Spherical rank ' num2str(l) ', residual ' sfun ' norm: ' num2str(grid_profile(l+1))]); end % Do the plotting plot(0:max_rank,abs(grid_profile)); xlabel('spherical rank'); ylabel('integration residual'); end % Art is what you can get away with. % % Andy Warhol
github
tsajed/nmr-pred-master
fpl2rho.m
.m
nmr-pred-master/spinach/kernel/utilities/fpl2rho.m
626
utf_8
acb785abd725b06f1f125556bd9f68c9
% Integrates over the spatial degrees of freedom and returns the % average spin state vector across the sample. Syntax: % % rho=fpl2rho(rho,dims) % % Parameters: % % rho - Fokker-Planck state vector % % dims - spatial dimensions of the % Fokker-Planck problem % % [email protected] function rho=fpl2rho(rho,dims) % Expose the spin dimension rho=reshape(rho,[numel(rho)/prod_dims prod(dims)]); % Sum over the spatial coordinates rho=sum(rho,2)/prod(dims); end % I would like to die on Mars, just not on impact. % % Elon Musk
github
tsajed/nmr-pred-master
binpack.m
.m
nmr-pred-master/spinach/kernel/utilities/binpack.m
870
utf_8
f10cfd77f138e0e0b946e6bb85b6f4c6
% A simple 1D bin packing algorithm. % % [email protected] function bins=binpack(box_sizes,bin_size) % Number the boxes box_index=(1:numel(box_sizes))'; % Find boxes that are bigger than bins big_boxes=(box_sizes>bin_size); bins=num2cell(box_index(big_boxes)); box_sizes(big_boxes)=[]; box_index(big_boxes)=[]; % Pack the rest of the boxes while numel(box_index)>0 % Get enough boxes to fill the bin current_boxes=(cumsum(box_sizes)<bin_size); % Stuff them into the bin bins{end+1}=box_index(current_boxes); %#ok<AGROW> box_sizes(current_boxes)=[]; box_index(current_boxes)=[]; end end % "Ford!" he said, "there's an infinite number of monkeys % outside who want to talk to us about this script for % Hamlet they've worked out." % % Douglas Adams, "The Hitchhiker's Guide to the Galaxy"
github
tsajed/nmr-pred-master
irr_sph_ten.m
.m
nmr-pred-master/spinach/kernel/utilities/irr_sph_ten.m
2,950
utf_8
edc07d4ae6e4da2dde5ff2487b9ebb14
% Returns a cell array of single-spin irreducible spherical tensor opera- % tors T(k,m). A two-argument call % % T=irr_sph_ten(mult,k) % % where 'mult' is the multiplicity of the spin in question and 'k' is the % irreducible spherical tensor rank required, returns a cell array of ten- % sors of that rank in the order of decreasing projection. A single argu- % ment call % T=irr_sph_ten(mult) % % produces tensors of all ranks and concatenates them into a cell array in % the order of ascending rank. % % The resulting spherical tensors are normalized in such a way as to obey % the following commutation relation: % % [Lz,T_lm]=m*T_lm % % Note: operator normalization in spin dynamics is an old and thorny ques- % tion. Many different conventions exist, but the only way to make the re- % sulting formalism independent of the total spin quantum number is to im- % pose identical commutation relations rather than equal matrix norms. % % [email protected] % [email protected] function T=irr_sph_ten(mult,k) % Adapt to the input style switch nargin case 1 % Generate tensors of all ranks and put them into a cell array if isnumeric(mult)&&(numel(mult)==1)&&(mult>0)&&(mod(mult,1)==0) T=cell(mult^2,1); for n=0:(mult-1) T((n^2+1):((n+1)^2))=irr_sph_ten(mult,n); end else error('mult must be a non-negative integer.'); end case 2 % Generate spherical tensor operators of the specified rank if isnumeric(mult)&&(numel(mult)==1)&&(mod(mult,1)==0)&&... isnumeric(k)&&(numel(k)==1)&&(k>0)&&(k<mult)&&(mod(k,1)==0) % Get Pauli matrices L=pauli(mult); % Preallocate the cell array T=cell(2*k+1,1); % Get the top state T{1}=((-1)^k)*(2^(-k/2))*L.p^k; % Apply sequential lowering using Racah's commutation rule for n=2:(2*k+1) q=k-n+2; T{n}=(1/sqrt((k+q)*(k-q+1)))*(L.m*T{n-1}-T{n-1}*L.m); end elseif isnumeric(mult)&&(numel(mult)==1)&&(mod(mult,1)==0)&&... isnumeric(k)&&(numel(k)==1)&&(k==0) % For zero rank, return a unit matrix T={speye(mult)}; else % For non-physical ranks, complain and bomb out error('mult must be a non-negative integer and k must be an integer from [0, mult-1] interval.'); end end end % I swear by my life and my love of it that I will never live for the sake % of another man, nor ask another man to live for mine. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
human2opspec.m
.m
nmr-pred-master/spinach/kernel/utilities/human2opspec.m
5,635
utf_8
e938a5147583cb1af886ab53f438f170
% Converts user-friendly descriptions of spin states and operators into the % formal description (opspec) used by Spinach kernel. The function supports % two types of calls: % % 1. If both inputs are strings, e.g. % % [opspecs,coeffs]=human2opspec(spin_system,'Lz','13C') % % the function returns a list of single-spin opspecs for all spins with the % specified name. In the example above, the list of Lz operator specificati- % ons for all 13C nuclei in the system would be returned. % % Valid labels for operators in this type of call are 'E', 'Lz', 'L+', 'L-' % and 'Tl,m'. In the latter case, l and m are integers. Valid labels for the % spins are standard isotope names as well as 'electrons', 'nuclei', 'all'. % % 2. If the two inputs are a cell array of strings and a cell array of num- % bers respectively, a product operator specification is produced, e.g. % % [opspecs,coeffs]=human2opspec(spin_system,{'Lz','L+'},{1,2}) % % would return the LzL+ operator specification with Lz on spin 1 and L+ on % spin 2. Valid labels for operators in the cell array are 'E', 'Lz', 'L+', % 'L-' and 'Tl,m'. In the latter case, l and m are integers. % % [email protected] % [email protected] function [opspecs,coeffs]=human2opspec(spin_system,operators,spins) % Check input validity grumble(operators,spins); % 'Lz','1H' type call returns a sum if ischar(operators)&&ischar(spins) % Parse the specification switch spins case 'all' % Use all spins in the system spin_numbers=1:spin_system.comp.nspins; case 'electrons' % Count electrons spin_numbers=find(cellfun(@(x)strncmp(x,'E',1),spin_system.comp.isotopes)); case 'nuclei' % Count non-electrons spin_numbers=find(~cellfun(@(x)strncmp(x,'E',1),spin_system.comp.isotopes)); otherwise % Count specific spins spin_numbers=find(strcmp(spin_system.comp.isotopes,spins)); end % Bomb out if the list of spins is empty if numel(spin_numbers)==0, error('no such spins in the system.'); end % Preallocate descriptors coeffs=zeros(numel(spin_numbers),1); opspecs=cell(numel(spin_numbers),1); % Use recursive calls for n=1:numel(spin_numbers) [opspecs(n),coeffs(n)]=human2opspec(spin_system,{operators},{spin_numbers(n)}); end % Return the outcome return % 'Lz',[1 2 4] type call returns a sum elseif ischar(operators)&&isnumeric(spins) % Preallocate descriptors coeffs=zeros(numel(spins),1); opspecs=cell(numel(spins),1); % Use recursive calls for n=1:numel(spins) [opspecs(n),coeffs(n)]=human2opspec(spin_system,{operators},{spins(n)}); end % Return the outcome return % {'Lz','L+'},{1,4} type call returns an operator elseif iscell(operators)&&iscell(spins) % Start with an empty opspec and a unit coefficient opspecs={zeros(1,spin_system.comp.nspins)}; coeffs=1; % Parse operator selection for n=1:numel(operators) switch operators{n} case 'E' % Unit operator opspecs{1}(spins{n})=0; coeffs=1*coeffs; case 'L+' % Raising operator opspecs{1}(spins{n})=1; coeffs=-sqrt(2)*coeffs; case 'Lz' % Z projection operator opspecs{1}(spins{n})=2; coeffs=1*coeffs; case 'L-' % Lowering operator opspecs{1}(spins{n})=3; coeffs=sqrt(2)*coeffs; otherwise % Validate the irreducible spherical tensor input if isempty(regexp(operators{n},'^T([\+\-]?\d+),([\+\-]?\d+)$','once')) error('unrecognized operator specification.'); end % Extract the quantum numbers indices=textscan(operators{n},'T%n,%n'); l=indices{1}; m=indices{2}; % Validate the quantum numbers if (l<0)||(abs(m)>l) error('invalid indices in irreducible spherical tensors.'); end % Write the specification opspecs{1}(spins{n})=lm2lin(l,m); coeffs=1*coeffs; end end else % Complain and bomb out error('invalid operator or state specification.'); end end % Input validation function grumble(operators,spins) if (~(ischar(operators)&&ischar(spins)))&&... (~(iscell(operators)&&iscell(spins)))&&... (~(ischar(operators)&&isnumeric(spins))) error('invalid operator or state specification.'); end if iscell(operators)&&(~all(cellfun(@ischar,operators))) error('if operators is a cell array, all elements must be strings.'); end if iscell(spins)&&(~all(cellfun(@isnumeric,spins))) error('if spins is a cell array, all elements must be numbers.'); end end % A "moral commandment" is a contradiction in terms. The moral is the % chosen, not the forced; the understood, not the obeyed. The moral is % the rational, and reason accepts no commandments. % % Ayn Rand
github
tsajed/nmr-pred-master
sphten2zeeman.m
.m
nmr-pred-master/spinach/kernel/utilities/sphten2zeeman.m
1,071
utf_8
4c8a7a1a8a92a3e13a0be77956ee37bf
% Returns a matrix that converts state vectors written in the % spherical tensor basis set used by Spinach into state vectors % written in the Zeeman basis set in Liouville space. % % Note: the matrix need not be square and may be huge. % % [email protected] function P=sphten2zeeman(spin_system) % Preallocate the answer P=spalloc(prod(spin_system.comp.mults.^2),size(spin_system.bas.basis,1),0); % Loop over the basis set for n=1:size(spin_system.bas.basis,1) % Get the state going rho=sparse(1); % Loop over the elements for k=1:size(spin_system.bas.basis,2) % Get the spherical tensors for the current spin ists=irr_sph_ten(spin_system.comp.mults(k)); % Multiply into the state rho=kron(rho,ists{spin_system.bas.basis(n,k)+1}); end % Stretch and write down P(:,n)=rho(:)/norm(rho(:),2); %#ok<SPRIX> end end % Nurture your minds with great thoughts. To believe % in the heroic makes heroes. % % Benjamin Disraeli
github
tsajed/nmr-pred-master
axrh2mat.m
.m
nmr-pred-master/spinach/kernel/utilities/axrh2mat.m
1,601
utf_8
b3d6cd0ee8ee8d3fdebe01b359d1fb5c
% Converts axiality and rhombicity representation of the anisotro- % pic part of a 3x3 interaction tensor into the corresponding mat- % rix. Euler angles should be specified in radians. Syntax: % % M=axrh2mat(iso,ax,rh,alp,bet,gam) % % Parameters: % % iso - isotropic part of the interaction % % ax - interaction axiality, defined as zz-(xx+yy)/2 % in terms of eigenvalues % % rh - interaction rhombicity, defined as (xx-yy) in % terms of eigenvalues % % alp - alpha Euler angle in radians % % bet - beta Euler angle in radians % % gam - gamma Euler angle in radians % % [email protected] function M=axrh2mat(iso,ax,rh,alp,bet,gam) % Check consistency grumble(iso,ax,rh,alp,bet,gam); % Compute eigenvalues xx=(2*iso-2*ax+3*rh)/6; yy=(2*iso-2*ax-3*rh)/6; zz=(1*iso+2*ax)/3; % Rotate the matrix R=euler2dcm(alp,bet,gam); M=R*diag([xx yy zz])*R'; end % Consistency enforcement function grumble(iso,ax,rh,alp,bet,gam) if (~isnumeric(iso))||(~isreal(iso))||(~isscalar(iso))||... (~isnumeric(ax))||(~isreal(ax))||(~isscalar(ax))||... (~isnumeric(rh))||(~isreal(rh))||(~isscalar(rh))||... (~isnumeric(alp))||(~isreal(alp))||(~isscalar(alp))||... (~isnumeric(bet))||(~isreal(bet))||(~isscalar(bet))||... (~isnumeric(gam))||(~isreal(gam))||(~isscalar(gam)) error('all inputs must be real scalars.'); end end % I'm working to improve my methods, and every hour % I save is an hour added to my life. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
existentials.m
.m
nmr-pred-master/spinach/kernel/utilities/existentials.m
12,935
utf_8
08d056cded782d586ea36dc417733567
% Kernel integrity control. Checks for collisions between Spinach func- % tions and anything else that the user may have installed or written % in the current Matlab instance. % % Do not switch this off -- collisions of function names and path probl- % ems are the most frequent support topic at the forum. % % [email protected] % [email protected] (David Goodwin) function existentials() % Do not run existential testing inside parallel pools if isworkernode, return; end % Locate Spinach root_dir=which('existentials'); root_dir=root_dir(1:end-32); % Check location of kernel functions kernel_functions={'assume','average','basis','coherence','correlation','create',... 'carrier','decouple','equilibrium','evolution','execute',... 'hamiltonian','homospoil','kinetics','frqoffset','krylov',... 'lindbladian','operator','orientation','propagator','rotframe',... 'reduce','relaxation','residual','spin','splice','state',... 'step','trajan','trajsimil','spinlock','stateinfo','stepsize',... 'thermalize','singlet'}; for n=1:numel(kernel_functions) expected_location=[root_dir filesep 'kernel' filesep kernel_functions{n} '.m']; apparent_location=which(kernel_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' kernel_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of kernel utilities kernel_utilities={'absorb','anax2dcm','anax2quat','ang2cgsppm','apodization','axis_1d','axrh2mat','banner',... 'binpack','castep2nqi','cce','centroid','cgsppm2ang','clean_up','clebsch_gordan',... 'conmat','corrfun','crop_2d','dcm2euler','dcm2quat','dcm2wigner','dfpt','dihedral',... 'dilute','dipolar','dirdiff','eeqq2nqi','equilibrate','euler2dcm','euler2wigner',... 'existentials','expmint','fdhess','fdkup','fdlap','fdmat','fdvec','fdweights','fftdiff',... 'fourlap','fpl2phan','fpl2rho','fprint','frac2cart','gauss2mhz','gaussfun','hartree2joule',... 'hdot','hess_reorder','hilb2liouv','human2opspec','int_2d','interpmat','intrep',... 'irr_sph_ten','isworkernode','kill_spin','killcross','killdiag','krondelta','lcurve',... 'lin2lm','lin2lmn','lm2lin','lmn2lin','lorentzfun','mat2sphten','md5_hash','mhz2gauss',... 'molplot','mprealloc','mt2hz','negligible','p_superop','pad','path_trace','pauli',... 'perm_group','phan2fpl','plot_1d','plot_2d','plot_3d','probmax','quat2anax','quat2dcm',... 'relax_split','report','rotor_stack','scomponents','shift_iso','significant','slice_2d',... 'sniff','sparse2csr','spher_harmon','sphten2mat','sphten2oper','sphten2state','sphten2zeeman',... 'statmerge','stitch','summary','svd_shrink','sweep2ticks','symmetrize','symmetry',... 'tensor_analysis','tolerances','transfermat','unit_oper','unit_state','v2fplanck',... 'volplot','wigner','xyz2dd','xyz2hfc','xyz2sph','zeeman2sphten','zfs2mat','zte'}; for n=1:numel(kernel_utilities) expected_location=[root_dir filesep 'kernel' filesep 'utilities' filesep kernel_utilities{n} '.m']; apparent_location=which(kernel_utilities{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' kernel_utilities{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of pulse shapes kernel_shapes={'cartesian2polar','chirp_pulse_af','chirp_pulse_xy','grad_pulse','grad_sandw','polar2cartesian',... 'pulse_shape','read_wave','sawtooth','shaped_pulse_af','shaped_pulse_xy','sim_pulse','triwave',... 'vg_pulse','wave_basis'}; for n=1:numel(kernel_shapes) expected_location=[root_dir filesep 'kernel' filesep 'pulses' filesep kernel_shapes{n} '.m']; apparent_location=which(kernel_shapes{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' kernel_shapes{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of optimal control functions oc_functions={'control_sys','fminkrotov','fminnewton','fminsimplex','grape','hessprep','hessreg','krotov',... 'lbfgs','linesearch','optim_report','optim_tols','penalty','quasinewton'}; for n=1:numel(oc_functions) expected_location=[root_dir filesep 'kernel' filesep 'optimcon' filesep oc_functions{n} '.m']; apparent_location=which(oc_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' oc_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of grid functions grid_functions={'gaussleg','grid_kron','grid_test','repulsion','shrewd'}; for n=1:numel(grid_functions) expected_location=[root_dir filesep 'kernel' filesep 'grids' filesep grid_functions{n} '.m']; apparent_location=which(grid_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' grid_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of external functions ext_functions={'assofix','b2r','combnk','expv','fourdif','jacobianest','lgwt','lpredict','phantom3d','simps'}; for n=1:numel(ext_functions) expected_location=[root_dir filesep 'kernel' filesep 'external' filesep ext_functions{n} '.m']; apparent_location=which(ext_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' ext_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of cache functions cache_functions={'ist_product_table','sle_operators'}; for n=1:numel(cache_functions) expected_location=[root_dir filesep 'kernel' filesep 'cache' filesep cache_functions{n} '.m']; apparent_location=which(cache_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' cache_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of context functions context_functions={'crystal','doublerot','floquet','gridfree','hydrodynamics','imaging','liquid',... 'oscillator','powder','roadmap','singlerot'}; for n=1:numel(cache_functions) expected_location=[root_dir filesep 'kernel' filesep 'contexts' filesep context_functions{n} '.m']; apparent_location=which(context_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' context_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of experiments functions exp_functions={['hyperpol' filesep 'dnp_field_scan'],['hyperpol' filesep 'dnp_freq_scan'],... ['hyperpol' filesep 'masdnp'],['hyperpol' filesep 'solid_effect'],... ['overtone' filesep 'overtone_a'],['overtone' filesep 'overtone_cp'],... ['overtone' filesep 'overtone_dante'],['overtone' filesep 'overtone_pa'],... ['pseudocon' filesep 'cg_fast'],['pseudocon' filesep 'chi_eff'],... ['pseudocon' filesep 'hfc2pcs'],['pseudocon' filesep 'hfc2pms'],... ['pseudocon' filesep 'ilpcs'],['pseudocon' filesep 'ipcs'],... ['pseudocon' filesep 'ippcs'],['pseudocon' filesep 'kpcs'],... ['pseudocon' filesep 'logfactorial'],['pseudocon' filesep 'lpcs'],... ['pseudocon' filesep 'pcs_combi_fit'],['pseudocon' filesep 'pcs2chi'],... ['pseudocon' filesep 'pms2chi'],['pseudocon' filesep 'points2mult'],... ['pseudocon' filesep 'ppcs'],['pseudocon' filesep 'qform2sph'],... 'acquire','clip_hsqc','cn2d',... 'cosy','crazed','crosspol','dante','deer_3p_hard_deer','deer_3p_hard_echo','deer_3p_soft_deer',... 'deer_3p_soft_diag','deer_3p_soft_hole','deer_4p_soft_deer','deer_4p_soft_diag','deer_4p_soft_hole',... 'deer_analyt','dqf_cosy','endor_cw','endor_davies','endor_mims','eseem','fieldsweep','hetcor',... 'hmqc','hnco','hncoca','holeburn','hp_acquire','hsqc','hyscore','lcosy','levelpop','m2s',... 'noesy','noesyhsqc','oopeseem','rapidscan','roesy','rydmr','rydmr_exp','s2m','slowpass',... 'sp_acquire','traject','ufcosy','zerofield'}; for n=1:numel(exp_functions) expected_location=[root_dir filesep 'experiments' filesep exp_functions{n} '.m']; apparent_location=which(exp_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' exp_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end % Check location of miscellaneous functions etc_functions={'cst_display','destreak','fid2ascii','g2spinach','gparse',... 'guess_csa_pro','guess_j_pro','guess_j_nuc','hfc_display','karplus_fit',... 'nuclacid','protein','read_bmrb','read_pdb_pro','read_pdb_nuc','s2spinach',... 'strychnine','zfs_sampling'}; for n=1:numel(etc_functions) expected_location=[root_dir filesep 'etc' filesep etc_functions{n} '.m']; apparent_location=which(etc_functions{n}); if ~strcmp(expected_location,apparent_location) disp(['Function ' etc_functions{n}]); disp(['Expected location ' expected_location]); disp(['Apparent location ' apparent_location]); error(['function name collision: either Matlab path is not set correctly or you '... 'have a file with the same name as one of the essential Spinach functions '... 'somewhere, and it prevents Spinach from running.']); end end end % It has been my observation that most people get ahead % during the time that others waste. % % Henry Ford
github
tsajed/nmr-pred-master
wigner.m
.m
nmr-pred-master/spinach/kernel/utilities/wigner.m
1,432
utf_8
436429ecce79ecc2493a86cb52ec1c6a
% Computes Wigner matrices of user-specified ranks. Syntax: % % D=wigner(l,alp,bet,gam) % % where alp, bet and gam are Euler angles in radians. Rows and columns % of the resulting Wigner matrix are sorted by descending ranks, e.g.: % % [D( 2,2) ... D( 2,-2) % ... ... ... % D(-2,2) ... D(-2,-2)] % % The resulting Wigner matrix is to be used as v=W*v, where v is a co- % lumn vector of irreducible spherical tensor coefficients, listed ver- % tically in the order: T(2,2), T(2,1), T(2,0), T(2,-1), T(2,-2). % % [email protected] function D=wigner(l,alp,bet,gam) % Check consistency grumble(l,alp,bet,gam); % Get Pauli matrices L=pauli(2*l+1); % Compute Wigner matrix (Brink & Satchler, Eq 2.13) D=expm(-1i*L.z*alp)*expm(-1i*L.y*bet)*expm(-1i*L.z*gam); end % Consistency enforcement function grumble(l,alp,bet,gam) if (~isnumeric(l))||(~isreal(l))||(~isscalar(l))||(mod(l,1)~=0)||(l<0) error('l must be a non-negative real integer.'); end if (~isnumeric(alp))||(~isreal(alp))||(~isscalar(alp))||... (~isnumeric(bet))||(~isreal(bet))||(~isscalar(bet))||... (~isnumeric(gam))||(~isreal(gam))||(~isscalar(gam)) error('alp, bet and gam must be real scalars.'); end end % Every stink that fights the ventilator thinks it % is Don Quixote. % % Stanistaw Lec
github
tsajed/nmr-pred-master
tensor_analysis.m
.m
nmr-pred-master/spinach/kernel/utilities/tensor_analysis.m
1,616
utf_8
207b76ff9b5e1527be86f6ea9132189d
% Returns diagnostic information about an interaction tensor. Syntax: % % [eigvals,dcm,iso]=tensor_analysis(spin_system,tensor) % % Parameters: % % tensor - a 3x3 Cartesian interaction tensor matrix % % Outputs: % % eigvals - eigenvalues of the tensor % % dcm - directional cosine matrix for the orientation % of the tensor eigenframe relative to the fra- % me it's been supplied in. % % iso - isotropic part of the tensor % % Note: directional cosine matrix is not unique. Although the function % makes some effort at consistency, it cannot be guaranteed. % % [email protected] function [eigvals,dcm,iso]=tensor_analysis(spin_system,tensor) % Check consistency grumble(tensor); % Get the eigensystem [dcm,eigvals]=eig(symmetrize(spin_system,full(tensor))); % Sort the eigensystem [~,index]=sort(abs(diag(eigvals)),1,'ascend'); % Rearrange the eigenvalues eigvals=diag(eigvals); eigvals=eigvals(index); % Rearrange the eigenvectors dcm=dcm(:,index); % Kill the inversion component dcm=dcm*det(dcm); % Prefer upper half-space for positive directions if dcm(3,3)<0 dcm(:,3)=-dcm(:,3); dcm(:,1)=-dcm(:,1); end % Compute the isotropic part iso=mean(eigvals); end % Consistency enforcement function grumble(tensor) if (~isnumeric(tensor))||(~ismatrix(tensor))||any(size(tensor)~=[3 3])||(~isreal(tensor)) error('interaction tensor must be a real 3x3 matrix.'); end end % He who dares not offend cannot be honest. % % Thomas Paine
github
tsajed/nmr-pred-master
zoom_3d.m
.m
nmr-pred-master/spinach/kernel/utilities/zoom_3d.m
1,556
utf_8
43f4854fa234f15ada77b68ae5be45ba
% Zooms a 3D data cube to the fractional limits specified % by the user. Syntax: % % [density,ext]=zoom_3d(density,ext,zoom_ranges) % % Parameters: % % density - probability density cube with dimensions % ordered as [X Y Z] % % ext - grid extents in Angstrom, ordered as % [xmin xmax ymin ymax zmin zmax] % % zoom_ranges - zoom ranges along each axis as fractions, % e.g. [0.3 0.6 0.1 0.2 0.5 0.8] % % [email protected] function [density,ext]=zoom_3d(density,ext,zoom_ranges) % Generate axis ticks oldxvals=linspace(ext(1),ext(2),size(density,1)); oldyvals=linspace(ext(3),ext(4),size(density,2)); oldzvals=linspace(ext(5),ext(6),size(density,3)); % Get new range indices xmin=max([1 floor(size(density,1)*zoom_ranges(1))]); ymin=max([1 floor(size(density,2)*zoom_ranges(3))]); zmin=max([1 floor(size(density,3)*zoom_ranges(5))]); xmax=min([size(density,1) ceil(size(density,1)*zoom_ranges(2))]); ymax=min([size(density,2) ceil(size(density,2)*zoom_ranges(4))]); zmax=min([size(density,3) ceil(size(density,3)*zoom_ranges(6))]); % Extract the subcube density=density(xmin:xmax,ymin:ymax,zmin:zmax); % Update the extents ext=[oldxvals(xmin) oldxvals(xmax) ... oldyvals(ymin) oldyvals(ymax) ... oldzvals(zmin) oldzvals(zmax)]; end % Either you think - or else others have to think for you and % take power from you, pervert and discipline your natural ta- % stes, civilize and sterilize you. % % F. Scott Fitzgerald
github
tsajed/nmr-pred-master
clebsch_gordan.m
.m
nmr-pred-master/spinach/kernel/utilities/clebsch_gordan.m
5,110
utf_8
6d77301826ebda2514757e13819586bb
% Calculates Clebsch-Gordan coefficients. Syntax: % % cg=clebsch_gordan(L,M,L1,M1,L2,M2) % % If physically inadmissible indices are supplied, a zero is returned. % % A very considerable amount of thought has been given to the accuracy % and performance of this function. % % [email protected] function cg=clebsch_gordan(L,M,L1,M1,L2,M2) % Check consistency grumble(L,M,L1,M1,L2,M2); % Set the default answer cg=0; % Match the notation to Varshalovich, Section 8.2.1 c=L; gam=M; a=L1; alp=M1; b=L2; bet=M2; % Run zero tests (Stage I) prefactor_is_nonzero=(a+alp>=0)&&(a-alp>=0)&&... (b+bet>=0)&&(b-bet>=0)&&... (c+gam>=0)&&(c-gam>=0)&&... krondelta(gam,alp+bet); % Proceed if appropriate if prefactor_is_nonzero % Run zero tests (Stage II) delta_is_nonzero=(a+b-c>=0)&&(a-b+c>=0)&&... (-a+b+c>=0)&&(a+b+c+1>=0); % Proceed if appropriate if delta_is_nonzero % Run zero tests (Stage III) lower_sum_limit=max([alp-a, b+gam-a, 0]); upper_sum_limit=min([c+b+alp, c+b-a, c+gam]); sum_is_nonzero=(upper_sum_limit>=lower_sum_limit); % Proceed if appropriate if sum_is_nonzero % Compile a look-up table of gamma functions gamma(a+b+c+2)=java.math.BigInteger.ONE; gamma(:)=gamma(a+b+c+2); for k=3:(a+b+c+2) gamma(k)=gamma(k-1).multiply(java.math.BigInteger.valueOf(k-1)); end % Compute prefactor numerator numer=java.math.BigInteger.valueOf(2*c+1); numer=numer.multiply(gamma(a-b+c+1)); numer=numer.multiply(gamma(-a+b+c+1)); numer=numer.multiply(gamma(c+gam+1)); numer=numer.multiply(gamma(c-gam+1)); numer=numer.multiply(gamma(a+b-c+1)); % Compute prefactor denominator denom=gamma(a+b+c+2); denom=denom.multiply(gamma(a+alp+1)); denom=denom.multiply(gamma(a-alp+1)); denom=denom.multiply(gamma(b+bet+1)); denom=denom.multiply(gamma(b-bet+1)); % Perform floating-point division accur=length(denom.toString)-length(numer.toString)+64; numer=java.math.BigDecimal(numer); denom=java.math.BigDecimal(denom); prefactor=numer.divide(denom,accur,java.math.RoundingMode.HALF_UP); % Compute the sum z_sum=java.math.BigDecimal.ZERO; for z=lower_sum_limit:upper_sum_limit % Compute term numerator numer=java.math.BigInteger.valueOf((-1)^(b+bet+z)); numer=numer.multiply(gamma(c+b+alp-z+1)); numer=numer.multiply(gamma(a-alp+z+1)); % Compute term denominator denom=gamma(z+1); denom=denom.multiply(gamma(c-a+b-z+1)); denom=denom.multiply(gamma(c+gam-z+1)); denom=denom.multiply(gamma(a-b-gam+z+1)); % Perform floating-point division numer=java.math.BigDecimal(numer); denom=java.math.BigDecimal(denom); sum_term=numer.divide(denom,accur,java.math.RoundingMode.HALF_UP); % Add the term to the total z_sum=z_sum.add(sum_term); end % Return to double precision cg_sq=z_sum.multiply(z_sum).multiply(prefactor); cg=z_sum.signum*sqrt(double(cg_sq)); end end end end % Consistency enforcement function grumble(L,M,L1,M1,L2,M2) if (~isnumeric(L))||(~isnumeric(L1))||(~isnumeric(L2))||... (~isnumeric(M))||(~isnumeric(M1))||(~isnumeric(M2)) error('all arguments must be numeric.'); end if (~isreal(L))||(~isreal(L1))||(~isreal(L2))||... (~isreal(M))||(~isreal(M1))||(~isreal(M2)) error('all arguments must be real.'); end if (numel(L)~=1)||(numel(L1)~=1)||(numel(L2)~=1)||... (numel(M)~=1)||(numel(M1)~=1)||(numel(M2)~=1) error('all arguments must have one element.'); end if (mod(2*L+1,1)~=0)||(mod(2*L1+1,1)~=0)||(mod(2*L2+1,1)~=0)||... (mod(2*M+1,1)~=0)||(mod(2*M1+1,1)~=0)||(mod(2*M2+1,1)~=0) error('all arguments must be integer or half-integer.'); end end % The miracle of the appropriateness of the language of mathematics for the % formulation of the laws of physics is a wonderful gift which we neither % understand nor deserve. We should be grateful for it and hope that it will % remain valid in future research and that it will extend, for better or for % worse, to our pleasure, even though perhaps also to our bafflement, to % wide branches of learning. % % Eugene Wigner, http://dx.doi.org/10.1002/cpa.3160130102
github
tsajed/nmr-pred-master
euler2wigner.m
.m
nmr-pred-master/spinach/kernel/utilities/euler2wigner.m
4,265
utf_8
d6513655695ef5113c4156054c60001a
% Second-rank Wigner rotation matrix as a function of Euler angles. Two % possible input styles are: % % W=euler2wigner(alpha,beta,gamma) % W=euler2wigner([alpha beta gamma]) % % where alpha, beta and gamma are Euler angles in radians. Rows and columns % of the resulting Wigner matrix are sorted by descending ranks, that is: % % [D( 2,2) ... D( 2,-2) % ... ... ... % D(-2,2) ... D(-2,-2)] % % The resulting Wigner matrix is to be used as v=W*v, where v is a column % vector of irreducible spherical tensor coefficients, listed vertically in % the following order: T(2,2), T(2,1), T(2,0), T(2,-1), T(2,-2). % % [email protected] % [email protected] function W=euler2wigner(arg1,arg2,arg3) % Adapt to the input style if nargin==1 % Assume that a single input is a 3-vector alp=arg1(1); bet=arg1(2); gam=arg1(3); elseif nargin==3 % Assume that three inputs are Euler angles alp=arg1; bet=arg2; gam=arg3; else % Bomb out in all other cases error('incorrect number of input arguments.'); end % Check consistency grumble(alp,bet,gam); % Do the math, as per Brink and Satchler, Eq 2.17 W=[ exp(-1i*(+2)*alp)* (+cos(bet/2)^4)* exp(-1i*(+2)*gam), ... exp(-1i*(+2)*alp)* (-sin(bet)*(cos(bet)+1)/2)* exp(-1i*(+1)*gam), ... exp(-1i*(+2)*alp)* (+sqrt(3/8)*sin(bet)^2)* exp(-1i*( 0)*gam), ... exp(-1i*(+2)*alp)* (+sin(bet)*(cos(bet)-1)/2)* exp(-1i*(-1)*gam), ... exp(-1i*(+2)*alp)* (+sin(bet/2)^4)* exp(-1i*(-2)*gam); ... exp(-1i*(+1)*alp)* (+sin(bet)*(cos(bet)+1)/2)* exp(-1i*(+2)*gam), ... exp(-1i*(+1)*alp)* (+(2*cos(bet)-1)*(cos(bet)+1)/2)* exp(-1i*(+1)*gam), ... exp(-1i*(+1)*alp)* (-sqrt(3/2)*sin(bet)*cos(bet))* exp(-1i*( 0)*gam), ... exp(-1i*(+1)*alp)* (-(2*cos(bet)+1)*(cos(bet)-1)/2)* exp(-1i*(-1)*gam), ... exp(-1i*(+1)*alp)* (+sin(bet)*(cos(bet)-1)/2)* exp(-1i*(-2)*gam); ... exp(-1i*( 0)*alp)* (+sqrt(3/8)*sin(bet)^2)* exp(-1i*(+2)*gam), ... exp(-1i*( 0)*alp)* (+sqrt(3/2)*sin(bet)*cos(bet))* exp(-1i*(+1)*gam), ... exp(-1i*( 0)*alp)* (3*cos(bet)^2-1)/2* exp(-1i*( 0)*gam), ... exp(-1i*( 0)*alp)* (-sqrt(3/2)*sin(bet)*cos(bet))* exp(-1i*(-1)*gam), ... exp(-1i*( 0)*alp)* (+sqrt(3/8)*sin(bet)^2)* exp(-1i*(-2)*gam); ... exp(-1i*(-1)*alp)* (-sin(bet)*(cos(bet)-1)/2)* exp(-1i*(+2)*gam), ... exp(-1i*(-1)*alp)* (-(2*cos(bet)+1)*(cos(bet)-1)/2)* exp(-1i*(+1)*gam), ... exp(-1i*(-1)*alp)* (+sqrt(3/2)*sin(bet)*cos(bet))* exp(-1i*( 0)*gam), ... exp(-1i*(-1)*alp)* (+(2*cos(bet)-1)*(cos(bet)+1)/2)* exp(-1i*(-1)*gam), ... exp(-1i*(-1)*alp)* (-sin(bet)*(cos(bet)+1)/2)* exp(-1i*(-2)*gam); ... exp(-1i*(-2)*alp)* (+sin(bet/2)^4)* exp(-1i*(+2)*gam), ... exp(-1i*(-2)*alp)* (-sin(bet)*(cos(bet)-1)/2)* exp(-1i*(+1)*gam), ... exp(-1i*(-2)*alp)* (+sqrt(3/8)*sin(bet)^2)* exp(-1i*( 0)*gam), ... exp(-1i*(-2)*alp)* (+sin(bet)*(cos(bet)+1)/2)* exp(-1i*(-1)*gam), ... exp(-1i*(-2)*alp)* (+cos(bet/2)^4)* exp(-1i*(-2)*gam)]; end % Consistency enforcement function grumble(alp,bet,gam) if (~isnumeric(alp))||(~isnumeric(bet))||(~isnumeric(gam)) error('all inputs must be numeric.'); end if (~isreal(alp))||(~isreal(bet))||(~isreal(gam)) error('all inputs must be real.'); end if (numel(alp)~=1)||(numel(bet)~=1)||(numel(gam)~=1) error('all inputs must have one element.'); end end % There is nothing of any importance in life - except how well you do % your work. Nothing. Only that. Whatever else you are, will come from % that. It's the only measure of human value. All the codes of ethics % they'll try to ram down your throat are just so much paper money put % out by swindlers to fleece people of their virtues. The code of com- % petence is the only system of morality that's on a gold standard. % When you grow up, you'll know what I mean. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
probmax.m
.m
nmr-pred-master/spinach/kernel/utilities/probmax.m
563
utf_8
62b608e4801e9141cdaa24967600dc43
% Finds the maximum of the probability density. % % [email protected] function [x,y,z]=probmax(probden,ranges) % Get coordinate arrays [X,Y,Z]=ndgrid(linspace(ranges(1),ranges(2),size(probden,1)),... linspace(ranges(3),ranges(4),size(probden,2)),... linspace(ranges(5),ranges(6),size(probden,3))); % Get the max [~,index]=max(probden(:)); % Get maximum coordinates x=X(index); y=Y(index); z=Z(index); end % What exactly is your "fair share" of what % someone else has worked for? % % Thomas Sowell
github
tsajed/nmr-pred-master
fdmat.m
.m
nmr-pred-master/spinach/kernel/utilities/fdmat.m
1,435
utf_8
b51a5ff829b47097c12e13a52b875ade
% Returns arbitrary-order central finite-difference differentiation % matrix (sparse) with unit spacing and periodic boundary conditions. % Syntax: % % D=fdmat(dim,npoints,order) % % Parameters: % % dim - dimension of the column vector to be % differentiated % % nstenc - number of points in the finite diffe- % rence stencil % % order - order of the derivative required % % [email protected] function D=fdmat(dim,nstenc,order) % Check consistency grumble(dim,nstenc,order); % Preallocate the answer D=spalloc(dim,dim,dim*nstenc); % Wraparound fill with centered schemes stencil=((1-nstenc)/2):((nstenc-1)/2); w=fdweights(0,stencil,order); for n=1:dim D(n,mod(stencil+n-1,dim)+1)=w(end,:); %#ok<SPRIX> end end % Consistency enforcement function grumble(dim,nstenc,order) if (dim<1)||(nstenc<1)||(order<1)||(mod(dim,1)~=0)||(mod(nstenc,1)~=0)||(mod(order,1)~=0) error('all input parameters must be positive integers.'); end if dim<3 error('minimum differentiation matrix dimension is 3.'); end if mod(nstenc,2)~=1 error('the number of stencil points must be odd.'); end if order>=nstenc error('derivative order must be smaller than the stencil size.'); end end % We may eventually come to realize that chastity % is no more a virtue than malnutrition. % % Alex Comfort
github
tsajed/nmr-pred-master
hess_reorder.m
.m
nmr-pred-master/spinach/kernel/utilities/hess_reorder.m
2,292
utf_8
72c90d46e3eb7617e958eeb4cca8fb88
% The waveforms on different channels are assumed to be stored in the % rows of the input array. The Hessian elements correspond to the ele- % ments of the waveform array ordered as: % % [X1 Y1 Z1 X2 Y2 Z2 ... Xn Yn Zn] % % where X,Y,Z are different control channels and the index enumerates % the time discretization points. Gradient dimensions and element or- % der are the same as the input waveform dimensions and element order. % Elements of the Hessian are reordered as to correspond to the wavef- % orm array: % [X1 X2 ... Xn Y1 Y2 ... Yn Z1 Z2 ... Zn] % % interchanging the order from controls then time point to time point % then controls, or visa versa. % % Inputs: % hess - the old Hessian matrix to be reordered, curre- % ntly ordered K first then N. % % K - the first ordered variable of the old Hessian, % control channels in the example above. % % N - the second ordered variable of the old Hessian, % time points in the example above. % % Output: % hess_new - the newly order Hessian with N first then K. % % [email protected] function hess_new=hess_reorder(hess,K,N) % Check consistency grumble(hess,K,N) % Pre-allocate space for new Hessian hess_new=zeros(size(hess)); % Loop over the elements parfor j=1:(N*K)^2 % Dummy variable for parfor to work hess_temp=zeros(size(hess)); % Row and column of new Hessian row=1+mod(j-1,N*K); col=1+(j-1-mod(j-1,N*K))/(N*K); % Variables corresponding to elements k1=1+mod(row-1,N); k2=1+mod(col-1,N); n1=1+(row-1-mod(row-1,N))/(N); n2=1+(col-1-mod(col-1,N))/(N); % Row and column of the old Hessian row_old=n1+K*(k1-1); col_old=n2+K*(k2-1); % Allocate the old Hessian to its new place hess_temp(row,col)=hess(row_old,col_old); hess_new=hess_new+hess_temp; end end % Consistency enforcement function grumble(hess,dim1,dim2) if numel(hess)~=(dim1*dim2)^2 error('Hessian size should be (K*N)^2') end end % If it's true that our species is alone in the universe, % then I'd have to say the universe aimed rather low and % settled for very little. % % George Carlin
github
tsajed/nmr-pred-master
absorb.m
.m
nmr-pred-master/spinach/kernel/utilities/absorb.m
1,539
utf_8
cdff513e969bcc9b1960712d1a5aed1f
% Designates specific states as "dark" -- any population reaching % them would end up being summed up and stored in them forever in % a frozen state. Syntax: % % L=absorb(spin_system,L,dark_states) % % where L is the Liouvillian and dark_states contains the numbers % of the states that should be switched into the absorption mode. % % Note: absorption functionality is only available in the sphten- % liouv formalism. % % [email protected] function L=absorb(spin_system,L,dark_states) % Check consistency grumble(spin_system,L,dark_states); % Zero columns corresponding to dark states L(:,dark_states)=0; end % Consistency enforcement function grumble(spin_system,L,dark_states) if ~strcmp(spin_system.bas.formalims,'sphten-liouv') error('this function is only applicable to sphten-liouv formalism.'); end if (~isnumeric(L))||(size(L,1)~=size(L,2)) error('L must be a square matrix.'); end if any(size(L)~=size(spin_system.bas.basis,1)) error('Dimension of the Liouvillian must match the dimension of the basis set.'); end if (~isnumeric(dark_states))||(~isvector(dark_states))||(~isreal(dark_states))||... any(mod(dark_states,1)~=0)||any(dark_states<=0) error('dark_states must be a vector of positive integers.'); end if any(dark_states>size(spin_system.bas.basis,1)) error('an element of the dark_states vector exceeds the state space dimension.'); end end % Acting in a bad play is like spitting into eternity. % % Faina Ranevskaya
github
tsajed/nmr-pred-master
gauss2mhz.m
.m
nmr-pred-master/spinach/kernel/utilities/gauss2mhz.m
557
utf_8
866bc949d001ef3589f27a86a0d187de
% Converts hyperfine couplings from Gauss to MHz (linear % frequency). Syntax: % % hfc_mhz=gauss2mhz(hfc_gauss) % % Arrays of any dimensions are supported. % % [email protected] function hfc_mhz=gauss2mhz(hfc_gauss) if isnumeric(hfc_gauss)&&isreal(hfc_gauss) hfc_mhz=2.802495365*hfc_gauss; else error('the argument must be an array of real numbers.'); end end % A celibate clergy is an especially good idea, because it tends to % suppress any hereditary propensity toward fanaticism. % % Carl Sagan
github
tsajed/nmr-pred-master
xyz2sph.m
.m
nmr-pred-master/spinach/kernel/utilities/xyz2sph.m
469
utf_8
4dcdd5ed3aa528bf792f9eb009a41d35
% Converts Cartesian coordinates [x y z] into spherical coordinates % according to the ISO convention. % % [email protected] function [r, theta, phi] = xyz2sph(x, y, z) % Radius 0 <= r < Inf r=sqrt(x.^2+y.^2+z.^2); % Inclination 0 <= theta <= pi theta=acos(z./r); % Azimuth 0 <= phi < 2*pi phi=atan2(y,x); end % Q: How would a theoretical physicist milk a cow? % A: As a first approximation, consider a spherical cow in vacuum...
github
tsajed/nmr-pred-master
v2fplanck.m
.m
nmr-pred-master/spinach/kernel/utilities/v2fplanck.m
788
utf_8
59585d448a9939f4be64a18af42d9c64
% Translates a stationary 3D velocity field into a Fokker-Planck % evolution generator. % % [email protected] % [email protected] function F=v2fplanck(U,V,W,parameters) % Get the translation generators [Fx,Fy,Fz]=hydrodynamics(parameters); % Build the Fokker-Planck flow generator F=spdiags(Fx*U(:)+Fy*V(:)+Fz*W(:),0,prod(parameters.npts),prod(parameters.npts))+... spdiags(U(:),0,prod(parameters.npts),prod(parameters.npts))*Fx+... spdiags(V(:),0,prod(parameters.npts),prod(parameters.npts))*Fy+... spdiags(W(:),0,prod(parameters.npts),prod(parameters.npts))*Fz; % Add the diffusion term F=F-1i*parameters.diffc*(Fx*Fx+Fy*Fy+Fz*Fz); end % "He's spending a year dead for tax reasons." % % Douglas Adams, The Hitchhiker's Guide to the Galaxy
github
tsajed/nmr-pred-master
axis_1d.m
.m
nmr-pred-master/spinach/kernel/utilities/axis_1d.m
2,492
utf_8
72119cf2ebad8b04c7a2d58b49548c3e
% Generates axes for plotting. % % [email protected] function [ax,ax_label]=axis_1d(spin_system,parameters) % Build the axis and apply the offset if numel(parameters.sweep)==1 ax=linspace(-parameters.sweep/2,parameters.sweep/2,parameters.zerofill)+parameters.offset; else ax=linspace(parameters.sweep(1),parameters.sweep(2),parameters.zerofill); end % Convert the units if necessary switch parameters.axis_units case 'ppm' ax_label=[parameters.spins{1} ' chemical shift / ppm']; ax=1000000*(2*pi)*ax/(spin(parameters.spins{1})*spin_system.inter.magnet); case 'Gauss' ax_label='Magnetic induction / Gauss'; ax=10000*(spin_system.inter.magnet-2*pi*ax/spin('E')); case 'Gauss-labframe' ax_label='Magnetic induction / Gauss'; ax=10000*(2*pi*ax/spin('E')); case 'mT' ax_label='Magnetic induction / mT'; ax=1000*(spin_system.inter.magnet-2*pi*ax/spin('E')); case 'mT-labframe' ax_label='Magnetic induction / mT'; ax=1000*(2*pi*ax/spin('E')); case 'T' ax_label='Magnetic induction / Tesla'; ax=spin_system.inter.magnet-2*pi*ax/spin('E'); case 'Hz' ax_label=[parameters.spins{1} ' offset linear frequency / Hz']; ax=1*ax; case 'kHz' ax_label=[parameters.spins{1} ' offset linear frequency / kHz']; ax=0.001*ax; case 'MHz' ax_label=[parameters.spins{1} ' offset linear frequency / MHz']; ax=0.000001*ax; case 'MHz-labframe' ax_label=[parameters.spins{1} ' linear frequency / MHz']; ax=0.000001*(ax-spin_system.inter.magnet*spin(parameters.spins{1})/(2*pi)); case 'GHz' ax_label=[parameters.spins{1} ' offset linear frequency / GHz']; ax=0.000000001*ax; case 'GHz-labframe' ax_label=[parameters.spins{1} ' linear frequency / GHz']; ax=0.000000001*(ax-spin_system.inter.magnet*spin(parameters.spins{1})/(2*pi)); otherwise error('unknown axis units.'); end end % The God of the Old Testament is arguably the most unpleasant character in % all fiction: jealous and proud of it; a petty, unjust, unforgiving control % freak; a vindictive, bloodthirsty ethnic cleanser; a misogynistic, homopho- % bic, racist, infanticidal, genocidal, filicidal, pestilential, megalomania- % cal, sadomasochistic, capriciously malevolent bully. % % Richard Dawkins, "The God Delusion"
github
tsajed/nmr-pred-master
lmn2lin.m
.m
nmr-pred-master/spinach/kernel/utilities/lmn2lin.m
2,047
utf_8
e694562633c062dd42eb54db4d046c2a
% Converts L,M,N Wigner function specification to linear indexing speci- % fication. In the linear indexing convention, the Wigner functions are % listed in the order of increasing L rank. Within each L rank, the func- % tions are listed in the order of decreasing left index, and, for each % left index, in the order of decreasing right index. Syntax: % % I=lmn2lin(L,M,N) % % Wigner functions are enumerated using base one indexing, that is: % % (L=0,M=0,N=0) -> I=1 % (L=1,M=1,N=1) -> I=2 % (L=1,M=1,N=0) -> I=3, et cetera... % % Arrays of any dimension are accepted as arguments. % % [email protected] function I=lmn2lin(L,M,N) % Check consistency grumble(L,M,N); % Get the linear index I=L.*(4*L.^2+6*(L-M)+5)/3-M-N+1; end % Consistency enforcement function grumble(L,M,N) if (~isnumeric(L))||(~isreal(L))||any(mod(L(:),1)~=0)||... (~isnumeric(M))||(~isreal(M))||any(mod(M(:),1)~=0)||... (~isnumeric(N))||(~isreal(N))||any(mod(N(:),1)~=0) error('all elements of the inputs must be real integers.'); end if any(abs(M(:))>L(:)) error('unacceptable M projection number.'); end if any(abs(N(:))>L(:)) error('unacceptable N projection number.'); end if any(L(:)<0) error('unacceptable Wigner function rank.'); end if any(size(L)~=size(M))||any(size(L)~=size(N)) error('array dimensions are inconsistent.'); end end % IK has compiled, over the years, a list of books that allow % one to successfully withstand the toxic social atmosphere of % academic establishments. In the approximate order of reading, % the books are: % % - Ayn Rand, "Atlas Shrugged" % - Ayn Rand, "The Fountainhead" % - Friedrich Nietzsche, "Beyond Good and Evil" % - David DeAngelo, "Deep Inner Game" % - Ragnar Redbeard, "Might is Right" % % If you are starting your career in Academia, or think about % applying for a faculty post, read these books.