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
|
shaped_pulse_xy.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/shaped_pulse_xy.m
| 2,308 |
utf_8
|
1260d6e1278ac01983b4146f0ad12f8c
|
% Shaped pulse function using Cartesian coordinates.
%
% <http://spindynamics.org/wiki/index.php?title=Shaped_pulse_xy.m>
function [rho,P]=shaped_pulse_xy(spin_system,drift,controls,amplitudes,time_grid,rho)
% Check consistency
grumble(drift,controls,amplitudes,time_grid,rho);
% Decide the methods
switch nargout
case 1
% Run Krylov propagation
for n=1:numel(time_grid)
% Generate the evolution step operator
slice_operator=drift;
for k=1:numel(controls)
slice_operator=slice_operator+amplitudes{k}(n)*controls{k};
end
% Apply the evolution slice
rho=step(spin_system,slice_operator,rho,time_grid(n));
end
case 2
% Get the propagator going
P=speye(size(drift));
% Compute the pulse propagator
parfor n=1:numel(time_grid)
% Generate the evolution step operator
slice_operator=drift;
for k=1:numel(controls)
slice_operator=slice_operator+amplitudes{k}(n)*controls{k}; %#ok<PFBNS>
end
% Apply the evolution slice
P=propagator(spin_system,slice_operator,time_grid(n))*P;
end
% Apply pulse propagator
rho=P*rho;
end
end
% Consistency enforcement
function grumble(drift,controls,amplitudes,time_grid,rho) %#ok<INUSD>
% to be written
end
% When IK proposed the fibre etching technique featured in the 2004
% JMR paper (http://dx.doi.org/10.1016/j.jmr.2004.08.017), he could
% see terror in his supervisors's eyes - Peter Hore reasonably tho-
% ught that the notoriously eccentric Russian student could not pos-
% sibly be trusted with boiling hydrofluoric acid in a high-power
% laser lab. The Chemistry Department safety officer held a similar
% view. It is not entirely clear how IK got hold of several millili-
% ters of concentrated HF and a heat gun on a Saturday night in the
% PTCL Teaching Lab, but the photographs of the resulting fibre tip
% were left on Peter's table on Monday. The paper was accepted by
% JMR without revisions.
|
github
|
tsajed/nmr-pred-master
|
pulse_shape.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/pulse_shape.m
| 1,558 |
utf_8
|
597f1551090d023b60c69f0c8be1440f
|
% Shaped pulse waveforms. Add your own if necessary. Syntax:
%
% waveform=pulse_shape(pulse_name,npoints)
%
% Parameters:
%
% pulse_name - the name of the pulse
%
% npoints - number of points in the pulse
%
% [email protected]
function waveform=pulse_shape(pulse_name,npoints)
% Check consistency
grumble(pulse_name,npoints);
% Choose the shape
switch pulse_name
case 'gaussian'
time_grid=linspace(-2,2,npoints);
waveform=normpdf(time_grid);
case 'rectangular'
waveform=ones(1,npoints);
otherwise
% Complain and bomb out
error('unknown pulse name.');
end
end
% Consistency enforcement
function grumble(pulse_name,npoints)
if ~ischar(pulse_name)
error('pulse_name parameter must be a character string.');
end
if (numel(npoints)~=1)||(~isnumeric(npoints))||(~isreal(npoints))||...
(npoints<1)||(mod(npoints,1)~=0)
error('npoints parameter must be a positive real integer greater than 1.');
end
end
% Let me start with a parable. It concerns an Eastern European country
% whose parliament was considering a total smoking ban. In response, a
% consortium of tobacco companies demonstrated that the savings made in
% healthcare as a result of the decline in smoking-related diseases were
% chicken feed besides the reduced payout in pensions as the result of
% premature death - not to mention the fiscal increment from the habit.
%
% Stewart Dakers
|
github
|
tsajed/nmr-pred-master
|
shaped_pulse_af.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/shaped_pulse_af.m
| 3,631 |
utf_8
|
b96a135717d2dcd2e93ff925404317ba
|
% Shaped pulse in amplitude-frequency coordinates using Fokker-Planck
% formalism. Syntax:
%
% rho=shaped_pulse_af(spin_system,L0,Lx,Ly,rho,rf_frq_list,...
% rf_amp_list,rf_dur_list,rf_phi,max_rank,method)
%
% Parameters:
%
% L0 - drift Liouvillian that continues
% running in the background
%
% Lx - X projection of the RF operator
%
% Ly - Y projection of the RF operator
%
% rho - initial condition
%
% rf_frq_list - a vector of RF frequencies at each
% time slice, Hz
%
% rf_amp_list - a vector of RF amplitudes at each
% time slice, Hz
%
% rf_dur_list - a vector of time slice durations,
% in seconds
%
% rf_phi - RF phase at time zero
%
% max_rank - maximum rank of the Fokker-Planck
% theory
%
% method - propagation method, 'expv' for Krylov
% propagation, 'expm' for exponential
% propagation, 'evolution' for Spinach
% evolution function
%
% [email protected]
function rho=shaped_pulse_af(spin_system,L0,Lx,Ly,rho,rf_frq_list,rf_amp_list,rf_dur_list,rf_phi,max_rank,method)
% Set the defaults
if ~exist('method','var'), method='expv'; end
% Get problem dimensions
spc_dim=2*max_rank+1; spn_dim=size(L0,1); stk_dim=size(rho,2);
report(spin_system,['lab space problem dimension ' num2str(spc_dim)]);
report(spin_system,['spin space problem dimension ' num2str(spn_dim)]);
report(spin_system,['state vector stack size ' num2str(stk_dim)]);
report(spin_system,['Fokker-Planck problem dimension ' num2str(spc_dim*spn_dim)]);
% Compute RF angles and Fourier derivative operator
[rotor_angles,d_dphi]=fourdif(spc_dim,1);
% Add the phase
rotor_angles=rotor_angles+rf_phi;
% Build the background Liouvillian
F0=kron(speye(spc_dim),L0);
% Build the RF operator
F1=cell(spc_dim);
for n=1:spc_dim
for k=1:spc_dim
F1{n,k}=spalloc(spn_dim,spn_dim,0);
end
F1{n,n}=cos(rotor_angles(n))*Lx+sin(rotor_angles(n))*Ly;
end
F1=clean_up(spin_system,cell2mat(F1),spin_system.tols.liouv_zero);
% Build the phase increment operator
M=kron(d_dphi,speye(size(L0)));
% Project the state
P=spalloc(spc_dim,1,1); P(1)=1; rho=kron(P,rho);
% Run the pulse
switch method
case 'expv'
% Use Krylov propagation
for n=1:numel(rf_frq_list)
report(spin_system,['Krylov propagation step ' num2str(n) ' of ' num2str(numel(rf_frq_list)) '...']);
rho=step(spin_system,F0+2*pi*rf_amp_list(n)*F1+2i*pi*rf_frq_list(n)*M,rho,rf_dur_list(n));
end
case 'expm'
% Use exponential propagation
for n=1:numel(rf_frq_list)
rho=propagator(spin_system,F0+2*pi*rf_amp_list(n)*F1+2i*pi*rf_frq_list(n)*M,rf_dur_list(n))*rho;
end
case 'evolution'
% Use the evolution function
for n=1:numel(rf_frq_list)
rho=evolution(spin_system,F0+2*pi*rf_amp_list(n)*F1+2i*pi*rf_frq_list(n)*M,[],rho,rf_dur_list(n),1,'final');
end
otherwise
% Complain and bomb out
error('unknown propagation method.');
end
% Fold back the state
rho=squeeze(sum(reshape(full(rho),[spn_dim spc_dim stk_dim]),2));
end
% A man gazing at the stars is at the mercy
% of the puddles in the road.
%
% Alexander Smith
|
github
|
tsajed/nmr-pred-master
|
read_wave.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/read_wave.m
| 1,720 |
utf_8
|
c5d0a2ff222049d09da608139ea7ec40
|
% Reads wavegauss.pk files. Arguments:
%
% filename - a string containing the name of the file
%
% npoints - waveform upsampling or downsampling is
% performed to this number of points
%
% Note: phases are returned in degrees, amplitudes in percent.
%
% [email protected]
function [amplitudes,phases]=read_wave(filename,npoints)
% Read the file
wavefile=fopen(filename,'r');
waveform=textscan(wavefile,'%f, %f','CommentStyle','##');
fclose(wavefile);
% Build complex waveform
waveform=waveform{1}.*exp(1i*pi*waveform{2}/180);
% Resample the waveform
waveform=interp1(linspace(0,1,numel(waveform)),real(waveform),linspace(0,1,npoints),'pchip')+...
1i*interp1(linspace(0,1,numel(waveform)),imag(waveform),linspace(0,1,npoints),'pchip');
% Convert back into amplitudes and phases
amplitudes=abs(waveform);
phases=90-(180/pi)*atan2(real(waveform),imag(waveform));
end
% I condemn Christianity... It is, to me, the greatest of all imaginable
% corruptions. [...] To breed in humans a self-contradiction, an art of
% self-pollution, a will to lie at any price, an aversion and contempt for
% all good and honest instincts! [...] The beyond as the will to deny all
% reality; the cross as the distinguishing mark of the most subterranean
% conspiracy ever heard of -- against health, beauty, well-being, intel-
% lect... against life itself.
%
% I call Christianity the one great curse, the one great intrinsic depra-
% vity, the one great instinct of revenge, for which no means are veno-
% mous enough, or secret, subterranean and small enough - I call it the
% one immortal blemish upon the human race...
%
% Friedrich Nietzsche
|
github
|
tsajed/nmr-pred-master
|
triwave.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/triwave.m
| 1,156 |
utf_8
|
4cf472acf9cc9f3945fdfa385e52dd5d
|
% Returns a triangular waveform. Syntax:
%
% waveform=triwave(amplitude,frequency,time_grid)
%
% Arguments:
%
% amplitude - amplitude at the tooth top
%
% frequency - waveform frequency, Hz
%
% time_grid - vector of time points, seconds
%
% [email protected]
function waveform=triwave(amplitude,frequency,time_grid)
% Check consistency
grumble(amplitude,frequency,time_grid);
% Compute the waveform
waveform=abs(sawtooth(amplitude,frequency,time_grid));
end
% Consistency enforcement
function grumble(amplitude,frequency,time_grid)
if (numel(amplitude)~=1)||(~isnumeric(amplitude))||(~isreal(amplitude))
error('amplitude parameter must be a real number.');
end
if (numel(frequency)~=1)||(~isnumeric(frequency))||(~isreal(frequency))
error('frequency parameter must be a real number.');
end
if (~isnumeric(time_grid))||(~isreal(time_grid))
error('time_grid parameter must be a vector of real numbers.');
end
end
% I am here to determine whether what you had just done is simple
% incompetence or deliberate sabotage.
%
% Joseph Stalin, to his generals, in May 1941.
|
github
|
tsajed/nmr-pred-master
|
grad_sandw.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/grad_sandw.m
| 3,702 |
utf_8
|
05346aded1d5c4a56f9d56688ceb36b1
|
% Computes the effect of a gradient sandwich on the sample average density
% matrix using Edwards formalism. It is assumed that the effect of diffusi-
% on is negligible, that the gradients are linear, and that they are anti-
% symmetric about the middle of the sample. Syntax:
%
% rho=grad_sandw(spin_system,L,rho,P,g_amps,s_len,g_durs,s_facs)
%
% Arguments:
%
% rho - spin system state vector
%
% L - system Liouvillian
%
% P - total propagator for all events happening
% between the two gradients
%
% g_amps - row vector containing the amplitudes of
% the two gradients, Gauss/cm
%
% s_len - sample length, cm
%
% g_durs - row vector containing the durations of
% the two gradients, seconds
%
% s_facs - shape factors of the two gradients, use
% [1 1] for square gradient pulses
%
% Note: the function integrates over sample coordinates - subsequent gra-
% dient pulses would not refocus the magnetization that it has left
% defocused. More information on the subject is available in Luke's
% paper (http://dx.doi.org/10.1016/j.jmr.2014.01.011).
%
% [email protected]
% [email protected]
function rho=grad_sandw(spin_system,L,rho,P,g_amps,s_len,g_durs,s_facs)
% Check consistency
grumble(spin_system,L,rho,P,g_amps,s_len,g_durs,s_facs);
% Inform the user
report(spin_system,'computing the effect of a gradient sandwich...');
% Get effective gradient operators
R=carrier(spin_system,'all')/spin_system.inter.magnet;
G1=1e-4*s_facs(1)*g_amps(1)*s_len*g_durs(1)*R;
G2=1e-4*s_facs(2)*g_amps(2)*s_len*g_durs(2)*R;
% Check approximation applicability
if significant(L*G1-G1*L,1e-6)||significant(L*G2-G2*L,1e-6)
error('the Liouvillian does not commute with gradient operators.');
end
% Run background Liouvillian evolution during first gradient
rho=evolution(spin_system,L,[],rho,g_durs(1),1,'final');
% Account for rescaling of sample integral into [0,1]
rho=evolution(spin_system,G1,[],rho,-1/2,1,'final');
% Evolution under the gradient pulses and P
aux_mat=[-G2, 1i*P; 0*G1, G1]; aux_rho=[0*rho; rho];
aux_rho=evolution(spin_system,aux_mat,[],aux_rho,1,1,'final');
% Map back into the state vector space
rho=aux_rho(1:end/2,:);
% Undo the evolution overshoot
rho=evolution(spin_system,G2,[],rho,1/2,1,'final');
% Run background Liouvillian evolution during second gradient
rho=evolution(spin_system,L,[],rho,g_durs(2),1,'final');
end
% Consistency enforcement
function grumble(spin_system,L,rho,P,g_amps,s_len,g_durs,s_facs)
if ~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})
error('this function is only applicable in Liouville space.');
end
if (~isnumeric(L))||(~isnumeric(rho))||(~isnumeric(P))||(~isnumeric(g_amps))||...
(~isnumeric(s_len))||(~isnumeric(g_durs))||(~isnumeric(s_facs))
error('all arguments apart from spin_system must be numeric.');
end
if (~isreal(g_amps))||(numel(g_amps)~=2)
error('g_amps vector must have two real elements.');
end
if (~isreal(s_len))||(~isscalar(s_len))||(s_len<=0)
error('s_len must be a positive real number.');
end
if (~isreal(g_durs))||(numel(g_durs)~=2)||(any(g_durs<0))
error('g_durs vector must have two real non-negative elements.');
end
if (~isreal(s_facs))||(numel(s_facs)~=2)||(any(s_facs<0))
error('s_facs vector must have two real non-negative elements.');
end
end
% Morality is simply the attitude we adopt towards
% people we personally dislike.
%
% Oscar Wilde
|
github
|
tsajed/nmr-pred-master
|
cartesian2polar.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/cartesian2polar.m
| 5,606 |
utf_8
|
cd858484d46884e6e5f6e9124e021422
|
% Converts the [RF_x, RF_y] representation of a pulse waveform and the
% derivatives of any function with respect to those RF values into the
% [RF_amplitude, RF_phase] representation and the derivatives of the
% function with respect to the amplitudes and phases. Syntax:
%
% [A,phi,df_dA,df_dphi]=cartesian2polar(x,y,df_dx,df_dy)
%
% Parameters:
%
% x - vector of waveform amplitudes along X
%
% y - vector of waveform amplitudes along Y
%
% df_dx - optional vector of derivatives of a scalar function
% with respect to the waveform amplitudes along X
%
% df_dy - optional vector of derivatives of a scalar function
% with respect to the waveform amplitudes along Y
%
% d2f_dx2 - optional matrix of second derivatives of a scalar function
% with respect to the waveform amplitudes along X
%
% d2f_dxdy- optional matrix of second derivatives of a scalar function
% with respect to the waveform amplitudes along X and Y
%
% d2f_dy2 - optional matrix of second derivatives of a scalar function
% with respect to the waveform amplitudes along Y
%
% Outputs:
%
% A - vector of waveform amplitudes
%
% phi - vector of waveform phases
%
% df_dA - vector of derivatives of the function with respect
% to the waveform amplitudes.
%
% df_dphi - vector of derivatives of the function with respect
% to the waveform phases.
%
% d2f_dA2 - matrix of second derivatives of the function with respect
% to the waveform amplitudes.
%
% d2f_dAdphi- matrix of second derivatives of the function with respect
% to the waveform amplitudes and phases.
%
% d2f_dphi2- matrix of second derivatives of the function with respect
% to the waveform phases.
%
% [email protected]
function [A,phi,df_dA,df_dphi,d2f_dA2,d2f_dAdphi,d2f_dphi2]=cartesian2polar(x,y,df_dx,df_dy,d2f_dx2,d2f_dxdy,d2f_dy2)
% Check consistency
if nargin==2
grumble(x,y);
elseif nargin==4
grumble(x,y,df_dx,df_dy);
elseif nargin==7
grumble(x,y,df_dx,df_dy,d2f_dx2,d2f_dxdy,d2f_dy2);
else
error('incorrect number of arguments.');
end
% Transform coordinates
A=sqrt(x.^2+y.^2); phi=atan2(y,x);
% Transform derivatives
if (nargin>2)&&(nargout>2)
df_dA=df_dx.*cos(phi)+df_dy.*sin(phi);
df_dphi=-df_dx.*y+df_dy.*x;
end
% Transform second derivatives
if (nargin>4)&&(nargout>4)
d2f_dphi2= -A.*(cos(phi).*df_dx+sin(phi).*df_dy)+...
A.*A.*(cos(phi).*cos(phi).*d2f_dy2-...
2*cos(phi).*sin(phi).*d2f_dxdy+...
sin(phi).*sin(phi).*d2f_dx2);
d2f_dA2=cos(phi).*cos(phi).*d2f_dx2+...
2*cos(phi).*sin(phi).*d2f_dxdy+...
sin(phi).*sin(phi).*d2f_dy2;
d2f_dAdphi=cos(phi).*df_dy-sin(phi).*df_dx+...
A.*cos(phi).*sin(phi).*d2f_dy2+...
A.*cos(phi).*cos(phi).*d2f_dxdy-...
A.*sin(phi).*sin(phi).*d2f_dxdy-...
A.*cos(phi).*sin(phi).*d2f_dx2;
end
end
% Consistency enforcement
function grumble(x,y,df_dx,df_dy,d2f_dx2,d2f_dxdy,d2f_dy2)
if nargin==2
if (~isnumeric(x))||(~isreal(x))
error('x parameter must be a vector of real numbers.');
end
if (~isnumeric(y))||(~isreal(y))
error('y parameter must be a vector of real numbers.');
end
if ~all(size(x)==size(y))
error('x and y vectors must have the same dimension.');
end
elseif nargin==4
if (~isnumeric(x))||(~isreal(x))
error('x parameter must be a vector of real numbers.');
end
if (~isnumeric(y))||(~isreal(y))
error('y parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dx))||(~isreal(df_dx))
error('df_dx parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dy))||(~isreal(df_dy))
error('df_dy parameter must be a vector of real numbers.');
end
if (~all(size(x)==size(y)))||(~all(size(y)==size(df_dx)))||(~all(size(df_dx)==size(df_dy)))
error('all input vectors must have the same dimension.');
end
elseif nargin==7
if (~isnumeric(x))||(~isreal(x))
error('x parameter must be a vector of real numbers.');
end
if (~isnumeric(y))||(~isreal(y))
error('y parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dx))||(~isreal(df_dx))
error('df_dx parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dy))||(~isreal(df_dy))
error('df_dy parameter must be a vector of real numbers.');
end
if (~isnumeric(d2f_dx2))||(~isreal(d2f_dx2))
error('d2f_dx2 parameter must be a matrix of real numbers.');
end
if (~isnumeric(d2f_dy2))||(~isreal(d2f_dy2))
error('d2f_dy2 parameter must be a matrix of real numbers.');
end
if (~isnumeric(d2f_dxdy))||(~isreal(d2f_dxdy))
error('ddf_dxdy parameter must be a matrix of real numbers.');
end
if (~all(size(x)==size(y)))||(~all(size(y)==size(df_dx)))||(~all(size(df_dx)==size(df_dy)))
error('all input vectors must have the same dimension.');
end
if (size(d2f_dx2,2)~=length(df_dx))||(size(d2f_dx2,1)~=size(d2f_dx2,2))||all(size(d2f_dx2)~=size(d2f_dy2))||all(size(d2f_dy2)~=size(d2f_dxdy))
error('all input matrices must have the same, square dimensions.');
end
end
end
% Beware of geeks bearing formulas.
%
% Warren Buffett
|
github
|
tsajed/nmr-pred-master
|
vg_pulse.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/vg_pulse.m
| 8,574 |
utf_8
|
74f26e90fda6513d7234e7db168e9bf5
|
% Veshtort-Griffin shaped pulses, generated from tables given in
%
% http://dx.doi.org/10.1002/cphc.200400018
%
% There are good reasons to believe (see Section 2.2 of the paper) that
% these are the best possible pulses within their design specifications
% and basis sets. Syntax:
%
% waveform=vg_pulse(pulse_name,npoints,duration)
%
% The input should specify a pulse duration (in seconds), which is used
% for normalization. The output is the amplitude of the waveform (there
% is no phase modulation), in radians per second, normalized to produce
% a 90-degree pulse. The following pulse names are available: E0A, E0B,
% E100A, E100B, E200A, E200D, E200F, E300C, E300F, E400B, E300A, E500A,
% E500B, E500C, E600A, E600C, E600F, E800A, E800B, E1000B.
%
% [email protected]
function waveform=vg_pulse(pulse_name,npoints,duration)
% Check consistency
grumble(pulse_name,npoints,duration);
% Stockpile names
names={'E0A' 'E0B' 'E100A' 'E100B' 'E200A' 'E200D' 'E200F' 'E300C' 'E300F' 'E400B'...
'E300A' 'E500A' 'E500B' 'E500C' 'E600A' 'E600C' 'E600F' 'E800A' 'E800B' 'E1000B'};
% Stockpile cosine coefficients
cosines=[...
-0.763 -0.763 -0.734 0.265 0.282 0.276 0.251 0.228 0.269 0.231 0.222 0.240 0.242 0.222 -0.739 0.239 0.249 0.238 0.235 0.254
-0.905 0.869 -0.650 0.974 -0.314 1.213 -0.931 0.592 1.126 0.933 -1.440 2.042 0.405 0.819 0.847 1.546 1.305 -1.816 -1.192 1.239
2.472 -0.171 2.395 -1.502 -0.534 -1.708 0.675 -1.261 -1.566 -1.183 0.164 -1.300 -0.333 0.080 -0.077 -1.609 -1.032 0.999 1.553 -1.345
-0.811 0.039 -1.132 -0.208 0.612 0.050 -0.018 0.475 -0.114 -0.242 2.366 -1.880 -0.332 -1.473 0.531 0.363 0.388 1.235 0.122 -0.753
-0.088 -0.005 0.058 0.498 -0.040 0.201 -0.086 0.027 0.229 0.256 -1.646 0.904 -0.257 0.248 -0.357 -0.774 -1.735 0.152 -0.716 0.797
0.001 0.003 0.036 0.158 0.084 0.109 0.070 -0.069 0.116 0.041 0.246 0.009 0.260 0.128 -0.140 0.078 1.087 -0.710 -0.336 0.610
0.107 0.001 0.053 -0.165 -0.157 -0.082 -0.026 0.008 -0.015 0.025 0.192 0.072 0.064 0.018 -0.183 0.208 -0.273 -0.002 0.525 -1.169
-0.054 0.001 -0.045 -0.079 0.002 -0.029 0.012 0.011 -0.058 -0.052 -0.211 0.032 -0.014 0.044 0.087 0.071 0.115 -0.120 -0.185 0.377
0.006 0.001 0.011 0.051 0.072 0.012 0.000 -0.005 0.006 0.002 0.118 -0.110 -0.014 -0.029 0.090 -0.057 -0.003 0.011 0.022 0.103
0.002 0.001 0.000 0.035 -0.021 0.009 0.001 -0.002 0.010 0.007 0.003 0.033 -0.034 -0.024 0.012 -0.009 -0.036 -0.032 0.008 -0.055
0.004 0.000 0.000 -0.015 -0.003 -0.005 0.002 0.001 0.003 0.001 -0.058 0.006 0.021 0.007 -0.029 -0.002 -0.017 0.083 -0.041 0.009
-0.002 0.000 0.000 -0.015 -0.005 -0.004 0.000 -0.001 -0.004 -0.001 0.043 -0.009 -0.004 0.001 -0.021 -0.021 0.026 0.064 0.045 -0.043
0.001 0.000 -0.001 0.003 0.006 0.000 0.001 0.000 -0.002 -0.002 -0.008 0.008 0.005 0.000 -0.003 0.015 -0.026 -0.051 -0.007 0.020
0.001 0.000 0.001 0.006 0.002 0.000 0.001 0.000 0.000 0.000 -0.008 -0.007 -0.003 0.000 0.008 -0.001 0.020 -0.038 -0.021 0.013
0.001 0.000 0.000 -0.001 -0.002 -0.001 0.000 0.000 0.000 0.000 0.010 -0.001 -0.002 -0.002 0.005 -0.001 -0.012 0.011 0.013 -0.008
0.000 0.000 0.000 -0.002 0.000 -0.001 0.000 0.000 0.000 0.000 -0.004 0.001 0.001 -0.001 -0.002 -0.002 0.001 0.008 0.001 -0.020
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 -0.002 -0.001 0.000 -0.003 0.000 0.000 0.000 -0.005 0.020
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.003 0.000 0.001 -0.001 -0.001 -0.002 -0.003 -0.001 0.003 -0.007
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 -0.001 -0.001 0.000 0.000 0.000 0.001 0.001 -0.002 -0.001
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 0.000 0.000 0.000 0.000 -0.001 -0.001 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.001 0.000 0.000 0.000 0.000 0.000 -0.001 -0.002 0.001 0.000];
% Stockpile sine coefficients
sines=[...
0.000 0.000 0.092 -2.104 1.459 -1.270 -1.273 -1.279 -0.788 -0.533 -0.772 -0.681 -3.105 -0.215 -0.360 0.249 -2.489 -0.238 -0.773 0.242
0.000 0.000 -0.729 -0.025 1.934 -0.244 0.913 0.828 -1.010 -1.288 -0.064 0.389 0.674 -1.555 -3.153 -1.861 0.874 -0.228 1.045 -1.607
0.000 0.000 0.564 0.795 -2.256 0.615 -0.312 0.029 0.875 1.006 0.427 -0.552 -1.212 0.357 0.210 -0.773 -0.847 -2.724 -0.918 -2.102
0.000 0.000 -0.057 0.222 0.189 0.106 0.106 -0.082 0.078 0.022 -0.269 0.177 1.609 0.525 1.867 1.583 0.610 0.724 -1.052 1.532
0.000 0.000 -0.032 -0.292 0.234 -0.125 -0.023 -0.038 -0.033 -0.010 0.284 0.313 -0.346 -0.034 -0.113 -0.285 0.255 1.886 1.391 -0.409
0.000 0.000 -0.063 -0.113 0.037 -0.056 -0.003 0.047 -0.102 -0.061 -0.144 -0.193 0.025 0.013 -0.168 0.121 -0.123 -0.316 -0.271 1.110
0.000 0.000 0.079 0.093 -0.025 0.036 0.009 -0.012 0.015 -0.007 -0.064 0.043 -0.017 -0.029 -0.081 -0.039 0.010 -0.305 -0.101 -0.359
0.000 0.000 -0.033 0.053 -0.063 0.017 -0.005 -0.002 0.024 0.026 0.110 -0.020 -0.085 -0.039 -0.091 -0.017 -0.003 -0.040 0.076 -0.091
0.000 0.000 0.004 -0.028 0.036 -0.006 0.003 0.003 0.001 -0.001 -0.047 -0.017 0.085 0.018 0.050 -0.068 -0.077 -0.020 -0.035 0.071
0.000 0.000 -0.001 -0.024 0.007 -0.006 -0.001 0.001 -0.007 -0.001 -0.008 0.035 -0.034 0.009 0.066 0.054 0.090 0.026 0.018 0.056
0.000 0.000 0.004 0.007 -0.010 0.002 0.000 0.000 -0.003 -0.002 0.028 -0.013 0.022 -0.002 -0.015 -0.005 -0.053 0.008 0.027 -0.102
0.000 0.000 -0.003 0.009 0.000 0.002 0.000 0.001 0.001 0.001 -0.024 -0.002 -0.012 0.000 -0.018 0.001 0.033 0.022 -0.042 0.025
0.000 0.000 0.001 -0.002 0.001 0.000 0.000 0.001 0.000 0.001 0.008 0.003 -0.001 -0.002 -0.003 0.001 -0.014 0.013 0.016 0.027
0.000 0.000 0.000 -0.004 0.001 0.000 0.000 0.000 -0.001 0.000 0.004 -0.003 0.002 -0.001 0.001 -0.002 0.002 -0.017 0.008 -0.010
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 0.000 -0.007 0.002 -0.002 0.000 0.004 -0.002 0.000 -0.008 -0.010 0.003
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.004 0.000 0.001 0.000 0.001 0.001 0.001 0.002 0.003 -0.005
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 -0.002 -0.001 -0.002 0.000 -0.002 0.002 0.001 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 0.000 0.000 -0.001 -0.001 -0.001 0.002 0.003 -0.002 0.004
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.001 0.000 -0.001 -0.001 0.000 0.000 -0.002 0.000 0.001 -0.002
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 -0.001 0.000 -0.001 -0.001 0.000 -0.001 0.001 -0.001 -0.001 -0.002];
% Parse the pulse name
pulse_number=find(strcmp(names,pulse_name));
if isempty(pulse_number), error('incorrect pulse name.'); end
% Preallocate the pulse
waveform=zeros(1,npoints);
% Build the time grid
time_grid=linspace(0,2*pi,npoints);
% Compute cosine terms
for k=0:20
waveform=waveform+cosines(k+1,pulse_number)*cos(k*time_grid);
end
% Compute sine terms
for k=1:20
waveform=waveform+sines(k,pulse_number)*sin(k*time_grid);
end
% Normalize the waveform
waveform=2*pi*waveform/duration;
end
% Consistency enforcement
function grumble(pulse_name,npoints,duration)
if ~ischar(pulse_name)
error('pulse_name parameter must be a character string.');
end
if (numel(npoints)~=1)||(~isnumeric(npoints))||(~isreal(npoints))||...
(npoints<1)||(mod(npoints,1)~=0)
error('npoints parameter must be a positive real integer greater than 1.');
end
if (numel(duration)~=1)||(~isnumeric(duration))||(~isreal(duration))||(duration<0)
error('duration parameter must be a positive real number.');
end
end
% It is not the works, but the belief which is here decisive and determines
% the order of rank -- to employ once more an old religious formula with a
% new and deeper meaning -- it is some fundamental certainty which a noble
% soul has about itself, something which is not to be sought, is not to be
% found, and perhaps, also, is not to be lost. The noble soul has reverence
% for itself.
%
% Friedrich Nietzsche,
% "Beyond Good and Evil"
|
github
|
tsajed/nmr-pred-master
|
chirp_pulse_xy.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/chirp_pulse_xy.m
| 1,328 |
utf_8
|
60a1699f404ce6434d4dec3a29937a8b
|
% Chirp pulse waveform with a sine bell amplitude envelope in Cartesian
% coordinates. Syntax:
%
% [Cx,Cy]=chirp_pulse_xy(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 [Cx,Cy]=chirp_pulse_xy(npoints,duration,bandwidth,smfactor)
% Compute timing grid
time_grid=linspace(-0.5,0.5,npoints);
% Compute amplitudes
amplitudes=1-abs(sin(pi*time_grid).^smfactor);
% Compute phases
phases=pi*duration*bandwidth*(time_grid.^2);
% Calibrate amplitudes
amplitudes=2*pi*sqrt(bandwidth/duration)*amplitudes;
% Transform into Cartesian representation
[Cx,Cy]=polar2cartesian(amplitudes,phases);
end
% "No one realized that the pumps that delivered fuel to the
% emergency generators were electric."
%
% Angel Feliciano, representative of Verizon
% explaining why Verizon's backup power failed
% during the August 13, 2003 blackout, causing
% disruption to the 911 service.
|
github
|
tsajed/nmr-pred-master
|
polar2cartesian.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/polar2cartesian.m
| 5,677 |
utf_8
|
6bd36555a087883533cbbe7263d035e3
|
% Converts [RF_amplitude, RF_phase] representation of a pulse waveform and
% the derivatives of any function with respect to those amplitudes and pha-
% ses into the [RF_x, RF_y] representation and the derivatives of the func-
% tion with respect to those X and Y RF values. Syntax:
%
% [x,y,df_dx,df_dy]=polar2cartesian(A,phi,df_dA,df_dphi)
%
% Parameters:
%
% A - vector of waveform amplitudes
%
% phi - vector of waveform phases
%
% df_dA - optional vector of derivatives of some scalar function
% with respect to the waveform amplitudes.
%
% df_dphi - optional vector of derivatives of some scalar function
% with respect to the waveform phases.
%
% d2f_dA2 - matrix of second derivatives of the function with respect
% to the waveform amplitudes.
%
% d2f_dAdphi- matrix of second derivatives of the function with respect
% to the waveform amplitudes and phases.
%
% d2f_dphi2- matrix of second derivatives of the function with respect
% to the waveform phases.
%
% Outputs:
%
% x - vector of waveform amplitudes along X
%
% y - vector of waveform amplitudes along Y
%
% df_dx - vector of derivatives of the function with respect to
% the waveform amplitudes along X
%
% df_dy - vector of derivatives of the function with respect to
% the waveform amplitudes along Y
%
% d2f_dx2 - optional matrix of second derivatives of a scalar function
% with respect to the waveform amplitudes along X
%
% d2f_dxdy- optional matrix of second derivatives of a scalar function
% with respect to the waveform amplitudes along X and Y
%
% d2f_dy2 - optional matrix of second derivatives of a scalar function
% with respect to the waveform amplitudes along Y
%
% [email protected]
function [x,y,df_dx,df_dy,d2f_dx2,d2f_dxdy,d2f_dy2]=polar2cartesian(A,phi,df_dA,df_dphi,d2f_dA2,d2f_dAdphi,d2f_dphi2)
% Check consistency
if nargin==2
grumble(A,phi);
elseif nargin==4
grumble(A,phi,df_dA,df_dphi);
elseif nargin==7
grumble(A,phi,df_dA,df_dphi,d2f_dA2,d2f_dAdphi,d2f_dphi2);
else
error('incorrect number of arguments.');
end
% Transform coordinates
x=A.*cos(phi); y=A.*sin(phi);
% Transform derivatives
if (nargin>2)&&(nargout>2)
df_dx=df_dA.*cos(phi)-df_dphi.*sin(phi)./A;
df_dy=df_dA.*sin(phi)+df_dphi.*cos(phi)./A;
end
% Transform second derivatives
if (nargin>4)&&(nargout>4)
A4=A.^4; A3=A.^3; A2=A.^2;
d2f_dx2=+2*x.*y.*df_dphi./A4+y.*y.*d2f_dphi2./A4+df_dA./A-x.*x.*df_dA./A3-2*x.*y.*d2f_dAdphi./A3+x.*x.*d2f_dA2./A2;
d2f_dy2=-2*x.*y.*df_dphi./A4+x.*x.*d2f_dphi2./A4+df_dA./A-y.*y.*df_dA./A3+2*x.*y.*d2f_dAdphi./A3+y.*y.*d2f_dA2./A2;
d2f_dxdy=-df_dphi./A2+2*y.*y.*df_dphi./A4-x.*y.*d2f_dphi2./A4-x.*y.*df_dA./A3+x.*x.*d2f_dAdphi./A3-y.*y.*d2f_dAdphi./A3+x.*y.*d2f_dA2./A2;
end
end
% Consistency enforcement
function grumble(A,phi,df_dA,df_dphi,d2f_dA2,d2f_dAdphi,d2f_dphi2)
if nargin==2
if (~isnumeric(A))||(~isreal(A))||(~all(A>=0))
error('amplitude parameter must be a vector of non-negative real numbers.');
end
if (~isnumeric(phi))||(~isreal(phi))
error('phase parameter must be a vector of real numbers.');
end
if ~all(size(A)==size(phi))
error('amplitude and phase vectors must have the same dimension.');
end
elseif nargin==4
if (~isnumeric(A))||(~isreal(A))||(~all(A>=0))
error('amplitude parameter must be a vector of non-negative real numbers.');
end
if (~isnumeric(phi))||(~isreal(phi))
error('phase parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dA))||(~isreal(df_dA))
error('df_dA parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dphi))||(~isreal(df_dphi))
error('df_dphi parameter must be a vector of real numbers.');
end
if (~all(size(A)==size(phi)))||(~all(size(phi)==size(df_dA)))||(~all(size(df_dA)==size(df_dphi)))
error('all input vectors must have the same dimension.');
end
elseif nargin==7
if (~isnumeric(A))||(~isreal(A))||(~all(A>=0))
error('amplitude parameter must be a vector of non-negative real numbers.');
end
if (~isnumeric(phi))||(~isreal(phi))
error('phase parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dA))||(~isreal(df_dA))
error('df_dA parameter must be a vector of real numbers.');
end
if (~isnumeric(df_dphi))||(~isreal(df_dphi))
error('df_dphi parameter must be a vector of real numbers.');
end
if (~all(size(A)==size(phi)))||(~all(size(phi)==size(df_dA)))||(~all(size(df_dA)==size(df_dphi)))
error('all input vectors must have the same dimension.');
end
if (~isnumeric(d2f_dA2))||(~isreal(d2f_dA2))
error('d2f_dA2 parameter must be a matrix of real numbers.');
end
if (~isnumeric(d2f_dphi2))||(~isreal(d2f_dphi2))
error('d2f_dphi2 parameter must be a matrix of real numbers.');
end
if (~isnumeric(d2f_dAdphi))||(~isreal(d2f_dAdphi))
error('ddf_dAdphi parameter must be a matrix of real numbers.');
end
if (size(d2f_dA2,2)~=length(df_dA))||(size(d2f_dA2,1)~=size(d2f_dA2,2))||all(size(d2f_dA2)~=size(d2f_dphi2))||all(size(d2f_dphi2)~=size(d2f_dAdphi))
error('all input matrices must have the same, square dimensions.');
end
end
end
% A public opinion poll is no substitute for thought.
%
% Warren Buffett
|
github
|
tsajed/nmr-pred-master
|
grad_pulse.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/grad_pulse.m
| 4,237 |
utf_8
|
c183d457f49f7121f8d525daf67e7432
|
% Computes the effect of a gradient pulse on the sample average density
% matrix using Edwards formalism. It is assumed that the effect of dif-
% fusion is negligible, that the gradient is linear, and that it is an-
% tisymmetric about the middle of the sample. Syntax:
%
% rho=grad_pulse(spin_system,rho,g_amp,s_len,g_dur,s_fac)
%
% Arguments:
%
% rho - spin system state vector
%
% L - system Liouvillian
%
% g_amp - gradient amplitude, Gauss/cm
%
% s_len - sample length, cm
%
% g_dur - gradient pulse duration, seconds
%
% s_fac - gradient shape factor, use 1 for
% square gradient pulses
%
% Note: the function integrates over sample coordinates - subsequent gra-
% dient pulses would not refocus the magnetization that it has de-
% focused. To simulate a gradient sandwich, use grad_sandw.m func-
% tion. More information on the subject is available in Luke's pa-
% per (http://dx.doi.org/10.1016/j.jmr.2014.01.011).
%
% [email protected]
% [email protected]
function rho=grad_pulse(spin_system,L,rho,g_amp,s_len,g_dur,s_fac)
% Check consistency
grumble(spin_system,L,rho,g_amp,s_len,g_dur,s_fac)
% Inform the user
report(spin_system,'computing the effect of a gradient pulse...');
% Get effective gradient operator
G=1e-4*s_fac*g_amp*s_len*g_dur*carrier(spin_system,'all')/spin_system.inter.magnet;
% Check approximation applicability
if significant(L*G-G*L,1e-6)
error('the Liouvillian does not commute with the gradient operator.');
end
% Run background Liouvillian evolution
rho=evolution(spin_system,L,[],rho,g_dur,1,'final');
% Account for rescaling of sample integral into [0,1]
rho=evolution(spin_system,G,[],rho,-1/2,1,'final');
% Compute sample integral using auxiliary matrix method
aux_mat=[0*G, 1i*speye(size(G)); 0*G, G]; aux_rho=[0*rho; rho];
aux_rho=evolution(spin_system,aux_mat,[],aux_rho,1,1,'final');
% Map back into the state vector space
rho=aux_rho(1:end/2,:);
% Inform the user
report(spin_system,'gradient propagation done.')
end
% Consistency enforcement
function grumble(spin_system,L,rho,g_amp,s_len,g_dur,s_fac)
if ~ismember(spin_system.bas.formalism,{'sphten-liouv','zeeman-liouv'})
error('this function is only applicable in Liouville space.');
end
if (~isnumeric(L))||(~isnumeric(rho))||(~isnumeric(g_amp))||...
(~isnumeric(s_len))||(~isnumeric(g_dur))||(~isnumeric(s_fac))
error('all arguments apart from spin_system must be numeric.');
end
if (~isreal(g_amp))||(~isscalar(g_amp))
error('g_amp must be a real scalar.');
end
if (~isreal(s_len))||(~isscalar(s_len))||(s_len<=0)
error('s_len must be a positive real number.');
end
if (~isreal(g_dur))||(~isscalar(g_dur))||(g_dur<0)
error('g_dur must be a real non-negative scalar.');
end
if (~isreal(s_fac))||(~isscalar(s_fac))||(s_fac<0)
error('s_fac must be a real non-negative scalar.');
end
end
% I cannot understand why we idle discussing religion. If we are honest - and scientists
% have to be - we must admit that religion is a jumble of false assertions, with no basis
% in reality. The very idea of God is a product of the human imagination. It is quite
% understandable why primitive people, who were so much more exposed to the overpowering
% forces of nature than we are today, should have personified these forces in fear and
% trembling. But nowadays, when we understand so many natural processes, we have no need
% for such solutions. I can't for the life of me see how the postulate of an Almighty God
% helps us in any way. What I do see is that this assumption leads to such unproductive
% questions as why God allows so much misery and injustice, the exploitation of the poor
% by the rich and all the other horrors He might have prevented. If religion is still
% being taught, it is by no means because its ideas still convince us, but simply because
% some of us want to keep the lower classes quiet. Quiet people are much easier to govern
% than clamorous and dissatisfied ones. They are also much easier to exploit.
%
% Paul Dirac
|
github
|
tsajed/nmr-pred-master
|
wave_basis.m
|
.m
|
nmr-pred-master/spinach/kernel/pulses/wave_basis.m
| 3,090 |
utf_8
|
70011646cc9544f99942468390fb9dcf
|
% Common basis sets for the expansion of pulse waveforms. Returns the wave-
% form basis functions as columns of a matrix. Syntax:
%
% basis_waves=wave_basis(basis_type,n_functions,n_steps)
%
% Parameters:
%
% basis_type - may be set to 'sine_waves', 'cosine_waves',
% and 'legendre'. The sine and the cosine op-
% tions return the corresponding functions in
% the [-pi,pi] interval, legendre option re-
% turns legendre polynomials in the [-1,1] in-
% terval.
%
% n_functions - the number of functions to return (integer
% frequencies starting from zero on the case
% of cosines, integer frequencies starting
% from 1 inthe case of sines, legendre poly-
% nomial ranks in the case of legendre func-
% tion basis set.
%
% n_points - number of discretization points.
%
% Note: Because the resulting waveforms are discretized, they are not pre-
% cisely orthogonal under the standard scalar multiplication. An ex-
% tra orthogonalization step is therefore applied to make them ortho-
% gonal as vectors.
%
% [email protected]
function basis_waves=wave_basis(basis_type,n_functions,n_points)
% Check consistency
grumble(basis_type,n_functions,n_points);
% Preallocate the array
basis_waves=zeros(n_functions,n_points);
% Generate the functions
switch basis_type
case 'sine_waves'
% Fill the array
parfor n=1:n_functions
basis_waves(n,:)=sin(n*linspace(-pi,pi,n_points));
end
case 'cosine_waves'
% Fill the array
parfor n=1:n_functions
basis_waves(n,:)=cos((n-1)*linspace(-pi,pi,n_points));
end
case 'legendre'
% Fill the array
parfor n=1:n_functions
basis_waves(n,:)=mfun('P',n-1,linspace(-1,1,n_points));
basis_waves(n,:)=basis_waves(n,:)/norm(basis_waves(n,:));
end
otherwise
% Complain and bomb out
error('unrecognized basis function type.');
end
% Orthogonalize the array
basis_waves=orth(basis_waves');
end
% Consistency enforcement
function grumble(basis_type,n_functions,n_points)
if ~ischar(basis_type)
error('basis_type parameter must be a character string.');
end
if (numel(n_functions)~=1)||(~isnumeric(n_functions))||(~isreal(n_functions))||...
(n_functions<1)||(mod(n_functions,1)~=0)
error('n_functions parameter must be a positive real integer greater than 1.');
end
if (numel(n_points)~=1)||(~isnumeric(n_points))||(~isreal(n_points))||...
(n_points<1)||(mod(n_points,1)~=0)
error('n_points parameter must be a positive real integer greater than 1.');
end
end
% Self-esteem is the reputation we acquire with ourselves.
%
% Nathaniel Branden
|
github
|
tsajed/nmr-pred-master
|
oscillator.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/oscillator.m
| 1,368 |
utf_8
|
6c53aeeaf1935c1447ba630c0a307fe3
|
% Harmonic oscillator infrastructure. Syntax:
%
% [H_oscl,X_oscl,xgrid]=oscillator(parameters)
%
% where:
%
% parameters.frc_cnst - force constant
%
% parameters.dmd_mass - particle mass
%
% parameters.grv_cnst - gravitational acceleration
%
% parameters.n_points - number of discretization points
%
% parameters.rgn_size - oscillator box dimension
%
% The function returns:
%
% H_oscl - oscillator Hamiltonian
%
% X_oscl - oscillator X operator
%
% xgrid - X coordinate grid
%
% [email protected]
function [H_oscl,X_oscl,xgrid]=oscillator(parameters)
% Second derivative operator
d2_dx2=((parameters.n_points-1)/parameters.rgn_size)^2*fdmat(parameters.n_points,5,2);
% Coordinate grid
xgrid=linspace(-parameters.rgn_size/2,parameters.rgn_size/2,parameters.n_points)';
% Coordinate operator
X_oscl=spdiags(xgrid,0,parameters.n_points,parameters.n_points);
% Boundary conditions
d2_dx2(:,1)=0; d2_dx2(:,end)=0; d2_dx2(1,:)=0; d2_dx2(end,:)=0;
% Hamiltonian
H_oscl=-(1/(2*parameters.dmd_mass))*d2_dx2+(parameters.frc_cnst/2)*X_oscl^2+...
parameters.dmd_mass*parameters.grv_cnst*X_oscl;
end
% Just in terms of allocation of time resources, religion is
% not very efficient. There's a lot more I could be doing on
% a Sunday morning.
%
% Bill Gates
|
github
|
tsajed/nmr-pred-master
|
doublerot.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/doublerot.m
| 14,428 |
utf_8
|
cb152dc63d979f9801d438d1113dc5e8
|
% Fokker-Planck double angle spinning context. Generates a Liouvillian
% superoperator and passes it on to the pulse sequence function, which
% should be supplied as a handle. Syntax:
%
% answer=doublerot(spin_system,pulse_sequence,parameters,assumptions)
%
% where pulse sequence is a function handle to one of the pulse sequences
% located in the experiments directory, assumptions is a string that would
% be passed to assume.m when the Hamiltonian is built and parameters is a
% structure with the following subfields:
%
% parameters.rate_outer - outer rotor spinning rate in Hz
%
% parameters.rate_inner - inner rotor spinning rate in Hz
%
% parameters.axis_outer - spinning axis of the outer rotor,
% given as a normalized 3-element
% vector
%
% parameters.axis_inner - spinning axis of the inner rotor,
% given as a normalized 3-element
% vector
%
% parameters.rank_outer - 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) for the
% outer rotor
%
% parameters.rank_inner - 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) for the
% inner rotor
%
% 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
%
% Additional subfields may be required by the pulse sequence. The parameters
% structure is passed to the pulse sequence with the following additional
% parameters set:
%
% parameters.spc_dim - matrix dimension for the spatial
% dynamics subspace
%
% parameters.spn_dim - matrix dimension for the spin
% dynamics subspace
%
% This function returns the powder average of whatever it is that the pulse
% sequence returns.
%
% Note: arbitrary order rotating frame transformation is supported, inc-
% luding infinite order. See the header of rotframe.m for further
% information.
%
% Note: the state projector assumes a powder -- single crystal DOR is not
% currently supported.
%
% [email protected]
function answer=doublerot(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Get the Hamiltonian
[H,Q]=hamiltonian(assume(spin_system,assumptions));
% Apply offsets
H=frqoffset(spin_system,H,parameters);
% Count rotor trajectory points
npoints_inner=2*parameters.rank_inner+1;
npoints_outer=2*parameters.rank_outer+1;
npoints_total=npoints_outer*npoints_inner;
% Get problem dimensions
spc_dim=npoints_total; spn_dim=size(H,1);
report(spin_system,['lab space problem dimension ' num2str(spc_dim)]);
report(spin_system,['spin space problem dimension ' num2str(spn_dim)]);
report(spin_system,['Fokker-Planck problem dimension ' num2str(spc_dim*spn_dim)]);
parameters.spc_dim=spc_dim; parameters.spn_dim=spn_dim;
% Compute spectral derivative operators
[traj_inner,d_dphi_inner]=fourdif(npoints_inner,1);
[traj_outer,d_dphi_outer]=fourdif(npoints_outer,1);
% Compute rotor phase tracks
phases_outer=kron(traj_outer,ones(npoints_inner,1));
phases_inner=kron(ones(npoints_outer,1),traj_inner);
% Compute double spinning operator
M=2*pi*kron((parameters.rate_outer*kron(d_dphi_outer,speye(size(d_dphi_inner)))+...
parameters.rate_inner*kron(speye(size(d_dphi_outer)),d_dphi_inner)),speye(size(H)));
% Get rotor axis orientations
[phi_inner,theta_inner,~]=cart2sph(parameters.axis_inner(1),...
parameters.axis_inner(2),...
parameters.axis_inner(3));
[phi_outer,theta_outer,~]=cart2sph(parameters.axis_outer(1),...
parameters.axis_outer(2),...
parameters.axis_outer(3));
theta_inner=pi/2-theta_inner; theta_outer=pi/2-theta_outer;
% Compute outer rotor axis tilt
D_out2lab=euler2wigner(phi_outer,theta_outer,0);
% Compute inner rotor axis tilt
D_inn2out=euler2wigner(phi_inner,theta_inner,0);
% Get carrier operators
C=cell(size(parameters.rframes));
for n=1:numel(parameters.rframes)
C{n}=carrier(spin_system,parameters.rframes{n}{1});
end
% Get relaxation and kinetics
R=relaxation(spin_system); K=kinetics(spin_system);
% Get the averaging grid
sph_grid=load([spin_system.sys.root_dir '/kernel/grids/' parameters.grid '.mat']);
% Project relaxation and kinetics
R=kron(speye(spc_dim),R); K=kron(speye(spc_dim),K);
% Project the initial state
if isfield(parameters,'rho0')&&strcmp(parameters.grid,'single_crystal')
% Single crystal simulations start at 12 o'clock
space_part=zeros(parameters.spc_dim,1); space_part(1)=1;
parameters.rho0=kron(space_part,parameters.rho0);
report(spin_system,'single crystal simulation, rotor phase averaging switched off.');
elseif isfield(parameters,'rho0')
% Powder simulations start distributed
space_part=ones(parameters.spc_dim,1)/sqrt(parameters.spc_dim);
parameters.rho0=kron(space_part,parameters.rho0);
report(spin_system,'powder simulation, rotor phase averaging switched on.');
end
% Project the coil state
if isfield(parameters,'coil')&&strcmp(parameters.grid,'single_crystal')
% Single crystal simulations require unnormalized coil
space_part=ones(parameters.spc_dim,1);
parameters.coil=kron(space_part,parameters.coil);
spin_system.sys.disable{end+1}='norm_coil';
report(spin_system,'single crystal simulation, coil normalization switched off.');
elseif isfield(parameters,'coil')
% Powder simulations require normalized coil
space_part=ones(parameters.spc_dim,1)/sqrt(parameters.spc_dim);
parameters.coil=kron(space_part,parameters.coil);
report(spin_system,'powder simulation, coil normalization switched on.');
end
% Preallocate answer array
ans_array=cell(numel(sph_grid.weights),1);
% Shut up and inform the user
report(spin_system,['powder average being computed over ' num2str(numel(sph_grid.weights)) ' orientations.']);
if ~isfield(parameters,'verbose')||(parameters.verbose==0)
report(spin_system,'pulse sequence has been silenced to avoid excessive output.')
spin_system.sys.output='hush';
end
% Powder averaged spectrum
parfor q=1:numel(sph_grid.weights) %#ok<*PFBNS>
% Set crystallite orientation
D_mol2inn=euler2wigner([sph_grid.alphas(q) sph_grid.betas(q) sph_grid.gammas(q)])';
% Preallocate Liouvillian blocks
L=cell(npoints_total,npoints_total);
for n=1:npoints_total
for k=1:npoints_total
L{n,k}=krondelta(n,k)*H;
end
end
% Build Liouvillian blocks
for n=1:npoints_total
% Get the rotations
D_outer=euler2wigner(0,0,phases_outer(n));
D_inner=euler2wigner(0,0,phases_inner(n));
D=D_out2lab*D_outer*D_inn2out*D_inner*D_mol2inn;
% Build the block
for k=1:5
for m=1:5
L{n,n}=L{n,n}+D(k,m)*Q{k,m};
end
end
% Apply the rotating frame
for k=1:numel(parameters.rframes)
L{n,n}=rotframe(spin_system,C{k},(L{n,n}+L{n,n}')/2,parameters.rframes{k}{1},parameters.rframes{k}{2});
end
end
% Assemble the liouvillian
L=clean_up(spin_system,cell2mat(L),spin_system.tols.liouv_zero);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Run the pulse sequence
ans_array{q}=pulse_sequence(spin_system,parameters,L+1i*M,R,K);
end
% Add up structures
answer=sph_grid.weights(1)*ans_array{1};
for n=2:numel(ans_array)
answer=answer+sph_grid.weights(n)*ans_array{n};
end
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
if ~isfield(parameters,'rframes')
report(spin_system,'parameters.rframes field not set, assuming no additional rotating frame transformations.');
parameters.rframes={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency enforcement
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Formalism
if ~ismember(spin_system.bas.formalism,{'zeeman-liouv','sphten-liouv'})
error('this function is only available in Liouville space.');
end
% Rotor ranks
if ~isfield(parameters,'rank_outer')
error('parameters.rank_outer subfield must be present.');
elseif (~isnumeric(parameters.rank_outer))||(~isreal(parameters.rank_outer))||...
(mod(parameters.rank_outer,1)~=0)||(parameters.rank_outer<0)
error('parameters.rank_outer must be a positive real integer.');
end
if ~isfield(parameters,'rank_inner')
error('parameters.rank_inner subfield must be present.');
elseif (~isnumeric(parameters.rank_inner))||(~isreal(parameters.rank_inner))||...
(mod(parameters.rank_inner,1)~=0)||(parameters.rank_inner<0)
error('parameters.rank_inner must be a positive real integer.');
end
% Spinning rates
if ~isfield(parameters,'rate_outer')
error('parameters.rate_outer subfield must be present.');
elseif (~isnumeric(parameters.rate_outer))||(~isreal(parameters.rate_outer))
error('parameters.rate_outer must be a real number.');
end
if ~isfield(parameters,'rate_inner')
error('parameters.rate_inner subfield must be present.');
elseif (~isnumeric(parameters.rate_inner))||(~isreal(parameters.rate_inner))
error('parameters.rate_inner must be a real number.');
end
% Spinning axes
if ~isfield(parameters,'axis_outer')
error('parameters.axis_outer subfield must be present.');
elseif (~isnumeric(parameters.axis_outer))||(~isreal(parameters.axis_outer))||...
(~isrow(parameters.axis_outer))||(numel(parameters.axis_outer)~=3)
error('parameters.axis_outer must be a row vector of three real numbers.');
end
if ~isfield(parameters,'axis_inner')
error('parameters.axis_inner subfield must be present.');
elseif (~isnumeric(parameters.axis_inner))||(~isreal(parameters.axis_inner))||...
(~isrow(parameters.axis_inner))||(numel(parameters.axis_inner)~=3)
error('parameters.axis_inner must be a row vector of three real numbers.');
end
% Spherical grid
if ~isfield(parameters,'grid')
error('spherical averaging grid must be specified in parameters.grid variable.');
elseif isempty(parameters.grid)
error('parameters.grid variable cannot be empty.');
elseif ~ischar(parameters.grid)
error('parameters.grid variable must be a character string.');
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Rotating frame transformations
if ~isfield(parameters,'rframes')
error('parameters.rframes variable must be specified.');
elseif ~iscell(parameters.rframes)
error('parameters.rframes must be a cell array.');
end
for n=1:numel(parameters.rframes)
if ~iscell(parameters.rframes{n})
error('elements of parameters.rframes must be cell arrays.');
end
if numel(parameters.rframes{n})~=2
error('elements of parameters.rframes must have exactly two sub-elements each.');
end
if ~ischar(parameters.rframes{n}{1})
error('the first part of each element of parameters.rframes must be a character string.');
end
if ~ismember(parameters.rframes{n}{1},spin_system.comp.isotopes)
error('parameters.rframes refers to a spin that is not present in the system.');
end
if ~isnumeric(parameters.rframes{n}{2})
error('the second part of each element of parameters.rframes must be a number.');
end
end
end
% Show me a hero and I'll write you a tragedy.
%
% F. Scott Fitzgerald
|
github
|
tsajed/nmr-pred-master
|
gridfree.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/gridfree.m
| 9,938 |
utf_8
|
4022c6869a17347b8568ec5413610d90
|
% Fokker-Planck magic angle spinning and SLE context. Generates a Liouvil-
% lian superoperator and passes it on to the pulse sequence function, which
% should be supplied as a handle. Syntax:
%
% answer=gridfree(spin_system,pulse_sequence,parameters,assumptions)
%
% where pulse sequence is a function handle to one of the pulse sequences
% located in the experiments directory, assumptions is a string that would
% be passed to assume.m when the Hamiltonian is built and parameters is a
% structure with the following subfields:
%
% parameters.rate - spinning rate in Hz
%
% parameters.axis - spinning axis, given as a normalized
% 3-element vector
%
% parameters.spins - a cell array giving the spins that
% the pulse sequence involves, e.g.
% {'1H','13C'}
%
% 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 D-function 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.tau_c - correlation times (in seconds) for rotational
% diffusion. Single number for isotropic rotati-
% onal diffusion, two for axial and three for
% rhombic rotational diffusion. Other interacti-
% ons and coordinates are assumed to be specifi-
% ed in the rotational diffusion tensor eigen-
% frame.
%
% Additional subfields may be required by the pulse sequence. The parameters
% structure is passed to the pulse sequence with the following additional
% parameters set:
%
% parameters.spc_dim - matrix dimension for the spatial
% dynamics subspace
%
% parameters.spn_dim - matrix dimension for the spin
% dynamics subspace
%
% This function returns the powder average of whatever it is that the pulse
% sequence returns.
%
% Note: the choice of the Wigner function rank truncation level depends on
% the spinning rate (the slower the spinning, the greater ranks are
% required).
%
% Note: rotational correlation times for SLE go into parameters.tau_c, not
% inter.tau_c (the latter is only used by the Redfield theory module).
%
% Note: the state projector assumes a powder -- single crystal MAS is not
% currently supported.
%
% [email protected]
function answer=gridfree(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Get spatial operators
[Lx,Ly,Lz,D,~]=sle_operators(parameters.max_rank);
% Get spin Hamiltonian
[H,Q]=hamiltonian(assume(spin_system,assumptions));
% Apply offsets
H=frqoffset(spin_system,H,parameters);
% Get relaxation and kinetics
R=relaxation(spin_system);
K=kinetics(spin_system);
% Get problem dimensions
spc_dim=size(Lx,1); parameters.spc_dim=spc_dim;
spn_dim=size(H,1); parameters.spn_dim=spn_dim;
% Inform the user
report(spin_system,['spin space problem dimension ' num2str(spn_dim)]);
report(spin_system,['lab space space dimension ' num2str(spc_dim)]);
report(spin_system,['Fokker-Planck problem dimension ' num2str(spn_dim*spc_dim)]);
% Project isotropic parts
H=kron(speye(spc_dim),H);
R=kron(speye(spc_dim),R);
K=kron(speye(spc_dim),K);
% Add anisotropic parts
for k=1:5
for m=1:5
H=H+kron(D{k,m},Q{k,m});
end
end
% Rotation operator
if isfield(parameters,'rate')&&abs(parameters.rate)>0
% Normalize axis vector
spinning_axis=parameters.axis/norm(parameters.axis);
% Report to the user
report(spin_system,['spinning axis ort: ' num2str(spinning_axis)]);
report(spin_system,['spinning rate: ' num2str(parameters.rate) ' Hz']);
% Build rotation operator
Hr=2*pi*parameters.rate*(spinning_axis(1)*Lx+spinning_axis(2)*Ly+spinning_axis(3)*Lz);
% Add rotation operator
H=H+kron(Hr,speye(spn_dim));
end
% Diffusion operator
if isfield(parameters,'tau_c')
% Build diffusion operator
if numel(parameters.tau_c)==1
% Isotropic rotational diffusion
diff_iso=1/(6*parameters.tau_c);
Rd=diff_iso*(Lx^2+Ly^2+Lz^2);
elseif numel(parameters.tau_c)==2
% Axial rotational diffusion
diff_ax=1/(6*parameters.tau_c(1));
diff_eq=1/(6*parameters.tau_c(2));
Rd=diff_eq*Lx^2+diff_eq*Ly^2+diff_ax*Lz^2;
elseif numel(parameters.tau_c)==3
% Rhombic rotational diffusion
diff_xx=1/(6*parameters.tau_c(1));
diff_yy=1/(6*parameters.tau_c(2));
diff_zz=1/(6*parameters.tau_c(3));
Rd=diff_xx*Lx^2+diff_yy*Ly^2+diff_zz*Lz^2;
else
% Complain and bomb out
error('invalid correlation time specification.');
end
% Add diffusion operator
R=R-kron(Rd,speye(spn_dim));
end
% Clean up the result
H=clean_up(spin_system,H,spin_system.tols.liouv_zero);
R=clean_up(spin_system,R,spin_system.tols.liouv_zero);
K=clean_up(spin_system,K,spin_system.tols.liouv_zero);
% Inform the user
report(spin_system,['found ' num2str(nnz(H)+nnz(R)+nnz(K)) ' non-zeros in the Fokker-Planck Liouvillian.']);
% Project initial and detection states
P=spalloc(spc_dim,1,1); P(1)=1;
if isfield(parameters,'rho0')
parameters.rho0=kron(P,parameters.rho0);
end
if isfield(parameters,'coil')
parameters.coil=kron(P,parameters.coil);
end
% Report to the user
report(spin_system,'running the pulse sequence...');
% Call the pulse sequence
answer=pulse_sequence(spin_system,parameters,H,R,K);
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency enforcement
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Rotating frames
if isfield(parameters,'rframes')
error('numerical rotating frame transformation is not supported by SLE formalism.');
end
% Spherical grid
if isfield(parameters,'grid')
error('spherical integration is a part of the SLE formalism, this parameter is unnecessary.');
end
% Formalism
if ~ismember(spin_system.bas.formalism,{'zeeman-liouv','sphten-liouv'})
error('this function is only available in Liouville space.');
end
% Rotor rank
if ~isfield(parameters,'max_rank')
error('parameters.max_rank subfield must be present.');
elseif (~isnumeric(parameters.max_rank))||(~isreal(parameters.max_rank))||...
(mod(parameters.max_rank,1)~=0)||(parameters.max_rank<0)
error('parameters.max_rank must be a positive real integer.');
end
% Spinning rate
if isfield(parameters,'rate')&&((~isnumeric(parameters.rate))||(~isreal(parameters.rate)))
error('parameters.rate must be a real number.');
end
% Spinning axis
if isfield(parameters,'axis')&&((~isnumeric(parameters.axis))||(~isreal(parameters.axis))||...
(~isrow(parameters.axis))||(numel(parameters.axis)~=3))
error('parameters.axis must be a row vector of three real numbers.');
end
% Check rotational correlation time
if isfield(parameters,'tau_c')
if (~isnumeric(parameters.tau_c))||(numel(parameters.tau_c)>3)||(numel(parameters.tau_c)==0)
error('parameters.tau_c must be a vector of size 1, 2 or 3.');
end
if (~isreal(parameters.tau_c))||any(parameters.tau_c<0)
error('parameters.tau_c must have non-negative real elements.');
end
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
end
% No god and no religion can survive ridicule. No political church,
% no nobility, no royalty or other fraud, can face ridicule in a fair
% field, and live.
%
% Mark Twain
|
github
|
tsajed/nmr-pred-master
|
roadmap.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/roadmap.m
| 9,126 |
utf_8
|
08c8533eb7af211f82f7270aea7bb271
|
% Runs a simulation of a user-specified pulse sequence for each
% orientation found in the user-specified grid and returns the
% corresponding angles, integration weights, tessellation trian-
% gles and sequence results (as a cell array of whatever it is
% that the pulse sequence returns).
%
% The function supports parallel processing via Matlab's Distri-
% buted Computing Toolbox - different system orientations are eva-
% luated on different labs. Syntax:
%
% [alphas,betas,gammas,weights,triangles,fid]=...
% roadmap(spin_system,pulse_sequence,parameters,assumptions)
%
% Input arguments:
%
% pulse_sequence - pulse sequence function handle. See the
% /experiments directory for the list of
% pulse sequences that are supplied with
% Spinach.
%
% parameters - a structure containing sequence-specific
% parameters. See the pulse sequence header
% for the list of parameters each sequence
% requires. The parameters that this inter-
% face itself requires are:
%
% parameters.spins - a cell array giving the
% spins that the pulse sequence works on, in
% the order of channels, e.g. {'1H','13C'}
%
% parameters.offsets - a cell array giving
% transmitter offsets on each of the spins
% listed in parameters.spins.
%
% parameters.grid - name of the spherical
% averaging grid file (see the grids direc-
% tory in the kernel).
%
% assumptions - context-specific assumptions ('nmr', 'epr',
% 'labframe', etc.) - see the pulse sequence
% header and assumptions.m file for further
% information on this setting.
%
% Output arguments:
%
% alphas - an array of alpha Euler angles from the
% spherical grid
%
% betas - an array of beta Euler angles from the
% spherical grid
%
% gammas - an array of gamma Euler angles from the
% spherical grid
%
% weights - an array of summation weights appropri-
% ate for the corresponding points of the
% spherical grid
%
% triangles - an array of triangle specification from
% the tesselation information supplied in
% the grid file
%
% fid - a cell array of whatever it is that the
% pulse sequence function returns at each
% point inthe spherical grid
%
% [email protected]
function [alphas,betas,gammas,weights,triangles,answer]=roadmap(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Set the secularity assumptions
spin_system=assume(spin_system,assumptions);
% Get the rotational expansion of the Hamiltonian
[I,Q]=hamiltonian(spin_system);
% Get kinetics
K=kinetics(spin_system);
% Apply the offsets
I=frqoffset(spin_system,I,parameters);
% Get carrier operators
C=cell(size(parameters.rframes));
for n=1:numel(parameters.rframes)
C{n}=carrier(spin_system,parameters.rframes{n}{1});
end
% Get problem dimensions
parameters.spc_dim=1; parameters.spn_dim=size(I,1);
% Get the spherical averaging grid
spherical_grid=load([spin_system.sys.root_dir '/kernel/grids/' parameters.grid],...
'alphas','betas','gammas','weights','triangles');
% Assign local variables
alphas=spherical_grid.alphas; betas=spherical_grid.betas;
gammas=spherical_grid.gammas; weights=spherical_grid.weights;
triangles=spherical_grid.triangles;
% Preallocate the answer
answer=cell(numel(weights),1);
% Shut up and inform the user
report(spin_system,['powder average being computed over ' num2str(numel(weights)) ' orientations.']);
if ~isfield(parameters,'verbose')||(parameters.verbose==0)
report(spin_system,'pulse sequence has been silenced to avoid excessive output.')
spin_system.sys.output='hush';
end
% Crunch the orientations in parallel
parfor n=1:numel(weights)
% Get the full Liouvillian at the current orientation
H=I+orientation(Q,[alphas(n) betas(n) gammas(n)]); H=(H+H')/2;
% Apply rotating frames
for k=1:numel(parameters.rframes) %#ok<PFBNS>
H=rotframe(spin_system,C{k},H,parameters.rframes{k}{1},parameters.rframes{k}{2}); %#ok<PFBNS>
end
% Get the relaxation superoperator at the current orientation
R=relaxation(spin_system,[alphas(n) betas(n) gammas(n)]);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Run the simulation
answer{n}=pulse_sequence(spin_system,parameters,H,R,K); %#ok<PFBNS>
end
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
if ~isfield(parameters,'rframes')
report(spin_system,'parameters.rframes field not set, assuming no additional rotating frame transformations.');
parameters.rframes={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency checking
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Spherical grid
if ~isfield(parameters,'grid')
error('spherical averaging grid must be specified in parameters.grid variable.');
elseif isempty(parameters.grid)
error('parameters.grid variable cannot be empty.');
elseif ~ischar(parameters.grid)
error('parameters.grid variable must be a character string.');
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Rotating frame transformations
if ~isfield(parameters,'rframes')
error('parameters.rframes variable must be specified.');
elseif ~iscell(parameters.rframes)
error('parameters.rframes must be a cell array.');
end
for n=1:numel(parameters.rframes)
if ~iscell(parameters.rframes{n})
error('elements of parameters.rframes must be cell arrays.');
end
if numel(parameters.rframes{n})~=2
error('elements of parameters.rframes must have exactly two sub-elements each.');
end
if ~ischar(parameters.rframes{n}{1})
error('the first part of each element of parameters.rframes must be a character string.');
end
if ~ismember(parameters.rframes{n}{1},spin_system.comp.isotopes)
error('parameters.rframes refers to a spin that is not present in the system.');
end
if ~isnumeric(parameters.rframes{n}{2})
error('the second part of each element of parameters.rframes must be a number.');
end
end
end
% The fact that we live at the bottom of a deep gravity well, on the
% surface of a gas covered planet going around a nuclear fireball 90
% million miles away and think this to be normal is obviously some
% indication of how skewed our perspective tends to be.
%
% Douglas Adams
|
github
|
tsajed/nmr-pred-master
|
singlerot.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/singlerot.m
| 12,699 |
utf_8
|
11c0be61b6734e767a0f62021d190e8d
|
% Fokker-Planck magic angle spinning context. Generates a Liouvillian
% superoperator and passes it on to the pulse sequence function, which
% should be supplied as a handle. Syntax:
%
% answer=singlerot(spin_system,pulse_sequence,parameters,assumptions)
%
% where pulse sequence is a function handle to one of the pulse sequences
% located in the experiments directory, assumptions is a string that would
% be passed to assume.m when the Hamiltonian is built and parameters is a
% structure with the following subfields:
%
% parameters.rate - spinning rate in Hz
%
% parameters.axis - spinning axis, given as a normalized
% 3-element vector
%
% parameters.spins - a cell array giving the spins that
% the pulse sequence involves, e.g.
% {'1H','13C'}
%
% 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.grid - spherical grid file name. See grids
% directory in the kernel.
%
% Additional subfields may be required by the pulse sequence. The parameters
% structure is passed to the pulse sequence with the following additional
% parameters set:
%
% parameters.spc_dim - matrix dimension for the spatial
% dynamics subspace
%
% parameters.spn_dim - matrix dimension for the spin
% dynamics subspace
%
% This function returns the powder average of whatever it is that the pulse
% sequence returns.
%
% Note: arbitrary order rotating frame transformation is supported, inc-
% luding infinite order. See the header of rotframe.m for further
% information.
%
% Note: the state projector assumes a powder -- single crystal MAS is not
% currently supported.
%
% [email protected]
function answer=singlerot(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Get the Hamiltonian
[H,Q]=hamiltonian(assume(spin_system,assumptions));
% Apply offsets
H=frqoffset(spin_system,H,parameters);
% Get problem dimensions
spc_dim=2*parameters.max_rank+1; spn_dim=size(H,1);
report(spin_system,['lab space problem dimension ' num2str(spc_dim)]);
report(spin_system,['spin space problem dimension ' num2str(spn_dim)]);
report(spin_system,['Fokker-Planck problem dimension ' num2str(spc_dim*spn_dim)]);
parameters.spc_dim=spc_dim; parameters.spn_dim=spn_dim;
% Compute rotor angles and the derivative operator
[rotor_angles,d_dphi]=fourdif(spc_dim,1);
% Compute spinning operator
M=2*pi*parameters.rate*kron(d_dphi,speye(size(H)));
% Get rotor axis orientation
[phi,theta,~]=cart2sph(parameters.axis(1),parameters.axis(2),parameters.axis(3));
theta=pi/2-theta; D_rot2lab=euler2wigner(phi,theta,0);
% Get carrier operators
C=cell(size(parameters.rframes));
for n=1:numel(parameters.rframes)
C{n}=carrier(spin_system,parameters.rframes{n}{1});
end
% Get relaxation and kinetics
R=relaxation(spin_system); K=kinetics(spin_system);
% Get the averaging grid
sph_grid=load([spin_system.sys.root_dir '/kernel/grids/' parameters.grid '.mat']);
% Project relaxation and kinetics
R=kron(speye(spc_dim),R); K=kron(speye(spc_dim),K);
% Project the initial state
if isfield(parameters,'rho0')&&strcmp(parameters.grid,'single_crystal')
% Single crystal simulations start at 12 o'clock
space_part=zeros(parameters.spc_dim,1); space_part(1)=1;
parameters.rho0=kron(space_part,parameters.rho0);
report(spin_system,'single crystal simulation, rotor phase averaging switched off.');
elseif isfield(parameters,'rho0')
% Powder simulations start distributed
space_part=ones(parameters.spc_dim,1)/sqrt(parameters.spc_dim);
parameters.rho0=kron(space_part,parameters.rho0);
report(spin_system,'powder simulation, rotor phase averaging switched on.');
end
% Project the coil state
if isfield(parameters,'coil')&&strcmp(parameters.grid,'single_crystal')
% Single crystal simulations require unnormalized coil
space_part=ones(parameters.spc_dim,1);
parameters.coil=kron(space_part,parameters.coil);
spin_system.sys.disable{end+1}='norm_coil';
report(spin_system,'single crystal simulation, coil normalization switched off.');
elseif isfield(parameters,'coil')
% Powder simulations require normalized coil
space_part=ones(parameters.spc_dim,1)/sqrt(parameters.spc_dim);
parameters.coil=kron(space_part,parameters.coil);
report(spin_system,'powder simulation, coil normalization switched on.');
end
% Preallocate answer array
ans_array=cell(numel(sph_grid.weights),1);
% Shut up and inform the user
report(spin_system,['powder average being computed over ' num2str(numel(sph_grid.weights)) ' orientations.']);
if ~parameters.verbose
report(spin_system,'pulse sequence silenced to avoid excessive output.'); spin_system.sys.output='hush';
end
% Powder averaged spectrum
parfor q=1:numel(sph_grid.weights) %#ok<*PFBNS>
% Set crystallite orientation
D_mol2rot=euler2wigner([sph_grid.alphas(q) sph_grid.betas(q) sph_grid.gammas(q)])';
% Preallocate Liouvillian blocks
L=cell(2*parameters.max_rank+1,2*parameters.max_rank+1);
for n=1:(2*parameters.max_rank+1)
for k=1:(2*parameters.max_rank+1)
L{n,k}=krondelta(n,k)*H;
end
end
% Build Liouvillian blocks
for n=1:(2*parameters.max_rank+1)
% Get the rotation
D_rotor=euler2wigner(0,0,rotor_angles(n));
D=D_rot2lab*D_rotor*D_mol2rot;
% Build the block
for k=1:5
for m=1:5
L{n,n}=L{n,n}+D(k,m)*Q{k,m};
end
end
L{n,n}=(L{n,n}+L{n,n}')/2;
% Apply the rotating frame
for k=1:numel(parameters.rframes)
L{n,n}=rotframe(spin_system,C{k},L{n,n},parameters.rframes{k}{1},parameters.rframes{k}{2});
end
end
% Assemble the Fokker-Planck Liouvillian
L=clean_up(spin_system,cell2mat(L)+1i*M,spin_system.tols.liouv_zero);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Run the pulse sequence
ans_array{q}=pulse_sequence(spin_system,parameters,L,R,K);
end
% Add up structures
answer=sph_grid.weights(1)*ans_array{1};
for n=2:numel(ans_array)
answer=answer+sph_grid.weights(n)*ans_array{n};
end
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
if ~isfield(parameters,'rframes')
report(spin_system,'parameters.rframes field not set, assuming no additional rotating frame transformations.');
parameters.rframes={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency enforcement
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Formalism
if ~ismember(spin_system.bas.formalism,{'zeeman-liouv','sphten-liouv'})
error('this function is only available in Liouville space.');
end
% Rotor rank
if ~isfield(parameters,'max_rank')
error('parameters.max_rank subfield must be present.');
elseif (~isnumeric(parameters.max_rank))||(~isreal(parameters.max_rank))||...
(mod(parameters.max_rank,1)~=0)||(parameters.max_rank<0)
error('parameters.max_rank must be a positive real integer.');
end
% Spinning rate
if ~isfield(parameters,'rate')
error('parameters.rate subfield must be present.');
elseif (~isnumeric(parameters.rate))||(~isreal(parameters.rate))
error('parameters.rate must be a real number.');
end
% Spinning axis
if ~isfield(parameters,'axis')
error('parameters.axis subfield must be present.');
elseif (~isnumeric(parameters.axis))||(~isreal(parameters.axis))||...
(~isrow(parameters.axis))||(numel(parameters.axis)~=3)
error('parameters.axis must be a row vector of three real numbers.');
end
% Spherical grid
if ~isfield(parameters,'grid')
error('spherical averaging grid must be specified in parameters.grid variable.');
elseif isempty(parameters.grid)
error('parameters.grid variable cannot be empty.');
elseif ~ischar(parameters.grid)
error('parameters.grid variable must be a character string.');
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Rotating frame transformations
if ~isfield(parameters,'rframes')
error('parameters.rframes variable must be specified.');
elseif ~iscell(parameters.rframes)
error('parameters.rframes must be a cell array.');
end
for n=1:numel(parameters.rframes)
if ~iscell(parameters.rframes{n})
error('elements of parameters.rframes must be cell arrays.');
end
if numel(parameters.rframes{n})~=2
error('elements of parameters.rframes must have exactly two sub-elements each.');
end
if ~ischar(parameters.rframes{n}{1})
error('the first part of each element of parameters.rframes must be a character string.');
end
if ~ismember(parameters.rframes{n}{1},spin_system.comp.isotopes)
error('parameters.rframes refers to a spin that is not present in the system.');
end
if ~isnumeric(parameters.rframes{n}{2})
error('the second part of each element of parameters.rframes must be a number.');
end
end
end
% There are no set working hours, your contract requires you to work such
% hours as are reasonably necessary to perform your duties.
%
% [...]
%
% Associate Professors are not permitted to use the designation Professor.
% Any Associate Professor who mistakenly uses the title Professor will be
% told that this is not correct and asked to amend it.
%
% IK's contract at Southampton University, 2014
|
github
|
tsajed/nmr-pred-master
|
hydrodynamics.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/hydrodynamics.m
| 2,649 |
utf_8
|
bc4ad27ecd5cdc6c0d9387ead200ebe9
|
% A basic hydrodynamics infrastructure provider.
%
% [email protected]
% [email protected]
function [Fx,Fy,Fz]=hydrodynamics(parameters)
% Build derivative operators
switch parameters.cond{1}
case 'period'
% Finite-difference derivatives
if numel(parameters.npts)==1
Dx=fdmat(parameters.npts(1),parameters.cond{2},1)/(parameters.dims(1)/parameters.npts(1));
end
if numel(parameters.npts)==2
Dx=fdmat(parameters.npts(1),parameters.cond{2},1)/(parameters.dims(1)/parameters.npts(1));
Dy=fdmat(parameters.npts(2),parameters.cond{2},1)/(parameters.dims(2)/parameters.npts(2));
end
if numel(parameters.npts)==3
Dx=fdmat(parameters.npts(1),parameters.cond{2},1)/(parameters.dims(1)/parameters.npts(1));
Dy=fdmat(parameters.npts(2),parameters.cond{2},1)/(parameters.dims(2)/parameters.npts(2));
Dz=fdmat(parameters.npts(3),parameters.cond{2},1)/(parameters.dims(3)/parameters.npts(3));
end
case 'fourier'
% Fourier derivatives
if numel(parameters.npts)==1
[~,Dx]=fourdif(parameters.npts(1),1); Dx=(2*pi/parameters.dims(1))*Dx;
end
if numel(parameters.npts)==2
[~,Dx]=fourdif(parameters.npts(1),1); Dx=(2*pi/parameters.dims(1))*Dx;
[~,Dy]=fourdif(parameters.npts(2),1); Dy=(2*pi/parameters.dims(2))*Dy;
end
if numel(parameters.npts)==3
[~,Dx]=fourdif(parameters.npts(1),1); Dx=(2*pi/parameters.dims(1))*Dx;
[~,Dy]=fourdif(parameters.npts(2),1); Dy=(2*pi/parameters.dims(2))*Dy;
[~,Dz]=fourdif(parameters.npts(3),1); Dz=(2*pi/parameters.dims(3))*Dz;
end
otherwise
% Complain and bomb out
error('unrecognized derivative operator type.');
end
% Kron up derivative operators
if numel(parameters.npts)==1
Fx=-1i*Dx; Fy=[]; Fz=[];
end
if numel(parameters.npts)==2
Fx=-1i*kron(kron(speye(parameters.npts(2)),Dx),speye(size(1)));
Fy=-1i*kron(kron(Dy,speye(parameters.npts(1))),speye(size(1))); Fz=[];
end
if numel(parameters.npts)==3
Fx=-1i*kron(kron(kron(speye(parameters.npts(3)),speye(parameters.npts(2))),Dx),speye(size(1)));
Fy=-1i*kron(kron(kron(speye(parameters.npts(3)),Dy),speye(parameters.npts(1))),speye(size(1)));
Fz=-1i*kron(kron(kron(Dz,speye(parameters.npts(2))),speye(parameters.npts(1))),speye(size(1)));
end
end
% As for butter versus margarine, I trust cows
% more than chemists.
%
% Joan Gussow
|
github
|
tsajed/nmr-pred-master
|
liquid.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/liquid.m
| 7,042 |
utf_8
|
a05d9cd49ad028eb0ce831fd3d28e36b
|
% Liquid-phase interface to pulse sequences. Generates a Liouvillian
% superoperator and passes it on to the pulse sequence function, which
% should be supplied as a handle.
%
% This interface handles RDC mode -- if parameters.rdc switch is set,
% it would use the order matrix supplied by the user to compute the
% residual anisotropies of all interactions. Syntax:
%
% fid=liquid(spin_system,pulse_sequence,parameters,assumptions)
%
% Arguments:
%
% pulse_sequence - pulse sequence function handle. See the
% experiments directory for the list of
% pulse sequences that ship with Spinach.
%
% parameters - a structure containing sequence-specific
% parameters. See the pulse sequence header
% for the list of parameters each sequence
% requires. The parameters that this inter-
% face itself requires are:
%
% parameters.spins - a cell array giving the
% spins that the pulse sequence works on, in
% the order of channels, e.g. {'1H','13C'}
%
% parameters.offset - a cell array giving
% transmitter offsets on each of the spins
% listed in parameters.spins array.
%
% parameters.rdc - a logical switch control-
% ling the inclusion of residual dipolar co-
% uplings into the calculation.
%
% assumptions - context-specific assumptions ('nmr', 'epr',
% 'labframe', etc.) - see the pulse sequence
% header for information on this setting.
%
% This function returns whatever it is that the pulse sequence returns.
%
% [email protected]
function answer=liquid(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Set assumptions
spin_system=assume(spin_system,assumptions);
% Get the Liouvillian
if isfield(parameters,'rdc')&¶meters.rdc
% With RDCs, first get the relaxation and kinetics
R=relaxation(spin_system); K=kinetics(spin_system);
% Then do the liquid crystal averaging
spin_system=residual(spin_system);
% Then get the coherent parts of the Liouvillian
[I,Q]=hamiltonian(spin_system); H=I+orientation(Q,[0 0 0]);
else
% Get the isotropic Liouvillian
H=hamiltonian(spin_system);
R=relaxation(spin_system);
K=kinetics(spin_system);
end
% Process channel offsets
H=frqoffset(spin_system,H,parameters);
% Get carrier operators
C=cell(size(parameters.rframes));
for n=1:numel(parameters.rframes)
C{n}=carrier(spin_system,parameters.rframes{n}{1});
end
% Apply rotating frames
for k=1:numel(parameters.rframes)
H=rotframe(spin_system,C{k},H,parameters.rframes{k}{1},parameters.rframes{k}{2});
end
% Get problem dimensions
parameters.spc_dim=1; parameters.spn_dim=size(H,1);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Call the pulse sequence
answer=pulse_sequence(spin_system,parameters,H,R,K);
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
if ~isfield(parameters,'rframes')
report(spin_system,'parameters.rframes field not set, assuming no additional rotating frame transformations.');
parameters.rframes={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency enforcement
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Rotating frame transformations
if ~isfield(parameters,'rframes')
error('parameters.rframes variable must be specified.');
elseif ~iscell(parameters.rframes)
error('parameters.rframes must be a cell array.');
end
for n=1:numel(parameters.rframes)
if ~iscell(parameters.rframes{n})
error('elements of parameters.rframes must be cell arrays.');
end
if numel(parameters.rframes{n})~=2
error('elements of parameters.rframes must have exactly two sub-elements each.');
end
if ~ischar(parameters.rframes{n}{1})
error('the first part of each element of parameters.rframes must be a character string.');
end
if ~ismember(parameters.rframes{n}{1},spin_system.comp.isotopes)
error('parameters.rframes refers to a spin that is not present in the system.');
end
if ~isnumeric(parameters.rframes{n}{2})
error('the second part of each element of parameters.rframes must be a number.');
end
end
end
% A man who can conceive a thing as beautiful as this should never
% have allowed it to be erected. [...] But he will let it be built,
% so that women will hang out diapers on his terraces, so that men
% will spit on his stairways and draw dirty pictures on his walls.
% [...] They will be committing only a mean little indecency, but
% he has committed a sacrilege.
%
% Ayn Rand, "The Fountainhead"
|
github
|
tsajed/nmr-pred-master
|
floquet.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/floquet.m
| 9,877 |
utf_8
|
65d69fc1a0387f63323369e3bedaaaa9
|
% Floquet magic angle spinning context. Generates a Liouvillian super-
% operator and passes it on to the pulse sequence function, which sho-
% uld be supplied as a handle. Syntax:
%
% answer=floquet(spin_system,pulse_sequence,parameters,assumptions)
%
% where pulse sequence is a function handle to one of the pulse sequences
% located in the experiments directory, assumptions is a string that would
% be passed to assume.m when the Hamiltonian is built and parameters is a
% structure with the following subfields:
%
% parameters.rate - spinning rate in Hz
%
% parameters.axis - spinning axis, given as a normalized
% 3-element vector
%
% parameters.spins - a cell array giving the spins that
% the pulse sequence involves, e.g.
% {'1H','13C'}
%
% 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.grid - spherical grid file name. See grids
% directory in the kernel.
%
% Additional subfields may be required by the pulse sequence. The parameters
% structure is passed to the pulse sequence with the following additional
% parameters set:
%
% parameters.spc_dim - matrix dimension for the spatial
% dynamics subspace
%
% parameters.spn_dim - matrix dimension for the spin
% dynamics subspace
%
% This function returns the powder average of whatever it is that the pulse
% sequence returns.
%
% Note: the choice of the rank depends on the spinning rate (the slower
% the spinning, the greater ranks are required). The rank is appro-
% ximately equal to the number of spinning sidebands.
%
% Note: the state projector assumes a powder -- single crystal MAS is not
% currently supported.
%
% [email protected]
% [email protected]
function answer=floquet(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Get the Hamiltonian
[H,Q]=hamiltonian(assume(spin_system,assumptions));
% Apply frequency offsets
H=frqoffset(spin_system,H,parameters);
% Get relaxation and kinetics
R=relaxation(spin_system); K=kinetics(spin_system);
% Get the averaging grid
sph_grid=load([spin_system.sys.root_dir '/kernel/grids/' parameters.grid '.mat']);
% Get problem dimensions
spc_dim=2*parameters.max_rank+1; spn_dim=size(H,1);
report(spin_system,['lab space problem dimension ' num2str(spc_dim)]);
report(spin_system,['spin space problem dimension ' num2str(spn_dim)]);
report(spin_system,['Floquet problem dimension ' num2str(spc_dim*spn_dim)]);
parameters.spc_dim=spc_dim; parameters.spn_dim=spn_dim;
% Build the MAS part of the Liouvillian
M=2*pi*parameters.rate*kron(spdiags((parameters.max_rank:-1:-parameters.max_rank)',0,spc_dim,spc_dim),speye(spn_dim));
% Kron up relaxation and kinetics
R=kron(speye(spc_dim),R); K=kron(speye(spc_dim),K);
% Get the rotor orientation
[phi,theta,~]=cart2sph(parameters.axis(1),parameters.axis(2),parameters.axis(3));
theta=pi/2-theta; D_rot2lab=euler2wigner(phi,theta,0); D_lab2rot=D_rot2lab';
% Project states
P=spalloc(spc_dim,1,1); P((spc_dim+1)/2)=1;
if isfield(parameters,'rho0')
parameters.rho0=kron(P,parameters.rho0);
end
if isfield(parameters,'coil')
parameters.coil=kron(P,parameters.coil);
end
% Store problem dimension information
parameters.spc_dim=spc_dim; parameters.spn_dim=spn_dim;
% Estimate nonzero count
nnz_est=sum(sum(cellfun(@nnz,Q)));
% Preallocate answer array
ans_array=cell(numel(sph_grid.weights),1);
% Shut up and inform the user
report(spin_system,['powder average being computed over ' num2str(numel(sph_grid.weights)) ' orientations.']);
if ~isfield(parameters,'verbose')||(parameters.verbose==0)
report(spin_system,'pulse sequence has been silenced to avoid excessive output.');
spin_system.sys.output='hush';
end
% Powder averaged spectrum
parfor q=1:numel(sph_grid.weights) %#ok<*PFBNS>
% Set the crystal reference frame
D_mol2rot=euler2wigner(sph_grid.alphas(q),sph_grid.betas(q),sph_grid.gammas(q))';
% Move into rotor frame
D_mol2rot=D_rot2lab*D_mol2rot*D_lab2rot;
% Preallocate fourier terms
fourier_terms=cell(5,1);
% Get Fourier terms of the Hamiltonian
for n=1:5
fourier_terms{n}=spalloc(size(H,1),size(H,2),nnz_est);
D_rotor=zeros(5,5); D_rotor(n,n)=1;
D=D_rot2lab*D_rotor*D_lab2rot*D_mol2rot;
for m=1:5
for k=1:5
fourier_terms{n}=fourier_terms{n}+Q{k,m}*D(k,m);
end
end
end
% Add the isotropic part
fourier_terms{3}=fourier_terms{3}+H;
% Kron up into the Floquet space
F=spalloc(spc_dim*spn_dim,spc_dim*spn_dim,0);
for n=1:5
F=F+kron(spdiags(ones(spc_dim,1),n-3,spc_dim,spc_dim),fourier_terms{n});
end
% Add the MAS part and clean up
F=clean_up(spin_system,F+M,spin_system.tols.liouv_zero);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Run the pulse sequence
ans_array{q}=pulse_sequence(spin_system,parameters,F,R,K);
end
% Add up structures
answer=sph_grid.weights(1)*ans_array{1};
for n=2:numel(ans_array)
answer=answer+sph_grid.weights(n)*ans_array{n};
end
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency enforcement
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Rotating frames
if isfield(parameters,'rframes')
error('numerical rotating frame transformation is not supported by Floquet theory.');
end
% Formalism
if ~ismember(spin_system.bas.formalism,{'zeeman-liouv','sphten-liouv'})
error('this function is only available in Liouville space.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Rotor rank
if ~isfield(parameters,'max_rank')
error('parameters.max_rank subfield must be present.');
elseif (~isnumeric(parameters.max_rank))||(~isreal(parameters.max_rank))||...
(mod(parameters.max_rank,1)~=0)||(parameters.max_rank<0)
error('parameters.max_rank must be a positive real integer.');
end
% Spinning rate
if ~isfield(parameters,'rate')
error('parameters.rate subfield must be present.');
elseif (~isnumeric(parameters.rate))||(~isreal(parameters.rate))
error('parameters.rate must be a real number.');
end
% Spinning axis
if ~isfield(parameters,'axis')
error('parameters.axis subfield must be present.');
elseif (~isnumeric(parameters.axis))||(~isreal(parameters.axis))||...
(~isrow(parameters.axis))||(numel(parameters.axis)~=3)
error('parameters.axis must be a row vector of three real numbers.');
end
% Spherical grid
if ~isfield(parameters,'grid')
error('spherical averaging grid must be specified in parameters.grid variable.');
elseif isempty(parameters.grid)
error('parameters.grid variable cannot be empty.');
elseif ~ischar(parameters.grid)
error('parameters.grid variable must be a character string.');
elseif strcmp(parameters.grid,'single_crystal')
error('this module does not support single crystal simulations, use singlerot() instead.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
end
% If you've got a good idea then go ahead and do it. It's always
% easier to ask forgiveness than it is to get permission.
%
% Rear Admiral Grace Hopper
|
github
|
tsajed/nmr-pred-master
|
crystal.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/crystal.m
| 7,327 |
utf_8
|
a81332b76ec1a047239c55862e7fe2f9
|
% Single-crystal interface to pulse sequences. Generates a Liouvillian
% superoperator and passes it on to the pulse sequence function, which
% should be supplied as a handle. Syntax:
%
% answer=crystal(spin_system,pulse_sequence,parameters,assumptions)
%
% where pulse sequence is a function handle to one of the pulse sequences
% located in the experiments directory, assumptions is a string that would
% be passed to assume.m when the Hamiltonian is built and parameters is a
% structure with the following subfields:
%
% parameters.spins - a cell array giving the spins that
% the pulse sequence involves, e.g.
% {'1H','13C'}
%
% parameters.offset - a cell array giving transmitter off-
% sets in Hz on each of the spins listed
% in parameters.spins array
%
% parameters.orientation - a row vector of the three Euler angles
% (in radians) giving the orientation of
% the system relative to the input orien-
% tation.
%
% 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.
%
% Additional subfields may be required by the pulse sequence. The parameters
% structure is passed to the pulse sequence with the following additional
% parameters set:
%
% parameters.spc_dim - matrix dimension for the spatial
% dynamics subspace
%
% parameters.spn_dim - matrix dimension for the spin
% dynamics subspace
%
% This function returns whatever it is that the pulse sequence returns.
%
% [email protected]
function answer=crystal(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Set the secularity assumptions
spin_system=assume(spin_system,assumptions);
% Get the rotational expansion
[I,Q]=hamiltonian(spin_system);
% Apply the offsets
I=frqoffset(spin_system,I,parameters);
% Build the Hamiltonian
H=I+orientation(Q,parameters.orientation); H=(H+H')/2;
% Get carrier operators
C=cell(size(parameters.rframes));
for n=1:numel(parameters.rframes)
C{n}=carrier(spin_system,parameters.rframes{n}{1});
end
% Apply rotating frames
for k=1:numel(parameters.rframes)
H=rotframe(spin_system,C{k},H,parameters.rframes{k}{1},parameters.rframes{k}{2});
end
% Build relaxation and kinetics
R=relaxation(spin_system,parameters.orientation);
K=kinetics(spin_system);
% Get problem dimensions
parameters.spc_dim=1; parameters.spn_dim=size(H,1);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Call the pulse sequence
answer=pulse_sequence(spin_system,parameters,H,R,K);
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
if ~isfield(parameters,'rframes')
report(spin_system,'parameters.rframes field not set, assuming no additional rotating frame transformations.');
parameters.rframes={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency checking
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Orientation
if ~isfield(parameters,'orientation')
error('system orientation must be specified in parameters.orientation variable.');
elseif ~all(size(parameters.orientation)==[1 3])
error('parameters.orientation variable must be a row vector with three numbers.');
elseif ~isnumeric(parameters.orientation)
error('elements of parameters.orientation vector must be real numbers.');
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Rotating frame transformations
if ~isfield(parameters,'rframes')
error('parameters.rframes variable must be specified.');
elseif ~iscell(parameters.rframes)
error('parameters.rframes must be a cell array.');
end
for n=1:numel(parameters.rframes)
if ~iscell(parameters.rframes{n})
error('elements of parameters.rframes must be cell arrays.');
end
if numel(parameters.rframes{n})~=2
error('elements of parameters.rframes must have exactly two sub-elements each.');
end
if ~ischar(parameters.rframes{n}{1})
error('the first part of each element of parameters.rframes must be a character string.');
end
if ~ismember(parameters.rframes{n}{1},spin_system.comp.isotopes)
error('parameters.rframes refers to a spin that is not present in the system.');
end
if ~isnumeric(parameters.rframes{n}{2})
error('the second part of each element of parameters.rframes must be a number.');
end
end
end
% Why do they always teach us that it's easy and evil to do what we
% want and that we need discipline to restrain ourselves? It's the
% hardest thing in the world - to do what we want. And it takes the
% greatest kind of courage. I mean, what we really want.
%
% Ayn Rand, "The Fountainhead"
|
github
|
tsajed/nmr-pred-master
|
powder.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/powder.m
| 8,514 |
utf_8
|
7cce16925a809009ed290cb07740a8cb
|
% Powder interface to pulse sequences. Generates a Liouvillian super-
% operator, the initial state and the coil state, then passes them on
% to the pulse sequence function.
%
% This function supports parallel processing via Matlab's Distributed
% Computing Toolbox - different crystal orientations are evaluated on
% different labs. Arguments:
%
% pulse_sequence - pulse sequence function handle. See the
% experiments directory for the list of
% pulse sequences that ship with Spinach.
%
% parameters - a structure containing sequence-specific
% parameters. See the pulse sequence header
% for the list of parameters each sequence
% requires. The parameters that this inter-
% face itself requires are:
%
% parameters.spins - a cell array giving the
% spins that the pulse sequence works on, in
% the order of channels, e.g. {'1H','13C'}
%
% parameters.offset - a cell array giving
% transmitter offsets on each of the spins
% listed in parameters.spins.
%
% parameters.grid - name of the spherical
% averaging grid file (see the grids direc-
% tory in the kernel).
%
% assumptions - context-specific assumptions ('nmr', 'epr',
% 'labframe', etc.) - see the pulse sequence
% header for information on this setting.
%
% This function returns a powder average of whatever it is that the pul-
% se sequence returns. If a structure is returned by the pulse sequence,
% the structures are powder averaged field-by-field.
%
% [email protected]
% [email protected]
function answer=powder(spin_system,pulse_sequence,parameters,assumptions)
% Show the banner
banner(spin_system,'sequence_banner');
% Set common defaults
parameters=defaults(spin_system,parameters);
% Check consistency
grumble(spin_system,pulse_sequence,parameters,assumptions);
% Report to the user
report(spin_system,'building the Liouvillian...');
% Set the assumptions
spin_system=assume(spin_system,assumptions);
% Get the rotational expansion of the Hamiltonian
[I,Q]=hamiltonian(spin_system);
% Get kinetics superoperator
K=kinetics(spin_system);
% Add offsets to the isotropic part
I=frqoffset(spin_system,I,parameters);
% Get carrier operators
C=cell(size(parameters.rframes));
for n=1:numel(parameters.rframes)
C{n}=carrier(spin_system,parameters.rframes{n}{1});
end
% Get problem dimensions
parameters.spc_dim=1; parameters.spn_dim=size(I,1);
% Get the averaging grid as a struct
spherical_grid=load([spin_system.sys.root_dir '/kernel/grids/' parameters.grid],...
'alphas','betas','gammas','weights');
% Assign local variables
alphas=spherical_grid.alphas; betas=spherical_grid.betas;
gammas=spherical_grid.gammas; weights=spherical_grid.weights;
% Preallocate answer array
ans_array=cell(numel(weights),1);
% Shut up and inform the user
report(spin_system,['powder average being computed over ' num2str(numel(weights)) ' orientations.']);
if ~isfield(parameters,'verbose')||(parameters.verbose==0)
report(spin_system,'pulse sequence has been silenced to avoid excessive output.')
spin_system.sys.output='hush';
end
% Crunch orientations in parallel
parfor n=1:numel(weights)
% Get the full Hamiltonian at the current orientation
H=I+orientation(Q,[gammas(n) betas(n) alphas(n)]); H=(H+H')/2;
% Apply rotating frames
for k=1:numel(parameters.rframes) %#ok<PFBNS>
H=rotframe(spin_system,C{k},H,parameters.rframes{k}{1},parameters.rframes{k}{2}); %#ok<PFBNS>
end
% Get the relaxation superoperator at the current orientation
R=relaxation(spin_system,[gammas(n) betas(n) alphas(n)]);
% Report to the user
report(spin_system,'running the pulse sequence...');
% Run the simulation (it might return a structure)
ans_array{n}=pulse_sequence(spin_system,parameters,H,R,K); %#ok<PFBNS>
end
% Add up structures
answer=weights(1)*ans_array{1};
for n=2:numel(ans_array)
answer=answer+weights(n)*ans_array{n};
end
end
% Default parameters
function parameters=defaults(spin_system,parameters)
if ~isfield(parameters,'decouple')
report(spin_system,'parameters.decouple field not set, assuming no decoupling.');
parameters.decouple={};
end
if ~isfield(parameters,'rframes')
report(spin_system,'parameters.rframes field not set, assuming no additional rotating frame transformations.');
parameters.rframes={};
end
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,'verbose')
report(spin_system,'parameters.verbose field not set, silencing array operations.');
parameters.verbose=0;
end
end
% Consistency checking
function grumble(spin_system,pulse_sequence,parameters,assumptions)
% Spherical grid
if ~isfield(parameters,'grid')
error('spherical averaging grid must be specified in parameters.grid variable.');
elseif isempty(parameters.grid)
error('parameters.grid variable cannot be empty.');
elseif ~ischar(parameters.grid)
error('parameters.grid variable must be a character string.');
end
% Pulse sequence
if ~isa(pulse_sequence,'function_handle')
error('pulse_sequence argument must be a function handle.');
end
% Assumptions
if ~ischar(assumptions)
error('assumptions argument must be a character string.');
end
% Active spins
if isempty(parameters.spins)
error('parameters.spins variable cannot be empty.');
elseif ~iscell(parameters.spins)
error('parameters.spins variable must be a cell array.');
elseif ~all(cellfun(@ischar,parameters.spins))
error('all elements of parameters.spins cell array must be strings.');
elseif any(~ismember(parameters.spins,spin_system.comp.isotopes))
error('parameters.spins refers to a spin that is not present in the system.');
end
% Offsets
if isempty(parameters.offset)
error('parameters.offset variable cannot be empty.');
elseif ~isnumeric(parameters.offset)
error('parameters.offset variable must be an array of real numbers.');
elseif ~isfield(parameters,'spins')
error('parameters.spins variable must be specified alongside parameters.offset variable.');
elseif numel(parameters.offset)~=numel(parameters.spins)
error('parameters.offset variable must have the same number of elements as parameters.spins.');
end
% Rotating frame transformations
if ~isfield(parameters,'rframes')
error('parameters.rframes variable must be specified.');
elseif ~iscell(parameters.rframes)
error('parameters.rframes must be a cell array.');
end
for n=1:numel(parameters.rframes)
if ~iscell(parameters.rframes{n})
error('elements of parameters.rframes must be cell arrays.');
end
if numel(parameters.rframes{n})~=2
error('elements of parameters.rframes must have exactly two sub-elements each.');
end
if ~ischar(parameters.rframes{n}{1})
error('the first part of each element of parameters.rframes must be a character string.');
end
if ~ismember(parameters.rframes{n}{1},spin_system.comp.isotopes)
error('parameters.rframes refers to a spin that is not present in the system.');
end
if ~isnumeric(parameters.rframes{n}{2})
error('the second part of each element of parameters.rframes must be a number.');
end
end
end
% Do not confuse altruism with kindness. The irreducible primary of
% altruism is self-sacrifice - which means self-immolation, self-
% abnegation, self-denial. Do not hide behind such superficialities
% as whether you should or should not give a dime to a beggar. This
% is not the issue. The issue is whether you do or do not have the
% right to exist without giving him that dime. The issue is whether
% the need of others is the first mortgage on your life and the mo-
% ral purpose of your existence. Any man of self-esteem will answer:
% No. Altruism says: Yes.
%
% Ayn Rand
|
github
|
tsajed/nmr-pred-master
|
imaging.m
|
.m
|
nmr-pred-master/spinach/kernel/contexts/imaging.m
| 5,660 |
utf_8
|
ca7d80e75b1f4c5fb01b5c8cd16f89e7
|
% Generates spatially distributed dynamics operators. Syntax:
%
% [H,R,K,D,Gx,Gy,Gz,Fx,Fy,Fz]=imaging(H,Ph,K,Z,parameters)
%
% The following outputs are returned:
%
% H - spin Hamiltonian in the Fokker-Planck space
%
% R - spin relaxation superoperator in the Fokker-
% Planck space
%
% K - chemical kinetics superoperator in the Fokk-
% er-Planck space
%
% Gx,Gy,Gz - gradient operators (normalized for 1.0 T/m)
%
% D - diffusion operator (absorptive boundary con-
% conditions, normalized to 1.0 m^2/s)
%
% The following parameters must be provided:
%
% H - spin Hamiltonian commutation superoperator
% in Liouville space
%
% Ph - relaxation superoperators and their phantoms
% as {{R1,Ph1},{R2,Ph2},...}
%
% K - chemical kinetics superoperator in Liouvil-
% le space
%
% Z - normalized Zeeman Hamiltonian commutation
% superoperator in Liouville space(to be ob-
% tained from carrier.m and divided by the
% magnet field)
%
% parameters.dims - dimensions of the 3D box, meters
%
% parameters.npts - number of points in each dimension
% of the 3D box
%
% parameters.cond - {'fourier'} for Furier derivative operators;
% {'period',n} for n-point finite-difference
% operators with periodic boundary condition
%
% Note: gradients are assumed to be linear and centered on the
% middle of the sample.
%
% Note: the direct product order is Z(x)Y(x)X(x)Spin, this cor-
% responds to a column-wise vectorization of a 3D array
% with dimensions ordered as [X Y Z].
%
% [email protected]
% [email protected]
function [H,R,K,D,Gx,Gy,Gz,Fx,Fy,Fz]=imaging(H,Ph,K,Z,parameters)
% Adapt to the dimensionality
switch numel(parameters.npts)
case 1
% Call the hydrodynamics infrastructure
Fx=hydrodynamics(parameters); Fy=[]; Fz=[];
% Get the diffusion operator
D=-1i*Fx*Fx;
% Kron into Fokker-Planck space
Fx=kron(Fx,speye(size(Z)));
D=kron(D,speye(size(Z)));
% Generate normalized gradient operators
Gx=linspace(-0.5,0.5,parameters.npts(1));
Gx=spdiags(Gx',0,parameters.npts(1),parameters.npts(1));
Gx=parameters.dims(1)*kron(Gx,Z); Gy=[]; Gz=[];
case 2
% Call the hydrodynamics infrastructure
[Fx,Fy]=hydrodynamics(parameters); Fz=[];
% Get the diffusion operator
D=-1i*(Fx*Fx+Fy*Fy);
% Kron into Fokker-Planck space
Fx=kron(Fx,speye(size(Z)));
Fy=kron(Fy,speye(size(Z)));
D=kron(D,speye(size(Z)));
% Generate normalized gradient operators
IdX=speye(parameters.npts(1));
IdY=speye(parameters.npts(2));
Gx=linspace(-0.5,0.5,parameters.npts(1));
Gy=linspace(-0.5,0.5,parameters.npts(2));
Gx=spdiags(Gx',0,parameters.npts(1),parameters.npts(1));
Gy=spdiags(Gy',0,parameters.npts(2),parameters.npts(2));
Gx=parameters.dims(1)*kron(IdY,kron(Gx,Z));
Gy=parameters.dims(2)*kron(Gy,kron(IdX,Z)); Gz=[];
case 3
% Call the hydrodynamics infrastructure
[Fx,Fy,Fz]=hydrodynamics(parameters);
% Get the diffusion operator
D=-1i*(Fx*Fx+Fy*Fy+Fz*Fz);
% Kron into Fokker-Planck space
Fx=kron(Fx,speye(size(Z)));
Fy=kron(Fy,speye(size(Z)));
Fz=kron(Fz,speye(size(Z)));
D=kron(D,speye(size(Z)));
% Generate normalized gradient operators
IdX=speye(parameters.npts(1));
IdY=speye(parameters.npts(2));
IdZ=speye(parameters.npts(3));
Gx=linspace(-0.5,0.5,parameters.npts(1));
Gy=linspace(-0.5,0.5,parameters.npts(2));
Gz=linspace(-0.5,0.5,parameters.npts(3));
Gx=spdiags(Gx',0,parameters.npts(1),parameters.npts(1));
Gy=spdiags(Gy',0,parameters.npts(2),parameters.npts(2));
Gz=spdiags(Gz',0,parameters.npts(3),parameters.npts(3));
Gx=parameters.dims(1)*kron(IdZ,kron(IdY,kron(Gx,Z)));
Gy=parameters.dims(2)*kron(IdZ,kron(Gy,kron(IdX,Z)));
Gz=parameters.dims(3)*kron(Gz,kron(IdY,kron(IdX,Z)));
otherwise
% Complain and bomb out
error('incorrect number of spatial dimensions.');
end
% Project the infrastructure
H=kron(speye(prod(parameters.npts)),H);
K=kron(speye(prod(parameters.npts)),K);
% Preallocate relaxation matrix
R=spalloc(size(H,1),size(H,2),0);
% Build the relaxation matrix
if ~isempty(Ph)
for n=1:numel(Ph)
R=R+kron(spdiags(Ph{n}{2}(:),0,prod(parameters.npts),prod(parameters.npts)),Ph{n}{1});
end
end
end
% You have my sympathies with rotations theory - this is one of the
% most treacherous parts of spin dynamics. At the recent ENC, a guy
% approached Malcolm Levitt and declared that all rotation conventi-
% ons in his book are off by a sign. I could see Malcolm's face tur-
% ning white. Three hours later, when I completed my poster reading
% cycle and returned to Malcolm's poster, the two were still there,
% arguing heatedly over a laptop with Mathematica running. Somebody
% asked me what they were discussing. I said, "religion".
%
% IK's email to Fred Mentink-Vigier, 2014
|
github
|
tsajed/nmr-pred-master
|
ttclass_amensum.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_amensum.m
| 10,851 |
utf_8
|
32f7131d279f541862f1e4dededcda46
|
% Sums buffered tensor trains in a single tensor train by AMEn algorithm.
%
% y=ttclass_amensum(x, tol, opts)
%
% Input: x is a ttclass with buffered rank-one tensors
% tol is a relative tolerance parameter, e.g. 1.e-10.
% Output: y is a ttclass with a single tensor train, s.t.
% | x - y | < tol | x | in Frobenius norm
%
% [email protected]
% [email protected]
%
function y=ttclass_amensum(x, tol, opts)
% Parse opts parameters. We just populate what we do not have by defaults
if ~exist('opts','var')
opts = struct;
end
if ~isfield(opts, 'max_swp'); opts.max_swp=100; end
if ~isfield(opts, 'init_guess_rank'); opts.init_guess_rank=2; end
if ~isfield(opts, 'enrichment_rank'); opts.enrichment_rank=4; end
if ~isfield(opts, 'verb'); opts.verb=0; end
% Read tensor train sizes and ranks
[d,N]=size(x.cores);
sz=x.sizes;
rnk=x.ranks;
% Proceed a CP format and a sum of TT formats separately
if all(all(rnk==1))
% convert a ttclass to CP format
X=cell(d,1);
for k=1:d
X{k,1}=zeros(sz(k,1), sz(k,2),N);
for i=1:N
X{k,1}(:,:,i)=reshape(x.cores{k,i}, [sz(k,1),sz(k,2),1]);
end
end
% generate a random initial guess
y=rand(x, opts.init_guess_rank);
[y,~]=ttclass_ort(y,-1);
% generate a random enrichment
z=rand(x, opts.enrichment_rank);
[z,~]=ttclass_ort(z,-1);
% precompute interfaces of projections Y'X Z'X and Z'Y
yx = cell(d+1,1); yx{1}=ones(1,N); yx{d+1}=ones(N,1);
zx = cell(d+1,1); zx{1}=ones(1,N); zx{d+1}=ones(N,1);
zy = cell(d+1,1); zy{1}=1; zy{d+1}=1;
nrm = ones(d,1);
for k=d:-1:2
yx{k}=step_tt_by_cp(yx{k+1},y{k,1},X{k,1},-1);
zx{k}=step_tt_by_cp(zx{k+1},z{k,1},X{k,1},-1);
zy{k}=step_tt_by_tt(zy{k+1},z{k,1},y{k,1},-1);
nrm(k)=norm(yx{k},'fro');
if(nrm(k)>0)
yx{k}=yx{k}/nrm(k);
zx{k}=zx{k}/nrm(k);
end
end
% Set initial conditions
flipped=false;
satisfied=false;
iter=0;
while ~satisfied % Main iteration cycle
iter=iter+1;
% Read current ranks of approximation
ry=y.ranks;
rz=z.ranks;
sz=x.sizes;
% The difference between two consequitive iterations
largest_stepsize=0;
for k=1:d
% Solve local approximation problem
ynew=local_cp_to_tt(yx{k},yx{k+1},X{k,1},x.coeff);
nrm(k)=norm(ynew(:),'fro');
if (nrm(k)>0)
ynew=ynew/nrm(k);
else
nrm(k)=1;
end
% Check the convergence
relative_stepsize=norm(ynew(:)-y{k,1}(:))/norm(y{k,1}(:));
largest_stepsize=max(largest_stepsize, relative_stepsize);
if k<d
% Truncate the updated core
Y = reshape(ynew,[ry(k)*sz(k,1)*sz(k,2),ry(k+1)]);
[U,S,V] = svd(Y, 'econ');
S = diag(S);
rnew = ttclass_chop(S, tol*norm(S)/sqrt(d));
%r = min(r,rmax);
U = U(:,1:rnew);
V = diag(S(1:rnew))*V(:,1:rnew)';
ynew = U*V;
end
% Prepare error update and enrichment
if opts.enrichment_rank>0
% Compute new error core after truncation
% Project the truncated solution to the interface of Z
ynew = reshape(ynew, [ry(k)*sz(k,1)*sz(k,2)*ry(k+1), 1]);
ynew_enrich = reshape(ynew, [ry(k)*sz(k,1)*sz(k,2), ry(k+1)]);
ynew_enrich = ynew_enrich*zy{k+1};
% Save crys. We use it in the enrichment of the solution
yznew = reshape(ynew_enrich, [ry(k), sz(k,1)*sz(k,2)*rz(k+1)]);
yznew = zy{k}*yznew;
yznew = reshape(yznew, [rz(k)*sz(k,1)*sz(k,2)*rz(k+1), 1]);
znew = local_cp_to_tt(zx{k},zx{k+1},X{k,1},x.coeff);
znew = znew(:)/nrm(k) - yznew;
znew = reshape(znew, [rz(k)*sz(k,1)*sz(k,2), rz(k+1)]);
[znew,~]=qr(znew, 0);
rz(k+1) = size(znew, 2);
znew = reshape(znew, [rz(k),sz(k,1),sz(k,2),rz(k+1)]);
if k<d
% Compute the enrichment core
enrichment = local_cp_to_tt(yx{k},zx{k+1},X{k,1},x.coeff);
enrichment = enrichment(:)/nrm(k) - ynew_enrich(:);
enrichment = reshape(enrichment, [ry(k)*sz(k,1)*sz(k,2), rz(k+1)]);
% Enrich and orthogonalize the solution
U_enriched = [U, enrichment];
[U,R]=qr(U_enriched, 0);
R = R(:, 1:rnew);
V = R*V;
rnew = size(U,2);
end
end
if k<d
% Save the new block U
y.cores{k,1} = reshape(U, [ry(k),sz(k,1),sz(k,2),rnew]);
% Push the non-orthogonal factor forth the chain
next_core = reshape(y{k+1,1}, [ry(k+1), sz(k+1,1)*sz(k+1,2)*ry(k+2)]);
next_core = V*next_core;
y.cores{k+1,1} = reshape(next_core, [rnew,sz(k+1,1),sz(k+1,2),ry(k+2)]);
% Update the rank
ry(k+1)=rnew;
% Update the interfaces
yx{k+1}=step_tt_by_cp(yx{k},y{k,1},X{k,1},+1);
nrm(k)=norm(yx{k+1},'fro');
if (nrm(k)>0)
yx{k+1}=yx{k+1}/nrm(k);
end
if opts.enrichment_rank>0
zx{k+1}=step_tt_by_cp(zx{k},znew,X{k,1},+1);
zy{k+1}=step_tt_by_tt(zy{k},znew,y{k,1},+1);
if (nrm(k)>0)
zx{k+1}=zx{k+1}/nrm(k);
end
end
end
end
% Reverse the tensor trains
X = X(d:-1:1);
y=revert(y);
z=revert(z);
x=revert(x);
% ... and also the projections
yx(2:d) = yx(d:-1:2);
zx(2:d) = zx(d:-1:2);
zy(2:d) = zy(d:-1:2);
for k=2:d
yx{k} = yx{k}.';
zx{k} = zx{k}.';
zy{k} = zy{k}.';
end
nrm=nrm(d:-1:1);
% Mark that we are currently having a flipped TT
flipped = ~flipped;
% And exit only if the direction is correct
satisfied = (largest_stepsize<tol) && (iter<=opts.max_swp);
% Report if necessary
if opts.verb>0
str=sprintf('iter=%d, max_dx=%3.3e, max_r=%d\n',iter, largest_stepsize, max(y.ranks));
report(spin_system,str);
end
end
% Output in the ttclass format
if flipped
y=revert(y);
end
nrm=exp(sum(log(nrm))/d);
for k=1:d
y.cores{k,1}=nrm*y.cores{k,1};
end
y.tolerance=(nrm^d)*tol;
else
% sum of tensor trains
error('TT not ready yet');
end
end
function ttcore = local_cp_to_tt(left_interface,right_interface,cp,coeff)
% Read sizes
[r1,N1]=size(left_interface);
[N2,r2]=size(right_interface);
[sz1,sz2,Ncp]=size(cp);
[~,Ncf]=size(coeff);
if ~(N1==N2 && N2==Ncp && Ncp==Ncf)
error('CP ranks mismatch.');
end
N=Ncf;
% Contract left intefrace with CP data
left_interface=repmat(left_interface,[sz1*sz2,1]); % [r1*sz1*sz2, N]
cp=reshape(cp,[1,sz1*sz2*N]);
cp=repmat(cp,[r1,1]); % [r1,sz1*sz2*N]
cp=reshape(cp,[r1*sz1*sz2, N]);
left_interface=left_interface.*cp;
left_interface=reshape(left_interface,[r1*sz1*sz2,N]);
% Contract right interface with coeff vector
coeff=reshape(coeff,[N,1]);
coeff=repmat(coeff,[1,r2]);
right_interface=right_interface.*coeff; % [N,r2]
% Contract left and right interfaces
ttcore=left_interface*right_interface;
ttcore=reshape(ttcore,[r1,sz1,sz2,r2]);
end
function next_interface = step_tt_by_cp(interface, tt, cp, direction)
% Read sizes
[r1,sz1,sz2,r2] = size(tt);
[nn1,nn2,N] = size(cp);
if ~(sz1==nn1 && sz2==nn2)
error('sizes mismatch.');
end
switch direction
case +1 % Move one core to the right, compute next left interface
tt = reshape(tt, [r1, sz1*sz2*r2]);
interface = reshape(interface, [r1,N]);
next_interface = tt'*interface;
next_interface = reshape(next_interface, [sz1*sz2*r2, N]);
cp = reshape(cp, [sz1*sz2,N]);
cp = repmat(cp, [r2,1]);
next_interface = next_interface.*cp;
next_interface = reshape(next_interface, [sz1*sz2, r2*N]);
next_interface = sum(next_interface, 1);
next_interface = reshape(next_interface, [r2, N]);
case -1 % Move one core to the left, compute next right interface
tt = reshape(tt, [r1*sz1*sz2, r2]);
interface = reshape(interface, [N,r2]);
next_interface = interface*tt';
next_interface = reshape(next_interface, [N, r1*sz1*sz2]);
cp = reshape(cp, [sz1*sz2,N]);
cp = cp.';
cp = repmat(cp, [r1,1]);
cp = reshape(cp, [N, r1*sz1*sz2]);
next_interface = next_interface.*cp;
next_interface = reshape(next_interface, [N*r1, sz1*sz2]);
next_interface = sum(next_interface, 2);
next_interface = reshape(next_interface, [N, r1]);
otherwise
error('unrecognized direction.');
end
end
function next_interface = step_tt_by_tt(interface, ttx, tty, direction)
% Read sizes
[rx1,szx1,szx2,rx2] = size(ttx);
[ry1,szy1,szy2,ry2] = size(tty);
if ~(szx1==szy1 && szx2==szy2)
error('sizes mismatch.');
end
sz1=szx1; sz2=szx2;
switch direction
case +1 % Move one core to the right, compute next left interface
ttx = reshape(ttx, [rx1, sz1*sz2*rx2]);
tty = reshape(tty, [ry1*sz1*sz2, ry2]);
interface = reshape(interface, [rx1, ry1]);
next_interface = ttx'*interface;
next_interface = reshape(next_interface, [sz1*sz2, rx2*ry1]);
next_interface = next_interface.';
next_interface = reshape(next_interface, [rx2, ry1*sz1*sz2]);
next_interface = next_interface*tty;
next_interface = reshape(next_interface, [rx2, ry2]);
case -1 % Move one core to the left, compute next right interface
ttx = reshape(ttx, [rx1, sz1*sz2*rx2]);
tty = reshape(tty, [ry1*sz1*sz2, ry2]);
interface = reshape(interface, [ry2, rx2]);
next_interface = tty*interface;
next_interface = reshape(next_interface, [ry1, sz1*sz2*rx2]);
next_interface = next_interface*ttx';
next_interface = reshape(next_interface, [ry1, rx1]);
otherwise
error('unrecognized direction.');
end
end
|
github
|
tsajed/nmr-pred-master
|
ttclass_svd.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_svd.m
| 1,496 |
utf_8
|
51fd6a6e6abd1c75c8085b5e8dcb8457
|
% Performs TT-truncation (right-to-left) for a tensor train.
% Normally you should not call this subroutine directly.
%
% TTOUT=TTCLASS_SVD(TT)
%
% TT should contain a single tensor train, i.e. TT.ntrains=1.
% TT should be orthogonalised left-to-right, eg. by TTCLASS_ORT.
% TTOUT contains the same data approximated with lower TT-ranks.
% Approximation threshold is read from TT.tolerance (in Frobenius norm).
% TTOUT is return orthogonalised right-to-left.
%
% [email protected]
%
function ttout=ttclass_svd(tt)
% Read tensor ranks and dimensions
sz=tt.sizes;
rnk=tt.ranks;
d=tt.ncores;
N=tt.ntrains;
if N>1
error('Please sum all tensor trains before calling ttclass_svd');
end
% Preallocate the result
ttout=tt;
r=rnk(:,1);
% Define the relative approximation accuracy
eps=tt.tolerance(1,1)/tt.coeff(1,1);
eps=eps/sqrt(d);
% SVD cores right-to-left
for k=d:-1:2
C=reshape(ttout.cores{k,1}, [r(k), sz(k,1)*sz(k,2)*r(k+1)]);
B=reshape(ttout.cores{k-1,1}, [r(k-1)*sz(k-1,1)*sz(k-1,2), r(k)]);
[U,S,V]=svd(C,'econ');
S=diag(S);
rnew=ttclass_chop(S,eps*norm(S,'fro'));
U=U(:,1:rnew); S=S(1:rnew); V=V(:,1:rnew);
ttout.cores{k,1}=reshape(V', [rnew, sz(k,1), sz(k,2), r(k+1)]);
ttout.cores{k-1,1}=reshape(B*U*diag(S), [r(k-1), sz(k-1,1), sz(k-1,2), rnew]);
r(k)=rnew;
end
nrm=norm(ttout.cores{1,1}(:));
ttout.cores{1,1}=ttout.cores{1,1}/nrm;
ttout.coeff(1,1)=ttout.coeff(1,1)*nrm;
end
|
github
|
tsajed/nmr-pred-master
|
ttclass_sum.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_sum.m
| 1,353 |
utf_8
|
43e2237a406fe30867a50049f6b837f9
|
% This subroutine packs all trains from buffer to a single train.
% Normally you should not call it directly, use SHRINK instead.
%
% TTOUT=TTCLASS_SUM(TT)
%
% TT contains several buffered trains,
% TTOUT has one train with sum-of-ranks.
%
% [email protected]
%
function ttout=ttclass_sum(tt)
% Read tensor ranks and dimensions
sz=tt.sizes;
rnk=tt.ranks;
[d,N]=size(tt.cores);
% Fast return if possible
if N==1
ttout=tt;
return
end
% Total rank of all summands
R=sum(rnk,2);
R(1)=1; R(d+1)=1;
% Preallocate a single tensor train for all summands
core=cell(d,1);
for k=1:d
core{k}=zeros(R(k),sz(k,1),sz(k,2),R(k+1));
end
% Collect buffered trains in a single tensor train
rr=[zeros(d+1,1), cumsum(rnk,2)];
for n=1:N
if d>1
core{1,1}(1,:,:,rr(2,n)+1:rr(2,n+1))=tt.coeff(1,n)*tt.cores{1,n};
for k=2:d-1
core{k,1}(rr(k,n)+1:rr(k,n+1), :,:, rr(k+1,n)+1:rr(k+1,n+1))=tt.cores{k,n};
end
core{d,1}(rr(d,n)+1:rr(d,n+1),:,:,1)=tt.cores{d,n};
else
% Special case of one-site tensor trains
core{1,1}(1,:,:,1)=core{1,1}(1,:,:,1)+tt.coeff(1,n)*tt.cores{1,n};
end
end
% Construct empty ttclass array and fill the fields
ttout=ttclass;
ttout.coeff=1;
ttout.cores=core;
ttout.tolerance=abs(sum(tt.tolerance));
end
|
github
|
tsajed/nmr-pred-master
|
ttclass_amen_solve.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_amen_solve.m
| 18,579 |
utf_8
|
ed0bff477f38e79e4d9ae64abc3b3aa4
|
% Solves the linear system Ax=y using the AMEn iteration.
%
% x = amen_solve(A,y,tol,opts,x0)
%
% Input: A is a ttclass representing the square matrix;
% y is a ttclass representing the right hand side. Both A and y
% should have ntrains==1. Call shrink(A), shrink(y) if it is not
% the case.
% tol is the relative approximation and stopping tolerance (e.g. 1e-6).
% Output: x is a ttclass representing the solution such that
% |x-X| < tol |X| in Frobenius norm, where X is the exact solution.
% Optional input: opts is a structure of optional parameters;
% x0 is a ttclass representing the initial guess. It should
% have ntrains==1.
%
% [email protected]
% [email protected]
function x=ttclass_amen_solve(A,y,tol,opts,x0)
% Parse opts parameters. We just populate what we do not have by defaults
if ~exist('opts','var')
opts = struct;
end
% Maximal number of AMEn sweeps
if ~isfield(opts, 'nswp'); opts.nswp=20; end
% The rank of the initial guess, if it is not given as x0
if ~isfield(opts, 'init_guess_rank'); opts.init_guess_rank=2; end
% The rank of the residual and enrichment
if ~isfield(opts, 'enrichment_rank'); opts.enrichment_rank=4; end
% Local accuracy gap. If the iterative solver is used for local problems,
% it's stopping tolerance is set to (tol/sqrt(d))/resid_damp
if ~isfield(opts, 'resid_damp'); opts.resid_damp=2; end
% Maximal TT rank limit for the solution
if ~isfield(opts, 'rmax'); opts.rmax=Inf; end
% If the size of the local system is smaller than max_full_size, solve it
% directly, otherwise iteratively. Larger max_full_size gives higher
% accuracy, but may slow down the process.
if ~isfield(opts, 'max_full_size'); opts.max_full_size=500; end
% Maximal number of bicgstab iterations for local problems
if ~isfield(opts, 'local_iters'); opts.local_iters=100; end
% Verbocity level: silent (0), sweep info (1) or full info for each block (2).
if ~isfield(opts, 'verb'); opts.verb=1; end
% Check the initial guess
if ~exist('x0','var')
% Take initial guess at random
x0=rand(y, opts.init_guess_rank);
[x0,~]=ttclass_ort(x0,-1);
end
% Copy initial guess to the solution storage
x=x0;
% Check inputs for consistency
grumble(A,y,x);
% Read dimension and mode sizes
d=y.ncores; % dimension of the problem
sz=A.sizes; % mode sizes
sz=sz(:,1); % square matrix is assumed
% Clear coefficients from all data
A=clearcoeff(A);
y=clearcoeff(y);
x=clearcoeff(x);
% Initialize reductions of the system to the interfaces of the solution
reduction_XAX = cell(d+1,1); reduction_XAX{1}=1; reduction_XAX{d+1}=1;
reduction_XY = cell(d+1,1); reduction_XY{1}=1; reduction_XY{d+1}=1;
% If the residual is used, initialise its ranks and reductions
if opts.enrichment_rank>0
rz = [1;opts.enrichment_rank*ones(d-1,1);1];
% Reductions of the system to the interfaces of the residual
reduction_ZAX = cell(d+1,1); reduction_ZAX{1}=1; reduction_ZAX{d+1}=1;
reduction_ZY = cell(d+1,1); reduction_ZY{1}=1; reduction_ZY{d+1}=1;
end
% The TT truncation accumulates the error from a single step with the
% factor sqrt(d). Therefore, the tolerance should be adjusted to sqrt(d).
local_tolerance = tol/sqrt(d);
% Initialize some variables of the main loop
flipped = false; % It will mark that the TT formats are flipped
satisfied = false; % Check whether error or iteration stopping condition is hit
iter = 1; % The number of sweeps
% To prevent overflow, we keep the norms of A,y and x separately in the
% factored form
norm_x = ones(d-1,1); % norms of solution blocks
norm_yAx = ones(d-1,1); % Rescaling factors, equal to norm(y(i))/norm(A(i))/norm(x(i))
while ~satisfied % AMEn iteration, loop over sweeps
% Read TT ranks
ra=A.ranks; ry=y.ranks; rx=x.ranks;
maximal_error=0; % Maximal relative error and residual over the sweep
maximal_residual=0;
% Loop over cores
for k=d:-1:1
if ~flipped
% Iterating from d to 1, just orthogonalize the blocks
current_block = reshape(x.cores{k,1}, [rx(k), sz(k)*rx(k+1)]);
[v,u]=qr(current_block.', 0);
new_rx = size(v,2);
u = u.';
v = v.';
else
% Iterating from 1 to d, we update the solution
% Assemble the local right-hand side
current_rhs = local_vector(reduction_XY{k}, y.cores{k,1}, reduction_XY{k+1});
current_rhs = current_rhs*prod(norm_yAx);
% Read the initial guess -- the TT block from the prev. iteration
old_block = reshape(x.cores{k,1}, [rx(k)*sz(k)*rx(k+1),1]);
% Save the norm of the right-hand side
norm_rhs = norm(current_rhs);
% Read the matrix parts, accelerate a plenty of iterations with them
left_XAX = reduction_XAX{k};
current_A = A.cores{k,1};
right_XAX = reduction_XAX{k+1};
% Measure the previous residual
previous_Ax=local_matvec(old_block, left_XAX, current_A, right_XAX);
previous_residual = norm(current_rhs-previous_Ax)/norm_rhs;
if (rx(k)*sz(k)*rx(k+1)<opts.max_full_size)
% If the system size is small, assemble the full system and solve directly
current_matrix = local_matrix(left_XAX, current_A, right_XAX);
current_block = current_matrix\current_rhs;
% Report if verbocity is >1
if (opts.verb>1)
fprintf('amen_solve: swp=%d, i=%d. Backslash. ', iter, k);
end
else
% System is large, solve iteratively
% Extract the number of local iterations wisely
local_iters = opts.local_iters;
if (numel(local_iters)>1)
local_iters = local_iters(k);
end
% Run the bicgstab with the matrix defined by the structured MatVec
[current_block,~,bicg_res,bicg_iters] = bicgstab(...
@(x)local_matvec(x, left_XAX, current_A, right_XAX),...
current_rhs, max(local_tolerance/opts.resid_damp,eps*2), local_iters, [], [], old_block);
% Report to user
if (opts.verb>1)
fprintf('amen_solve: iter=%d, i=%d. Bicgstab: %g iters, residual %3.3e. ', iter, k, bicg_iters, bicg_res);
end
end
% Measure the error
local_error = norm(current_block-old_block)/norm(current_block);
% Update the worst errors
maximal_error = max(maximal_error, local_error);
maximal_residual = max(maximal_residual, previous_residual);
% Reshape the block for the truncation
current_block = reshape(current_block, [rx(k), sz(k)*rx(k+1)]);
% Truncation
if k>1
% Compute the SVD
[u,s,v] = svd(current_block,'econ');
s = diag(s);
% Select the rank based on Fro-norm thresholding
new_rx = ttclass_chop(s,local_tolerance*norm(s));
% Limit the rank to rmax
new_rx = min(new_rx, opts.rmax);
% Shrink SVD factors to r
% U*S will be cast to the neighbouring block
u = u(:,1:new_rx)*diag(s(1:new_rx));
% The current block will be left orthogonal
v = v(:,1:new_rx)';
% Save the truncated solution to compute the residual later
current_block = u*v;
% Report the chosen rank
if (opts.verb>1)
fprintf('Rank: %d. \n', new_rx);
end
end
% Copy the new block to the main storage
x.cores{k} = reshape(current_block, rx(k), sz(k), 1, rx(k+1));
end
% Update the residual z
if (opts.enrichment_rank>0)
if iter==1
% In the first sweep, there are no reductions yet.
% Just initialize z by random
zblock = randn(rz(k), sz(k)*rz(k+1));
else
% In higher sweeps, the reductions are computed, and we can
% evaluate new Z.
% Project y via the reductions onto the Z interface
zblock_y = local_vector(reduction_ZY{k}, y.cores{k,1}, reduction_ZY{k+1});
zblock_y = zblock_y*prod(norm_yAx);
% Project Ax
zblock_Ax = local_matvec(x.cores{k,1}, reduction_ZAX{k}, A.cores{k,1}, reduction_ZAX{k+1});
% z=y-Ax projected to Z
zblock = zblock_y-zblock_Ax;
end
% Reshape zblock for the orthogonalization
zblock = reshape(zblock, [rz(k), sz(k)*rz(k+1)]);
[zblock,~]=qr(zblock.', 0);
zblock = zblock.';
% Careful: store the old rank of z, since it is that will be used
% in the solution enrichment, not the updated value after the QR
old_rz = rz(k);
% Now replace it
rz(k) = size(zblock,1);
zblock = reshape(zblock, [rz(k), sz(k), 1, rz(k+1)]);
end;
if k>1
% Apply enrichment for the solution
if (opts.enrichment_rank>0)&&(iter>1)&&(flipped)
% The enrichment uses a mixed interface: the one of Z on
% the left, but the one of X on the right, since it must
% concatenate with the solution block.
% First, project y to Z-I-X
zblock_y = local_vector(reduction_ZY{k}, y.cores{k,1}, reduction_XY{k+1});
zblock_y = zblock_y*prod(norm_yAx);
% Project Ax to Z-I-X
zblock_Ax = local_matvec(x.cores{k,1}, reduction_ZAX{k}, A.cores{k,1}, reduction_XAX{k+1});
% z=y-Ax projected to Z-I-X
enrichment_block = zblock_y-zblock_Ax;
enrichment_block = reshape(enrichment_block, [old_rz, sz(k)*rx(k+1)]);
% Enrichment is made here
v2 = [v; enrichment_block];
v2 = v2.';
[v,rv]=qr(v2, 0);
v = v.';
% Pass the L-factor to the next block
rv = rv(:,1:new_rx);
u = u*rv.';
% Update the current solution rank
new_rx = size(v,1);
end
% Measure and remove the norm of u
new_norm_x = norm(u, 'fro');
if (new_norm_x>0)
u = u/new_norm_x;
else
new_norm_x=1;
end;
% Store it in norm_x
norm_x(k-1)=norm_x(k-1)*new_norm_x;
% Calculate the White's prediction for the next block by
% casting u onto it
next_block = x.cores{k-1,1};
next_block = reshape(next_block, [rx(k-1)*sz(k-1), rx(k)]);
next_block = next_block*u;
% Copy the rank
rx(k) = new_rx;
x.cores{k-1,1} = reshape(next_block, rx(k-1), sz(k-1),1, rx(k)); % now it is a good initial guess
% Copy the orthogonal current block to the storage
v = reshape(v, [rx(k), sz(k),1, rx(k+1)]);
x.cores{k,1} = v;
% Compute next interface reductions
% With X
[reduction_XAX{k},norm_A] = reduce_matrix(reduction_XAX{k+1}, v, A.cores{k,1}, v);
[reduction_XY{k},norm_y] = reduce_vector(reduction_XY{k+1}, v, y.cores{k,1});
% With Z
if (opts.enrichment_rank>0)
reduction_ZAX{k} = reduce_matrix(reduction_ZAX{k+1}, zblock, A.cores{k,1}, v);
reduction_ZY{k} = reduce_vector(reduction_ZY{k+1}, zblock, y.cores{k,1});
% Remove the norm of A and y
reduction_ZAX{k} = reduction_ZAX{k}/norm_A;
reduction_ZY{k} = reduction_ZY{k}/norm_y;
end
% Compute the new rescaling factor
norm_yAx(k-1) = (norm_y/(norm_A*norm_x(k-1)));
end
end % end of the loop over blocks
% Flip reductions
reduction_XAX = revert_interface(reduction_XAX, ra, rx, rx);
reduction_XY = revert_interface(reduction_XY, ry, rx);
if (opts.enrichment_rank>0)
reduction_ZAX = revert_interface(reduction_ZAX, ra, rz, rx);
reduction_ZY = revert_interface(reduction_ZY, ry, rz);
% Flip the ranks of Z
rz = rz(d+1:-1:1, :);
end
% Flip tensor trains
y=revert(y);
A=revert(A);
x=revert(x);
% Flip the sizes and norms
sz=sz(d:-1:1);
norm_x = norm_x(d-1:-1:1);
norm_yAx = norm_yAx(d-1:-1:1);
flipped = ~flipped;
% Report sweep info
if (opts.verb>0)&&(~flipped)
fprintf('amen_solve: iter=%d, err=%3.3e, res=%3.3e, rank=%d\n', iter, maximal_error, maximal_residual, max(rx));
end
% Check the stopping criteria
satisfied = ((maximal_error<tol)||(iter>=opts.nswp))&&(~flipped);
% Count the number of sweeps
if ~flipped
iter = iter+1;
end
end
% Cast spatial solution to the desired form
rx = x.ranks;
norm_x = exp(sum(log(norm_x))/d); % distribute norms equally
for k=1:d
x.cores{k,1} = reshape(x.cores{k,1}, [rx(k), sz(k), 1, rx(k+1)]); % store the sizes in
x.cores{k,1} = x.cores{k,1}*norm_x;
end
x.coeff=1;
x.tolerance=(norm_x^d)*tol;
end
%%%%%%%%% Auxiliary functions
function grumble(A,y,x0)
% Check the inputs for consistency
if ~isa(A,'ttclass') || ~isa(y,'ttclass')
error('Both matrix and right-hand-side should be ttclass.');
end
if A.ncores~=y.ncores
error('Dimensions of matrix and right-hand-side do not match.');
end
if A.ntrains>1 || y.ntrains>1
error('Both matrix and right-hand-side should be shrinked before solution.');
end
d=A.ntrains;
szA=A.sizes;
if ~all(szA(:,1)==szA(:,2))
error('Matrix should be square.');
end
szy=y.sizes;
if ~all(szy(:,1)==szA(:,2))
error('Mode sizes of the right-hand-side do not match those of the matrix.')
end
if ~all(szy(:,2)==ones(d,1))
error('The right-hand-side should be a vector.')
end
if exist('x0','var')
% Check the initial guess, if present
if A.ncores~=x0.ncores
error('Dimensions of matrix and initial guess do not match.');
end
szx=x0.sizes;
if ~all(szx(:,1)==szA(:,2))
error('Mode sizes of the initial guess do not match those of the matrix.')
end
if ~all(szx(:,2)==ones(d,1))
error('The initial guess should be a vector.')
end
end
end
% Takes right reductions of sizes (ra x rw x rx), and flips them to the left
% form (rw x rx x ra). Note: ranks should be given in the initial order.
function [interface] = revert_interface(interface, ra, rw, rx)
d = numel(interface)-1; % We trust it to come with R==1
if (nargin<4)
rx = ones(size(rw));
end;
for i=1:d
interface{i} = reshape(interface{i}, ra(i), rw(i)*rx(i));
interface{i} = interface{i}.';
if (nargin>3)
interface{i} = reshape(interface{i}, rw(i), rx(i), ra(i));
end;
end;
interface = interface(d+1:-1:1);
end
% Accumulates the right interface reduction of the matrix, W{k:d}'*A{k:d}*X{k:d}
function [interface,nrm] = reduce_matrix(interface, w, A, x)
% Right reduction has the form of the last matrix TT block, i.e. [ra, rw, rx]
[ra1,n,m,ra2]=size(A);
[rx1,~,~,rx2]=size(x);
[rw1,~,~,rw2]=size(w);
wc = reshape(w, rw1, n*rw2);
wc = conj(wc);
xc = reshape(x, rx1*m, rx2);
interface = reshape(interface, ra2*rw2, rx2);
interface = xc*interface.'; % size rx1 m x ra2 rw2
interface = reshape(interface, rx1, m*ra2*rw2);
interface = interface.';
interface = reshape(interface, m*ra2, rw2*rx1);
tmp = reshape(A, ra1*n, m*ra2);
interface = tmp*interface; % size ra1(k)*n, rw2*rx1
interface = reshape(interface, ra1, n*rw2*rx1);
interface = interface.';
interface = reshape(interface, n*rw2, rx1*ra1);
interface = wc*interface; % size rw1, rx1 ra1
interface = reshape(interface, rw1*rx1, ra1);
interface = interface.';
if (nargout>1)
nrm = norm(interface, 'fro');
interface = interface/nrm;
end
interface = reshape(interface, ra1, rw1, rx1);
end
% Accumulates the right interface reduction of the vector, W{k:d}'*X{k:d}
function [interface,nrm] = reduce_vector(interface, w, x)
% Right reduction has the form of the last vector TT block, i.e. [rx, rw]
[rw1,n,~,rw2]=size(w);
[rx1,~,~,rx2]=size(x);
wc = reshape(w, rw1, n*rw2);
tmp = reshape(x, rx1*n, rx2);
interface = tmp*interface; % size rx1 n x rw2
interface = reshape(interface, rx1, n*rw2);
interface = interface*wc'; % size rx1, rw1
if (nargout>1)
nrm = norm(interface, 'fro');
interface = interface/nrm;
end
end
% A matrix-vectors product for the matrix in the 3D TT (WAX1-A-WAX2), and
% full vectors of size (rx1*m*rx2). Returns (rw1*n*rw2)
function w=local_matvec(x, left_WAX, A, right_WAX)
[ra1,n,m,ra2]=size(A);
[rw1,rx1,~] = size(left_WAX);
[~,rw2,rx2] = size(right_WAX);
xc = reshape(x, [rx1*m, rx2]);
tmp = reshape(right_WAX, [ra2*rw2, rx2]);
w = xc*tmp.';
w = reshape(w, rx1, m*ra2*rw2);
w = w.';
w = reshape(w, m*ra2, rw2*rx1);
tmp = reshape(A, ra1*n, m*ra2);
w = tmp*w;
w = reshape(w, ra1*n*rw2, rx1);
w = w.';
w = reshape(w, rx1*ra1, n*rw2);
tmp = reshape(left_WAX, rw1, rx1*ra1);
w = tmp*w;
w = reshape(w, rw1*n*rw2, 1);
end
% Builds the full (rw1*n*rw2) x (rx1*m*rx2) matrix from its TT blocks
function B=local_matrix(left_WAX, A, right_WAX)
[ra1,n,m,ra2]=size(A);
[rw1,rx1,~] = size(left_WAX);
[~,rw2,rx2] = size(right_WAX);
B = reshape(left_WAX, [rw1*rx1, ra1]);
tmp = reshape(A, [ra1, n*m*ra2]);
B = B*tmp;
B = reshape(B, [rw1, rx1, n, m*ra2]);
B = permute(B, [1,3,2,4]);
B = reshape(B, [rw1*n*rx1*m, ra2]);
tmp = reshape(right_WAX, [ra2, rw2*rx2]);
B = B*tmp;
B = reshape(B, [rw1*n, rx1*m, rw2, rx2]);
B = permute(B, [1,3,2,4]);
B = reshape(B, [rw1*n*rw2, rx1*m*rx2]);
end
% Builds the full (rw1*n*rw2) x 1 vector from its TT blocks
function w=local_vector(left_WX, x, right_WX)
[rx1,n,~,rx2]=size(x);
[rw1,~] = size(left_WX);
[~,rw2] = size(right_WX);
w = reshape(x, [rx1, n*rx2]);
w = left_WX*w;
w = reshape(w, [rw1*n, rx2]);
w = w*right_WX;
w = reshape(w, [rw1*n*rw2, 1]);
end
|
github
|
tsajed/nmr-pred-master
|
ttclass_chop.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_chop.m
| 519 |
utf_8
|
8e97b25f14afdbf8d63e19ddc677e366
|
% This subroutine defines a rank of truncated SVD decomposition
% Normal users whould not call it directly.
%
% R=TTCLASS_CHOP(S,TOLERANCE)
%
% Here S is a vector od singular values for a matrix,
% TOLERANCE is absolute truncation threshold (Frobenius norm).
% Returns the optimal rank of low-rank approximation.
%
% [email protected]
%
function r=ttclass_chop(s,tolerance)
x=cumsum(s(end:-1:1).^2);
k=find(x>=tolerance^2,1);
if isempty(k)
r=0;
else
r=numel(s)-k+1;
end
end
|
github
|
tsajed/nmr-pred-master
|
ttclass_ort.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_ort.m
| 3,819 |
utf_8
|
5de9198609fad42b00d0a1379c98a58f
|
% Performs TT-orthogonalisation for all trains from buffer.
% DIR=+1 {default} gives you left-to-right orthogonality,
% DIR=-1 right-to-left
% Normally you should not call this subroutine directly.
%
% TT=TTCLASS_ORT(TT,DIR)
% [TT,LOGNRM]=TTCLASS_ORT(TT,DIR)
%
% On input, TT contains several buffered trains,
% On output, TT has all of them orthogonalised left-to-right.
% If LOGNRM is present, all buffered trains are also normalized,
% and natural logarithms of their norms returned in the vector LOGNRM.
% Use this option if the tensor norm is likely to exceed realmax()=1.7977e+308.
%
% [email protected]
%
function [tt,lognrm]=ttclass_ort(tt,dir)
% Read tensor ranks and dimensions
sz=tt.sizes;
rnk=tt.ranks;
d=tt.ncores;
N=tt.ntrains;
% Set the default dir if it is not present
if ~exist('dir','var')
dir=+1;
end
if (nargout>1)
lognrm=log(tt.coeff);
tt.coeff=ones(1,N);
end
switch dir
case +1
for n=1:N
% TT-othogonalise each tensor train left-to-right
r=rnk(:,n);
for k=1:d-1
B=reshape(tt.cores{k,n}, [r(k)*sz(k,1)*sz(k,2), r(k+1)]);
C=reshape(tt.cores{k+1,n}, [r(k+1), sz(k+1,1)*sz(k+1,2)*r(k+2)]);
[Q,R]=qr(B,0);
nrm=norm(R);
% Take care of the norm
if (nrm>0)
R=R/nrm;
if (nargout>1)
lognrm(1,n)=lognrm(1,n)+log(nrm);
else
tt.coeff(1,n)=tt.coeff(1,n)*nrm;
end
end
C=R*C;
rnew=size(Q,2);
tt.cores{k,n}=reshape(Q, [r(k), sz(k,1), sz(k,2), rnew]);
tt.cores{k+1,n}=reshape(C, [rnew, sz(k+1,1), sz(k+1,2), r(k+2)]);
r(k+1)=rnew;
end
% Take care of the last norm
nrm=norm(tt.cores{d,n}(:));
if (nrm>0)
tt.cores{d,n}=tt.cores{d,n}/nrm;
if (nargout>1)
lognrm(1,n)=lognrm(1,n)+log(nrm);
else
tt.coeff(1,n)=tt.coeff(1,n)*nrm;
end
end
end
case -1
for n=1:tt.ntrains
% TT-othogonalise each tensor train lright-to-left
r=rnk(:,n);
for k=d:-1:2
B=reshape(tt.cores{k,n}, [r(k), sz(k,1)*sz(k,2)*r(k+1)]);
C=reshape(tt.cores{k-1,n}, [r(k-1)*sz(k-1,1)*sz(k-1,2), r(k)]);
[Q,R]=qr(B.',0);
nrm=norm(R);
% Take care of the norm
if (nrm>0)
R=R/nrm;
if (nargout>1)
lognrm(1,n)=lognrm(1,n)+log(nrm);
else
tt.coeff(1,n)=tt.coeff(1,n)*nrm;
end
end
C=C*R.';
rnew=size(Q,2);
tt.cores{k,n}=reshape(Q.', [rnew, sz(k,1), sz(k,2), r(k+1)]);
tt.cores{k-1,n}=reshape(C, [r(k-1), sz(k-1,1), sz(k-1,2), rnew]);
r(k)=rnew;
end
% Take care of the last norm
nrm=norm(tt.cores{1,n}(:));
if (nrm>0)
tt.cores{1,n}=tt.cores{1,n}/nrm;
if (nargout>1)
lognrm(1,n)=lognrm(1,n)+log(nrm);
else
tt.coeff(1,n)=tt.coeff(1,n)*nrm;
end
end
end
otherwise
error('unrecognized parameter dir.');
end
end
|
github
|
tsajed/nmr-pred-master
|
ttclass_numel.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/ttclass_numel.m
| 710 |
utf_8
|
97f60f8e3294823ceb4f59353f1ba9d1
|
% Number of elements in the matrix represented by a tensor train.
% Syntax:
% n=ttclass_numel(ttrain)
%
% For large spin systems it may be too large to fit the integer.
%
% [email protected]
% [email protected]
function n=ttclass_numel(ttrain)
% Compute the number of elements
if isa(ttrain,'ttclass')
n=prod(prod(sizes(ttrain)));
else
error('this function only applies to tensor trains.');
end
% Check for infinities
if n>intmax
error('the number of elements exceeds Matlab''s intmax.');
end
end
% If it had been possible to build the tower of Babel without
% ascending it, the work would have been permitted.
%
% Franz Kafka
|
github
|
tsajed/nmr-pred-master
|
plus.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@struct/plus.m
| 1,073 |
utf_8
|
93460242fd0dd5c04ff3062211674a88
|
% Adds corresponding fields of two structures. Nested structu-
% res are processed recursively. Syntax:
%
% output_structure=plus(structure1,structure2)
%
% [email protected]
% [email protected]
function str3=plus(str1,str2)
% Decide how to proceed
if isstruct(str1)&&isstruct(str2)
% Get the field names
fnames1=fieldnames(str1); fnames2=fieldnames(str2);
% Check topology
if (numel(fnames1)~=numel(fnames2))||...
(~isempty(setdiff(fnames1,fnames2)))
error('structure topology mismatch.');
end
% Loop over field names
for n=1:length(fnames1)
% Recursive call for each field name
str3.(fnames1{n})=str1.(fnames1{n})+str2.(fnames1{n});
end
else
% Complain and bomb out
error('structure topology mismatch.');
end
end
% He was the sort of person who stood on mountaintops during
% thunderstorms in wet copper armour shouting "All the Gods
% are bastards!"
%
% Terry Pratchett
|
github
|
tsajed/nmr-pred-master
|
mtimes.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@struct/mtimes.m
| 956 |
utf_8
|
5601726df09404a4212637629b5dc5e3
|
% Multiplies all entries of a structure by a user-specified
% scalar. Nested structures are processed recursively. Syntax:
%
% output_structure=mtimes(scalar,input_structure)
%
% [email protected]
% [email protected]
function str_out=mtimes(scalar,str_in)
% Decide how to proceed
if isscalar(scalar)
% Get the field names
fnames=fieldnames(str_in);
% Loop over field names
for n=1:numel(fnames)
% Recursive call for each field name
str_out.(fnames{n})=scalar*str_in.(fnames{n});
end
else
% Complain and bomb out
error('the first argument must be a scalar.');
end
end
% Arthur Dent: What happens if I press this button?
% Ford Prefect: I wouldn't --
% Arthur Dent: Oh.
% Ford Prefect: What happened?
% Arthur Dent: A sign lit up, saying "please do not press this button again".
%
% Douglas Adams
|
github
|
tsajed/nmr-pred-master
|
plus.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@cell/plus.m
| 940 |
utf_8
|
31149a14aaee466b40fb00c288f42050
|
% Adds cell arrays element-by-element.
%
% [email protected]
function A=plus(A,B)
if iscell(A)&&iscell(B)&&all(size(A)==size(B))
for n=1:numel(A), A{n}=A{n}+B{n}; end
else
error('cell array sizes must match.');
end
end
% I came into the room, which was half dark, and presently spotted Lord
% Kelvin in the audience and realized that I was in for trouble at the last
% part of my speech dealing with the age of the Earth, where my views
% conflicted with his. To my relief, Kelvin fell fast asleep, but as I
% came to the important point, I saw the old bird sit up, open an eye and
% cock a baleful glance at me! Then a sudden inspiration came, and I said
% "Lord Kelvin had limited the age of the Earth, provided no new source of
% energy was discovered. That prophetic utterance refers to what we are
% now considering tonight, radium." Behold! The old boy beamed upon me.
%
% Ernest Rutherford
|
github
|
tsajed/nmr-pred-master
|
mtimes.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@cell/mtimes.m
| 543 |
utf_8
|
beb0e6df02028c9a678196badbcc4752
|
% Element-by-element multiplication of cell arrays of matrices.
%
% [email protected]
function C=mtimes(A,B)
if iscell(A)&&isnumeric(B)
C=cell(size(A)); for n=1:numel(A), C{n}=A{n}*B; end
elseif isnumeric(A)&&iscell(B)
C=cell(size(B)); for n=1:numel(B), C{n}=A*B{n}; end
else
error('at least one argument must be numeric.');
end
end
% We keep blaming Comrade Stalin and I agree that we have good reasons. But
% I would like to ask: who wrote those four million denunciation letters?
%
% S.D. Dovlatov
|
github
|
tsajed/nmr-pred-master
|
minus.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@cell/minus.m
| 300 |
utf_8
|
a452a40098a0deee00f05329e7fdf193
|
% Subtracts cell arrays element-by-element.
%
% [email protected]
function A=minus(A,B)
if iscell(A)&&iscell(B)&&all(size(A)==size(B))
for n=1:numel(A), A{n}=A{n}-B{n}; end
else
error('cell array sizes must match.');
end
end
% I can, therefore I am.
%
% Simone Weil
|
github
|
tsajed/nmr-pred-master
|
dot.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/dot.m
| 634 |
utf_8
|
4ed315ade74c2a8170df6bb02b79f71e
|
% Dot product of TT representations of matrices. Syntax:
%
% c=dot(a,b)
%
% [email protected]
% [email protected]
function c=dot(a,b)
% Check consistency
grumble(a,b);
% Compute the product
c=ctranspose(a)*b;
end
% Consistency enforcement
function grumble(a,b)
if (~isa(a,'ttclass'))||(~isa(b,'ttclass'))
error('both inputs should be tensor trains.')
end
if (size(a.cores,1)~=size(b.cores,1))||(~all(all(sizes(a)==sizes(b))))
error('tensor train structures must be consistent.')
end
end
% Any product that needs a manual to work is broken.
%
% Elon Musk
|
github
|
tsajed/nmr-pred-master
|
norm.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/norm.m
| 1,584 |
utf_8
|
6816c18c41f538aa0adf11e09a1d1402
|
% Computes the norm of the matrix represented by a tensor train. Syntax:
%
% ttnorm=norm(ttrain,norm_type)
%
% norm_type=1 returns the 1-norm
% norm_type=inf returns the inf-norm
% norm_type=2 returns the 2-norm
% norm_type='fro' returns the Frobenius norm
%
% Note: norms other than Frobenius norm are expensive for tensor trains.
%
% [email protected]
% [email protected]
function ttnorm=norm(ttrain,norm_type)
% The default option is TYP=1
if (nargin == 1); norm_type=1; end
% Compute the norm
switch norm_type
case 'fro'
% Frobenius norm
ttrain=ttclass_sum(ttrain);
ttrain=ttclass_ort(ttrain,-1);
ttnorm=abs(ttrain.coeff)*norm(ttrain.cores{1,1}(:));
case 1
% Maximum absolute column sum
error('1-norm is not yet implemented for ttclass');
case inf
% Maximum absolute row sum
error('inf-norm is not yet implemented for ttclass');
case 2
% Maximum absolute eigenvalue
error('2-norm is not yet implemented for ttclass');
otherwise
% Complain and bomb out
error('unrecognized norm type.');
end
end
% The most exciting phrase to hear in science, the one that heralds new
% discoveries, is not "eureka!" but rather "hmm....that's funny..."
%
% Isaac Asimov
%
%
% Contrary to what Asimov says, the most exciting phrase in science, the
% one that heralds new discoveries, is not "eureka!" or "that's funny...",
% it's "your research grant has been approved".
%
% John Alejandro King
|
github
|
tsajed/nmr-pred-master
|
kron.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/kron.m
| 2,068 |
utf_8
|
c00292ef772aa5660ba73b7164905922
|
% Kronecker product of two matrices in a tensor train format. Syntax:
%
% c=kron(a,b)
%
% WARNING: the result is not the same as the flat matrix Kronecker pro-
% duct (it is a row and column permutation away from it), but
% the resulting order of elements is consistent with the out-
% put of the tensor train vectorization (ttclass/vec) operati-
% on output.
%
% [email protected]
% [email protected]
function c=kron(a,b)
% Shrink a and b before going any further
a=shrink(a); b=shrink(b);
% Read sizes and ranks of the operands
[a_ncores,~]=size(a.cores); a_ranks=ranks(a); a_sizes=sizes(a);
[b_ncores,~]=size(b.cores); b_ranks=ranks(b); b_sizes=sizes(b);
% Check consistency
if a_ncores~=b_ncores
error('tensor train structures must be consistent.');
end
% Preallocate the result
new_cores=cell(a_ncores,1);
% Kron the cores
for nc=1:a_ncores
core_of_a=reshape(a.cores{nc,1},[a_ranks(nc,1)*a_sizes(nc,1),a_sizes(nc,2)*a_ranks(nc+1,1)]);
core_of_b=reshape(b.cores{nc,1},[b_ranks(nc,1)*b_sizes(nc,1),b_sizes(nc,2)*b_ranks(nc+1,1)]);
core_of_c=reshape(kron(core_of_b,core_of_a),[a_ranks(nc,1),a_sizes(nc,1),b_ranks(nc,1),b_sizes(nc,1),a_sizes(nc,2),a_ranks(nc+1,1),b_sizes(nc,2),b_ranks(nc+1,1)]);
new_cores{nc,1}=reshape(permute(core_of_c,[1 3 4 2 7 5 6 8]),[a_ranks(nc,1)*b_ranks(nc,1),b_sizes(nc,1)*a_sizes(nc,1),b_sizes(nc,2)*a_sizes(nc,2),a_ranks(nc+1,1)*b_ranks(nc+1,1)]);
end
% Write the output data structure
c=ttclass; c.coeff=b.coeff*a.coeff;
c.cores=reshape(new_cores,[a_ncores,1]);
if a.coeff==0 || b.coeff==0
% The result is exactly zero
c.tolerance=0;
else
% The relative tolerances sum up
c.tolerance=a.coeff*b.tolerance+b.coeff*a.tolerance;
end
end
% Gentlemen, you're trying to negotiate something you will never be able
% to negotiate. If negotiated, it will not be ratified. And if ratified,
% it will not work.
%
% Russell Bretherton, UK negotiator in Brussels, 1955
|
github
|
tsajed/nmr-pred-master
|
diag.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/diag.m
| 1,870 |
utf_8
|
191bfe0f479322a3bd9094dac9de24c1
|
% Mimics the diag behavior for tensor train matrix. Syntax:
%
% tt=diag(tt)
%
% If tt is a square matrix, return a vector by computing diag of every core.
% If tt is a vector (one mode size is ones), return a diagonal matrix.
%
% [email protected]
function tt=diag(tt)
% Read tensor train sizes and ranks
[ncores,ntrains]=size(tt.cores);
r=ranks(tt); sz=sizes(tt);
% Decide the dimensions
if all(sz(:,1)==ones(ncores,1)) || all(sz(:,2)==ones(ncores,1))
% Vector on input, diagonal matrix on output
for n=1:ntrains
for k=1:ncores
vector_core=tt.cores{k,n};
matrix_size=max(sz(k,1),sz(k,2));
matrix_core=zeros(r(k,n),matrix_size,matrix_size,r(k+1,n));
for p=1:r(k,n)
for q=1:r(k+1,n)
matrix_core(p,:,:,q)=diag(reshape(vector_core(p,:,:,q),[sz(k,1),sz(k,2)]));
end
end
tt.cores{k,n}=matrix_core;
end
end
else
% Matrix on input, column vector on output
if all(sz(:,1)==sz(:,2))
for n=1:ntrains
for k=1:ncores
matrix_core=tt.cores{k,n};
vector_size=min(sz(k,1),sz(k,2));
vector_core=zeros(r(k,n),vector_size,1,r(k+1,n));
for p=1:r(k,n)
for q=1:r(k+1,n)
vector_core(p,:,1,q)=diag(reshape(matrix_core(p,:,:,q),[sz(k,1),sz(k,2)]));
end
end
tt.cores{k,n}=vector_core;
end
end
else
error('Input should be either a square matrix or a vector.');
end
end
end
% The only mistake [the famous criminal finacier] Bernie Madoff made was
% to promise returns in this life.
%
% Harry Kroto
|
github
|
tsajed/nmr-pred-master
|
transpose.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/transpose.m
| 587 |
utf_8
|
5806bbccc81adb6b93bba2a772a29743
|
% Transposes a tensor without complex conjugation. Syntax:
%
% ttrain=transpose(ttrain)
%
% [email protected]
% [email protected]
function ttrain=transpose(ttrain)
% Read tensor sizes and ranks
[ncores,ntrains]=size(ttrain.cores);
% Swap the middle dimensions of all cores
for n=1:ntrains
for k=1:ncores
ttrain.cores{k,n}=permute(ttrain.cores{k,n},[1 3 2 4]);
end
end
end
% "Public welfare" is the welfare of those who do not earn it; those who do, are
% entitled to no welfare.
%
% Ayn Rand, "Atlas Shrugged"
|
github
|
tsajed/nmr-pred-master
|
mrdivide.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/mrdivide.m
| 720 |
utf_8
|
365b4610bcebe6bc9a9d0aef0b0221ca
|
% Divides a tensor train object by a scalar. Syntax:
%
% c=mrdivide(a,b)
%
% The first input should be a ttclass object and the
% second one a scalar.
%
% [email protected]
% [email protected]
function a=mrdivide(a,b)
% Division of tensor train by a scalar
if isa(a,'ttclass')&&isscalar(b)
% Divide the coefficients and update the tolerances
a.coeff=a.coeff/b; a.tolerance=a.tolerance/abs(b);
else
% Complain and bomb out
error('the first argument must be a tensor train and the second one a scalar.');
end
end
% It is dangerous to be right in matters on which the established
% authorities are wrong.
%
% Voltaire
|
github
|
tsajed/nmr-pred-master
|
clearcoeff.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/clearcoeff.m
| 729 |
utf_8
|
02b24ad006d2659ceef5baeffa2cb49d
|
% Absorbs the physical coefficient of the tensor train into
% its cores. Syntax:
%
% tt=clearcoeff(tt)
%
% The value of the tensor train remains the same.
%
% [email protected]
% [email protected]
function tt=clearcoeff(tt)
% Get the number of cores and trains
[ncores,ntrains]=size(tt.cores);
% Loop over the trains in the buffer
for n=1:ntrains
% Scale the coefficient
A=tt.coeff(1,n)^(1/ncores);
% Apply it to cores
for k=1:ncores
tt.cores{k,n}=A*tt.cores{k,n};
end
% Erase the coefficient
tt.coeff(1,n)=1;
end
end
% "Moral outrage is a middle-class luxury."
%
% Anonymous philosophy professor
|
github
|
tsajed/nmr-pred-master
|
isnumeric.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/isnumeric.m
| 438 |
utf_8
|
f38eac16170404dba2a67da27f6c7b20
|
% Returns TRUE for the tensor train class. Syntax:
%
% answer=isnumeric(tt)
%
% [email protected]
% [email protected]
function answer=isnumeric(tt)
% Non-empty tensor trains should return true()
if isa(tt,'ttclass')&&(~isempty(tt.cores))
answer=true();
else
answer=false();
end
end
% People who think honestly and deeply have a hostile
% attitude towards the public.
%
% Johann Wolfgang von Goethe
|
github
|
tsajed/nmr-pred-master
|
ttclass.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/ttclass.m
| 3,431 |
utf_8
|
5bd1a152d06f915314f7476f47b7b0f1
|
% Creates an object of a tensor train class. Syntax:
%
% tt=ttclass(coeff,kronterms,tolerance)
%
% Parameters:
%
% coeff - coefficient in front of the spin operator,
% usually be the interaction magnitude
%
% kronterms - column cell array of matrices whose Krone-
% cker product makes up the spin operator.
%
% tolerance - maximum deviation in the 2-norm between the
% TT representation and the flat matrix repre-
% sentation that the TT formalism is allowed
% to introduce.
%
% If multiple columns are supplied in kronterms, multiple coefficients
% are given in coeff, and multiple tolerances are given in tolerance,
% the resulting tensor train is assumed to be the sum of the individu-
% al tensor trains specified in different columns.
%
% [email protected]
% [email protected]
classdef ttclass
% Default properties
properties
coeff=0; % Physical coefficients (row vector)
cores={0}; % Cores of each tensor train (in columns)
tolerance=0; % Accuracy tolerances (row vector)
debuglevel=0; % Diagnostic output switch
end
% Method description
methods
% Constructor function
function tt=ttclass(coeff,kronterms,tolerance)
% Check the number of inputs
if nargin==0, return;
elseif (nargin==1)||(nargin==2)||(nargin>3)
error('incorrect number of input arguments.');
end
% Check consistency
grumble(coeff,kronterms,tolerance);
% Convert Kronecker products into tensor trains
tt.cores=kronterms;
for n=1:size(kronterms,2)
for d=1:size(kronterms,1)
tt.cores{d,n}=reshape(full(kronterms{d,n}),[1 size(kronterms{d,n}) 1]);
end
end
% Store the coefficients
tt.coeff=coeff;
% Store the tolerances
tt.tolerance=tolerance;
% Do not print diagnostics
tt.debuglevel=0;
end
end
end
% Consistency enforcement
function grumble(coeff,cores,tolerance)
if (~isnumeric(coeff))||(~isrow(coeff))
error('coeff must be a complex row vector.');
elseif (~iscell(cores))||isempty(cores)||numel(size(cores))~=2
error('cores must be a two-dimensional cell array with at least one element.');
elseif any(~cellfun(@isnumeric,cores))||any(~cellfun(@ismatrix,cores))
error('all elements of the cores cell array must be matrices.');
elseif (~isnumeric(tolerance))||(~isreal(tolerance))||(~isrow(tolerance))||any(tolerance<0)
error('tolerance must be a row vector with real non-negative elements.');
elseif numel(coeff)~=numel(tolerance)
error('coefficient and tolerance vectors must have the same number of elements.');
elseif size(cores,2)~=numel(coeff)
error('the number of columns in the operand array must match the number of coefficients.')
end
end
% "Kuprov cocktail": caffeine + modafinil + propranolol, 50 mg each.
% "Double Kuprov": 100 mg variety, reserved for extreme workloads.
|
github
|
tsajed/nmr-pred-master
|
ranks.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/ranks.m
| 822 |
utf_8
|
ed77cc9f19eac30b98342c6e2d4cffcc
|
% Returns the bond dimensions of a tensor train. Syntax:
%
% ttranks=ranks(ttrain)
%
% The output is (ncores+1) by (ntrains) array. The first
% and the last elements for each train are 1.
%
% [email protected]
% [email protected]
function ttranks=ranks(ttrain)
% Get core array dimensions
[ncores,ntrains]=size(ttrain.cores);
% Preallocate the answer
ttranks=zeros(ncores+1,ntrains);
% Loop over the buffer
for n=1:ntrains
% Extract the ranks
for k=1:ncores
ttranks(k,n)=size(ttrain.cores{k,n},1);
end
ttranks(ncores+1,n)=size(ttrain.cores{ncores,n},4);
end
end
% I refrain from publishing for fear that disputes and controversies
% may be raised against me by ignoramuses.
%
% Isaac Newton, in a letter to Leibniz
|
github
|
tsajed/nmr-pred-master
|
mean.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/mean.m
| 1,780 |
utf_8
|
505c236ae5422286dda85b0231d3cc79
|
% Mean of elements of a tensor train representation of a
% matrix. Syntax:
%
% answer=mean(ttrain,dim)
%
% The mean value is computed along the specified dimen-
% sion (dim=1 or dim=2).
%
% [email protected]
function answer=mean(ttrain,dim)
% Get sizes and ranks
[ncores,ntrains]=size(ttrain.cores);
tt_ranks=ranks(ttrain);
tt_sizes=sizes(ttrain);
% If all dimensions are singleton, return a scalar immediately
if all(tt_sizes(:)==1), answer=full(ttrain); return; end
% In dim is omitted, choose first non-singleton dimension
% (this mimics the Matlab behaviour for matices)
if nargin==1
dim=0;
for k=2:-1:1
if ~all(tt_sizes(:,k)==1)
dim=k;
end
end
end
% Make an auxiliary tensor train
answer=ttclass;
answer.coeff=ttrain.coeff;
answer.tolerance=zeros(1,ntrains);
answer.cores=cell(ncores,ntrains);
% Run through all tensor trains
for n=1:ntrains
% Run through all cores
for k=1:ncores
% Sum the appropriate dimension in each core
answer.cores{k,n}=sum(ttrain.cores{k,n},dim+1);
% Reshape the core and divide the result by the correspondent dimension
switch dim
case 1
answer.cores{k,n}=reshape(answer.cores{k,n},[tt_ranks(k,n),1,tt_sizes(k,2),tt_ranks(k+1,n)])/tt_sizes(k,1);
case 2
answer.cores{k,n}=reshape(answer.cores{k,n},[tt_ranks(k,n),tt_sizes(k,1),1,tt_ranks(k+1,n)])/tt_sizes(k,2);
otherwise
error('incorrect dimension specificaton.');
end
end
end
% If all modes are singleton, transform to a scalar
if all(all(sizes(answer)))==1, answer=full(answer); end
end
|
github
|
tsajed/nmr-pred-master
|
ctranspose.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/ctranspose.m
| 606 |
utf_8
|
830087c613f5c3ecd61710101fca2e10
|
% Computes a Hermitian conjugate of a matrix in a tensor train
% representation. Syntax:
%
% ttrain=ctranspose(ttrain)
%
% [email protected]
% [email protected]
function ttrain=ctranspose(ttrain)
% Read tensor sizes and ranks
[ncores,ntrains]=size(ttrain.cores);
% Swap the middle dimensions of all cores
for n=1:ntrains
for k=1:ncores
ttrain.cores{k,n}=permute(ttrain.cores{k,n},[1 3 2 4]);
end
end
% Conjugate the result
ttrain=conj(ttrain);
end
% What gives the artist real prestige is his imitators.
%
% Igor Stravinsky
|
github
|
tsajed/nmr-pred-master
|
vec.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/vec.m
| 1,384 |
utf_8
|
5aad94388c8dd72a7ff58440a6010884
|
% Stretches arrays into vectors - useful for situations when the stand-
% ard (:) syntax is not available. Syntax:
%
% A=vec(A)
%
% WARNING: for tensor trains this operation proceeds by stretching eve-
% ry core of the tensor train. the result is not the same as
% column-wise matrix stretching (it is an element permutation
% away from it), but the resulting order of elements is consi-
% stent with tensor train Kronecker product operation output.
%
% [email protected]
% [email protected]
function A=vec(A)
% Decide how to proceed
if isa(A,'ttclass')
% Read tensor train sizes and ranks
[ncores,ntrains]=size(A.cores);
ttm_ranks=ranks(A); ttm_sizes=sizes(A);
% Reshape the cores
for n=1:ntrains
for k=1:ncores
A.cores{k,n}=reshape(A.cores{k,n},[ttm_ranks(k,n),ttm_sizes(k,1)*ttm_sizes(k,2),1,ttm_ranks(k+1,n)]);
end
end
else
% Use standard Matlab stretch
A=reshape(A,[numel(A) 1]);
end
end
% Jean-Paul Sartre was sitting at a French cafe, revising his draft of Being
% and Nothingness. He said to the waitress, "I'd like a cup of coffee, plea-
% se, with no cream." The waitress replied, "I'm sorry, Monsieur, but we are
% out of cream. How about with no milk?"
|
github
|
tsajed/nmr-pred-master
|
hdot.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/hdot.m
| 1,611 |
utf_8
|
eb6826af52215250705b7f51b54be0ea
|
% Haramard dot product between two tensor train matrices. Syntax:
%
% c=hdot(a,b)
%
% [email protected]
function c=hdot(a,b)
% Check consistency
grumble(a,b);
% Read topology and initialize the answer
[ncores,ntrains_a]=size(a.cores); ranks_a=ranks(a);
[~ ,ntrains_b]=size(b.cores); ranks_b=ranks(b);
mode_sizes=sizes(a); c=0;
% Loop over TT buffers
for na=1:ntrains_a
for nb=1:ntrains_b
% Multiply coefficients
x=conj(a.coeff(na))*b.coeff(nb);
% Loop over TT cores and compute dot product
for k=1:ncores
core_b=reshape(b.cores{k,nb},[ranks_b(k,nb),mode_sizes(k,1)*mode_sizes(k,2)*ranks_b(k+1,nb)]);
core_b=x*core_b;
core_b=reshape(core_b,[ranks_a(k,nb)*mode_sizes(k,1)*mode_sizes(k,2),ranks_b(k+1,nb)]);
core_a=reshape(a.cores{k,na},[ranks_a(k,na)*mode_sizes(k,1)*mode_sizes(k,2),ranks_a(k+1,na)]);
x=core_a'*core_b;
end
% Add to the total
c=c+x;
end
end
end
% Consistency enforcement
function grumble(a,b)
if ~isa(a,'ttclass') || ~isa(b,'ttclass')
error('both arguments should be tensor trains.')
end
if size(a.cores,1)~=size(b.cores,1)
error('the number of cores in the arguments must be the same.')
end
if ~all(all(sizes(a)==sizes(b)))
error('tensor train mode sizes are not consistent.')
end
end
% The higher we soar, the smaller we appear to those who cannot fly.
%
% Friedrich Nietzsche, "Thus Spoke Zarathustra"
|
github
|
tsajed/nmr-pred-master
|
nnz.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/nnz.m
| 564 |
utf_8
|
339a7a7d65b6617798bed101c9cd61eb
|
% Number of nonzeros in all cores of a tensor train. Syntax:
%
% answer=nnz(ttrain)
%
% [email protected]
% [email protected]
function answer=nnz(ttrain)
% Count the non-zeros
answer=sum(sum(cellfun(@nnz,ttrain.cores)));
end
% Men have always been and forever would remain silly victims of lies and
% self-deceit in politics, until they learn to see, behind any moral, re-
% ligious, political or social statements, proclamations and promises the
% interests of specific social classes.
%
% Vladimir Lenin
|
github
|
tsajed/nmr-pred-master
|
revert.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/revert.m
| 674 |
utf_8
|
4f5ecd5143606ab0df50d58b16728f70
|
% Bit-revert permutation for the tensor train operator. Syntax:
%
% tt=revert(tt)
%
% [email protected]
function tt=revert(tt)
% Read sizes and ranks
[ncores,ntrains]=size(tt.cores);
% Swap bond indices
for n=1:ntrains
for k=1:ncores
tt.cores{k,n}=permute(tt.cores{k,n}, [4,2,3,1]);
end
end
% Revert the train direction
tt.cores=tt.cores(ncores:-1:1,:);
end
% Asking for efficiency nd adaptability in the same program is like
% asking for a beautiful and modest wife... we'll probably have to
% settle for one or the other.
%
% Gerald M. Weinberg, "The psychology of computer programming"
|
github
|
tsajed/nmr-pred-master
|
isreal.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/isreal.m
| 672 |
utf_8
|
1bd8c5780bae5b52c47e596f70ed0347
|
% Returns TRUE for the real-valued ttclass. Syntax:
%
% answer=isreal(tt)
%
% [email protected]
function answer=isreal(tt)
% Non-empty tensor trains should return true()
if isa(tt,'ttclass')
% Check coefficient first
answer=all(isreal(tt.coeff));
% If the coefficients are real, check the cores
if answer
for n=1:tt.ntrains
for k=1:tt.ncores
answer=isreal(tt{k,n});
if ~answer, return; end
end
end
end
else
error('Input is not a ttclass.');
end
end
% Democracy is a pathetic belief in the collective wisdom
% of individual ignorance.
%
% H.L. Mencken
|
github
|
tsajed/nmr-pred-master
|
sum.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/sum.m
| 1,823 |
utf_8
|
e0bcb7c4f07a01c8e5ae0b61c918d654
|
% Sum of elements of a tensor train representation of a matrix. Syntax:
%
% answer=sum(ttrain,dim)
%
% The sum is taken along the specified dimension (dim=1 or dim=2).
%
% [email protected]
% [email protected]
function answer=sum(ttrain,dim)
% Get sizes and ranks
[ncores,ntrains]=size(ttrain.cores);
tt_ranks=ranks(ttrain);
tt_sizes=sizes(ttrain);
% If all dimensions are singleton, return a scalar immediately
if all(tt_sizes(:)==1), answer=full(ttrain); return; end
% In dim is omitted, choose first non-singleton dimension
% (this mimics the Matlab behaviour for matices)
if nargin==1
dim=0;
for k=2:-1:1
if ~all(tt_sizes(:,k)==1)
dim=k;
end
end
end
% Make an auxiliary tensor train
answer=ttclass;
answer.coeff=ttrain.coeff;
answer.tolerance=zeros(1,ntrains);
answer.cores=cell(ncores,ntrains);
% Run through all tensor trains
for n=1:ntrains
% Run through all cores
for k=1:ncores
% Sum the appropriate dimension in each core
answer.cores{k,n}=sum(ttrain.cores{k,n},dim+1);
% Reshape the core
switch dim
case 1
answer.cores{k,n}=reshape(answer.cores{k,n},[tt_ranks(k,n),1,tt_sizes(k,2),tt_ranks(k+1,n)]);
case 2
answer.cores{k,n}=reshape(answer.cores{k,n},[tt_ranks(k,n),tt_sizes(k,1),1,tt_ranks(k+1,n)]);
otherwise
error('incorrect dimension specificaton.');
end
end
end
% If all modes are singleton, transform to a scalar
if all(all(sizes(answer)))==1, answer=full(answer); end
end
% The sledge rests in summer, the cart rests in winter, but the horse
% never rests.
%
% A Russian saying
|
github
|
tsajed/nmr-pred-master
|
shrink.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/shrink.m
| 908 |
utf_8
|
862451f6f6f1d11e28a63dacc4b6ff5e
|
% Approximates a given tensor train with lower TT-ranks. Syntax:
%
% ttrain=shrink(ttrain)
%
% Returns a single tensor train with right-to-left orthogonalisation.
%
% [email protected]
% [email protected]
function ttrain=shrink(ttrain)
% Read train sizes
[d,~]=size(ttrain.cores);
% Summation
ttrain=ttclass_sum(ttrain);
% Right-to-left orthogonalization
ttrain=ttclass_ort(ttrain);
% Check the norm and escape if the object is zero
nrm=ttrain.coeff*norm(ttrain.cores{d,1}(:));
if nrm==0, ttrain=0*unit_like(ttrain); return; end
% Truncation
ttrain=ttclass_svd(ttrain);
% Convert to a scalar if appropriate
if all(all(cellfun(@(x)size(x,2),ttrain.cores)==1))&&...
all(all(cellfun(@(x)size(x,3),ttrain.cores)==1))
ttrain=full(ttrain);
end
end
% "It's a tough life, being small and delicious."
%
% A Russian saying
|
github
|
tsajed/nmr-pred-master
|
ismatrix.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/ismatrix.m
| 407 |
utf_8
|
b7254d251d685122914e49f515bb4b0f
|
% Returns TRUE for the tensor train class. Syntax:
%
% answer=ismatrix(tt)
%
% [email protected]
% [email protected]
function answer=ismatrix(tt)
% Non-empty tensor trains should return true()
if isa(tt,'ttclass')&&(~isempty(tt.cores))
answer=true();
else
answer=false();
end
end
% The stronger the house, the greater the immigration.
%
% The Law of Three Little Pigs
|
github
|
tsajed/nmr-pred-master
|
full.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/full.m
| 1,492 |
utf_8
|
88c9bbf81a4497fc240f5126c863ca41
|
% Converts a tensor train representation of a matrix into a matrix.
% Syntax:
% answer=full(ttrain)
%
% Note: the result can be huge, careless use would crash the system.
%
% [email protected]
% [email protected]
function answer=full(ttrain)
% Preallocate the result
answer=zeros(size(ttrain));
% Get object dimensions
[ncores,ntrains]=size(ttrain.cores);
% Get tensor ranks
ttranks=ranks(ttrain);
% Get mode sizes
modesizes=sizes(ttrain);
% Loop over the buffer
for n=1:ntrains
% Multiply up the tensor train
next_term=reshape(ttrain.cores{ncores,n},[ttranks(ncores,n),modesizes(ncores,1)*modesizes(ncores,2)]);
for k=(ncores-1):(-1):1
next_term=reshape(ttrain.cores{k,n},[ttranks(k,n)*modesizes(k,1)*modesizes(k,2),ttranks(k+1,n)])*next_term;
next_term=reshape(next_term,[ttranks(k,n),modesizes(k,1),modesizes(k,2),prod(modesizes(k+1:ncores,1)),prod(modesizes(k+1:ncores,2))]);
next_term=reshape(permute(next_term,[1 4 2 5 3]),[ttranks(k,n),prod(modesizes(k:ncores,1))*prod(modesizes(k:ncores,2))]);
end
next_term=reshape(next_term,[prod(modesizes(1:ncores,1)),prod(modesizes(1:ncores,2))]);
% Add the matrix to the result
answer=answer+ttrain.coeff(n)*next_term;
end
end
% We must conduct research and then accept the results. If they don't
% stand up to experimentation, Buddha's own words must be rejected.
%
% Dalai Lama XIV
|
github
|
tsajed/nmr-pred-master
|
size.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/size.m
| 1,361 |
utf_8
|
222c4d5e38f9b1cadb6d3da9e6a4669d
|
% Returns the size of the matrix represented by a tensor train.
% Syntax:
% [m,n]=size(tt,dim)
%
% For large spin systems M and N may be too large to fit into
% the maximum integer permitted by Matlab.
%
% [email protected]
% [email protected]
function varargout=size(tt,dim)
% Multiply up physical dimensions of all cores
if nargin==1
m=prod(cellfun(@(x)size(x,2),tt.cores),1);
n=prod(cellfun(@(x)size(x,3),tt.cores),1);
varargout={[m(1) n(1)]};
elseif dim==1
m=prod(cellfun(@(x)size(x,2),tt.cores),1);
varargout={m(1)};
elseif dim==2
n=prod(cellfun(@(x)size(x,3),tt.cores),1);
varargout={n(1)};
else
error('incorrect call syntax.');
end
% Check for infinities
if any(varargout{1}>intmax)
error('tensor train dimensions exceed Matlab''s intmax.');
end
end
% Will fluorine ever have practical applications? It is very
% difficult to answer this question. I may, however, say in
% all sincerity that I gave this subject little thought when
% I undertook my researches, and I believe that all the chem-
% ists whose attempts preceded mine gave it no more conside-
% ration. A scientific research is a search after truth, and
% it is only after discovery that the question of applicabi-
% lity can be usefully considered.
%
% Henri Moissan
|
github
|
tsajed/nmr-pred-master
|
sizes.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/sizes.m
| 769 |
utf_8
|
3f04bc99817774a800acc1d1111751e2
|
% Returns mode sizes (physical dimensions of each core) of
% a tensor train. Syntax:
%
% modesizes=sizes(tt)
%
% The output is an array with ncores rows and two columns.
%
% [email protected]
% [email protected]
function modesizes=sizes(tt)
% Determine the number of cores
ncores=size(tt.cores,1);
% Preallocate the answer
modesizes=zeros(ncores,2);
% Fill in the answer
for k=1:ncores
modesizes(k,1)=size(tt.cores{k,1},2);
modesizes(k,2)=size(tt.cores{k,1},3);
end
end
% Computer models are no different from fashion models: seductive,
% unreliable, easily corrupted, and they lead sensible people to
% make fools of themselves.
%
% Jim Hacker, in "Yes, Prime Minister" (a BBC documentary)
|
github
|
tsajed/nmr-pred-master
|
conj.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/conj.m
| 575 |
utf_8
|
3ceb631d25f6aa84ea4d7d1d6141a78c
|
% Conjugate the elements of the tensor train matrix. Syntax:
%
% tt=conj(tt)
%
% [email protected]
% [email protected]
function tt=conj(tt)
% Read tensor train sizes and ranks
[ncores,ntrains]=size(tt.cores);
% Conjugate the cores
for n=1:ntrains
for k=1:ncores
tt.cores{k,n}=conj(tt.cores{k,n});
end
end
% Conjugate the coefficients
tt.coeff=conj(tt.coeff);
end
% I asked God for a bike, but I know God doesn't work that way.
% So I stole a bike and asked for forgiveness.
%
% Al Pacino
|
github
|
tsajed/nmr-pred-master
|
subsref.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/subsref.m
| 2,400 |
utf_8
|
6d416b5e01fa1147d3fa7eb199216cf9
|
% Dot and bracket property specifications for the tensor train class.
%
% [email protected]
% [email protected]
function answer=subsref(ttrain,reference)
switch reference(1).type
% Methods and properties
case '.'
% Return the output requested
switch reference(1).subs
case 'ncores', answer=size(ttrain.cores,1);
case 'ntrains', answer=size(ttrain.cores,2);
case 'sizes', answer=sizes(ttrain);
case 'ranks', answer=ranks(ttrain);
case 'coeff', answer=ttrain.coeff;
case 'cores', answer=ttrain.cores;
case 'tolerance', answer=ttrain.tolerance;
otherwise, error(['unknown field reference ',reference(1).subs]);
end
% Core extraction
case '{}'
% Return the core requested
if numel(reference(1).subs)~=2
error('exactly two indices required to extract tt{j,k} kernel.');
else
answer=ttrain.cores{reference(1).subs{1},reference(1).subs{2}};
end
% Matrix element extraction
case '()'
% Start with zero
answer=0;
% Convert indices
if numel(reference(1).subs)~=2
error('exactly two indices required to evaluate tt(j,k) element');
elseif (numel(reference(1).subs{1})==1)&&(numel(reference(1).subs{2})==1)
siz=sizes(ttrain);
ind=ttclass_ind2sub(siz(:,1),reference(1).subs{1});
jnd=ttclass_ind2sub(siz(:,2),reference(1).subs{2});
else
error('advanced indexing is not implemented for tensor trains.');
end
% Multiply up the tensor train
[ncores,ntrains]=size(ttrain.cores);
for n=1:ntrains
x=ttrain.cores{ncores,n}(:,ind(ncores),jnd(ncores),:);
for k=(ncores-1):(-1):1
x=ttrain.cores{k,n}(:,ind(k),jnd(k),:)*x;
end
answer=answer+ttrain.coeff(n)*x(1,1);
end
otherwise
error('unknown subscript reference type.');
end
% Allow nested indexing
if numel(reference)>1
answer=subsref(answer,reference(2:end));
end
end
% "A cactus is a very disappointed cucumber."
%
% A Russian saying
|
github
|
tsajed/nmr-pred-master
|
rand.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/rand.m
| 850 |
utf_8
|
673cd6e50adc12fa9d9e408cb8b05cc2
|
% Generates tensor train matrix with random entries, same physical index
% topology at the tensor train supplied, and specified TT-ranks. Syntax:
%
% tt=rand(tt,ttrank)
%
% [email protected]
% [email protected]
function tt=rand(tt,ttrank)
% Read tensor train sizes
[d,~]=size(tt.cores); sz=sizes(tt);
% Reallocate cores
tt.cores=cell(d,1);
% Fill the cores by random elements
tt.cores{1,1}=rand(1,sz(1,1),sz(1,2),ttrank);
for k=2:d-1
tt.cores{k,1}=rand(ttrank,sz(k,1),sz(k,2),ttrank);
end
tt.cores{d,1}=rand(ttrank,sz(d,1),sz(d,2),1);
% Unit coefficient and zero tolerance
tt.coeff=1; tt.tolerance=0;
end
% The problem with inviting professors to dinner parties is that they're
% used to talking for a minimum of 50 minutes at a time.
%
% Anonymous philosophy professor
|
github
|
tsajed/nmr-pred-master
|
plus.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/plus.m
| 1,037 |
utf_8
|
94add29cbc7f9d3cbc684e0c1595790a
|
% Tensor train addition operation. Does not perform the actual addition,
% but instead concatenates the operands until such time as recompression
% becomes absolutely necessary. Syntax:
%
% c=plus(a,b)
%
% [email protected]
% [email protected]
function a=plus(a,b)
% Validate the input
if (~isa(a,'ttclass'))||(~isa(b,'ttclass'))
error('both operands must be tensor train objects.');
elseif (size(a.cores,1)~=size(b.cores,1))||(~all(all(sizes(a)==sizes(b))))
error('dimension mismatch in tensor trains.');
end
% Write the sum object
a.coeff=[a.coeff b.coeff];
a.cores=[a.cores b.cores];
a.tolerance=[a.tolerance b.tolerance];
% Filter out zero coeff
pos=find(a.coeff);
if ~isempty(pos)
a.coeff=a.coeff(pos);
a.cores=a.cores(:,pos);
a.tolerance=a.tolerance(pos);
else
a=0*unit_like(a);
end
end
% Twinkle, twinkle, little star.
% I don't wonder what you are.
% We've got Science, we've got Math!
% You're a giant ball of gas.
|
github
|
tsajed/nmr-pred-master
|
unit_like.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/unit_like.m
| 1,785 |
utf_8
|
0bdd95c2f58b8d61a904947ec98435d4
|
% Returns a unit object of the same type as whatever is supplied.
%
% A=unit_like(A)
%
% Full square matrices, sparse matrices and tensor train represen-
% tations of square matrices are supported.
%
% [email protected]
function A=unit_like(A)
if isa(A,'ttclass')
% Unit tensor train of the same topology
mode_sizes=sizes(A);
if all(mode_sizes(:,1)==mode_sizes(:,2))
core=cell(A.ncores,1);
for k=1:A.ncores
core{k}=eye(mode_sizes(k,1));
end
A=ttclass(1,core,0);
else
error('tensor train does not represent a square matrix.');
end
elseif ismatrix(A)&&(size(A,1)==size(A,2))&&issparse(A)
% Unit sparse matrix of the same dimension
A=speye(size(A));
elseif ismatrix(A)&&(size(A,1)==size(A,2))&&(~issparse(A))
% Unit dense matrix of the same dimension
A=eye(size(A));
else
% Complain and bomb out
error('the input is not a square matrix or a representation thereof.');
end
end
% Briefly stated, the Gell-Mann Amnesia effect is as follows. You open the
% newspaper to an article on some subject you know well. You read the arti-
% cle and see the journalist has absolutely no understanding of either the
% facts or the issues. Often, the article is so wrong it actually presents
% the story backward -- reversing cause and effect. In any case, you read
% with exasperation or amusement the multiple errors in a story, and then
% turn the page to national or international affairs, and read as if the
% rest of the newspaper was somehow more accurate about Palestine than the
% baloney you just read. You turn the page, and forget what you know.
%
% Michael Crichton
|
github
|
tsajed/nmr-pred-master
|
mtimes.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/mtimes.m
| 5,965 |
utf_8
|
2dc0443feb0d20eea9a969bcd0222188
|
% Performs tensor train multiplication followed by a shrink. Syntax:
%
% c=mtimes(a,b)
%
% where first operand (a) can be scalar or tensor train, second operand
% (b) can be scalar, or tensor train, or full matrix.
%
% [email protected]
% [email protected]
function c=mtimes(a,b)
% Decide the type combination
if isa(a,'ttclass')&&isa(b,'double')&&isscalar(b)
% Multiply tensor train by a scalar from the right
c=a; c.coeff=b*c.coeff; c.tolerance=b*c.tolerance;
elseif isa(a,'ttclass')&&isa(b,'double')&&numel(b)>1
% Read sizes and ranks of the operands
[a_ncores,a_ntrains]=size(a.cores); a_ranks=ranks(a); a_sizes=sizes(a); b_sizes=size(b);
% Check consistency
if (prod(a_sizes(:,2))~=b_sizes(1))
error('tensor train and vector sizes should be consistent for multiplication.');
end
% Preallocate result
mc=prod(a_sizes(:,1)); nc=b_sizes(2); c=zeros(mc,nc);
% Loop over the buffers of the operands
for na=1:a_ntrains
% Set current vector as the right-hand side
d=b;
% Loop over the cores and perform multiplication
for ka=a_ncores:(-1):1
% Reshape the current vector
d=reshape(d,[a_ranks(ka+1,na)*a_sizes(ka,2),prod(a_sizes(1:ka-1,2))*prod(a_sizes(ka+1:a_ncores,1))*nc]);
% Extract the core of the first operand and reshape it appropriately
a_core=a.cores{ka,na};
a_core=reshape(a_core,[a_ranks(ka,na),a_sizes(ka,1),a_sizes(ka,2),a_ranks(ka+1,na)]);
a_core=permute(a_core,[1,2,4,3]);
a_core=reshape(a_core,[a_ranks(ka,na)*a_sizes(ka,1),a_ranks(ka+1,na)*a_sizes(ka,2)]);
% Perform the contraction
d=a_core*d;
d=reshape(d,[a_ranks(ka,na),a_sizes(ka,1),prod(a_sizes(1:ka-1,2))*prod(a_sizes(ka+1:a_ncores,1)),nc]);
d=permute(d,[1,3,2,4]);
end
% Accumulate the result
c=c+a.coeff(na)*reshape(d,[mc,nc]);
end
elseif isa(a,'double')&&isa(b,'ttclass')&&isscalar(a)
% Multiply tensor train by a scalar from the left
c=b; c.coeff=a*c.coeff; c.tolerance=a*c.tolerance;
elseif isa(a,'ttclass')&&isa(b,'ttclass')
% Read sizes and ranks of the operands
[a_ncores,a_ntrains]=size(a.cores); a_ranks=ranks(a); a_sizes=sizes(a);
[b_ncores,b_ntrains]=size(b.cores); b_ranks=ranks(b); b_sizes=sizes(b);
% Check consistency
if (a_ncores~=b_ncores)||(~all(a_sizes(:,2)==b_sizes(:,1)))
error('tensor train structures must be consistent.');
end
% Preallocate the result
new_cores=cell(a_ncores,a_ntrains,b_ntrains);
new_coeff=zeros(a_ntrains,b_ntrains);
new_tolerance=zeros(a_ntrains,b_ntrains);
% Loop over the buffers of the operands
for nb=1:b_ntrains
for na=1:a_ntrains
% Loop over the cores
for nc=1:a_ncores
% Extract cores from the operands
core_of_a=a.cores{nc,na};
core_of_b=b.cores{nc,nb};
% Run the index contraction: [la, ma, na, ra] * [lb, mb, nb, rb] -> [la, lb, ma, nb, ra, rb]
core_of_a=reshape(permute(core_of_a,[1 4 2 3]),[a_ranks(nc,na)*a_ranks(nc+1,na)*a_sizes(nc,1),a_sizes(nc,2)]);
core_of_b=reshape(permute(core_of_b,[2 3 1 4]),[b_sizes(nc,1),b_sizes(nc,2)*b_ranks(nc,nb)*b_ranks(nc+1,nb)]);
core_of_c=reshape(core_of_a*core_of_b,[a_ranks(nc,na),a_ranks(nc+1,na),a_sizes(nc,1),b_sizes(nc,2),b_ranks(nc,nb),b_ranks(nc+1,nb)]);
core_of_c=permute(core_of_c,[1 5 3 4 2 6]);
% Store the core of the result
new_cores{nc,na,nb}=reshape(core_of_c,[a_ranks(nc,na)*b_ranks(nc,nb),a_sizes(nc,1),b_sizes(nc,2),a_ranks(nc+1,na)*b_ranks(nc+1,nb)]);
end
% Multiply coefficients
new_coeff(na,nb)=a.coeff(na)*b.coeff(nb);
if a.coeff(na)==0 || b.coeff(nb)==0
% The summand is exactly zero
new_tolerance(na,nb)=0;
else
% Compute the norm of the current summand
tt_current=ttclass;
tt_current.coeff=a.coeff(na)*b.coeff(nb);
tt_current.cores=cell(a_ncores,1);
tt_current.cores=new_cores(:,na,nb);
tt_current.tolerance=0;
norm_current=norm(tt_current,'fro');
% Update accuracy
new_tolerance(na,nb)=norm_current*(a.tolerance(1,na)/abs(a.coeff(1,na))+b.tolerance(1,nb)/abs(b.coeff(1,nb)));
end
end
end
% Write the output data structure
c=ttclass; c.coeff=reshape(new_coeff,[1,a_ntrains*b_ntrains]);
c.cores=reshape(new_cores,[a_ncores,a_ntrains*b_ntrains]);
c.tolerance=reshape(new_tolerance,[1,a_ntrains*b_ntrains]);
% Filter out zero coeff
pos=find(c.coeff);
if ~isempty(pos)
c.coeff=c.coeff(pos);
c.cores=c.cores(:,pos);
c.tolerance=c.tolerance(pos);
else
c=0*unit_like(c);
end
% Compress the answer
c=shrink(c);
else
% Complain and bomb out
error('both operands must be either scalars or tensor trains.');
end
end
% Nothing is more revolting than the majority; for it consists of few vigorous
% predecessors, of knaves who accommodate themselves, of weak people who assi-
% milate themselves, and the mass that toddles after them without knowing in
% the least what it wants.
%
% Johann Wolfgang von Goethe
|
github
|
tsajed/nmr-pred-master
|
mldivide.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/mldivide.m
| 870 |
utf_8
|
753b64fec557e020644e064b581fd109
|
% Solves a linear system with tensor train objects. Syntax:
%
% x=mldivide(A,y)
%
% The first input should be a ttclass matrix and the
% second one a ttclass vector of appropriate mode sizes.
%
% Note: the AMEn-solve algorithm is applied to symmetrized
% system A'A x = A'y.
%
% [email protected]
function x=mldivide(A,y)
if isa(A,'ttclass')&&isa(y,'ttclass')
% Shrink the operands
A=shrink(A);
y=shrink(y);
% Form a symmetrised system
AA=shrink(A'*A);
Ay=shrink(A'*y);
% Solve it with AMEn algorithm
x=ttclass_amen_solve(AA,Ay,1e-6);
else
% Complain and bomb out
error('both arguments should be tensor trains.');
end
end
% The penalty for success is to be bored by the people
% who used to snub you.
%
% Nancy Astor
|
github
|
tsajed/nmr-pred-master
|
trace.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/trace.m
| 1,192 |
utf_8
|
086e187c1371bff5bb6924cd7965a146
|
% Computes the trace of a tensor train operator. Syntax:
%
% tttrace=trace(tt)
%
% [email protected]
% [email protected]
function tttrace=trace(tt)
% Read sizes and ranks
[ncores,ntrains]=size(tt.cores);
tt_ranks=ranks(tt); tt_sizes=sizes(tt);
% Make an auxiliary tensor train
ttaux=ttclass; ttaux.coeff=tt.coeff;
ttaux.tolerance=zeros(1,ntrains);
ttaux.cores=cell(ncores,ntrains);
% Run through all tensor trains
for n=1:ntrains
for k=1:ncores
% Preallocate a core
ttaux.cores{k,n}=zeros(tt_ranks(k,n),tt_ranks(k+1,n));
% Fill in the core
for j=1:tt_ranks(k+1,n)
for i=1:tt_ranks(k,n)
ttaux.cores{k,n}(i,j)=trace(reshape(tt.cores{k,n}(i,:,:,j),[tt_sizes(k,1),tt_sizes(k,2)]));
end
end
% Reshape the core
ttaux.cores{k,n}=reshape(ttaux.cores{k,n},[tt_ranks(k,n),1,1,tt_ranks(k+1,n)]);
end
end
% Sum up the auxiliary tensor train
tttrace=full(ttaux);
end
% Pronouncement of experts to the effect that something cannot
% be done has always irritated me. - Leo Szilard
|
github
|
tsajed/nmr-pred-master
|
rdivide.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/rdivide.m
| 752 |
utf_8
|
36cb64a77970cb6031449a15a3f65137
|
% Divides a tensor train object by a scalar. Syntax:
%
% c=rdivide(a,b)
%
% The first input should be a ttclass object and the
% second one a scalar.
%
% [email protected]
% [email protected]
function a=rdivide(a,b)
% Division of tensor train by a scalar
if isa(a,'ttclass')&&isscalar(b)
% Divide the coefficients and update the tolerances
a.coeff=a.coeff/b; a.tolerance=a.tolerance/abs(b);
else
% Complain and bomb out
error('the first argument must be a tensor train and the second one a scalar.');
end
end
% Documentation is like sex: when it is good, it is very, very good, and when
% it is bad it's still better than nothing.
%
% Jim Hargrove
|
github
|
tsajed/nmr-pred-master
|
minus.m
|
.m
|
nmr-pred-master/spinach/kernel/overloads/@ttclass/minus.m
| 1,042 |
utf_8
|
c4a72a765e7bae60094e8ef1657324c6
|
% Tensor train subtraction operation. Does not perform the actual subtraction
% but instead concatenates the operands until such time as recompression beco-
% mes absolutely necessary. Syntax:
%
% c=minus(a,b)
%
% [email protected]
% [email protected]
function a=minus(a,b)
% Validate the input
if (~isa(a,'ttclass'))||(~isa(b,'ttclass'))
error('both operands must be tensor train objects.');
elseif (size(a.cores,1)~=size(b.cores,1))||(~all(all(sizes(a)==sizes(b))))
error('dimension mismatch in tensor trains.');
end
% Write the difference object
a.coeff=[a.coeff -b.coeff];
a.cores=[a.cores b.cores];
a.tolerance=[a.tolerance b.tolerance];
% Filter out zero coeff
pos=find(a.coeff);
if ~isempty(pos)
a.coeff=a.coeff(pos);
a.cores=a.cores(:,pos);
a.tolerance=a.tolerance(pos);
else
a=0*unit_like(a);
end
end
% Meraki (Greek, n.) - the soul, creativity or love put into something;
% the essence of yourself that is put into your work.
|
github
|
tsajed/nmr-pred-master
|
ist_product_table.m
|
.m
|
nmr-pred-master/spinach/kernel/cache/ist_product_table.m
| 2,349 |
utf_8
|
21a7346291a6dfd9ce26b0b64366d459
|
% Structure coefficient tables for the associateive envelopes of su(mult)
% algebras. Syntax:
%
% [product_table_left,product_table_right]=ist_product_table(mult)
%
% The input parameter is the multiplicity of the spin in question. Output
% contains the structure constants in the following conventions:
%
% T{n}*T{m}=sum_over_k[product_table_left(n,m,k)*T{k}]
%
% T{m}*T{n}=sum_over_k[product_table_right(n,m,k)*T{k}]
%
% Disk caching is used and updated automatically.
%
% [email protected]
% [email protected]
function [product_table_left,product_table_right]=ist_product_table(mult)
% Check consistency
grumble(mult);
% Generate cache record name
table_file=['ist_product_table_' num2str(mult) '.mat'];
% Check the cache
if exist(table_file,'file')
% Lift data from the cache if the file is already available
load(table_file);
else
% Get the irreducible spherical tensors
T=irr_sph_ten(mult);
% Preallocate the arrays
product_table_left=zeros(mult^2,mult^2,mult^2);
product_table_right=zeros(mult^2,mult^2,mult^2);
% Get the structure coefficients
for m=1:mult^2
for k=1:mult^2
normalization=sqrt(trace(T{k}*T{k}')*trace(T{m}*T{m}'));
for n=1:mult^2
product_table_left(n,m,k)=trace(T{n}*T{m}*T{k}')/normalization;
product_table_right(n,m,k)=trace(T{m}*T{n}*T{k}')/normalization;
end
end
end
% Save the table to the cache
save(table_file,'product_table_left','product_table_right');
end
end
% Consistency enforcement
function grumble(mult)
if (numel(mult)~=1)||(~isnumeric(mult))||(~isreal(mult))||...
(mult<2)||(mod(mult,1)~=0)
error('mult must be a real integer greater than 1.');
end
end
% According to Oxford Chemistry folklore, Peter Atkins has once asked the
% following question at an interview for a Lecturer post: "What is it that
% you have done that a technician would not do?". The candidate produced a
% reasonable answer to the effect that a technician would not have the re-
% quired skills. A better answer was suggested by a member of the Inter-
% view Board some time later: "And what is it that you, Atkins, have done
% that a journalist would not do?"
|
github
|
tsajed/nmr-pred-master
|
sle_operators.m
|
.m
|
nmr-pred-master/spinach/kernel/cache/sle_operators.m
| 12,203 |
utf_8
|
559f4a2c2b9b6a2c65735def057aa88e
|
% Lab space basis set and lab space operators required by
% the SLE module. Syntax:
%
% [Lx,Ly,Lz,D,space_basis]=sle_operators(max_rank)
%
% Input parameters:
%
% max_rank - maximum L rank for Wigner functions
%
% Output parameters:
%
% space_basis - lab space basis set descriptor, in
% [L M N] format, giving indices of
% each Wigner function in the basis.
%
% Lx,Ly,Lz - representations of lab space rotation
% generators in the Wigner function basis,
% to be used in the building of the lab
% space diffusion operator.
%
% D - a cell array of Wigner function product
% superoperators, corresponding to multi-
% plication by D[2,M,N] of the basis Wig-
% ner functions, to be used in the build-
% ing of the spin Hamiltonian operator.
%
% Automatic caching is implemented -- the function would
% not recompute operator sets that it can find on disk.
%
% [email protected]
% [email protected]
function [Lx,Ly,Lz,D,space_basis]=sle_operators(max_rank)
% Check consistency
grumble(max_rank);
% Generate cache record name
current_path=which('sle_operators'); current_path=current_path(1:(end-15));
cache_file=[current_path 'sle_operators_rank_' num2str(max_rank) '.mat'];
% Check the cache
if exist(cache_file,'file')
% Lift data from the cache if the file is already available
load(cache_file);
else
% Determine the spatial problem dimension
basis_dim=(1+max_rank)*(1+2*max_rank)*(3+2*max_rank)/3;
% Preallocate the spatial basis descriptor
space_basis=zeros(basis_dim,3);
% Populate the spatial basis descriptor
for rank=0:max_rank
% Determine the index extents
extents_upper=rank*(2*rank-1)*(2*rank+1)/3+1;
extents_lower=(1+rank)*(1+2*rank)*(3+2*rank)/3;
% Assign Wigner function ranks
space_basis(extents_upper:extents_lower,1)=rank;
% Assign Wigner function left projection indices
space_basis(extents_upper:extents_lower,2)=kron((rank:-1:-rank)',ones(2*rank+1,1));
% Assign Wigner function right projection indices
space_basis(extents_upper:extents_lower,3)=kron(ones(2*rank+1,1),(rank:-1:-rank)');
end
% Build spatial L+ generator: pick the states that can be raised
source_states=space_basis(space_basis(:,2)<space_basis(:,1),:); new_dim=size(source_states,1);
% Build spatial L+ generator: find out what they are raised into
destin_states=source_states+[zeros(new_dim,1) ones(new_dim,1) zeros(new_dim,1)];
% Build spatial L+ generator: compute the corresponding matrix elements
matrix_elements=sqrt(source_states(:,1).*(source_states(:,1)+1)-...
source_states(:,2).*(source_states(:,2)+1));
% Build spatial L+ generator: determine linear indices of source states
L=source_states(:,1); M=source_states(:,2); N=source_states(:,3);
source_state_indices=L.*(4*L.^2+6*(L-M)+5)/3-M-N+1;
% Build spatial L+ generator: determine linear indices of destination states
L=destin_states(:,1); M=destin_states(:,2); N=destin_states(:,3);
destin_state_indices=L.*(4*L.^2+6*(L-M)+5)/3-M-N+1;
% Build spatial L+ generator: form the L+ matrix
Lp=sparse(destin_state_indices,source_state_indices,matrix_elements,basis_dim,basis_dim);
% Build Lx and Ly rotation generators from L+
Lx=(Lp+Lp')/2; Ly=(Lp-Lp')/2i;
% Build Lz rotation generator
Lz=spdiags(space_basis(:,2),0,basis_dim,basis_dim);
% Do a clean-up
clear('source_states','destin_states','matrix_elements','L','M','N',...
'source_state_indices','destin_state_indices','Lp');
% Preallocate product action matrices for second-rank Wigner functions
D=cell(5);
% Build the source state list
sources=kron(space_basis,ones(5,1));
% Loop over the left projection index
for m=1:5
% Loop over the right projection index
for n=1:5
% Get the indices of the acting Wigner function
L1=2; M1=3-m; N1=3-n;
% Preallocate destination state list
destinations=zeros(5*basis_dim,3);
% Loop over the basis set
for k=1:basis_dim
% Get the source indices
L2=space_basis(k,1); M2=space_basis(k,2); N2=space_basis(k,3);
% Determine destination indices
ranks=((L2-L1):(L2+L1))';
prj_m=(M1+M2)*ones(size(ranks));
prj_n=(N1+N2)*ones(size(ranks));
% Build the destination state list
destinations((5*(k-1)+1):(5*(k-1)+5),:)=[ranks prj_m prj_n];
end
% Screen source and destination lists
L=destinations(:,1); L2=sources(:,1);
M=destinations(:,2); M2=sources(:,2);
N=destinations(:,3); N2=sources(:,3);
hit_list=(L>=max(0,abs(L2-L1)))&(abs(M)<=L)&(abs(N)<=L)&(L<=max_rank);
L=L(hit_list); L1=L1*ones(size(L)); L2=L2(hit_list);
M=M(hit_list); M1=M1*ones(size(M)); M2=M2(hit_list);
N=N(hit_list); N1=N1*ones(size(N)); N2=N2(hit_list);
% Scaling factor for the structure coefficients that is equivalent
% to normalizing the Wigner D functions used
normalization_factor=sqrt((2*L2+1)./(2*L+1));
% Compute the structure coefficients of the Wigner D functions
matrix_elements=clebsch_gordan_bypass(L,M,L1,M1,L2,M2).*...
clebsch_gordan_bypass(L,N,L1,N1,L2,N2).*...
normalization_factor;
% Assign matrix elements
destin_state_indices=L.*(4*L.^2+6*(L-M)+5)/3-M-N+1;
source_state_indices=L2.*(4*L2.^2+6*(L2-M2)+5)/3-M2-N2+1;
D{m,n}=sparse(destin_state_indices,source_state_indices,matrix_elements,basis_dim,basis_dim);
end
end
% Save the cache record
save(cache_file,'space_basis','Lx','Ly','Lz','D','-v7.3');
end
end
% Hard-coded Clebsch-Gordan formulae for the L1=2 case
function cg=clebsch_gordan_bypass(L_array,~,~,M1_array,L2_array,M2_array)
% Preallocate the answer
cg=zeros(size(L_array));
parfor n=1:numel(L_array)
% Get local variables
L=L_array(n); M1=M1_array(n); L2=L2_array(n); M2=M2_array(n);
% Enumerate all cases explicitly
switch M1
case -2
switch L
case L2-2
cg(n)=sqrt(((-3+L2+M2)*(-2+L2+M2)*(-1+L2+M2)*(L2+M2))/...
(L2*(1-L2-4*power(L2,2)+4*power(L2,3))))/2;
case L2-1
cg(n)=-(sqrt(((1+L2-M2)*(-2+L2+M2)*(-1+L2+M2)*(L2+M2))/....
(L2*(-1-2*L2+power(L2,2)+2*power(L2,3))))/sqrt(2));
case L2
cg(n)=sqrt(1.5)*sqrt(((1+L2-M2)*(2+L2-M2)*(-1+L2+M2)*(L2+M2))/...
(L2*(-3+L2*(1+4*L2*(2+L2)))));
case L2+1
cg(n)=-(sqrt(((1+L2-M2)*(2+L2-M2)*(3+L2-M2)*(L2+M2))/...
(L2*(2+7*L2+7*power(L2,2)+2*power(L2,3))))/sqrt(2));
case L2+2
cg(n)=(power(-1,-2*L2+2*M2)*sqrt(((1+L2-M2)*(2+L2-M2)*(3+L2-M2)*(4+L2-M2))/...
(6+25*L2+35*power(L2,2)+20*power(L2,3)+4*power(L2,4))))/2;
end
case -1
switch L
case L2-2
cg(n)=-sqrt(((L2-M2)*(-2+L2+M2)*(-1+L2+M2)*(L2+M2))/...
(L2*(1-L2-4*power(L2,2)+4*power(L2,3))));
case L2-1
cg(n)=((1+L2-2*M2)*sqrt(((-1+L2+M2)*(L2+M2))/...
(L2*(-1-2*L2+power(L2,2)+2*power(L2,3)))))/sqrt(2);
case L2
cg(n)=sqrt(1.5)*sqrt(((1+L2-M2)*(L2+M2))/...
(L2*(-3+L2*(1+4*L2*(2+L2)))))*(-1+2*M2);
case L2+1
cg(n)=-((power(-1,-2*L2+2*M2)*sqrt(((1+L2-M2)*(2+L2-M2))/...
(L2*(1+L2)*(2+L2)*(1+2*L2)))*(L2+2*M2))/sqrt(2));
case L2+2
cg(n)=power(-1,-2*L2+2*M2)*sqrt(((1+L2-M2)*(2+L2-M2)*(3+L2-M2)*(1+L2+M2))/...
(6+25*L2+35*power(L2,2)+20*power(L2,3)+4*power(L2,4)));
end
case 0
switch L
case L2-2
cg(n)=sqrt(1.5)*sqrt(((-1+L2-M2)*(L2-M2)*(-1+L2+M2)*(L2+M2))/...
(L2*(1-L2-4*power(L2,2)+4*power(L2,3))));
case L2-1
cg(n)=sqrt(3)*M2*sqrt((power(L2,2)-power(M2,2))/...
(L2*(-1-2*L2+power(L2,2)+2*power(L2,3))));
case L2
cg(n)=(-(L2*(1+L2))+3*power(M2,2))/...
sqrt(L2*(-3+L2*(1+4*L2*(2+L2))));
case L2+1
cg(n)=-(power(-1,-2*L2+2*M2)*sqrt(3)*M2*sqrt(((1+L2-M2)*(1+L2+M2))/...
(L2*(1+L2)*(2+L2)*(1+2*L2))));
case L2+2
cg(n)=power(-1,-2*L2+2*M2)*sqrt(3)*sqrt(((1+L2-M2)*(2+L2-M2)*(1+L2+M2)*(2+L2+M2))/...
(12+50*L2+70*power(L2,2)+40*power(L2,3)+8*power(L2,4)));
end
case 1
switch L
case L2-2
cg(n)=-sqrt(((-2+L2-M2)*(-1+L2-M2)*(L2-M2)*(L2+M2))/...
(L2*(1-L2-4*power(L2,2)+4*power(L2,3))));
case L2-1
cg(n)=-((sqrt(((-1+L2-M2)*(L2-M2))/...
((-1+L2)*L2*(1+L2)*(1+2*L2)))*(1+L2+2*M2))/sqrt(2));
case L2
cg(n)=-(power(-1,-2*L2+2*M2)*sqrt(1.5)*sqrt(((L2-M2)*(1+L2+M2))/...
(L2*(-3+L2*(1+4*L2*(2+L2)))))*(1+2*M2));
case L2+1
cg(n)=(power(-1,-2*L2+2*M2)*(L2-2*M2)*sqrt(((1+L2+M2)*(2+L2+M2))/...
(L2*(2+7*L2+7*power(L2,2)+2*power(L2,3)))))/sqrt(2);
case L2+2
cg(n)=power(-1,-2*L2+2*M2)*sqrt(((1+L2-M2)*(1+L2+M2)*(2+L2+M2)*(3+L2+M2))/...
(6+25*L2+35*power(L2,2)+20*power(L2,3)+4*power(L2,4)));
end
case 2
switch L
case L2-2
cg(n)=sqrt(((-3+L2-M2)*(-2+L2-M2)*(-1+L2-M2)*(L2-M2))/...
(L2*(1-L2-4*power(L2,2)+4*power(L2,3))))/2;
case L2-1
cg(n)=(power(-1,-2*L2+2*M2)*sqrt(((-2+L2-M2)*(-1+L2-M2)*(L2-M2)*(1+L2+M2))/...
(L2*(-1-2*L2+power(L2,2)+2*power(L2,3)))))/sqrt(2);
case L2
cg(n)=power(-1,-2*L2+2*M2)*sqrt(1.5)*sqrt(((-1+L2-M2)*(L2-M2)*(1+L2+M2)*(2+L2+M2))/...
(L2*(-3+L2*(1+4*L2*(2+L2)))));
case L2+1
cg(n)=(power(-1,-2*L2+2*M2)*sqrt(((L2-M2)*(1+L2+M2)*(2+L2+M2)*(3+L2+M2))/...
(L2*(2+7*L2+7*power(L2,2)+2*power(L2,3)))))/sqrt(2);
case L2+2
cg(n)=(power(-1,-2*L2+2*M2)*sqrt(((1+L2+M2)*(2+L2+M2)*(3+L2+M2)*(4+L2+M2))/...
(6+25*L2+35*power(L2,2)+20*power(L2,3)+4*power(L2,4))))/2;
end
end
end
end
% Consistency enforcement
function grumble(max_rank)
if (numel(max_rank)~=1)||(~isnumeric(max_rank))||(~isreal(max_rank))||...
(max_rank<1)||(mod(max_rank,1)~=0)
error('max_rank must be a real positive integer.');
end
end
% To invent, you need a good imagination and a pile of junk.
%
% Thomas Edison
|
github
|
tsajed/nmr-pred-master
|
fminsimplex.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/fminsimplex.m
| 13,910 |
utf_8
|
d3bff5cd1d377cf7d5a96e32dd76ddbe
|
% Nelder-Mead and Multi-directional search simplex algorithms for
% minimisation of a gradient-free objective function
%
% <http://spindynamics.org/wiki/index.php?title=Fminsimplex.m>
function [x, f_min, data] = fminsimplex(cost_function, x, optim, cost_fun_vars)
x0 = x(:); data.x_shape=size(x); % Work with column vector internally.
data.n_vars = numel(x0);
% Always Bootstrap and set optimisation tolerances
% - assume user isn't optimisation expert
optim.cost_function=cost_function;
optim=optim_tols(optim,data.n_vars);
% add cost function variables to the data structure (empty if not provided)
if ~exist('cost_fun_vars','var'), cost_fun_vars=[]; end
data.cost_fun_vars=cost_fun_vars;
% penalty terms to consider (default=0), affects output display only.
data.npen=optim.algo.npen;
X = [zeros(data.n_vars,1) eye(data.n_vars)];
X(:,1) = x0; data.n_fx=0;
data.iter = 0; data.iter_inner = 0;
data.parallel_cost_fcn=optim.algo.parallel_cost_fcn;
data.timeTotal=tic; data.time_fx=0; data.iter_timer=tic;
% Set up initial simplex.
scale = max(norm(x0,inf),1);
switch optim.algo.init_simplex
case {'equilateral'}
% Regular simplex - all edges have same length.
% Generated from construction given in reference [18, pp. 80-81] of [1].
alpha = scale / (data.n_vars*sqrt(2)) * [ sqrt(data.n_vars+1)-1+data.n_vars sqrt(data.n_vars+1)-1 ];
X(:,2:data.n_vars+1) = (x0 + alpha(2)*ones(data.n_vars,1)) * ones(1,data.n_vars);
for j=2:data.n_vars+1
X(j-1,j) = x0(j-1) + alpha(1);
end
case {'right-angled'}
% Right-angled simplex based on co-ordinate axes.
alpha = scale*ones(data.n_vars+1,1);
for j=2:data.n_vars+1
X(:,j) = x0 + alpha(j)*X(:,j);
end
end
% find simplex functional values (cost function should be parallel)
[data,f_x]=objeval(X,cost_function, data);
fmin_old = f_x(1);
% print optimisation header
iterative_reporting([],[],'head',[],optim,data);
exitflag=[]; data.how=' initial'; data.size = 0;
data.n_fx = data.n_vars+1;
[f_x,j] = sort(f_x); X = X(:,j);
f_min = f_x(1); x_min = X(:,1);
data.size_simplex = norm(X(:,2:data.n_vars+1)-x_min*ones(1,data.n_vars),1) / max(1, norm(x_min,1));
% Start optimisation
while(true)
% define the minimum
f_min = f_x(1);
% Add one to the current iteration
data.itertime=toc(data.iter_timer); data.iter_timer=tic; data.iter = data.iter+1;
% check if iterations exceeds maximum
if(optim.tols.max_iter < data.iter), exitflag=-1; break, end
if f_min < fmin_old
% report diagnostics to user
data.size_simplex = norm(X(:,2:data.n_vars+1)-x_min*ones(1,data.n_vars),1) / max(1, norm(x_min,1));
iterative_reporting(f_min,fmin_old,'iter',exitflag,optim,data);
% Call output function if specified
if(output_function(optim.sys.outputfun,'iter')), exitflag=-1; break, end
end
x_min = X(:,1); fmin_old = f_min;
% Stopping Test 1 - f reached target value?
if f_min <= optim.tols.termination ,exitflag = 0; break, end
switch optim.algo.method
case 'md_simplex'
data.iter_inner = 0;
while(true) %%% Inner repeat loop.
data.iter_inner = data.iter_inner+1;
% Stopping Test 2 - too many f-evals?
if data.n_fx >= optim.tols.max_n_fx, exitflag = 1; break, end
% Stopping Test 3 - converged? test (4.3) in [1].
data.size_simplex = norm(X(:,2:data.n_vars+1)-x_min*ones(1,data.n_vars),1) / max(1, norm(x_min,1));
if data.size_simplex <= optim.tols.simplex_min, exitflag = 2; break, end
X_r=zeros(length(x_min),data.n_vars);
for j=1:data.n_vars % ---Rotation (reflection) step.
X_r(:,j) = x_min - (X(:,j+1)-x_min);
end
[data,f_r]=objeval(X_r,cost_function, data);
replaced = ( min(f_r) < f_min);
if replaced
X_e=zeros(length(x_min),data.n_vars);
for j=1:data.n_vars % ---Expansion step.
X_e(:,j) = x_min - optim.tols.expansion*(X_r(:,j)-x_min);
end
[data,f_e]=objeval(X_e,cost_function, data);
% Accept expansion or rotation?
if min(f_e) < min(f_x)
X(:,2:data.n_vars+1) = X_e;
f_x(2:data.n_vars+1) = f_e; % Accept rotation.
data.size = data.size + 1; % Accept expansion (f and V already set).
data.how=' expand';
else
X(:,2:data.n_vars+1) = X_r;
f_x(2:data.n_vars+1) = f_r; % Accept rotation.
data.how=' reflect';
end
else
X_c=zeros(length(x_min),data.n_vars);
for j=1:data.n_vars % ---Contraction step.
X_c(:,j) = x_min + optim.tols.contraction*(X(:,j+1)-x_min);
end
[data,f_c]=objeval(X_c,cost_function, data);
replaced = (min(f_c) < f_min);
data.how='contract';
% Accept contraction (f and V already set).
X(:,2:data.n_vars+1) = X_c;
f_x(2:data.n_vars+1) = f_c; % Accept rotation.
data.size = data.size - 1;
end
[f_x,j]=sort(f_x); X = X(:,j);
if replaced, break, end
if optim.sys.output && rem(data.iter_inner,10) == 0
optim_report(optim.sys.output,[' ...inner iterations = ' int2str(data.iter_inner)],1);
end
end %%% Of inner repeat loop.
if ~isempty(exitflag), break, end
case 'nm_simplex'
% Stopping Test 2 - too many f-evals?
if data.n_fx >= optim.tols.max_n_fx, exitflag = 1; break, end
% Stopping Test 3 - converged? test (4.3) in [1].
x_min = X(:,1);
data.size_simplex = norm(X(:,2:data.n_vars+1)-x_min*ones(1,data.n_vars),1) / max(1, norm(x_min,1));
if data.size_simplex <= optim.tols.simplex_min, exitflag = 2; break, end
% One step of the Nelder-Mead simplex algorithm
vbar = sum(X(:,1:data.n_vars),2)./data.n_vars; % Mean value
X_r = (1 + optim.tols.reflection)*vbar - optim.tols.reflection*X(:,data.n_vars+1); x = X_r(:);
[data,f_r]=objeval(x,cost_function, data);
X_k = X_r; f_k = f_r; data.how = ' reflect';
if f_r < f_x(1)
if f_r < f_x(1)
X_e = optim.tols.expansion*X_r + (1-optim.tols.expansion)*vbar; x = X_e(:);
[data,f_e]=objeval(x,cost_function, data);
if f_e < f_x(1)
X_k = X_e; f_k = f_e;
data.how = ' expand';
end
end
else
X_t = X(:,1); f_t = f_x(1);
if f_r < f_t
X_t = X_r; f_t = f_r;
end
X_c = optim.tols.contraction*X_t + (1-optim.tols.contraction)*vbar; x = X_c(:);
[data,f_c]=objeval(x,cost_function, data);
if f_c < f_x(data.n_vars)
X_k = X_c; f_k = f_c;
data.how = 'contract';
else
for j = 2:data.n_vars
X(:,j) = (X(:,1) + X(:,j))/2;
end
[data,f_x]=objeval(X,cost_function, data);
X_k = (X(:,1) + X(:,data.n_vars+1))/2; x(:) = X_k;
[data,f_k]=objeval(x,cost_function, data);
data.how = ' shrink';
end
end
X(:,data.n_vars+1) = X_k;
f_x(data.n_vars+1) = f_k;
[f_x,j] = sort(f_x); X = X(:,j);
end
end %%%%%% Of outer loop.
% Call output function if specified
if(output_function(optim.sys.outputfun,'done')), exitflag=-2; end
% Finished.
switch optim.algo.method
case 'md_simplex'
x(:) = x_min;
x=reshape(x,data.x_shape);
case 'nm_simplex'
x(:) = X(:,1);
x=reshape(x,data.x_shape);
end
data=iterative_reporting(f_min,fmin_old,'term',exitflag,optim,data);
function exit=output_function(outputfun,where)
exit=false; % initialise
if(~isempty(outputfun)) % data structure to output function
% <add any variable to export here>
% if exit is returned as true, optimisation will finish
if isempty(opt_arg)
exit=feval(outputfun,reshape(x,data.x_shape),data,where);
else
exit=feval(outputfun,reshape(x,data.x_shape),data,where,opt_arg);
end
end
end
end
function data=iterative_reporting(fx_min,fmin_old,report_case,exitflag,optim,data)
switch report_case
case {'head'}
% Report start of optimisation to user
switch(optim.algo.method)
case 'nm_simplex', optim_report(optim.sys.output,'start optimisation using Nelder-Mead, simplex method',1);
case 'md_simplex', optim_report(optim.sys.output,'start optimisation using Multi-directional, simplex method',1);
end
optim_report(optim.sys.output,['Cost Function = @', func2str(optim.sys.costfun.handle)],1);
optim_report(optim.sys.output,'==============================================================================================',1);
obj_fun_str=[blanks(17) optim.sys.obj_fun_str]; obj_fun_str=obj_fun_str(end-17:end);
if ismember(optim.algo.method,{'nm_simplex'})
optim_report(optim.sys.output,['Iter Time #f(x) how ' obj_fun_str ' splx-size Change'],1);
elseif ismember(optim.algo.method,{'md_simplex'})
optim_report(optim.sys.output,['Iter Time #f(x) how InIter ' obj_fun_str ' splx-size Change'],1);
end
optim_report(optim.sys.output,'----------------------------------------------------------------------------------------------',1);
case {'iter'}
t=data.itertime;
if t<1e-3, Tstr=sprintf('%5.0e',t); elseif t<10, Tstr=sprintf('%5.3f',t); elseif t<1e2, Tstr=sprintf('%5.2f', t);
elseif t<1e3, Tstr=sprintf('%5.1f',t); elseif t<=99999, Tstr=sprintf('%5.0f',t); else Tstr=sprintf('%5.0e',t);
end
% Report optimisation iterasation to user
if ismember(optim.algo.method,{'nm_simplex'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f ' data.how ' %17.9g %10.5g (%2.1f%%)'],...
data.iter,data.n_fx,optim.sys.obj_fun_disp(fx_min),data.size_simplex,100*(fx_min-fmin_old)/(abs(fmin_old)+eps)),1);
elseif ismember(optim.algo.method,{'md_simplex'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f ' data.how ' %5.0f %17.9g %10.5g (%2.1f%%)'],...
data.iter,data.n_fx,data.iter_inner,optim.sys.obj_fun_disp(fx_min),data.size_simplex,100*(fx_min-fmin_old)/(abs(fmin_old)+eps)),1);
end
case {'term'}
optim_report(optim.sys.output,'==============================================================================================',1);
% Make exist output structure
switch(optim.algo.method)
case 'nm_simplex', data.algorithm='Nelder-Mead Simplex method';
case 'md_simplex', data.algorithm='Multi-directional Simplex method';
end
% report optimisation results to user
data.exit_message=exitmessage(exitflag);
data.minimum = optim.sys.obj_fun_disp(fx_min);
data.timeTotal=toc(data.timeTotal);
data.timeIntern=data.timeTotal-data.time_fx;
optim_report(optim.sys.output,'Optimisation Results',1)
optim_report(optim.sys.output,[' Algorithm Used : ' data.algorithm],1);
optim_report(optim.sys.output,[' Exit message : ' data.exit_message],1);
optim_report(optim.sys.output,[' Iterations : ' int2str(data.iter)],1);
optim_report(optim.sys.output,[' Function Count : ' int2str(data.n_fx)],1);
optim_report(optim.sys.output,[' Minimum found : ' num2str(data.minimum)],1);
optim_report(optim.sys.output,[' Optimiser Time : ' num2str(data.timeIntern) ' seconds'],1);
optim_report(optim.sys.output,[' Function calc Time : ' num2str(data.time_fx) ' seconds'],1);
optim_report(optim.sys.output,[' Total Time : ' num2str(data.timeTotal) ' seconds'],1);
optim_report(optim.sys.output,'==============================================================================================',1);
if ~isinteger(optim.sys.output) && optim.sys.output>=3, optim_report(optim.sys.output,[],[],true); end
pause(1.5);
end
end
function message=exitmessage(exitflag)
switch(exitflag) % list of exiflag messages
case 2, message='Simplex size less than defined tolerance <simplex_min>';
case 1, message='Max no. of function evaluations exceeded.';
case 0, message='Exceeded target.';
case -1, message='Max no. of iterations exceeded.';
case -2, message='Algorithm was terminated by the output function.';
otherwise, message='Undefined exit code';
end
end
% Seek freedom and become captive of your desires. Seek discipline and find
% your liberty.
%
% Frank Herbert
|
github
|
tsajed/nmr-pred-master
|
control_sys.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/control_sys.m
| 6,790 |
utf_8
|
57f9087ab0a0c20d9456ed9d05a872c3
|
% Options and structure creation for a control system. Sets the various
% options used throughout optimal control algorithms.
%
% Modifications to this function are discouraged -- the accuracy settings
% should be modified by setting the sub-fields of the ctrl_param structure.
%
% <http://spindynamics.org/wiki/index.php?title=Control_sys.m>
function ctrl_param=control_sys(spin_system,control_system)
% list of CONTROL algorithms
% >>>>-add to lists as appropriate-<<<<
optimcon_algos={'grape','tannor','zhu-rabitz'};
% ========================== STRUCT = OPTIM.SYS ==========================
% store the cost function handle; throw error is not supplied - should
% always be supplied if used with fminnewton: inherited from fminnewton
% inputs
% control banner
if isfield(control_system,'method') && ismember(control_system.method,optimcon_algos)
ctrl_param.method=control_system.method;
control_system=rmfield(control_system,'method'); % parsed -> remove
else
error('must provide a control method e.g. grape, tannor, or zhu-rabitz')
end
optim_report(spin_system.sys.output,' ');
optim_report(spin_system.sys.output,'===========================================');
optim_report(spin_system.sys.output,'= =');
optim_report(spin_system.sys.output,'= CONTROLS =');
optim_report(spin_system.sys.output,'= =');
optim_report(spin_system.sys.output,'===========================================');
optim_report(spin_system.sys.output,' ');
optim_report(spin_system.sys.output,[pad('Control algorithm',80) pad(ctrl_param.method,20) ' ']);
controls=control_system.control_ops; num_ctrls=numel(controls);
ctrl_param.control_ops=controls;
ctrl_param.comm_rel=zeros(num_ctrls);
for n=1:num_ctrls
for m=1:num_ctrls
ctrl_param.comm_rel(n,m)=1-any(any(controls{n}*controls{m}-controls{m}*controls{n}));
end
end
optim_report(spin_system.sys.output,[pad('Number of control operators',80) pad(int2str(num_ctrls),20) ' (calculated)']);
control_system=rmfield(control_system,'control_ops'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Pairwise non-commuting control operators',80) pad(int2str((sum(ctrl_param.comm_rel(:)==0))./2),20) ' (calculated)']);
% test for hermitian control_ops
if ~all(cellfun(@ishermitian,ctrl_param.control_ops))
optim_report(spin_system.sys.output,pad('WARNING: not all control operators are Hermitian',80));
end
if isfield(control_system,'target')
ctrl_param.target=control_system.target;
control_system=rmfield(control_system,'target'); % parsed -> remove
end
if isfield(control_system,'rho')
ctrl_param.rho=control_system.rho;
control_system=rmfield(control_system,'rho'); % parsed -> remove
end
if isfield(control_system,'ref_waveform') && ~ismember(ctrl_param.method,{'grape'})
ctrl_param.ref_waveform=control_system.ref_waveform;
control_system=rmfield(control_system,'ref_waveform'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Reference waveform provided',80) pad('true',20) ' (user-specified)']);
elseif ~ismember(ctrl_param.method,{'grape'})
optim_report(spin_system.sys.output,[pad('Reference waveform provided',80) pad('false',20) ' (default)']);
end
if isfield(control_system,'power_level') && control_system.power_level>0
ctrl_param.power_level=control_system.power_level;
control_system=rmfield(control_system,'power_level'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Control pulse control amplitude (rad/s)',80) pad(num2str(ctrl_param.power_level,'%0.6g'),20) ' (user-specified)']);
end
if ismember(ctrl_param.method,{'tannor','zhu-rabitz'})
if isfield(control_system,'krotov_microiteration')
ctrl_param.krotov_microiteration=control_system.krotov_microiteration;
control_system=rmfield(control_system,'krotov_microiteration'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Krotov microiteration tolerance',80) pad(num2str(ctrl_param.krotov_microiteration,'%0.8e'),20) ' (user-specified)']);
else
ctrl_param.krotov_microiteration=1e-6;
optim_report(spin_system.sys.output,[pad('Krotov microiteration tolerance',80) pad(num2str(ctrl_param.krotov_microiteration,'%0.8e'),20) ' (safe default)']);
end
if isfield(control_system,'lambda')
ctrl_param.lambda=control_system.lambda;
control_system=rmfield(control_system,'lambda'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('krotov lagrange multiplier, lambda',80) pad(num2str(ctrl_param.lambda,'%0.8e'),20) ' (user-specified)']);
else
ctrl_param.lambda=1e-3;
optim_report(spin_system.sys.output,[pad('krotov lagrange multiplier, lambda',80) pad(num2str(ctrl_param.lambda,'%0.8e'),20) ' (safe default)']);
end
end
if isfield(control_system,'pulse_duration') && control_system.pulse_duration>0
ctrl_param.pulse_duration=control_system.pulse_duration;
control_system=rmfield(control_system,'pulse_duration'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Total duration of control pulses (s)',80) pad(num2str(ctrl_param.pulse_duration,'%0.6g'),20) ' (user-specified)']);
if isfield(control_system,'nsteps') && mod(1,control_system.nsteps+1) && control_system.nsteps>0
ctrl_param.nsteps=control_system.nsteps;
control_system=rmfield(control_system,'nsteps'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Number of control pulse',80) pad(int2str(ctrl_param.nsteps),20) ' (user-specified)']);
if isfield(control_system,'time_step') && control_system.time_step==ctrl_param.pulse_duration/ctrl_param.nsteps
ctrl_param.time_step=control_system.time_step;
control_system=rmfield(control_system,'time_step'); % parsed -> remove
optim_report(spin_system.sys.output,[pad('Length of single control pulse (s)',80) pad(num2str(ctrl_param.time_step,'%0.6g'),20) ' (user-specified)']);
end
end
end
%optim_report(optim_param.sys.output,[pad('Penalty function type',80) pad(int2str(1),20) 'TODO']);
unprocessed=fieldnames(control_system);
if ~isempty(unprocessed)
optim_report(spin_system.sys.output,'----------------------------------------------------------------------------------------------');
for n=1:numel(unprocessed)
optim_report(spin_system.sys.output,[pad('WARNING: unprocessed option',80) pad(unprocessed{n},20)]);
end
optim_report(spin_system.sys.output,'----------------------------------------------------------------------------------------------');
end
end
|
github
|
tsajed/nmr-pred-master
|
fminnewton.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/fminnewton.m
| 17,628 |
utf_8
|
15ea3b38da97ebf79602ae45fa5bfee0
|
% Finds a local minimum of a function of several variables using
% newton-based algorithms.
%
% Based on fminlbfgs.m code from D. Kroon, University of Twente (Nov 2010).
%
% <http://spindynamics.org/wiki/index.php?title=Fminnewton.m>
function [x,fx,grad,hess,data]=fminnewton(cost_function,x_0,optim,hess_init,cost_fun_vars)
% Initialize the structure of the initial guess
x = x_0(:); data.x_shape=size(x_0); data.n_vars = numel(x_0);
% Always Bootstrap and set optimisation tolerances
% - assume user isn't optimisation expert
optim.cost_function=cost_function;
optim=optim_tols(optim,data.n_vars);
% initialise counters and timers
data.iter=0; data.n_fx=0; data.n_grad=0; data.n_hess=0; data.n_cond=0; data.firstorderopt=[];
data.timeTotal=tic; data.time_fx=0; data.time_gfx=0; data.time_hfx=0; data.iter_timer=tic;
% add cost function variables to the data structure (empty if not provided)
if ~exist('cost_fun_vars','var'), cost_fun_vars=[]; end
data.cost_fun_vars=cost_fun_vars;
% penalty terms to consider (default=0), affects output display only.
data.npen=optim.algo.npen;
% initialise lbfgs memory counter
if ismember(optim.algo.method,{'lbfgs'}),
store.lbfgs_store=0;
store.n_store=optim.algo.n_store; optim.algo=rmfield(optim.algo,'n_store');
store.deltaX=optim.algo.deltaX; optim.algo=rmfield(optim.algo,'deltaX');
store.deltaG=optim.algo.deltaG; optim.algo=rmfield(optim.algo,'deltaG');
end
% print optimisation header
iterative_reporting([],[],'head',[],optim,data);
% set initial Hessian approximation if given, for bfgs or sr1
if ismember(optim.algo.method,{'bfgs','sr1'}) && exist('hess_init','var')
hess=hess_init;
else
hess=eye(data.n_vars);
end
% initialise exitflag, functional and its derivatives
exitflag=[]; fx=[]; grad=[]; alpha=0; dir=[];
% send to output function if defined
if(output_function(optim.sys.outputfun,'init')), exitflag=-1; end
% Start optimisation
while(true)
% Calculate the initial error and gradient and hessian
if ismember(optim.algo.method,{'newton'}) && isempty(exitflag)
[data,fx,grad,hess]=objeval(x(:),cost_function, data);
elseif isempty(grad) && isempty(exitflag)
[data,fx,grad]=objeval(x(:),cost_function, data);
end
% check if iterations exceeds maximum
if(optim.tols.max_iter <= data.iter), exitflag=0; end
%search direction (p_current)
if(isempty(exitflag)), [dir,grad,hess,data]=search_dir(grad,hess,optim,data,dir); end
if(isempty(exitflag)), data.firstorderopt=norm(grad,Inf); end
% Show the current iteration information
data.itertime=toc(data.iter_timer); data.iter_timer=tic;
% report diagnostics to user
iterative_reporting(fx,alpha,'iter',exitflag,optim,data);
% Call output function if specified
if(output_function(optim.sys.outputfun,'iter')), exitflag=-1; end
% Check if exitflag is set
if(~isempty(exitflag)), break, end
% Keep the variables for next iteration
store.fx=fx; store.x=x(:); store.grad=grad(:);
% make a linesearch in the search direction
[alpha,fx,grad,exitflag,data] = linesearch(cost_function,...
dir, x, fx, grad, data, optim);
if isempty(fx), fx=store.fx; grad=store.grad; x=store.x; end
% update current x with search direction and step length
x=x+alpha*dir;
% hessian update if quasi-newton
if ismember(optim.algo.method,{'lbfgs','bfgs','sr1'}) && (isempty(exitflag))
% required when the linesearch has used the newton step
if isempty(grad)
[data,fx,grad]=objeval(x(:),cost_function, data);
end
[hess,dir,store]=hessian_update(x,grad,hess,store,optim.algo);
end
% Update number of iterations
if (isempty(exitflag)), data.iter=data.iter+1; end
% Gradient norm too small, change in x too small, terminal functional value reached.
if(optim.algo.max_min*optim.tols.fx < optim.algo.max_min*fx), exitflag=4; end
if(optim.tols.x > max(abs(store.x-x))), exitflag=2; end
if(optim.tols.gfx > data.firstorderopt), exitflag=1; end
end
% Call output function if specified
if(output_function(optim.sys.outputfun,'done')), exitflag=-1; end
% ensure outputs exist, if not then re-evaluate
if ismember(optim.algo.method,{'newton'}) && isempty(grad)
[data,fx,grad,hess]=objeval(x(:),cost_function, data);
elseif isempty(grad)
[data,fx,grad]=objeval(x(:),cost_function, data);
end
% Set outputs
x=reshape(x,data.x_shape); grad=reshape(grad,data.x_shape);
data=iterative_reporting(fx,alpha,'term',exitflag,optim,data);
function exit=output_function(outputfun,where)
exit=false; % initialise
if(~isempty(outputfun)) % data structure to output function
% <add any variable to export here>
% if exit is returned as true, optimisation will finish
exit=feval(outputfun,reshape(x,data.x_shape),data,where);
end
end
end
function [dir,grad,hess,data]=search_dir(grad,hess,optim,data,dir)
% find the search direction
switch optim.algo.method
case {'grad_descent','grad_ascent'}
% set the search direction as the gradient direction
dir=grad;
case 'lbfgs'
% calculate the direction for the first iterate only
if data.iter==0, dir=optim.algo.max_min.*grad; end
case {'sr1','bfgs','newton'}
% prepare the Hessian to be definite and well-conditioned
[grad,hess,data]=hessprep(grad,hess,optim,data);
% force real and symmetric hessian
if ~isreal(hess), hess=real(hess); grad=real(grad); end
if ~issymmetric(hess), hess=(hess+hess')./2; end
% calculate the search direction from the Hessian and the gradient
if xor((strcmp(optim.reg.method,'CHOL') && data.n_cond>0), optim.algo.inv_method)
dir = -hess*grad;
else dir = -hess\grad;
end
end
end
function [hess,dir,store] = hessian_update(x,grad,hess,store,algo)
switch algo.method
case 'lbfgs' % limited-memory-BFGS
% Update a list with the history of deltaX and deltaG
store.deltaX=[x-store.x store.deltaX(:,1:store.n_store-1)];
store.deltaG=[grad-store.grad store.deltaG(:,1:store.n_store-1)];
% size of store of deltaX and deltaG
store.lbfgs_store=min(store.lbfgs_store+1, store.n_store);
% Set new Direction with L-BFGS with scaling as described by Nocedal
dir=lbfgs(store.deltaX, store.deltaG, grad, store.lbfgs_store);
case {'bfgs','sr1'}
% calculate BFGS Hessian update
hess=quasinewton(hess, x, store.x, -algo.max_min*grad, -algo.max_min*store.grad, algo.inv_method, algo.method);
dir=[]; % no search direction yet
otherwise
error('unsupported quasi-Newton hessian update method')
end
end
function data=iterative_reporting(fx,alpha,report_case,exitflag,optim,data)
switch report_case
case {'head'}
% Report start of optimisation to user
switch(optim.algo.method)
case 'sr1', optim_report(optim.sys.output,['start ' optim.algo.extremum(1:5) 'isation using quasi-newton, Symmetric Rank 1 Hessian update'],1);
case 'bfgs', optim_report(optim.sys.output,['start ' optim.algo.extremum(1:5) 'isation using quasi-newton, BFGS method'],1);
case 'lbfgs', optim_report(optim.sys.output,['start ' optim.algo.extremum(1:5) 'isation using quasi-newton, limited memory BFGS method'],1);
case 'grad_descent', optim_report(optim.sys.output,['start ' optim.algo.extremum(1:5) 'isation using Steepest Gradient Descent method'],1);
case 'grad_ascent', optim_report(optim.sys.output,['start ' optim.algo.extremum(1:5) 'isation using Steepest Gradient Ascent method'],1);
case 'newton', optim_report(optim.sys.output,['start ' optim.algo.extremum(1:5) 'isation using Newton-Raphson method'],1);
end
optim_report(optim.sys.output,['Cost Function = @', func2str(optim.sys.costfun.handle)],1);
obj_fun_str=[blanks(17) optim.sys.obj_fun_str]; obj_fun_str=obj_fun_str(end-17:end);
if ~optim.algo.pen
optim_report(optim.sys.output,'==============================================================================================',1);
if ismember(optim.reg.method,{'RFO','TRM'}) || optim.reg.track_eig
optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #H(x) min|eig| #cond cond(H) ' obj_fun_str ' Step-size 1st-optim'],1);
elseif ismember(optim.reg.method,{'CHOL','reset'})
optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #H(x) #reg ' obj_fun_str ' Step-size 1st-optim'],1);
else optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #H(x) ' obj_fun_str ' Step-size 1st-optim'],1);
end
optim_report(optim.sys.output,'----------------------------------------------------------------------------------------------',1);
else
optim_report(optim.sys.output,'==========================================================================================================',1);
if ismember(optim.reg.method,{'RFO','TRM'}) || optim.reg.track_eig
optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #H(x) min|eig| #cond cond(H) ' obj_fun_str ' sum(pen) Step-size 1st-optim'],1);
elseif ismember(optim.reg.method,{'CHOL','reset'})
optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #H(x) #reg ' obj_fun_str ' sum(pen) Step-size 1st-optim'],1);
else optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #H(x) ' obj_fun_str ' sum(pen) Step-size 1st-optim'],1);
end
optim_report(optim.sys.output,'----------------------------------------------------------------------------------------------------------',1);
end
case {'iter'}
% Report optimisation iterate to user
t=data.itertime;
if t<1e-3, Tstr=sprintf('%5.0e',t); elseif t<10, Tstr=sprintf('%5.3f',t); elseif t<1e2, Tstr=sprintf('%5.2f', t);
elseif t<1e3, Tstr=sprintf('%5.1f',t); elseif t<=99999, Tstr=sprintf('%5.0f',t); else Tstr=sprintf('%5.0e',t);
end
if ~optim.algo.pen
if (ismember(optim.reg.method,{'RFO','TRM'}) && (isfield(data,'n_cond') && data.n_cond>0)) || optim.reg.track_eig
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %8.3g %4.0f %9.3g %17.9g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,data.hess_mineig,data.n_cond,data.hess_cond,optim.sys.obj_fun_disp(fx),alpha,data.firstorderopt),1);
elseif ismember(optim.reg.method,{'RFO','TRM'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %8.1s %4.0f %9.1s %17.9g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,'-',0,'-',optim.sys.obj_fun_disp(fx),alpha,data.firstorderopt),1);
elseif ismember(optim.reg.method,{'CHOL','reset'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %5.0f %17.9g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,data.n_cond,optim.sys.obj_fun_disp(fx),alpha,data.firstorderopt),1);
else optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %17.9g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,optim.sys.obj_fun_disp(fx),alpha,data.firstorderopt),1);
end
else
if (ismember(optim.reg.method,{'RFO','TRM'}) && (isfield(data,'n_cond') && data.n_cond>0)) || optim.reg.track_eig
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %8.3g %4.0f %9.3g %17.9g %10.4g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,data.hess_mineig,data.n_cond,data.hess_cond,...
optim.sys.obj_fun_disp(data.fx_sep_pen(1)),optim.sys.obj_fun_disp(sum(data.fx_sep_pen(2:end))),alpha,data.firstorderopt),1);
elseif ismember(optim.reg.method,{'RFO','TRM'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %8.1s %4.0f %9.1s %17.9g %10.4g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,'-',0,'-',...
optim.sys.obj_fun_disp(data.fx_sep_pen(1)),optim.sys.obj_fun_disp(sum(data.fx_sep_pen(2:end))),alpha,data.firstorderopt),1);
elseif ismember(optim.reg.method,{'CHOL','reset'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %5.0f %17.9g %10.4g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,data.n_cond,...
optim.sys.obj_fun_disp(data.fx_sep_pen(1)),optim.sys.obj_fun_disp(sum(data.fx_sep_pen(2:end))),alpha,data.firstorderopt),1);
else optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %17.9g %10.4g %10.5g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_hess,...
optim.sys.obj_fun_disp(data.fx_sep_pen(1)),optim.sys.obj_fun_disp(sum(data.fx_sep_pen(2:end))),alpha,data.firstorderopt),1);
end
end
case {'term'}
% Make exit output structure
optim_report(optim.sys.output,'==============================================================================================',1);
switch(optim.algo.method)
case 'sr1', data.algorithm='Symmetric Rank 1 Hessian update (SR1)';
case 'bfgs', data.algorithm='Broyden-Fletcher-Goldfarb-Shanno Hessian update (BFGS)';
case 'lbfgs', data.algorithm='limited memory Broyden-Fletcher-Goldfarb-Shanno update (L-BFGS)';
case 'grad_descent', data.algorithm='Steepest Gradient Descent';
case 'grad_ascent', data.algorithm='Steepest Gradient Ascent';
case 'newton', data.algorithm='Newton-Raphson method';
end
% report optimisation results to user
data.exit_message=exitmessage(exitflag);
data.extremum = optim.sys.obj_fun_disp(fx);
data.timeTotal=toc(data.timeTotal);
data.timeIntern=data.timeTotal-data.time_fx-data.time_gfx-data.time_hfx;
optim_report(optim.sys.output,'Optimisation Results',1)
optim_report(optim.sys.output,[' Algorithm Used : ' data.algorithm],1);
optim_report(optim.sys.output,[' Exit message : ' data.exit_message],1);
optim_report(optim.sys.output,[' Iterations : ' int2str(data.iter)],1);
optim_report(optim.sys.output,[' Function Count : ' int2str(data.n_fx)],1);
optim_report(optim.sys.output,[' Gradient Count : ' int2str(data.n_grad)],1);
optim_report(optim.sys.output,[' Hessian Count : ' int2str(data.n_hess)],1);
optim_report(optim.sys.output,[' M' optim.algo.extremum(2:end) ' found : ' num2str(data.extremum)],1);
optim_report(optim.sys.output,[' norm(gradient) : ' num2str(data.firstorderopt)],1);
optim_report(optim.sys.output,[' Optimiser Time : ' num2str(data.timeIntern) ' seconds'],1);
optim_report(optim.sys.output,[' Function calc Time : ' num2str(data.time_fx) ' seconds'],1);
optim_report(optim.sys.output,[' Gradient calc Time : ' num2str(data.time_gfx) ' seconds'],1);
optim_report(optim.sys.output,[' Hessian calc Time : ' num2str(data.time_hfx) ' seconds'],1);
optim_report(optim.sys.output,[' Total Time : ' num2str(data.timeTotal) ' seconds'],1);
optim_report(optim.sys.output,'==============================================================================================',1);
if isnumeric(optim.sys.output) && optim.sys.output>=3, optim_report(optim.sys.output,[],[],true); end
end
end
function message=exitmessage(exitflag)
% list of exiflag messages
switch(exitflag)
case 1, message='Change in gradient norm less than specified tolerance, tol_gfx.';
case 2, message='Change in x was smaller than the specified tolerance, tol_x.';
case 3, message='Boundary reached.';
case 4, message='Specified terminal functional value reached';
case 0, message='Number of iterations exceeded the specified maximum.';
case -1, message='Algorithm was terminated by the output function.';
case -2, message='Line search cannot find an acceptable point along the current search';
case -3, message='Hessian matrix is not positive definite';
otherwise, message='Undefined exit code';
end
end
% There is a sacred horror about everything grand. It is easy to admire
% mediocrity and hills; but whatever is too lofty, a genius as well as a
% mountain, an assembly as well as a masterpiece, seen too near, is
% appalling... People have a strange feeling of aversion to anything grand.
% They see abysses, they do not see sublimity; they see the monster, they
% do not see the prodigy.
%
% Victor Hugo - Ninety-three
|
github
|
tsajed/nmr-pred-master
|
optim_report.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/optim_report.m
| 1,757 |
utf_8
|
f7dd7f8057046240b90b693d6bed03a2
|
% Writes a log message to the console or an ACSII file. Syntax:
%
% <http://spindynamics.org/wiki/index.php?title=Optim_report.m>
function optim_report(output,report_string,depth,close_file)
% close all open files if selected
if nargin==4 && islogical(close_file) && close_file,
fclose('all');
return;
end
% Ignore the call if the system is hushed
if ~strcmp(output,'hush')
% Validate the input
grumble(output,report_string);
% Compose the prefix
call_stack=dbstack;
for n=1:numel(call_stack)
call_stack(n).name=[call_stack(n).name ' > '];
end
if ~exist('depth','var'), depth=0;
elseif depth>= numel(call_stack), depth=numel(call_stack)-1; end
prefix_string=[call_stack(end:-1:2+depth).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=[prefix_string blanks(50)];
prefix_string=prefix_string(1: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
fprintf(output,'%s\n',report_string);
end
end
% Consistency enforcement
function grumble(output,report_string)
if isempty(output)
error('optim_system.sys.output field must exist.');
end
if ((~isa(output,'double'))&&(~isa(output,'char')))||...
(isa(output,'char')&&(~strcmp(output,'hush')))
error('optim_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
|
github
|
tsajed/nmr-pred-master
|
quasinewton.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/quasinewton.m
| 2,352 |
utf_8
|
a57492127a57a92030c59bafac69caa9
|
% BFGS and SR1 Hessian update.
%
% <http://spindynamics.org/wiki/index.php?title=Quasinewton.m>
function B_new=quasinewton(B_old,x_new,x_old,df_new,df_old,inv_method,algo)
% Check consistency
grumble(x_new,x_old,df_new,df_old);
% if no method is supplied, use the bfgs formula
if ~exist('algo','var'), algo='bfgs'; end
% default inv_method is true if not given or not logical
if ~exist('inv_method','var'), inv_method=true; end
if ~islogical(inv_method), inv_method=true; end
% Eliminate rounding errors
B_old=real((B_old+B_old')/2);
% Compute shorthands
dx=x_new-x_old; ddf=df_new-df_old;
switch algo
case {'bfgs'}
if inv_method
% Update the inverse Hessian
B_new=B_old+(dx'*ddf+ddf'*B_old*ddf)*(dx*dx')/((dx'*ddf)^2)-...
((B_old*ddf)*dx'+dx*(ddf'*B_old))/(dx'*ddf);
elseif ~inv_method
% Update the Hessian
B_new=B_old+(ddf*ddf')/(ddf'*dx)-((B_old*dx)*(dx'*B_old))/(dx'*B_old*dx);
end
case {'sr1'}
if inv_method
% Update the inverse Hessian
B_new=B_old+((dx-B_old*ddf)*(dx-B_old*ddf)')/((dx-B_old*ddf)'*ddf);
elseif ~inv_method
% Update the Hessian
B_new=B_old+((ddf-B_old*dx)*(ddf-B_old*dx)')/((ddf-B_old*dx)'*dx);
end
otherwise
error('unsupported quasi-newton update method')
end
% Eliminate rounding errors
B_new=real((B_new+B_new')/2);
end
% Consistency enforcement
function grumble(x_new,x_old,df_new,df_old)
if (size(x_new,2)~=1)||(size(x_old,2)~=1)||(size(df_old,2)~=1)||(size(df_new,2)~=1)
error('all vector inputs must be column vectors.');
end
if (~isreal(x_new))||(~isreal(x_old))||(~isreal(df_new))||(~isreal(df_old))
error('all vector inputs must be real.');
end
end
% Of all tyrannies, a tyranny exercised for the good of its victims may be
% the most oppressive. It may be better to live under robber barons than
% under omnipotent moral busybodies. The robber baron's cruelty may some-
% times sleep, his cupidity may at some point be satiated; but those who
% torment us for our own good will torment us without end, for they do so
% with the approval of their consciences.
%
% C.S. Lewis
|
github
|
tsajed/nmr-pred-master
|
krotov.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/krotov.m
| 5,158 |
utf_8
|
abcabbd52696973dab872bdfe49c82ed
|
% Krotov type algorithms for phase-sensitive state-to-state transfer prob-
% lems.
%
% <http://spindynamics.org/wiki/index.php?title=Krotov.m>
function [diag_data,waveform,traj_fwd,traj_bwd,fidelity,grad]=...
krotov(spin_system,ctrl_system,drift,waveform,traj_fwd,traj_bwd,hess)
% Scale the waveform
waveform=ctrl_system.power_level*waveform;
% scale the reference waveform (if supplied) else use last waveform
if ~isfield(ctrl_system,'ref_waveform')
ctrl_system.ref_waveform=waveform;
end
% Silence spinach output for propagator diagnostics
outtemp=spin_system.sys.output;
spin_system.sys.output='hush';
if exist('hess','var')
hess_index=reshape(1:numel(waveform),[numel(ctrl_system.control_ops) ctrl_system.nsteps]);
end
if isempty(traj_fwd)
% initialise trajectories
traj_fwd=zeros(size(ctrl_system.rho,1),ctrl_system.nsteps+1);
traj_bwd=zeros(size(ctrl_system.rho,1),ctrl_system.nsteps+1);
% Run the initial forward propagation
traj_fwd(:,1)=ctrl_system.rho;
for n=1:ctrl_system.nsteps
L=drift;
for k=1:numel(ctrl_system.control_ops)
L=L+waveform(k,n)*ctrl_system.control_ops{k};
end
traj_fwd(:,n+1)=step(spin_system,L,traj_fwd(:,n),ctrl_system.time_step);
end
% Run the initial backward propagation
traj_bwd(:,ctrl_system.nsteps+1)=ctrl_system.target;
for n=ctrl_system.nsteps:-1:1
L=drift';
for k=1:numel(ctrl_system.control_ops)
L=L+waveform(k,n)*ctrl_system.control_ops{k};
end
traj_bwd(:,n)=step(spin_system,L,traj_bwd(:,n+1),-ctrl_system.time_step);
end
else
% Run forward Krotov sweep
traj_fwd(:,1)=ctrl_system.rho;
for n=1:ctrl_system.nsteps
% Run microiterations
difference=1;
while difference > ctrl_system.krotov_microiteration
% Start the Liouvillian and store previous control values
L=drift; prev_values=waveform(:,n);
for k=1:numel(ctrl_system.control_ops)
if exist('hess','var')
waveform(k,n)=ctrl_system.ref_waveform(k,n)+...
(1/ctrl_system.lambda)*(1/hess(hess_index(k,n),hess_index(k,n)))*imag(traj_bwd(:,n+1)'*ctrl_system.control_ops{k}*traj_fwd(:,n));
for p=(n-1):-1:1
waveform(k,n)=waveform(k,n)-...
(1/hess(hess_index(k,n),hess_index(k,n)))*hess(hess_index(k,n),hess_index(k,p))*(waveform(k,p)-ctrl_system.ref_waveform(k,p));
end
else
waveform(k,n)=ctrl_system.ref_waveform(k,n)+...
(1/ctrl_system.lambda)*imag(traj_bwd(:,n+1)'*ctrl_system.control_ops{k}*traj_fwd(:,n));
end
L=L+waveform(k,n)*ctrl_system.control_ops{k};
end
% Compute the difference
difference=norm(waveform(:,n)-prev_values);
% Refresh the forward point
traj_fwd(:,n+1)=step(spin_system,L,traj_fwd(:,n),ctrl_system.time_step);
end
end
% Run backward Krotov sweep
traj_bwd(:,ctrl_system.nsteps+1)=ctrl_system.target;
for n=ctrl_system.nsteps:-1:1
L=drift';
for k=1:numel(ctrl_system.control_ops)
if ismember(ctrl_system.method,{'zhu-rabitz'})
waveform(k,n)=waveform(k,n)+(1/ctrl_system.lambda)*imag(traj_bwd(:,n+1)'*ctrl_system.control_ops{k}*traj_fwd(:,n+1));
end
L=L+waveform(k,n)*ctrl_system.control_ops{k};
end
traj_bwd(:,n)=step(spin_system,L,traj_bwd(:,n+1),-ctrl_system.time_step);
end
end
% compute the gradient if needed
if exist('hess','var')
% Preallocate results
grad=zeros(size(waveform));
for n=1:ctrl_system.nsteps
for k=1:numel(ctrl_system.control_ops)
grad(k,n)=-2*imag(traj_bwd(:,n+1)'*ctrl_system.control_ops{k}*traj_fwd(:,n))-...
2*ctrl_system.power_level*ctrl_system.lambda*(waveform(k,n)-ctrl_system.ref_waveform(k,n));
end
end
grad=grad./ctrl_system.power_level;
end
% Normalize the total objective, total gradient, and total Hessian
fidelity=real(ctrl_system.target'*traj_fwd(:,end));
waveform=real(waveform./ctrl_system.power_level);
% re-enable spinach console output
spin_system.sys.output=outtemp;
% Compile diagnostics data
if nargout>1
diag_data.rho=ctrl_system.rho;
diag_data.target=ctrl_system.target;
diag_data.trajectory=traj_fwd;
diag_data.trajectory_bwd=traj_bwd;
diag_data.drift=drift;
end
end
% It wasn't a dark and stormy night. It should have been, but there's
% the weather for you. For every mad scientist who's had a convenient
% thunderstorm just on the night his Great Work is complete and lying
% on the slab, there have been dozens who've sat around aimlessly un-
% der the peaceful stars while Igor clocks up the overtime.
%
% Terry Pratchett
|
github
|
tsajed/nmr-pred-master
|
grape.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/grape.m
| 13,528 |
utf_8
|
8591860cae3678be8002f5235143c259
|
% Gradient Ascent Pulse Engineering (GRAPE) objective function, gradient
% and Hessian. Propagates the system through a user-supplied shaped pulse
% from a given initial state and projects the result onto the given final
% state. The real part of the projection is returned, along with its
% gradient and Hessian with respect to amplitudes of all operators in every
% time step of the shaped pulse.
%
% <http://spindynamics.org/wiki/index.php?title=Grape.m>
function [diag_data,fidelity,total_grad,total_hess]=...
grape(spin_sys,ctrl_sys,drift,waveform) %#ok<*PFBNS>
% Allow numeric input for single source calculations
if isnumeric(ctrl_sys.rho)
rho={ctrl_sys.rho};
else
rho=ctrl_sys.rho;
end
% Allow numeric input for single target calculations
if isnumeric(ctrl_sys.target)
target={ctrl_sys.target};
else
target=ctrl_sys.target;
end
% Allow numeric input for single control calculations
if isnumeric(ctrl_sys.control_ops)
controls={ctrl_sys.control_ops};
else
controls=ctrl_sys.control_ops;
end
% Preallocate results
fidelity=0; total_grad=zeros(size(waveform));
total_hess=zeros(size(waveform,1)*size(waveform,2));
current_state_array=cell(1,numel(target));
% Scale the waveform
waveform=ctrl_sys.power_level*waveform;
% Silence spinach output for propagator diagnostics
outtemp=spin_sys.sys.output;
spin_sys.sys.output='hush';
% Loop over sources and targets
for contribution=1:numel(rho)
% Grab the current source and target
init_state=rho{contribution};
target_state=target{contribution};
% Preallocate trajectory arrays
fwd_traj=zeros(size(init_state,1),ctrl_sys.nsteps+1);
bwd_traj=zeros(size(init_state,1),ctrl_sys.nsteps+1);
% Run the forward propagation
fwd_traj(:,1)=init_state;
for n=1:ctrl_sys.nsteps
L=drift;
for k=1:length(controls)
L=L+waveform(k,n)*controls{k};
end
fwd_traj(:,n+1)=step(spin_sys,L,fwd_traj(:,n),ctrl_sys.time_step);
end
% Run the backward propagation
bwd_traj(:,ctrl_sys.nsteps+1)=target_state;
for n=ctrl_sys.nsteps:-1:1
L=drift';
for k=1:length(controls)
L=L+waveform(k,n)*controls{k};
end
bwd_traj(:,n)=step(spin_sys,L,bwd_traj(:,n+1),-ctrl_sys.time_step);
end
% Compute the gradient
if nargout==3
% Loop over time steps in parallel
parfor n=1:ctrl_sys.nsteps
% Initialize the Liouvillian
L=drift;
% Add current controls
for k=1:length(controls)
L=L+waveform(k,n)*controls{k};
end
% Calculate gradient at this timestep
grad(:,n)=grape_grad(spin_sys,L,controls,waveform,fwd_traj,bwd_traj,ctrl_sys.time_step,n);
end
% Add the gradient to the total
total_grad=total_grad+real(grad);
% Compute the gradient and hessian
elseif nargout>3
% initialise cell structure for propagators and their derivatives
props=cell(1,ctrl_sys.nsteps);
props_D=cell(length(controls),ctrl_sys.nsteps);
props_DD=cell(length(controls),length(controls),ctrl_sys.nsteps);
% propagator and derivative calculations
parfor n=1:ctrl_sys.nsteps
% Initialize the Liouvillian at this timestep
L=drift;
% Add all current controls to Liouvillian for the current timestep
for k=1:length(controls)
L=L+waveform(k,n)*controls{k};
end
% Compute and store propagators and their derivatives
[props(1,n),props_D(:,n),props_DD(:,:,n)]=grape_hess(spin_sys,L,controls,ctrl_sys.time_step,fwd_traj(:,n));
end
%initialise gradient vector and Hessian matrix
grad=zeros(length(controls),ctrl_sys.nsteps);
hess=cell(ctrl_sys.nsteps,ctrl_sys.nsteps); hess(:,:)={zeros(length(controls))};
% split the hessian into two, to aid parfor over ctrl_system.nsteps/2
hess_upper=cell(ceil(ctrl_sys.nsteps/2),ctrl_sys.nsteps); hess_upper(:,:)={zeros(length(controls))};
hess_lower=cell(floor(ctrl_sys.nsteps/2),ctrl_sys.nsteps); hess_lower(:,:)={zeros(length(controls))};
parfor n_prime=1:ceil(ctrl_sys.nsteps/2)
% Preallocate space for parfor use
grad_k=zeros(length(controls),ctrl_sys.nsteps);
hess_k=zeros(length(controls));
% create a hessian block vector to aid parfor loop
hess_vec_l=cell(1,ctrl_sys.nsteps); hess_vec_l(:,:)={zeros(length(controls))};
hess_vec_u=cell(1,ctrl_sys.nsteps); hess_vec_u(:,:)={zeros(length(controls))};
for m_prime=1:ctrl_sys.nsteps+1
% calculate n and m proper from primed coordinates
m=m_prime+n_prime-1;
if m>ctrl_sys.nsteps
m=1+ctrl_sys.nsteps-mod(m,ctrl_sys.nsteps);
n=ctrl_sys.nsteps-n_prime+1;
else
n=n_prime;
end
for k=1:length(controls)
for j=1:length(controls)
% <sigma|UN...Un+1 D^2(n) Un...U1|rho>
if m==n && j==k
% Calculate gradient at this timestep
grad_k(k,n)=bwd_traj(:,n+1)'*(props_D{k,n}*fwd_traj(:,n));
% calculate KxK hessian diagonal
hess_k(k,j)=bwd_traj(:,n+1)'*props_DD{k,j,n}*fwd_traj(:,n);
elseif m==n
% calculate KxK hessian off-diagonal
hess_k(k,j)=bwd_traj(:,n+1)'*props_DD{k,j,n};
elseif n<m, N=[n m]; K=[k j]
% Calculate and store initial derivative(1)*forward_traj
forward_store=props_D{K(1),N(1)}*fwd_traj(:,N(1));
% loop over timesteps between derivatives
for n_ind=N(1)+1:N(2)-1
% update forward_traj between derivatives
forward_store=props{1,n_ind}*forward_store;
end
% Calculate and derivative(2)*forward_traj
forward_store=props_D{K(2),N(2)}*forward_store;
% Calculate Hessian element
hess_k(k,j)=bwd_traj(:,N(2)+1)'*forward_store;
end
end
end
% Allocate the Hessian elements to parfor vector
if n>ceil(ctrl_sys.nsteps/2)
hess_vec_l{1,m}=hess_k;
else
hess_vec_u{1,m}=hess_k;
end
end
% allocate hessian parfor vector to hessian blocks
hess_lower(n_prime,:)=hess_vec_l;
hess_upper(n_prime,:)=hess_vec_u;
% Allocate the gradient over controls at this timestep
grad=grad+grad_k;
end
% construct hessian proper from upper and lower blocks
hess(1:ceil(ctrl_sys.nsteps/2),:)=hess_upper;
hess(1+ceil(ctrl_sys.nsteps/2):end,:)=hess_lower(end:-1:1,:);
% Add the hessian to the total
total_hess=total_hess+real(cell2mat(hess));
% Add the gradient to the total
total_grad=total_grad+real(grad);
end
% Compute the cost function and add to the total
fidelity=fidelity+real(target_state'*fwd_traj(:,end));
% store the current state
current_state_array(contribution)={fwd_traj(:,end)};
end
% Normalize the total objective, total gradient, and total Hessian
fidelity=fidelity/numel(rho);
total_grad=ctrl_sys.power_level*total_grad/numel(rho);
total_hess=(ctrl_sys.power_level^2)*total_hess/(numel(rho));
% create block-diagonal blanking matrix
offdiag_blank=kron(eye(size(waveform,2)),ones(size(waveform,1)));
diag_blank=~offdiag_blank;
% Force Hessian symmetry and fill empty Hessian entries
total_hess=(total_hess+total_hess').*diag_blank+...
(total_hess+total_hess').*offdiag_blank/2;
% re-enable spinach console output
spin_sys.sys.output=outtemp;
% Compile diagnostics data
diag_data.current_state=current_state_array;
diag_data.rho=rho;
diag_data.target=target;
diag_data.total_objective=fidelity;
diag_data.spin_system=spin_sys;
diag_data.ctrl_system.power_level=ctrl_sys.power_level;
diag_data.trajectory=fwd_traj;
diag_data.total_grad=total_grad;
diag_data.total_hess=total_hess;
diag_data.dt=ctrl_sys.time_step;
diag_data.controls=controls;
diag_data.waveform=waveform;
diag_data.ctrl_system.nsteps=ctrl_sys.nsteps;
diag_data.drift=drift;
end
function [props,props_d,props_dd]=grape_hess(spin_system,L,ctrls,dt,fwd_traj)
% Preallocate propagator derivatives
props_d=cell(1,length(ctrls));
props_dd=cell(length(ctrls),length(ctrls));
switch spin_system.tols.dP_method
case 'auxmat'
% loop over K*K controls
for k=1:length(ctrls)
for j=1:length(ctrls)
if k==j
%find explicit propagator to reuse for off-diagonal
prop_dirdiff=dirdiff(spin_system,L,{ctrls{k},ctrls{k}},dt,3);
% store 1st and 2nd order propagator derivatives
props_d(k)=prop_dirdiff(2); props_dd(k,k)=prop_dirdiff(3);
else
% Create the auxiliary matrix
aux_matrix=[L, ctrls{k}, 0*L; 0*L, L, ctrls{j}; 0*L, 0*L, L];
% Propagate the auxiliary vector
aux_vector=step(spin_system,aux_matrix,[zeros(size(fwd_traj)); zeros(size(fwd_traj)); fwd_traj],dt);
% Store propagated second order derivative vector
props_dd{k,j}=2*aux_vector(1:(end/3));
end
end
end
% Store propagator of Liouvillian, L.
props=prop_dirdiff(1);
otherwise
error('grape: unknown second order differentiation method.');
end
end
function control_derivatives=grape_grad(spin_system,L,ctrls,wf,fwd_traj,bwd_traj,dt,n)
% Preallocate derivatives
control_derivatives=zeros(length(ctrls),1);
% Generate control derivatives
switch spin_system.tols.dP_method
case 'auxmat'
% Loop over controls
for k=1:length(ctrls)
% Create the auxiliary matrix
aux_matrix=[L, ctrls{k}; 0*L, L];
% Propagate the auxiliary vector
aux_vector=step(spin_system,aux_matrix,[zeros(size(fwd_traj(:,n))); fwd_traj(:,n)],dt);
% Compute the derivative
control_derivatives(k)=bwd_traj(:,n+1)'*aux_vector(1:(end/2));
end
case 'fd_O(h^2)'
% Get the finite difference step
delta=max(abs(wf(:)))*sqrt(eps);
% Loop over controls
for k=1:length(ctrls)
% Compute control derivatives with central finite differences
control_derivatives(k)=bwd_traj(:,n+1)'*(step(spin_system,L+delta*ctrls{k},fwd_traj(:,n),dt)-...
step(spin_system,L-delta*ctrls{k},fwd_traj(:,n),dt))/(2*delta);
end
case 'fd_O(h^4)'
% Get the finite difference step
delta=max(abs(wf(:)))*sqrt(eps);
% Loop over controls
for k=1:length(ctrls)
% Compute control derivatives with central finite differences
control_derivatives(k)=bwd_traj(:,n+1)'*(-1*step(spin_system,L+2*delta*ctrls{k},fwd_traj(:,n),dt)...
+8*step(spin_system,L+delta*ctrls{k},fwd_traj(:,n),dt)...
-8*step(spin_system,L-delta*ctrls{k},fwd_traj(:,n),dt)...
+1*step(spin_system,L-2*delta*ctrls{k},fwd_traj(:,n),dt))/(12*delta);
end
otherwise
% Complain and bomb out
error('unknown differentiation method.');
end
end
% In any culture, subculture, or family in which belief is valued above
% thought, self-surrender is valued above self-expression, and conformity
% is valued above integrity, those who preserve their self-esteem are
% likely to be heroic exceptions.
%
% Nathaniel Branden
|
github
|
tsajed/nmr-pred-master
|
objeval.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/objeval.m
| 3,088 |
utf_8
|
e60d6bdeefcb93c5557521470336efe2
|
% function to call and collect the correct amount of outputs from an
% objective function
%
% <http://spindynamics.org/wiki/index.php?title=Objeval.m>
function [data,fx,grad,hess]=objeval(x,obj_fun_handle, data)
% Call the cost function with gradient and Hessian if nessesary
fcn_list=dbstack;
if numel(fcn_list)==1, optimise_fcn={}; end
if numel(fcn_list)>1, optimise_fcn=fcn_list(2).name; end
if ismember(optimise_fcn,{'linesearch','fminnewton','sectioning','bracketing'})
timem=tic;
if ( nargout ==2 )
if ~isempty(data.cost_fun_vars)
[fx,data.cost_fun_vars]=...
feval(obj_fun_handle,reshape(x,data.x_shape),data.cost_fun_vars);
else
[fx]=feval(obj_fun_handle,reshape(x,data.x_shape));
end
data.time_fx=data.time_fx+toc(timem);
data.n_fx=data.n_fx+1;
elseif ( nargout ==3 )
if ~isempty(data.cost_fun_vars)
[fx,grad,data.cost_fun_vars]=...
feval(obj_fun_handle,reshape(x,data.x_shape),data.cost_fun_vars);
else
[fx,grad]=feval(obj_fun_handle,reshape(x,data.x_shape));
end
data.time_gfx=data.time_gfx+toc(timem);
data.n_fx=data.n_fx+1; data.n_grad=data.n_grad+1;
grad=grad(:);
elseif ( nargout ==4 )
if ~isempty(data.cost_fun_vars)
[fx,grad,hess,data.cost_fun_vars]=...
feval(obj_fun_handle,reshape(x,data.x_shape),data.cost_fun_vars);
else
[fx,grad,hess]=feval(obj_fun_handle,reshape(x,data.x_shape));
end
data.time_hfx=data.time_hfx+toc(timem);
data.n_fx=data.n_fx+1; data.n_grad=data.n_grad+1; data.n_hess=data.n_hess+1;
grad=grad(:);
end
% store then sum fx if penalties are included
if data.npen>0, data.fx_sep_pen=fx; fx=sum(fx); end
elseif ismember(optimise_fcn,{'fminsimplex'})
fx=zeros(size(x,2),data.npen+1);
if data.parallel_cost_fcn
X=cell(size(x,2),1);
for n=1:numel(X), X{n}=reshape(x(:,n),data.x_shape); end
% Call the cost function with gradient and Hessian if nessesary
timem=tic;
if isempty(data.cost_fun_vars)
[Fx]=feval(obj_fun_handle,X);
else
[Fx,data.cost_fun_vars]=feval(obj_fun_handle,X,data.cost_fun_vars);
end
for n=1:numel(X), fx(n,:)=Fx{n}; end
data.time_fx=data.time_fx+toc(timem);
data.n_fx=data.n_fx+numel(X);
else
for n=1:size(x,2)
% Call the cost function with gradient and Hessian if nessesary
timem=tic;
if isempty(data.cost_fun_vars)
[fx(n,:)]=feval(obj_fun_handle,reshape(x(:,n),data.x_shape));
else
[fx(n,:),data.cost_fun_vars]=feval(obj_fun_handle,reshape(x(:,n),data.x_shape),data.cost_fun_vars);
end
data.time_fx=data.time_fx+toc(timem);
data.n_fx=data.n_fx+1;
end
end
% store then sum fx if penalties are included
if data.npen>0, data.fx_sep_pen=fx; fx=sum(fx,2); end
end
end
|
github
|
tsajed/nmr-pred-master
|
hessprep.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/hessprep.m
| 1,734 |
utf_8
|
aaddb7bf831c91de17c966b0b5ebf3af
|
% function to prepare a Hessian matrix to be definite and well-conditioned
%
% <http://spindynamics.org/wiki/index.php?title=Hessprep.m>
function [grad,hess,data]=hessprep(grad,hess,optim,data)
% force real and symmetric hessian
if ~isreal(hess), hess=real(hess); end
if ~issymmetric(hess), hess=(hess+hess')./2; end
% test for definite Hessian
if (~isempty(optim.reg.method)) || (~isempty(optim.reg.cond_method))
if ismember(optim.algo.extremum,{'minimum'}) % positive definite test
% check if positive definite
[~,def_test]=chol(hess);
elseif ismember(optim.algo.extremum,{'maximum'}) % negative definite test
% find largest and smallest eigenvalues
[~,eig_bnd,conv_test]=eigs(hess,2,'BE',struct('isreal',true,'issymmetric',true));
if ~(logical(conv_test)), def_test=1; % eigenvalues didn't converge
elseif all(diag(eig_bnd))>0, def_test=0; % positive definite Hessian
else def_test=1; % all else, regularise the Hessian
end
end
% if definite hessian, check the condition number
if ~(logical(def_test)), hess_cond=cond(hess); end
end
if (~isempty(optim.reg.method) && (logical(def_test)) ) ||...
(~isempty(optim.reg.cond_method) && optim.reg.max_cond<hess_cond)
% regularise or/and condition the hessian
[hess,grad,data]=hessreg(hess,grad,optim.reg,data);
elseif optim.reg.track_eig
% explicit tracking of Hessian eigenvalues
[data.hess_eigvecs,data.hess_eigs]=eig(hess);
data.hess_mineig=min(diag(data.hess_eigs));
data.hess_cond=max(diag(data.hess_eigs))/data.hess_mineig;
data.n_cond=0;
end
end
|
github
|
tsajed/nmr-pred-master
|
fminkrotov.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/fminkrotov.m
| 12,813 |
utf_8
|
e8383a5b053d6fd38b292c83987db02c
|
% Krotov type algorithms for phase-sensitive state-to-state transfer prob-
% lems.
%
% <http://spindynamics.org/wiki/index.php?title=Fminkrotov.m>
function [x,fx,grad,data]=fminkrotov(cost_function,x_0,optim,hess_init,cost_fun_vars)
% Initialize the structure of the initial guess
x = x_0(:); data.x_shape=size(x_0); data.n_vars = numel(x_0);
% Always Bootstrap and set optimisation tolerances
% - assume user isn't optimisation expert
optim.cost_function=cost_function;
optim=optim_tols(optim,data.n_vars);
% add cost function variables to the data structure (empty if not provided)
if ~exist('cost_fun_vars','var'), cost_fun_vars=[]; end
data.cost_fun_vars=cost_fun_vars;
% penalty terms to consider (default=0), affects output display only.
data.npen=optim.algo.npen;
% initialise counters and timers
data.iter=0; data.n_fx=0; data.n_grad=0; data.n_cond=0; data.firstorderopt=[];
data.timeTotal=tic; data.time_fx=0; data.time_gfx=0; data.iter_timer=tic;
% print optimisation header
iterative_reporting([],'head',[],optim,data);
% initialise exitflag, functional and its derivatives
exitflag=[];
% set initial Hessian approximation
if ~exist('hess_init','var'), optim.hess=eye(data.n_vars);
else optim.hess=hess_init; end
if ismember(optim.algo.method,{'krotov-bfgs','krotov-sr1'})
[data,x,vec_fwd,vec_bwd,fx,grad]=gradient_function(cost_function,x,[],[],data,optim.hess);
optim.hess=real(optim.hess+optim.hess')./2;
[grad,hess,exitflag,data]=hessian_prep(grad,optim.hess,optim.reg,data);
optim.hess=real(hess+hess')./2;
else
[data,x,vec_fwd,vec_bwd,fx]=gradient_function(cost_function,x,[],[],data,optim.hess);
end
% Show the current iteration information
data.itertime=toc(data.iter_timer); data.iter_timer=tic;
% report diagnostics to user
iterative_reporting(fx,'iter',exitflag,optim,data);
% Enter the main interation loop
while (true)
% Keep the variables for next iteration
store.x=x(:); store.fx=fx;
% Update number of iterations
if (isempty(exitflag)), data.iter=data.iter+1; end
if ismember(optim.algo.method,{'krotov-bfgs','krotov-sr1'})
store.grad=grad(:);
[data,x,vec_fwd,vec_bwd,fx,grad]=gradient_function(cost_function,x,vec_fwd,vec_bwd,data,optim.hess);
else
[data,x,vec_fwd,vec_bwd,fx]=gradient_function(cost_function,x,vec_fwd,vec_bwd,data,optim.hess);
end
% check optimality conditions
if (data.iter > optim.tols.max_iter), exitflag=0; end
if (optim.algo.max_min*fx < optim.algo.max_min*store.fx), exitflag=1; end
if (optim.algo.max_min*optim.tols.fx < optim.algo.max_min*fx), exitflag=4; end
if (optim.tols.x > max(abs(store.x(:)-x(:)))), exitflag=2; end
% Check if exitflag is set from 3 previous checks
if(~isempty(exitflag)), x=store.x; fx=store.fx; data.iter=data.iter-1; break, end;
% Show the current iteration information
data.itertime=toc(data.iter_timer); data.iter_timer=tic;
% report diagnostics to user
iterative_reporting(fx,'iter',exitflag,optim,data);
% Call output function if specified
if(output_function(optim.sys.outputfun,'iter')), exitflag=-1; end
% Compute the gradient for bfgs or sr1
if ismember(optim.algo.method,{'krotov-bfgs','ktotov-sr1'})
[hess,store]=hessian_update(x(:),grad,optim.hess,store,optim.algo);
optim.hess=real(hess+hess')./2;
[grad,hess,data]=hessprep(grad,optim.hess,optim,data);
optim.hess=real(hess+hess')./2;
end
end
% Call output function if specified
if(output_function(optim.sys.outputfun,'done')), exitflag=-1; end
% Set outputs
x=reshape(x,data.x_shape);
if exist('grad','var')
grad=reshape(grad,data.x_shape);
else
grad=[];
end
data=iterative_reporting(fx,'term',exitflag,optim,data);
function exit=output_function(outputfun,where)
exit=false; % initialise
if(~isempty(outputfun)) % data structure to output function
% <add any variable to export here>
% if exit is returned as true, optimisation will finish
exit=feval(outputfun,reshape(x,data.x_shape),data,where);
end
end
end
function [data,x,traj_fwd,traj_bwd,fx,grad]=gradient_function(obj_fun_handle,x,vec_fwd,vec_bwd,data,hess)
% Call the cost function with gradient and Hessian if nessesary
timem=tic;
if ( nargout ==5 )
if ~isempty(data.cost_fun_vars)
[x,traj_fwd,traj_bwd,fx,data.cost_fun_vars]=...
feval(obj_fun_handle,reshape(x,data.x_shape),vec_fwd,vec_bwd,data.cost_fun_vars);
else
[x,traj_fwd,traj_bwd,fx]=feval(obj_fun_handle,reshape(x,data.x_shape),vec_fwd,vec_bwd);
end
data.time_fx=data.time_fx+toc(timem);
data.n_fx=data.n_fx+1;
elseif ( nargout ==6 )
if ~isempty(data.cost_fun_vars)
[x,traj_fwd,traj_bwd,fx,grad,data.cost_fun_vars]=...
feval(obj_fun_handle,reshape(x,data.x_shape),vec_fwd,vec_bwd,hess,data.cost_fun_vars);
else
[x,traj_fwd,traj_bwd,fx,grad]=feval(obj_fun_handle,reshape(x,data.x_shape),vec_fwd,vec_bwd,hess);
end
data.time_gfx=data.time_gfx+toc(timem);
data.n_fx=data.n_fx+1; data.n_grad=data.n_grad+1;
grad=grad(:);
end
end
function [grad,hess,exitflag,data]=hessian_prep(grad,hess,reg,data)
% tests for positive definite and initialise exitflag
[~,pos_def_test]=chol(hess); exitflag=[];
if ~isreal(hess), exitflag =-5; % test real hessian
elseif ~issymmetric(hess), exitflag=-4; % test for symmetric hessian
elseif (~isempty(reg.method) && (logical(pos_def_test)) ) ||...
(~isempty(reg.cond_method) && reg.max_cond<cond(hess))
% regularise or/and condition the hessian
[hess,grad,data]=hessreg(hess,grad,reg,data);
elseif reg.track_eig
% explicit tracking of Hessian eigenvalues (for debugging)
[data.hess_eigvecs,data.hess_eigs]=eig(hess);
data.hess_mineig=min(diag(data.hess_eigs));
data.hess_cond=max(diag(data.hess_eigs))/data.hess_mineig;
data.n_cond=0;
end
end
function [hess,store] = hessian_update(x,grad,hess,store,algo)
% hessian update for quasi-Newton methods and hybrid-quasi-Newton methods
hess=quasinewton(hess, x, store.x, -algo.max_min*grad, -algo.max_min*store.grad, false, algo.method(8:end));
end
function data=iterative_reporting(fx,report_case,exitflag,optim,data)
switch report_case
case {'head'}
% Report start of optimisation to user
switch(optim.algo.method)
case 'krotov', optim_report(optim.sys.output,'start krotov optimisation',1);
case 'krotov-sr1', optim_report(optim.sys.output,'start krotov optimisation using quasi-newton, Symmetric Rank 1 Hessian update',1);
case 'krotov-bfgs', optim_report(optim.sys.output,'start krotov optimisation using quasi-newton, BFGS method',1);
end
optim_report(optim.sys.output,['Cost Function = @', func2str(optim.sys.costfun.handle)],1);
optim_report(optim.sys.output,'==============================================================================================',1);
obj_fun_str=[blanks(17) optim.sys.obj_fun_str]; obj_fun_str=obj_fun_str(end-17:end);
if ismember(optim.reg.method,{'RFO','TRM'}) || optim.reg.track_eig
optim_report(optim.sys.output,['Iter Time #f(x) #g(x) min(eig) #cond cond(H) ' obj_fun_str ' 1st-optim'],1);
elseif ismember(optim.reg.method,{'CHOL','reset'})
optim_report(optim.sys.output,['Iter Time #f(x) #g(x) #reg ' obj_fun_str ' 1st-optim'],1);
else optim_report(optim.sys.output,['Iter Time #f(x) #g(x) ' obj_fun_str ' 1st-optim'],1);
end
optim_report(optim.sys.output,'----------------------------------------------------------------------------------------------',1);
case {'iter'}
t=data.itertime;
if t<1e-3, Tstr=sprintf('%5.0e',t); elseif t<10, Tstr=sprintf('%5.3f',t); elseif t<1e2, Tstr=sprintf('%5.2f', t);
elseif t<1e3, Tstr=sprintf('%5.1f',t); elseif t<=99999, Tstr=sprintf('%5.0f',t); else Tstr=sprintf('%5.0e',t);
end
% Report optimisation iterasation to user
if (ismember(optim.reg.method,{'RFO','TRM'}) && (isfield(data,'n_cond') && data.n_cond>0)) || optim.reg.track_eig
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %8.3g %4.0f %9.3g %17.9g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.hess_mineig,data.n_cond,data.hess_cond,optim.sys.obj_fun_disp(fx),data.firstorderopt),1);
elseif ismember(optim.reg.method,{'RFO','TRM'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %8.1s %4.0f %9.1s %17.9g %9.3g'],...
data.iter,data.n_fx,data.n_grad,'-',0,'-',optim.sys.obj_fun_disp(fx),data.firstorderopt),1);
elseif ismember(optim.reg.method,{'CHOL','reset'})
optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %5.0f %17.9g %9.3g'],...
data.iter,data.n_fx,data.n_grad,data.n_cond,optim.sys.obj_fun_disp(fx),data.firstorderopt),1);
else optim_report(optim.sys.output,sprintf(['%4.0f ',Tstr,' %5.0f %5.0f %17.9g %9.3g'],...
data.iter,data.n_fx,data.n_grad,optim.sys.obj_fun_disp(fx),data.firstorderopt),1);
end
case {'term'}
optim_report(optim.sys.output,'==============================================================================================',1);
% Make exist output structure
switch(optim.algo.method)
case 'krotov', data.algorithm='Krotov method';
case 'krotov-sr1', data.algorithm='Krotov method, Symmetric Rank 1 Hessian update (SR1)';
case 'krotov-bfgs', data.algorithm='Krotov method, Broyden-Fletcher-Goldfarb-Shanno Hessian update (BFGS)';
end
% report optimisation results to user
data.exit_message=exitmessage(exitflag);
data.minimum = optim.sys.obj_fun_disp(fx);
data.timeTotal=toc(data.timeTotal);
data.timeIntern=data.timeTotal-data.time_fx-data.time_gfx;
optim_report(optim.sys.output,'Optimisation Results',1)
optim_report(optim.sys.output,[' Algorithm Used : ' data.algorithm],1);
optim_report(optim.sys.output,[' Exit message : ' data.exit_message],1);
optim_report(optim.sys.output,[' Iterations : ' int2str(data.iter)],1);
optim_report(optim.sys.output,[' Function Count : ' int2str(data.n_fx)],1);
optim_report(optim.sys.output,[' Gradient Count : ' int2str(data.n_grad)],1);
optim_report(optim.sys.output,[' Minimum found : ' num2str(data.minimum)],1);
optim_report(optim.sys.output,[' Optimiser Time : ' num2str(data.timeIntern) ' seconds'],1);
optim_report(optim.sys.output,[' Function calc Time : ' num2str(data.time_fx) ' seconds'],1);
optim_report(optim.sys.output,[' Gradient calc Time : ' num2str(data.time_gfx) ' seconds'],1);
optim_report(optim.sys.output,[' Total Time : ' num2str(data.timeTotal) ' seconds'],1);
optim_report(optim.sys.output,'==============================================================================================',1);
if ~isinteger(optim.sys.output) && optim.sys.output>=3, optim_report(optim.sys.output,[],[],true); end
pause(1.5);
end
end
function message=exitmessage(exitflag)
switch(exitflag) % list of exiflag messages
case 1, message='Objective function, f(x), is not strictly decreasing';
case 2, message='Change in x was smaller than the specified tolerance, tol_x.';
case 3, message='Boundary fminimum reached.';
case 4, message='Specified terminal functional value reached';
case 0, message='Number of iterations exceeded the specified maximum.';
case -1, message='Algorithm was terminated by the output function.';
case -2, message='Line search cannot find an acceptable point along the current search';
case -3, message='Hessian matrix is not positive definite';
otherwise, message='Undefined exit code';
end
end
% There is a sacred horror about everything grand. It is easy to admire
% mediocrity and hills; but whatever is too lofty, a genius as well as a
% mountain, an assembly as well as a masterpiece, seen too near, is
% appalling... People have a strange feeling of aversion to anything grand.
% They see abysses, they do not see sublimity; they see the monster, they
% do not see the prodigy.
%
% Victor Hugo - Ninety-three
|
github
|
tsajed/nmr-pred-master
|
penalty.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/penalty.m
| 4,563 |
utf_8
|
5a621417cb8dffed9ed565c9888114f1
|
% Penalty terms for the Optimal Control module. Returns the penalty
% function and its gradient for the waveform, which should be sup-
% plied as row vector or a horizontal stack thereof.
%
% <http://spindynamics.org/wiki/index.php?title=Penalty.m>
function [pen_term,pen_grad,pen_hess]=penalty(wf,type,fb,cb)
% Check consistency
if ismember(type,{'SNS','SNC'})
grumble(wf,type,fb,cb);
else
grumble(wf,type);
end
% Preallocate the results
if nargout>0, pen_term=0; end
if nargout>1, pen_grad=zeros(size(wf)); end
if nargout>2, pen_hess=zeros(numel(wf)); end
% Decide the penalty type
switch type
case 'NS'
% Compute the penalty
if nargout>0
pen_term=sum(sum(wf.^2));
pen_term=pen_term/size(wf,2);
end
% Compute the gradient
if nargout>1
pen_grad=2*wf;
pen_grad=pen_grad/size(wf,2);
end
% Compute the Hessian
if nargout>2
pen_hess=2*speye(numel(wf));
pen_hess=pen_hess/size(wf,2);
end
case 'DNS'
% Differentiation matrix
D=fdmat(size(wf,2),5,1);
% Compute the penalty
if nargout>0
dwf=wf*D';
pen_term=sum(sum(dwf.^2));
pen_term=pen_term/size(dwf,2);
end
% Compute the gradient
if nargout>1
pen_grad=2*dwf*D;
pen_grad=pen_grad/size(dwf,2);
end
% Compute the Hessian
if nargout>2
pen_hess=2*kron(D'*D,speye(size(wf,1)));
pen_hess=pen_hess/size(wf,2);
end
case 'SNS'
% Build ceiling hole inventory
ch_map=(wf>cb); ch_actual=wf.*ch_map; ch_wanted=cb.*ch_map;
% Build floor hole inventory
fh_map=(wf<fb); fh_actual=wf.*fh_map; fh_wanted=fb.*fh_map;
% Compute the penalty
pen_term=pen_term+sum(sum((ch_actual-ch_wanted).^2))+...
sum(sum((fh_actual-fh_wanted).^2));
pen_term=pen_term/size(wf,2);
% Compute the gradient
if nargout>1
pen_grad=2*(ch_actual-ch_wanted)+2*(fh_actual-fh_wanted);
pen_grad=pen_grad/size(wf,2);
end
% Compute the Hessian
if nargout>2
pen_hess=2*ch_map/size(wf,2)+2*fh_map/size(wf,2);
pen_hess=diag(pen_hess(:));
pen_hess=pen_hess/size(wf,2);
end
case 'SNC'
% Build ceiling hole inventory
ch_map=(wf>cb); ch_actual=wf.*ch_map; ch_wanted=cb.*ch_map;
% Build floor hole inventory
fh_map=(wf<fb); fh_actual=wf.*fh_map; fh_wanted=fb.*fh_map;
% Compute the penalty
pen_term=pen_term+(1/6)*sum(sum((abs(ch_actual-ch_wanted)).^3))+...
(1/6)*sum(sum((abs(fh_actual-fh_wanted)).^3));
pen_term=pen_term/size(wf,2);
% Compute the gradient
if nargout>1
pen_grad=(1/2)*(ch_actual-ch_wanted).^2+(1/2)*(fh_actual-fh_wanted).^2;
pen_grad=pen_grad/size(wf,2);
end
% Compute the Hessian
if nargout>2
pen_hess=(ch_actual-ch_wanted)+(fh_actual-fh_wanted);
pen_hess=diag(pen_hess(:));
pen_hess=pen_hess/size(wf,2);
end
otherwise
error('unknown penalty function type.');
end
end
% Consistency enforcement
function grumble(wf,type,fb,cb)
if ~isnumeric(wf)||(~isreal(wf))
error('waveform must be a real numeric array.');
end
if ~ischar(type)
error('type must be a character string.');
end
if ismember(type,{'SNS','SNC'})
if ~isnumeric(fb)||(~isreal(fb))
error('floor_bound must be a real numeric array.');
end
if ~isnumeric(cb)||(~isreal(cb))
error('ceiling_bound must be a real numeric array.');
end
if any(size(wf)~=size(fb))
error('floor bound array must have the same dimension as the waveform array.');
end
if any(size(wf)~=size(cb))
error('ceiling bound array must have the same dimension as the waveform array.');
end
if any(any(cb<=fb))
error('the ceiling bound should be above the floor bound.');
end
end
end
% I would never die for my beliefs because I might be wrong.
%
% Bertrand Russell
|
github
|
tsajed/nmr-pred-master
|
hessreg.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/hessreg.m
| 8,444 |
utf_8
|
63121c6ece25f6262e476760d35d36ea
|
% Hessian Regularisation for quasi-Newton and Newton-Raphson optimisation
% regularisations. To be used when ill-conditioned or near-singular Hessian
% matrices are expected. Can also be used to condition any square,
% symmetric matrix.
%
% <http://spindynamics.org/wiki/index.php?title=Hessreg.m>
function [H,g,data]=hessreg(H,g,reg_param,data)
% Bootstrap if necessary
if ~exist('reg_param','var'), reg_param=bootstrap(); end
% Check consistency
grumble(H);
%initialise regularisation counter
ind=0;
switch reg_param.method
case {''}
% nothing to do
case {'reset'}
% simple reset hessian to the identity i.e. gradient descent iterate
ind=ind+1; % increase counter
%reset the hessian to identity
H=eye(size(H));
case {'CHOL'}
% If specified, perform Cholesky regularisation
if min(diag(H))>=0; sigma=norm(H,'fro');
else sigma=norm(H,'fro')-min(diag(H)); end
ind=ind+1; % increase counter
[~,pos_def_test]=chol(H);
while ind<reg_param.n_reg && logical(pos_def_test)
[L,pos_def_test]=chol(H+sigma*eye(size(H))); iL=inv(L.');
%output the inverse hessian
H=iL.'*iL;
% increase sigma and counter
sigma=max(2*sigma,norm(H,'fro')); ind = ind+1;
end
case {'TRM'}
% Trust Region Method of regularisation
switch reg_param.cond_method
case {''}
ind=ind+1; % increase counter
% eigendecomposition
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,H);
% use the eigendecomposition to reform hessian
H=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma);
case {'iterative','scaled'}
ind=ind+1; % increase counter
reg_param.delta=1; % initialise alpha
% eigendecomposition
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,H);
if ismember(reg_param.cond_method,{'scaled'})
% scale alpha to smallest eigenvalue
reg_param.delta=sqrt(abs(min(diag(hess_eigs))));
% initial scaling of the Hessian
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,H);
end
% use the eigendecomposition to reform hessian
H=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma);
hess_comp=H;
% iteratively condition the hessian until < limit
while cond(H,2)>reg_param.max_cond...
&& ind<reg_param.n_reg
% define new alpha
reg_param.delta=reg_param.delta*reg_param.phi;
% eigendecomposition
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,hess_comp);
% use the eigendecomposition to reform hessian
H=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma);
ind=ind+1; % increase counter
end
end
case {'RFO'}
% Rational Function Optimisation
switch reg_param.cond_method
case {''}
ind=ind+1; % increase counter
% eigendecomposition
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,H,g);
% use the eigendecomposition to reform hessian
[H,g]=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma,g);
case {'iterative','scaled'}
ind=ind+1; % increase counter
reg_param.alpha=1; % initialise alpha
% eigendecomposition
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,H,g);
if ismember(reg_param.cond_method,{'scaled'})
% scale alpha to smallest eigenvalue
reg_param.alpha=sqrt(1/abs(min(diag(hess_eigs))));
% initial scaling of the Hessian
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,H,g);
end
% use the eigendecomposition to reform hessian
[H,g]=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma,g);
hess_comp=H; grad_comp=g;
% iteratively condition the hessian until < limit
while cond(H,2)>reg_param.max_cond...
&& ind<reg_param.n_reg
% define new alpha
reg_param.alpha=reg_param.alpha*reg_param.phi;
% eigendecomposition
[hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,hess_comp,grad_comp);
% use the eigendecomposition to reform hessian
[H,g]=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma,grad_comp);
ind=ind+1; % increase counter
end
end
otherwise
error('unknown regularisation method')
end
% compile diagnostics data
if nargout>2 && exist('data','var')
if ismember(reg_param.method,{'TRM','RFO'})
[hess_eigvecs,hess_eigs]=eig(H);
data.hess_eigs=diag(hess_eigs);
data.hess_eigvecs=hess_eigvecs;
data.hess_mineig=min(abs(data.hess_eigs));
data.hess_cond=max(abs(data.hess_eigs))/data.hess_mineig;
end
data.n_cond=ind;
else data=[];
end
end
function [hess_eigs,hess_eigvecs,sigma]=find_eigs(reg_param,hess,grad)
switch reg_param.method
case {'RFO'}
% define the auxiliary Hessian
hess_aug=[(reg_param.alpha^2).*hess reg_param.alpha.*grad;
reg_param.alpha.*grad' 0];
% eigendecomposition of auxiliary Hessian
[hess_eigvecs,hess_eigs]=eig(hess_aug);
% find lambda smaller than lowest Hessian negative eigenvalue
sigma=reg_param.def*min([0 min(reg_param.def*diag(hess_eigs))]);
case {'TRM'}
% eigendecompositon of Hessian
[hess_eigvecs,hess_eigs]=eig(hess);
% find lambda smaller than lowest Hessian negative eigenvalue
sigma=reg_param.def*max([0 reg_param.delta-min(reg_param.def*diag(hess_eigs))]);
end
end
function [hess,grad]=reconstruct_hess(reg_param,hess_eigs,hess_eigvecs,sigma,grad)
% set the identity
I=eye(size(hess_eigs));
% switch between regularisation optim_param.regularisation
switch reg_param.method
case {'RFO'}
% scale Hessian to have all positive eigenvalues
hess=hess_eigvecs*((hess_eigs-sigma.*I)/hess_eigvecs);
% rescale the Hessian and gradient
grad=hess(1:end-1,end)./(reg_param.alpha);
% set Hessian to correct size
hess=hess(1:end-1,1:end-1)./(reg_param.alpha^2);
case {'TRM'}
% scale Hessian to have all positive eigenvalues
hess=hess_eigvecs*((hess_eigs+sigma.*I)/hess_eigvecs);
end
end
% Set default options if not already set
function reg_param=bootstrap()
reg_param.method='RFO';
reg_param.cond_method='iterative';
reg_param.alpha=1;
reg_param.delta=1;
reg_param.max_cond=1e4;
reg_param.phi=0.9;
reg_param.n_reg=2500;
end
% Consistency enforcement
function grumble(H)
if (~isnumeric(H))||(size(H,1)~=size(H,2))||...
(~issymmetric(H))||(~isreal(H))
error('The Hessian must be a symmmetric, real, square, matrix.');
end
end
% A youth who had begun to read geometry with Euclid, when he had learnt
% the first proposition, inquired, "What do I get by learning these
% things?". So Euclid called a slave and said "Give him three pence, since
% he must make a gain out of what he learns."
%
% Joannes Stobaeus
|
github
|
tsajed/nmr-pred-master
|
lbfgs.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/lbfgs.m
| 871 |
utf_8
|
20b9db7e31b7e671f27fcb1aff1ebc44
|
% L-BFGS optimization step update.
%
% <http://spindynamics.org/wiki/index.php?title=Lbfgs.m>
function direction=lbfgs(x_hist,df_hist,grad,N)
% Initialize variables
a=zeros(1,N);
p=zeros(1,N);
for i=1:N
p(i)= 1 / (df_hist(:,i)'*x_hist(:,i));
a(i) = p(i)* x_hist(:,i)' * grad;
grad = grad - a(i) * df_hist(:,i);
end
% Scaling of initial Hessian (identity matrix)
p_k = df_hist(:,1)'*x_hist(:,1) / sum(df_hist(:,1).^2);
% Make r = - Hessian * gradient
direction = p_k * grad;
for i=N:-1:1,
b = p(i) * df_hist(:,i)' * direction;
direction = direction + x_hist(:,i)*(a(i)-b);
end
direction=-direction;
end
% If someone steals your password, you can change it. But if someone
% steals your thumbprint, you can't get a new thumb. The failure mod-
% es are very different.
%
% Bruce Schneier, on biometric security
|
github
|
tsajed/nmr-pred-master
|
optim_tols.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/optim_tols.m
| 43,168 |
utf_8
|
574a0a12d2b17e159d4daad011e4bbf8
|
% Tolerances and options for optimisation and control. Sets the various
% optimisation methods, corresponding tolerances, and options used
% throughout numerical optimisation.
%
% Modifications to this function are discouraged -- the accuracy settings
% should be modified by setting the sub-fields of the optim structure.
%
% <http://spindynamics.org/wiki/index.php?title=Optim_tols.m>
function optim_param=optim_tols(optim,n_vars)
% list of OPTIMISATION algorithms
% >>>>-add to list as appropriate-<<<<
optim_algos={'lbfgs','bfgs','newton','sr1','grad_ascent','grad_descent','krotov','krotov-bfgs','krotov-sr1'};
% list of LINE-SEARCH methods and rules
% >>>>-add to lists as appropriate-<<<<
search_algos={'bracket-section','backtracking','newton-step'};
search_rules={'Wolfe','Wolfe-strong','Wolfe-weak','Goldstein','Armijo'};
% list of REGULARISATION and conditioning proceedures
% >>>>-add to lists as appropriate-<<<<
reg_method={'RFO','TRM','CHOL'};
reg_cond={'iterative','scaled','none'};
% max number of variables before switch to lbfgs (excluding grad_descent and grad_ascent)
lbfgs_switch=5000;
% ========================== STRUCT = OPTIM.SYS ==========================
% store the cost function handle; throw error is not supplied - should
% always be supplied if used with fminnewton: inherited from fminnewton
% inputs
if isempty(optim)
error('Empty optimisation options');
elseif ~isfield(optim,'cost_function') || ~isa(optim.cost_function,'function_handle'),
error('Optimisation functional must be supplied as a function handle e.g. @cost_function')
else
optim_param.sys.costfun=functions(optim.cost_function);
optim_param.sys.costfun.handle=optim.cost_function;
optim=rmfield(optim,'cost_function'); % parsed -> remove
% remove workspace field - can be commented if appropriate
if isfield(optim_param.sys.costfun,'workspace')
optim_param.sys.costfun = rmfield(optim_param.sys.costfun,'workspace');
end
end
% Decide output destination
if isfield(optim,'output') && strcmp(optim.output,'hush')
% Hush the output
optim_param.sys.output='hush';
optim=rmfield(optim,'output'); % parsed -> remove
elseif isfield(optim,'output')&&(~strcmp(optim.output,'console'));
% Close all open files
% Print to a user-specified file
optim_param.sys.output=fopen(optim.output,'a');
optim=rmfield(optim,'output'); % parsed -> remove
elseif isfield(optim,'output')&&(strcmp(optim.output,'console'));
optim_param.sys.output=1;
optim=rmfield(optim,'output'); % parsed -> remove
else
% Print to the console (default -> force)
optim_param.sys.output=1;
end
% Optimisation output function, evaluated at each iteration
if isfield(optim,'outputfun') && isa(optim.outputfun,'function_handle')
optim_param.sys.outputfun=optim.outputfun;
optim=rmfield(optim,'outputfun'); % parsed -> remove
else
% (default -> force)
optim_param.sys.outputfun='';
end
% get function call info for cost_function
file_parse_info=getcallinfo(optim_param.sys.costfun.file); %optim_param.sys.costfun.info
% ========================================================================
if ismember(optim_param.sys.costfun.type,{'scopedfunction'})
optim_param.sys.costfun.type='local'; %scopedfunction=local function
end
if ismember(optim_param.sys.costfun.type,{'nested','local','simple'})
[~,optim_param.sys.costfun.name]=fileparts(optim_param.sys.costfun.function);
for n=1:numel(file_parse_info)
if strcmp(file_parse_info(n).name,optim_param.sys.costfun.name)
optim_param.sys.costfun.fcn_calls=unique(file_parse_info(n).calls.fcnCalls.names)';
end
end
elseif strcmp(optim_param.sys.costfun.type,'anonymous')
% throw error for anonymous function
error('cost function handle should not be anonymous - please use nested, local, or simple functions')
end
fcn_list=dbstack;
if numel(fcn_list)==1, optimise_fcn={}; end
if numel(fcn_list)>1, optimise_fcn=fcn_list(2).name; end
% ========================== STRUCT = OPTIM.ALGO =========================
% optimisation banner
optim_report(optim_param.sys.output,' ');
optim_report(optim_param.sys.output,'===========================================');
optim_report(optim_param.sys.output,'= =');
optim_report(optim_param.sys.output,'= OPTIMISATION =');
optim_report(optim_param.sys.output,'= =');
optim_report(optim_param.sys.output,'===========================================');
optim_report(optim_param.sys.output,' ');
if isfield(optim,'extremum') && ismember(optim.extremum,{'maximum','minimum'}) && ~ismember(optim.method,{'grad_descent','grad_ascent'}) && ismember(optimise_fcn,{'fminnewton','fminkrotov'})
optim_param.algo.extremum=optim.extremum;
optim=rmfield(optim,'extremum'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Find extremum',80) pad(optim_param.algo.extremum,20) ' (user-specified)']);
elseif ismember(optim.method,{'grad_descent'}) && ismember(optimise_fcn,{'fminnewton','fminkrotov'})
optim_param.algo.extremum='minimum';
optim_report(optim_param.sys.output,[pad('Find extremum',80) pad(optim_param.algo.extremum,20) ' (safe default)']);
elseif ismember(optim.method,{'grad_ascent'}) && ismember(optimise_fcn,{'fminnewton','fminkrotov'})
optim_param.algo.extremum='maximum';
optim_report(optim_param.sys.output,[pad('Find extremum',80) pad(optim_param.algo.extremum,20) ' (safe default)']);
elseif ismember(optimise_fcn,{'fminkrotov'})
optim_param.algo.extremum='maximum';
optim_report(optim_param.sys.output,[pad('Find extremum',80) pad(optim_param.algo.extremum,20) ' (safe default)']);
else
optim_param.algo.extremum='minimum';
optim_report(optim_param.sys.output,[pad('Find extremum',80) pad(optim_param.algo.extremum,20) ' (safe default)']);
end
switch optim_param.algo.extremum
case 'maximum'
optim_param.algo.max_min=+1;
case 'minimum'
optim_param.algo.max_min=-1;
end
if isfield(optim,'npen') && mod(optim.npen,1)==0
optim_param.algo.pen=true;
optim_param.algo.npen=optim.npen;
optim=rmfield(optim,'npen'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Display penalty terms',80) pad('true',20) ' (user-specified)']);
optim_report(optim_param.sys.output,[pad('Number of penalty terms',80) pad(int2str(optim_param.algo.npen),20) ' (user-specified)']);
else
optim_param.algo.pen=false;
optim_param.algo.npen=0;
end
% Optimisation method
switch optimise_fcn
case {'fminnewton','fminkrotov'}
if (~isfield(optim,'method') || ~ismember(optim.method,optim_algos)) && ~ismember(optimise_fcn,{'fminkrotov'})
optim_param.algo.method='lbfgs';
optim_report(optim_param.sys.output,[pad('Optimisation method',80) pad(optim_param.algo.method,20) ' (safe default)']);
elseif (n_vars > lbfgs_switch) && ~ismember(optim.method,{'grad_descent','grad_ascent'}) && ~ismember(optimise_fcn,{'fminkrotov'})
optim_param.algo.method='lbfgs';
optim_report(optim_param.sys.output,[pad(['Optimisation method (variables > ' num2str(lbfgs_switch) ')'],80) pad(optim_param.algo.method,20) ' (safe default)']);
elseif (~isfield(optim,'method') || ~ismember(optim.method,optim_algos))
optim_param.algo.method='krotov';
optim_report(optim_param.sys.output,[pad('Optimisation method',80) pad(optim_param.algo.method,20) ' (safe default)']);
elseif ismember(optim.method,optim_algos) % must be stated explicitly for krotov
optim_param.algo.method=optim.method;
optim=rmfield(optim,'method'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Optimisation method',80) pad(optim_param.algo.method,20) ' (user-specified)']);
end
if ~ismember(optimise_fcn,{'fminkrotov'})
% Store for the l-BFGS algorithm
if ismember(optim_param.algo.method,{'lbfgs'})
if isfield(optim,'n_store') && (mod(optim.n_store,1)==0) && optim.n_store>0 % if exists and is positive integer
optim_param.algo.n_store=optim.n_store; flag=0;
optim=rmfield(optim,'n_store'); % parsed -> remove
else
optim_param.algo.n_store=20; flag=1;
end
% Trial if StoreN fits into memory
succes=false;
while(~succes)
try
optim_param.algo.deltaX=zeros(n_vars,optim_param.algo.n_store);
optim_param.algo.deltaG=zeros(n_vars,optim_param.algo.n_store);
succes=true;
catch ME
optim_report(optim_param.sys.output,[pad('WARNING: lbfgs store, out of memory...',80) pad(num2str(optim_param.algo.n_store),20) ' (decrease size)']);
succes=false;
optim_param.algo.deltaX=[]; optim_param.algo.deltaG=[];
optim_param.algo.n_store=optim_param.algo.n_store-1;
if(optim_param.algo.n_store<1)
rethrow(ME);
end
end
end
if flag, optim_report(optim_param.sys.output,[pad('lbfgs iteration store',80) pad(num2str(optim_param.algo.n_store),20) ' (safe default)']);
else optim_report(optim_param.sys.output,[pad('lbfgs iteration store',80) pad(num2str(optim_param.algo.n_store),20) ' (user-specified)']);
end
end
end
if ismember(optim_param.algo.method,{'sr1','bfgs'}) && ~ismember(optimise_fcn,{'fminkrotov'})
if isfield(optim,'inverse_method')
optim_param.algo.inv_method=optim.inverse_method;
optim=rmfield(optim,'inverse_method'); % parsed -> remove
if optim_param.algo.inv_method, inverse_str='true'; else inverse_str='false'; end
optim_report(optim_param.sys.output,[pad(['Inverse-' optim_param.algo.method ' Hessian update method'],80) pad(num2str(inverse_str),20) ' (user-specified)']);
else
optim_param.algo.inv_method=true;
optim_report(optim_param.sys.output,[pad(['Inverse-' optim_param.algo.method ' Hessian update method'],80) pad('true',20) ' (safe default)']);
end
elseif ismember(optim_param.algo.method,{'sr1','bfgs','newton','krotov-bfgs','krotov-sr1'})
optim_param.algo.inv_method=false;
end
% ========================== STRUCT = OPTIM.TOLS =========================
% Maximum optimisation iterations
if isfield(optim,'max_iterations') && (mod(optim.max_iterations,1)==0 || isinf(optim.max_iterations)) && optim.max_iterations>=0
optim_param.tols.max_iter=optim.max_iterations;
optim=rmfield(optim,'max_iterations'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Maximum optimisation iterations',80) pad(num2str(optim_param.tols.max_iter),20) ' (user-specified)']);
else
optim_param.tols.max_iter=100;
optim_report(optim_param.sys.output,[pad('Maximum optimisation iterations',80) pad(num2str(optim_param.tols.max_iter),20) ' (safe default)']);
end
% termination tolerance on x
if isfield(optim,'tol_x') && isnumeric(optim.tol_x)
optim_param.tols.x=optim.tol_x;
optim=rmfield(optim,'tol_x'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Termination tolerance on x',80) pad(num2str(optim_param.tols.x,'%0.8g'),20) ' (user-specified)']);
else
optim_param.tols.x=1e-6;
optim_report(optim_param.sys.output,[pad('Termination tolerance on x',80) pad(num2str(optim_param.tols.x,'%0.8g'),20) ' (safe default)']);
end
if isfield(optim,'cost_display')
optim_param.algo.f_disp=optim.cost_display;
optim=rmfield(optim,'cost_display'); % parsed -> remove
end
% termination tolerance on f(x)
if isfield(optim,'tol_fx') && isnumeric(optim.tol_fx)
optim_param.tols.fx=optim.tol_fx;
optim=rmfield(optim,'tol_fx'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Termination tolerance on f(x)',80) pad(num2str(optim_param.tols.fx,'%0.9g'),20) ' (user-specified)']);
else
optim_param.tols.fx=optim_param.algo.max_min*Inf;
end
% termination tolerance on the norm of gradient
if isfield(optim,'tol_gfx') && isnumeric(optim.tol_gfx) && ~ismember(optimise_fcn,{'fminkrotov'})
optim_param.tols.gfx=optim.tol_gfx;
optim=rmfield(optim,'tol_gfx'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Termination tolerance on norm[grad(x)] (1st order optimility)',80) pad(num2str(optim_param.tols.gfx,'%0.8g'),20) ' (user-specified)']);
elseif ~ismember(optimise_fcn,{'fminkrotov'})
optim_param.tols.gfx=1e-6;
optim_report(optim_param.sys.output,[pad('Termination tolerance on norm[grad(x)] (1st order optimility)',80) pad(num2str(optim_param.tols.gfx,'%0.8g'),20) ' (safe default)']);
end
% ======================= STRUCT = OPTIM.LINESEARCH ======================
% linesearch does not apply to krotov methods
if ~ismember(optimise_fcn,{'fminkrotov'})
% add maximising/minimising strategy to linesreach structure
switch optim_param.algo.extremum
case 'maximum'
optim_param.linesearch.max_min=+1;
case 'minimum'
optim_param.linesearch.max_min=-1;
end
% linesearch method
if isfield(optim,'linesearch') && ismember(optim.linesearch,search_algos)
optim_param.linesearch.method=optim.linesearch;
optim=rmfield(optim,'linesearch'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Line-search method',80) pad(optim_param.linesearch.method,20) ' (user-specified)']);
else
optim_param.linesearch.method='bracket-section';
optim_report(optim_param.sys.output,[pad('Line-search method',80) pad(optim_param.linesearch.method,20) ' (safe default)']);
end
% no line-search is equivalent to 'newton-step'
if ~ismember(optim_param.linesearch.method,{'newton-step'})
% linesearch conditions
if isfield(optim,'linesearch_rules') && ismember(optim.linesearch_rules,search_rules)
if ismember(optim.linesearch_rules,'Wolfe'), optim.linesearch_rules='Wolfe-strong'; end % Wolfe-strong is assumed for Wolfe
optim_param.linesearch.rules=optim.linesearch_rules;
optim=rmfield(optim,'linesearch_rules'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Line-search conditions',80) pad(optim_param.linesearch.rules,20) ' (user-specified)']);
elseif ismember(optim_param.linesearch.method,{'backtracking'})
optim_param.linesearch.rules='Armijo';
optim_report(optim_param.sys.output,[pad('Line-search conditions',80) pad(optim_param.linesearch.rules,20) ' (safe default)']);
else
optim_param.linesearch.rules='Wolfe-strong';
optim_report(optim_param.sys.output,[pad('Line-search conditions',80) pad(optim_param.linesearch.rules,20) ' (safe default)']);
end
% Armijo condition: sufficient decrease
if isfield(optim,'tol_linesearch_fx') && ismember(optim_param.linesearch.rules,{'Wolfe-strong','Wolfe-weak','Armijo'}) &&...
0<(optim.tol_linesearch_fx<1)
optim_param.linesearch.tols.c1=optim.tol_linesearch_fx;
optim=rmfield(optim,'tol_linesearch_fx'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Armijo-Goldstein inequality: condition of sufficient decrease',80) pad(num2str(optim_param.linesearch.tols.c1,'%0.8g'),20) ' (user-specified)']);
elseif isfield(optim,'tol_linesearch_fx') && ismember(optim_param.linesearch.rules,{'Goldstein'}) &&...
0<(optim.tol_linesearch_fx<0.5)
optim_param.linesearch.tols.c1=optim.tol_linesearch_fx;
optim=rmfield(optim,'tol_linesearch_fx'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Armijo-Goldstein inequality: condition of sufficient decrease',80) pad(num2str(optim_param.linesearch.tols.c1,'%0.8g'),20) ' (user-specified)']);
elseif ismember(optim_param.linesearch.rules,{'Wolfe-strong','Wolfe-weak','Armijo'}) && ismember(optim_param.algo.method,{'newton'})
optim_param.linesearch.tols.c1=1e-2;
optim_report(optim_param.sys.output,[pad('Armijo-Goldstein inequality: condition of sufficient decrease',80) pad(num2str(optim_param.linesearch.tols.c1,'%0.8g'),20) ' (safe default)']);
elseif ismember(optim_param.linesearch.rules,{'Wolfe-strong','Wolfe-weak','Armijo'})
optim_param.linesearch.tols.c1=1e-2;
optim_report(optim_param.sys.output,[pad('Armijo-Goldstein inequality: condition of sufficient decrease',80) pad(num2str(optim_param.linesearch.tols.c1,'%0.8g'),20) ' (safe default)']);
elseif ismember(optim_param.linesearch.rules,{'Goldstein'})
optim_param.linesearch.tols.c1=0.25;
optim_report(optim_param.sys.output,[pad('Armijo-Goldstein inequality: condition of sufficient decrease',80) pad(num2str(optim_param.linesearch.tols.c1,'%0.8g'),20) ' (safe default)']);
end
% Wolfe condition: curvature condition
if isfield(optim,'tol_linesearch_gfx') && ismember(optim_param.linesearch.rules,{'Wolfe','Wolfe-strong'}) &&...
optim_param.linesearch.tols.c1<(optim.tol_linesearch_gfx<1)
optim_param.linesearch.tols.c2=optim.tol_linesearch_gfx;
optim=rmfield(optim,'tol_linesearch_gfx'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Wolfe-Powel condition: curvature condition',80) pad(num2str(optim_param.linesearch.tols.c2,'%0.8g'),20) ' (user-specified)']);
elseif ismember(optim_param.linesearch.rules,{'Wolfe-weak','Wolfe-strong'})
optim_param.linesearch.tols.c2=0.9;
optim_report(optim_param.sys.output,[pad('Wolfe-Powel condition: curvature condition',80) pad(num2str(optim_param.linesearch.tols.c2,'%0.8g'),20) ' (safe default)']);
end
% Backtracting linesearch contraction factor
if isfield(optim,'tol_linesearch_reduction')&& ismember(optim_param.linesearch.method,{'backtracking'}) &&...
0<(optim.tol_linesearch_reduction<1)
optim_param.linesearch.tols.tau=optim.tol_linesearch_reduction;
optim=rmfield(optim,'tol_linesearch_reduction'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Backtracting step reduction factor',80) pad(num2str(optim_param.linesearch.tols.tau,'%0.8g'),20) ' (user-specified)']);
elseif ismember(optim_param.linesearch.method,{'backtracking'}) && ismember(optim_param.linesearch.rules,{'Goldstein'})
optim_param.linesearch.tols.tau=(2/(1+sqrt(5))); %1/sqrt(2)
optim_report(optim_param.sys.output,[pad('Backtracting step reduction factor',80) pad(num2str(optim_param.linesearch.tols.tau,'%0.8g'),20) ' (safe default)']);
elseif ismember(optim_param.linesearch.method,{'backtracking'})
optim_param.linesearch.tols.tau=(2/(1+sqrt(5))); %0.5;%1/sqrt(2);
optim_report(optim_param.sys.output,[pad('Backtracting step reduction factor',80) pad(num2str(optim_param.linesearch.tols.tau,'%0.8g'),20) ' (safe default)']);
end
if ismember(optim_param.linesearch.method,{'bracket-section'})
% Bracket expansion if stepsize becomes larger
if isfield(optim,'tau1') && optim.tau1>1
optim_param.linesearch.tols.tau1=optim.tau1;
optim=rmfield(optim,'tau1'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Bracket expansion if stepsize becomes larger',80) pad(num2str(optim_param.linesearch.tols.tau1,'%0.8g'),20) ' (user-specified)']);
else
optim_param.linesearch.tols.tau1=3;
optim_report(optim_param.sys.output,[pad('Bracket expansion if stepsize becomes larger',80) pad(num2str(optim_param.linesearch.tols.tau1,'%0.8g'),20) ' (safe default)']);
end
% Left bracket reduction used in section phase
if isfield(optim,'tau2') && 0<(optim.tau2<1)
optim_param.linesearch.tols.tau2=optim.tau2;
optim=rmfield(optim,'tau2'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Left bracket reduction used in section phase',80) pad(num2str(optim_param.linesearch.tols.tau2,'%0.8g'),20) ' (user-specified)']);
else
optim_param.linesearch.tols.tau2=0.1;
optim_report(optim_param.sys.output,[pad('Left bracket reduction used in section phase',80) pad(num2str(optim_param.linesearch.tols.tau2,'%0.8g'),20) ' (safe default)']);
end
% Right bracket reduction used in section phase
if isfield(optim,'tau3') && 0<(optim.tau3<1)
optim_param.linesearch.tols.tau3=optim.tau3;
optim=rmfield(optim,'tau3'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Right bracket reduction used in section phase',80) pad(num2str(optim_param.linesearch.tols.tau3,'%0.8g'),20) ' (user-specified)']);
else
optim_param.linesearch.tols.tau3=0.5;
optim_report(optim_param.sys.output,[pad('Right bracket reduction used in section phase',80) pad(num2str(optim_param.linesearch.tols.tau3,'%0.8g'),20) ' (safe default)']);
end
end
end
end
% =========================== STRUCT = OPTIM.REG =========================
% if newton, sr1, or bfgs method defined, set hessian tolerances
if ismember(optim_param.algo.method,{'newton','sr1','bfgs','krotov-bfgs','krotov-sr1'})
switch optim_param.algo.extremum
case 'maximum'
optim_param.reg.def=-1;
case 'minimum'
optim_param.reg.def=+1;
end
% Hessian regularisation method
if isfield(optim,'regularisation') && ismember(optim.regularisation,reg_method)
optim_param.reg.method=optim.regularisation;
optim=rmfield(optim,'regularisation'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Hessian/approximation regularisation method',80) pad(optim_param.reg.method,20) ' (user-specified)']);
elseif ismember(optim_param.algo.method,{'newton'})
optim_param.reg.method='RFO';
optim_report(optim_param.sys.output,[pad('Hessian/approximation regularisation method',80) pad(optim_param.reg.method,20) ' (safe default)']);
elseif ismember(optim_param.algo.method,{'sr1','bfgs'})
optim_param.reg.method='';
optim_report(optim_param.sys.output,[pad('Hessian/approximation regularisation method',80) pad('none',20) ' (safe default)']);
elseif ismember(optim_param.algo.method,{'krotov-bfgs','krotov-sr1'})
optim_param.reg.method='TRM';
optim_report(optim_param.sys.output,[pad('Hessian/approximation regularisation method',80) pad(optim_param.reg.method,20) ' (safe default)']);
else
optim_param.reg.method='';
end
% Hessian conditioning method -
if isfield(optim,'conditioning') && ismember(optim.conditioning,reg_cond)
if ismember(optim_param.reg.method,{'RFO','TRM'})
if ismember(optim.conditioning,{'none',''})
optim_param.reg.cond_method='';
optim=rmfield(optim,'conditioning'); % parsed -> remove
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad('none',20) ' (user-specified)']);
else
optim_param.reg.cond_method=optim.conditioning;
optim=rmfield(optim,'conditioning'); % parsed -> remove
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad(optim_param.reg.cond_method,20) ' (user-specified)']);
end
elseif ismember(optim_param.reg.method,{'CHOL'})
optim_param.reg.cond_method='';
end
elseif ismember(optim_param.reg.method,{'RFO'}) && any(ismember({'krotov'},optim_param.sys.costfun.fcn_calls))
optim_param.reg.cond_method='scaled';
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad(optim_param.reg.cond_method,20) ' (safe default)']);
elseif ismember(optim_param.reg.method,{'RFO'})
optim_param.reg.cond_method='iterative';
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad(optim_param.reg.cond_method,20) ' (safe default)']);
elseif ismember(optim_param.reg.method,{'TRM'})
if ~isfield(optim,'max_cond'), optim_param.reg.cond_method='';
else optim_param.reg.cond_method='iterative'; end
optim_report(optim_param.sys.output,[pad('Hessian/approximation conditioning method',80) pad('none',20) ' (safe default)']);
elseif ~ismember(optim_param.reg.method,{'CHOL'}) && ismember(optimise_fcn,{'fminkrotov'})
optim_param.reg.method='RFO';
optim_param.reg.cond_method='scaled';
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad(optim_param.reg.cond_method,20) ' (safe default)']);
elseif ~ismember(optim_param.reg.method,{'CHOL'})
optim_param.reg.method='RFO';
optim_param.reg.cond_method='iterative';
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad(optim_param.reg.cond_method,20) ' (safe default)']);
elseif isfield(optim,'max_cond')
optim_param.reg.method='RFO';
optim_param.reg.cond_method='iterative';
optim_report(optim_param.sys.output,[pad(['Hessian/approximation conditioning method (' optim_param.reg.method ')'],80) pad(optim_param.reg.cond_method,20) ' (safe default)']);
else
optim_param.reg.cond_method='';
end
% Maximum Regularisation/conditioning iterates for RFO, TRM and CHOL
if isfield(optim,'n_reg') && ismember(optim_param.reg.method,reg_method) && (mod(optim.n_reg,1)==0) && optim.n_reg>0
optim_param.reg.n_reg=optim.n_reg;
optim=rmfield(optim,'n_reg'); % parsed -> remove
if ismember(optim_param.reg.method,{'CHOL'})
optim_report(optim_param.sys.output,[pad(['Maximum regularisation (' optim_param.reg.method ') iteratations'],80) pad(num2str(optim_param.reg.n_reg),20) ' (user-specified)']);
elseif ismember(optim_param.reg.method,{'RFO','TRM'})
optim_report(optim_param.sys.output,[pad(['Maximum conditioning (' optim_param.reg.method ') iteratations'],80) pad(num2str(optim_param.reg.n_reg),20) ' (user-specified)']);
end
elseif ismember(optim_param.reg.method,reg_method)
optim_param.reg.n_reg=2500;
if ismember(optim_param.reg.method,{'CHOL'})
optim_report(optim_param.sys.output,[pad(['Maximum regularisation (' optim_param.reg.method ') iteratations'],80) pad(num2str(optim_param.reg.n_reg),20) ' (safe default)']);
elseif ismember(optim_param.reg.method,{'RFO','TRM'})
optim_report(optim_param.sys.output,[pad(['Maximum conditioning (' optim_param.reg.method ') iteratations'],80) pad(num2str(optim_param.reg.n_reg),20) ' (safe default)']);
end
end
if ~ismember(optim_param.reg.method,{'CHOL'})
% Hessian conditioning method for RFO
if isfield(optim,'alpha') && ismember(optim_param.reg.method ,{'RFO'}) && (optim.alpha>0)
optim_param.reg.alpha=optim.alpha;
optim=rmfield(optim,'alpha'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('RFO uniform scaling factor (alpha)',80) pad(num2str(optim_param.reg.alpha,'%0.8g'),20) ' (user-specified)']);
elseif ismember(optim_param.reg.method,{'RFO'})
optim_param.reg.alpha=1;
optim_report(optim_param.sys.output,[pad('RFO uniform scaling factor (alpha)',80) pad(num2str(optim_param.reg.alpha,'%0.8g'),20) ' (safe default)']);
end
% Hessian delta value for TRM
if isfield(optim,'delta') && ismember(optim_param.reg.method,{'TRM'}) && (optim.delta>0)
optim_param.reg.delta=optim.delta;
optim=rmfield(optim,'delta'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('TRM uniform shifting factor (delta)',80) pad(num2str(optim_param.reg.delta,'%0.8g'),20) ' (user-specified)']);
elseif ismember(optim_param.reg.method,{'TRM'})
optim_param.reg.delta=1;
optim_report(optim_param.sys.output,[pad('TRM uniform shifting factor (delta)',80) pad(num2str(optim_param.reg.delta,'%0.8g'),20) ' (safe default)']);
end
if ~isempty(optim_param.reg.cond_method)
% Hessian phi, alpha reduction factor for RFO
if isfield(optim,'phi') && ismember(optim_param.reg.method,{'RFO','TRM'}) && (optim.phi>0)
optim_param.reg.phi=optim.phi;
optim=rmfield(optim,'phi'); % parsed -> remove
optim_report(optim_param.sys.output,[pad([optim_param.reg.method ' conditioning factor (phi)'],80) pad(num2str(optim_param.reg.phi,'%0.8g'),20) ' (user-specified)']);
elseif ismember(optim_param.reg.method,{'RFO'})
optim_param.reg.phi=0.9;
optim_report(optim_param.sys.output,[pad([optim_param.reg.method ' conditioning factor (phi)'],80) pad(num2str(optim_param.reg.phi,'%0.8g'),20) ' (safe default)']);
elseif ismember(optim_param.reg.method,{'TRM'})
optim_param.reg.phi=1/(0.9)^2;
optim_report(optim_param.sys.output,[pad([optim_param.reg.method ' conditioning factor (phi)'],80) pad(num2str(optim_param.reg.phi,'%0.8g'),20) ' (safe default)']);
end
% maximum condition number of Hessian for iterative or scaled conditioning
if isfield(optim,'max_cond') && ismember(optim_param.reg.method,{'RFO','TRM'}) && optim.max_cond>0
optim_param.reg.max_cond=optim.max_cond;
optim=rmfield(optim,'max_cond'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Maximum Hessian/approximation condition number',80) pad(num2str(optim_param.reg.max_cond,'%0.8e'),20) ' (user-specified)']);
elseif ismember(optim_param.reg.cond_method,{'iterative'})&&ismember(optim_param.reg.method,{'RFO','TRM'})
optim_param.reg.max_cond=1e4;
optim_report(optim_param.sys.output,[pad('Maximum Hessian/approximation condition number',80) pad(num2str(optim_param.reg.max_cond,'%0.8e'),20) ' (safe default)']);
elseif ismember(optim_param.reg.cond_method,{'scaled'})&&ismember(optim_param.reg.method,{'RFO','TRM'})
optim_param.reg.max_cond=1e14;
optim_report(optim_param.sys.output,[pad('Maximum Hessian/approximation condition number',80) pad(num2str(optim_param.reg.max_cond,'%0.8e'),20) ' (safe default)']);
end
end
end
% optional eigenvalue tracking (should be used for investigating a problem or debugging)
else
optim_param.reg.method='';
optim_param.reg.cond_method='';
end
if isfield(optim,'track_eig') && ismember(optim_param.algo.method,{'newton','sr1','bfgs','krotov-bfgs','krotov-sr1'})
optim_param.reg.track_eig=optim.track_eig;
optim=rmfield(optim,'track_eig'); % parsed -> remove
if optim_param.reg.track_eig, track_str='true'; else track_str='false'; end
optim_report(optim_param.sys.output,[pad('Explicitly track eigenvalues of Hessian/approximation',80) pad(num2str(track_str),20) ' (user-specified)']);
else
optim_param.reg.track_eig=false;
end
case {'fminsimplex'}
if (~isfield(optim,'method') || ~ismember(optim.method,{'nm_simplex','md_simplex'}))
optim_param.algo.method='nm_simplex';
optim_report(optim_param.sys.output,[pad('Optimisation method',80) pad(optim_param.algo.method,20) ' (safe default)']);
elseif ismember(optim.method,{'nm_simplex','md_simplex'}) % must be stated explicitly for krotov
optim_param.algo.method=optim.method;
optim=rmfield(optim,'method'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Optimisation method',80) pad(optim_param.algo.method,20) ' (user-specified)']);
end
if isfield(optim,'parallel_cost_fcn')
optim_param.algo.parallel_cost_fcn=optim.parallel_cost_fcn;
optim=rmfield(optim,'parallel_cost_fcn'); % parsed -> remove
if optim_param.algo.parallel_cost_fcn, par_str='true'; else par_str='false'; end
optim_report(optim_param.sys.output,[pad(['Parallel-' optim_param.algo.method ' cost function'],80) pad(num2str(par_str),20) ' (user-specified)']);
else
optim_param.algo.parallel_cost_fcn=false; % do not report to user - this is an advanced method
end
if (~isfield(optim,'simplex_min'))
optim_param.tols.simplex_min=1e-3;
optim_report(optim_param.sys.output,[pad('Tolerance for cgce test based on relative size of simplex',80) pad(num2str(optim_param.tols.simplex_min,'%0.8e'),20) ' (safe default)']);
else
optim_param.tols.simplex_min=optim.simplex_min;
optim=rmfield(optim,'simplex_min'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Tolerance for cgce test based on relative size of simplex',80) pad(num2str(optim_param.tols.simplex_min,'%0.8e'),20) ' (user-specified)']);
end
% Maximum optimisation iterations
if isfield(optim,'max_iterations') && (mod(optim.max_iterations,1)==0 || isinf(optim.max_iterations)) && optim.max_iterations>=0
optim_param.tols.max_iter=optim.max_iterations;
optim=rmfield(optim,'max_iterations'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Maximum optimisation iterations',80) pad(num2str(optim_param.tols.max_iter),20) ' (user-specified)']);
else
optim_param.tols.max_iter=100;
optim_report(optim_param.sys.output,[pad('Maximum optimisation iterations',80) pad(num2str(optim_param.tols.max_iter),20) ' (safe default)']);
end
% maximum optimisation iterates
if (~isfield(optim,'max_n_fx'))
optim_param.tols.max_n_fx=Inf;
optim_report(optim_param.sys.output,[pad('Max no. of f-evaluations',80) pad(num2str(optim_param.tols.max_n_fx),20) ' (safe default)']);
else
optim_param.tols.max_n_fx=optim.max_n_fx;
optim=rmfield(optim,'max_n_fx'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Max no. of f-evaluations',80) pad(num2str(optim_param.tols.max_n_fx),20) ' (user-specified)']);
end
if (~isfield(optim,'termination'))
optim_param.tols.termination=-Inf;
optim_report(optim_param.sys.output,[pad('Target for f-values',80) pad(num2str(optim_param.tols.termination,'%0.8e'),20) ' (safe default)']);
else
optim_param.tols.termination=optim.termination;
optim=rmfield(optim,'termination'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Target for f-values',80) pad(num2str(optim_param.tols.termination,'%0.8e'),20) ' (user-specified)']);
end
if (~isfield(optim,'init_simplex'))
optim_param.algo.init_simplex='equilateral';
optim_report(optim_param.sys.output,[pad('Initial simplex',80) pad(optim_param.algo.init_simplex,20) ' (safe default)']);
else
optim_param.algo.init_simplex=optim.init_simplex;
optim=rmfield(optim,'init_simplex'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Initial simplex',80) pad(optim_param.algo.init_simplex,20) ' (user-specified)']);
end
if (~isfield(optim,'expansion'))
optim_param.tols.expansion=2;
optim_report(optim_param.sys.output,[pad('Expansion factor',80) pad(num2str(optim_param.tols.expansion,'%0.8e'),20) ' (safe default)']);
else
optim_param.tols.expansion=optim.expansion;
optim=rmfield(optim,'expansion'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Expansion factor',80) pad(num2str(optim_param.tols.expansion,'%0.8e'),20) ' (user-specified)']);
end
if (~isfield(optim,'contraction'))
optim_param.tols.contraction=0.5;
optim_report(optim_param.sys.output,[pad('Contraction factor',80) pad(num2str(optim_param.tols.contraction,'%0.8e'),20) ' (safe default)']);
else
optim_param.tols.contraction=optim.contraction;
optim=rmfield(optim,'contraction'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Contraction factor',80) pad(num2str(optim_param.tols.contraction,'%0.8e'),20) ' (user-specified)']);
end
if (~isfield(optim,'reflection')) && ismember(optim_param.algo.method,{'nm_simplex'})
optim_param.tols.reflection=1.0;
optim_report(optim_param.sys.output,[pad('Reflection factor',80) pad(num2str(optim_param.tols.reflection,'%0.8e'),20) ' (safe default)']);
elseif ismember(optim_param.algo.method,{'nm_simplex'})
optim_param.tols.reflection=optim.reflection;
optim=rmfield(optim,'reflection'); % parsed -> remove
optim_report(optim_param.sys.output,[pad('Reflection factor',80) pad(num2str(optim_param.tols.reflection,'%0.8e'),20) ' (user-specified)']);
end
otherwise
error('unknown optimisation function')
end
% objective function display
if isfield(optim,'obj_fun_disp') && isa(optim.obj_fun_disp,'function_handle')
obj_fun_disp_data=functions(optim.obj_fun_disp);
if ismember(obj_fun_disp_data.type,{'anonymous'})
optim_param.sys.obj_fun_disp=optim.obj_fun_disp;
optim=rmfield(optim,'obj_fun_disp'); % parsed -> remove
optim_report(optim_param.sys.output,[pad(['Objective function display = ', func2str(optim_param.sys.obj_fun_disp)],100) ' (user-specified)']);
fx=sym('fx');
obj_fun_str=char(optim_param.sys.obj_fun_disp(fx));
obj_fun_str=strrep(obj_fun_str,'fx','f(x)');
optim_param.sys.obj_fun_str=obj_fun_str;
else
error('objective function display should be an anonymous function')
end
else
% (default -> force)
optim_param.sys.obj_fun_disp=@(f_x)(f_x);
optim_param.sys.obj_fun_str='f(x)';
end
optim_param.sys.obj_fun_str=[optim_param.algo.extremum(1:3) '[' optim_param.sys.obj_fun_str ']'];
% Optimisation output function, evaluated at each iteration
if isa(optim_param.sys.outputfun,'function_handle')
optim_report(optim_param.sys.output,[pad(['Optimisation output function = @', func2str(optim_param.sys.outputfun)],100) ' (user-specified)']);
end
unprocessed=fieldnames(optim);
if ~isempty(unprocessed)
optim_report(optim_param.sys.output,'----------------------------------------------------------------------------------------------');
for n=1:numel(unprocessed)
optim_report(optim_param.sys.output,[pad('WARNING: unprocessed option',80) pad(unprocessed{n},20)]);
end
optim_report(optim_param.sys.output,'----------------------------------------------------------------------------------------------');
end
end
|
github
|
tsajed/nmr-pred-master
|
linesearch.m
|
.m
|
nmr-pred-master/spinach/kernel/optimcon/linesearch.m
| 11,759 |
utf_8
|
35f058447bda67464a20c82e7a0e5a98
|
% Performs a line search to find an appropriate step length called from
% within a given optimisation algorithm, e.g. using fminnewton.m. This
% function generally assumes cheap gradients.
%
% bracket-section line search based on fminlbfgs.m code from D. Kroon,
% University of Twente (Nov 2010).
%
% <http://spindynamics.org/wiki/index.php?title=Linesearch.m>
function [alpha,fx_1,gfx_1,exitflag,data]=linesearch(cost_function,...
d_0, x_0, fx_0, gfx_0, data, optim)
% set alpha to alpha_0
if (ismember(optim.algo.method,{'grad_ascent','grad_descent'})) ||...
(ismember(optim.algo.method,{'lbfgs','bfgs','sr1'}) && data.iter==0)
alpha=min(1/norm(gfx_0,Inf),5);
else
alpha=1;
end
% set new x to that with initial alpha
x_1=x_0+alpha*d_0;
% preallocate initial functional and gradient
fx_1=[]; gfx_1=[]; exitflag=[];
switch optim.linesearch.method
case {'bracket-section'}
% initial evaluation of line search
switch optim.linesearch.rules
case {'Armijo','Goldstein'}
[data,fx_1]=objeval(x_1,cost_function, data);
case {'Wolfe','Wolfe-weak','Wolfe-strong'}
[data,fx_1,gfx_1]=objeval(x_1,cost_function, data);
end
% Find a bracket [A B] of acceptable points
[A, B, alpha, fx_1, gfx_1, exitflag, data] = bracketing(cost_function,...
alpha, d_0, x_0, fx_0, gfx_0, fx_1, gfx_1, data, optim.linesearch);
if (exitflag == 2)
% Find acceptable point within bracket
[alpha, fx_1, gfx_1, exitflag, data] = sectioning(cost_function,...
A, B, x_0, fx_0, gfx_0, d_0, data, optim.linesearch);
end
case {'backtracking'}
fminimum = fx_0 - 1e16*(1+abs(fx_0));
% find acceptable search length
while (true)
% initial evaluation of line search
switch optim.linesearch.rules
case {'Armijo','Goldstein'}
[data,fx_1]=objeval(x_1,cost_function, data);
case {'Wolfe','Wolfe-weak','Wolfe-strong'}
[data,fx_1,gfx_1]=objeval(x_1,cost_function, data);
end
% Terminate if f < fminimum
if (fx_1 <= fminimum), exitflag = 3; return; end
% Goldstein conditions of sufficient decrease satisfied
if alpha_conditions(1,alpha,fx_0,fx_1,gfx_0,gfx_1,d_0,optim.linesearch) &&...
alpha_conditions(2,alpha,fx_0,fx_1,gfx_0,gfx_1,d_0,optim.linesearch)
break,
end
% set new alpha with contraction factor (rho)
alpha = alpha*optim.linesearch.tols.tau;
% check step length is not too small
if alpha < eps, exitflag = -2; break, end
% update x with new alpha
x_1=x_0+alpha*d_0;
end
case {'newton-step'}
%already done
alpha=1; fx_1=[]; gfx_1=[];
otherwise
error('unknown line search method')
end
end
function [A, B, alpha, fx, gfx, exitflag, data] = bracketing(cost_function,...
alpha, d_0, x_0, fx_0, gfx_0, fx_2, gfx_2, data, ls_param)
% Initialise bracket A and bracket B
A.alpha = []; A.fx = []; A.gfx = [];
B.alpha = []; B.fx = []; B.gfx = [];
% Set maximum value of alpha (determined by fminimum)
fminimum = (-1e16*(1+abs(fx_0)) - ls_param.max_min*fx_0);
alpha_max = ls_param.max_min*(fx_0 - fminimum)/(ls_param.tols.c1*gfx_0'*d_0);
% Evaluate f(alpha) and f'(alpha)
fx=fx_0; fx_1 = fx_0;
gfx = gfx_0; gfx_1 = gfx_0;
alpha_1=0; alpha_2=alpha;
while(true)
% Terminate if f < fminimum
if (fx_2 <= fminimum),
exitflag = 3; return;
end
% Bracket located - case 1 (Wolfe conditions)
if ~alpha_conditions(1,alpha,fx_0,fx_2,gfx_0,[],d_0,ls_param) ||...
~alpha_conditions(0,[],fx_0,fx_2,[],[],[],ls_param)
% Set the bracket values
A.alpha = alpha_1; A.fx = fx_1; A.gfx = gfx_1;
B.alpha = alpha_2; B.fx = fx_2; B.gfx = gfx_2;
% Finished bracketing phase
exitflag = 2; return
end
% Acceptable steplength found
if alpha_conditions(2,alpha,fx_0,fx_2,gfx_0,gfx_2,d_0,ls_param)
% Store the found alpha values
alpha=alpha_2; fx=fx_2; gfx=gfx_2;
% Finished bracketing phase, and no need to call sectioning phase
exitflag = []; return
end
% Bracket located - case 2
if ~alpha_conditions(3,[],[],[],[],gfx_2,d_0,ls_param)
% Set the bracket values
A.alpha = alpha_2; A.fx = fx_2; A.gfx = gfx_2;
B.alpha = alpha_1; B.fx = fx_1; B.gfx = gfx_1;
% Finished bracketing phase
exitflag = 2; return
end
% Update alpha (2*alpha_2 - alpha_1 > alpha_max )
if (2*alpha_2 - alpha_1 < alpha_max )
brcktEndpntA = 2*alpha_2-alpha_1;
brcktEndpntB = min(alpha_max,alpha_2+ls_param.tols.tau1*(alpha_2-alpha_1));
% Find global minimizer in bracket [brcktEndpntA,brcktEndpntB] of 3rd-degree polynomial
% that interpolates f() and f'() at alphaPrev and at alpha
alpha_new = cubic_interpolation(brcktEndpntA,brcktEndpntB,...
alpha_1, alpha_2, fx_1, gfx_1'*d_0, fx_2, gfx_2'*d_0,ls_param.max_min);
alpha_1 = alpha_2;
alpha_2=alpha_new;
else
alpha_2 = alpha_max;
end
% Evaluate f(alpha) and f'(alpha)
fx_1 = fx_2; gfx_1 = gfx_2;
x_1=x_0+alpha_2*d_0;
% Calculate value and gradient of current alpha
[data,fx_2, gfx_2]=objeval(x_1,cost_function, data);
end
end
function [alpha, fx_1, gfx_1, exitflag, data] = sectioning(cost_function, A, B, x_0, fx_0, gfx_0, d_0, data, ls_param)
alpha=[]; fx_1=[]; gfx_1=[];
while(true)
% Pick alpha in reduced bracket
End_A = A.alpha + min(ls_param.tols.tau2,ls_param.tols.c2)*(B.alpha - A.alpha);
End_B = B.alpha - ls_param.tols.tau3*(B.alpha - A.alpha);
% Find global minimizer in bracket [brcktEndpntA,brcktEndpntB] of 3rd-degree
% polynomial that interpolates f() and f'() at "a" and at "b".
alpha = cubic_interpolation(End_A,End_B,...
A.alpha, B.alpha, A.fx, A.gfx'*d_0, B.fx, B.gfx'*d_0,ls_param.max_min);
% No acceptable point could be found
if (abs( (alpha - A.alpha)*(A.gfx'*d_0) ) <= eps(max(1,abs(fx_0))))
exitflag = -2; return;
end
% Calculate value and gradient of current alpha
[data,fx_1, gfx_1]=objeval(x_0+alpha*d_0, cost_function, data);
% Store current bracket position of A
Tmp=A;
% Update the current brackets
if ~alpha_conditions(1,alpha,fx_0,fx_1,gfx_0,gfx_1,d_0,ls_param) ||...
~alpha_conditions(0,alpha,A.fx,fx_1,A.gfx,gfx_1,d_0,ls_param)
% Update bracket B to current alpha
B.alpha = alpha; B.fx = fx_1; B.gfx = gfx_1;
else
% Wolfe conditions, if true then acceptable point found
if alpha_conditions(2,alpha,fx_0,fx_1,gfx_0,gfx_1,d_0,ls_param)
exitflag = []; return,
end
% Update bracket A
A.alpha = alpha; A.fx = fx_1; A.gfx = gfx_1;
% B becomes old bracket A;
if ls_param.max_min*(A.alpha - B.alpha)*(gfx_1'*d_0) >= 0, B=Tmp; end
end
% No acceptable point could be found
if (abs(B.alpha-A.alpha) < eps), exitflag = -2; return, end
end
end
function [alpha,fx]= cubic_interpolation(End_A,End_B,alpha_A,alpha_B,f_A,dir_deriv_A,f_B,dir_deriv_B,max_min)
% determines the coefficients of the cubic polynomial
c1=-2*(f_B-f_A) + (dir_deriv_A+dir_deriv_B)*(alpha_B-alpha_A);
c2= 3*(f_B-f_A) - (2*dir_deriv_A+dir_deriv_B)*(alpha_B-alpha_A);
c3=(alpha_B-alpha_A)*dir_deriv_A;
c4=f_A;
% Convert bounds to the z-space
bounds = ([End_A End_B ]-alpha_A)./(alpha_B - alpha_A);
% Find minima and maxima from the roots of the derivative of the polynomial.
sPoints = roots([3*c1 2*c2 1*c3]);
% Remove imaginary and points outside range and make vector with solutions
sPoints(imag(sPoints)~=0)=[];
sPoints(sPoints<min(bounds))=[];
sPoints(sPoints>max(bounds))=[];
sPoints=[min(bounds) sPoints(:)' max(bounds)];
% Select the global minimum point
[fx,k]=max(max_min*polyval([c1 c2 c3 c4],sPoints)); fx=max_min*fx;
% Add the offset and scale back from [0..1] to the alpha domain
alpha = alpha_A + sPoints(k)*(alpha_B - alpha_A);
end
function test=alpha_conditions(test_type,alpha,fx_0,fx_1,gfx_0,gfx_1,d_0,ls_def)
% note: ls_def.max_min switches maximisation (+1) and minimisation (-1)
fx_0=ls_def.max_min.*fx_0;
fx_1=ls_def.max_min.*fx_1;
switch ls_def.rules
case {'Armijo'}
if test_type==0
% increase (max) or decrease (min) of functional value -
% gradient free test
test=(fx_1 > fx_0);
elseif test_type==1
% sufficient increase( max) or decrease (min) of function -
% also called Armijo condition
test=(fx_1 >= fx_0 + ls_def.max_min.*ls_def.tols.c1*alpha*(gfx_0'*d_0));
elseif test_type==2
test=1;
elseif test_type==3
test=1;
end
case {'Goldstein'}
if test_type==0
% increase (max) or decrease (min) of functional value -
% gradient free test
test=(fx_1 > fx_0);
elseif test_type==1
% sufficient increase( max) or decrease (min) of function -
% also called Armijo condition
test=(fx_1 >= fx_0 + ls_def.max_min.*ls_def.tols.c1*alpha*(gfx_0'*d_0));
elseif test_type==2
test=(fx_1 >= fx_0 + ls_def.max_min.*(1-ls_def.tols.c1)*alpha*(gfx_0'*d_0));
elseif test_type==3
test=(gfx_1'*d_0 < 0);
end
case {'Wolfe-weak','Wolfe'}
if test_type==0
% increase (max) or decrease (min) of functional value -
% gradient free test
test=(fx_1 > fx_0);
elseif test_type==1
% sufficient increase( max) or decrease (min) of function -
% also called Armijo condition
test=(fx_1 >= fx_0 + ls_def.max_min.*ls_def.tols.c1*alpha*(gfx_0'*d_0));
elseif test_type==2
test=(gfx_1'*d_0 >= ls_def.tols.c2*(gfx_0'*d_0));
elseif test_type==3
test=(ls_def.max_min.*gfx_1'*d_0 > 0);
end
case {'Wolfe-strong'}
if test_type==0
% increase (max) or decrease (min) of functional value -
% gradient free test
test=(fx_1 > fx_0);
elseif test_type==1
% sufficient increase( max) or decrease (min) of function -
% also called Armijo condition
test=(fx_1 >= fx_0 + ls_def.max_min.*ls_def.tols.c1*alpha*(gfx_0'*d_0));
elseif test_type==2
test=(abs(gfx_1'*d_0) <= ls_def.tols.c2*abs(gfx_0'*d_0));
elseif test_type==3
test=(ls_def.max_min.*gfx_1'*d_0 > 0);
end
otherwise
error('unknown linesearch conditions')
end
end
|
github
|
tsajed/nmr-pred-master
|
maryan.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/maryan.m
| 332 |
utf_8
|
c88272a34c8e931883d89b087f7d0565
|
% A trap for legacy function calls.
%
% [email protected]
function maryan(varargin)
% Direct the user to the new function
error('This function is deprecated, use rydmr() or rydmr_exp() instead.');
end
% No man is regular in his attendance at the House of
% Commons until he is married.
%
% Benjamin Disraeli
|
github
|
tsajed/nmr-pred-master
|
mfe.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/mfe.m
| 337 |
utf_8
|
d1059327267b2aa5a8882461ca2d288a
|
% A trap for legacy function calls.
%
% [email protected]
function mfe(varargin)
% Direct the user to the new function
error('This function is deprecated, use rydmr() or rydmr_exp() instead.');
end
% The bravest sight in the world is to see a great man
% struggling against adversity.
%
% Lucius Annaeus Seneca
|
github
|
tsajed/nmr-pred-master
|
g03_parse.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/g03_parse.m
| 544 |
utf_8
|
e4f122bac1d86bac4cbc9473dd477696
|
% A trap for legacy function calls.
%
% [email protected]
function g03_parse(varargin)
% Direct the user to the new function
error('This function is deprecated, use gparse() instead.');
end
% If some "pacifist" society renounced the retaliatory use of force, it
% would be left helplessly at the mercy of the first thug who decided
% to be immoral. Such a society would achieve the opposite of its inten-
% tion: instead of abolishing evil, it would encourage and reward it.
%
% Ayn Rand, "The Virtue of Selfishness"
|
github
|
tsajed/nmr-pred-master
|
state_diagnostics.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/state_diagnostics.m
| 308 |
utf_8
|
ff3cdf6e21e55e60cbb2ade506247268
|
% A trap for legacy function calls.
%
% [email protected]
function state_diagnostics(varargin)
% Direct the user to the new function
error('This function is deprecated, use stateinfo() instead.');
end
% A man is never so proud as when striking an attitude of humility.
%
% C.S. Lewis
|
github
|
tsajed/nmr-pred-master
|
g03_to_spinach.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/g03_to_spinach.m
| 315 |
utf_8
|
ba075e44bb72a741911e87a47c19eb2b
|
% A trap for legacy function calls.
%
% [email protected]
function g03_to_spinach(varargin)
% Direct the user to the new function
error('This function is deprecated, use g2spinach() instead.');
end
% If I asked the public what they wanted, they would
% say "a faster horse".
%
% Henry Ford
|
github
|
tsajed/nmr-pred-master
|
mary.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/mary.m
| 285 |
utf_8
|
5e5a909aaefa86cfcd8bfaec635b4034
|
% A trap for legacy function calls.
%
% [email protected]
function mary(varargin)
% Direct the user to the new function
error('This function is deprecated, use rydmr() or rydmr_exp() instead.');
end
% As for our majority... one is enough.
%
% Benjamin Disraeli
|
github
|
tsajed/nmr-pred-master
|
h_superop.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/h_superop.m
| 470 |
utf_8
|
06c55ce1e1ce4899428c98f16a9709c2
|
% A trap for legacy function calls.
%
% [email protected]
function h_superop(varargin)
% Direct the user to the new function
error('This function is deprecated, use hamiltonian() instead.');
end
% History has shown us that it's not religion that's
% the problem, but any system of thought that insists
% that one group of people are inviolably in the right,
% whereas the others are in the wrong and must somehow
% be punished.
%
% Rod Liddle
|
github
|
tsajed/nmr-pred-master
|
offset.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/offset.m
| 283 |
utf_8
|
0aa7a17ad484f8a8946ca0f78da9c3a9
|
% A trap for legacy function calls.
%
% [email protected]
function offset(varargin)
% Direct the user to the new function
error('This function is deprecated, use frqoffset() instead.');
end
% "If nothing is self-evident, nothing can be proved"
%
% C.S. Lewis
|
github
|
tsajed/nmr-pred-master
|
statevec.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/statevec.m
| 399 |
utf_8
|
2dfe9115dc6b1570e6353d9dde35d405
|
% A trap for legacy function calls.
%
% [email protected]
function statevec(varargin)
% Direct the user to the new function
error('This function is deprecated, use state() instead.');
end
% We are back with the self-deluding idiocies of the liberals,
% the people who think something that isn't a circle really is
% a circle, if it only wants to be a circle.
%
% Rod Liddle
|
github
|
tsajed/nmr-pred-master
|
a_superop.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/a_superop.m
| 723 |
utf_8
|
f6f5fbc6e644c8af46730a38afce2626
|
% A trap for legacy function calls.
%
% [email protected]
function a_superop(varargin)
% Direct the user to the new function
error('This function is deprecated, use operator() instead.');
end
% For economic and political thought to make useful progress,
% it needs to be informed by evolutionary biology. This seems
% a very necessary exercise, since any attempt to understand
% morality, politics, economics or business without reference
% to evolutionary biology is ridiculous. As I explain to my
% children, ants are Marxist, dogs are Burkean conservatives
% and cats are libertarians. And, as I explain to our clients,
% a flower is a weed with an advertising budget.
%
% Rory Sutherland
|
github
|
tsajed/nmr-pred-master
|
k_superop.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/k_superop.m
| 371 |
utf_8
|
64e160237f5520e6d554c14ba0d8aa62
|
% A trap for legacy function calls.
%
% [email protected]
function k_superop(varargin)
% Direct the user to the new function
error('This function is deprecated, use kinetics() instead.');
end
% "Why 100? If I were wrong, one would have been enough."
%
% Albert Eistein's response to Nazis lining up
% 100 Aryan scientists to denounce his theories
|
github
|
tsajed/nmr-pred-master
|
simpson2spinach.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/simpson2spinach.m
| 279 |
utf_8
|
38f1875f720e5ecada507cd0fedb0791
|
% A trap for legacy function calls.
%
% [email protected]
function simpson2spinach(varargin)
% Direct the user to the new function
error('This function is deprecated, use s2spinach() instead.');
end
% Science advances one funeral at a time.
%
% Max Planck
|
github
|
tsajed/nmr-pred-master
|
pulse_acquire.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/pulse_acquire.m
| 498 |
utf_8
|
2d7060200adeb4a2cbb3601e9318c288
|
% A trap for legacy function calls.
%
% [email protected]
function pulse_acquire(varargin)
% Direct the user to the new function
error('This function is deprecated, use acquire(), hp_acquire() or sp_acquire() instead.');
end
% I have brought myself, by long meditation, to the conviction
% that a human being with a settled purpose must accomplish it,
% and that nothing can resist a will which would stake even
% existence upon its fulfillment.
%
% Benjamin Disraeli
|
github
|
tsajed/nmr-pred-master
|
c_superop.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/c_superop.m
| 1,273 |
utf_8
|
9b74037eb18634a6e2ab64f677b0e8f7
|
% A trap for legacy function calls.
%
% [email protected]
function c_superop(varargin)
% Direct the user to the new function
error('This function is deprecated, use operator() instead.');
end
% You can always tell when a public figure has said something with the ring
% of truth about it by the abject apology and recantation which arrives a
% day or two later. By and large, the greater the truth, the more abject
% the apology. Often there is a sort of partial non-apology apology first:
% I'm sorry if I upset anyone, but I broadly stand by what I said, even if
% my wording was perhaps a little awkward. That, however, won't do - by now
% the hounds of hell are howling at the back door. [...] People who feel
% themselves to be a victim of this truth are the first to go berserk, then
% the multifarious groups who depend for their living on giving succour to
% one another's victimhood get in on the act - charities, academics, spe-
% cialists and so on. Witless liberals in the media start writing damning
% criticisms of the truth and the person who was stupid enough to tell the
% truth. Sooner or later even that cornucopia of incessant whining, Radio
% 4's You and Yours programme, will have got in on the act.
%
% Rod Liddle
|
github
|
tsajed/nmr-pred-master
|
r_superop.m
|
.m
|
nmr-pred-master/spinach/kernel/legacy/r_superop.m
| 304 |
utf_8
|
4ff96fbb579f527d1f76ac6696066ec7
|
% A trap for legacy function calls.
%
% [email protected]
function r_superop(varargin)
% Direct the user to the new function
error('This function is deprecated, use relaxation() instead.');
end
% In the fields of observation chance favors only the prepared mind.
%
% Louis Pasteur
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.