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
tsajed/nmr-pred-master
plot_1d.m
.m
nmr-pred-master/spinach/kernel/utilities/plot_1d.m
3,959
utf_8
52d2b971d3a325d0883c9ea48b20d266
% 1D plotting utility. Uses the same parameters structure as 1D pulse % sequences. Input syntax: % % plot_1d(spin_system,spectrum,parameters) % % Input parameters: % % parameters.sweep sweep width, Hz % % parameters.spins spin species, e.g. {'1H'} % % parameters.offset transmitter offset, Hz % % parameters.axis_units axis units ('ppm','Gauss', % 'mT','T','Hz','kHz','MHz') % % parameters.derivative if set to 1, the spectrum is % differentiated before plotting % % parameters.invert_axis if set to 1, the frequency axis % is inverted before plotting % % Any extra arguments given to this function will be passed to the built-in % Matlab function plot(). % % [email protected] % [email protected] function plot_1d(spin_system,spectrum,parameters,varargin) % Set common defaults parameters=defaults(spin_system,parameters); % Check consistency grumble(spectrum,parameters); % If a complex spectrum is received, plot both components if ~isreal(spectrum) % Recursively plot the real component subplot(2,1,1); plot_1d(spin_system,real(spectrum),parameters,varargin{:}); title('Real part of the complex spectrum.'); % Recursively plot the imaginary component subplot(2,1,2); plot_1d(spin_system,imag(spectrum),parameters,varargin{:}); title('Imaginary part of the complex spectrum.'); return; end % Get the axis [ax,ax_label]=axis_1d(spin_system,parameters); % Compute the derivative if necessary if isfield(parameters,'derivative')&&parameters.derivative spectrum=fdvec(spectrum,5,1); end % Plot the spectrum plot(ax,spectrum,varargin{:}); axis tight; % Label the axis xlabel(ax_label); % Invert the axis if necessary if isfield(parameters,'invert_axis')&&parameters.invert_axis set(gca,'XDir','reverse'); end end % Default parameters function parameters=defaults(spin_system,parameters) if (~isfield(parameters,'offset'))&&(numel(parameters.sweep)==1) report(spin_system,'parameters.offset field not set, assuming zero offsets.'); parameters.offset=zeros(size(parameters.spins)); end if ~isfield(parameters,'axis_units') report(spin_system,'parameters.axis_units field not set, assuming ppm.'); parameters.axis_units='ppm'; end if ~isfield(parameters,'invert_axis') report(spin_system,'parameters.invert_axis field not set, assuming NMR tradition.'); parameters.invert_axis=1; end end % Consistency enforcement function grumble(spectrum,parameters) if (~isnumeric(spectrum))||(~isvector(spectrum)) error('spectrum should be a vector of numbers.'); end if (~isfield(parameters,'offset'))&&(numel(parameters.sweep)==1) error('offset should be specified in parameters.offset variable.'); end if (numel(parameters.sweep)==2)&&isfield(parameters,'offset') error('offset should not be specified when spectral extents are given in parameters.sweep variable.'); end if ~isfield(parameters,'sweep') error('sweep width should be specified in parameters.sweep variable.'); end if (numel(parameters.sweep)~=1)&&(numel(parameters.sweep)~=2) error('parameters.sweep array should have one or two elements.'); end if ~isfield(parameters,'axis_units') error('axis units must be specified in parameters.axis_units variable.'); end if ~ischar(parameters.axis_units) error('parameters.axis_units must be a character string.'); end if ~isfield(parameters,'spins') error('working spins should be specified in parameters.spins variable.'); end if (~iscell(parameters.spins))||(numel(parameters.spins)~=1) error('parameters.spins cell array must have exactly one element.'); end end % The only sin on earth is to do things badly. % % Ayn Rand
github
tsajed/nmr-pred-master
dirdiff.m
.m
nmr-pred-master/spinach/kernel/utilities/dirdiff.m
2,174
utf_8
741772511db8416d34d4afeb5f30ff0f
% Directional derivatives of the matrix exponential. Implements Equation 11 % of Najfeld and Havel and our Equations 16 and 17. Syntax: % % D=dirdiff(spin_system,A,B,T,N) % % if A an B are matrices, computes the N-th derivative of the matrix expo- % nential exp(A*T) in the direction B. If B is a cell array, computes the % mixed derivative of exp(A*T) in directions B{1}, B{2}, etc. % % [email protected] % [email protected] function D=dirdiff(spin_system,A,B,T,N) % Check consistency grumble(A,B,T,N); % Preallocate arrays auxmat=cell(N,N); D=cell(1,N); % Build auxiliary matrix for n=1:N for k=1:N auxmat{n,k}=sparse(size(A,1),size(A,2)); end end if iscell(B) for n=1:(N-1), auxmat{n,n+1}=B{n}; end else for n=1:(N-1), auxmat{n,n+1}=B; end end for n=1:N, auxmat{n,n}=A; end % Tighten up exponentiation tolerance spin_system.tols.prop_chop=1e-14; % Exponentiate auxiliary matrix auxmat=propagator(spin_system,cell2mat(auxmat),T); % Extract directional derivatives for n=1:N D{n}=factorial(n-1)*auxmat(1:size(A,1),(1:size(A,2))+size(A,2)*(n-1)); end end % Consistency enforcement function grumble(A,B,T,N) if (~isnumeric(N))||(~isreal(N))||(~isscalar(N))||(N<2)||(mod(N,1)~=0) error('N must be a real integer greater than 1.'); end if iscell(B) if numel(B)~=N-1 error('number of B matrices must equal N-1.'); else for n=1:numel(B) if (~isnumeric(A))||(size(A,1)~=size(A,2))||... (~isnumeric(B{n}))||(size(B{n},1)~=size(B{n},2)) error('A and B must be square matrices.'); end end end else if (~isnumeric(A))||(size(A,1)~=size(A,2))||... (~isnumeric(B))||(size(B,1)~=size(B,2)) error('A and B must be square matrices.'); end end if (~isnumeric(T))||(~isreal(T))||(~isscalar(T)) error('T must be a real scalar.'); end end % Disciplining yourself to do what you know is right % and important, although difficult, is the high road % to pride, self-esteem, and personal satisfaction. % % Margaret Thatcher
github
tsajed/nmr-pred-master
report.m
.m
nmr-pred-master/spinach/kernel/utilities/report.m
2,275
utf_8
b265dc54d5bbfddb257f62b35084a2f8
% Writes a log message to the console or an ACSII file. Syntax: % % report(spin_system,report_string) % % where report_string is a character string. A newline symbol at the end % of the string is not necessary - it is added by the function. % % [email protected] % [email protected] function report(spin_system,report_string) % Catch single-argument calls if nargin==1 error('console reporting function requires two arguments.'); end % Ignore the call if the system is hushed if ~strcmp(spin_system.sys.output,'hush') % Validate the input grumble(spin_system,report_string); % Compose the prefix call_stack=dbstack; for n=1:numel(call_stack) call_stack(n).name=[call_stack(n).name ' > ']; end prefix_string=[call_stack(end:-1:2).name]; prefix_string=prefix_string(1:(end-3)); % Fix empty prefixes if isempty(prefix_string) prefix_string=' '; end % Roll the prefix if numel(prefix_string)<50 prefix_string=pad(prefix_string,50); else prefix_string=['...' prefix_string((end-46):end)]; end % Add prefix to the report string report_string=['[' prefix_string ' ] ' report_string]; % Send the report string to the output, ignoring impossible writes try fprintf(spin_system.sys.output,'%s\n',report_string); end %#ok<TRYNC> end end % Consistency enforcement function grumble(spin_system,report_string) if (~isfield(spin_system,'sys'))||~isfield(spin_system.sys,'output') error('spin_system.sys.output field must exist.'); end if ((~isa(spin_system.sys.output,'double'))&&(~isa(spin_system.sys.output,'char')))||... (isa(spin_system.sys.output,'char')&&(~strcmp(spin_system.sys.output,'hush'))) error('spin_system.sys.output must be either ''hush'' or a file ID.'); end if ~ischar(report_string) error('report_string must be a string.'); end end % All parts should go together without forcing. You must remember that the % parts you are reassembling were disassembled by you. Therefore, if you % can't get them together again, there must be a reason. By all means, do % not use a hammer. % % IBM Manual, 1925
github
tsajed/nmr-pred-master
sphten2mat.m
.m
nmr-pred-master/spinach/kernel/utilities/sphten2mat.m
2,907
utf_8
48b9796604056dc8abf5df48b34a271b
% Converts the nine components of the irreducible spherical tensor re- % presentation of an interaction tensor into the Cartesian representa- % tion with a 3x3 matrix. % % Spherical tensor components should be listed in the following order: % % rank 0: (0,0) % rank 1: (1,1) (1,0) (1,-1) % rank 2: (2,2) (2,1) (2,0) (2,-1) (2,-2) % % and should be supplied as coefficients in front of the corresponding % irreducible spherical tenror operators. Syntax: % % M=sphten2mat(rank0,rank1,rank2) % % Parameters: % % rank0 - a single number giving the coefficient of T(0,0) in % the spherical tensor expansion. % % rank1 - a row vector with three numbers giving the coeffici- % ents of T(1,1), T(1,0) and T(1,-1) in the spherical % tensor expansion. % % rank2 - a row vector with five numbers giving the coeffici- % ents of T(2,2), T(2,1), T(2,0), T(2,-1) and T(2,-2) % in the spherical tensor expansion. % % See Table 1 in http://dx.doi.org/10.1016/0022-2364(77)90011-7 (note % that minus signs are absorbed into the coefficients in Spinach). % % [email protected] function M=sphten2mat(rank0,rank1,rank2) % Check the input grumble(rank0,rank1,rank2) % Preallocate the answer M=zeros(3); % Rank 0 component if ~isempty(rank0) M=M-(1/sqrt(3))*[1 0 0; 0 1 0; 0 0 1]*rank0; end % Rank 1 components if exist('rank1','var')&&~isempty(rank1) M=M-(1/2)*[0 0 -1; 0 0 -1i; 1 1i 0]*rank1(1); M=M-(1/sqrt(8))*[0 -2i 0; 2i 0 0; 0 0 0]*rank1(2); M=M-(1/2)*[0 0 -1; 0 0 1i; 1 -1i 0]*rank1(3); end % Rank 2 components if exist('rank2','var')&&~isempty(rank2) M=M+(1/2)*[1 1i 0; 1i -1 0; 0 0 0]*rank2(1); M=M-(1/2)*[0 0 1; 0 0 1i; 1 1i 0]*rank2(2); M=M+(1/sqrt(6))*[-1 0 0; 0 -1 0; 0 0 2]*rank2(3); M=M+(1/2)*[0 0 1; 0 0 -1i; 1 -1i 0]*rank2(4); M=M+(1/2)*[1 -1i 0; -1i -1 0; 0 0 0]*rank2(5); end end % Consistency enforcement function grumble(rank0,rank1,rank2) if (~isnumeric(rank0))||(~isnumeric(rank1))||(~isnumeric(rank2)) error('all inputs must be vectors.'); end if (numel(rank0)~=1)&&(~isempty(rank0)) error('the first input must either be empty or have exactly one element.'); end if (numel(rank1)~=3)&&(~isempty(rank1)) error('the second input must either be empty or have exactly three elements.'); end if (numel(rank2)~=5)&&(~isempty(rank2)) error('the third input must either be empty or have exactly five elements.'); end end % When you're young, you look at television and think "there's a conspi- % racy - the networks have conspired to dumb us down". But when you get % a little older, you realize that's not true. The networks are in busi- % ness to give people exactly what they want. That's a far more depres- % sing thought. % % Steve Jobs
github
tsajed/nmr-pred-master
unit_oper.m
.m
nmr-pred-master/spinach/kernel/utilities/unit_oper.m
1,437
utf_8
eb5264b07ec428049c3b023d8026e19c
% Returns a unit operator in the current formalism and basis. Syntax: % % A=unit_oper(spin_system) % % [email protected] % [email protected] function A=unit_oper(spin_system) % Decide how to proceed switch spin_system.bas.formalism case 'sphten-liouv' % Unit matrix A=speye(size(spin_system.bas.basis,1)); case 'zeeman-liouv' % Unit matrix A=speye(prod(spin_system.comp.mults.^2)); case 'zeeman-hilb' % Unit matrix A=speye(prod(spin_system.comp.mults)); otherwise % Complain and bomb out error('unknown formalism specification.'); end end % The substance of this book, as it is expressed in the editor's preface, is % that to measure "right" by the false philosophy of the Hebrew prophets and % "weepful" Messiahs is madness. Right is not the offspring of doctrine, but % of power. All laws, commandments, or doctrines as to not doing to another % what you do not wish done to you, have no inherent authority whatever, but % receive it only from the club, the gallows and the sword. A man truly free % is under no obligation to obey any injunction, human or divine. [...] Men % should not be bound by moral rules invented by their foes. % % Leo Tolstoy, about Ragnar Redbeard's "Might is Right"
github
tsajed/nmr-pred-master
dfpt.m
.m
nmr-pred-master/spinach/kernel/utilities/dfpt.m
3,132
utf_8
f2537d9e3eba296daa3a9a5fcb3cd245
% Graph partitioning module. Analyzes the system connectivity graph and % creates a list of all connected subgraphs of up to the user-specified % size by crawling the graph in all available directions. Syntax: % % subgraphs=dfpt(conmatrix,max_subgraph_size) % % Arguments: % % conmatrix - a matrix with 1 for connected spins % and zeros elsewhere. % % max_subgraph_size - maximum connected subgraph size in % the resulting subgraph list. % % Output: a matrix with each row corresponding to a subgraph. Each row % contains 1 for spins that belong to the subgraph and zeros elsewhere. % % [email protected] function subgraphs=dfpt(conmatrix,max_subgraph_size) % Check consistency grumble(conmatrix,max_subgraph_size); % Start at each spin in the network subgraphs=eye(size(conmatrix)); % Depth-first path tracing through the coupling graph for n=1:(max_subgraph_size-1) % Determine immediate neigbours reachable from current subgraphs neighbor_matrix=logical(double(subgraphs)*double(conmatrix)); neighbor_matrix(logical(subgraphs))=0; % Determine the dimensions of the new subgraph descriptor array ngraphs=nnz(neighbor_matrix)+nnz(sum(neighbor_matrix,2)==0); nspins=size(conmatrix,2); % Preallocate the new subgraph descriptor array new_subgraphs=zeros(ngraphs,nspins); % Grow each subgraph by one node in each available direction list_position=1; for k=1:size(subgraphs,1) spins_to_add=find(neighbor_matrix(k,:)); if isempty(spins_to_add) new_subgraphs(list_position,:)=subgraphs(k,:); list_position=list_position+1; else for m=spins_to_add new_subgraphs(list_position,:)=subgraphs(k,:); new_subgraphs(list_position,m)=1; list_position=list_position+1; end end end % Remove repetitions new_subgraphs=logical(new_subgraphs); subgraphs=unique(new_subgraphs,'rows'); end % Convert to sparse matrix subgraphs=sparse(subgraphs); end % Consistency enforcement function grumble(conmatrix,max_subgraph_size) if (~islogical(conmatrix))||(~issparse(conmatrix)) error('conmatrix argument must be a sparse logical matrix.'); end if size(conmatrix,1)~=size(conmatrix,2) error('conmatrix matrix must be square.'); end if (numel(max_subgraph_size)~=1)||(~isnumeric(max_subgraph_size))||(~isreal(max_subgraph_size))||... (max_subgraph_size<1)||(mod(max_subgraph_size,1)~=0) error('max_subgraph_size must be a real positive integer.'); end end % Psychologists call this "cognitive dissonance" - the ability to make a % compelling, heartfelt case for one thing while doing another. Being able % to pull off this sort of trick is an essential skill in many professions: % "even if his message bore no relation to his actions, it expressed pre- % cisely and succinctly what he should have been doing". % % The Economist
github
tsajed/nmr-pred-master
crop_2d.m
.m
nmr-pred-master/spinach/kernel/utilities/crop_2d.m
2,008
utf_8
dae199e0d941af7f931aa94bc1db2b8f
% Crops 2D spectra to user-specified ranges (in ppm). % % [email protected] function [spec,parameters]=crop_2d(spin_system,spec,parameters,crop_ranges) % Accommodate homonuclear 2D sequences if numel(parameters.spins)==1, parameters.spins=[parameters.spins parameters.spins]; end if numel(parameters.offset)==1, parameters.offset=[parameters.offset parameters.offset]; end if numel(parameters.sweep)==1, parameters.sweep=[parameters.sweep parameters.sweep]; end % Build axes and apply offsets axis_f1_hz=linspace(-parameters.sweep(1)/2,parameters.sweep(1)/2,size(spec,1))+parameters.offset(1); axis_f2_hz=linspace(-parameters.sweep(2)/2,parameters.sweep(2)/2,size(spec,2))+parameters.offset(2); % Convert the units axis_f1_ppm=1000000*(2*pi)*axis_f1_hz/(spin(parameters.spins{1})*spin_system.inter.magnet); axis_f2_ppm=1000000*(2*pi)*axis_f2_hz/(spin(parameters.spins{2})*spin_system.inter.magnet); % Find array bounds l_bound_f1=find(axis_f1_ppm>crop_ranges{1}(1),1); r_bound_f1=find(axis_f1_ppm>crop_ranges{1}(2),1); l_bound_f2=find(axis_f2_ppm>crop_ranges{2}(1),1); r_bound_f2=find(axis_f2_ppm>crop_ranges{2}(2),1); % Find the new offsets parameters.offset=[(axis_f1_hz(l_bound_f1)+axis_f1_hz(r_bound_f1))/2 ... (axis_f2_hz(l_bound_f2)+axis_f2_hz(r_bound_f2))/2]; % Find the new sweeps parameters.sweep= [(axis_f1_hz(r_bound_f1)-axis_f1_hz(l_bound_f1)) ... (axis_f2_hz(r_bound_f2)-axis_f2_hz(l_bound_f2))]; % Update the point counts parameters.zerofill=[(r_bound_f1-l_bound_f1) (r_bound_f2-l_bound_f2)]; % Cut the spectrum spec=spec(l_bound_f1:r_bound_f1,l_bound_f2:r_bound_f2); end % There is long term price instability for lanthanides, as most come % from China, but are produced with little regard for the environment % or workers' health. Attempts to improve conditions led to a 3000% % price increase for dysprosium in 2011. % % EPSRC reviewer, on one of IK's grant applications
github
tsajed/nmr-pred-master
mt2hz.m
.m
nmr-pred-master/spinach/kernel/utilities/mt2hz.m
632
utf_8
17ba7e517cbe2183eaf1d8981e8f35f1
% Converts hyperfine couplings from milliTesla to Hz % (linear frequency). Syntax: % % hfc_hz=mt2hz(hfc_mt) % % Arrays of any dimension are supported. % % [email protected] function hfc_hz=mt2hz(hfc_mt) if isnumeric(hfc_mt)&&isreal(hfc_mt) hfc_hz=1e7*2.802495365*hfc_mt; else error('the input argument must be an array of real numbers.'); end end % You know that I write slowly. This is chiefly because I am never % satisfied until I have said as much as possible in a few words, and % writing briefly takes far more time than writing at length. % % Carl Friedrich Gauss
github
tsajed/nmr-pred-master
negligible.m
.m
nmr-pred-master/spinach/kernel/utilities/negligible.m
728
utf_8
fd27a36e877d8ee08925de3155e28ae2
% An aux function determining whether a given object deserves attention % given the tolerance specified. Used in the internal decision making % performed by Spinach kernel functions. Syntax: % % answer=negligible(object,tolerance) % % Parameters: % % object - the object whose significance is to be assessed % % tolerance - significance threshold % % The function returns a logical value. If the object cannot be asses- % ed based on the current heuristics, it is deemed non-negligible. % % [email protected] function answer=negligible(object,tolerance) answer=~significant(object,tolerance); end % It's too bad that stupidity isn't painful. % % Anton Szandor LaVey
github
tsajed/nmr-pred-master
slice_2d.m
.m
nmr-pred-master/spinach/kernel/utilities/slice_2d.m
3,935
utf_8
eb2c5288f45d57eb4b8c17d3cf7c3f1a
% Contour plot slicing utility with non-linear adaptive contour spacing. % Calls plot_3d() and allows slice extraction. Syntax: % % plot_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs) % % The following functions are used to compute contour levels: % % cont_levs_pos=delta(2)*xmax*linspace(0,1,ncont).^k+xmax*delta(1); % cont_levs_neg=delta(2)*xmin*linspace(0,1,ncont).^k+xmin*delta(1); % % where: % % * xmax and xmin are calculated from the spectrum; % % * delta is the minimum and maximum elevation (as a fraction of total % intensity) of the contours above the baseline. A reasonable value % for most 2D spectra is [0.02 0.2 0.02 0.2]. The first pair of num- % bers refers to the positive contours and the second pair to the % negative ones. % % * ncont is the number of contours, a reasonable value is 20. % % * k controls the curvature of the contour spacing function: k=1 % corresponds to linear spacing and k>1 bends the spacing curve to % increase the sampling density near the baseline. A reasonable % value is 2; % % * ncol is a number of colors in the colormap (around 256 is fine); % % * m is the curvature of the colormap: m=1 corresponds to a linear % color ramp into the red for positive contours and into the blue % for negative contours. A reasonable value for high-contrast % plotting is 6. % % * signs can be set to 'positive', 'negative' or 'both' - this will % cause the corresponding contours to be plotted. % % The following subfields are required inthe parameters structure: % % parameters.sweep one or two sweep widths, Hz % % parameters.spins cell array with one ot two character % strings specifying the working spins. % % parameters.offset one or two transmitter offsets, Hz % % parameters.axis_units axis units ('ppm','Hz','Gauss') % % [email protected] function slice_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs) % Do contour plotting subplot(1,3,1); [f2,f1,S]=plot_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs); title('2D spectrum'); drawnow(); % Switch off performance warning warning('off','MATLAB:griddedInterpolant:MeshgridEval2DWarnId'); % Get the spectrum extents spec_min=min(spectrum(:)); spec_max=max(spectrum(:)); % Enter the slicing loop while true() % Record pointer position subplot(1,3,1); [x,y]=ginput(1); % Compute axis grids [F1,F2]=ndgrid(f1,f2); % Create the interpolant S_int=griddedInterpolant(F1,F2,transpose(S),'spline'); % Compute the traces trace_f1=S_int(ones(size(f2))*x,f2); trace_f2=S_int(f1,ones(size(f1))*y); % Call the 1D plotting routine for F1 parameters_f1=parameters; parameters_f1.spins=parameters.spins(1); parameters_f1.offset=parameters.offset(1); parameters_f1.sweep=parameters.sweep(1); parameters_f1.zerofill=parameters.zerofill(1); subplot(1,3,2); plot_1d(spin_system,trace_f1,parameters_f1); set(gca,'YLim',[spec_min spec_max]); title('F1 slice'); drawnow(); % Call the 1D plotting routine for F2 parameters_f2=parameters; if numel(parameters.spins)==2 parameters_f2.spins=parameters.spins(2); end if numel(parameters.offset)==2 parameters_f2.offset=parameters.offset(2); end parameters_f2.sweep=parameters.sweep(2); parameters_f2.zerofill=parameters.zerofill(2); subplot(1,3,3); plot_1d(spin_system,trace_f2,parameters_f2); set(gca,'YLim',[spec_min spec_max]); title('F2 slice'); drawnow(); end end % There's a great deal of difference between an eager man who wants % to read a book and a tired man who wants a book to read. % % Gilbert K. Chesterton
github
tsajed/nmr-pred-master
cgsppm2ang.m
.m
nmr-pred-master/spinach/kernel/utilities/cgsppm2ang.m
873
utf_8
1c7a6d162c1d9ebeedd75e7e374df8b0
% Converts magnetic susceptibility from the cgs-ppm (aka cm^3/mol) units % quoted by quantum chemistry packages into Angstrom^3 units required by % Spinach pseudocontact shift functionality. Syntax: % % ang=cgsppm2ang(cgsppm) % % Arrays of any dimension are supported. % % [email protected] function ang=cgsppm2ang(cgsppm) % Check consistency grumble(cgsppm); % Do the calculation ang=4*pi*1e18*cgsppm/6.02214129e23; end % Consistency enforcement function grumble(cgsppm) if ~isnumeric(cgsppm) error('input must be numeric.'); end end % "What is this thing, anyway?" said the Dean, inspecting the implement in % his hands. "It's called a shovel," said the Senior Wrangler. "I've seen % the gardeners use them. You stick the sharp end in the ground. Then it % gets a bit technical." % % Terry Pratchett
github
tsajed/nmr-pred-master
int_2d.m
.m
nmr-pred-master/spinach/kernel/utilities/int_2d.m
4,987
utf_8
bd928c92987972495dcac0057172802f
% 2D spectral integrator. Calls plot_2d.m and then launches either an % interactive integration procedure (if no range file name is given) % and records the range data into a file, or runs an automatic integ- % ration if the range file name from a previous run is supplied. % Syntax: % % int_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,... % m,signs,filename) % % The following functions are used to compute contour levels: % % cont_levs_pos=delta(2)*xmax*linspace(0,1,ncont).^k+xmax*delta(1); % cont_levs_neg=delta(2)*xmin*linspace(0,1,ncont).^k+xmin*delta(1); % % where: % % * xmax and xmin are calculated from the spectrum; % % * delta is the minimum and maximum elevation (as a fraction of total % intensity) of the contours above the baseline. A reasonable value % for most 2D spectra is [0.02 0.2 0.02 0.2]. The first pair of num- % bers refers to the positive contours and the second pair to the % negative ones. % % * ncont is the number of contours, a reasonable value is 20. % % * k controls the curvature of the contour spacing function: k=1 % corresponds to linear spacing and k>1 bends the spacing curve to % increase the sampling density near the baseline. A reasonable % value is 2; % % * ncol is a number of colors in the colormap (around 256 is fine); % % * m is the curvature of the colormap: m=1 corresponds to a linear % color ramp into the red for positive contours and into the blue % for negative contours. A reasonable value for high-contrast % plotting is 6. % % * signs can be set to 'positive', 'negative' or 'both' - this will % cause the corresponding contours to be plotted. % % The following subfields are required inthe parameters structure: % % parameters.sweep one or two sweep widths, Hz % % parameters.spins cell array with one ot two character % strings specifying the working spins. % % parameters.offset one or two transmitter offsets, Hz % % parameters.axis_units axis units ('ppm','Hz','Gauss') % % [email protected] function int_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs,filename) % Do contour plotting [f2,f1,S]=plot_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs); % Switch off performance warning warning('off','MATLAB:griddedInterpolant:MeshgridEval2DWarnId'); % Check if the file exists if ~exist('filename','var') % Proceed with interactive integration while true() % Report to the user disp('Interactive integration, define the box by clicking on its opposite corners.'); % Record pointer position [corners_x,corners_y]=ginput(2); % Compute axis grids [F1,F2]=ndgrid(f1,f2); % Create the interpolant S_int=griddedInterpolant(F1,F2,transpose(S),'spline'); % Make function handle fhandle=@(x,y)S_int(x,y); % Compute the integral I=integral2(fhandle,corners_x(1),corners_x(2),corners_y(1),corners_y(2),'RelTol',1e-3,'AbsTol',1e-3); % Report to the user disp(['X range: ' num2str(min(corners_x)) ' to ' num2str(max(corners_x))]); disp(['Y range: ' num2str(min(corners_y)) ' to ' num2str(max(corners_y))]); disp(['Integral: ' num2str(abs(I))]); end elseif exist(filename,'file') % Load ranges from file disp('Found the ranges file, integrals:'); load(filename,'ranges'); % Perform automatic integration for n=1:size(ranges,1) %#ok<NODEF> % Get pointer position corners_x=ranges{n,1}; corners_y=ranges{n,2}; % Compute axis grids [F1,F2]=ndgrid(f1,f2); % Create the interpolant S_int=griddedInterpolant(F1,F2,transpose(S),'spline'); % Make function handle fhandle=@(x,y)S_int(x,y); % Compute the integral I=integral2(fhandle,corners_x(1),corners_x(2),corners_y(1),corners_y(2),'RelTol',1e-3,'AbsTol',1e-3); % Report to the user disp(I); end else % Record ranges into a file n=1; while true() % Get mouse input [ranges{n,1},ranges{n,2}]=ginput(2); %#ok<AGROW> % Write the file save(filename,'ranges'); % Give feedback disp(['Recorded X range: ' num2str(min(ranges{n,1})) ' to ' num2str(max(ranges{n,1}))]); disp(['Recorded Y range: ' num2str(min(ranges{n,2})) ' to ' num2str(max(ranges{n,2}))]); % Increment counter n=n+1; end end end % Beware of the person of one book. % % Thomas Aquinas
github
tsajed/nmr-pred-master
fftdiff.m
.m
nmr-pred-master/spinach/kernel/utilities/fftdiff.m
1,136
utf_8
f948aeace36c979e735e35f96a5f920e
% Spectral differentiation kernel. To be used for accurate numerical % differentiation of real signals in the following way: % % derivative=real(fft(ifft(signal).*fftdiff(1,length(signal),1)')); % % [email protected] function kern=fftdiff(order,npoints,dx) if mod(npoints,2)==1 % Kernel for odd point counts kern=ifftshift((2i*pi*((1-npoints)/2:((npoints)/2))/(npoints*dx)).^order); elseif mod(npoints,2)==0 % Kernel for even point counts kern=ifftshift((2i*pi*(((-npoints)/2):((npoints-1)/2))/(npoints*dx)).^order); else % Complain and bomb out error('npoints parameter must be an integer.'); end end % A few people laughed, a few people cried, most people were silent. I re- % membered the line from the Hindu scripture, the Bhagavad-Gita; Vishnu is % trying to persuade the Prince that he should do his duty and, to impress % him, takes on his multi-armed form and says, 'Now I am become Death, the % destroyer of worlds.' I suppose we all thought that, one way or another. % % J. Robert Oppenheimer, about the first atomic detonation
github
tsajed/nmr-pred-master
symmetrize.m
.m
nmr-pred-master/spinach/kernel/utilities/symmetrize.m
1,156
utf_8
8b16385f90dce90c58510d177dff6c2e
% Symmetrizes interaction tensors. This is required to avoid numerical % instabilities associated with small asymmetries during the diagonali- % zation process. Syntax: % % A=symmetrize(spin_system,A) % % [email protected] function A=symmetrize(spin_system,A) % Check consistency grumble(A); % If the asymmetry is significant, make a fuss if norm(A-transpose(A))>spin_system.tols.inter_sym report(spin_system,'WARNING - significant asymmetry detected in a coupling tensor.'); report(spin_system,['WARNING - symmetric part norm: ' num2str(norm((A+A')/2)/(2*pi)) ' Hz']); report(spin_system,['WARNING - antisymmetric part norm: ' num2str(norm((A-A')/2)/(2*pi)) ' Hz']); report(spin_system,'WARNING - the tensor has been symmetrized.'); end % Symmetrize the tensor A=(A+transpose(A))/2; 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 % "Smoking - NO HYDROGEN!" % % A safety warning on Anatole Abragam's door
github
tsajed/nmr-pred-master
hilb2liouv.m
.m
nmr-pred-master/spinach/kernel/utilities/hilb2liouv.m
1,936
utf_8
556ed19d99d4b703f381e73bfc060b88
% Converts Hilbert space operators into Liouville space superoperators % or state vectors. Syntax: % % L=hilb2liouv(H,conv_type) % % Parameters: % % H - a Hilbert space operator % % conv_type - the type of Liouville space superoperator to return: % % 'left' - produces left side product superoperator % % 'right' - produces right side product superoperator % % 'comm' - produces commutation superoperator % % 'acomm' - produces anticommutation superoperator % % 'statevec' - stretches the operator into a state vector % % [email protected] function L=hilb2liouv(H,conv_type) % Check consistency grumble(H,conv_type); % Prepare a unit matrix unit=speye(size(H)); % Decide how to proceed switch conv_type case 'comm' % Compute a commutation superoperator L=kron(unit,H)-kron(transpose(H),unit); case 'acomm' % Compute an anticommutation superoperator L=kron(unit,H)+kron(transpose(H),unit); case 'left' % Compute a left side product superoperator L=kron(unit,H); case 'right' % Compute a right side product superoperator L=kron(transpose(H),unit); case 'statevec' % Stretch into a state vector L=H(:); otherwise % Complain and bomb out error('unknown conversion type specification.'); end end % Consistency enforcement function grumble(H,conv_type) if ~isnumeric(H) error('H parameter must be numeric.'); end if ~ischar(conv_type) error('conv_type parameter must be a character string.'); end end % If it wasn't for the fun and money, I really don't know % why I'd bother. % % Terry Pratchett
github
tsajed/nmr-pred-master
sniff.m
.m
nmr-pred-master/spinach/kernel/utilities/sniff.m
291
utf_8
0056719e033bec102876cb4b3c75644a
% Validates the spin_system object and prints an informative error message % or an informative warning if something is found to be askew. % % [email protected] function sniff(spin_system) %#ok<INUSD> % Remains to be written error('this function is currently empty.'); end
github
tsajed/nmr-pred-master
transfermat.m
.m
nmr-pred-master/spinach/kernel/utilities/transfermat.m
1,129
utf_8
af3fc494152b115d76c46c1c624abfea
% Transfer matrix calculation for linear amplifiers. Syntax: % % T=transfermat(amp_inps,amp_outs) % % Parameters: % % amp_inps - a matrix with amplifier input vectors as columns % % amp_outs - a matrix with amplifier output vectors as columns % % Outputs: % % T - the transfer matrix, such that amp_outs=T*amp_inps % in the least squares sense % % Note: the number of input-output vector pairs should be bigger than % the number of elements in those vectors. % % [email protected] function T=transfermat(amp_inps,amp_outs) % Run the SVD pseudoinverse T=amp_inps\amp_outs; end % "In accordance with the University's disciplinary procedure, I am con- % ducting an investigation into allegations made against you with regard % to entering the Chemistry buildings on multiple occasions during the % University closure period between 17:00 on Wednesday 23rd December 2015 % and 08:00 on Monday 4th January 2016." % % Gill Reid, Head of Southampton Chemistry, % initiating a disciplinary procedure against % IK for working over the Christmas break.
github
tsajed/nmr-pred-master
statmerge.m
.m
nmr-pred-master/spinach/kernel/utilities/statmerge.m
928
utf_8
ec47242d42574198a26c155938884750
% Merges means and standard deviations of the mean for multiple sample sets % into a total mean and total standard deviation of the mean. Syntax: % % [total_mean,total_stdm]=statmerge(means,stdms,npoints) % % Parameters: % % means - a vector of mean values for each sample set % % stdms - a vector of standard deviations of the mean % for each sample set % % npoints - a vector specifying the number of samples in % each sample set % % [email protected] function [total_mean,total_stdm]=statmerge(means,stdms,npoints) % Compute the combined mean total_mean=sum(means.*npoints)/sum(npoints); % Convert stdms to stds stds=stdms.*sqrt(npoints); % Combine stds total_std=sqrt(sum((npoints/sum(npoints)).*(stds.^2))); % Convert std to stdm total_stdm=total_std/sqrt(sum(npoints)); end % Redemption, but not repentance. % % Michael Krug
github
tsajed/nmr-pred-master
summary.m
.m
nmr-pred-master/spinach/kernel/utilities/summary.m
14,385
utf_8
50a2961889419f70d24feb578417241c
% Prints various summaries on behalf of the spin system setup modules % of Spinach kernel. Edits to this function are discouraged. % % [email protected] function summary(spin_system,topic,header) switch topic case 'zeeman' report(spin_system,header); report(spin_system,'=============================================================================================='); report(spin_system,'# Spin 2S+1 Matrix norm(rank0) norm(rank1) norm(rank2) '); report(spin_system,'----------------------------------------------------------------------------------------------'); for n=1:spin_system.comp.nspins if significant(spin_system.inter.zeeman.matrix{n},0) [rank0,rank1,rank2]=mat2sphten(spin_system.inter.zeeman.matrix{n}); report(spin_system,[pad(num2str(n),6) pad(spin_system.comp.isotopes{n},6) pad(num2str(spin_system.comp.mults(n)),6)... num2str(spin_system.inter.zeeman.matrix{n}(1,:),'%+10.3e %+10.3e %+10.3e')]); report(spin_system,[' ' num2str(spin_system.inter.zeeman.matrix{n}(2,:),'%+10.3e %+10.3e %+10.3e')... ' ' pad(num2str(norm(rank0),'%10.4e'),13) pad(num2str(norm(rank1),'%10.4e'),13) num2str(norm(rank2),'%10.4e')]); report(spin_system,[' ' num2str(spin_system.inter.zeeman.matrix{n}(3,:),'%+10.3e %+10.3e %+10.3e')]); if n<spin_system.comp.nspins, report(spin_system,''); end end end report(spin_system,'=============================================================================================='); case 'coordinates' report(spin_system,header); report(spin_system,'======================================'); report(spin_system,'N Spin X Y Z '); report(spin_system,'--------------------------------------'); for n=1:spin_system.comp.nspins report(spin_system,[strjust([num2str(n) blanks(3-length(num2str(n)))],'left') ' '... strjust([spin_system.comp.isotopes{n} blanks(5-length(spin_system.comp.isotopes{n}))],'center') ' '... num2str(spin_system.inter.coordinates{n},'%+5.3f ') ' ' spin_system.comp.labels{n}]); end report(spin_system,'======================================'); case 'pbc' report(spin_system,header); report(spin_system,'==============================='); report(spin_system,' X Y Z '); report(spin_system,'-------------------------------'); for n=1:numel(spin_system.inter.pbc) report(spin_system,[' ' pad(num2str(spin_system.inter.pbc{n}(1),'%+5.3f '),10)... pad(num2str(spin_system.inter.pbc{n}(2),'%+5.3f '),10)... pad(num2str(spin_system.inter.pbc{n}(3),'%+5.3f '),10)]); end report(spin_system,'==============================='); case 'couplings' report(spin_system,header); report(spin_system,'============================================================================================='); report(spin_system,'Spin A Spin B Matrix norm(rank0) norm(rank1) norm(rank2) '); report(spin_system,'---------------------------------------------------------------------------------------------'); [rows,cols,~]=find(cellfun(@norm,spin_system.inter.coupling.matrix)>spin_system.tols.inter_cutoff); for n=1:numel(rows) [rank0,rank1,rank2]=mat2sphten(spin_system.inter.coupling.matrix{rows(n),cols(n)}); report(spin_system,[' ' pad(num2str(rows(n)),6) ' ' pad(num2str(cols(n)),6) ... num2str(spin_system.inter.coupling.matrix{rows(n),cols(n)}(1,:),'%+10.3e %+10.3e %+10.3e')]); report(spin_system,[' ' num2str(spin_system.inter.coupling.matrix{rows(n),cols(n)}(2,:),'%+10.3e %+10.3e %+10.3e')... ' ' pad(num2str(norm(rank0),'%10.4e'),13) pad(num2str(norm(rank1),'%10.4e'),13) num2str(norm(rank2),'%10.4e')]); report(spin_system,[' ' num2str(spin_system.inter.coupling.matrix{rows(n),cols(n)}(3,:),'%+10.3e %+10.3e %+10.3e')]); if n<numel(rows), report(spin_system,''); end end report(spin_system,'============================================================================================='); case 'chemistry' if numel(spin_system.chem.parts)>1 for n=1:numel(spin_system.chem.parts) report(spin_system,['chemical subsystem ' num2str(n) ' contains spins: ' num2str(spin_system.chem.parts{n})]); end report(spin_system,'inter-subsystem reaction rates:'); report(spin_system,'==============================='); report(spin_system,' N(from) N(to) Rate(Hz) '); report(spin_system,'-------------------------------'); [rows,cols,vals]=find(spin_system.chem.rates); for n=1:length(vals) report(spin_system,[' ' strjust([num2str(rows(n)) blanks(3-length(num2str(rows(n))))],'left') ' '... strjust([num2str(cols(n)) blanks(3-length(num2str(cols(n))))],'left') ' '... num2str(vals(n),'%+0.3e')]); end report(spin_system,'==============================='); end [rows,cols,vals]=find(spin_system.chem.flux_rate); if numel(vals)>0 report(spin_system,'point-to-point flux rates:'); report(spin_system,'==============================='); report(spin_system,' N(from) N(to) Rate(Hz) '); report(spin_system,'-------------------------------'); for n=1:length(vals) report(spin_system,[' ' strjust([num2str(rows(n)) blanks(3-length(num2str(rows(n))))],'left') ' '... strjust([num2str(cols(n)) blanks(3-length(num2str(cols(n))))],'left') ' '... num2str(vals(n),'%+0.3e')]); end end case 'rlx_rates_t1_t2' report(spin_system,header); report(spin_system,'========================================'); report(spin_system,'N Spin R1 R2 '); report(spin_system,'----------------------------------------'); for n=1:spin_system.comp.nspins report(spin_system,[strjust([num2str(n) blanks(3-length(num2str(n)))],'left') ' '... strjust([spin_system.comp.isotopes{n} blanks(5-length(spin_system.comp.isotopes{n}))],'center') ' '... num2str(spin_system.rlx.r1_rates(n),'%+0.5e ') ' '... num2str(spin_system.rlx.r2_rates(n),'%+0.5e ') ' '... spin_system.comp.labels{n}]); end report(spin_system,'========================================'); case 'rlx_rates_lindblad' report(spin_system,header); report(spin_system,'========================================'); report(spin_system,'N Spin R1 R2 '); report(spin_system,'----------------------------------------'); for n=1:spin_system.comp.nspins report(spin_system,[strjust([num2str(n) blanks(3-length(num2str(n)))],'left') ' '... strjust([spin_system.comp.isotopes{n} blanks(5-length(spin_system.comp.isotopes{n}))],'center') ' '... num2str(spin_system.rlx.lind_r1_rates(n),'%+0.5e ') ' '... num2str(spin_system.rlx.lind_r2_rates(n),'%+0.5e ') ' '... spin_system.comp.labels{n}]); end report(spin_system,'========================================'); case 'rlx_rates_nott' report(spin_system,' '); report(spin_system,'=== Nottingham DNP relaxation theory ==='); report(spin_system,['Electron R1: ' num2str(spin_system.rlx.nott_r1e) ' Hz']); report(spin_system,['Electron R2: ' num2str(spin_system.rlx.nott_r2e) ' Hz']); report(spin_system,['Nuclear R1: ' num2str(spin_system.rlx.nott_r1n) ' Hz']); report(spin_system,['Nuclear R2: ' num2str(spin_system.rlx.nott_r2n) ' Hz']); report(spin_system,'========================================'); case 'rlx_rates_weiz' report(spin_system,' '); report(spin_system,'==== Weizmann DNP relaxation theory ===='); report(spin_system,['Electron R1: ' num2str(spin_system.rlx.weiz_r1e) ' Hz']); report(spin_system,['Electron R2: ' num2str(spin_system.rlx.weiz_r2e) ' Hz']); report(spin_system,['Nuclear R1: ' num2str(spin_system.rlx.weiz_r1n) ' Hz']); report(spin_system,['Nuclear R2: ' num2str(spin_system.rlx.weiz_r2n) ' Hz']); [rows,cols,vals]=find(spin_system.rlx.weiz_r1d); for n=1:numel(vals) report(spin_system,['Inter-nuclear dipolar R1(' num2str(rows(n)) ',' num2str(cols(n)) '): ' num2str(vals(n)) ' Hz']); end [rows,cols,vals]=find(spin_system.rlx.weiz_r2d); for n=1:numel(vals) report(spin_system,['Inter-nuclear dipolar R2(' num2str(rows(n)) ',' num2str(cols(n)) '): ' num2str(vals(n)) ' Hz']); end report(spin_system,'========================================'); case 'symmetry' report(spin_system,header); report(spin_system,'====================='); report(spin_system,' Group Spins '); report(spin_system,'---------------------'); for n=1:length(spin_system.comp.sym_spins) report(spin_system,[' ' spin_system.comp.sym_group{n} ' ' num2str(spin_system.comp.sym_spins{n})]); end report(spin_system,'====================='); case 'basis' nstates=size(spin_system.bas.basis,1); if nstates > spin_system.tols.basis_hush report(spin_system,['over ' num2str(spin_system.tols.basis_hush) ' states in the basis - printing suppressed.']); else report(spin_system,'final basis set summary (L,M quantum numbers in irreducible spherical tensor products).') report(spin_system,['N ' blanks(length(num2str(spin_system.comp.nspins))) num2str(1:spin_system.comp.nspins,['%d ' blanks(7-length(num2str(spin_system.comp.nspins)))])]); for n=1:nstates current_line=blanks(7+8*spin_system.comp.nspins); spin_number=num2str(n); current_line(1:length(spin_number))=spin_number; for k=1:spin_system.comp.nspins [L,M]=lin2lm(spin_system.bas.basis(n,k)); current_line(7+8*(k-1)+1)='('; current_line(7+8*(k-1)+2)=num2str(L); current_line(7+8*(k-1)+3)=','; proj=num2str(M); switch length(proj) case 1 current_line(7+8*(k-1)+4)=proj; current_line(7+8*(k-1)+5)=')'; case 2 current_line(7+8*(k-1)+4)=proj(1); current_line(7+8*(k-1)+5)=proj(2); current_line(7+8*(k-1)+6)=')'; end end report(spin_system,current_line); end report(spin_system,' '); end report(spin_system,['state space dimension ' num2str(nstates) ' (' num2str(100*nstates/(prod(spin_system.comp.mults)^2)) '% of the full state space).']); otherwise error('unknown topic.'); end end % 1: Blessed are the strong, for they shall possess the earth -- cursed are % the weak, for they shall inherit the yoke. % % 2: Blessed are the powerful, for they shall be reverenced among men -- % cursed are the feeble, for they shall be blotted out. % % 3: Blessed are the bold, for they shall be masters of the world -- cursed % are the humble, for they shall be trodden under hoofs. % % 4: Blessed are the victorious, for victory is the basis of right -- % cursed are the vanquished, for they shall be vassals forever. % % 5: Blessed are the iron-handed, for the unfit shall flee before them -- % cursed are the poor in spirit, for they shall be spat upon. % % 6: Blessed are the death-defiant, for their days shall be long in the % lands -- cursed are the gazers toward a richer life beyond the grave, for % they shall perish amidst plenty. % % 7: Blessed are the destroyers of false hope, for they are true Messiahs -- % cursed are the God-adorers, for they shall be shorn sheep. % % 8: Blessed are the valiant, for they shall obtain great treasure -- % cursed are the believers in good and evil, for they are frightened by % shadows. % % 9: Blessed are those who believe in what is best for them, for never % shall their minds be terrorized -- cursed are the "lambs of God", for % they shall be bled whiter than snow. % % 10: Blessed is the man who has a sprinkling of enemies, for they shall % make him a hero -- cursed is he who doeth good unto others who sneer upon % him in return, for he shall be despised. % % 11: Blessed are the mighty-minded, for they shall ride the whirlwinds -- % cursed are they who teach lies for truth and truth for lies, for they are % an abomination. % % 12: Thrice cursed are the weak whose insecurity makes them vile, for they % shall serve and suffer. % % 13: The angel of self-deceit is camped in the souls of the "righteous" -- % the eternal flame of power through joy dwelleth within the flesh of a % Satanist. % % Anton Szandor LaVey, "Satanic Bible"
github
tsajed/nmr-pred-master
stitch.m
.m
nmr-pred-master/spinach/kernel/utilities/stitch.m
1,833
utf_8
84bb801d963fcb263c39896f7818bab0
% Stitching function for bidirectionally propagated 3D experiments. Syntax: % % fid=stitch(spin_system,L,rho_stack,coil_stack,mtp_oper,mtp_time,t1,t2,t3) % % Parameters: % % L - spin system Liouvillian % % rho_stack - state vector stack from the forward part of % the simulation % % coil_stack - coil vector stack from the backward part of % the sumulation % % mtp_oper - operator for the pulse to be executed in the % middle of the t2 period % % mtp_time - duration for the pulse to be executed in the % middle of the t2 period % % t1.nsteps - number of time steps in t1 % % t2.nsteps - number of time steps in t2 % % t3.nsteps - number of time steps in t3 % % The function returns the three-dimensional free induction decay. % % [email protected] function fid=stitch(spin_system,L,rho_stack,coil_stack,mtp_oper,mtp_time,t1,t2,t3) % Preallocate the fid fid=zeros(t3.nsteps,t2.nsteps,t1.nsteps); % Run the reduction without splitting the space spin_system.sys.disable={'pt','symmetry'}; P=reduce(spin_system,L+mtp_oper,[rho_stack coil_stack]); rho_stack=P{1}'*rho_stack; coil_stack=P{1}'*coil_stack; L=P{1}'*L*P{1}; mtp_oper=P{1}'*mtp_oper*P{1}; % Compute propagators P_forw=propagator(spin_system,L,t2.timestep/2); P_back=P_forw'; P_mtp=propagator(spin_system,mtp_oper,mtp_time); % Stitch the trajectories for k=1:t2.nsteps report(spin_system,['stitching forward and backward trajectories, step '... num2str(k) '/' num2str(t2.nsteps) '...']); fid(:,k,:)=coil_stack'*P_mtp*rho_stack; rho_stack=P_forw*rho_stack; coil_stack=P_back*coil_stack; end end % A wolf hates both men and dogs, but dogs he hates more. % % Sergey Dovlatov
github
tsajed/nmr-pred-master
dcm2euler.m
.m
nmr-pred-master/spinach/kernel/utilities/dcm2euler.m
3,633
utf_8
f2bce8038fb9fdf1403774d9accce78a
% Converts DCM into Euler angles (Varshalovich B convention). Syntax: % % [alpha,beta,gamma]=dcm2euler(dcm) % % OR % % angles=dcm2euler(dcm) % % In the latter case, anglews is a row vector containing the three Euler % angles, ordered as [alpha beta gamma]. % % Note: The problem of recovering Euler angles from a DCM is in general % ill-posed. The function below is a product of very considerable amount % of thought and has has passed rigorous testing. In all cases it either % returns a correct answer or gives an informative error message. % % [email protected] function [arg1,arg2,arg3]=dcm2euler(dcm) % Check consistency grumble(dcm); % Get the beta angle out and wrap it into [0,pi] beta=mod(acos(dcm(3,3)),pi); % Do a brute force surface scan with respect to alpha and gamma alphas=pi*linspace(0.05,1.95,20); gammas=pi*linspace(0.05,1.95,20); n_min=1; k_min=1; err_min=1; for n=1:20 for k=1:20 err_current=norm(euler2dcm(alphas(n),beta,gammas(k))-dcm); if err_current<err_min n_min=n; k_min=k; err_min=err_current; end end end alpha=alphas(n_min); gamma=gammas(k_min); % Run the optimization on alpha and gamma options=optimset('Display','off','LargeScale','off','TolX',1e-12,'TolFun',1e-12); answer=fminunc(@(angles)norm(euler2dcm(angles(1),beta,angles(2))-dcm),[alpha gamma],options); alpha=answer(1); gamma=answer(2); % Wrap both angles into [0,2*pi] alpha=mod(alpha,2*pi); gamma=mod(gamma,2*pi); % Make sure the result is good enough and bomb out if it's not if norm(dcm-euler2dcm(alpha,beta,gamma))>1e-3 disp(dcm); disp(euler2dcm(alpha,beta,gamma)); error('DCM to Euler conversion failed.'); end % Adapt to the output style if nargout==1||nargout==0 arg1=[alpha beta gamma]; elseif nargout==3 arg1=alpha; arg2=beta; arg3=gamma; else error('incorrect number of output arguments.'); end end % Consistency enforcement function grumble(dcm) if (~isnumeric(dcm))||(~isreal(dcm))||(~all(size(dcm)==[3 3])) error('DCM must be a real 3x3 matrix.'); end if norm(dcm'*dcm-eye(3))>1e-6 warning('DCM is not orthogonal to 1e-6 tolerance - conversion accuracy not guaranteed.'); end if norm(dcm'*dcm-eye(3))>1e-2 error('DCM is not orthogonal to 1e-2 tolerance, cannot proceed with conversion.'); end if abs(det(dcm)-1)>1e-6 warning('DCM determinant is not unit to 1e-6 tolerance - conversion accuracy not guaranteed.'); end if abs(det(dcm)-1)>1e-2 error('DCM determinant is not unit to 1e-2 tolerance, cannot proceed with conversion.'); end end % I would give the greatest sunset in the world for one sight of New York's % skyline. Particularly when one can't see the details. Just the shapes. The % shapes and the thought that made them. The sky over New York and the will % of man made visible. What other religion do we need? And then people tell % me about pilgrimages to some dank pesthole in a jungle where they go to do % homage to a crumbling temple, to a leering stone monster with a pot belly, % created by some leprous savage. Is it beauty and genius they want to see? % Do they seek a sense of the sublime? Let them come to New York, stand on % the shore of the Hudson, look and kneel. When I see the city from my win- % dow - no, I don't feel how small I am - but I feel that if a war came to % threaten this, I would like to throw myself into space, over the city, and % protect these buildings with my body. % % Ayn Rand, "The Fountainhead"
github
tsajed/nmr-pred-master
zfs2mat.m
.m
nmr-pred-master/spinach/kernel/utilities/zfs2mat.m
675
utf_8
bfd8d9fb23298f193e2eff0e0d2a0506
% Converts D and E zero-field splitting parameters to a diagonal matrix. % % [email protected] function M=zfs2mat(D,E) % Compute the matrix M=[-D/3+E, 0, 0; 0, -D/3-E, 0; 0, 0, 2*D/3]; end % To watch the courageous Afghan freedom fighters battle modern % arsenals with simple hand-held weapons is an inspiration to % those who love freedom. Their courage teaches us a great lesson - % that there are things in this world worth defending. To the Afghan % people, I say on behalf of all Americans that we admire your % heroism, your devotion to freedom, and your relentless struggle % against your oppressors. % % Ronald Reagan, 21 March 1983
github
tsajed/nmr-pred-master
anax2quat.m
.m
nmr-pred-master/spinach/kernel/utilities/anax2quat.m
1,614
utf_8
83ed77433dd697e4a85418a9f85c4821
% Converts angle-axis rotation parameters into a quaternion. Syntax: % % q=anax2quat(rot_axis,rot_angle) % % Arguments: % % rot_axis - cartesian direction vector given as a row or column % with three real elements % % rot_angle - rotation angle in radians % % Output: a structure with four fields q.u, q.i, q.j, q.k giving the % four components of the quaternion. % % [email protected] % [email protected] function q=anax2quat(rot_axis,rot_angle) % Check consistency grumble(rot_axis,rot_angle); % Normalize the axis vector rot_axis=rot_axis/norm(rot_axis,2); % Compute the quaternion q.u=cos(rot_angle/2); q.i=rot_axis(1)*sin(rot_angle/2); q.j=rot_axis(2)*sin(rot_angle/2); q.k=rot_axis(3)*sin(rot_angle/2); end % Consistency enforcement function grumble(rot_axis,rot_angle) if (~isnumeric(rot_axis))||(~isnumeric(rot_angle)) error('both inputs must be numeric.'); end if any(~isreal(rot_axis))||any(~isreal(rot_angle)) error('both inputs must be real.'); end if numel(rot_axis)~=3 error('direction vector must have three real elements.'); end if numel(rot_angle)~=1 error('rotation angle must be a real number.'); end end % Many lecture videos in IK's Spin Dynamics course (http://spindynamics.org) % look far too smooth and orderly for something that requires ten boardfuls % of dense mathematics. In the actual reality, the subject is very hard to % read and neat lecture videos were in a few cases assembled piecewise from % half a dozen partially successful attempts.
github
tsajed/nmr-pred-master
eeqq2nqi.m
.m
nmr-pred-master/spinach/kernel/utilities/eeqq2nqi.m
1,585
utf_8
3005ecba9c3aa49523259107f5c61e94
% Converts the C_q and eta_q quadrupolar interaction specification con- % vention into a 3x3 interaction matrix in Hz. Usage: % % Q=eeqq2nqi(C_q,eta_q,I,euler_angles) % % where C_q is the quadrupolar coupling constant (Hz), eta_q is the quad- % rupolar tensor asymmetry parameter, I is the spin quantum number and % the last parameter is a vector of three Euler angles in radians, giving % the orientation of the principal axis frame relative to the lab frame. % % [email protected] function Q=eeqq2nqi(C_q,eta_q,I,eulers) % Check consistency grumble(C_q,eta_q,I,eulers); % Get the eigenvalues XX=-C_q*(1-eta_q)/(4*I*(2*I-1)); YY=-C_q*(1+eta_q)/(4*I*(2*I-1)); ZZ=+C_q/(2*I*(2*I-1)); % Get the rotation matrix R=euler2dcm(eulers); % Get the quadrupole tensor matrix Q=R*diag([XX YY ZZ])*R'; end % Consistency enforcement function grumble(C_q,eta_q,I,eulers) if (~isnumeric(C_q))||(~isnumeric(eta_q))||(~isnumeric(I))||(~isnumeric(eulers)) error('all inputs must be numeric.'); end if (~isreal(C_q))||(~isreal(eta_q))||(~isreal(I))||(~isreal(eulers)) error('all inputs must be real.'); end if numel(eulers)~=3 error('eulers vector must have three elements.'); end if (numel(C_q)~=1)||(numel(eta_q)~=1) error('C_a and eta_q arguments must have a single element.'); end if (numel(I)~=1)||(I<1)||(mod(2*I+1,1)~=0) error('I must be an integer or half-integer greater or equal to 1.'); end end % A true man does what he will, not what he must. % % George R.R. Martin, "Game of Thrones"
github
tsajed/nmr-pred-master
fdhess.m
.m
nmr-pred-master/spinach/kernel/utilities/fdhess.m
2,749
utf_8
09491c4660d70ff587b791bda12c8f13
% Returns the finite-difference Hessian of a 3D array using a finite % difference scheme with a user-specified number of stencil points. % The dimensions of the 3D array are assumed to be ordered as [X Y Z]. % Syntax: % H=fdhess(A,npoints) % % where the second parameter specifies the number of points in the % finite difference stencil that should be used. The result is a 3x3 % cell array of 3D matrices ordered in the following way: % % {d2A_dxdx d2A_dxdy d2A_dxdz % d2A_dydx d2A_dydy d2A_dydz % d2A_dzdx d2A_dzdy d2A_dzdz} % % Periodic boundary condition is used. % % [email protected] function H=fdhess(A,npoints) % Check consistency grumble(A,npoints); % Compute derivatives d2A_dzdz=reshape(kron(kron(fdmat(size(A,3),npoints,2),speye(size(A,2))),speye(size(A,1)))*A(:),size(A)); d2A_dzdy=reshape(kron(kron(fdmat(size(A,3),npoints,1),fdmat(size(A,2),npoints,1)),speye(size(A,1)))*A(:),size(A)); d2A_dzdx=reshape(kron(kron(fdmat(size(A,3),npoints,1),speye(size(A,2))),fdmat(size(A,1),npoints,1))*A(:),size(A)); d2A_dydz=reshape(kron(kron(fdmat(size(A,3),npoints,1),fdmat(size(A,2),npoints,1)),speye(size(A,1)))*A(:),size(A)); d2A_dydy=reshape(kron(kron(speye(size(A,3)),fdmat(size(A,2),npoints,2)),speye(size(A,1)))*A(:),size(A)); d2A_dydx=reshape(kron(kron(speye(size(A,3)),fdmat(size(A,2),npoints,1)),fdmat(size(A,1),npoints,1))*A(:),size(A)); d2A_dxdz=reshape(kron(kron(fdmat(size(A,3),npoints,1),speye(size(A,2))),fdmat(size(A,1),npoints,1))*A(:),size(A)); d2A_dxdy=reshape(kron(kron(speye(size(A,3)),fdmat(size(A,2),npoints,1)),fdmat(size(A,1),npoints,1))*A(:),size(A)); d2A_dxdx=reshape(kron(kron(speye(size(A,3)),speye(size(A,2))),fdmat(size(A,1),npoints,2))*A(:),size(A)); % Form the Hessian array H={d2A_dxdx d2A_dxdy d2A_dxdz; d2A_dydx d2A_dydy d2A_dydz; d2A_dzdx d2A_dzdy d2A_dzdz}; end % Consistency enforcement function grumble(A,npoints) if (~isnumeric(A))||(ndims(A)~=0) error('A must be a three-dimensional numeric array.'); end if any(size(A)<npoints) error('the dimension of A is not big enough for the finite difference stencil specified.'); end if (mod(npoints,1)~=0)||(mod(npoints,2)~=1)||(npoints<3) error('the number of stencil points must be an odd integer greater than 3.'); end end % Take therefore the talent from him, and give it unto him which % hath ten talents. For unto every one that hath shall be given, % and he shall have abundance: but from him that hath not shall % be taken away even that which he hath. And cast ye the unprofi- % table servant into outer darkness: there shall be weeping and % gnashing of teeth. % % Matthew 25:28-30
github
tsajed/nmr-pred-master
lin2lmn.m
.m
nmr-pred-master/spinach/kernel/utilities/lin2lmn.m
1,576
utf_8
5a211d633afeebf95469bc76ed88602c
% Converts linear indexing specification of a Wigner function to L,M,N % indexing. 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: % % [L,M,N]=lin2lmn(I) % % Wigner functions are enumerated using one base indexing, that is: % % I=1 -> (L=0,M=0,N=0) % I=2 -> (L=1,M=1,N=1) % I=3 -> (L=1,M=1,N=0), et cetera... % % Arrays of any dimension are accepted as arguments. % % [email protected] function [L,M,N]=lin2lmn(I) % Check consistency grumble(I); % Get the rank big_root=(27*I+sqrt(729*I.^2-3)).^(1/3); L=ceil((3^(1/3)+big_root.^2)./(2*(3^(2/3))*big_root)-1); % Get the left index rank_page_position=I-(4*L.^3-L)/3-1; M=L-fix(rank_page_position./(2*L+1)); % Get the right index N=L+(2*L+1).*(L-M)-rank_page_position; % Make sure the conversion is correct if nnz(lmn2lin(L,M,N)~=I)>0 error('IEEE arithmetic breakdown, please contact the developer.'); end end % Consistency enforcement function grumble(I) if (~isnumeric(I))||(~isreal(I))||any(mod(I(:),1)~=0)||any(I(:)<1) error('all elements of the input array must be positive integers.'); end end % Who gave you the authority to decide which colour % Spinach logo was going to be? % % Kelly-Anne Ferguson to IK, in April 2011.
github
tsajed/nmr-pred-master
plot_2d.m
.m
nmr-pred-master/spinach/kernel/utilities/plot_2d.m
9,638
utf_8
b32c60c0d4222dc37608d9a3c1723425
% Contour plotting utility with non-linear adaptive contour spacing. The % function is useful for NMR data where small cross-peaks must be adequa- % tely contoured next to large diagonal peaks. Syntax: % % plot_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs) % % The following functions are used to compute contour levels: % % cont_levs_pos=delta(2)*xmax*linspace(0,1,ncont).^k+xmax*delta(1); % cont_levs_neg=delta(2)*xmin*linspace(0,1,ncont).^k+xmin*delta(1); % % where: % % * xmax and xmin are calculated from the spectrum; % % * delta is the minimum and maximum elevation (as a fraction of total % intensity) of the contours above the baseline. A reasonable value % for most 2D spectra is [0.02 0.2 0.02 0.2]. The first pair of num- % bers refers to the positive contours and the second pair to the % negative ones. % % * ncont is the number of contours, a reasonable value is 20. % % * k controls the curvature of the contour spacing function: k=1 % corresponds to linear spacing and k>1 bends the spacing curve to % increase the sampling density near the baseline. A reasonable % value is 2; % % * ncol is a number of colors in the colormap (around 256 is fine); % % * m is the curvature of the colormap: m=1 corresponds to a linear % color ramp into the red for positive contours and into the blue % for negative contours. A reasonable value for high-contrast % plotting is 6. % % * signs can be set to 'positive', 'negative' or 'both' - this will % cause the corresponding contours to be plotted. % % The following subfields are required inthe parameters structure: % % parameters.sweep one or two sweep widths, Hz % % parameters.spins cell array with one ot two character % strings specifying the working spins. % % parameters.offset one or two transmitter offsets, Hz % % parameters.axis_units axis units ('ppm','Hz','Gauss') % % [email protected] function [axis_f1,axis_f2,spectrum]=plot_2d(spin_system,spectrum,parameters,ncont,delta,k,ncol,m,signs) % Set common defaults parameters=defaults(spin_system,parameters); % Check consistency grumble(spectrum,parameters,ncont,delta,k,ncol,m,signs); % Inform the user report(spin_system,'plotting...'); % If a complex spectrum is received, plot both components if nnz(imag(spectrum))>0 % Recursively plot the real part subplot(1,2,1); plot_2d(spin_system,real(spectrum),parameters,ncont,delta,k,ncol,m,signs); title('Real part of the complex spectrum.'); % Recursively plot the imaginary part subplot(1,2,2); plot_2d(spin_system,imag(spectrum),parameters,ncont,delta,k,ncol,m,signs); title('Imaginary part of the complex spectrum.'); return end % Determine data extents xmax=max(spectrum(:)); xmin=min(spectrum(:)); % Compute contour levels if (xmax>0)&&(strcmp(signs,'positive')||strcmp(signs,'both')) positive_contours=delta(2)*xmax*linspace(0,1,ncont).^k+xmax*delta(1); else positive_contours=[]; end if (xmin<0)&&(strcmp(signs,'negative')||strcmp(signs,'both')) negative_contours=delta(4)*xmin*linspace(0,1,ncont).^k+xmin*delta(3); else negative_contours=[]; end contours=[negative_contours(end:-1:1) positive_contours]; % Accommodate homonuclear 2D sequences if numel(parameters.spins)==1, parameters.spins=[parameters.spins parameters.spins]; end if numel(parameters.offset)==1, parameters.offset=[parameters.offset parameters.offset]; end if numel(parameters.sweep)==1, parameters.sweep=[parameters.sweep parameters.sweep]; end % Build axes and apply offsets axis_f1=linspace(-parameters.sweep(1)/2,parameters.sweep(1)/2,size(spectrum,2))+parameters.offset(1); axis_f2=linspace(-parameters.sweep(2)/2,parameters.sweep(2)/2,size(spectrum,1))+parameters.offset(2); % Convert the units switch parameters.axis_units case 'ppm' axis_f1=1000000*(2*pi)*axis_f1/(spin(parameters.spins{1})*spin_system.inter.magnet); axis_f2=1000000*(2*pi)*axis_f2/(spin(parameters.spins{2})*spin_system.inter.magnet); axis_f1_label=['F1: ' parameters.spins{1} ' chemical shift / ppm']; axis_f2_label=['F2: ' parameters.spins{2} ' chemical shift / ppm']; case 'Gauss' axis_f1=10000*(spin_system.inter.magnet-2*pi*axis_f1/spin('E')); axis_f2=10000*(spin_system.inter.magnet-2*pi*axis_f2/spin('E')); axis_f1_label='F1: magnetic induction / Gauss'; axis_f2_label='F2: magnetic induction / Gauss'; case 'Hz' axis_f1=1*axis_f1+0; axis_f2=1*axis_f2+0; axis_f1_label=['F1: ' parameters.spins{1} ' linear frequency / Hz']; axis_f2_label=['F2: ' parameters.spins{2} ' linear frequency / Hz']; case 'kHz' axis_f1=0.001*axis_f1+0; axis_f2=0.001*axis_f2+0; axis_f1_label=['F1: ' parameters.spins{1} ' linear frequency / kHz']; axis_f2_label=['F2: ' parameters.spins{2} ' linear frequency / kHz']; case 'MHz' axis_f1=0.000001*axis_f1+0; axis_f2=0.000001*axis_f2+0; axis_f1_label=['F1: ' parameters.spins{1} ' linear frequency / MHz']; axis_f2_label=['F2: ' parameters.spins{2} ' linear frequency / MHz']; case 'points' axis_f1=1:size(spectrum,2); axis_f2=1:size(spectrum,1); axis_f1_label=['F1: ' parameters.spins{1} ' linear frequency / points']; axis_f2_label=['F2: ' parameters.spins{2} ' linear frequency / points']; otherwise error('unknown axis units.'); end % Plot the spectrum spectrum=transpose(spectrum); contour(axis_f2,axis_f1,spectrum,contours); % Invert the axes set(gca,'XDir','reverse','YDir','reverse'); % Label the axes xlabel(axis_f2_label); ylabel(axis_f1_label); % Colour the contours if any(positive_contours)&&any(negative_contours) plot_range=max(abs(positive_contours))+max(abs(negative_contours)); nredcont=ceil(ncol*max(abs(positive_contours))/plot_range); nbluecont=ceil(ncol*max(abs(negative_contours))/plot_range); elseif any(positive_contours) plot_range=max(abs(positive_contours)); nbluecont=0; nredcont=ceil(ncol*max(abs(positive_contours))/plot_range); elseif any(negative_contours) plot_range=max(abs(negative_contours)); nredcont=0; nbluecont=ceil(ncol*max(abs(negative_contours))/plot_range); else error('spectrum contouring produced no contours.'); end colors=0.9*(1-[linspace(1,0,nbluecont)' linspace(1,0,nbluecont)' linspace(0,0,nbluecont)'; linspace(0,0,nredcont)' linspace(0,1,nredcont)' linspace(0,1,nredcont)']).^m; colormap(gca,colors); % Draw the color bar if ~ismember('colorbar',spin_system.sys.disable) colorbar(gca,'southoutside'); end end % Default parameters function parameters=defaults(spin_system,parameters) if ~isfield(parameters,'offset') report(spin_system,'parameters.offset field not set, assuming zero offsets.'); parameters.offset=zeros(size(parameters.spins)); end if ~isfield(parameters,'axis_units') report(spin_system,'parameters.axis_units field not set, assuming ppm.'); parameters.axis_units='ppm'; end end % Consistency enforcement function grumble(spectrum,parameters,ncont,delta,k,ncol,m,signs) if (~isnumeric(spectrum))||(~ismatrix(spectrum)) error('spectrum must be a matrix.'); end if (~isfield(parameters,'offset')) error('offsets should be specified in parameters.offset variable.'); end if (numel(parameters.offset)~=1)&&(numel(parameters.offset)~=2) error('parameters.offset array should have one or two elements.'); end if ~isfield(parameters,'sweep') error('sweep widths should be specified in parameters.sweep variable.'); end if (numel(parameters.sweep)~=1)&&(numel(parameters.sweep)~=2) error('parameters.sweep array should have one or two elements.'); end if ~isfield(parameters,'axis_units') error('axis units must be specified in parameters.axis_units variable.'); end if ~ischar(parameters.axis_units) error('parameters.axis_units must be a character string.'); end if ~isfield(parameters,'spins') error('working spins should be specified in parameters.spins variable.'); end if ~iscell(parameters.spins) error('parameters.spins should be a cell array of character strings.'); end if (numel(parameters.spins)~=1)&&(numel(parameters.spins)~=2) error('parameters.spins cell array should have one or two elements.'); end if (~isnumeric(ncont))||(~isscalar(ncont))||(~isreal(ncont))||(ncont<1)||(mod(ncont,1)~=0) error('ncont parameter must be a positive integer.'); end if (~isnumeric(delta))||(numel(delta)~=4)||(~isreal(delta))||any(delta>1)||any(delta<0) error('delta parameter must be a vector with four real elements between 0 and 1.'); end if (~isnumeric(k))||(~isscalar(k))||(~isreal(k))||(k<1)||(mod(k,1)~=0) error('k parameter must be a positive integer.'); end if (~isnumeric(ncol))||(~isscalar(ncol))||(~isreal(ncol))||(ncol<1)||(mod(ncol,1)~=0) error('ncol parameter must be a positive integer.'); end if (~isnumeric(m))||(~isscalar(m))||(~isreal(m))||(m<1)||(mod(m,1)~=0) error('m parameter must be a positive integer.'); end if ~ischar(signs) error('signs parameter must be a character string.'); end end % After all, every murderer when he kills runs the risk of the most % dreadful of deaths, whereas those who kill him risk nothing except % promotion. % % Albert Camus
github
tsajed/nmr-pred-master
fourlap.m
.m
nmr-pred-master/spinach/kernel/utilities/fourlap.m
2,800
utf_8
157eedbb5c7cb559daf36c67a408cd8f
% Returns a Fourier spectral representation of the Laplacian acting % on a 3D data array. Syntax: % % L=fourlap(npoints,extents) % % The following parameters are needed: % % npoints - a three-element vector specifying the number of % discretization points in each dimension of the % 3D cube of data that the operator will be acting % on, ordered as [X Y Z]. % % extents - a three-element vector specifying axis extents, % ordered as [X Y Z]. % % The resulting operator is a sparse matrix designed to act on the vec- % torization of rho. The dimensions of rho are assumed to be ordered % as [X Y Z]. % % Note: periodic boundary conditions. % % [email protected] function L=fourlap(npoints,extents) % Check consistency grumble(npoints,extents); % Decide the dimensionality switch numel(npoints) case 1 % Get differentiation matrices [~,Dxx]=fourdif(npoints(1),2); % Normalize differentiation matrices Dxx=(2*pi/extents(1))^2*Dxx; % Compute the Laplacian L=Dxx; case 2 % Get differentiation matrices [~,Dxx]=fourdif(npoints(1),2); [~,Dyy]=fourdif(npoints(2),2); % Normalize differentiation matrices Dxx=(2*pi/extents(1))^2*Dxx; Dyy=(2*pi/extents(2))^2*Dyy; % Compute the Laplacian L=kron(Dyy,speye(npoints(1)))+... kron(speye(npoints(2)),Dxx); case 3 % Get differentiation matrices [~,Dxx]=fourdif(npoints(1),2); [~,Dyy]=fourdif(npoints(2),2); [~,Dzz]=fourdif(npoints(3),2); % Normalize differentiation matrices Dxx=(2*pi/extents(1))^2*Dxx; Dyy=(2*pi/extents(2))^2*Dyy; Dzz=(2*pi/extents(3))^2*Dzz; % Compute the Laplacian L=kron(kron(Dzz,speye(npoints(2))),speye(npoints(1)))+... kron(kron(speye(npoints(3)),Dyy),speye(npoints(1)))+... kron(kron(speye(npoints(3)),speye(npoints(2))),Dxx); otherwise % Complain and bomb out error('incorrect number of spatial dimensions.'); end end % Consistency enforcement function grumble(npoints,extents) if (~isnumeric(npoints))||(~isreal(npoints))||(any(npoints<1))||any(mod(npoints,1)~=0) error('npoints must be a three-element vector of positive integers.'); end if (~isnumeric(extents))||(~isreal(extents))||(any(extents<=0)) error('extents must be an array of positive real numbers.'); end end % Of course it's the same old story. Truth usually % is the same old story. % % Margaret Thatcher
github
tsajed/nmr-pred-master
isworkernode.m
.m
nmr-pred-master/spinach/kernel/utilities/isworkernode.m
398
utf_8
10a12b853eccd04cb1a4ece6e3df423f
% Returns true if executed inside a parfor or spmd block. % % [email protected] function answer=isworkernode() % Best way I could find answer=~isempty(getCurrentTask()); end % In the beginning the Universe was created. This has % made a lot of people very angry and been widely re- % garded as a bad move. % % Douglas Adams, "Hitchhiker's Guide to the Galaxy"
github
tsajed/nmr-pred-master
dilute.m
.m
nmr-pred-master/spinach/kernel/utilities/dilute.m
1,806
utf_8
e2128851d16aa1146bc8ce719b137191
% Splits the spin system into several independent subsystems, each % containing only one instance of a user specified isotope that is % deemed "dilute". All spin system data is updated accordingly and % basis set information, if found, is destroyed. Syntax: % % spin_systems=dilute(spin_system,isotope) % % where isotope is a character string specifying the isotope to be % treated as dilute. A cell array of spin_system objects is retur- % ned, with each cell corresponding to one of the newly formed in- % dependent isotopomers. % % [email protected] % [email protected] function spin_systems=dilute(spin_system,isotope) % Check consistency grumble(isotope); % Inform the user report(spin_system,['treating ' isotope ' as a dilute isotope.']); % Find out how which spins belong to the dilute species dilute_spins=find(cellfun(@(x)strcmp(x,isotope),spin_system.comp.isotopes)); % Inform the user if numel(dilute_spins)>0 report(spin_system,[num2str(numel(dilute_spins)) ' instances of ' isotope ' found in the spin system.']); else error('the specified isotopes are not present in the system.'); end % Preallocate the answer spin_systems=cell(numel(dilute_spins),1); % Create new spin systems for n=1:numel(dilute_spins) spin_systems{n}=kill_spin(spin_system,setdiff(dilute_spins,dilute_spins(n))); end % Inform the user report(spin_system,[num2str(numel(dilute_spins)) ' independent subsystems returned.']); end % Consistency enforcement function grumble(isotope) if ~ischar(isotope) error('isotope must be a character string.'); end end % "Dear Mother, good news today." % % Albert Einstein, in a 1919 postcard to his mother telling her that his % general theory of relativity had been proven.
github
tsajed/nmr-pred-master
sweep2ticks.m
.m
nmr-pred-master/spinach/kernel/utilities/sweep2ticks.m
1,674
utf_8
26786ae57adde778620b9517355c65cd
% Converts offset-sweep-npoints specification to axis ticks in Hz. % Syntax: % axis_hz=sweep2ticks(offs,sweep,npoints) % % Parameters: % % offs - offset from carrier frequency, Hz % % sweep - sweep width, Hz % % npoints - number of points in the spectrum % % The function returns the frequency axis of the spectrum, suitable % for use in functions like plot(). % % [email protected] function axis_hz=sweep2ticks(offs,sweep,npoints) % Check consistency grumble(offs,sweep,npoints); % Build the axis axis_hz=-linspace(-sweep/2,sweep/2,npoints)'+offs; end % Consistency enforcement function grumble(offs,sweep,npoints) if (~isnumeric(offs))||(~isreal(offs))||(~isscalar(offs)) error('offset must be a real scalar.'); end if (~isnumeric(sweep))||(~isreal(sweep))||(~isscalar(sweep)) error('sweep must be a real scalar.'); end if (~isnumeric(npoints))||(~isreal(npoints))||(~isscalar(npoints))||... (mod(npoints,1)~=0)||(npoints<1) error('npoints must be a real integer greater than 1.'); end end % Spinach code is clear, useful and elegant because the program is the % primary workhorse for the whole of IK's group and a few of their col- % laborators. Anything that is ugly, buggy or not well documented gets % fixed or thrown out in a matter of days. This also applies to "over- % hyped" algorithms that did not deliver, under real-world testing, on % the claims made by the authors of the corresponding papers. When ask- % ing us to implement something you had published, do consider the pos- % sibility that, at some point in the past, we may have done it.
github
tsajed/nmr-pred-master
path_trace.m
.m
nmr-pred-master/spinach/kernel/utilities/path_trace.m
5,082
utf_8
f58cecde2958673b551d48b82063f1c5
% Liouvillian path tracing. Treats the user-supplied Liouvillian % as the adjacency matrix of a graph, computes the weakly connect- % ed subgraphs of that graph and returns a cell array of project- % ors into the corresponding independently evolving subspaces. % Syntax: % projectors=reduce(spin_system,L,rho) % % where L is the Liouvillian and rho is the initial state (in the % case of source state screening) or the detection state (if des- % tination state screening is used). The output is a cell array of % projectors into independently evolving reduced subspaces. Those % projectors are to be used as follows: % % L_reduced=P'*L*P; rho_reduced=P'*rho; % % Further information is available here: % % http://link.aip.org/link/doi/10.1063/1.3398146 % http://dx.doi.org/10.1016/j.jmr.2011.03.010 % % [email protected] function projectors=path_trace(spin_system,L,rho) % Check the input grumble(spin_system,L,rho); % Check run conditions if ismember('pt',spin_system.sys.disable) % Return a unit projector if path tracing is disabled report(spin_system,'WARNING - path tracing disabled by the user.'); projectors={speye(size(L))}; return elseif size(L,2)<256 % Return a unit projector if the space is small anyway report(spin_system,'small space - path tracing skipped.'); projectors={speye(size(L))}; return else % Report to the user report(spin_system,['analyzing ' num2str(size(L,1)) '-dimensional state space.']); report(spin_system,['Liouvillian zero tolerance ' num2str(spin_system.tols.liouv_zero)]); report(spin_system,['cross-term tolerance for path drop ' num2str(spin_system.tols.path_drop)]); report(spin_system,['population tolerance for subspace drop ' num2str(spin_system.tols.subs_drop)]); end % Get the connectivity matrix G=(abs(L)>spin_system.tols.path_drop); % Make sure isolated states do not get lost G=or(G,transpose(G)); G=or(G,speye(size(G))); % Get the weakly connected subgraphs member_states=scomponents(G); % Determine the number of subspaces n_subspaces=max(member_states); report(spin_system,['found ' num2str(n_subspaces) ' non-interacting subspaces.']); report(spin_system,'running subspace population analysis...'); % Analyze independent subspaces subspace_important=true(n_subspaces,1); tolerance=spin_system.tols.subs_drop; parfor n=1:n_subspaces % Determine the importance subspace_important(n)=(norm(rho.*(member_states==n),1)>tolerance); end significant_subspaces=find(subspace_important); n_subspaces=numel(significant_subspaces); % Preallocate projectors and counters projectors=cell(1,n_subspaces); % Build projectors into significant subspaces parfor n=1:n_subspaces % Find states populating the current subspace state_index=find(member_states==significant_subspaces(n)); % Determine subspace dimension subspace_dim=numel(state_index); % Build the projector into the current subspace projectors{n}=sparse(state_index,1:subspace_dim,ones(1,subspace_dim),size(L,1),subspace_dim); end % Report to the user for n=1:n_subspaces report(spin_system,['populated subspace found, dimension=' num2str(size(projectors{n},2))]); end report(spin_system,['keeping a total of ' num2str(n_subspaces) ' independent subspace(s) '... 'of total dimension ' num2str(sum(cellfun(@(x)size(x,2),projectors)))]); % Merge small subspaces if ismember('merge',spin_system.sys.disable) % Inform the user report(spin_system,'WARNING - small subspace merging disabled by the user.'); else % Inform the user report(spin_system,'merging small subspaces...'); % Compile dimension statistics subspace_dims=cellfun(@(x)size(x,2),projectors); % Call the bin packer bins=binpack(subspace_dims,spin_system.tols.merge_dim); % Group the subspaces new_projectors=cell(numel(bins),1); for n=1:numel(bins) new_projectors{n}=[projectors{bins{n}}]; end projectors=new_projectors; % Report to the user for n=1:numel(projectors) report(spin_system,['working subspace ' num2str(n) ', dimension ' num2str(size(projectors{n},2))]); end end end % Consistency enforcement function grumble(spin_system,L,rho) if ~ismember(spin_system.bas.formalism,{'zeeman-liouv','sphten-liouv'}) error('path tracing is only available for zeeman-liouv and sphten-liouv formalisms.'); end if (~isnumeric(L))||(~isnumeric(rho)) error('both inputs must be numeric.'); end if size(L,1)~=size(L,2) error('Liouvillian must be square.'); end if size(L,2)~=size(rho,1) error('Liouvillian and state vector dimensions must be consistent.'); end end % "My dear fellow, who will let you?" % "That's not the point. The point is, who will stop me?" % % Ayn Rand, "The Fountainhead"
github
tsajed/nmr-pred-master
fdvec.m
.m
nmr-pred-master/spinach/kernel/utilities/fdvec.m
2,655
utf_8
43c02d1e65fc491d88f531cb8ea46d03
% Performs arbitrary-order finite-difference differentiation of a % user-supplied row or column vector. Uses central finite-differe- % nce stencils in the middle and sided stencils of the same order % of accuracy on the sides. Syntax: % % dx=fdvec(x,npoints,order) % % Parameters: % % x - column or row vector to be differentiated % % npoints - number of points in the finite difference % stencil % % order - order of the derivative required % % [email protected] function dx=fdvec(x,npoints,order) % Check consistency grumble(x,npoints,order) % Preallocate the answer dx=zeros(size(x)); x=x(:); % Compute edges with sided schemes for n=1:(npoints-1)/2 w=fdweights(n,1:npoints,order); dx(n)=w(end,:)*x(1:npoints); dx(end-n+1)=-w(end,end:-1:1)*x((end-npoints+1):end); end % Fill in the middle with centered schemes stencil=((1-npoints)/2):((npoints-1)/2); w=fdweights(0,stencil,order); for n=((npoints-1)/2+1):(numel(x)-(npoints-1)/2) dx(n)=w(end,:)*x(stencil+n); end end % Consistency enforcement function grumble(x,npoints,order) if (~isnumeric(x))||(~isvector(x)) error('x argument must be a vector.'); end if (npoints<1)||(order<1)||(mod(npoints,1)~=0)||(mod(order,1)~=0) error('stencil size and derivative order must be positive integers.'); end if numel(x)<3 error('x must have more than three elements.'); end if mod(npoints,2)~=1 error('the number of stencil points must be odd.'); end if order>=npoints error('derivative order must be smaller than the stencil size.'); end end % So whereas back then I wrote about the tyranny of the majority, today % I'd combine that with the tyranny of the minorities. [...] I say to % both bunches, whether you're a majority or minority, bug off! To hell % with anybody who wants to tell me what to write. All this political % correctness that's rampant on campuses is bullshit. % % You can't fool around with the dangerous notion of telling a university % what to teach and what not to. If you don't like the curriculum, go to % another school. Faculty members who toe the same line are sanctimonious % nincompoops! [...] In the same vein, we should immediately bar all quo- % tas, which politicize the process through lowered admission standards % that accept less-qualified students. The terrible result is the price- % less chance lost by all. The whole concept of higher education is nega- % ted unless the sole criterion used to determine if students qualify is % the grades they score on standardized tests. % % Ray Bradbury
github
tsajed/nmr-pred-master
conmat.m
.m
nmr-pred-master/spinach/kernel/utilities/conmat.m
1,396
utf_8
448fc7dec5d507ef1286d3a13522c0d7
% Fast connectivity matrix. % % [email protected] function conmatrix=conmat(xyz,r0) % Sort X coordinates [x_sorted,x_index]=sort(xyz(:,1)); % Scan X coordinates A=false(size(xyz,1),size(xyz,1)); for n=1:size(xyz,1) for k=(n+1):size(xyz,1) if abs(x_sorted(n)-x_sorted(k))<r0 A(x_index(n),x_index(k))=1; A(x_index(k),x_index(n))=1; else break; end end end % Sort Y coordinates [y_sorted,y_index]=sort(xyz(:,2)); % Scan Y coordinates B=false(size(xyz,1),size(xyz,1)); for n=1:size(xyz,1) for k=(n+1):size(xyz,1) if abs(y_sorted(n)-y_sorted(k))<r0 B(y_index(n),y_index(k))=1; B(y_index(k),y_index(n))=1; else break; end end end % Sort Z coordinates [z_sorted,z_index]=sort(xyz(:,3)); % Scan Y coordinates C=false(size(xyz,1),size(xyz,1)); for n=1:size(xyz,1) for k=(n+1):size(xyz,1) if abs(z_sorted(n)-z_sorted(k))<r0 C(z_index(n),z_index(k))=1; C(z_index(k),z_index(n))=1; else break; end end end % Compile the dirty matrix conmatrix=A&B&C; % Clean up the matrix [row,col]=find(conmatrix); for n=1:numel(row) if norm(xyz(row(n),:)-xyz(col(n),:),2)>r0 conmatrix(row(n),col(n))=0; end end end
github
tsajed/nmr-pred-master
killdiag.m
.m
nmr-pred-master/spinach/kernel/utilities/killdiag.m
601
utf_8
e4c21bf4f4b57f751a828bc59df5df25
% Wipes the diagonal using the brush with the specified dimensions. % % [email protected] function spec=killdiag(spec,brush_dim) % Loop over the column index for n=1:size(spec,2) % Find the row index k=n*size(spec,1)/size(spec,2); % Find the row index extents k=floor(k-brush_dim/2):ceil(k+brush_dim/2); % Avoid array boundaries k(k<1)=[]; k(k>size(spec,1))=[]; % Zero the elements spec(k,n)=0; end end % "I do wish we could chat longer, but... I'm having % an old friend for dinner." % % Hannibal Lecter
github
tsajed/nmr-pred-master
quat2anax.m
.m
nmr-pred-master/spinach/kernel/utilities/quat2anax.m
1,260
utf_8
e39d0de4d157bcc0895346b6c513f0ca
% Converts a quaternion into angle-axis rotation parameters. Syntax: % % [rot_axis,rot_angle]=quat2anax(q) % % where q is a structure with four fields q.u, q.i, q.j, q.k giving % the four components of the quaternion. % % Output: % % rot_axis - cartesian direction vector given as a row or column % with three real elements % % rot_angle - rotation angle in radians % % [email protected] function [rot_axis,rot_angle]=quat2anax(q) % Check consistency grumble(q); % Normalize the quaternion qnorm=norm([q.u q.i q.j q.k],2); q.u=q.u/qnorm; q.i=q.i/qnorm; q.j=q.j/qnorm; q.k=q.k/qnorm; % Compute the angle rot_angle=2*atan2(norm([q.i q.j q.k],2),q.u); % Compute the axis if rot_angle==0 rot_axis=[0 0 1]; else rot_axis=[q.i q.j q.k]/norm([q.i q.j q.k],2); end end % Consistency enforcement function grumble(q) if ~all(isfield(q,{'i','j','k','u'})) error('quaternion data structure must contain u, i, j, and k fields.'); end if ~isreal([q.u q.i q.j q.k]) error('quaternion elements must be real.'); end end % "Mediocrity" does not mean an average intelligence; it means an % average intelligence that resents and envies its betters. % % Ayn Rand
github
tsajed/nmr-pred-master
hdot.m
.m
nmr-pred-master/spinach/kernel/utilities/hdot.m
848
utf_8
91a69f208649bda9842cf2a1152a2069
% Hadamard matrix product. Useful as a replacement for trace(A'*B) because % trace(A'*B)=hadm(conj(A),B) and the latter only needs O(n^2) multiplica- % tions as opposed to O(n^3) for trace(A'*B). Syntax: % % H=hdot(A,B) % % [email protected] function H=hdot(A,B) % Check consistency grumble(A,B); % Do the calculation H=sum(conj(A(:)).*B(:)); end % Consistency enforcement function grumble(A,B) if (~isnumeric(A))||(~isnumeric(B)) error('both inputs must be numeric.'); end if ~all(size(A)==size(B)) error('the two inputs must have identical dimensions.'); end end % An infinite number of mathematicians walk into a bar. The first one % orders a pint of beer, the second one half a pint, the third one a % quarter... "Gotcha!" says the bartender and pours two pints.
github
tsajed/nmr-pred-master
relax_split.m
.m
nmr-pred-master/spinach/kernel/utilities/relax_split.m
1,049
utf_8
e721c09e6d54b2569d5ac94e2bbf4801
% Splits the relaxation superoperator into longitudinal, transverse and % mixed components. % % [email protected] function [R1,R2,Rm]=relax_split(spin_system,R) % Interpret the basis [L,M]=lin2lm(spin_system.bas.basis); % Index single- and multi-spin orders (sso and mso) sso_mask=(sum(logical(spin_system.bas.basis),2)==1); mso_mask=(sum(logical(spin_system.bas.basis),2)>1 ); % Index longlitudinal and transverse states long_sso_mask=any((L>0)&(M==0),2)&sso_mask; tran_sso_mask=any((L>0)&(M~=0),2)&sso_mask; % Split the relaxation superoperator R1=R; R1(~long_sso_mask,~long_sso_mask)=0; R2=R; R2(~tran_sso_mask,~tran_sso_mask)=0; Rm=R; R2(~mso_mask,~mso_mask)=0; end % He that reproveth a scorner getteth to himself shame: and he that % rebuketh a wicked man getteth himself a blot. Reprove not a scorn- % er, lest he hate thee: rebuke a wise man, and he will love thee. % Give instruction to a wise man, and he will be yet wiser: teach a % just man, and he will increase in learning. % % Proverbs 9:7
github
tsajed/nmr-pred-master
fprint.m
.m
nmr-pred-master/spinach/kernel/utilities/fprint.m
1,431
utf_8
4c495e8aec3d0db6d5697339d500b97e
% 2D spectrum integral fingerprinting utility. Breaks the spectrum % down into bins of user-specified size and returns the integrals % over those bins. Syntax: % % fp=fprint(spectrum,nbins) % % Parameters: % % spectrum - the matrix of a real or complex 2D spectrum % % nbins - a vector with two integers, specifying the % number of bins in each spectral dimension % % Note: spectrum matrix dimensions must be divisible by the corres- % ponding element of nbins vector. % % [email protected] function fp=fprint(spectrum,nbins) % Decide problem dimensionality switch ndims(spectrum) case 2 % Preallocate the answer fp=zeros(nbins); % Determine bin boundaries bins_x=linspace(0,size(spectrum,1),nbins(1)+1); bins_y=linspace(0,size(spectrum,2),nbins(2)+1); % Loop over the bins for n=1:nbins(1) for k=1:nbins(2) % Compute bin integrals fp(n,k)=trapz(trapz(spectrum((bins_x(n)+1):bins_x(n+1),(bins_y(k)+1):bins_y(k+1)))); end end otherwise error('not implemented'); end % Never underestimate the bandwidth of a station wagon full of % tapes hurtling down the highway. % % Andrew Tanenbaum
github
tsajed/nmr-pred-master
intrep.m
.m
nmr-pred-master/spinach/kernel/utilities/intrep.m
2,974
utf_8
d203a548676b6be940ecef3033e89b1e
% Interaction representation transformation with respect to % a specified Hamiltonian to specified order in perturbation % theory. Syntax: % % Hr=intrep(spin_system,H0,H,T,order) % % Parameters: % % H0 - the Hamiltonian with respect to which the % interaction representation transformation % is to be done % % H - laboratory frame Hamiltonian H0+H1 that is % to be transformed into the interaction rep- % resentation % % T - period of the H0 propagator % % order - perturbation theory order in the rotating % frame transformation % % [email protected] function Hr=intrep(spin_system,H0,H,T,order) % Check consistency grumble(H0,H,order); % Confirm that T is indeed the period P=propagator(spin_system,H0,T); if norm(P-speye(size(P)),1)>1e-6 error('the value of T supplied is not a period of exp(-i*H0*t) propagator.'); end % Confirm that norms are sensible norm_h0=norm(H0,1); norm_h1=norm(H-H0,1); if norm_h1>norm_h0 error('norm(H1) found to be bigger than norm(H0): H1 must be a perturbation.'); else report(spin_system,['rotating frame period: ' num2str(T) ' seconds']); report(spin_system,['H0 (lab frame) 1-norm: ' num2str(norm_h0)]); report(spin_system,['H1 (lab frame) 1-norm: ' num2str(norm_h1)]); end % Decide the theory order switch order case 0 % Shortcut for high field Hr=H-H0; case Inf % Shortcut for infinite order Hr=(1i/T)*logm(expm(-1i*H*T)); otherwise % Get the derivatives D=dirdiff(spin_system,H0,H-H0,T,order+1); % Get the first term Hr=(1i/T)*(D{1}'*D{2}); % Get the rest of the series for n=2:order for k=1:n Hr=Hr+(1i/T)*nchoosek(n-1,k-1)*D{n-k+1}'*D{k+1}/factorial(n); end end end % Clean up the output Hr=clean_up(spin_system,(Hr+Hr')/2,spin_system.tols.liouv_zero); % Return matrix density statistics report(spin_system,['interaction representation Hamiltonain dimension ' num2str(size(Hr,1)) ... ', nnz ' num2str(nnz(Hr)) ', density ' num2str(100*nnz(Hr)/numel(Hr))... '%, sparsity ' num2str(issparse(Hr))]); end % Consistency enforcement function grumble(H0,H,order) if (~ishermitian(H))||(~ishermitian(H0)) error('both H and H0 must be Hermitian.'); end if ((~isreal(order))||(order<1)||(mod(order,1)~=0))&&(~isinf(order)) error('unsupported rotating frame transformation theory order.'); end end % There is no difference between communism and socialism, except in the % means of achieving the same ultimate end: communism proposes to enslave % men by force, socialism - by vote. It is merely the difference between % murder and suicide. % % Ayn Rand
github
tsajed/nmr-pred-master
ang2cgsppm.m
.m
nmr-pred-master/spinach/kernel/utilities/ang2cgsppm.m
663
utf_8
677828861b5d552c086587d4af7395c8
% Converts magnetic susceptibility from the Angstrom^3 units % required by Spinach pseudocontact shift functionality into % the cgs-ppm (aka cm^3/mol) units quoted by quantum chemist- % ry packages into. Syntax: % % cgsppm=ang2cgsppm(ang) % % Arrays of any dimension are supported. % % [email protected] function cgsppm=ang2cgsppm(ang) % Check consistency grumble(ang); % Do the calculation cgsppm=6.02214129e23*ang/(4*pi*1e18); end % Consistency enforcement function grumble(ang) if ~isnumeric(ang) error('input must be numeric.'); end end % No artist tolerates reality. % % Friedrich Nietzsche
github
tsajed/nmr-pred-master
phan2fpl.m
.m
nmr-pred-master/spinach/kernel/utilities/phan2fpl.m
756
utf_8
9cd6a0be10ef4e320036b78f3ae3595a
% Projects a spatial intensity distribution into the Fokker-Planck % space, using the spin state supplied. Syntax: % % rho=phan2fpl(phan,rho) % % Parameters: % % phan - phantom (the spatial distribution of the % amplitude of the specified spin state) % % rho - the spin state in question % % [email protected] function rho=phan2fpl(phan,rho) % Stretch the phantom and kron it into the spin state rho=kron(phan(:),rho); end % Q: "How many members of a certain demographic group does % it take to perform a specified task?" % % A: "A finite number: one to perform the task and the rem- % ainder to act in a manner stereotypical of the group % in question."
github
tsajed/nmr-pred-master
kill_spin.m
.m
nmr-pred-master/spinach/kernel/utilities/kill_spin.m
4,407
utf_8
c773a2aa101681bdfba3f89b224e4277
% Removes the specified spins from the spin_system structure and updates % all internal structures accordingly. Syntax: % % spin_system=kill_spin(spin_system,hit_list) % % where hit_list is a vector of integers or a logical matrix giving the % numbers of spins to be removed from the system. % % [email protected] % [email protected] function spin_system=kill_spin(spin_system,hit_list) % Check consistency grumble(spin_system,hit_list) % Catch logical indexing if any(hit_list==0), hit_list=find(hit_list); end % Inform the user report(spin_system,['removing ' num2str(numel(hit_list)) ' spins from the system...']); % Update isotopes list spin_system.comp.isotopes(hit_list)=[]; % Update spin numbers spin_system.comp.nspins=spin_system.comp.nspins-numel(hit_list); % Update labels list spin_system.comp.labels(hit_list)=[]; % Update multiplicities and magnetogyric ratios spin_system.comp.mults(hit_list)=[]; spin_system.inter.gammas(hit_list)=[]; % Update base frequencies spin_system.inter.basefrqs(hit_list)=[]; % Update Zeeman tensor array spin_system.inter.zeeman.matrix(hit_list)=[]; % Update coupling tensor array spin_system.inter.coupling.matrix(hit_list,:)=[]; spin_system.inter.coupling.matrix(:,hit_list)=[]; % Update coordinates spin_system.inter.coordinates(hit_list)=[]; % Update proximity matrix spin_system.inter.proxmatrix(hit_list,:)=[]; spin_system.inter.proxmatrix(:,hit_list)=[]; % Update relaxation parameters if ~isempty(spin_system.rlx.r1_rates) spin_system.rlx.r1_rates(hit_list)=[]; end if ~isempty(spin_system.rlx.r2_rates) spin_system.rlx.r2_rates(hit_list)=[]; end if ~isempty(spin_system.rlx.lind_r1_rates) spin_system.rlx.lind_r1_rates(hit_list)=[]; end if ~isempty(spin_system.rlx.lind_r2_rates) spin_system.rlx.lind_r2_rates(hit_list)=[]; end if ~isempty(spin_system.rlx.srfk_mdepth) spin_system.rlx.srfk_mdepth(hit_list,:)=[]; spin_system.rlx.srfk_mdepth(:,hit_list)=[]; end if ~isempty(spin_system.rlx.weiz_r1d) spin_system.rlx.weiz_r1d(hit_list,:)=[]; spin_system.rlx.weiz_r1d(:,hit_list)=[]; end if ~isempty(spin_system.rlx.weiz_r2d) spin_system.rlx.weiz_r2d(hit_list,:)=[]; spin_system.rlx.weiz_r2d(:,hit_list)=[]; end % Update kinetics for n=1:numel(spin_system.chem.parts) spin_system.chem.parts{n}=setdiff(spin_system.chem.parts{n},hit_list); end spin_system.chem.flux_rate(hit_list,:)=[]; spin_system.chem.flux_rate(:,hit_list)=[]; % Update radical recombination parameters reacting_spins=zeros(1,spin_system.comp.nspins+numel(hit_list)); reacting_spins(spin_system.chem.rp_electrons)=1; reacting_spins(hit_list)=[]; spin_system.chem.rp_electrons=find(reacting_spins); if (~isempty(spin_system.chem.rp_rates))&&(numel(spin_system.chem.rp_electrons)<2) error('cannot destroy an essential electron in a radical pair system.'); end % If any basis set information is found, destroy it if isfield(spin_system,'bas') spin_system=rmfield(spin_system,'bas'); report(spin_system,'WARNING - basis set information must be re-created.'); end % If any assumption information is found, destroy it if isfield(spin_system.inter.zeeman,'strength') spin_system.inter.zeeman=rmfield(spin_system.inter.zeeman,'strength'); report(spin_system,'WARNING - assumption information mst be re-created.'); end if isfield(spin_system.inter.coupling,'strength') spin_system.inter.coupling=rmfield(spin_system.inter.coupling,'strength'); report(spin_system,'WARNING - assumption information mst be re-created.'); end end % Consistency enforcement function grumble(spin_system,hit_list) if islogical(hit_list) if(numel(hit_list)~=spin_system.comp.nspins) error('the size of the hit mask does not match the number of spins in the system.'); end else if (~isnumeric(hit_list))||any(hit_list<1) error('hit_list must be a logical matrix or an array of positive numbers.'); end if any(hit_list>spin_system.comp.nspins) error('at least one number in hit_list exceeds the number of spins.'); end end end % I do not see that the sex of the candidate is an argument against % her admission as privatdozent. After all, we are a university, not % a bath house. % % David Hilbert, about Emmy Noether, in 1915.
github
tsajed/nmr-pred-master
gaussfun.m
.m
nmr-pred-master/spinach/kernel/utilities/gaussfun.m
532
utf_8
db46c4330494c2ef7152d464d52e70dc
% Normalized Gaussian function in magnetic resonance notation. Syntax: % % g=gaussfun(x,fwhm) % % where fwhm is the full width at half-maximum. % % [email protected] function y=gaussfun(x,fwhm) % Compute standard deviation sigma=fwhm/(2*sqrt(2*log(2))); % Compute the Gaussian y=(1/(sigma*sqrt(2*pi)))*exp(-(x.^2)/(2*sigma^2)); end % Fifty years ago the back streets of Leningrad % have taught me one lesson: when a fight is un- % avoidable, punch first. % % Vladimir Putin
github
tsajed/nmr-pred-master
sphten2oper.m
.m
nmr-pred-master/spinach/kernel/utilities/sphten2oper.m
1,208
utf_8
e7a47c3a8e06b54fbb1ae8db1e051386
% Generates a operator from its spherical tensor expansion produced % by zeeman2sphten() function. Syntax: % % L=sphten2operator(spin_system,stexp,spin_num) % % where stexp is a cell array with the first element of each row giving % the operator name and the second element being the corresponding sphe- % rical tensor expansion coefficient. The last argument is the number of % the spin to which the expansion refers. % % [email protected] % [email protected] function L=sphten2oper(spin_system,stexp,spin_num) % Validate the input grumble(spin_system,stexp,spin_num); % Get the state vector L=sparse(0); for n=1:size(stexp,1) % Get the state Ln=operator(spin_system,stexp(n,1),{spin_num}); % Add to the total L=L+stexp{n,2}*Ln; end end % Input validation function function grumble(spin_system,stexp,spin_num) if ~isfield(spin_system,'bas') error('basis set information is missing, run basis() before calling this function.'); end if ~iscell(stexp) error('stexp must be a cell array.'); end if (~isnumeric(spin_num))||(~isreal(spin_num))||(mod(spin_num,1)~=0)||(spin_num<1) error('spin_num must be a positive integer.'); end end
github
tsajed/nmr-pred-master
svd_shrink.m
.m
nmr-pred-master/spinach/kernel/utilities/svd_shrink.m
1,310
utf_8
22cbd18e5b84400a43996baab71df2ac
% Generates a minimal set of vector-covector pairs for the parallel % implementation of the time propagation algorithm described in % http://dx.doi.org/10.1063/1.3679656 (Equation 9). Syntax: % % [vec,cov]=svd_shrink(spin_system,rho,tol) % % Parameters: % % rho - density matrix % % tol - singluar value drop tolerance % % [email protected] function [vec,cov]=svd_shrink(spin_system,rho,tol) % Check consistency grumble(rho); % Run the singular value decomposition [vec,S,cov]=svd(full(rho)); S=diag(S); % Get the drop mask drop_mask=(S<tol); % Update the user report(spin_system,['dropped ' num2str(nnz(drop_mask)) ' insignificant '... 'vector-covector pairs from the density matrix.']); % Eliminate small singular values vec(:,drop_mask)=[]; cov(:,drop_mask)=[]; S(drop_mask)=[]; % Spread the coefficients vec=vec*diag(sqrt(S)); cov=cov*diag(sqrt(S)); end % Consistency enforcement function grumble(rho) if (~isnumeric(rho))||(size(rho,1)~=size(rho,2)) error('rho must be a square matrix.'); end end % If everyone likes your research, you can be certain that % you have not done anything important. That is the first % thing to grasp. Conflict goes with the territory. % % Andrew Oswald
github
tsajed/nmr-pred-master
expmint.m
.m
nmr-pred-master/spinach/kernel/utilities/expmint.m
1,443
utf_8
73fdd6c9439dcc35b826979f99fbde65
% Computes matrix exponential integrals of the following general type: % % Integrate[expm(-i*A*t)*B*expm(i*C*t),{t,0,T}] % % Matrix A must be Hermitian. For further information see the paper by % Charles van Loan (http://dx.doi.org/10.1109/TAC.1978.1101743). Syntax: % % R=expmint(spin_system,A,B,C,T) % % [email protected] % [email protected] function R=expmint(spin_system,A,B,C,T) % Check consistency grumble(A,B,C,T); % Build auxiliary matrix auxmat=[-A, 1i*B; 0*A, -C]; % Compute the integral auxmat=propagator(spin_system,auxmat,T); R=auxmat(1:(end/2),1:(end/2))'*... auxmat(1:(end/2),(end/2+1):end); % Clean up the result R=clean_up(spin_system,R,spin_system.tols.liouv_zero); end % Consistency enforcement function grumble(A,B,C,T) if (~isnumeric(A))||(~isnumeric(B))||(~isnumeric(C))||... (~ismatrix(A))||(~ismatrix(B))||(~ismatrix(C)) error('A, B and C arguments must be matrices.'); end if (~all(size(A)==size(B)))||(~all(size(B)==size(C))) error('A, B and C matrices must have the same dimension.'); end if ~ishermitian(A) error('A matrix must be Hermitian.'); end if (~isnumeric(T))||(~isreal(T))||(~isscalar(T)) error('T must be a real scalar.'); end end % LADY NANCY ASTOR: "If you were my husband, Winston, I'd put poison in your tea." % WINSTON CHURCHILL: "If I were your husband, Nancy, I'd drink it."
github
tsajed/nmr-pred-master
scomponents.m
.m
nmr-pred-master/spinach/kernel/utilities/scomponents.m
2,172
utf_8
d1d43abd56be4bce359c8ae739a65c99
% Computes the strongly connected components of a graph. Returns % an index for the component number of every vertex in the graph % with the adjacency matrix A. Syntax: % % sci=scomponents(A) % % where A is square logical matrix and sci is a vector indicating % which component each node of the graph belongs to. % % Algorithm description is at http://dx.doi.org/10.1137/0201010 % % [email protected] % [email protected] function sci=scomponents(A) % Check the input if (~islogical(A))||(~ismatrix(A))||(size(A,1)~=size(A,2)) error('the input must be a square logical matrix.'); end % Get the CSR indices [rp,ci]=sparse2csr(sparse(A)); % Run Tarjan's algorithm n=length(rp)-1; sci=zeros(n,1); cn=1; root=zeros(n,1); dt=zeros(n,1); t=0; cs=zeros(n,1); css=0; rs=zeros(2*n,1); rss=0; for sv=1:n v=sv; if root(v)>0, continue; end rss=rss+1; rs(2*rss-1)=v; rs(2*rss)=rp(v); root(v)=v; sci(v)=-1; dt(v)=t; t=t+1; css=css+1; cs(css)=v; while rss>0 v=rs(2*rss-1); ri=rs(2*rss); rss=rss-1; while ri<rp(v+1) w=ci(ri); ri=ri+1; if root(w)==0 root(w)=w; sci(w)=-1; dt(w)=t; t=t+1; css=css+1; cs(css)=w; rss=rss+1; rs(2*rss-1)=v; rs(2*rss)=ri; v=w; ri=rp(w); continue; end end for ri=rp(v):rp(v+1)-1 w=ci(ri); if sci(w)==-1 if dt(root(v))>dt(root(w)), root(v)=root(w); end end end if root(v)==v while css>0 w=cs(css); css=css-1; sci(w)=cn; if w==v, break; end end cn=cn+1; end end end end % The Monks of Cool, whose tiny and exclusive monastery is hidden in a % really cool and laid-back valley in the lower Ramtops, have a passing- % out test for a novice. He is taken into a room full of all types of % clothing and asked: "Yo, my son, which of these is the most stylish % thing to wear?" And the correct answer is: "Hey, whatever I select". % % Terry Pratchett
github
tsajed/nmr-pred-master
mat2sphten.m
.m
nmr-pred-master/spinach/kernel/utilities/mat2sphten.m
2,779
utf_8
dcb96a780e3cb92a69e556b768d5e24c
% Converts a 3x3 interaction matrix into the irreducible spherical tensor % notation: one rank 0 component, three rank 1 components and five rank 2 % components to the total of nine independent components. % % The components are listed in the following order: % % rank 0: (0,0) % rank 1: (1,1) (1,0) (1,-1) % rank 2: (2,2) (2,1) (2,0) (2,-1) (2,-2) % % and are returned as coefficients in front of the corresponding irreduci- % ble spherical tenror operators. Syntax: % % [rank0,rank1,rank2]=mat2sphten(M) % % Outputs: % % rank0 - a single number giving the coefficient of T(0,0) in % the spherical tensor expansion. % % rank1 - a row vector with three numbers giving the coeffici- % ents of T(1,1), T(1,0) and T(1,-1) in the spherical % tensor expansion. % % rank2 - a row vector with five numbers giving the coeffici- % ents of T(2,2), T(2,1), T(2,0), T(2,-1) and T(2,-2) % in the spherical tensor expansion. % % See Table 1 in http://dx.doi.org/10.1016/0022-2364(77)90011-7 (note % that minus signs are absorbed into the coefficients in Spinach). % % [email protected] function [rank0,rank1,rank2]=mat2sphten(M) % Adapt to empty matrices if isempty(M), M=zeros(3); end % Check consistency grumble(M); % Set result dimensions rank1=zeros(3,1); rank2=zeros(5,1); % Rank 0 component rank0=-(1/sqrt(3))*trace(M); % Rank 1 components rank1(1)=-(1/2)*(M(3,1)-M(1,3)-1i*(M(3,2)-M(2,3))); rank1(2)=-(1i/sqrt(2))*(M(1,2)-M(2,1)); rank1(3)=-(1/2)*(M(3,1)-M(1,3)+1i*(M(3,2)-M(2,3))); % Rank 2 components rank2(1)=+(1/2)*(M(1,1)-M(2,2)-1i*(M(1,2)+M(2,1))); rank2(2)=-(1/2)*(M(1,3)+M(3,1)-1i*(M(2,3)+M(3,2))); rank2(3)=(1/sqrt(6))*(2*M(3,3)-M(1,1)-M(2,2)); rank2(4)=+(1/2)*(M(1,3)+M(3,1)+1i*(M(2,3)+M(3,2))); rank2(5)=+(1/2)*(M(1,1)-M(2,2)+1i*(M(1,2)+M(2,1))); end % Consistency enforcement function grumble(M) if (~isnumeric(M))||(~isreal(M))||(~ismatrix(M))||any(size(M)~=[3 3]) error('the argument must be a real 3x3 matrix.'); end end % When I was 13 I think - Hewlett and Packard were my idols - I called up % Bill Hewlett because he lived in Palo Alto and there were no unlisted % numbers in the phonebook - which gives you a clue to my age. And he % picked up the phone and I talked to him and I asked him if he'd give me % some spare parts for something I was building called a frequency coun- % ter. And he did, but in addition to that he gave me something way more % important. He gave me a job that summer - a summer job - at Hewlett- % Packard right here in Santa Clara off 280, in a division that built fre- % quency counters. And I was in heaven. % % Steve Jobs
github
tsajed/nmr-pred-master
lorentzfun.m
.m
nmr-pred-master/spinach/kernel/utilities/lorentzfun.m
543
utf_8
428e2c8ff1a296981915b56f51618ff6
% Normalized Lorentzian function in magnetic resonance notation. Syntax: % % g=lorentzfun(x,fwhm) % % where fwhm is the full width at half-maximum. % % [email protected] function y=lorentzfun(x,fwhm) % Get the width parameter gamma=fwhm/2; % Compute the Lorentzian y=(1/(pi*gamma))*(1./(1+(x/gamma).^2)); end % [...] the sexual revolution was the mockery of the century, % because now women were giving to men for free what they used % to have to marry us for. % % A feminist web site
github
tsajed/nmr-pred-master
cce.m
.m
nmr-pred-master/spinach/kernel/utilities/cce.m
1,979
utf_8
332585b9b8dbb41b670e53869698205c
% Cluster Correlation Expansion function - partitions the spin_system % object into individual subsystems prescribed by the CCE clusterisa- % tion model [DOI reference here]. Syntax: % % [subsystems,indices]=cce(spin_system,system,bath,order) % % Parameters: % % system - a row vector giving the numbers of the % spins belonging to the "system" % % bath - a row vector giving the numbers of the % spins belonging to the "bath" % % order - CCE expansion order, the number of bath % spins in each subsystem % % Outputs: % % subsystems - a cell array of spin system objects % for the individual subsystems % % indices - a cell array of index vectors indi- % cating which bath spins ended up in % each of the generated subsystems. % The spins are listed in the order % of increasing index. % % [email protected] % [email protected] function [subsystems,indices]=cce(spin_system,system,bath,order) % Start the index array indices={}; % Loop over bath cluster sizes for n=1:order % Generate bath spin picks partial_index=combnk(bath,n); % Sort in ascending order partial_index=sort(partial_index,2,'ascend'); % Remove repetitions partial_index=unique(partial_index,'rows'); % Convert into a cell array partial_index=mat2cell(partial_index,ones(size(partial_index,1),1),n); % Add to the total indices=[indices; partial_index]; %#ok<AGROW> end % Build the corresponding subsystems subsystems=cell(numel(indices,1)); parfor n=1:numel(indices) % Remove the spins that are not included in each cluster subsystems{n}=kill_spin(spin_system,setdiff(1:spin_system.comp.nspins,... [system indices{n}])); end end
github
tsajed/nmr-pred-master
anax2dcm.m
.m
nmr-pred-master/spinach/kernel/utilities/anax2dcm.m
1,431
utf_8
69ddaf3bacea8b6f5c3c7f7b1a9d67a8
% Converts angle-axis rotation parameters to directional % cosine matrix. Angle should be in radians, axis is nor- % malized by the function. Syntax: % % dcm=anax2dcm(rot_axis,rot_angle) % % Arguments: % % rot_axis - cartesian direction vector given as % a row or column with three real ele- % ments % % rot_angle - rotation angle in radians % % [email protected] function dcm=anax2dcm(rot_axis,rot_angle) % Check consistency grumble(rot_axis,rot_angle); % Normalize the axis rot_axis=rot_axis(:)/norm(rot_axis(:),2); % Compute the DCM dcm=eye(3)-sin(rot_angle)*[ 0 -rot_axis(3) rot_axis(2); rot_axis(3) 0 -rot_axis(1); -rot_axis(2) rot_axis(1) 0 ]+... (1-cos(rot_angle))*(rot_axis*rot_axis'-eye(3)); end % Consistency enforcement function grumble(rot_axis,rot_angle) if (~isnumeric(rot_axis))||(~isnumeric(rot_angle)) error('both inputs must be numeric.'); end if any(~isreal(rot_axis))||any(~isreal(rot_angle)) error('both inputs must be real.'); end if numel(rot_axis)~=3 error('direction vector must have three real elements.'); end if numel(rot_angle)~=1 error('rotation angle must be a real number.'); end end % "The brightest flame casts the darkest shadow." % % George R.R. Martin
github
tsajed/nmr-pred-master
dipolar.m
.m
nmr-pred-master/spinach/kernel/utilities/dipolar.m
6,606
utf_8
827e01525aee4718f439a76ea78494cd
% Computes dipolar couplings in the presence or absence of periodic % boundary conditions. This is an auxiliary function of Spinach ker- % nel, direct calls are discouraged. Use xyz2dd to convert Cartesian % coordinates to dipolar couplings. % % [email protected] function spin_system=dipolar(spin_system) % Report to the user report(spin_system,['dipolar interaction distance threshold: ' num2str(spin_system.tols.prox_cutoff) ' Angstrom.']); report(spin_system,'running dipolar interaction network analysis...'); % Preallocate distance vector array distvects=cell(spin_system.comp.nspins,spin_system.comp.nspins); % Loop over chemical species for m=1:numel(spin_system.chem.parts) % Extract the spin list spin_list=spin_system.chem.parts{m}; % Loop over atom pairs for n=spin_list for k=spin_list % Only proceed if coordinates are specified if (~isempty(spin_system.inter.coordinates{n}))&&(~isempty(spin_system.inter.coordinates{k}))&&(n~=k) % Determine possible distance vectors from n to k if isempty(spin_system.inter.pbc) % Compute the distance vector for standalone system dv=spin_system.inter.coordinates{k}-spin_system.inter.coordinates{n}; elseif numel(spin_system.inter.pbc)==1 % Preallocate distance vector array nvecs=2*spin_system.tols.dd_ncells+1; dv=zeros(nvecs,3); % Compute distance vectors with 1D periodic boundary linear_index=1; for p=-spin_system.tols.dd_ncells:spin_system.tols.dd_ncells dv(linear_index,:)=spin_system.inter.coordinates{k}+p*spin_system.inter.pbc{1}-... spin_system.inter.coordinates{n}; linear_index=linear_index+1; end elseif numel(spin_system.inter.pbc)==2 % Preallocate distance vector array nvecs=(2*spin_system.tols.dd_ncells+1)^2; dv=zeros(nvecs,3); % Compute distance vectors with 2D periodic boundary linear_index=1; for p=-spin_system.tols.dd_ncells:spin_system.tols.dd_ncells for q=-spin_system.tols.dd_ncells:spin_system.tols.dd_ncells dv(linear_index,:)=spin_system.inter.coordinates{k}+p*spin_system.inter.pbc{1}+... q*spin_system.inter.pbc{2}-spin_system.inter.coordinates{n}; linear_index=linear_index+1; end end elseif numel(spin_system.inter.pbc)==3 % Preallocate distance vector array nvecs=(2*spin_system.tols.dd_ncells+1)^3; dv=zeros(nvecs,3); % Compute distance vectors with 3D periodic boundary linear_index=1; for p=-spin_system.tols.dd_ncells:spin_system.tols.dd_ncells for q=-spin_system.tols.dd_ncells:spin_system.tols.dd_ncells for r=-spin_system.tols.dd_ncells:spin_system.tols.dd_ncells dv(linear_index,:)=spin_system.inter.coordinates{k}+p*spin_system.inter.pbc{1}+... q*spin_system.inter.pbc{2}+r*spin_system.inter.pbc{3}-... spin_system.inter.coordinates{n}; linear_index=linear_index+1; end end end else % Complain and bomb out error('PBC translation vector array has invalid dimensions.'); end % Ignore distance vectors that are longer than the threshold dv=dv(sqrt(sum(dv.^2,2))<spin_system.tols.prox_cutoff,:); % Detect atomic collisions if any(sqrt(sum(dv.^2,2))<0.5) % Bomb out for distances closer than 0.5 Angstrom error(['collision detected between spin ' num2str(n) ' and spin ' num2str(k) ' or their PBC images.']); end % Assign the cell array if ~isempty(dv), distvects{n,k}=dv; end end end end end % Get proximity matrix spin_system.inter.proxmatrix=sparse(~cellfun(@isempty,distvects)); % Find interacting atom pairs [rows,cols,~]=find(spin_system.inter.proxmatrix); % Report to the user report(spin_system,['found ' num2str(numel(rows)/2) ' spin pair(s) with distance under the '... 'threshold of ' num2str(spin_system.tols.prox_cutoff) ' Angstrom.']); % Loop over interacting atom pairs for n=1:numel(rows) % Loop over PBC directions for k=1:size(distvects{rows(n),cols(n)},1) % Get the distance distance=norm(distvects{rows(n),cols(n)}(k,:),2); % Get the ort ort=distvects{rows(n),cols(n)}(k,:)/distance; % Compute the dipolar interaction prefactor (0.5 due to double counting) A=0.5*spin_system.inter.gammas(rows(n))*spin_system.inter.gammas(cols(n))*... spin_system.tols.hbar*spin_system.tols.mu0/(4*pi*(distance*1e-10)^3); % Compute the dipolar coupling matrix D=A*[1-3*ort(1)*ort(1) -3*ort(1)*ort(2) -3*ort(1)*ort(3); -3*ort(2)*ort(1) 1-3*ort(2)*ort(2) -3*ort(2)*ort(3); -3*ort(3)*ort(1) -3*ort(3)*ort(2) 1-3*ort(3)*ort(3)]; % Add to the total spin_system.inter.coupling.matrix{rows(n),cols(n)}=spin_system.inter.coupling.matrix{rows(n),cols(n)}+D; end end end % What worries me about religion is that it teaches people to % be satisfied with not understanding. % % Richard Dawkins
github
tsajed/nmr-pred-master
fdlap.m
.m
nmr-pred-master/spinach/kernel/utilities/fdlap.m
3,339
utf_8
d82df57a50cccf027a969a106be10ac8
% Returns a finite-difference representation of the Laplacian for a 3D % array with a user-specified finite difference stencil size. The re- % sulting operator is a sparse matrix designed to act on the vectori- % zation of the 3D array. The dimensions of the 3D array are assumed % to be ordered as [X Y Z]. Syntax: % % L=fdlap(npoints,extents,nstenc) % % The following parameters are needed: % % dims - a three-element vector specifying the number of % discretization points in each dimension of the % 3D cube of data that the operator will be acting % on, ordered as [X Y Z]. % % extents - a three-element vector specifying axis extents, % ordered as [X Y Z]. % % nstenc - number of finite-difference stencil points for % the finite-difference approximations. % % The resulting operator is a sparse matrix designed to act on the vec- % torization of rho. The dimensions of rho are assumed to be ordered % as [X Y Z]. % % Periodic boundary condition is used. % % [email protected] function L=fdlap(dims,extents,nstenc) % Check consistency grumble(dims,extents,nstenc); switch numel(dims) case 1 % Get differentiation matrices Dxx=fdmat(dims(1),nstenc,2); % Normalize differentiation matrices Dxx=(dims(1)/extents(1))^2*Dxx; % Compute the Laplacian L=Dxx; case 2 % Get differentiation matrices Dxx=fdmat(dims(1),nstenc,2); Dyy=fdmat(dims(2),nstenc,2); % Normalize differentiation matrices Dxx=(dims(1)/extents(1))^2*Dxx; Dyy=(dims(2)/extents(2))^2*Dyy; % Compute the Laplacian L=kron(Dyy,speye(dims(1)))+... kron(speye(dims(2)),Dxx); case 3 % Get differentiation matrices Dxx=fdmat(dims(1),nstenc,2); Dyy=fdmat(dims(2),nstenc,2); Dzz=fdmat(dims(3),nstenc,2); % Normalize differentiation matrices Dxx=(dims(1)/extents(1))^2*Dxx; Dyy=(dims(2)/extents(2))^2*Dyy; Dzz=(dims(3)/extents(3))^2*Dzz; % Compute the Laplacian L=kron(kron(Dzz,speye(dims(2))),speye(dims(1)))+... kron(kron(speye(dims(3)),Dyy),speye(dims(1)))+... kron(kron(speye(dims(3)),speye(dims(2))),Dxx); otherwise % Complain and bomb out error('incorrect number of spatial dimensions.'); end end % Consistency enforcement function grumble(dims,extents,nstenc) if (~isnumeric(dims))||(~isreal(dims))||(any(dims<1))||any(mod(dims,1)~=0) error('npoints must be a three-element vector of positive integers.'); end if (~isnumeric(extents))||(~isreal(extents))||(any(extents<=0)) error('extents must be an array of positive real numbers.'); end if any(dims<nstenc) error('array dimension is not big enough for the finite difference stencil specified.'); end if (mod(nstenc,1)~=0)||(mod(nstenc,2)~=1)||(nstenc<3) error('the number of stencil points must be an odd integer greater or equal to 3.'); end end % We owe no morality to those who hold us under a gun. % % Ayn Rand
github
tsajed/nmr-pred-master
pauli.m
.m
nmr-pred-master/spinach/kernel/utilities/pauli.m
2,086
utf_8
94982ebd7f6c7f8dd68c8cafd23752b3
% Pauli matrices for a spin of user-specified multiplicity. Syntax: % % sigma=pauli(mult) % % Where mult is an integer specifying the multiplicity and the following % fields are returned in the output: % % sigma.u - unit operator % % sigma.p - raising operator % % sigma.m - lowering operator % % sigma.x - Pauli sigma_x matrix % % sigma.y - Pauli sigma_y matrix % % sigma.z - Pauli sigma_z matrix % % The matrices are normalized so as to fulfil the following commutation % relations: % % [sigma.x,sigma.y]=1i*pauli.z % [sigma.y,sigma.z]=1i*pauli.x % [sigma.z,sigma.x]=1i*pauli.y % % with the raising and lowering operators defined as: % % sigma.p=sigma.x+1i*sigma.y % sigma.m=sigma.x-1i*sigma.y % % [email protected] function sigma=pauli(mult) % Make sure the input is valid if (~isnumeric(mult))||(~isscalar(mult))||(~isreal(mult))||... (mult<0)||(mod(mult,1)~=0) error('spin multiplicity must be a positive integer.'); end % Get the Pauli matrices if mult==2 % Spin-half matrices are hard-coded for speed sigma.u=sparse([1 0; 0 1]); sigma.p=sparse([0 1; 0 0]); sigma.m=sparse([0 0; 1 0]); sigma.z=sparse([0.5 0; 0 -0.5]); sigma.x=0.5*(sigma.p+sigma.m); sigma.y=-0.5*1i*(sigma.p-sigma.m); else % Everything else goes through the standard procedure spin=(mult-1)/2; prjs=((mult-1):-1:0)-spin; sigma.u=speye(mult,mult); sigma.p=spdiags(sqrt(spin*(spin+1)-prjs.*(prjs+1))',1,mult,mult); sigma.m=spdiags(sqrt(spin*(spin+1)-prjs.*(prjs-1))',-1,mult,mult); sigma.x=0.5*(sigma.p+sigma.m); sigma.y=-0.5*1i*(sigma.p-sigma.m); sigma.z=spdiags(prjs',0,mult,mult); end end % Any refusal to recognize reality, for any reason whatever, has dis- % astrous consequences. There are no evil thoughts except one -- the % refusal to think. Don't ignore your own desires... Don't sacrifice % them. Examine their cause. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
frac2cart.m
.m
nmr-pred-master/spinach/kernel/utilities/frac2cart.m
1,952
utf_8
0c9b8c549348af909189f3550078b96d
% Converts fractional crystallographic coordinates to Cartesian % coordinates. Syntax: % % [XYZ,va,vb,vc]=frac2cart(a,b,c,alpha,beta,gamma,ABC) % % Parameters: % % a,b,c - three unit cell dimensions % % alp,bet,gam - three unit cell angles, degrees % % ABC - fractional atomic coordinates as % Nx3 array of numbers % % Outputs: % % XYZ - Cartesian atomic coordinates as % Nx3 array of numbers % % va, vb, vc - primitive lattice vectors % % [email protected] function [XYZ,va,vb,vc]=frac2cart(a,b,c,alp,bet,gam,ABC) % Check consistency grumble(a,b,c,alp,bet,gam,ABC); % Compute the transformation matrix v=a*b*c*sqrt(1-cosd(alp)^2-cosd(bet)^2-cosd(gam)^2+2*cosd(alp)*cosd(bet)*cosd(gam)); T=[a b*cosd(gam) c*cosd(bet); 0 b*sind(gam) c*(cosd(alp)-cosd(bet)*cosd(gam))/sind(gam); 0 0 v/(a*b*sind(gam))]; % Apply the transformation matrix XYZ=(T*ABC')'; % Get the primitive vectors va=T(:,1); vb=T(:,2); vc=T(:,3); end % Consistency enforcement function grumble(a,b,c,alp,bet,gam,ABC) if (~isnumeric(a))||(~isscalar(a))||(~isreal(a))||(a<=0)||... (~isnumeric(b))||(~isscalar(b))||(~isreal(b))||(b<=0)||... (~isnumeric(c))||(~isscalar(c))||(~isreal(c))||(c<=0) error('a, b, c must be positive real numbers.'); end if (~isnumeric(alp))||(~isscalar(alp))||(~isreal(alp))||... (~isnumeric(bet))||(~isscalar(bet))||(~isreal(bet))||... (~isnumeric(gam))||(~isscalar(gam))||(~isreal(gam)) error('alp, bet, gam must be real scalars.'); end if (~isnumeric(ABC))||(~isreal(ABC))||(size(ABC,2)~=3) error('ABC must be an Nx3 array of real numbers.'); end end % Socialism never took root in America because the poor see % themselves not as an exploited proletariat but as tempora- % rily embarrassed millionaires. % % John Steinbeck
github
tsajed/nmr-pred-master
significant.m
.m
nmr-pred-master/spinach/kernel/utilities/significant.m
1,320
utf_8
ef8c331e427f57f0ef381578b27360ea
% An aux function determining whether a given object deserves attention % given the tolerance specified. Used in the internal decision making % performed by Spinach kernel functions. Syntax: % % answer=significant(object,tolerance) % % Parameters: % % object - the object whose significance is to be assessed % % tolerance - significance threshold % % The function returns a logical value. If the object cannot be asses- % ed based on the current heuristics, it is deemed significant. % % [email protected] function answer=significant(object,tolerance) % Check the input if (~isnumeric(tolerance))||(~isscalar(tolerance))||(~isreal(tolerance))||(tolerance<0) error('tolerance parameter must be a non-negative real number.'); end % Decide on the significance if ~isnumeric(object) % Non-numeric objects are significant answer=true(); elseif isempty(object) % Empty arrays are not significant answer=false(); elseif norm(object,1)<tolerance % Arrays with a small norm are not significant answer=false(); else % Everything else is significant answer=true(); end end % There is a beast in man that needs to be exercised, not exorcised. % % Anton Szandor LaVey
github
tsajed/nmr-pred-master
perm_group.m
.m
nmr-pred-master/spinach/kernel/utilities/perm_group.m
19,832
utf_8
71e331975b2c3366baddf4db358c5ed4
% Permutation group database. Returns basic information about permutation % groups up to S6. Syntax: % % group=perm_group(group_name) % % The following group names are available: S2, S3, S4, S5, S6, S4A, the % latter one being the largest Abelian subgroup of S4. % % Output fields: % % group.name - long name of the group % % group.order - number of elements in the group % % group.nclasses - number of classes in the group % % group.class_sizes - a row vector giving number of elements % in each class % % group.class - a cell array of matrices giving the ele- % ments belonging to each class. The ele- % ments are given as row vectors of permu- % tation strings stacked vertically into % a matrix. % % group.n_irreps - number of irreducible representations in % the group % % group.irrep_dims - a row vector giving dimensions of irre- % ducible representation % % group.class_characters - a matrix of characters for each irredu- % cible representation (in rows) of each % class (in columns). % % [email protected] function group=perm_group(group_name) switch group_name case 'S2' group.name='S2 permutation group (Abelian)'; group.order=2; group.nclasses=2; group.class_sizes=[1 1]; group.class{1}=[1 2]; group.class{2}=[2 1]; group.n_irreps=2; group.irrep_dims=[1 1]; group.class_characters=[1 1; 1 -1]; case 'S3' group.name='S3 permutation group (non-Abelian)'; group.order=6; group.nclasses=3; group.class_sizes=[1 2 3]; group.class{1}=[1 2 3]; group.class{2}=[2 3 1; 3 1 2]; group.class{3}=[1 3 2; 3 2 1; 2 1 3]; group.n_irreps=3; group.irrep_dims=[1 1 2]; group.class_characters=[1 1 1; 1 1 -1; 2 -1 0]; case 'S4' group.name='S4 permutation group (non-Abelian)'; group.order=24; group.nclasses=5; group.class_sizes=[1 6 8 6 3]; group.class{1}=[1 2 3 4]; group.class{2}=[2 3 4 1; 2 4 1 3; 3 1 4 2; 3 4 2 1; 4 1 2 3; 4 3 1 2]; group.class{3}=[1 3 4 2; 1 4 2 3; 4 2 1 3; 3 2 4 1; 2 4 3 1; 4 1 3 2; 3 1 2 4; 2 3 1 4]; group.class{4}=[1 2 4 3; 1 3 2 4; 1 4 3 2; 2 1 3 4; 4 2 3 1; 3 2 1 4]; group.class{5}=[2 1 4 3; 3 4 1 2; 4 3 2 1]; group.n_irreps=5; group.irrep_dims=[1 1 2 3 3]; group.class_characters=[1 1 1 1 1;... 1 -1 1 -1 1;... 2 0 -1 0 2;... 3 1 0 -1 -1;... 3 -1 0 1 -1]; case 'S5' group.name='S5 permutation group (non-Abelian)'; group.order=120; group.nclasses=7; group.class_sizes=[1 10 20 15 30 20 24]; group.class{1}=[1 2 3 4 5]; group.class{2}=[1 2 3 5 4; 1 2 4 3 5; 1 2 5 4 3; 1 3 2 4 5; 1 4 3 2 5; 1 5 3 4 2; 2 1 3 4 5; 3 2 1 4 5; 4 2 3 1 5; 5 2 3 4 1]; group.class{3}=[1 2 4 5 3; 1 2 5 3 4; 1 3 4 2 5; 1 3 5 4 2; 1 4 2 3 5; 1 4 3 5 2; 1 5 2 4 3; 1 5 3 2 4; 2 3 1 4 5; 2 4 3 1 5; 2 5 3 4 1; 3 1 2 4 5; 3 2 4 1 5; 3 2 5 4 1; 4 1 3 2 5; 4 2 1 3 5; 4 2 3 5 1; 5 1 3 4 2; 5 2 1 4 3; 5 2 3 1 4]; group.class{4}=[1 3 2 5 4; 1 4 5 2 3; 1 5 4 3 2; 2 1 3 5 4; 2 1 4 3 5; 2 1 5 4 3; 3 2 1 5 4; 3 4 1 2 5; 3 5 1 4 2; 4 2 5 1 3; 4 3 2 1 5; 4 5 3 1 2; 5 2 4 3 1; 5 3 2 4 1; 5 4 3 2 1]; group.class{5}=[1 3 4 5 2; 1 3 5 2 4; 1 4 2 5 3; 1 4 5 3 2; 1 5 2 3 4; 1 5 4 2 3; 2 3 4 1 5; 2 3 5 4 1; 2 4 1 3 5; 2 4 3 5 1; 2 5 1 4 3; 2 5 3 1 4; 3 1 4 2 5; 3 1 5 4 2; 3 2 4 5 1; 3 2 5 1 4; 3 4 2 1 5; 3 5 2 4 1; 4 1 2 3 5; 4 1 3 5 2; 4 2 1 5 3; 4 2 5 3 1; 4 3 1 2 5; 4 5 3 2 1; 5 1 2 4 3; 5 1 3 2 4; 5 2 1 3 4; 5 2 4 1 3; 5 3 1 4 2; 5 4 3 1 2]; group.class{6}=[2 1 4 5 3; 2 1 5 3 4; 2 3 1 5 4; 2 4 5 1 3; 2 5 4 3 1; 3 1 2 5 4; 3 4 1 5 2; 3 4 5 2 1; 3 5 1 2 4; 3 5 4 1 2; 4 1 5 2 3; 4 3 2 5 1; 4 3 5 1 2; 4 5 1 3 2; 4 5 2 1 3; 5 1 4 3 2; 5 3 2 1 4; 5 3 4 2 1; 5 4 1 2 3; 5 4 2 3 1]; group.class{7}=[2 3 4 5 1; 2 3 5 1 4; 2 4 1 5 3; 2 4 5 3 1; 2 5 1 3 4; 2 5 4 1 3; 3 1 4 5 2; 3 1 5 2 4; 3 4 2 5 1; 3 4 5 1 2; 3 5 2 1 4; 3 5 4 2 1; 4 1 2 5 3; 4 1 5 3 2; 4 3 1 5 2; 4 3 5 2 1; 4 5 1 2 3; 4 5 2 3 1; 5 1 2 3 4; 5 1 4 2 3; 5 3 1 2 4; 5 3 4 1 2; 5 4 1 3 2; 5 4 2 1 3]; group.n_irreps=7; group.irrep_dims=[1 1 4 4 6 5 5]; group.class_characters=[1 1 1 1 1 1 1; 1 -1 1 1 -1 -1 1; 4 2 1 0 0 -1 -1; 4 -2 1 0 0 1 -1; 6 0 0 -2 0 0 1; 5 1 -1 1 -1 1 0; 5 -1 -1 1 1 -1 0]; case 'S6' group.name='S6 permutation group (non-Abelian)'; group.order=720; group.nclasses=11; group.class_sizes=[1 15 40 45 90 120 144 15 40 90 120]; group.class{1}=[1 2 3 4 5 6]; group.class{2}=[1 2 3 4 6 5; 1 2 3 5 4 6; 1 2 3 6 5 4; 1 2 4 3 5 6; 1 2 5 4 3 6; 1 2 6 4 5 3; 1 3 2 4 5 6; 1 4 3 2 5 6; 1 5 3 4 2 6; 1 6 3 4 5 2; 2 1 3 4 5 6; 3 2 1 4 5 6; 4 2 3 1 5 6; 5 2 3 4 1 6; 6 2 3 4 5 1]; group.class{3}=[1 2 3 5 6 4; 1 2 3 6 4 5; 1 2 4 5 3 6; 1 2 4 6 5 3; 1 2 5 3 4 6; 1 2 5 4 6 3; 1 2 6 3 5 4; 1 2 6 4 3 5; 1 3 4 2 5 6; 1 3 5 4 2 6; 1 3 6 4 5 2; 1 4 2 3 5 6; 1 4 3 5 2 6; 1 4 3 6 5 2; 1 5 2 4 3 6; 1 5 3 2 4 6; 1 5 3 4 6 2; 1 6 2 4 5 3; 1 6 3 2 5 4; 1 6 3 4 2 5; 2 3 1 4 5 6; 2 4 3 1 5 6; 2 5 3 4 1 6; 2 6 3 4 5 1; 3 1 2 4 5 6; 3 2 4 1 5 6; 3 2 5 4 1 6; 3 2 6 4 5 1; 4 1 3 2 5 6; 4 2 1 3 5 6; 4 2 3 5 1 6; 4 2 3 6 5 1; 5 1 3 4 2 6; 5 2 1 4 3 6; 5 2 3 1 4 6; 5 2 3 4 6 1; 6 1 3 4 5 2; 6 2 1 4 5 3; 6 2 3 1 5 4; 6 2 3 4 1 5]; group.class{4}=[1 2 4 3 6 5; 1 2 5 6 3 4; 1 2 6 5 4 3; 1 3 2 4 6 5; 1 3 2 5 4 6; 1 3 2 6 5 4; 1 4 3 2 6 5; 1 4 5 2 3 6; 1 4 6 2 5 3; 1 5 3 6 2 4; 1 5 4 3 2 6; 1 5 6 4 2 3; 1 6 3 5 4 2; 1 6 4 3 5 2; 1 6 5 4 3 2; 2 1 3 4 6 5; 2 1 3 5 4 6; 2 1 3 6 5 4; 2 1 4 3 5 6; 2 1 5 4 3 6; 2 1 6 4 5 3; 3 2 1 4 6 5; 3 2 1 5 4 6; 3 2 1 6 5 4; 3 4 1 2 5 6; 3 5 1 4 2 6; 3 6 1 4 5 2; 4 2 3 1 6 5; 4 2 5 1 3 6; 4 2 6 1 5 3; 4 3 2 1 5 6; 4 5 3 1 2 6; 4 6 3 1 5 2; 5 2 3 6 1 4; 5 2 4 3 1 6; 5 2 6 4 1 3; 5 3 2 4 1 6; 5 4 3 2 1 6; 5 6 3 4 1 2; 6 2 3 5 4 1; 6 2 4 3 5 1; 6 2 5 4 3 1; 6 3 2 4 5 1; 6 4 3 2 5 1; 6 5 3 4 2 1]; group.class{5}=[1 2 4 5 6 3; 1 2 4 6 3 5; 1 2 5 3 6 4; 1 2 5 6 4 3; 1 2 6 3 4 5; 1 2 6 5 3 4; 1 3 4 5 2 6; 1 3 4 6 5 2; 1 3 5 2 4 6; 1 3 5 4 6 2; 1 3 6 2 5 4; 1 3 6 4 2 5; 1 4 2 5 3 6; 1 4 2 6 5 3; 1 4 3 5 6 2; 1 4 3 6 2 5; 1 4 5 3 2 6; 1 4 6 3 5 2; 1 5 2 3 4 6; 1 5 2 4 6 3; 1 5 3 2 6 4; 1 5 3 6 4 2; 1 5 4 2 3 6; 1 5 6 4 3 2; 1 6 2 3 5 4; 1 6 2 4 3 5; 1 6 3 2 4 5; 1 6 3 5 2 4; 1 6 4 2 5 3; 1 6 5 4 2 3; 2 3 4 1 5 6; 2 3 5 4 1 6; 2 3 6 4 5 1; 2 4 1 3 5 6; 2 4 3 5 1 6; 2 4 3 6 5 1; 2 5 1 4 3 6; 2 5 3 1 4 6; 2 5 3 4 6 1; 2 6 1 4 5 3; 2 6 3 1 5 4; 2 6 3 4 1 5; 3 1 4 2 5 6; 3 1 5 4 2 6; 3 1 6 4 5 2; 3 2 4 5 1 6; 3 2 4 6 5 1; 3 2 5 1 4 6; 3 2 5 4 6 1; 3 2 6 1 5 4; 3 2 6 4 1 5; 3 4 2 1 5 6; 3 5 2 4 1 6; 3 6 2 4 5 1; 4 1 2 3 5 6; 4 1 3 5 2 6; 4 1 3 6 5 2; 4 2 1 5 3 6; 4 2 1 6 5 3; 4 2 3 5 6 1; 4 2 3 6 1 5; 4 2 5 3 1 6; 4 2 6 3 5 1; 4 3 1 2 5 6; 4 5 3 2 1 6; 4 6 3 2 5 1; 5 1 2 4 3 6; 5 1 3 2 4 6; 5 1 3 4 6 2; 5 2 1 3 4 6; 5 2 1 4 6 3; 5 2 3 1 6 4; 5 2 3 6 4 1; 5 2 4 1 3 6; 5 2 6 4 3 1; 5 3 1 4 2 6; 5 4 3 1 2 6; 5 6 3 4 2 1; 6 1 2 4 5 3; 6 1 3 2 5 4; 6 1 3 4 2 5; 6 2 1 3 5 4; 6 2 1 4 3 5; 6 2 3 1 4 5; 6 2 3 5 1 4; 6 2 4 1 5 3; 6 2 5 4 1 3; 6 3 1 4 5 2; 6 4 3 1 5 2; 6 5 3 4 1 2]; group.class{6}=[1 3 2 5 6 4; 1 3 2 6 4 5; 1 3 4 2 6 5; 1 3 5 6 2 4; 1 3 6 5 4 2; 1 4 2 3 6 5; 1 4 5 2 6 3; 1 4 5 6 3 2; 1 4 6 2 3 5; 1 4 6 5 2 3; 1 5 2 6 3 4; 1 5 4 3 6 2; 1 5 4 6 2 3; 1 5 6 2 4 3; 1 5 6 3 2 4; 1 6 2 5 4 3; 1 6 4 3 2 5; 1 6 4 5 3 2; 1 6 5 2 3 4; 1 6 5 3 4 2; 2 1 3 5 6 4; 2 1 3 6 4 5; 2 1 4 5 3 6; 2 1 4 6 5 3; 2 1 5 3 4 6; 2 1 5 4 6 3; 2 1 6 3 5 4; 2 1 6 4 3 5; 2 3 1 4 6 5; 2 3 1 5 4 6; 2 3 1 6 5 4; 2 4 3 1 6 5; 2 4 5 1 3 6; 2 4 6 1 5 3; 2 5 3 6 1 4; 2 5 4 3 1 6; 2 5 6 4 1 3; 2 6 3 5 4 1; 2 6 4 3 5 1; 2 6 5 4 3 1; 3 1 2 4 6 5; 3 1 2 5 4 6; 3 1 2 6 5 4; 3 2 1 5 6 4; 3 2 1 6 4 5; 3 2 4 1 6 5; 3 2 5 6 1 4; 3 2 6 5 4 1; 3 4 1 5 2 6; 3 4 1 6 5 2; 3 4 5 2 1 6; 3 4 6 2 5 1; 3 5 1 2 4 6; 3 5 1 4 6 2; 3 5 4 1 2 6; 3 5 6 4 2 1; 3 6 1 2 5 4; 3 6 1 4 2 5; 3 6 4 1 5 2; 3 6 5 4 1 2; 4 1 3 2 6 5; 4 1 5 2 3 6; 4 1 6 2 5 3; 4 2 1 3 6 5; 4 2 5 1 6 3; 4 2 5 6 3 1; 4 2 6 1 3 5; 4 2 6 5 1 3; 4 3 2 5 1 6; 4 3 2 6 5 1; 4 3 5 1 2 6; 4 3 6 1 5 2; 4 5 1 3 2 6; 4 5 2 1 3 6; 4 5 3 1 6 2; 4 5 3 6 2 1; 4 6 1 3 5 2; 4 6 2 1 5 3; 4 6 3 1 2 5; 4 6 3 5 1 2; 5 1 3 6 2 4; 5 1 4 3 2 6; 5 1 6 4 2 3; 5 2 1 6 3 4; 5 2 4 3 6 1; 5 2 4 6 1 3; 5 2 6 1 4 3; 5 2 6 3 1 4; 5 3 2 1 4 6; 5 3 2 4 6 1; 5 3 4 2 1 6; 5 3 6 4 1 2; 5 4 1 2 3 6; 5 4 2 3 1 6; 5 4 3 2 6 1; 5 4 3 6 1 2; 5 6 1 4 3 2; 5 6 2 4 1 3; 5 6 3 1 4 2; 5 6 3 2 1 4; 6 1 3 5 4 2; 6 1 4 3 5 2; 6 1 5 4 3 2; 6 2 1 5 4 3; 6 2 4 3 1 5; 6 2 4 5 3 1; 6 2 5 1 3 4; 6 2 5 3 4 1; 6 3 2 1 5 4; 6 3 2 4 1 5; 6 3 4 2 5 1; 6 3 5 4 2 1; 6 4 1 2 5 3; 6 4 2 3 5 1; 6 4 3 2 1 5; 6 4 3 5 2 1; 6 5 1 4 2 3; 6 5 2 4 3 1; 6 5 3 1 2 4; 6 5 3 2 4 1]; group.class{7}=[1 3 4 5 6 2; 1 3 4 6 2 5; 1 3 5 2 6 4; 1 3 5 6 4 2; 1 3 6 2 4 5; 1 3 6 5 2 4; 1 4 2 5 6 3; 1 4 2 6 3 5; 1 4 5 3 6 2; 1 4 5 6 2 3; 1 4 6 3 2 5; 1 4 6 5 3 2; 1 5 2 3 6 4; 1 5 2 6 4 3; 1 5 4 2 6 3; 1 5 4 6 3 2; 1 5 6 2 3 4; 1 5 6 3 4 2; 1 6 2 3 4 5; 1 6 2 5 3 4; 1 6 4 2 3 5; 1 6 4 5 2 3; 1 6 5 2 4 3; 1 6 5 3 2 4; 2 3 4 5 1 6; 2 3 4 6 5 1; 2 3 5 1 4 6; 2 3 5 4 6 1; 2 3 6 1 5 4; 2 3 6 4 1 5; 2 4 1 5 3 6; 2 4 1 6 5 3; 2 4 3 5 6 1; 2 4 3 6 1 5; 2 4 5 3 1 6; 2 4 6 3 5 1; 2 5 1 3 4 6; 2 5 1 4 6 3; 2 5 3 1 6 4; 2 5 3 6 4 1; 2 5 4 1 3 6; 2 5 6 4 3 1; 2 6 1 3 5 4; 2 6 1 4 3 5; 2 6 3 1 4 5; 2 6 3 5 1 4; 2 6 4 1 5 3; 2 6 5 4 1 3; 3 1 4 5 2 6; 3 1 4 6 5 2; 3 1 5 2 4 6; 3 1 5 4 6 2; 3 1 6 2 5 4; 3 1 6 4 2 5; 3 2 4 5 6 1; 3 2 4 6 1 5; 3 2 5 1 6 4; 3 2 5 6 4 1; 3 2 6 1 4 5; 3 2 6 5 1 4; 3 4 2 5 1 6; 3 4 2 6 5 1; 3 4 5 1 2 6; 3 4 6 1 5 2; 3 5 2 1 4 6; 3 5 2 4 6 1; 3 5 4 2 1 6; 3 5 6 4 1 2; 3 6 2 1 5 4; 3 6 2 4 1 5; 3 6 4 2 5 1; 3 6 5 4 2 1; 4 1 2 5 3 6; 4 1 2 6 5 3; 4 1 3 5 6 2; 4 1 3 6 2 5; 4 1 5 3 2 6; 4 1 6 3 5 2; 4 2 1 5 6 3; 4 2 1 6 3 5; 4 2 5 3 6 1; 4 2 5 6 1 3; 4 2 6 3 1 5; 4 2 6 5 3 1; 4 3 1 5 2 6; 4 3 1 6 5 2; 4 3 5 2 1 6; 4 3 6 2 5 1; 4 5 1 2 3 6; 4 5 2 3 1 6; 4 5 3 2 6 1; 4 5 3 6 1 2; 4 6 1 2 5 3; 4 6 2 3 5 1; 4 6 3 2 1 5; 4 6 3 5 2 1; 5 1 2 3 4 6; 5 1 2 4 6 3; 5 1 3 2 6 4; 5 1 3 6 4 2; 5 1 4 2 3 6; 5 1 6 4 3 2; 5 2 1 3 6 4; 5 2 1 6 4 3; 5 2 4 1 6 3; 5 2 4 6 3 1; 5 2 6 1 3 4; 5 2 6 3 4 1; 5 3 1 2 4 6; 5 3 1 4 6 2; 5 3 4 1 2 6; 5 3 6 4 2 1; 5 4 1 3 2 6; 5 4 2 1 3 6; 5 4 3 1 6 2; 5 4 3 6 2 1; 5 6 1 4 2 3; 5 6 2 4 3 1; 5 6 3 1 2 4; 5 6 3 2 4 1; 6 1 2 3 5 4; 6 1 2 4 3 5; 6 1 3 2 4 5; 6 1 3 5 2 4; 6 1 4 2 5 3; 6 1 5 4 2 3; 6 2 1 3 4 5; 6 2 1 5 3 4; 6 2 4 1 3 5; 6 2 4 5 1 3; 6 2 5 1 4 3; 6 2 5 3 1 4; 6 3 1 2 5 4; 6 3 1 4 2 5; 6 3 4 1 5 2; 6 3 5 4 1 2; 6 4 1 3 5 2; 6 4 2 1 5 3; 6 4 3 1 2 5; 6 4 3 5 1 2; 6 5 1 4 3 2; 6 5 2 4 1 3; 6 5 3 1 4 2; 6 5 3 2 1 4]; group.class{8}=[2 1 4 3 6 5; 2 1 5 6 3 4; 2 1 6 5 4 3; 3 4 1 2 6 5; 3 5 1 6 2 4; 3 6 1 5 4 2; 4 3 2 1 6 5; 4 5 6 1 2 3; 4 6 5 1 3 2; 5 3 2 6 1 4; 5 4 6 2 1 3; 5 6 4 3 1 2; 6 3 2 5 4 1; 6 4 5 2 3 1; 6 5 4 3 2 1]; group.class{9}=[2 3 1 5 6 4; 2 3 1 6 4 5; 2 4 5 1 6 3; 2 4 6 1 3 5; 2 5 4 6 1 3; 2 5 6 3 1 4; 2 6 4 5 3 1; 2 6 5 3 4 1; 3 1 2 5 6 4; 3 1 2 6 4 5; 3 4 5 6 1 2; 3 4 6 5 2 1; 3 5 4 1 6 2; 3 5 6 2 4 1; 3 6 4 1 2 5; 3 6 5 2 1 4; 4 1 5 2 6 3; 4 1 6 2 3 5; 4 3 5 6 2 1; 4 3 6 5 1 2; 4 5 1 3 6 2; 4 5 2 6 3 1; 4 6 1 3 2 5; 4 6 2 5 1 3; 5 1 4 6 2 3; 5 1 6 3 2 4; 5 3 4 2 6 1; 5 3 6 1 4 2; 5 4 1 6 3 2; 5 4 2 3 6 1; 5 6 1 2 3 4; 5 6 2 1 4 3; 6 1 4 5 3 2; 6 1 5 3 4 2; 6 3 4 2 1 5; 6 3 5 1 2 4; 6 4 1 5 2 3; 6 4 2 3 1 5; 6 5 1 2 4 3; 6 5 2 1 3 4]; group.class{10}=[2 1 4 5 6 3; 2 1 4 6 3 5; 2 1 5 3 6 4; 2 1 5 6 4 3; 2 1 6 3 4 5; 2 1 6 5 3 4; 2 3 4 1 6 5; 2 3 5 6 1 4; 2 3 6 5 4 1; 2 4 1 3 6 5; 2 4 5 6 3 1; 2 4 6 5 1 3; 2 5 1 6 3 4; 2 5 4 3 6 1; 2 5 6 1 4 3; 2 6 1 5 4 3; 2 6 4 3 1 5; 2 6 5 1 3 4; 3 1 4 2 6 5; 3 1 5 6 2 4; 3 1 6 5 4 2; 3 4 1 5 6 2; 3 4 1 6 2 5; 3 4 2 1 6 5; 3 4 5 2 6 1; 3 4 6 2 1 5; 3 5 1 2 6 4; 3 5 1 6 4 2; 3 5 2 6 1 4; 3 5 4 6 2 1; 3 5 6 1 2 4; 3 6 1 2 4 5; 3 6 1 5 2 4; 3 6 2 5 4 1; 3 6 4 5 1 2; 3 6 5 1 4 2; 4 1 2 3 6 5; 4 1 5 6 3 2; 4 1 6 5 2 3; 4 3 1 2 6 5; 4 3 2 5 6 1; 4 3 2 6 1 5; 4 3 5 1 6 2; 4 3 6 1 2 5; 4 5 1 6 2 3; 4 5 2 1 6 3; 4 5 6 1 3 2; 4 5 6 2 1 3; 4 5 6 3 2 1; 4 6 1 5 3 2; 4 6 2 1 3 5; 4 6 5 1 2 3; 4 6 5 2 3 1; 4 6 5 3 1 2; 5 1 2 6 3 4; 5 1 4 3 6 2; 5 1 6 2 4 3; 5 3 1 6 2 4; 5 3 2 1 6 4; 5 3 2 6 4 1; 5 3 4 6 1 2; 5 3 6 2 1 4; 5 4 1 2 6 3; 5 4 2 6 1 3; 5 4 6 1 2 3; 5 4 6 2 3 1; 5 4 6 3 1 2; 5 6 1 3 4 2; 5 6 2 3 1 4; 5 6 4 1 3 2; 5 6 4 2 1 3; 5 6 4 3 2 1; 6 1 2 5 4 3; 6 1 4 3 2 5; 6 1 5 2 3 4; 6 3 1 5 4 2; 6 3 2 1 4 5; 6 3 2 5 1 4; 6 3 4 5 2 1; 6 3 5 2 4 1; 6 4 1 2 3 5; 6 4 2 5 3 1; 6 4 5 1 3 2; 6 4 5 2 1 3; 6 4 5 3 2 1; 6 5 1 3 2 4; 6 5 2 3 4 1; 6 5 4 1 2 3; 6 5 4 2 3 1; 6 5 4 3 1 2]; group.class{11}=[2 3 4 5 6 1; 2 3 4 6 1 5; 2 3 5 1 6 4; 2 3 5 6 4 1; 2 3 6 1 4 5; 2 3 6 5 1 4; 2 4 1 5 6 3; 2 4 1 6 3 5; 2 4 5 3 6 1; 2 4 5 6 1 3; 2 4 6 3 1 5; 2 4 6 5 3 1; 2 5 1 3 6 4; 2 5 1 6 4 3; 2 5 4 1 6 3; 2 5 4 6 3 1; 2 5 6 1 3 4; 2 5 6 3 4 1; 2 6 1 3 4 5; 2 6 1 5 3 4; 2 6 4 1 3 5; 2 6 4 5 1 3; 2 6 5 1 4 3; 2 6 5 3 1 4; 3 1 4 5 6 2; 3 1 4 6 2 5; 3 1 5 2 6 4; 3 1 5 6 4 2; 3 1 6 2 4 5; 3 1 6 5 2 4; 3 4 2 5 6 1; 3 4 2 6 1 5; 3 4 5 1 6 2; 3 4 5 6 2 1; 3 4 6 1 2 5; 3 4 6 5 1 2; 3 5 2 1 6 4; 3 5 2 6 4 1; 3 5 4 2 6 1; 3 5 4 6 1 2; 3 5 6 1 4 2; 3 5 6 2 1 4; 3 6 2 1 4 5; 3 6 2 5 1 4; 3 6 4 2 1 5; 3 6 4 5 2 1; 3 6 5 1 2 4; 3 6 5 2 4 1; 4 1 2 5 6 3; 4 1 2 6 3 5; 4 1 5 3 6 2; 4 1 5 6 2 3; 4 1 6 3 2 5; 4 1 6 5 3 2; 4 3 1 5 6 2; 4 3 1 6 2 5; 4 3 5 2 6 1; 4 3 5 6 1 2; 4 3 6 2 1 5; 4 3 6 5 2 1; 4 5 1 2 6 3; 4 5 1 6 3 2; 4 5 2 3 6 1; 4 5 2 6 1 3; 4 5 6 2 3 1; 4 5 6 3 1 2; 4 6 1 2 3 5; 4 6 1 5 2 3; 4 6 2 3 1 5; 4 6 2 5 3 1; 4 6 5 2 1 3; 4 6 5 3 2 1; 5 1 2 3 6 4; 5 1 2 6 4 3; 5 1 4 2 6 3; 5 1 4 6 3 2; 5 1 6 2 3 4; 5 1 6 3 4 2; 5 3 1 2 6 4; 5 3 1 6 4 2; 5 3 4 1 6 2; 5 3 4 6 2 1; 5 3 6 1 2 4; 5 3 6 2 4 1; 5 4 1 3 6 2; 5 4 1 6 2 3; 5 4 2 1 6 3; 5 4 2 6 3 1; 5 4 6 1 3 2; 5 4 6 3 2 1; 5 6 1 2 4 3; 5 6 1 3 2 4; 5 6 2 1 3 4; 5 6 2 3 4 1; 5 6 4 1 2 3; 5 6 4 2 3 1; 6 1 2 3 4 5; 6 1 2 5 3 4; 6 1 4 2 3 5; 6 1 4 5 2 3; 6 1 5 2 4 3; 6 1 5 3 2 4; 6 3 1 2 4 5; 6 3 1 5 2 4; 6 3 4 1 2 5; 6 3 4 5 1 2; 6 3 5 1 4 2; 6 3 5 2 1 4; 6 4 1 3 2 5; 6 4 1 5 3 2; 6 4 2 1 3 5; 6 4 2 5 1 3; 6 4 5 1 2 3; 6 4 5 3 1 2; 6 5 1 2 3 4; 6 5 1 3 4 2; 6 5 2 1 4 3; 6 5 2 3 1 4; 6 5 4 1 3 2; 6 5 4 2 1 3]; group.n_irreps=11; group.irrep_dims=[1 1 5 5 10 10 9 9 5 5 16]; group.class_characters=[1 1 1 1 1 1 1 1 1 1 1; 1 -1 1 1 -1 -1 1 -1 1 1 -1; 5 3 2 1 1 0 0 -1 -1 -1 -1; 5 -3 2 1 -1 0 0 1 -1 -1 1; 10 2 1 -2 0 -1 0 -2 1 0 1; 10 -2 1 -2 0 1 0 2 1 0 -1; 9 3 0 1 -1 0 -1 3 0 1 0; 9 -3 0 1 1 0 -1 -3 0 1 0; 5 1 -1 1 -1 1 0 -3 2 -1 0; 5 -1 -1 1 1 -1 0 3 2 -1 0; 16 0 -2 0 0 0 1 0 -2 0 0]; case 'S4A' group.name='Largest Abelian subgroup of S4 permutation group'; group.order=8; group.nclasses=8; group.class_sizes=[1 1 1 1 1 1 1 1]; group.class{1}=[1 2 3 4]; group.class{2}=[4 3 2 1]; group.class{3}=[2 1 4 3]; group.class{4}=[3 4 1 2]; group.class{5}=[4 3 2 1]; group.class{6}=[1 2 3 4]; group.class{7}=[3 4 1 2]; group.class{8}=[2 1 4 3]; group.n_irreps=8; group.irrep_dims=[1 1 1 1 1 1 1 1]; group.class_characters=[1 1 1 1 1 1 1 1; 1 1 -1 -1 1 1 -1 -1; 1 -1 1 -1 1 -1 1 -1; 1 -1 -1 1 1 -1 -1 1; 1 1 1 1 -1 -1 -1 -1; 1 1 -1 -1 -1 -1 1 1; 1 -1 1 -1 -1 1 -1 1; 1 -1 -1 1 -1 1 1 -1]; otherwise error(['permutation group ' group_name ' is not available.']); end % Get the list of group elements group.elements=vertcat(group.class{:}); % Transform class-wise character list into element-wise list group.characters=zeros(length(group.class_sizes),sum(group.class_sizes)); for n=1:length(group.class_sizes) for k=1:group.class_sizes(n) group.characters(:,sum(group.class_sizes(1:(n-1)))+k)=group.class_characters(:,n); end end end % It's so wonderful to see a great, new, crucial idea which is not mine! % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
killcross.m
.m
nmr-pred-master/spinach/kernel/utilities/killcross.m
255
utf_8
f6071b17d58bcea310d1fe40e4f234be
% Wipes the specified rows and columns. % % [email protected] function spec=killcross(spec,f1idx,f2idx) % Wipe the indices spec(f2idx,:)=0; spec(:,f1idx)=0; end % A narcissist is someone better-looking than you are. % % Gore Vidal
github
tsajed/nmr-pred-master
symmetry.m
.m
nmr-pred-master/spinach/kernel/utilities/symmetry.m
10,436
utf_8
ea35bca6be1eb1968685ab6164d9f981
% Symmetry treatment. This is a service function of the Spinach % kernel that should not be called directly. % % [email protected] % [email protected] function spin_system=symmetry(spin_system,bas) % Check consistency grumble(spin_system,bas); % Check the disable switch if ismember('symmetry',spin_system.sys.disable) % Issue a reminder to the user report(spin_system,'WARNING - symmetry factorization disabled by the user.'); % Write empty cells spin_system.comp.sym_group={}; spin_system.comp.sym_spins={}; spin_system.comp.sym_a1g_only=true(); else % Symmetry group if isfield(bas,'sym_group') spin_system.comp.sym_group=bas.sym_group; else spin_system.comp.sym_group={}; end % Symmetry-related spins if isfield(bas,'sym_spins') spin_system.comp.sym_spins=bas.sym_spins; else spin_system.comp.sym_spins={}; end % Irreducible representation composition if isfield(bas,'sym_a1g_only') spin_system.comp.sym_a1g_only=bas.sym_a1g_only; else spin_system.comp.sym_a1g_only=true(); end % Report back to the user if ~isempty(spin_system.comp.sym_group) summary(spin_system,'symmetry','permutation symmetry summary'); end % Compute group direct product if necessary if numel(spin_system.comp.sym_group)>1 % Lift constituent groups from the database ngroups=numel(spin_system.comp.sym_group); groups=cell(1,ngroups); for n=1:ngroups groups{n}=perm_group(spin_system.comp.sym_group{n}); end % Compute direct product character table group.characters=1; for n=1:ngroups group.characters=kron(group.characters,groups{n}.characters); end group.irrep_dims=group.characters(:,1)'; group.n_irreps=size(group.characters,1); report(spin_system,['' num2str(group.n_irreps) ' irreps in the group direct product.']); report(spin_system,['dimensions of the irreps ' num2str(group.irrep_dims)]); % Compute direct product element list group.elements=groups{1}.elements; group.order=groups{1}.order; for n=2:ngroups group.elements=[kron(group.elements,ones(groups{n}.order,1))... kron(ones(group.order,1),groups{n}.elements+size(group.elements,2))]; group.order=group.order*groups{n}.order; end report(spin_system,['' num2str(size(group.elements,1)) ' symmetry operations in the group direct product.']); % Concatenate spin lists spins=horzcat(spin_system.comp.sym_spins{:}); elseif numel(spin_system.comp.sym_group)==1 % Lift the group from the database spins=spin_system.comp.sym_spins{1}; group=perm_group(spin_system.comp.sym_group{1}); report(spin_system,['' num2str(group.n_irreps) ' irreps in the symmetry group.']); report(spin_system,['dimensions of the irreps ' num2str(group.irrep_dims)]); else % Remind the user that symmetry is not operational report(spin_system,'no symmetry information available.'); end % Run the SALC procedure if exist('group','var') % Preallocate the permutation table permutation_table=zeros(size(spin_system.bas.basis,1),group.order); % Compute the permutation table parfor n=1:group.order %#ok<*PFBNS> group_element=1:spin_system.comp.nspins; group_element(spins)=group_element(spins(group.elements(n,:))); permuted_basis=spin_system.bas.basis(:,group_element); [~,index]=sortrows(permuted_basis); permutation_table(:,n)=index; end % Compute irreducible representations if spin_system.comp.sym_a1g_only % Inform the user report(spin_system,'Liouville space symmetry mode - fully symmetric irrep only.'); % Prune the permutation table symmetry_related_states=unique(sort(permutation_table,2,'ascend'),'rows'); dimension=size(symmetry_related_states,1); % Populate the coefficient matrix index=unique([kron(ones(group.order,1),(1:dimension)') symmetry_related_states(:) ones(dimension*group.order,1)],'rows'); coeff_matrix=sparse(index(:,1),index(:,2),index(:,3),dimension,size(spin_system.bas.basis,1)); % Normalize the coefficient matrix norms=sqrt(sum(coeff_matrix.^2,2)); coeff_matrix=spdiags(norms.^(-1),0,dimension,dimension)*coeff_matrix; % Report back to the user report(spin_system,['A1g irrep, ' num2str(dimension) ' states.']); % Return the projector and dimension spin_system.bas.irrep.projector=coeff_matrix'; spin_system.bas.irrep.dimension=dimension; else % Inform the user report(spin_system,'WARNING - full symmetry treatment, all irreps will be included.'); % Determine the problem dimension basis_dim=size(spin_system.bas.basis,1); % Loop over irreducible representations for n=1:group.n_irreps % Inform the user report(spin_system,['processing irrep #' num2str(n) ' out of ' num2str(group.n_irreps) '...']); % Preallocate the coefficient matrix coeff_matrix=spalloc(basis_dim,basis_dim,basis_dim*group.order); % Compute the coefficient matrix for k=1:basis_dim % Populate the coefficient matrix for m=1:group.order coeff_matrix(k,permutation_table(k,m))=coeff_matrix(k,permutation_table(k,m))+group.characters(n,m); %#ok<SPRIX> end % Unify the signs non_zero_elements=nonzeros(coeff_matrix(k,:)); if any(non_zero_elements) coeff_matrix(k,:)=coeff_matrix(k,:)*sign(non_zero_elements(1)); %#ok<SPRIX> end end % Remove identical rows and all-zero rows coeff_matrix=unique(coeff_matrix,'rows'); coeff_matrix(sum(abs(coeff_matrix),2)<spin_system.tols.liouv_zero,:)=[]; % If the irrep is 2+ dimensional, orthonormalize the SALCs. Otherwise, just normalize the SALCs. if group.irrep_dims(n)>1 report(spin_system,['WARNING: ' num2str(group.irrep_dims(n)) '-dimensional irrep encountered. Will have to orthogonalize (slow).']); coeff_matrix=orth(full(coeff_matrix'))'; else for k=1:size(coeff_matrix,1) coeff_matrix(k,:)=coeff_matrix(k,:)/norm(coeff_matrix(k,:)); end end % Inform the user and write the irrep into the data structure report(spin_system,['irreducible representation #' num2str(n) ', ' num2str(size(coeff_matrix,1)) ' states.']); spin_system.bas.irrep(n).projector=coeff_matrix'; spin_system.bas.irrep(n).dimension=size(coeff_matrix,1); end end end end end % Consistency enforcement function grumble(spin_system,bas) % Check symmetry parameters if isfield(bas,'sym_group') % Check the type if (~iscell(bas.sym_group))||any(~cellfun(@ischar,bas.sym_group)) error('bas.sym_group must be a cell array of strings.'); end % Check that bas.sym_spins exists if ~isfield(bas,'sym_spins') error('bas.sym_spins must be specified alongside bas.sym_group.'); end % Check the type if (~iscell(bas.sym_spins))||any(~cellfun(@isnumeric,bas.sym_spins)) error('bas.sym_spins must be a cell array of vectors.'); end % Check the dimensions if numel(bas.sym_spins)~=numel(bas.sym_group) error('bas.sym_group and bas.sym_spins arrays must have the same number of elements.'); end % Check the spin indices for m=1:length(bas.sym_spins) % Check for sense if any(bas.sym_spins{m}>spin_system.comp.nspins)||any(bas.sym_spins{m}<1)||(numel(bas.sym_spins{m})<2) error('incorrect spin labels in bas.sym_spins.'); end % Check for intersections for n=1:length(bas.sym_spins) if (n~=m)&&(~isempty(intersect(bas.sym_spins{m},bas.sym_spins{n}))) error('same spin is listed in multiple symmetry groups in bas.sym_spins.'); end end end % Check the group names for n=1:length(bas.sym_group) if ~ismember(bas.sym_group{n},{'S2','S3','S4','S4A','S5','S6'}) error('the group requested in bas.sym_group is not available.'); end end % Check the irrep switch if isfield(bas,'sym_a1g_only')&&(~isnumeric(bas.sym_a1g_only))&&(~islogical(bas.sym_a1g_only))&&((bas.sym_a1g_only~=1)||(bas.sym_a1g_only~=0)) error('the allowed values for bas.sym_a1g_only are 0 and 1.'); end else % Enforce no sys.sym_spins without sys.sym_group if isfield(bas,'sym_spins') error('bas.sym_group must be specified alongside bas.sym_spins.'); end % Enforce no sys.sym_a1g_only without sys.sym_group if isfield(bas,'sym_a1g_only') error('bas.sym_group must be specified alongside bas.sym_a1g_only.'); end end end % I am regularly asked what an average Internet user can % do to ensure his security. My first answer is usually % "nothing, you're screwed". % % Bruce Schneier
github
tsajed/nmr-pred-master
interpmat.m
.m
nmr-pred-master/spinach/kernel/utilities/interpmat.m
4,437
utf_8
e2e9e5f38bde0747e0fd360e530038c8
% Returns a matrix that acts on a stretched pseudocontact shift density cube % and projects out the values of the PCS at the Cartesian coordinates given. % Tricubic interpolation is used. Syntax: % % P=interpmat(cube_dims,ranges,xyz) % % Parameters: % % cube_dims - PCS cube dimensions, ordered as [X Y Z]. % % ranges - cartesian axis extents for the pseudocontact shift % cube as [xmin xmax ymin ymax zmin zmax] in Angstroms. % % xyz - nuclear coordinates as [x y z] with multiple rows) at % which PCS is to be evaluated, in Angstroms. % % Output: % % P - matrix projecting out PCS values at the given positi- % ons from the stretched PCS cube. % % Note: this function is a part of the PCS inverse problem solver module and % should not normally be called directly by the user. % % [email protected] function P=interpmat(cube_dims,ranges,xyz) % Check consistency grumble(cube_dims,ranges,xyz); % Extract the bounds xmin=ranges(1); xmax=ranges(2); ymin=ranges(3); ymax=ranges(4); zmin=ranges(5); zmax=ranges(6); % Preallocate the answer P=spalloc(size(xyz,1),prod(cube_dims),64*size(xyz,1)); % Compute grids x_grid=linspace(xmin,xmax,cube_dims(1)); y_grid=linspace(ymin,ymax,cube_dims(2)); z_grid=linspace(zmin,zmax,cube_dims(3)); % Compute grid intervals x_grid_interval=(xmax-xmin)/(cube_dims(1)-1); y_grid_interval=(ymax-ymin)/(cube_dims(2)-1); z_grid_interval=(zmax-zmin)/(cube_dims(3)-1); % Loop over points parfor n=1:size(xyz,1) %#ok<*PFBNS> % Move into fractional coordinates x=(xyz(n,1)-xmin)/x_grid_interval; y=(xyz(n,2)-ymin)/y_grid_interval; z=(xyz(n,3)-zmin)/z_grid_interval; % Decide stencil points x_stencil=[min([max([1 (ceil(x)-1)]) (cube_dims(1)-3)])... min([max([2 (ceil(x)-0)]) (cube_dims(1)-2)])... min([max([3 (ceil(x)+1)]) (cube_dims(1)-1)])... min([max([4 (ceil(x)+2)]) (cube_dims(1)-0)])]; y_stencil=[min([max([1 (ceil(y)-1)]) (cube_dims(2)-3)])... min([max([2 (ceil(y)-0)]) (cube_dims(2)-2)])... min([max([3 (ceil(y)+1)]) (cube_dims(2)-1)])... min([max([4 (ceil(y)+2)]) (cube_dims(2)-0)])]; z_stencil=[min([max([1 (ceil(z)-1)]) (cube_dims(3)-3)])... min([max([2 (ceil(z)-0)]) (cube_dims(3)-2)])... min([max([3 (ceil(z)+1)]) (cube_dims(3)-1)])... min([max([4 (ceil(z)+2)]) (cube_dims(3)-0)])]; % Extract subgrid values x_subgrid=x_grid(x_stencil); y_subgrid=y_grid(y_stencil); z_subgrid=z_grid(z_stencil); % Compute interpolation vectors x_intvec=spalloc(1,cube_dims(1),4); x_intvec(x_stencil)=fdweights(xyz(n,1),x_subgrid,0); %#ok<SPRIX> y_intvec=spalloc(1,cube_dims(2),4); y_intvec(y_stencil)=fdweights(xyz(n,2),y_subgrid,0); %#ok<SPRIX> z_intvec=spalloc(1,cube_dims(3),4); z_intvec(z_stencil)=fdweights(xyz(n,3),z_subgrid,0); %#ok<SPRIX> % Update the answer P(n,:)=kron(z_intvec,kron(y_intvec,x_intvec)); end end % Consistency enforcement function grumble(cube_dims,ranges,xyz) if (~isnumeric(cube_dims))||(~isreal(cube_dims))||... (numel(cube_dims)~=3)||any(mod(cube_dims,1)~=0) error('cube_dims must contain three positive integer elements.'); end if any(cube_dims<4), error('too few points in the cube.'); end if (~isnumeric(xyz))||(~isreal(xyz))||(size(xyz,2)~=3) error('xyz must be an Nx3 array of atomic coordinates.'); end if (~isnumeric(ranges))||(~isreal(ranges))||(numel(ranges)~=6) error('ranges must be a real vector with six elements.'); end if (ranges(1)>=ranges(2))||(ranges(3)>=ranges(4))||(ranges(5)>=ranges(6)) error('ranges array should have xmin<xmax, ymin<ymax and zmin<zmax.'); end if any(xyz(:,1)<ranges(1))||any(xyz(:,1)>ranges(2))||... any(xyz(:,2)<ranges(3))||any(xyz(:,2)>ranges(4))||... any(xyz(:,3)<ranges(5))||any(xyz(:,3)>ranges(6)) error('extrapolation is not supported.'); end end % Pick up a camera. Shoot something. No matter how small, no matter how % cheesy, no matter whether your friends and your sister star in it. Put % your name on it as director. Now you're a director. Everything after % that - you're just negotiating your budget and your fee. % % James Cameron
github
tsajed/nmr-pred-master
centroid.m
.m
nmr-pred-master/spinach/kernel/utilities/centroid.m
586
utf_8
6afe1d74e9878ea3fbb54563acb46f26
% Finds the centroid of a 3D probability density in a cube. % % [email protected] function [x,y,z]=centroid(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 norm n=sum(sum(sum(probden))); % Get centroid coordinates x=sum(sum(sum(X.*probden)))/n; y=sum(sum(sum(Y.*probden)))/n; z=sum(sum(sum(Z.*probden)))/n; end % Life is warfare. % % Lucius Annaeus Seneca
github
tsajed/nmr-pred-master
plot_3d.m
.m
nmr-pred-master/spinach/kernel/utilities/plot_3d.m
8,479
utf_8
e276bec2f80d02566db61985f8d9a41e
% Volume isosurface plotting utility with non-linear adaptive isosurface % spacing.The function is useful for NMR data where small cross-peaks % must be adequately contoured next to large diagonal peaks. Syntax: % % plot_3d(spin_system,spectrum,parameters,ncont,delta,k,signs) % % The following functions are used to compute contour levels: % % cont_levs_pos=delta(2)*xmax*linspace(0,1,ncont).^k+xmax*delta(1); % cont_levs_neg=delta(2)*xmin*linspace(0,1,ncont).^k+xmin*delta(1); % % where: % % * xmax and xmin are calculated from the spectrum; % % * delta is the minimum and maximum elevation (as a fraction of total % intensity) of the contours above the baseline. A reasonable value % for most 3D spectra is [0.02 0.2]; % % * ncont is the number of contours, a reasonable value is 20. % % * k controls the curvature of the contour spacing function: k=1 % corresponds to linear spacing and k>1 bends the spacing curve to % increase the sampling density near the baseline. A reasonable % value is 2; % % * signs can be set to 'positive', 'negative' or 'both' - this will % cause the corresponding contours to be plotted. % % The following subfields are required inthe parameters structure: % % parameters.sweep three widths, Hz % % parameters.spins cell array with three character % strings specifying the working % spins. % % parameters.offset three transmitter offsets, Hz % % parameters.axis_units axis units ('ppm','Hz','Gauss') % % [email protected] % [email protected] function plot_3d(spin_system,spectrum,parameters,ncont,delta,k,signs) % Check consistency grumble(spectrum,parameters,ncont,delta,k,signs); % Inform the user report(spin_system,'plotting...'); % Determine data extents xmax=max(spectrum(:)); xmin=min(spectrum(:)); % Compute contour levels if (xmax>0)&&(strcmp(signs,'positive')||strcmp(signs,'both')) positive_contours=delta(2)*xmax*linspace(0,1,ncont).^k+xmax*delta(1); else positive_contours=[]; end if (xmin<0)&&(strcmp(signs,'negative')||strcmp(signs,'both')) negative_contours=delta(4)*xmin*linspace(0,1,ncont).^k+xmin*delta(3); else negative_contours=[]; end contours=[negative_contours(end:-1:1) positive_contours]; % Build axes and apply offsets axis_f1=linspace(-parameters.sweep(1)/2,parameters.sweep(1)/2,size(spectrum,1))+parameters.offset(1); axis_f2=linspace(-parameters.sweep(2)/2,parameters.sweep(2)/2,size(spectrum,2))+parameters.offset(2); axis_f3=linspace(-parameters.sweep(3)/2,parameters.sweep(3)/2,size(spectrum,3))+parameters.offset(3); % Convert the units switch parameters.axis_units case 'ppm' axis_f1=1000000*(2*pi)*axis_f1/(spin(parameters.spins{1})*spin_system.inter.magnet); axis_f2=1000000*(2*pi)*axis_f2/(spin(parameters.spins{2})*spin_system.inter.magnet); axis_f3=1000000*(2*pi)*axis_f3/(spin(parameters.spins{3})*spin_system.inter.magnet); axis_label='ch. shift / ppm'; case 'Gauss' axis_f1=10000*(spin_system.inter.magnet-2*pi*axis_f1/spin('E')); axis_f2=10000*(spin_system.inter.magnet-2*pi*axis_f2/spin('E')); axis_f3=10000*(spin_system.inter.magnet-2*pi*axis_f3/spin('E')); axis_label='magn. ind. / Gauss'; case 'Hz' axis_f1=1*axis_f1+0; axis_f2=1*axis_f2+0; axis_f3=1*axis_f3+0; axis_label='lin. freq. / Hz'; otherwise error('unknown axis units.'); end % Plot the 3D spectrum subplot(2,2,1,'replace'); hold('on'); [X,Y,Z]=meshgrid(axis_f2,axis_f1,axis_f3); for n=contours p=patch(isosurface(X,Y,Z,spectrum,n)); set(p,'FaceColor','red','EdgeColor','none'); end axis([min(axis_f2) max(axis_f2) min(axis_f1) max(axis_f1) min(axis_f3) max(axis_f3)]); axis('square'); box('on'); grid('on'); camlight(); lighting('gouraud'); set(gca,'XDir','reverse','YDir','reverse','ZDir','reverse'); set(gca,'CameraPosition',[min(axis_f2)-max(axis_f2)... min(axis_f1)-max(axis_f1)... min(axis_f3)-max(axis_f3)]*100); xlabel([parameters.spins{2} ' ' axis_label]); ylabel([parameters.spins{1} ' ' axis_label]); zlabel([parameters.spins{3} ' ' axis_label]); hold('off'); % Plot F3-F2 projection subplot(2,2,3); proj_params=parameters; proj_params.spins=proj_params.spins([3 2]); proj_params.offset=proj_params.offset([3 2]); proj_params.sweep=proj_params.sweep([3 2]); proj_params.npoints=proj_params.npoints([3 2]); proj_params.zerofill=proj_params.zerofill([3 2]); plot_2d(spin_system,squeeze(sum(spectrum,1)),proj_params,20,delta,2,256,6,signs); axis('square'); grid('on'); set(gca,'XDir','reverse','YDir','reverse'); % Plot F2-F1 projection subplot(2,2,4); proj_params=parameters; proj_params.spins=proj_params.spins([2 1]); proj_params.offset=proj_params.offset([2 1]); proj_params.sweep=proj_params.sweep([2 1]); proj_params.npoints=proj_params.npoints([2 1]); proj_params.zerofill=proj_params.zerofill([2 1]); plot_2d(spin_system,squeeze(sum(spectrum,3)),proj_params,20,delta,2,256,6,signs); axis('square'); grid('on'); set(gca,'XDir','reverse','YDir','reverse'); % Plot F3-F1 projection subplot(2,2,2); proj_params=parameters; proj_params.spins=proj_params.spins([3 1]); proj_params.offset=proj_params.offset([3 1]); proj_params.sweep=proj_params.sweep([3 1]); proj_params.npoints=proj_params.npoints([3 1]); proj_params.zerofill=proj_params.zerofill([3 1]); plot_2d(spin_system,squeeze(sum(spectrum,2)),proj_params,20,delta,2,256,6,signs); axis('square'); grid('on'); set(gca,'XDir','reverse','YDir','reverse'); % Make the figure bigger than the defalut set(gcf,'Position',[100,100,1024,768]); end % Consistency enforcement function grumble(spectrum,parameters,ncont,delta,k,signs) if (~isnumeric(spectrum))||(~isreal(spectrum))||(ndims(spectrum)~=3) error('spectrum must be a real cube of numbers.'); end if (~isfield(parameters,'offset')) error('offsets should be specified in parameters.offset variable.'); end if numel(parameters.offset)~=3 error('parameters.offset array should have three elements.'); end if ~isfield(parameters,'sweep') error('sweep widths should be specified in parameters.sweep variable.'); end if numel(parameters.sweep)~=3 error('parameters.sweep array should have three elements.'); end if ~isfield(parameters,'axis_units') error('axis units must be specified in parameters.axis_units variable.'); end if ~ischar(parameters.axis_units) error('parameters.axis_units must be a character string.'); end if ~isfield(parameters,'spins') error('working spins should be specified in parameters.spins variable.'); end if ~iscell(parameters.spins) error('parameters.spins should be a cell array of character strings.'); end if numel(parameters.spins)~=3 error('parameters.spins cell array should have three elements.'); end if (~isnumeric(ncont))||(~isscalar(ncont))||(~isreal(ncont))||(ncont<1)||(mod(ncont,1)~=0) error('ncont parameter must be a positive integer.'); end if (~isnumeric(delta))||(numel(delta)~=4)||(~isreal(delta))||any(delta>1)||any(delta<0) error('delta parameter must be a vector with four real elements between 0 and 1.'); end if (~isnumeric(k))||(~isscalar(k))||(~isreal(k))||(k<1)||(mod(k,1)~=0) error('k parameter must be a positive integer.'); end if ~ischar(signs) error('signs parameter must be a character string.'); end end % The English are well known throughout the world for their lack of poli- % tical scruples. They are experts at the art of hiding their misdeeds % behind a facade of virtue. They have been at it for centuries, and it % has become such a part of their nature that they hardly notice it any % longer. They carry on with such a pious expression and deadly serious- % ness that they even convince themselves that they are the exemplars of % political virtue. They do not admit their hypocrisy to themselves. It % never happens that one Englishman says to another with a wink or a smi- % le "We don't want to fool ourselves, do we now." They do not only beha- % ve as if they were the model of piety and virtue - they really believe % that they are. That is both amusing and dangerous. % % Mickey Mouse
github
tsajed/nmr-pred-master
hartree2joule.m
.m
nmr-pred-master/spinach/kernel/utilities/hartree2joule.m
428
utf_8
a624aecda234c26d76174690309a3775
% Converts Hartree energy units into J/mol. Syntax: % % energy=hartree2joule(energy) % % Arrays of any dimension are supported. % % [email protected] function energy=hartree2joule(energy) % Perform the conversion energy=2625499.62*energy; end % "We only need to be lucky once. You need to be % lucky every time." % % The IRA to Margaret Thatcher, after % a failed assassination attempt.
github
tsajed/nmr-pred-master
mhz2gauss.m
.m
nmr-pred-master/spinach/kernel/utilities/mhz2gauss.m
657
utf_8
a44c974a7f775f085f28b7374165ec01
% Converts hyperfine couplings from MHz (linear frequency) % to Gauss. Syntax: % % hfc_gauss=mhz2gauss(hfc_mhz) % % Arrays of any dimensions are supported. % % [email protected] function hfc_gauss=mhz2gauss(hfc_mhz) if isnumeric(hfc_mhz)&&isreal(hfc_mhz) hfc_gauss=hfc_mhz/2.802495365; else error('the argument must be an array of real numbers.'); end end % "Trillian had come to suspect that the main reason [Zaphood] had % had such a wild and successful life was that he never really un- % derstood the significance of anything he did." % % Douglas Adams, "The Hitchhiker's Guide to the Galaxy"
github
tsajed/nmr-pred-master
lm2lin.m
.m
nmr-pred-master/spinach/kernel/utilities/lm2lin.m
1,263
utf_8
e449279327599e7929e96a7ac394df81
% Converts L,M spin state specification to linear indexing specification. % In the linear indexing convention, the states are listed in the order of % inc reasing L rank, and, within ranks, in the order of decreasing M pro- % jection. Syntax: I=lm2lin(L,M) % % WARNING - zero base indexing, that is: % % (L=0,M=0) -> I=0 % (L=1,M=1) -> I=1 % (L=1,M=0) -> I=2, et cetera... % % Arrays of any dimension are accepted as arguments. % % [email protected] function I=lm2lin(L,M) % Check consistency grumble(L,M); % Get the linear index I=L.^2+L-M; end % Consistency enforcement function grumble(L,M) if (~isnumeric(L))||(~isreal(L))||any(mod(L(:),1)~=0)||... (~isnumeric(M))||(~isreal(M))||any(mod(M(:),1)~=0) error('all elements of the inputs must be real integers.'); end if any(abs(M(:))>L(:)) error('unacceptable projection number.'); end if any(L(:)<0) error('unacceptable total angular momentum.'); end if any(size(L)~=size(M)) error('array dimensions are inconsistent.'); end end % A casual stroll through the lunatic asylum shows that faith does not % prove anything. % % Friedrich Nietzsche
github
tsajed/nmr-pred-master
tolerances.m
.m
nmr-pred-master/spinach/kernel/utilities/tolerances.m
14,822
utf_8
410287a797baec77b067198e427f4f4a
% Tolerances and fundamental constants. Sets the various accuracy cut-offs, % constants and tolerances used throughout Spinach kernel. % % Modifications to this function are discouraged -- the accuracy settings % should be modified by setting the sub-fields of the sys.tols structure, % see the input preparation manual in the /docs directory. % % [email protected] % [email protected] function spin_system=tolerances(spin_system,sys) % Interaction clean-up tolerance if isfield(sys,'tols')&&isfield(sys.tols,'inter_cutoff') spin_system.tols.inter_cutoff=sys.tols.inter_cutoff; report(spin_system,[pad('Drop interaction tensors with norms below (rad/s)',80) pad(num2str(spin_system.tols.inter_cutoff,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.inter_cutoff=eps(); report(spin_system,[pad('Drop interaction tensors with norms below (rad/s)',80) pad(num2str(spin_system.tols.inter_cutoff,'%0.8e'),20) ' (paranoid)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.inter_cutoff=1e-2; report(spin_system,[pad('Drop interaction tensors with norms below (rad/s)',80) pad(num2str(spin_system.tols.inter_cutoff,'%0.8e'),20) ' (loose)']); else spin_system.tols.inter_cutoff=1e-10; report(spin_system,[pad('Drop interaction tensors with norms below (rad/s)',80) pad(num2str(spin_system.tols.inter_cutoff,'%0.8e'),20) ' (safe default)']); end % Liouvillian zero tolerance if isfield(sys,'tols')&&isfield(sys.tols,'liouv_zero') spin_system.tols.liouv_zero=sys.tols.liouv_zero; report(spin_system,[pad('Drop Liovillian terms with amplitudes below (rad/s)',80) pad(num2str(spin_system.tols.liouv_zero,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.liouv_zero=eps(); report(spin_system,[pad('Drop Liovillian terms with amplitudes below (rad/s)',80) pad(num2str(spin_system.tols.liouv_zero,'%0.8e'),20) ' (paranoid)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.liouv_zero=1e-5; report(spin_system,[pad('Drop Liovillian terms with amplitudes below (rad/s)',80) pad(num2str(spin_system.tols.liouv_zero,'%0.8e'),20) ' (loose)']); else spin_system.tols.liouv_zero=1e-10; report(spin_system,[pad('Drop Liovillian terms with amplitudes below (rad/s)',80) pad(num2str(spin_system.tols.liouv_zero,'%0.8e'),20) ' (safe default)']); end % Zero tolerance for the series terms in the exponential propagator if isfield(sys,'tols')&&isfield(sys.tols,'prop_chop') spin_system.tols.prop_chop=sys.tols.prop_chop; report(spin_system,[pad('Drop exponential propagator terms with amplitudes below',80) pad(num2str(spin_system.tols.prop_chop,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.prop_chop=eps(); report(spin_system,[pad('Drop exponential propagator terms with amplitudes below',80) pad(num2str(spin_system.tols.prop_chop,'%0.8e'),20) ' (paranoid)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.prop_chop=1e-8; report(spin_system,[pad('Drop exponential propagator terms with amplitudes below',80) pad(num2str(spin_system.tols.prop_chop,'%0.8e'),20) ' (loose)']); else spin_system.tols.prop_chop=1e-10; report(spin_system,[pad('Drop exponential propagator terms with amplitudes below',80) pad(num2str(spin_system.tols.prop_chop,'%0.8e'),20) ' (safe default)']); end % Subspace drop population tolerance if isfield(sys,'tols')&&isfield(sys.tols,'subs_drop') spin_system.tols.subs_drop=sys.tols.subs_drop; report(spin_system,[pad('Drop subspaces with total populations below',80) pad(num2str(spin_system.tols.subs_drop,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.subs_drop=eps(); report(spin_system,[pad('Drop subspaces with total populations below',80) pad(num2str(spin_system.tols.subs_drop,'%0.8e'),20) ' (paranoid)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.subs_drop=1e-2; report(spin_system,[pad('Drop subspaces with total populations below',80) pad(num2str(spin_system.tols.subs_drop,'%0.8e'),20) ' (loose)']); else spin_system.tols.subs_drop=1e-10; report(spin_system,[pad('Drop subspaces with total populations below',80) pad(num2str(spin_system.tols.subs_drop,'%0.8e'),20) ' (safe default)']); end % Irrep population tolerance if isfield(sys,'tols')&&isfield(sys.tols,'irrep_drop') spin_system.tols.irrep_drop=sys.tols.irrep_drop; report(spin_system,[pad('Drop irreducible representations with populations below',80) pad(num2str(spin_system.tols.irrep_drop,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.irrep_drop=eps(); report(spin_system,[pad('Drop irreducible representations with populations below',80) pad(num2str(spin_system.tols.irrep_drop,'%0.8e'),20) ' (paranoid)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.irrep_drop=1e-2; report(spin_system,[pad('Drop irreducible representations with populations below',80) pad(num2str(spin_system.tols.irrep_drop,'%0.8e'),20) ' (loose)']); else spin_system.tols.irrep_drop=1e-10; report(spin_system,[pad('Drop irreducible representations with populations below',80) pad(num2str(spin_system.tols.irrep_drop,'%0.8e'),20) ' (safe default)']); end % Path drop tolerance if isfield(sys,'tols')&&isfield(sys.tols,'path_drop') spin_system.tols.path_drop=sys.tols.path_drop; report(spin_system,[pad('Disconect subspaces with cross-terms below (rad/s)',80) pad(num2str(spin_system.tols.path_drop,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.path_drop=eps(); report(spin_system,[pad('Disconect subspaces with cross-terms below (rad/s)',80) pad(num2str(spin_system.tols.path_drop,'%0.8e'),20) ' (paranoid)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.path_drop=1e-2; report(spin_system,[pad('Disconect subspaces with cross-terms below (rad/s)',80) pad(num2str(spin_system.tols.path_drop,'%0.8e'),20) ' (loose)']); else spin_system.tols.path_drop=1e-10; report(spin_system,[pad('Disconect subspaces with cross-terms below (rad/s)',80) pad(num2str(spin_system.tols.path_drop,'%0.8e'),20) ' (safe default)']); end % ZTE sample length if isfield(sys,'tols')&&isfield(sys.tols,'zte_nsteps') spin_system.tols.zte_nsteps=sys.tols.zte_nsteps; report(spin_system,[pad('Number of steps in the zero track elimination sample',80) pad(num2str(spin_system.tols.zte_nsteps),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.zte_nsteps=16; report(spin_system,[pad('Number of steps in the zero track elimination sample',80) pad(num2str(spin_system.tols.zte_nsteps),20) ' (loose)']); else spin_system.tols.zte_nsteps=32; report(spin_system,[pad('Number of steps in the zero track elimination sample',80) pad(num2str(spin_system.tols.zte_nsteps),20) ' (safe default)']); end % ZTE zero track tolerance if isfield(sys,'tols')&&isfield(sys.tols,'zte_tol') spin_system.tols.zte_tol=sys.tols.zte_tol; report(spin_system,[pad('Consider trajectory tracks to be zero below',80) pad(num2str(spin_system.tols.zte_tol,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('cowboy',sys.enable) spin_system.tols.zte_tol=1e-6; report(spin_system,[pad('Consider trajectory tracks to be zero below',80) pad(num2str(spin_system.tols.zte_tol,'%0.8e'),20) ' (loose)']); else spin_system.tols.zte_tol=1e-24; report(spin_system,[pad('Consider trajectory tracks to be zero below',80) pad(num2str(spin_system.tols.zte_tol,'%0.8e'),20) ' (safe default)']); end % ZTE state vector density threshold if isfield(sys,'tols')&&isfield(sys.tols,'zte_maxden') spin_system.tols.zte_maxden=sys.tols.zte_maxden; report(spin_system,[pad('ZTE off for state vector densities above',80) pad(num2str(spin_system.tols.zte_maxden),20) ' (user-specified)']); else spin_system.tols.zte_maxden=0.5; report(spin_system,[pad('ZTE off for state vector densities above',80) pad(num2str(spin_system.tols.zte_maxden),20) ' (safe default)']); end % Proximity tolerance for dipolar couplings if isfield(sys,'tols')&&isfield(sys.tols,'prox_cutoff') spin_system.tols.prox_cutoff=sys.tols.prox_cutoff; report(spin_system,[pad('Drop dipolar couplings over distances greater than (Angstrom)',80) pad(num2str(spin_system.tols.prox_cutoff),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.prox_cutoff=inf(); report(spin_system,[pad('Drop dipolar couplings over distances greater than (Angstrom)',80) pad(num2str(spin_system.tols.prox_cutoff),20) ' (paranoid)']); else spin_system.tols.prox_cutoff=100; report(spin_system,[pad('Drop dipolar couplings over distances greater than (Angstrom)',80) pad(num2str(spin_system.tols.prox_cutoff),20) ' (safe default)']); end % Krylov method switchover if isfield(sys,'tols')&&isfield(sys.tols,'krylov_switchover') spin_system.tols.krylov_switchover=sys.tols.krylov_switchover; report(spin_system,[pad('Use Krylov propagation for nnz(L) above',80) pad(num2str(spin_system.tols.krylov_switchover),20) ' (user-specified)']); else spin_system.tols.krylov_switchover=1e5; report(spin_system,[pad('Use Krylov propagation for nnz(L) above',80) pad(num2str(spin_system.tols.krylov_switchover),20) ' (safe default)']); end % Basis printing hush tolerance if isfield(sys,'tols')&&isfield(sys.tols,'basis_hush') spin_system.tols.basis_hush=sys.tols.basis_hush; report(spin_system,[pad('Do not print the basis for state space dimensions over',80) pad(num2str(spin_system.tols.basis_hush),20) ' (user-specified)']); else spin_system.tols.basis_hush=256; report(spin_system,[pad('Do not print the basis for state space dimensions over',80) pad(num2str(spin_system.tols.basis_hush),20) ' (safe default)']); end % Subspace bundle size if isfield(sys,'tols')&&isfield(sys.tols,'merge_dim') spin_system.tols.merge_dim=sys.tols.merge_dim; report(spin_system,[pad('Collect small subspaces into bundles of dimension',80) pad(num2str(spin_system.tols.merge_dim),20) ' (user-specified)']); else spin_system.tols.merge_dim=1000; report(spin_system,[pad('Collect small subspaces into bundles of dimension',80) pad(num2str(spin_system.tols.merge_dim),20) ' (safe default)']); end % Sparse algebra tolerance on density if isfield(sys,'tols')&&isfield(sys.tols,'dense_matrix') spin_system.tols.dense_matrix=sys.tols.dense_matrix; report(spin_system,[pad('Force sparse algebra for matrix density below',80) pad(num2str(spin_system.tols.dense_matrix),20) ' (user-specified)']); else spin_system.tols.dense_matrix=0.10; report(spin_system,[pad('Force sparse algebra for matrix density below',80) pad(num2str(spin_system.tols.dense_matrix),20) ' (safe default)']); end % Sparse algebra tolerance on dimension if isfield(sys,'tols')&&isfield(sys.tols,'small_matrix') spin_system.tols.small_matrix=sys.tols.small_matrix; report(spin_system,[pad('Force full algebra for matrix dimension below',80) pad(num2str(spin_system.tols.small_matrix),20) ' (user-specified)']); else spin_system.tols.small_matrix=200; report(spin_system,[pad('Force full algebra for matrix dimension below',80) pad(num2str(spin_system.tols.small_matrix),20) ' (safe default)']); end % Relative accuracy of the elements of Redfield superoperator if isfield(sys,'tols')&&isfield(sys.tols,'rlx_integration') spin_system.tols.rlx_integration=sys.tols.rlx_integration; report(spin_system,[pad('Relative accuracy for the elements of Redfield superoperator',80) pad(num2str(spin_system.tols.rlx_integration,'%0.8e'),20) ' (user-specified)']); elseif isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.tols.rlx_integration=1e-6; report(spin_system,[pad('Relative accuracy for the elements of Redfield superoperator',80) pad(num2str(spin_system.tols.rlx_integration,'%0.8e'),20) ' (paranoid)']); else spin_system.tols.rlx_integration=1e-4; report(spin_system,[pad('Relative accuracy for the elements of Redfield superoperator',80) pad(num2str(spin_system.tols.rlx_integration,'%0.8e'),20) ' (safe default)']); end % Algorithm selection for propagator derivatives if isfield(sys,'tols')&&isfield(sys.tols,'dP_method') spin_system.tols.dP_method=sys.tols.dP_method; report(spin_system,[pad('Matrix exponential differentiation algorithm',80) pad(spin_system.tols.dP_method,20) ' (user-specified)']); else spin_system.tols.dP_method='auxmat'; report(spin_system,[pad('Matrix exponential differentiation algorithm',80) pad(spin_system.tols.dP_method,20) ' (safe default)']); end % Number of PBC images for dipolar couplings if isfield(sys,'tols')&&isfield(sys.tols,'dd_ncells') spin_system.tols.dd_ncells=sys.tols.dd_ncells; report(spin_system,[pad('Number of PBC images for dipolar couplings in periodic systems',80) pad(num2str(spin_system.tols.dd_ncells),20) ' (user-specified)']); else spin_system.tols.dd_ncells=2; report(spin_system,[pad('Number of PBC images for dipolar couplings in periodic systems',80) pad(num2str(spin_system.tols.dd_ncells),20) ' (safe default)']); end % Fundamental constants spin_system.tols.hbar=1.054571628e-34; report(spin_system,[pad('Planck constant (hbar)',80) pad(num2str(spin_system.tols.hbar,'%0.8e'),20)]); spin_system.tols.kbol=1.3806503e-23; report(spin_system,[pad('Boltzmann constant (k)',80) pad(num2str(spin_system.tols.kbol,'%0.8e'),20)]); spin_system.tols.freeg=2.0023193043622; report(spin_system,[pad('Free electron g-factor',80) pad(num2str(spin_system.tols.freeg,'%0.8e'),20)]); spin_system.tols.mu0=4*pi*1e-7; report(spin_system,[pad('Vacuum permeability',80) pad(num2str(spin_system.tols.mu0,'%0.8e'),20)]); % Paranoia switches if isfield(sys,'enable')&&ismember('paranoia',sys.enable) spin_system.sys.disable=unique([spin_system.sys.disable {'trajlevel','krylov','clean-up','expv'}]); end end % Man once surrendering his reason, has no remaining guard against % absurdities the most monstrous, and like a ship without rudder, % is the sport of every wind. % % Thomas Jefferson
github
tsajed/nmr-pred-master
equilibrate.m
.m
nmr-pred-master/spinach/kernel/utilities/equilibrate.m
269
utf_8
7dae323be6de9a16df803636cdd1d17c
% Equilibrates a linear chemical kinetics system for % a user-specified time. Syntax: % % c=equilibrate(K,c0,t) % % [email protected] function c=equilibrate(K,c0,t) % Run the chemical kinetics for a specified time c=expm(K*t)*c0; end
github
tsajed/nmr-pred-master
quat2dcm.m
.m
nmr-pred-master/spinach/kernel/utilities/quat2dcm.m
1,281
utf_8
aa4dad5b1d28a070200c6a5530d4c6df
% Converts a quaternion rotation specification into a corresponding % direction cosine matrix. Syntax: % % dcm=quat2anax(q) % % where q is a structure with four fields q.u, q.i, q.j, q.k giving % the four components of the quaternion. % % [email protected] function dcm=quat2dcm(q) % Check consistency grumble(q); % Normalize the quaternion qnorm=norm([q.u q.i q.j q.k],2); q.u=q.u/qnorm; q.i=q.i/qnorm; q.j=q.j/qnorm; q.k=q.k/qnorm; % Preallocate the answer dcm=zeros(3,3); % Compute the answer dcm(1,1)=q.u^2+q.i^2-q.j^2-q.k^2; dcm(1,2)=2*(q.i*q.j+q.u*q.k); dcm(1,3)=2*(q.i*q.k-q.u*q.j); dcm(2,1)=2*(q.i*q.j-q.u*q.k); dcm(2,2)=q.u^2-q.i^2+q.j^2-q.k^2; dcm(2,3)=2*(q.j*q.k+q.u*q.i); dcm(3,1)=2*(q.i*q.k+q.u*q.j); dcm(3,2)=2*(q.j*q.k-q.u*q.i); dcm(3,3)=q.u^2-q.i^2-q.j^2+q.k^2; end % Consistency enforcement function grumble(q) if ~all(isfield(q,{'i','j','k','u'})) error('quaternion data structure must contain u, i, j, and k fields.'); end if ~all(isreal([q.u q.i q.j q.k])) error('quaternion elements must be real.'); end end % Ah, there's nothing more exciting than science. You get all the % fun of sitting still, being quiet, writing down numbers, paying % attention... science has it all. % % Principal Skinner
github
tsajed/nmr-pred-master
p_superop.m
.m
nmr-pred-master/spinach/kernel/utilities/p_superop.m
5,872
utf_8
e07bac99ee7832977644582da0679a92
% Sided product superoperator in the spherical tensor basis set. Returns % superoperators corresponding to right or left multiplication of a den- % sity matrix by a user-specified operator. Syntax: % % A=p_superop(spin_system,opspec,side) % % Arguments: % % opspec - Spinach operator specification described in Sections 2.1 % and 3.3 of the following paper: % % http://dx.doi.org/10.1016/j.jmr.2010.11.008 % % side - 'left' or 'right' causes the function to return a product % superoperator corresponding to a product from that side; % 'comm' or 'acomm' results in commutation and anticommuta- % tion superoperator respectively. % % Note: This is a very general function to which direct calls are not % usually required -- please use the (much friendlier) operator() % function. % % [email protected] % [email protected] function A=p_superop(spin_system,opspec,side) % Issue a recursive call if appropriate if strcmp(side,'comm') A=p_superop(spin_system,opspec,'leftofcomm')-... p_superop(spin_system,opspec,'rightofcomm'); return; elseif strcmp(side,'acomm') A=p_superop(spin_system,opspec,'left')+... p_superop(spin_system,opspec,'right'); return; end % Validate the input grumble(spin_system,opspec); % Determine the relevant spins active_spins=find(opspec); % For unit operator use a shortcut if isempty(active_spins) A=unit_oper(spin_system); return; end % Preallocate source state index source=cell(1,numel(active_spins)); % Preallocate destination state index destin=cell(1,numel(active_spins)); % Preallocate structure coefficients table struct=cell(1,numel(active_spins)); % Loop over the relevant spins for n=1:length(active_spins) % Get right and left product action tables for the current spin [pt_left,pt_right]=ist_product_table(spin_system.comp.mults(active_spins(n))); % Extract pages corresponding to the current state switch side case {'left','leftofcomm'} pt=squeeze(pt_left(opspec(active_spins(n))+1,:,:)); case {'right','rightofcomm'} pt=squeeze(pt_right(opspec(active_spins(n))+1,:,:)); otherwise error('invalid side specification.'); end % Convert product action table to indices [destin{n},source{n},struct{n}]=find(pt); % Switch to 0 index for unit state source{n}=source{n}-1; destin{n}=destin{n}-1; end % Compute the structure coefficients for the relevant sub-algebra from=source{1}; to=destin{1}; coeff=struct{1}; for n=2:numel(active_spins) from=[kron(from,ones(size(source{n},1),1)) kron(ones(size(from,1),1),source{n})]; to=[kron(to,ones(size(destin{n},1),1)) kron(ones(size(to,1),1),destin{n})]; coeff=kron(coeff,struct{n}); end % Preallocate the answer matrix_dim=size(spin_system.bas.basis,1); A=spalloc(matrix_dim,matrix_dim,matrix_dim); % Lift the basis columns corresponding to the relevant spins basis_cols=spin_system.bas.basis(:,active_spins); % For commutation superoperators remove commuting paths if ismember(side,{'leftofcomm','rightofcomm'}) kill_mask=(sum(from,2)==0)|(sum(to,2)==0); from(kill_mask,:)=[]; to(kill_mask,:)=[]; coeff(kill_mask,:)=[]; end % Loop over source states for n=1:size(from,1) % Retrieve the source subspace source_subsp_idx=true(size(basis_cols,1),1); for m=1:size(from,2) source_subsp_idx=and(source_subsp_idx,(basis_cols(:,m)==from(n,m))); end source_subsp=spin_system.bas.basis(source_subsp_idx,:); source_subsp_idx=find(source_subsp_idx); source_subsp(:,active_spins)=[]; % Retrieve the destination subspace destin_subsp_idx=true(size(basis_cols,1),1); for m=1:size(to,2) destin_subsp_idx=and(destin_subsp_idx,(basis_cols(:,m)==to(n,m))); end destin_subsp=spin_system.bas.basis(destin_subsp_idx,:); destin_subsp_idx=find(destin_subsp_idx); destin_subsp(:,active_spins)=[]; % Fill the operator if isequal(source_subsp,destin_subsp) % If the subspaces fully match, use the raw indices subsp_dim=size(source_subsp,1); A=A+sparse(source_subsp_idx,destin_subsp_idx,coeff(n)*ones(subsp_dim,1),matrix_dim,matrix_dim); else % Otherwise, use brute-force state-by-state matching [does_it_go_anywhere,where_it_goes_if_it_does]=ismember(source_subsp,destin_subsp,'rows'); A=A+sparse(source_subsp_idx(does_it_go_anywhere),... destin_subsp_idx(where_it_goes_if_it_does(does_it_go_anywhere)),... coeff(n)*ones(nnz(does_it_go_anywhere),1),matrix_dim,matrix_dim); end end end % Consistency enforcement function grumble(spin_system,opspec) if ~isfield(spin_system,'bas') error('basis set information is missing, run basis() before calling this function.'); end if ~ismember(spin_system.bas.formalism,{'sphten-liouv'}) error('this function only supports sphten-liouv formalism.'); end if (~isnumeric(opspec))||(~isrow(opspec))||any(mod(opspec,1)~=0) error('opspec must be a row vector of integers.'); end if numel(opspec)~=spin_system.comp.nspins error('the number of elements in the opspec array must be equal to the number of spins.'); end if any((opspec+1)>spin_system.comp.mults.^2) error('physically impossible state requested in opspec.'); end end % My philosophy, in essence, is the concept of man as a heroic being, % with his own happiness as the moral purpose of his life, with pro- % ductive achievement as his noblest activity, and reason as his only % absolute. % % Ayn Rand
github
tsajed/nmr-pred-master
sphten2state.m
.m
nmr-pred-master/spinach/kernel/utilities/sphten2state.m
1,274
utf_8
3e16a8a8db0d6ddd6983c2fb2c518775
% Generates a state vector from its spherical tensor expansion produced % by zeeman2sphten() function. Syntax: % % rho=sphten2state(spin_system,stexp,spin_num) % % where stexp is a cell array with the first element of each row giving % the operator name and the second element being the corresponding sphe- % rical tensor expansion coefficient. The last argument is the number of % the spin to which the expansion refers. % % [email protected] % [email protected] function rho=sphten2state(spin_system,stexp,spin_num) % Validate the input grumble(spin_system,stexp,spin_num); % Get the state vector rho=sparse(0); for n=1:size(stexp,1) % Get the state vn=state(spin_system,stexp(n,1),{spin_num}); % Normalise the state vn=vn/sqrt(vn(:)'*vn(:)); % Add to the total rho=rho+stexp{n,2}*vn; end end % Input validation function function grumble(spin_system,stexp,spin_num) if ~isfield(spin_system,'bas') error('basis set information is missing, run basis() before calling this function.'); end if ~iscell(stexp) error('stexp must be a cell array.'); end if (~isnumeric(spin_num))||(~isreal(spin_num))||(mod(spin_num,1)~=0)||(spin_num<1) error('spin_num must be a positive integer.'); end end
github
tsajed/nmr-pred-master
fpl2phan.m
.m
nmr-pred-master/spinach/kernel/utilities/fpl2phan.m
853
utf_8
0fc482450c034c53ff8ee4842cc54f08
% Returns the image encoded within the Fokker-Planck vector by the % user-specified Liouville space coil state. Syntax: % % phan=fpl2phan(rho,coil,dims) % % Parameters: % % rho - state vector in Fokker-Planck space % % coil - observable state vector in Liouville space % % dims - spatial dimensions of the Fokker-Planck % problem % % [email protected] function phan=fpl2phan(rho,coil,dims) % Expose the spin dimension rho=reshape(rho,[numel(coil) prod(dims)]); % Compute the observable phan=coil'*rho; % Reshape as needed phan=reshape(phan,dims); end % Malcolm Levitt's most fearsome battle cry, the one that sends the chill % down the spines of any committee and makes marrow freeze in their bones % in expectation of what is to come, is "Erm, excuse me..."
github
tsajed/nmr-pred-master
molplot.m
.m
nmr-pred-master/spinach/kernel/utilities/molplot.m
1,706
utf_8
749ea08b983966a11f451915891ff201
% Plots a stick representation of a molecule from Cartesian coordinates % supplied. Coordinates must be in Angstroms. Syntax: % % molplot(xyz,conmatrix) % % Parameters: % % xyz - Cartesian coordinates, as Nx3 matrix % % conmatrix - NxN connectivity matrix indicating chemical % bonds that should be drawn as sticks. If an % empty vector is supplied, 1.6 Angstrom cut- % off distance is used % % [email protected] function molplot(xyz,conmatrix) % Check consistency grumble(xyz,conmatrix); % Get the connectivity matrix if isempty(conmatrix) conmatrix=conmat(xyz,1.6); end % Prepare coordinate arrays nbonds=nnz(conmatrix); X=zeros(1,3*nbonds); Y=zeros(1,3*nbonds); Z=zeros(1,3*nbonds); [rows,cols]=find(conmatrix); for n=1:nbonds X((3*(n-1)+1):(3*n))=[xyz(rows(n),1) xyz(cols(n),1) NaN]; Y((3*(n-1)+1):(3*n))=[xyz(rows(n),2) xyz(cols(n),2) NaN]; Z((3*(n-1)+1):(3*n))=[xyz(rows(n),3) xyz(cols(n),3) NaN]; end % Draw the molecule plot3(X,Y,Z); end % Consistency enforcement function grumble(xyz,conmatrix) if (~isnumeric(xyz))||(~isreal(xyz))||(size(xyz,2)~=3) error('xyz must be an Nx3 real matrix.'); end if ~isempty(conmatrix) if (size(conmatrix,1)~=size(conmatrix,2))||... (size(conmatrix,1)~=size(xyz,1)) error('conmatrix must be a logical square matrix of the same dimension as the number of rows in xyz.'); end end end % The most terrifying fact about the universe is not that it is % hostile but that it is indifferent... However vast the darkness, % we must supply our own light. % % Stanley Kubrick
github
tsajed/nmr-pred-master
lin2lm.m
.m
nmr-pred-master/spinach/kernel/utilities/lin2lm.m
1,219
utf_8
ed9a2ae330c0b0d26432688d411caa13
% Converts linear indexing state specification to L,M indexing. In % the linear indexing convention, the states are listed in the order % of increasing L rank, and, within ranks, in the order of decreas- % ing M projection. Syntax: [L,M]=lin2lm(I) % % WARNING - zero base indexing, that is: % % I=0 -> (L=0,M=0) % I=1 -> (L=1,M=1) % I=2 -> (L=1,M=0), et cetera... % % Arrays of any dimension are accepted as arguments. % % [email protected] function [L,M]=lin2lm(I) % Check consistency grumble(I); % Get the ranks and projections L=fix(sqrt(I)); M=L.^2+L-I; % Make sure the conversion is correct if nnz(lm2lin(L,M)~=I)>0 error('IEEE arithmetic breakdown, please contact the developer.'); end end % Consistency enforcement function grumble(I) if (~isnumeric(I))||(~isreal(I))||any(mod(I(:),1)~=0)||any(I(:)<0) error('all elements of the input array must be non-negative integers.'); end end % Arrogance on the part of the meritorious is even more offensive % to us than the arrogance of those without merit: for merit itself % is offensive. % % Friedrich Nietzsche
github
tsajed/nmr-pred-master
fdkup.m
.m
nmr-pred-master/spinach/kernel/utilities/fdkup.m
3,777
utf_8
a218d6f10a38f735158e9e236425a9a2
% Returns a finite difference representation of the Kuprov operator: % % K[rho]=-(1/3)*Trace(Hessian[rho]*chi) % % with the number of stencil points in the finite difference approxi- % mation specified by user. Syntax: % % K=fdkup(npoints,extents,chi,nstenc) % % The following parameters are needed: % % npoints - a three-element vector specifying the dimensions % of the 3D cube of data that the operator will be % acting on, in Angstroms. % % chi - the electron magnetic susceptibility tensor in % cubic Angstroms. % % extents - a three-element vector specifying axis extents % in Angstroms. % % nstenc - number of finite-difference stencil points for % the finite-difference approximations. % % The resulting operator is a sparse matrix designed to act on the % vectorization of rho. The dimensions of rho are assumed to be or- % dered as [X Y Z]. % % Periodic boundary condition is used. % % For further details see http://dx.doi.org/10.1039/C4CP03106G. % % [email protected] % [email protected] function K=fdkup(npoints,extents,chi,nstenc) % Check consistency grumble(npoints,extents,chi,nstenc); % Compute second derivative operators d2_dzdz=kron(kron(fdmat(npoints(3),nstenc,2),speye(npoints(2))),speye(npoints(1))); d2_dydy=kron(kron(speye(npoints(3)),fdmat(npoints(2),nstenc,2)),speye(npoints(1))); d2_dxdx=kron(kron(speye(npoints(3)),speye(npoints(2))),fdmat(npoints(1),nstenc,2)); d2_dydx=kron(kron(speye(npoints(3)),fdmat(npoints(2),nstenc,1)),fdmat(npoints(1),nstenc,1)); d2_dzdx=kron(kron(fdmat(npoints(3),nstenc,1),speye(npoints(2))),fdmat(npoints(1),nstenc,1)); d2_dzdy=kron(kron(fdmat(npoints(3),nstenc,1),fdmat(npoints(2),nstenc,1)),speye(npoints(1))); d2_dxdz=d2_dzdx; d2_dydz=d2_dzdy; d2_dxdy=d2_dydx; % Normalize second derivative operators d2_dxdx=(npoints(1)/extents(1))*(npoints(1)/extents(1))*d2_dxdx; d2_dxdy=(npoints(1)/extents(1))*(npoints(2)/extents(2))*d2_dxdy; d2_dxdz=(npoints(1)/extents(1))*(npoints(3)/extents(3))*d2_dxdz; d2_dydx=(npoints(2)/extents(2))*(npoints(1)/extents(1))*d2_dydx; d2_dydy=(npoints(2)/extents(2))*(npoints(2)/extents(2))*d2_dydy; d2_dydz=(npoints(2)/extents(2))*(npoints(3)/extents(3))*d2_dydz; d2_dzdx=(npoints(3)/extents(3))*(npoints(1)/extents(1))*d2_dzdx; d2_dzdy=(npoints(3)/extents(3))*(npoints(2)/extents(2))*d2_dzdy; d2_dzdz=(npoints(3)/extents(3))*(npoints(3)/extents(3))*d2_dzdz; % Form the Kuprov operator K=-(1/3)*(chi(1,1)*d2_dxdx+chi(1,2)*d2_dxdy+chi(1,3)*d2_dxdz+... chi(2,1)*d2_dydx+chi(2,2)*d2_dydy+chi(2,3)*d2_dydz+... chi(3,1)*d2_dzdx+chi(3,2)*d2_dzdy+chi(3,3)*d2_dzdz); end % Consistency enforcement function grumble(npoints,extents,chi,nstenc) if (~isnumeric(npoints))||(numel(npoints)~=3)||(~isreal(npoints))||... (any(npoints<1))||any(mod(npoints,1)~=0) error('dims must be a three-element vector of positive integers.'); end if (~isnumeric(extents))||(numel(extents)~=3)||(~isreal(extents))||(any(extents<=0)) error('extents must be a three-element vector of positive real numbers.'); end if any(npoints<nstenc) error('array dimension is not big enough for the finite difference stencil specified.'); end if (mod(nstenc,1)~=0)||(mod(nstenc,2)~=1)||(nstenc<3) error('the number of stencil points must be an odd integer greater than 3.'); end if (~isnumeric(chi))||(any(size(chi)~=3))||(~isreal(chi))||(norm(chi-chi')>1e-10) error('chi must be a real symmetric 3x3 matrix.'); end end % The power of accurate observation is commonly called % cynicism by those who have not got it. % % George Bernard Shaw
github
tsajed/nmr-pred-master
mprealloc.m
.m
nmr-pred-master/spinach/kernel/utilities/mprealloc.m
1,856
utf_8
ae769ea3bf403d8398d8da53e9fec5eb
% Preallocates an operator in the current basis. Syntax: % % A=mprealloc(spin_system,nnzpc) % % Parameters: % % nnzpc - expected number of non-zeros per column % % [email protected] function A=mprealloc(spin_system,nnzpc) % Check the input if (~isnumeric(nnzpc))||(~isreal(nnzpc))||(~isscalar(nnzpc))||(mod(nnzpc,1)~=0) error('nnzpc parameter must be a positive real integer.'); end % Do the math switch spin_system.bas.formalism case 'sphten-liouv' % Create a zero Liouville space matrix operator problem_dim=size(spin_system.bas.basis,1); A=spalloc(problem_dim,problem_dim,nnzpc*problem_dim); case 'zeeman-hilb' % Create a zero Hilbert space matrix operator problem_dim=prod(spin_system.comp.mults); A=spalloc(problem_dim,problem_dim,nnzpc*problem_dim); case 'zeeman-liouv' % Create a zero Liouville space matrix operator problem_dim=prod(spin_system.comp.mults.^2); A=spalloc(problem_dim,problem_dim,nnzpc*problem_dim); otherwise % Complain and bomb out error('unknown formalism specification.'); end end % In 2006, Oxford's Magdalen College (where Erwin Schrodinger was a Fellow % between 1933 and 1936) received a sum of money from a benefactor towards % "increasing the art content of the College". A number of works were pre- % sented for competition, among them a beautiful stone obelisk, called "Mo- % nument to Knowledge" with the Schrodinger equation inscribed on it. The % obelisk was rejected - the inscriber had missed the bar off Planck's con- % stant. As the College Governing Body put it, the equation, as written, % "would have exploded the stone it was inscribed upon".
github
tsajed/nmr-pred-master
spher_harmon.m
.m
nmr-pred-master/spinach/kernel/utilities/spher_harmon.m
1,443
utf_8
9490c86690e660a11cac1143c9ffd344
% Computes spherical harmonics. Syntax: % % Y=spher_harmon(l,m,theta,phi) % % Parameters: % % l - L quantum number % % m - M quantum number % % theta - a vector of theta angles in radians % % phi - a vector of phi angles in radians % % [email protected] function Y=spher_harmon(l,m,theta,phi) % Check consistency grumble(l,m,theta,phi); % Get Schmidt-normalized Legendres S=legendre(l,cos(theta),'sch'); S=S(abs(m)+1,:); S=S(:); % Make spherical harmonics if m==0 Y=sqrt((2*l+1)/(4*pi))*S.*exp(1i*m*phi); else Y=sqrt((2*l+1)/(4*pi))*S.*exp(1i*m*phi)/sqrt(2); end % Flip the sign if needed if (m>0)&&(mod(m,2)==1), Y=-Y; end end % Consistency enforcement function grumble(l,m,theta,phi) 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(m))||(~isreal(m))||(~isscalar(m))||(mod(m,1)~=0)||(m<-l)||(m>l) error('m must be a real integer from [-l,l] interval.'); end if (~isnumeric(theta))||(~isreal(theta))||(size(theta,2)~=1) error('theta must be a real scalar or column vector.'); end if (~isnumeric(phi))||(~isreal(phi))||(size(phi,2)~=1) error('phi must be a real scalar or column vector.'); end end % Don't pay any attention to what they write about % you. Just measure it in inches. % % Andy Warhol
github
tsajed/nmr-pred-master
fdweights.m
.m
nmr-pred-master/spinach/kernel/utilities/fdweights.m
2,253
utf_8
55f7411498fb404d38d8919c7e2d8ec4
% Calculates finite difference weights for numerical derivatives (inclu- % ding order 0, which amounts to interpolation). Syntax: % % w=fdweights(target_point,grid_points,max_order) % % Parameters: % % target_point - the point at which the derivative is required % % grid_points - the points at which the function is given % % max_order - maximum derivative order % % The function returns finite difference coefficient array with the coef- % ficients for the successive derivatives in rows. % % [email protected] % [email protected] function w=fdweights(target_point,grid_points,max_order) % Check consistency grumble(target_point,grid_points,max_order); % Compute the weights n=length(grid_points); w=zeros(max_order+1,n); w1=1; w4=grid_points(1)-target_point; w(1,1)=1; for i=2:n mn=min(i,max_order+1); w2=1; w5=w4; w4=grid_points(i)-target_point; for j=1:(i-1) w3=grid_points(i)-grid_points(j); w2=w2*w3; if j==(i-1) w(2:mn,i)=w1*((1:(mn-1))'.*w(1:(mn-1),i-1)-w5*w(2:mn,i-1))/w2; w(1,i)=-w1*w5*w(1,i-1)/w2; end w(2:mn,j)=(w4*w(2:mn,j)-(1:(mn-1))'.*w(1:(mn-1),j))/w3; w(1,j)=w4*w(1,j)/w3; end w1=w2; end end % Consistency enforcement function grumble(target_point,grid_points,max_order) if (~isnumeric(target_point))||(~isnumeric(grid_points))||(~isnumeric(max_order))||... (~isreal(target_point))||(~isreal(grid_points))||(~isreal(max_order)) error('all input arguments must be numeric and real.'); end if numel(target_point)~=1 error('target_point must be a scalar.'); end if ~isvector(grid_points) error('grid_points must be a vector.'); end if (target_point>max(grid_points))||(target_point<min(grid_points)) error('the target point should be inside the grid.'); end if ~issorted(grid_points) error('grid_points array must be sorted in ascending order.'); end if mod(max_order,1)~=0 error('max_order must be an integer.'); end if max_order>=numel(grid_points) error('max_order must be smaller than the number of grid points.'); end end % Conscience and cowardice are really the same things. Conscience % is the trade name of the firm. % % Oscar Wilde
github
tsajed/nmr-pred-master
dihedral.m
.m
nmr-pred-master/spinach/kernel/utilities/dihedral.m
980
utf_8
6f9b86e6e2520287a019750bef8fd3c7
% Computes the dihedral angle between vectors specified % by the four sets of atomic coordinates. The angle is % returned in degrees. The atoms are assumed to be bon- % ded as A-B-C-D. Syntax: % % phi=dihedral(A,B,C,D) % % [email protected] function phi=dihedral(A,B,C,D) % Check consistency grumble(A,B,C,D); % Do the math b1=B-A; b2=C-B; b3=D-C; b1=b1/norm(b1); b2=b2/norm(b2); b3=b3/norm(b3); phi=180*atan2(dot(norm(b2)*b1,cross(b2,b3)),dot(cross(b1,b2),cross(b2,b3)))/pi; end % Consistency enforcement function grumble(A,B,C,D) if (~isnumeric(A))||(~isnumeric(B))||(~isnumeric(C))||(~isnumeric(D))||... (~isreal(A))||(~isreal(B))||(~isreal(C))||(~isreal(D))||... (numel(A)~=3)||(numel(B)~=3)||(numel(C)~=3)||(numel(D)~=3) error('the arguments must be 3-element vectors of real numbers.'); end end % IK's bitcoin address is 18p5ttXFwyqbtiLAhUCDWk2vo61DVUZS21. He % probably deserves a pint of beer, right? ;)
github
tsajed/nmr-pred-master
volplot.m
.m
nmr-pred-master/spinach/kernel/utilities/volplot.m
5,448
utf_8
704983c4c1885d881504242dacf3a0c9
% Volumetric plot function for scalar fields. Syntax: % % volplot(data_cube,axis_ranges) % % where data_cube is a 3D cube of real data and axis % ranges is a six-element vector giving axis extents % as [xmin xmax ymin ymax zmin zmax]. % % [email protected] function volplot(data_cube,axis_ranges) % Check consistency grumble(data_cube,axis_ranges); % Switch OpenGL to software opengl software; % Scale positive and negative values max_pos=max(data_cube(data_cube>0)); if (~isempty(max_pos))&&(max_pos>0) data_cube(data_cube>0)=data_cube(data_cube>0)/max_pos; disp(['Positive values divided by ' num2str(max_pos) ' to map them into [0,1].']); end min_neg=min(data_cube(data_cube<0)); if (~isempty(min_neg))&&(min_neg<0) data_cube(data_cube<0)=-data_cube(data_cube<0)/min_neg; disp(['Negative values divided by ' num2str(-min_neg) ' to map them into [-1,0].']); end % Add colour calibration spots data_cube(1,1,1)=1; data_cube(2,2,2)=-1; % Permute dimensions to match surf/meshgrid convention data_cube=permute(data_cube,[3 2 1]); % Determine cube dimensions nx=size(data_cube,3); xmin=axis_ranges(1); xmax=axis_ranges(2); ny=size(data_cube,2); ymin=axis_ranges(3); ymax=axis_ranges(4); nz=size(data_cube,1); zmin=axis_ranges(5); zmax=axis_ranges(6); % Get a persistent graphics window clf reset; hold on; set(gcf,'Renderer','OpenGL'); set(gca,'Projection','perspective','Box','on','XGrid','on','YGrid','on',... 'ZGrid','on','CameraPosition',3*[xmax ymax zmax]*euler2dcm(0,pi/10,0)); % Draw planes parallel to the XY plane for n=1:nz plane=squeeze(data_cube(n,:,:)); plane(abs(plane)<1/64)=NaN; [X,Y]=meshgrid(linspace(xmin,xmax,nx),linspace(ymin,ymax,ny)); Z=linspace(zmin,zmax,nz); Z=Z(n)*ones(ny,nx); if ~all(isnan(plane(:))) surf(X,Y,Z,plane,'FaceAlpha','flat','EdgeAlpha',0,'AlphaDataMapping','scaled','AlphaData',abs(plane)); end end % Draw planes parallel to the XZ plane for n=1:ny plane=squeeze(data_cube(:,n,:)); plane(abs(plane)<1/64)=NaN; [X,Z]=meshgrid(linspace(xmin,xmax,nx),linspace(zmin,zmax,nz)); Y=linspace(ymin,ymax,ny); Y=Y(n)*ones(nz,nx); if ~all(isnan(plane(:))) surf(X,Y,Z,plane,'FaceAlpha','flat','EdgeAlpha',0,'AlphaDataMapping','scaled','AlphaData',abs(plane)); end end % Draw planes parallel to the YZ plane for n=1:nx plane=squeeze(data_cube(:,:,n)); plane(abs(plane)<1/64)=NaN; [Y,Z]=meshgrid(linspace(ymin,ymax,ny),linspace(zmin,zmax,nz)); X=linspace(xmin,xmax,nx); X=X(n)*ones(nz,ny); if ~all(isnan(plane(:))) surf(X,Y,Z,plane,'FaceAlpha','flat','EdgeAlpha',0,'AlphaDataMapping','scaled','AlphaData',abs(plane)); end end % Interpolate alpha map new_alpha=interp1(1:64,alphamap,1:0.25:64,'pchip'); % Scale and filter alpha map new_alpha=new_alpha/5; new_alpha(new_alpha<0.01)=0; % Apply new alpha map alphamap(new_alpha); % Clean up axes axis tight; axis equal; hold off; xlabel('X'); ylabel('Y'); zlabel('Z'); % Set blue -> white -> red colormap colormap(b2r(-0.25,0.25)); end % Consistency enforcement function grumble(data_cube,axis_ranges) if (~isnumeric(axis_ranges))||(~isreal(axis_ranges))||(numel(axis_ranges)~=6) error('axis_ranges must be a real vector with six elements.'); end if (axis_ranges(1)>=axis_ranges(2))||(axis_ranges(3)>=axis_ranges(4))||(axis_ranges(5)>=axis_ranges(6)) error('ranges array should have xmin<xmax, ymin<ymax and zmin<zmax.'); end if (~isnumeric(data_cube))||(~isreal(data_cube))||(ndims(data_cube)~=3) error('data_cube must be a s three-dimensional array of real numbers.'); end end % IK's PCS paper has has taken about five years to write - the suspicion that % Equation 16 might exist dates back to about 2009, but the direct derivation % (simplifying the Laplacian of the convolution of point dipole solution with % electron spin density) has proven impossible. Gareth Charnock (IK's PhD stu- % dent at Oxford) had spent three years struggling with fiendishly elusive in- % tegrals, some of which did not converge or even exist in either Lebesgue or % functional sense. Gareth produced a big enough heap of A4 paper to graduate, % but the problem stood unsolved, having by that time also defeated Gottfried % Otting, Peter Hore, Giacomo Parigi, Guido Pintacuda and (it is thought) Iva- % no Bertini himself when he tried it many years ago. % % Fast forward to April 2014, when IK was sitting in a conference centre hotel % room and staring gloomily into his laptop screen, writing a talk for ESR2014, % intended as a grim warning to the effect of "do not try this at home". "What % a bloody shame", he thought and decided to give it a last chance by googling % up some quantum chemistry literature he vaguely suspected may have encounte- % red similar integrals in a different context. He clicked on the first search % result and Equation 11 flashed on the screen, apparently "a standard relati- % on" in the formalism used to compute 3D integrals in quantum chemistry. That % was it -- five pages of dense handwriting later, Equation 16 was typed hasti- % ly into the laptop, which was then unplugged and taken into the lecture thea- % tre. The talk was in 10 minutes, and it had a new title: "A partial differen- % tial equation for pseudocontact shift". % % http://dx.doi.org/10.1039/C4CP03106G
github
tsajed/nmr-pred-master
clean_up.m
.m
nmr-pred-master/spinach/kernel/utilities/clean_up.m
1,649
utf_8
81b37e3e9fa2fdcb77716243bdd4ae83
% Array clean-up utility. Drops non-zero elements with magnitude below the % user-specified tolerance and converts between sparse and dense represen- % tations depending on the density of non-zeros in the array. Syntax: % % A=clean_up(spin_system,A,nonzero_tol) % % [email protected] % [email protected] function A=clean_up(spin_system,A,nonzero_tol) % Check consistency grumble(A,nonzero_tol); % Check if clean-up is allowed if ~ismember('clean-up',spin_system.sys.disable) % Clean up the matrix A=nonzero_tol*round((1/nonzero_tol)*A); % A small matrix should always be full if issparse(A)&&any(size(A)<spin_system.tols.small_matrix), A=full(A); end % A big sparse matrix with too many non-zeros should be full if issparse(A)&&(nnz(A)/numel(A)>spin_system.tols.dense_matrix), A=full(A); end % A big full matrix with too few non-zeros should be sparse if (~issparse(A))&&(nnz(A)/numel(A)<spin_system.tols.dense_matrix)&&... (all(size(A)>spin_system.tols.small_matrix)) A=sparse(A); end end end % Consistency enforcement function grumble(A,nonzero_tol) %#ok<INUSL> if ~isnumeric(nonzero_tol) error('the tolerance parameter must be numeric.'); end if (~isreal(nonzero_tol))||(numel(nonzero_tol)~=1)||(nonzero_tol<=0) error('nonzero_tol parameter must be a positive real number.'); end end % The most dangerous man to any government is the man who is able to think % things out for himself, without regard to the prevailing superstitions % and taboos. % % H.L. Mencken
github
tsajed/nmr-pred-master
corrfun.m
.m
nmr-pred-master/spinach/kernel/utilities/corrfun.m
3,927
utf_8
df440de11c91f97ab68786f09c80cbb1
% Rotational correlation function, normalized to be the correlation func- % tion between second rank Wigner functions. Syntax: % % [weights,rates]=corrfun(spin_system,k,m,p,q) % % where the indices k,m,p,q correspond to the four indices found in the % ensemble-averaged Wigner function product: % % G(k,m,p,q)=<D2(k,m)*D2(p,q)'> % % the function requires spin_system.rlx.tau_c to be either a single cor- % relation time (in which case the isotropic rotational diffusion model % is used) or vector with two correlation times (in which case they are % assumed to be correlation times for rotation around and perpendicular- % ly to the main axis respectively) or vector with three correlation ti- % mes (in which case those are assumed to be the correlation times for % the rotation around the XX, YY and ZZ direction respectively of the % rotational diffusion tensor). % % The function returns the weights and decay rates of the individual ex- % ponentials in the correlation function. Note that the decay rates re- % turned are negative numbers. % % Note: Wigner function indices are sorted in descending order, that is, % [1 2 3 4 5] in the input maps onto [2 1 0 -1 -2]. % % [email protected] function [weights,rates]=corrfun(spin_system,k,m,p,q) % Check consistency grumble(k,m,p,q); % Select rotational diffusion model switch numel(spin_system.rlx.tau_c) case 1 % Use isotropic rotational diffusion model D=1/(6*spin_system.rlx.tau_c); rates=-6*D; weights=(1/5)*krondelta(k,p)*krondelta(m,q); case 2 % Use axial rotational diffusion model D_ax=1/(6*spin_system.rlx.tau_c(1)); D_eq=1/(6*spin_system.rlx.tau_c(2)); weights=(1/5)*krondelta(k,p)*krondelta(m,q); rates=-(6*D_eq+((m-3)^2)*(D_ax-D_eq)); case 3 % Use anisotropic rotational diffusion model Dxx=1/(6*spin_system.rlx.tau_c(1)); Dyy=1/(6*spin_system.rlx.tau_c(2)); Dzz=1/(6*spin_system.rlx.tau_c(3)); % Refuse to process degenerate cases if (abs(Dxx-Dyy)<1e-6*mean([Dxx Dyy Dzz]))||... (abs(Dyy-Dzz)<1e-6*mean([Dxx Dyy Dzz]))||... (abs(Dzz-Dxx)<1e-6*mean([Dxx Dyy Dzz])) error('the three rotational correlation times must be different.'); end % Compute decay rates delta=sqrt(Dxx^2+Dyy^2+Dzz^2-Dxx*Dyy-Dxx*Dzz-Dyy*Dzz); rates(1)=-(4*Dxx+Dyy+Dzz); rates(2)=-(Dxx+4*Dyy+Dzz); rates(3)=-(Dxx+Dyy+4*Dzz); rates(4)=-(2*Dxx+2*Dyy+2*Dzz-2*delta); rates(5)=-(2*Dxx+2*Dyy+2*Dzz+2*delta); % Compute coefficients lambda_p=sqrt(2/3)*(Dxx+Dyy-2*Dzz+2*delta)/(Dxx-Dyy); lambda_m=sqrt(2/3)*(Dxx+Dyy-2*Dzz-2*delta)/(Dxx-Dyy); h(1,2)=1/sqrt(2); h(1,4)=1/sqrt(2); h(2,2)=-1/sqrt(2); h(2,4)=1/sqrt(2); h(3,5)=1/sqrt(2); h(3,1)=-1/sqrt(2); h(4,1)=1/sqrt(2+lambda_m^2); h(4,3)=lambda_m/sqrt(2+lambda_m^2); h(4,5)=1/sqrt(2+lambda_m^2); h(5,1)=1/sqrt(2+lambda_p^2); h(5,3)=lambda_p/sqrt(2+lambda_p^2); h(5,5)=1/sqrt(2+lambda_p^2); % Compute weights for j=1:5, weights(j)=(1/5)*krondelta(k,p)*h(j,m)*h(j,q); end %#ok<AGROW> end end % Consistency enforcement function grumble(k,m,p,q) if (~isnumeric(k))||(~isnumeric(m))||... (~isnumeric(p))||(~isnumeric(q)) error('all indices must be numeric.'); end if ~isreal([k m p q]) error('all indices must be real.'); end if any(mod([k m p q],1)~=0) error('all indices must be integers.'); end if any([k m p q]>5)||any([k m p q]<1) error('k,m,p,q must be from [1,5] interval.'); end end % "But they are useless. They can only give you answers." % % Pablo Picasso, about computers.
github
tsajed/nmr-pred-master
krondelta.m
.m
nmr-pred-master/spinach/kernel/utilities/krondelta.m
279
utf_8
f7e344eeb76194157948ab9d6887785a
% Kronecker symbol. Syntax: % % d=krondelta(a,b) % % [email protected] function d=krondelta(a,b) if a==b, d=1; else, d=0; end end % Die ganzen Zahlen hat der liebe Gatt gemacht, % alles andere ist Menschenwerk. % % Leopold Kronecker
github
tsajed/nmr-pred-master
apodization.m
.m
nmr-pred-master/spinach/kernel/utilities/apodization.m
8,057
utf_8
0ad443b71611fb9e133cea297325df2e
% Performs free induction decay apodization. Supports 1D, 2D and 3D FIDs with % the following syntax: % % fid=apodization(fid,window_type,params) % % Arguments: % % fid - The free induction decay. The function expects a column % vector in the case of 1D FID, a 2D matrix with the time % origin located at the (1,1) corner point in the case of % a 2D FID, and a 3D matrix with the time origin located % at the (1,1,1) corner point in the case of a 3D FID. % % window_type - Type of the window function. The following window func- % tion types are supported: % % 'none-1d' divides the first point by 2 and does noth- % ing else. % % 'crisp-1d' divides the first point by 2 and multiplies % the FID by a matched cos^8 half-bell. % % 'exp-1d' divides the first point by 2 and multiplies % the FID by a decaying exponential with the % decay rate specified by the user. % % 'gaussian-1d' divides the first point by 2 and multiplies % the FID by a decaying Gaussian with the de- % cay rate specified by the user. % % 'cosbell-1d' divides the first point by 2 and multiplies % the FID by a matched cosine half-bell. % % 'echo-1d' multiplies the FID by sine square bell, used % for DEER spin echoes. % % 'kaiser-1d' divides the first point by 2 and multiplies % the FID by a Kaiser function with the decay % rate specified by the user. % % 'hamming-1d' divides the first point by 2 and multiplies % the FID by a matched Hamming function. % % 'none-2d' divides the corner point by 2 and does noth- % ing else. % % 'crisp-2d' divides the corner point by 2 and multipli- % es the FID by a matched cos^4 half-bell. % % 'exp-2d' divides the corner point by 2 and multipli- % es the FID by a decaying exponential in both % dimensions with the decay rate specified by % the user. % % 'gaussian-2d' divides the corner point by 2 and multipli- % the FID by a decaying Gaussian in both dim- % ensions with the decay rate specified by % the user. % % 'cosbell-2d' divides the corner point by 2 and multipli- % es the FID by a matched cosine half-bell in % both dimensions. % % 'sqcosbell-2d' divides the first point by 2 and multiplies % the FID by matched squared cosine half-bell. % % 'echo-2d' multiplies one dimension by the square sine % bell, used for DEER echo processing. % % 'cosbell-3d' divides the corner point by 2 and multipli- % es the FID by a matched cosine half-bell in % all three dimensions. % % params - decay rate parameters for those window functions that % require such parameters. If a function does not requi- % re a parameter, the value of params is ignored. Defa- % value of params is zero. % % [email protected] function fid=apodization(fid,window_type,params) % Set the defaults if ~exist('params','var'), params=0; end % Check consistency grumble(fid,window_type,params); % Apply the window function switch window_type case 'none-1d' fid(1)=fid(1)/2; case 'crisp-1d' fid(1)=fid(1)/2; fid=fid.*cos(linspace(0,pi/2,numel(fid))').^8; case 'exp-1d' fid(1)=fid(1)/2; fid=fid.*exp(-params*linspace(0,1,numel(fid))'); case 'gaussian-1d' fid(1)=fid(1)/2; fid=fid.*exp(-params*(linspace(0,1,numel(fid))').^2); case 'cosbell-1d' fid(1)=fid(1)/2; fid=fid.*cos(linspace(0,pi/2,numel(fid))'); case 'sqcosbell-1d' fid(1)=fid(1)/2; fid=fid.*cos(linspace(0,pi/2,numel(fid))').^2; case 'kaiser-1d' fid(1)=fid(1)/2; fid=fid.*kaiser(numel(fid),params); case 'hamming-1d' fid(1)=fid(1)/2; fid=fid.*hamming(numel(fid)); case 'echo-1d' fid=fid.*sin(linspace(0,pi,numel(fid))').^2; case 'echo-2d' decay_col=sin(linspace(0,pi,size(fid,1))').^2; decay_row=ones(size(fid,2),1); fid=fid.*kron(decay_col,decay_row'); case 'none-2d' fid(1,1)=fid(1,1)/2; case 'crisp-2d' fid(1,1)=fid(1,1)/2; decay_col=cos(linspace(0,pi/2,size(fid,1))').^4; decay_row=cos(linspace(0,pi/2,size(fid,2))').^4; fid=fid.*kron(decay_col,decay_row'); case 'exp-2d' fid(1,1)=fid(1,1)/2; decay_col=exp(-params*linspace(0,1,size(fid,1))'); decay_row=exp(-params*linspace(0,1,size(fid,2))'); fid=fid.*kron(decay_col,decay_row'); case 'gaussian-2d' fid(1,1)=fid(1,1)/2; decay_col=exp(-params*(linspace(0,1,size(fid,1))').^2); decay_row=exp(-params*(linspace(0,1,size(fid,2))').^2); fid=fid.*kron(decay_col,decay_row'); case 'cosbell-2d' fid(1,1)=fid(1,1)/2; decay_col=cos(linspace(0,pi/2,size(fid,1))'); decay_row=cos(linspace(0,pi/2,size(fid,2))'); fid=fid.*kron(decay_col,decay_row'); case 'sqcosbell-2d' fid(1,1)=fid(1,1)/2; decay_col=cos(linspace(0,pi/2,size(fid,1))').^2; decay_row=cos(linspace(0,pi/2,size(fid,2))').^2; fid=fid.*kron(decay_col,decay_row'); case 'cosbell-3d' fid(1,1,1)=fid(1,1,1)/2; [f1,f2,f3]=ndgrid(linspace(0,pi/2,size(fid,1)),... linspace(0,pi/2,size(fid,2)),... linspace(0,pi/2,size(fid,3))); fid=fid.*cos(f1).*cos(f2).*cos(f3); case 'sqcosbell-3d' fid(1,1,1)=fid(1,1,1)/2; [f1,f2,f3]=ndgrid(linspace(0,pi/2,size(fid,1)),... linspace(0,pi/2,size(fid,2)),... linspace(0,pi/2,size(fid,3))); fid=fid.*(cos(f1).^2).*(cos(f2).^2).*(cos(f3).^2); otherwise error(['function ' window_type ' not implemented.']); end end % Consistency enforcement function grumble(fid,window_type,decay_rate) if (~isnumeric(fid))||(~isnumeric(decay_rate)) error('fid and decay rate must be numeric.'); end if (numel(decay_rate)~=1)||(~isreal(decay_rate))||(decay_rate<0) error('decay rate must be a positive real number.'); end if ~ischar(window_type) error('window_type must be a character string.'); end if strcmp(window_type((end-1):end),'1d')&&... ((numel(size(fid))~=2)||(size(fid,2)~=1)||(size(fid,1)<2)) error('1D window functions require FID to be a column vector.'); end if strcmp(window_type((end-1):end),'2d')&&... ((numel(size(fid))~=2)||any(size(fid)<2)) error('2D window functions require FID to be a 2D matrix.'); end if strcmp(window_type((end-1):end),'3d')&&... ((numel(size(fid))~=3)||any(size(fid)<2)) error('3D window functions require FID to be a 3D matrix.'); end end % I have had my results for a long time, but I do not yet % know how I am to arrive at them. % % Carl Friedrich Gauss
github
tsajed/nmr-pred-master
zte.m
.m
nmr-pred-master/spinach/kernel/utilities/zte.m
5,566
utf_8
a7003372b5f1eb62c201b8efe1c47394
% Zero track elimination function. Inspects the first few steps in the % system trajectory and drops the states that did not get populated to a % user-specified tolerance. The default tolerance may be altered by set- % ting sys.tols.zte_tol variable before calling create(). Syntax: % % projector=zte(spin_system,L,rho,nstates) % % Parameters: % % L - the Liouvillian to be used for time propagation % % rho - the initial state to be used for time propagation % % nstates - if this parameter is specified, only nstates most % populated states are kept, irrespective of the to- % lerance parameter % % Output: % % projector - projector matrix into the reduced space, to be used % as follows: L_reduced=P'*L*P, rho_reduced=P'*rho; % % Further information is available in IK's JMR paper on the subject: % % http://dx.doi.org/10.1016/j.jmr.2008.08.008 % % [email protected] function projector=zte(spin_system,L,rho,nstates) % Validate the input grumble(spin_system,L,rho); % Run Zero Track Elimination if ismember('zte',spin_system.sys.disable) % Skip if instructed to do so by the user report(spin_system,'WARNING - zero track elimination disabled, basis set left unchanged.'); % Return a unit matrix projector=speye(size(L)); elseif nnz(rho)/numel(rho)>spin_system.tols.zte_maxden % Skip if the benefit is likely to be minor report(spin_system,'WARNING - too few zeros in the state vector, basis set left unchanged.'); % Return a unit matrix projector=speye(size(L)); elseif norm(rho,1)<spin_system.tols.zte_tol % Skip if the state vector norm is too small for Krylov procedure report(spin_system,'WARNING - state vector norm below drop tolerance, basis set left unchanged.'); % Return a unit matrix projector=speye(size(L)); else % Estimate the Larmor time step timestep=stepsize(L); % Do not allow infinite time step if isinf(timestep) report(spin_system,'zero Liouvillian supplied, using unit time step.'); timestep=1; end % Report to the user if exist('nstates','var') report(spin_system,['keeping ' num2str(nstates) ' states with the greatest trajectory weight.']); else report(spin_system,['dropping states with amplitudes below ' num2str(spin_system.tols.zte_tol)... ' within the first ' num2str(timestep*spin_system.tols.zte_nsteps) ' seconds.']); end report(spin_system,['a maximum of ' num2str(spin_system.tols.zte_nsteps) ' steps shall be taken, ' num2str(timestep) ' seconds each.']); % Preallocate the trajectory trajectory=zeros(numel(rho),spin_system.tols.zte_nsteps); % Set the starting point trajectory(:,1)=rho; report(spin_system,['evolution step 0, active space dimension ' num2str(nnz(abs(trajectory(:,1))>spin_system.tols.zte_tol))]); % Compute trajectory steps with Krylov technique for n=2:spin_system.tols.zte_nsteps % Take a step forward trajectory(:,n)=step(spin_system,L,trajectory(:,n-1),timestep); % Analyze the trajectory prev_space_dim=nnz(max(abs(trajectory(:,1:(n-1))),[],2)>spin_system.tols.zte_tol); curr_space_dim=nnz(max(abs(trajectory),[],2)>spin_system.tols.zte_tol); % Inform the user report(spin_system,['evolution step ' num2str(n-1) ', active space dimension ' num2str(curr_space_dim)]); % Terminate if done early if curr_space_dim==prev_space_dim, break; end end % Determine which tracks to drop if exist('nstates','var') % Determine state amplitudes amplitudes=max(abs(trajectory),[],2); % Sort the maximum amplitudes in descending order [~,index]=sort(amplitudes,'descend'); % Drop all states beyond a given number zero_track_mask=true(size(rho)); zero_track_mask(index(1:nstates))=false(); else % Drop all states with maximum amplitude below the threshold zero_track_mask=(max(abs(trajectory),[],2)<spin_system.tols.zte_tol); end % Take a unit matrix and delete the columns corresponding to zero tracks projector=speye(size(L)); projector(:,zero_track_mask)=[]; % Report back to the user report(spin_system,['state space dimension reduced from ' num2str(size(L,2)) ' to ' num2str(size(projector,2))]); end end % Input validation function function grumble(spin_system,L,rho) if ~ismember(spin_system.bas.formalism,{'zeeman-liouv','sphten-liouv'}) error('zero track elimination is only available for zeeman-liouv and sphten-liouv formalisms.'); end if (~isnumeric(L))||(~isnumeric(rho)) error('both inputs must be numeric.'); end if ~isvector(rho) error('single state vector expected, not a stack.'); end if size(L,1)~=size(L,2) error('Liouvillian must be square.'); end if size(L,2)~=size(rho,1) error('Liouvillian and state vector dimensions must be consistent.'); end end % Every great scientific truth goes through three stages. First, people say % it conflicts with the Bible. Next they say it had been discovered before. % Lastly they say they always believed it. % % Louis Agassiz
github
tsajed/nmr-pred-master
rotor_stack.m
.m
nmr-pred-master/spinach/kernel/utilities/rotor_stack.m
3,396
utf_8
c4ed13d68bf6c33318dd0b8eb1ea7c81
% Returns a rotor stack of Liouvillians or Hamiltonians. The stack is % needed for the traditional style calculation of MAS dynamics. Syntax: % % L=rotor_stack(spin_system,parameters,assumptions) % % Parameters: % % parameters.axis - spinning axis, given as a normalized % 3-element vector % % parameters.offset - a cell array giving transmitter off- % sets in Hz on each of the spins listed % in parameters.spins array % % parameters.max_rank - maximum harmonic rank to retain in % the solution (increase till conver- % gence is achieved, approximately % equal to the number of spinning si- % debands in the spectrum) % % parameters.rframes - rotating frame specification, e.g. % {{'13C',2},{'14N,3}} requests second % order rotating frame transformation % with respect to carbon-13 and third % order rotating frame transformation % with respect to nitrogen-14. When % this option is used, the assumptions % on the respective spins should be % laboratory frame. % % parameters.orientation - the orientation of the spin system at rotor % phase zero, a vector of three Euler angles % in radians. % % Note: relaxation and chemical kinetics are not included. % % [email protected] function L=rotor_stack(spin_system,parameters,assumptions) % Get the Hamiltonian [H,Q]=hamiltonian(assume(spin_system,assumptions)); % Apply offsets H=frqoffset(spin_system,H,parameters); % Get rotor axis orientation [phi,theta,~]=cart2sph(parameters.axis(1),parameters.axis(2),parameters.axis(3)); theta=pi/2-theta; D_lab2rot=euler2wigner(phi,theta,0); D_rot2lab=D_lab2rot'; % Compute rotor angles [rotor_angles,~]=fourdif(2*parameters.max_rank+1,1); % Get carrier operators C=cell(size(parameters.rframes)); for n=1:numel(parameters.rframes) C{n}=carrier(spin_system,parameters.rframes{n}{1}); end % Set crystallite orientation D_crystal=euler2wigner(parameters.orientation); % Preallocate Liouvillian blocks L=cell(2*parameters.max_rank+1,1); % Build Liouvillian blocks parfor n=1:(2*parameters.max_rank+1) %#ok<*PFBNS> % Get the rotation D_rotor=euler2wigner(0,0,rotor_angles(n)); if strcmp(parameters.masframe,'magnet') D=D_rot2lab*D_rotor*D_lab2rot*D_crystal; elseif strcmp(parameters.masframe,'rotor') D=D_rot2lab*D_rotor*D_crystal; else D=0; error('unknown MAS frame.'); %#ok<NASGU> end % Build the block L{n}=H; for k=1:5 for m=1:5 L{n}=L{n}+D(k,m)*Q{k,m}; end end L{n}=(L{n}+L{n}')/2; % Apply the rotating frame for k=1:numel(parameters.rframes) L{n}=rotframe(spin_system,C{k},L{n},parameters.rframes{k}{1},parameters.rframes{k}{2}); end % Clean up the result L{n}=clean_up(spin_system,L{n},spin_system.tols.liouv_zero); end end % Never complain and never explain. % % Benjamin Disraeli
github
tsajed/nmr-pred-master
xyz2dd.m
.m
nmr-pred-master/spinach/kernel/utilities/xyz2dd.m
1,548
utf_8
bdb467f2a77eb37191d097db18fc34a7
% Converts coordinate specification of the dipolar interaction % into the dipolar interaction constant (angular frequency un- % its), three Euler angles in radians and the dipolar interac- % tion matrix (angular frequency units). Syntax: % % [d,alp,bet,gam,m]=xyz2dd(r1,r2,isotope1,isotope2) % % where r1 and r2 are 3-element vectors of spin coordinates in % Angstroms and isotope(1,2) are isotope strings, e.g. '13C'. % % N.B. Euler angles are not uniquely defined for the orientati- % on of axial interactions (gamma angle can be anything). % % [email protected] function [d,alp,bet,gam,m]=xyz2dd(r1,r2,isotope1,isotope2) % Fundamental constants hbar=1.054571628e-34; mu0=4*pi*1e-7; % Get the distance distance=norm(r2-r1,2); % Get the ort ort=(r2-r1)/distance; % Get the dipolar interaction constant d=spin(isotope1)*spin(isotope2)*hbar*mu0/(4*pi*(distance*1e-10)^3); % Get the Euler angles [alp,bet,~]=cart2sph(ort(1),ort(2),ort(3)); bet=pi/2-bet; gam=0; % Get the dipolar coupling matrix and symmetrise it m=d*[1-3*ort(1)*ort(1) -3*ort(1)*ort(2) -3*ort(1)*ort(3); -3*ort(2)*ort(1) 1-3*ort(2)*ort(2) -3*ort(2)*ort(3); -3*ort(3)*ort(1) -3*ort(3)*ort(2) 1-3*ort(3)*ort(3)]; m=(m+m')/2; end % This principle is not a theorem, but a physical proposition, % that is, a vaguely stated and, strictly speaking, false as- % sertion. Such assertions often happen to be fruitful sourc- % es for mathematical theorems. % % Vladimir Arnold
github
tsajed/nmr-pred-master
zeeman2sphten.m
.m
nmr-pred-master/spinach/kernel/utilities/zeeman2sphten.m
1,797
utf_8
0980b33c65b4637f8a563833ff7d9abf
% Generates spherical tensor expansions for single-spin Zeeman % basis operators in Hilbert space. Syntax: % % stexp=zeeman2sphten(matrix,type) % % where matrix is a single-spin matrix written in the Zeeman ba- % sis in Hilbert space, type denote the matrix is a density mat- % rix or a operator, and stexp is a cell array with the first % element of each row giving the operator name and the second % element being the corresponding expansion coefficient. The se- % cond argument should be set to 'state' to get a state vector % expansion and to 'oper' to get an operator expansion. % % [email protected] % [email protected] function stexp=zeeman2sphten(matrix,type) % Validate the input grumble(type); % Get the IST operators I=irr_sph_ten(numel(diag(matrix))); % Preallocate the output stexp=cell(numel(I),2); % Run the expansion for n=1:numel(I) % Build operator name [L,M]=lin2lm(n-1); stexp{n,1}=['T' num2str(L) ',' num2str(M)]; % Choose correct normalisation switch type case 'state' % Get the coefficient stexp{n,2}=trace(I{n}'*matrix)/sqrt(trace(I{n}'*I{n})); case 'oper' % Get the coefficient stexp{n,2}=trace(I{n}'*matrix)/trace(I{n}'*I{n}); otherwise % Complain and bomb out error('The input type is wrong.'); end end end % Input validation function function grumble(type) if ~ischar(type) error('the variable type must be a character string.'); end if ~ismember(type,{'state','oper'}) error('valid values for type are ''state'' and ''oper''.'); end end
github
tsajed/nmr-pred-master
sparse2csr.m
.m
nmr-pred-master/spinach/kernel/utilities/sparse2csr.m
1,474
utf_8
3c80738f30e8449faf35525f8f7e6aae
% Computes a partial Compressed Row Storage transformation for a given % Matlab sparse matrix. Only returns the index arrays and ignores the % values. Syntax: % % [row_ptr,col_idx]=sparse2csr(A) % % Parameters: % % A - sparse matrix to be converted into the CSR % format % % Outputs: % % row_ptr - row pointer array of the CSR format % % col_idx - column index array of the CSR format % % [email protected] % [email protected] function [row_ptr,col_idx]=sparse2csr(A) % Check consistency grumble(A); % Set problem dimensions matrix_dim=size(A,1); n_nonzeros=nnz(A); % Get Cartesian indices [rows,cols]=find(A); % Preallocate the answer col_idx=zeros(n_nonzeros,1); row_ptr=zeros(matrix_dim+1,1); % Count row elements for n=1:n_nonzeros row_ptr(rows(n)+1)=row_ptr(rows(n)+1)+1; end row_ptr=cumsum(row_ptr); % Build column index for n=1:n_nonzeros col_idx(row_ptr(rows(n))+1)=cols(n); row_ptr(rows(n))=row_ptr(rows(n))+1; end % Build row index for n=matrix_dim:-1:1 row_ptr(n+1)=row_ptr(n); end row_ptr(1)=0; row_ptr=row_ptr+1; end % Consistency enforcement function grumble(A) if (~islogical(A))||(~ismatrix(A))||(~issparse(A)) error('A must be a sparse logical matrix.'); end end % It had long since come to my attention that people of % accomplishment rarely sat back and let things happen % to them. They went out and happened to things. % % Leonardo Da Vinci
github
tsajed/nmr-pred-master
dcm2quat.m
.m
nmr-pred-master/spinach/kernel/utilities/dcm2quat.m
3,822
utf_8
ae52e6b446c66c6e0897b87cccf44e10
% Converts a direction cosine matrix representation of a rotation into % the unit quaternion representation. Syntax: % % q=dcm2quat(dcm) % % Output: a structure with four fields q.u, q.i, q.j, q.k giving the % four components of the quaternion. % % [email protected] function q=dcm2quat(dcm) % Check consistency grumble(dcm); % Get the trace tr_dcm=trace(dcm); % Run the conversion if tr_dcm>0 % Most angles are straightforward A=sqrt(tr_dcm+1); q.u=0.5*A; q.i=(dcm(2,3)-dcm(3,2))/(2*A); q.j=(dcm(3,1)-dcm(1,3))/(2*A); q.k=(dcm(1,2)-dcm(2,1))/(2*A); else % Zero trace case needs more care d=diag(dcm); if (d(2)>d(1))&&(d(2)>d(3)) A=sqrt(d(2)-d(1)-d(3)+1.0); q.j=0.5*A; if A~=0, A=0.5/A; end q.u=(dcm(3,1)-dcm(1,3))*A; q.i=(dcm(1,2)+dcm(2,1))*A; q.k=(dcm(2,3)+dcm(3,2))*A; elseif d(3)>d(1) A=sqrt(d(3)-d(1)-d(2)+1.0); q.k=0.5*A; if A~=0, A = 0.5/A; end q.u=(dcm(1,2)-dcm(2,1))*A; q.i=(dcm(3,1)+dcm(1,3))*A; q.j=(dcm(2,3)+dcm(3,2))*A; else A=sqrt(d(1)-d(2)-d(3)+1.0); q.i=0.5*A; if A~=0, A=0.5/A; end q.u=(dcm(2,3)-dcm(3,2))*A; q.j=(dcm(1,2)+dcm(2,1))*A; q.k=(dcm(3,1)+dcm(1,3))*A; end end end % Consistency enforcement function grumble(dcm) if (~isnumeric(dcm))||(~isreal(dcm))||(~all(size(dcm)==[3 3])) error('DCM must be a real 3x3 matrix.'); end if norm(dcm'*dcm-eye(3))>1e-6 warning('DCM is not orthogonal to 1e-6 tolerance - conversion accuracy not guaranteed.'); end if norm(dcm'*dcm-eye(3))>1e-2 error('DCM is not orthogonal to 1e-2 tolerance, cannot proceed with conversion.'); end if abs(det(dcm)-1)>1e-6 warning('DCM determinant is not unit to 1e-6 tolerance - conversion accuracy not guaranteed.'); end if abs(det(dcm)-1)>1e-2 error('DCM determinant is not unit to 1e-2 tolerance, cannot proceed with conversion.'); end end % I was playing in a tournament in Germany one year when a man approached % me. Thinking he just wanted an autograph, I reached for my pen, when the % man made a startling announcement... "I've solved chess!" I sensibly % started to back away in case the man was dangerous as well as insane, but % the man continued: "I'll bet you 50 marks that if you come back to my % hotel room I can prove it to you." Well, 50 marks was 50 marks, so I % humored the fellow and accompanied him to his room. Back at the room, we % sat down at his chess board. "I've worked it all out, white mates in 12 % moves no matter what." I played with black perhaps a bit incautiously, % but I found to my horror that white's pieces coordinated very strangely, % and that I was going to be mated on the 12th move! I tried again, and I % played a completely different opening that couldn't possibly result in % such a position, but after a series of very queer-looking moves, once % again I found my king surrounded, with mate to fall on the 12th move. I % asked the man to wait while I ran downstairs and fetched Emmanuel Lasker, % who was world champion before me. He was extremely skeptical, but agreed % to at least come and play. Along the way we snagged Alekhine, who was % then world champion, and the three of us ran back up to the room. % % Lasker took no chances, but played as cautiously as could be, yet after % a bizarre, pointless-looking series of maneuvers, found himself hemmed % in a mating net from which there was no escape. Alekhine tried his hand, % too, but all to no avail. % % It was awful! Here we were, the finest players in the world, men who had % devoted our very lives to the game, and it was all over! The tournaments, % the matches, everything - chess had been solved, white wins. % % We killed him, of course. % % Jose Raul Capablanca, only half joking.
github
tsajed/nmr-pred-master
lcurve.m
.m
nmr-pred-master/spinach/kernel/utilities/lcurve.m
2,869
utf_8
c0b8184b4bc2c5e4eb7d99fed4484c38
% L-curve analysis function. Syntax: % % lambda_opt=lcurve(lambda,err,reg,mode) % % Parameters: % % lam - row vector of regularisation parameters % % err - row vector of least squares errors % % reg - row vector of regularisation functional values % % The function returns the regularisation parameter at the point of the % maximum curvature of the L-curve. % % [email protected] function lam_opt=lcurve(lam,err,reg,mode) % Move to logarithmic coordinates log_lam=log10(lam); log_err=log10(err); log_reg=log10(reg); % Resample using quintic spline sp_err=spapi(optknt(log_lam,5),log_lam,log_err); sp_reg=spapi(optknt(log_lam,5),log_lam,log_reg); log_err=fnval(linspace(min(log_lam),max(log_lam),1000),sp_err); log_reg=fnval(linspace(min(log_lam),max(log_lam),1000),sp_reg); log_lam=linspace(min(log_lam),max(log_lam),1000); % Return to linear coordinates err=10.^log_err; reg=10.^log_reg; lam=10.^log_lam; % Plot the L-curve subplot(1,2,1); plot(err,reg,'b-'); hold on; axis tight; axis equal; xlabel('least squares error'); ylabel('regularisation error'); % Get the derivatives switch mode case 'log' % Derivatives in logarithmic coordinates xp=fdvec(log_err,5,1); xpp=fdvec(log_err,5,2); yp=fdvec(log_reg,5,1); ypp=fdvec(log_reg,5,2); % Plot in logarithmic coordinates set(gca,'xscale','log'); set(gca,'yscale','log'); case 'linear' % Derivatives in linear coordinates xp=fdvec(err,5,1); xpp=fdvec(err,5,2); yp=fdvec(reg,5,1); ypp=fdvec(reg,5,2); end % Get the signed curvature kappa=(xp.*ypp-yp.*xpp)./((xp.^2+yp.^2).^(3/2)); % Plot the curvature subplot(1,2,2); plot(lam,kappa); set(gca,'xscale','log'); hold on; xlabel('regularisation parameter'); ylabel('L-curve curvature'); axis tight; % Find the optimum point [~,index]=max(kappa); lam_opt=lam(index); subplot(1,2,1); plot(err(index),reg(index),'ro'); subplot(1,2,2); plot(lam(index),kappa(index),'ro'); end % I don't like ass kissers, flag wavers or team players. I like people who % buck the system. Individualists. I often warn people: "Somewhere along % the way, someone is going to tell you, 'There is no "I" in team.' What % you should tell them is, 'Maybe not. But there is an "I" in independence, % individuality and integrity.'" Avoid teams at all cost. Keep your circle % small. Never join a group that has a name. If they say, "We're the So- % and-Sos," take a walk. And if, somehow, you must join, if it's unavoid- % able, such as a union or a trade association, go ahead and join. But don't % participate; it will be your death. And if they tell you you're not a te- % am player, congratulate them on being observant. % % George Carlin
github
tsajed/nmr-pred-master
castep2nqi.m
.m
nmr-pred-master/spinach/kernel/utilities/castep2nqi.m
1,531
utf_8
3b543d1c141e38ad6a0bd4b6ea36ca2a
% Converts CASTEP EFG tensor (it is printed in atomic units) to NQI % 3x3 tensor in Hz that is required by Spinach. Syntax: % % nqi=castep2nqi(V,Q,I) % % Parameters: % % V - EFG tensor from CASTEP output, a.u. % % Q - nuclear quadrupole moment, barn % % I - nuclear spin quantum number % % [email protected] function nqi=castep2nqi(V,Q,I) % Check consistency grumble(V,Q,I) % Fundamental constants efg_atomic=9.717362e+21; e_charge=1.60217657e-19; h_planck=6.62606957e-34; % Calculation nqi=V*efg_atomic*(Q*1e-28)*e_charge/(h_planck*2*I*(2*I-1)); end % Consistency enforcement function grumble(V,Q,I) if (~isnumeric(V))||(~isnumeric(Q))||(~isnumeric(I)) error('all inputs must be numeric.'); end if (~isreal(V))||(~isreal(Q))||(~isreal(I)) error('all inputs must be real.'); end if ~all(size(V)==[3 3]) error('V argument must be a 3x3 matrix.'); end if numel(Q)~=1 error('Q argument must have a single element.'); end if (numel(I)~=1)||(I<1)||(mod(2*I+1,1)~=0) error('I must be an integer or half-integer greater or equal to 1.'); end end % My children! We have fought in many battles together, over mountaintops % and beach heads, through forests and deserts. I have seen great acts of % valor from each one of you, which does my heart proud. I have also seen % dirty fighting, backstabbing, cruel and wanton feats of savagery, which % pleases me equally well. For you are all warriors. % % Queen Potema
github
tsajed/nmr-pred-master
banner.m
.m
nmr-pred-master/spinach/kernel/utilities/banner.m
3,083
utf_8
731fa3b6606e57b88cee21d2392c22c1
% Prints the banners. This is an internal function of the Spinach kernel, % user edits are discouraged. % % [email protected] function banner(spin_system,identifier) switch identifier case 'version_banner' report(spin_system,' '); report(spin_system,'============================================'); report(spin_system,'= ='); report(spin_system,'= SPINACH v1.8 ='); report(spin_system,'= ='); report(spin_system,'= Ilya Kuprov, Hannah Hogben, ='); report(spin_system,'= Luke Edwards, Matthew Krzystyniak ='); report(spin_system,'= Gareth Charnock, Li-Ping Yang ='); report(spin_system,'= Dmitry Savostyanov, Sergey Dolgov ='); report(spin_system,'= Frederic Mentink-Vigier, David Goodwin ='); report(spin_system,'= Zenawi Welderufael, Jean-Nicolas Dumez ='); report(spin_system,'= Peter Hore, Liza Suturina, Ahmed Allami ='); report(spin_system,'= ='); report(spin_system,'= GNU Public License v2.5 ='); report(spin_system,'= ='); report(spin_system,'============================================'); report(spin_system,' '); case 'spin_system_banner' report(spin_system,' '); report(spin_system,'============================================'); report(spin_system,'= ='); report(spin_system,'= SPIN SYSTEM ='); report(spin_system,'= ='); report(spin_system,'============================================'); report(spin_system,' '); case 'basis_banner' report(spin_system,' '); report(spin_system,'============================================'); report(spin_system,'= ='); report(spin_system,'= BASIS SET ='); report(spin_system,'= ='); report(spin_system,'============================================'); report(spin_system,' '); case 'sequence_banner' report(spin_system,' '); report(spin_system,'============================================'); report(spin_system,'= ='); report(spin_system,'= PULSE SEQUENCE ='); report(spin_system,'= ='); report(spin_system,'============================================'); report(spin_system,' '); otherwise error('unknown banner.'); end end % The free man will ask neither what his country can do for him, nor what % he can do for his country. % % Milton Friedman
github
tsajed/nmr-pred-master
unit_state.m
.m
nmr-pred-master/spinach/kernel/utilities/unit_state.m
1,223
utf_8
8c6ea4cecf40c375c05daecb33744f15
% Returns a unit state in the current formalism and basis. Syntax: % % rho=unit_state(spin_system) % % There are no adjustable parameters. % % [email protected] % [email protected] function rho=unit_state(spin_system) % Decide how to proceed switch spin_system.bas.formalism case 'sphten-liouv' % Normalized T(0,0) state rho=sparse(1,1,1,size(spin_system.bas.basis,1),1); case 'zeeman-liouv' % Normalized stretched unit matrix rho=speye(prod(spin_system.comp.mults)); rho=rho(:); rho=rho/norm(rho,2); case 'zeeman-hilb' % Unit matrix rho=speye(prod(spin_system.comp.mults)); otherwise % Complain and bomb out error('unknown formalism specification.'); end end % There used to be a simple story about Russian literature, that we % thought the good writers were the ones who opposed the regime. Once % we don't have that story about Russia as a competitor, or an enemy, % it was much less clear to us what we should be interested in. % % Edwin Frank, the editor of NYRB Classics
github
tsajed/nmr-pred-master
dcm2wigner.m
.m
nmr-pred-master/spinach/kernel/utilities/dcm2wigner.m
2,585
utf_8
312f02cab4eb464b048bbb6067a0a525
% Converts a directional cosine matrix into second-rank Wigner function % matrix. 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] function W=dcm2wigner(dcm) % Check consistency grumble(dcm); % Compute A and B coefficients A=sqrt(0.5*(dcm(1,1)+1i*dcm(1,2)-1i*dcm(2,1)+dcm(2,2))); B=sqrt(0.5*(-dcm(1,1)+1i*dcm(1,2)+1i*dcm(2,1)+dcm(2,2))); % Verify amplitudes if abs(A*A'-0.5*(1+dcm(3,3)))+abs(B*B'-0.5*(1-dcm(3,3)))>1e-6 error('DCM does not pass self-consistency check on amplitudes.'); end % Verify phases if abs(A*B+0.5*(dcm(1,3)-1i*dcm(2,3)))+abs(A*B'-0.5*(dcm(3,1)+1i*dcm(3,2)))>1e-6 A=-A; end if abs(A*B+0.5*(dcm(1,3)-1i*dcm(2,3)))+abs(A*B'-0.5*(dcm(3,1)+1i*dcm(3,2)))>1e-6 error('DCM does not pass self-consistency check on phases.'); end % Compute Wigner matrix Z=A*A'-B*B'; W=[ A^4 2*A^3*B sqrt(6)*A^2*B^2 2*A*B^3 B^4 -2*A^3*B' A^2*(2*Z-1) sqrt(6)*A*B*Z B^2*(2*Z+1) 2*A'*B^3 sqrt(6)*A^2*B'^2 -sqrt(6)*A*B'*Z 0.5*(3*Z^2-1) sqrt(6)*A'*B*Z sqrt(6)*A'^2*B^2 -2*A*B'^3 B'^2*(2*Z+1) -sqrt(6)*A'*B'*Z A'^2*(2*Z-1) 2*A'^3*B B'^4 -2*A'*B'^3 sqrt(6)*A'^2*B'^2 -2*A'^3*B' A'^4 ]; end % Consistency enforcement function grumble(dcm) if (~isnumeric(dcm))||(~isreal(dcm))||(~all(size(dcm)==[3 3])) error('DCM must be a real 3x3 matrix.'); end if norm(dcm'*dcm-eye(3))>1e-6 warning('DCM is not orthogonal to 1e-6 tolerance - conversion accuracy not guaranteed.'); end if norm(dcm'*dcm-eye(3))>1e-2 error('DCM is not orthogonal to 1e-2 tolerance, cannot proceed with conversion.'); end if abs(det(dcm)-1)>1e-6 warning('DCM determinant is not unit to 1e-6 tolerance - conversion accuracy not guaranteed.'); end if abs(det(dcm)-1)>1e-2 error('DCM determinant is not unit to 1e-2 tolerance, cannot proceed with conversion.'); end end % The hallmark of a second rater is resentment for another man's achievement. % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
shift_iso.m
.m
nmr-pred-master/spinach/kernel/utilities/shift_iso.m
2,064
utf_8
c8dc1127a718c64ce58873a334fb5db6
% Replaces the isotropic parts of interaction tensors with user-supplied values. % This is useful for correcting DFT calculations, where the anisotropy is usually % satisfactory, but the isotropic part often is not. Arguments: % % tensors - a cell array of interaction tensors as 3x3 matrices % % spin_numbers - a vector containing the numbers of spins in the tensors % array that should have the isotropic values replaced % % new_iso - a vector containing the new isotropic parts in the same % order as the spin numbers listed in spin_numbers % % [email protected] % [email protected] function tensors=shift_iso(tensors,spin_numbers,new_iso) % Check consistency grumble(tensors,spin_numbers,new_iso) % Loop over the tensors for n=1:numel(spin_numbers) % Pull out the anisotropy [~,rank1,rank2]=mat2sphten(tensors{spin_numbers(n)}); % Rebuild with the new isotropic part tensors{spin_numbers(n)}=sphten2mat([],rank1,rank2)+new_iso(n)*eye(3); end end % Consistency enforcement function grumble(tensors,spin_numbers,new_iso) if (~iscell(tensors))||any(any(~cellfun(@isreal,tensors)))||... any(any(~cellfun(@(x)all(size(x)==[3 3]|isempty(x)),tensors))) error('tensors parameter must be a cell array of real 3x3 matrices.'); end if (~isnumeric(spin_numbers))||any(mod(spin_numbers,1)~=0)||any(spin_numbers<1) error('spin_numbers must be a vector of positive integers.'); end if any(spin_numbers>numel(tensors)) error('an index in spin_numbers is greater than the number of tensors supplied.'); end if (~isnumeric(new_iso))||(~isreal(new_iso)) error('new_iso must be a vector of real numbers.'); end if numel(spin_numbers)~=numel(new_iso) error('the number of elements in spin_number and new_iso parameters must be the same.'); end end % There once was an X from place B, % Who satisfied predicate P, % Then X did thing A, % In a specified way, % Resulting in circumstance C.
github
tsajed/nmr-pred-master
euler2dcm.m
.m
nmr-pred-master/spinach/kernel/utilities/euler2dcm.m
1,944
utf_8
21c30b60b250c5185033c7d66f347e0e
% Converts Euler angles to a direction cosine matrix. Syntax: % % R=euler2dcm(alpha,beta,gamma) % % OR % % R=euler2dcm([alpha beta gamma]) % % where alpha, beta and gamma are Euler angles in radians. The resulting % rotation matrix is to be used as follows: % % v=R*v (for 3x1 vectors) % A=R*A*R' (for 3x3 interaction tensors) % % [email protected] function R=euler2dcm(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); % Build the individual rotation matrices, % as per Brink & Satchler, Fig 1a R_alpha=[cos(alp) -sin(alp) 0; % (CCW around Z) sin(alp) cos(alp) 0; 0 0 1]; R_beta= [cos(bet) 0 sin(bet); % (CCW around Y) 0 1 0; -sin(bet) 0 cos(bet)]; R_gamma=[cos(gam) -sin(gam) 0; % (CCW around Z) sin(gam) cos(gam) 0; 0 0 1]; % Build the direction cosine matrix R=R_alpha*R_beta*R_gamma; 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 % I am so hungry for any sight of anyone who's able to do whatever it is % he's doing! % % Ayn Rand, "Atlas Shrugged"
github
tsajed/nmr-pred-master
xyz2hfc.m
.m
nmr-pred-master/spinach/kernel/utilities/xyz2hfc.m
1,053
utf_8
daec3780923b56e7e4a7b0b517b5f953
% Converts point electron and nuclear coordinates (Angstroms) % into a hyperfine interaction tensor in Hz. Syntax: % % A=xyz2hfc(e_xyz,n_xyz,isotope) % % [email protected] function A=xyz2hfc(e_xyz,n_xyz,isotope) % Fundamental constants hbar=1.054571800e-34; mu0=4*pi*1e-7; % Get magnetogyric ratios gamma_e=spin('E'); gamma_n=spin(isotope); % Get the distance distance=norm(e_xyz-n_xyz); % Get the ort ort=(e_xyz-n_xyz)/distance; % Compute the dipolar interaction prefactor D=gamma_e*gamma_n*hbar*mu0/(4*pi*(distance*1e-10)^3); % Compute the dipolar coupling matrix A=D*[1-3*ort(1)*ort(1) -3*ort(1)*ort(2) -3*ort(1)*ort(3); -3*ort(2)*ort(1) 1-3*ort(2)*ort(2) -3*ort(2)*ort(3); -3*ort(3)*ort(1) -3*ort(3)*ort(2) 1-3*ort(3)*ort(3)]; end % "English people as a whole have a rooted distrust of total % abstainers as politicians." % % The Very Rev'd H. Hensley Henson, then Dean of Durham, % in a letter to the Times, 4th January 1916.
github
tsajed/nmr-pred-master
md5_hash.m
.m
nmr-pred-master/spinach/kernel/utilities/md5_hash.m
1,231
utf_8
46fcfac57c36c60c3db6fabf66b5310d
% Computes the MD5 hash of any Matlab object and returns it as a % hex string. Identical sparse and full matrices return different % hashes. Syntax: % % hashstr=md5_hash(A) % % [email protected] function hashstr=md5_hash(A) % Create the engine engine=java.security.MessageDigest.getInstance('MD5'); % Feed the object to the engine engine.update(getByteStreamFromArray(A)); % Compute the hash hashstr=typecast(engine.digest,'uint8'); % Convert into a hex string hashstr=sprintf('%.2x',double(hashstr)); end % The basic principle of the new education is to be that dunces and % idlers must not be made to feel inferior to intelligent and indus- % trious pupils. That would be "undemocratic". These differences be- % tween pupils - for there are obviously and nakedly individual dif- % ferences - must be disguised. This can be done at various levels. % At universities, examinations must be framed so that nearly all the % students get good marks. [...] But all the time there must be no % faintest hint that they are inferior to the children who are at % work. Whatever nonsense they are engaged in must have - I believe % the English already use the phrase - "parity of esteem". % % C.S. Lewis
github
tsajed/nmr-pred-master
chirp_pulse_af.m
.m
nmr-pred-master/spinach/kernel/pulses/chirp_pulse_af.m
1,778
utf_8
33d42445d2f2960931dc9e2a4e18de68
% Chirp pulse waveform with a sine bell amplitude envelope in amplitude- % frequency coordinates. Syntax: % % [ampls,freqs]=chirp_pulse_af(npoints,duration,bandwidth,smfactor) % % with the following parameters: % % npoints - number of discretization points in % the waveform % % duration - pulse duration, seconds % % bandwidth - chirp sweep bandwidth around % zero frequency, Hz % % smfactor - sine power to be used for the % amplitude envelope % % [email protected] % [email protected] function [ampls,freqs]=chirp_pulse_af(npoints,duration,bandwidth,smfactor) % Compute amplitudes ampls=1-abs(sin(linspace(-pi/2,pi/2,npoints)).^smfactor); % Compute frequencies freqs=linspace(-bandwidth/2,bandwidth/2,npoints); % Calibrate amplitudes ampls=2*pi*sqrt(bandwidth/duration)*ampls; end % My suggestion was quite simple: put that needed code number in a % little capsule, and then implant that capsule right next to the % heart of a volunteer. The volunteer would carry with him a big, % heavy butcher knife as he accompanies the President. If ever the % President wanted to fire nuclear weapons, the only way he could % do so would be for him first, with his own hands, to kill one hu- % man being. The President says, "George, I'm sorry but tens of mil- % lions must die." He has to look at someone and realize what death % is - what an innocent death is. Blood on the White House carpet. % Its reality brought home. % % When I suggested this to friends in the Pentagon they said, "My % God, that's terrible. Having to kill someone would distort the % President's judgment. He might never push the button." % % Roger Fisher