%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MRiLab auto generated file: DO NOT EDIT!     %
% Generated by MRiLab "DoWriteXML2m" Generator %
% MRiLab Version 1.3                           %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [rfAmp,rfPhase,rfFreq,rfCoil,GzAmp,GyAmp,GxAmp,ADC,Ext,uts,ts,flags]=PSD_FIESTA3D
global VCtl
global VVar
CV1=3e-3;
CV10=0;
CV11=0;
CV12=0;
CV13=0;
CV14=0;
CV2=4e-3;
CV3=2*pi/2;
CV4=2;
CV5=0;
CV6=0;
CV7=0;
CV8=0;
CV9=0;
rfAmpAll=[];
rfPhaseAll=[];
rfFreqAll=[];
rfCoilAll=[];
GzAmpAll=[];
GyAmpAll=[];
GxAmpAll=[];
ADCAll=[];
ExtAll=[];
rfTimeAll=[];
GzTimeAll=[];
GyTimeAll=[];
GxTimeAll=[];
ADCTimeAll=[];
ExtTimeAll=[];
SEtAll=[];
uts=[];
ts=[];
flags=[];
if VCtl.PlotSeq == 1
rfAmp=[];
rfPhase=[];
rfFreq=[];
rfCoil=[];
GzAmp=[];
GyAmp=[];
GxAmp=[];
ADC=[];
Ext=[];
Freq=1;
Notes='regular TR section';
AttributeOpt={'on','off'};
Switch=AttributeOpt{1};
TREnd=Inf;
TRStart=1;
tE=VCtl.TR;
tS=0;
if VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')
% do nothing
else
ts = [ts tS tE];
end
ts = [0 max(ts)-min(ts)];
return;
end
%==============Pulses 1==============
rfAmp=[];
rfPhase=[];
rfFreq=[];
rfCoil=[];
GzAmp=[];
GyAmp=[];
GxAmp=[];
ADC=[];
Ext=[];
rfTime=[];
GzTime=[];
GyTime=[];
GxTime=[];
ADCTime=[];
ExtTime=[];
Freq=1;
Notes='regular TR section';
AttributeOpt={'on','off'};
Switch=AttributeOpt{1};
TREnd=Inf;
TRStart=1;
tE=VCtl.TR;
tS=0;
if isempty(tS) | isempty(tE) | (tS>=tE)
error('SE setting is incorrect for Pulses 1!');
end
if VVar.TRCount<TRStart | VVar.TRCount>TREnd | mod(VVar.TRCount-TRStart,Freq)~=0 | strcmp(Switch,'off')
% do nothing
else
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{1};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=1;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp1,rfPhase1,rfFreq1,rfCoil1,rfTime1]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil1(1)
rfAmp=[rfAmp rfAmp1];
rfPhase=[rfPhase rfPhase1];
rfFreq=[rfFreq rfFreq1];
rfCoil=[rfCoil rfCoil1];
rfTime=[rfTime rfTime1];
end
else
rfAmp=[rfAmp rfAmp1];
rfPhase=[rfPhase rfPhase1];
rfFreq=[rfFreq rfFreq1];
rfCoil=[rfCoil rfCoil1];
rfTime=[rfTime rfTime1];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=2;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp2,rfPhase2,rfFreq2,rfCoil2,rfTime2]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil2(1)
rfAmp=[rfAmp rfAmp2];
rfPhase=[rfPhase rfPhase2];
rfFreq=[rfFreq rfFreq2];
rfCoil=[rfCoil rfCoil2];
rfTime=[rfTime rfTime2];
end
else
rfAmp=[rfAmp rfAmp2];
rfPhase=[rfPhase rfPhase2];
rfFreq=[rfFreq rfFreq2];
rfCoil=[rfCoil rfCoil2];
rfTime=[rfTime rfTime2];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=3;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp3,rfPhase3,rfFreq3,rfCoil3,rfTime3]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil3(1)
rfAmp=[rfAmp rfAmp3];
rfPhase=[rfPhase rfPhase3];
rfFreq=[rfFreq rfFreq3];
rfCoil=[rfCoil rfCoil3];
rfTime=[rfTime rfTime3];
end
else
rfAmp=[rfAmp rfAmp3];
rfPhase=[rfPhase rfPhase3];
rfFreq=[rfFreq rfFreq3];
rfCoil=[rfCoil rfCoil3];
rfTime=[rfTime rfTime3];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=4;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp4,rfPhase4,rfFreq4,rfCoil4,rfTime4]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil4(1)
rfAmp=[rfAmp rfAmp4];
rfPhase=[rfPhase rfPhase4];
rfFreq=[rfFreq rfFreq4];
rfCoil=[rfCoil rfCoil4];
rfTime=[rfTime rfTime4];
end
else
rfAmp=[rfAmp rfAmp4];
rfPhase=[rfPhase rfPhase4];
rfFreq=[rfFreq rfFreq4];
rfCoil=[rfCoil rfCoil4];
rfTime=[rfTime rfTime4];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=5;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp5,rfPhase5,rfFreq5,rfCoil5,rfTime5]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil5(1)
rfAmp=[rfAmp rfAmp5];
rfPhase=[rfPhase rfPhase5];
rfFreq=[rfFreq rfFreq5];
rfCoil=[rfCoil rfCoil5];
rfTime=[rfTime rfTime5];
end
else
rfAmp=[rfAmp rfAmp5];
rfPhase=[rfPhase rfPhase5];
rfFreq=[rfFreq rfFreq5];
rfCoil=[rfCoil rfCoil5];
rfTime=[rfTime rfTime5];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=6;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp6,rfPhase6,rfFreq6,rfCoil6,rfTime6]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil6(1)
rfAmp=[rfAmp rfAmp6];
rfPhase=[rfPhase rfPhase6];
rfFreq=[rfFreq rfFreq6];
rfCoil=[rfCoil rfCoil6];
rfTime=[rfTime rfTime6];
end
else
rfAmp=[rfAmp rfAmp6];
rfPhase=[rfPhase rfPhase6];
rfFreq=[rfFreq rfFreq6];
rfCoil=[rfCoil rfCoil6];
rfTime=[rfTime rfTime6];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=7;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp7,rfPhase7,rfFreq7,rfCoil7,rfTime7]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil7(1)
rfAmp=[rfAmp rfAmp7];
rfPhase=[rfPhase rfPhase7];
rfFreq=[rfFreq rfFreq7];
rfCoil=[rfCoil rfCoil7];
rfTime=[rfTime rfTime7];
end
else
rfAmp=[rfAmp rfAmp7];
rfPhase=[rfPhase rfPhase7];
rfFreq=[rfFreq rfFreq7];
rfCoil=[rfCoil rfCoil7];
rfTime=[rfTime rfTime7];
end
end
p=[];
%--------------------
AttributeOpt={'on','off'};
p.AnchorTE=AttributeOpt{2};
AttributeOpt={'Non','Hamming','Hanning'};
p.Apod=AttributeOpt{3};
p.CoilID=8;
p.DupSpacing=0;
p.Duplicates=1;
p.FA=VCtl.FlipAng;
p.Notes='alpha pulse';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.TBP=4;
p.dt=20e-6;
p.rfFreq=0;
p.rfPhase=rem(VVar.TRCount-1,CV4)*CV3;
p.tEnd=1.5e-3;
p.tStart=1.2e-3;
if strcmp(p.Switch,'on')
if strcmp(p.AnchorTE,'on')
switch VCtl.TEAnchor
case 'Start'
VCtl.TEAnchorTime=p.tStart;
case 'Middle'
VCtl.TEAnchorTime=(p.tStart+p.tEnd)/2;
case 'End'
VCtl.TEAnchorTime=p.tEnd;
end
end
[rfAmp8,rfPhase8,rfFreq8,rfCoil8,rfTime8]=rfSinc(p);
if strcmp(VCtl.MultiTransmit,'off')
if VCtl.MasterTxCoil==rfCoil8(1)
rfAmp=[rfAmp rfAmp8];
rfPhase=[rfPhase rfPhase8];
rfFreq=[rfFreq rfFreq8];
rfCoil=[rfCoil rfCoil8];
rfTime=[rfTime rfTime8];
end
else
rfAmp=[rfAmp rfAmp8];
rfPhase=[rfPhase rfPhase8];
rfFreq=[rfFreq rfFreq8];
rfCoil=[rfCoil rfCoil8];
rfTime=[rfTime rfTime8];
end
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Gz1Sign=1;
p.Gz2Sign=-1;
p.Notes='cartesian phase';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.t1End=VCtl.TE-CV1;
p.t1Start=VCtl.TE-CV2;
p.t2End=VCtl.TE+CV2;
p.t2Start=VCtl.TE+CV1;
p.tRamp=100e-6;
if strcmp(p.Switch,'on')
[GzAmp1,GzTime1]=GzCartesian(p);
GzAmp=[GzAmp GzAmp1];
GzTime=[GzTime GzTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Gy1Sign=1;
p.Gy2Sign=-1;
p.Notes='cartesian phase';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.t1End=VCtl.TE-CV1;
p.t1Start=VCtl.TE-CV2;
p.t2End=VCtl.TE+CV2;
p.t2Start=VCtl.TE+CV1;
p.tRamp=100e-6;
if strcmp(p.Switch,'on')
[GyAmp1,GyTime1]=GyCartesian(p);
GyAmp=[GyAmp GyAmp1];
GyTime=[GyTime GyTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Gx1Sign=-1;
p.Gx2Sign=1;
p.Gx3Sign=-1;
p.Notes='cartesian frequency';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.t1Start=VCtl.TE-CV2;
p.t2Middle=VCtl.TE;
p.t3Start=VCtl.TE+CV1;
p.tRamp=100e-6;
if strcmp(p.Switch,'on')
[GxAmp1,GxTime1]=GxCartesian(p);
GxAmp=[GxAmp GxAmp1];
GxTime=[GxTime GxTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Notes='cartesian readout';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tMiddle=VCtl.TE;
if strcmp(p.Switch,'on')
[ADC1,ADCTime1]=ADCCartesian(p);
ADC=[ADC ADC1];
ADCTime=[ADCTime ADCTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Ext=5;
p.Notes='calculate remaining scan time';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tStart=0;
if strcmp(p.Switch,'on')
[Ext1,ExtTime1]=ExtBit(p);
Ext=[Ext Ext1];
ExtTime=[ExtTime ExtTime1];
end
p=[];
%--------------------
p.DupSpacing=0;
p.Duplicates=1;
p.Ext=7;
p.Notes='demodulate signal phase referring to rf phase at ADC';
AttributeOpt={'on','off'};
p.Switch=AttributeOpt{1};
p.tStart=1.35e-3;
if strcmp(p.Switch,'on')
[Ext2,ExtTime2]=ExtBit(p);
Ext=[Ext Ext2];
ExtTime=[ExtTime ExtTime2];
end
p=[];
%--------------------
SEt=[tS tE];
rfAmp(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
rfPhase(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
rfFreq(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
rfCoil(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
GzAmp(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];
GyAmp(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];
GxAmp(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];
ADC(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];
Ext(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];
rfTime(rfTime<0 | rfTime>SEt(2)-SEt(1)) = [];
GzTime(GzTime<0 | GzTime>SEt(2)-SEt(1)) = [];
GyTime(GyTime<0 | GyTime>SEt(2)-SEt(1)) = [];
GxTime(GxTime<0 | GxTime>SEt(2)-SEt(1)) = [];
ADCTime(ADCTime<0 | ADCTime>SEt(2)-SEt(1)) = [];
ExtTime(ExtTime<0 | ExtTime>SEt(2)-SEt(1)) = [];
rfAmp(abs(rfAmp)<eps) = 0;
rfTime = rfTime + SEt(1);
GzTime = GzTime + SEt(1);
GyTime = GyTime + SEt(1);
GxTime = GxTime + SEt(1);
ADCTime = ADCTime + SEt(1);
ExtTime = ExtTime + SEt(1);
rfAmpAll=[rfAmpAll rfAmp];
rfPhaseAll=[rfPhaseAll rfPhase];
rfFreqAll=[rfFreqAll rfFreq];
rfCoilAll=[rfCoilAll rfCoil];
GzAmpAll=[GzAmpAll GzAmp];
GyAmpAll=[GyAmpAll GyAmp];
GxAmpAll=[GxAmpAll GxAmp];
ADCAll=[ADCAll ADC];
ExtAll=[ExtAll Ext];
rfTimeAll=[rfTimeAll rfTime];
GzTimeAll=[GzTimeAll GzTime];
GyTimeAll=[GyTimeAll GyTime];
GxTimeAll=[GxTimeAll GxTime];
ADCTimeAll=[ADCTimeAll ADCTime];
ExtTimeAll=[ExtTimeAll ExtTime];
SEtAll=[SEtAll SEt];
end
%====================================
if isempty(rfTimeAll)
error('rf sequence line can not be empty! Master Tx coil element must be used.');
end
if isempty(GzTimeAll)
error('GzSS sequence line can not be empty!');
end
if isempty(GyTimeAll)
error('GyPE sequence line can not be empty!');
end
if isempty(GxTimeAll)
error('GxR sequence line can not be empty!');
end
if isempty(ADCTimeAll)
error('ADC sequence line can not be empty!');
end
if isempty(ExtTimeAll)
error('Ext sequence line can not be empty!');
end
SEflag=repmat([0 0 0 0 0 0]',[1 2]);
rfflag=repmat([1 0 0 0 0 0]',[1 max(size(rfTimeAll))]);
Gzflag=repmat([0 1 0 0 0 0]',[1 max(size(GzTimeAll))]);
Gyflag=repmat([0 0 1 0 0 0]',[1 max(size(GyTimeAll))]);
Gxflag=repmat([0 0 0 1 0 0]',[1 max(size(GxTimeAll))]);
ADCflag=repmat([0 0 0 0 1 0]',[1 max(size(ADCTimeAll))]);
Extflag=repmat([0 0 0 0 0 1]',[1 max(size(ExtTimeAll))]);
ts=[[min(SEtAll) max(SEtAll)] rfTimeAll GzTimeAll GyTimeAll GxTimeAll ADCTimeAll ExtTimeAll]-min(SEtAll);
flags=[SEflag rfflag Gzflag Gyflag Gxflag ADCflag Extflag];
[ts,ind]=sort(ts);
uts=unique(ts);
flags=flags(:,ind);
[rfTime,ind]=sort(rfTimeAll-min(SEtAll));
rfAmp=rfAmpAll(:,ind);
rfPhase=rfPhaseAll(:,ind);
rfFreq=rfFreqAll(:,ind);
rfCoil=rfCoilAll(:,ind);
[GzTime,ind]=sort(GzTimeAll-min(SEtAll));
GzAmp=GzAmpAll(:,ind);
[GyTime,ind]=sort(GyTimeAll-min(SEtAll));
GyAmp=GyAmpAll(:,ind);
[GxTime,ind]=sort(GxTimeAll-min(SEtAll));
GxAmp=GxAmpAll(:,ind);
[ADCTime,ind]=sort(ADCTimeAll-min(SEtAll));
ADC=ADCAll(:,ind);
[ExtTime,ind]=sort(ExtTimeAll-min(SEtAll));
Ext=ExtAll(:,ind);
rfAmp(1) = 0;
rfPhase(1) = 0;
rfFreq(1) = 0;
GzAmp(1) = 0;
GyAmp(1) = 0;
GxAmp(1) = 0;
ADC(1) = 0;
Ext(1) = 0;
rfAmp(end) = 0;
rfPhase(end) = 0;
rfFreq(end) = 0;
GzAmp(end) = 0;
GyAmp(end) = 0;
GxAmp(end) = 0;
ADC(end) = 0;
Ext(end) = 0;
end


function [modelLOD] = setQualitativeConstraints(model,cond_uptake,cond_uptake_LODs, cond_secretion,cond_secretion_LODs,cellConc,t,cellWeight,ambiguous_metabolites,basisMedium)
% This function sets qualitative constraints (by enforcing minimal uptake or secretion based on individual detection limits), e.g., based on the uptake and secretion
% profile of metabolites measured through mass-spectrometry. Uptake is only possible if the lower bound has been set to a value >0 using `setMediumConstraints`
% The minimal allowable uptake and secretion flux is defined by enforcing uptake at or above the limit of detection (mass-spectrometry). If these values are not available, a very small value, e.g., 1.0E-06 can be used. Note that this
% value has to be below the concentrations defined in the medium. Otherwise the model will be infeasible. Alternatively to the LODs a small value can
% be used (e.g., 0.00001). Note that the value has to be above the threshold later called zero.
%
% USAGE:
%
%    [modelLOD] = setQualitativeConstraints(model, cond_uptake, cond_uptake_LODs, cond_secretion, cond_secretion_LODs, cellConc, t, cellWeight, ambiguous_metabolites, basisMedium)
%
% INPUTS:
%    model:                   Metabolic model (Recon), with set constraints (output of `setMediumConstraints`)
%    cond_uptake:             Vector of exchanges of metabolites consumed by the cells in the experiment
%    cond_uptake_LODs:        Vector of detection limits (LOD in Mm) for the compounds and in the experiment
%    cond_secretion:          Vector of metabolite exchanges consumed by the cells in the experiment
%    cond_secretion_LODs:     Vector of detection limits (LOD in Mm) for the compounds and in the experiment
%    cellConc:                Cell concentration (cells per 1 ml)
%    t:                       Time in hours
%    cellWeight:              gDW per cell
%    ambiguous_metabolites:   Since all exchanges, except the ones specified in `uptake` and `secretion` are closed in `modelLOD`, this input
%                             variable allows to specify metabolite exchanges that should remain open.
%                             Thus, if these exchanges are open in the starting model they can be uptaken
%                             or secreted by the `modelLOD`, e.g., `ambiguous_metabolites`
%                             This can for example be the case if it is suspected that an uptake or secretion might have taken place in concentrations below the
%                             detection limit.
%    basisMedium:             Vector defining the metabolite exchanges of the basic medium, i.e., `ions`, `mediumCompounds`
%
% OUTPUT:
%    modelLOD:                Model that is constrained qualitatively to the condition-specific uptake and secretion profile
%
% .. Author: - Maike K. Aurich 27/05/15

A = strfind(model.rxns, 'EX_');
%Find all exchange reactions
for i = 1:length(A);
    B= A{i};
       if  isempty(B);
       A{i}=[0];
       end
end
cc = cell2mat(A);
idx_EXreactions= find(cc);
ex_Rxns = model.rxns(idx_EXreactions); %make exchange reaction list

%% Calculate flux rates (LODs)
for i = 1 : length(cond_uptake_LODs)
    [ub_up_flux(i,1)] = conc2Rate(cond_uptake_LODs(i),cellConc, t, cellWeight);
end

for i = 1 : length(cond_secretion_LODs) % conversion from conc.(minimal detection value total, in Mm) to flux value per cell mmol/gDW/hr
        [lb_secr_flux(i,1)] = conc2Rate(cond_secretion_LODs(i),cellConc, t, cellWeight);
end

%% Define which exchanges to close and close them
conditional_exchanges = [cond_uptake;cond_secretion;basisMedium;ambiguous_metabolites];

no_exchange = ex_Rxns(find(~ismember(ex_Rxns,conditional_exchanges)));%find reactions not associated with detected exhange metabolites, basic medium metabolites, low quantity metabolites

model = changeRxnBounds(model,no_exchange,0,'b'); %block all other Exchange reactions

%% Apply LOD constraints to enforce uptake and secretion

for k=1:length(cond_uptake)
    ub=ub_up_flux(k);
    rxns = cond_uptake(k);
model = changeRxnBounds(model,rxns,-ub,'u'); %enforce uptake of metabolites taken up by cells in the experiment
end
clear k
for k=1:length(cond_secretion)
    lb=lb_secr_flux(k);
model = changeRxnBounds(model,cond_secretion(k),lb,'l');% enforce secretion of metabolites secreted by the cells in the experiment
end

modelLOD = model;
end


% Script: view_coulomb.m
% Display Coulomb stress change map together with seismicity
% Allow to analyze seismicity rate changes using the Ztools
%
% J. Woessner, jochen.woessner@sed.ethz.ch, 05.07.2004

report_this_filefun(mfilename('fullpath'));

% Default value for map view
bMap =1;

% Load CFS file
[sFilename, sPathname] = uigetfile('*.mat', 'Pick CFS change MAT-file');
sHelp = [sPathname sFilename];
sFile = [sFilename(1:length(sFilename)-4)];
load(sHelp)
rCfs = eval(sFile);

% Load rate change file
[sFilename1, sPathname1] = uigetfile('*.mat', 'Pick Rate Change MAT-file');
sHelp1 = [sPathname1 sFilename1];
sFile1 = [sFilename1(1:length(sFilename1)-4)];
load(sHelp1)

% Set up the Seismicity Map window Enviroment
% Find out of figure already exists
[existFlag,figNumber]=figure_exists('Coulomb-map',1);
newcfsmapWindowFlag=~existFlag;

if newcfsmapWindowFlag
    oldfig_button = 0;
end

if oldfig_button == 0
    cfsmap = figure_w_normalized_uicontrolunits( ...
        'Name','Coulomb-map',...
        'NumberTitle','off', ...
        'MenuBar','none', ...
        'NextPlot','add', ...
        'backingstore','on',...
        'Visible','off', ...
        'Position',[ (fipo(3:4) - [600 400]) ZmapGlobal.Data.map_len]);
    % make menu bar
    matdraw

    % Display
    add_menu_divider();
    add_symbol_menu('eq_plot');

    % Menu: Ztools
    op1 = uimenu('Label','Ztools');
    uimenu(op1,'Label','Rate change, p-,c-,k-value map in aftershock sequence (MLE) ',...
        'Callback','sel= ''in'';,rcvalgrid_a2');
    uimenu(op1,'Label','Load existing  Rate change, p-,c-,k-value map (MLE)',...
        'Callback','sel= ''lo'';rcvalgrid_a2');

    % Menu: ZAnalyze
    op2 = uimenu('Label',' ZAnalyze ');
    uimenu(op2,'Label','Refresh ', 'Callback','view_coulombmap')
    uimenu(op2,'Label','Select EQ in Circle - Constant R',...
         'Callback','h1 = gca;met = ''ra''; ho=false;plot_circbootfit_a2;watchoff(cfsmap)')
    uimenu(op2,'Label','Select EQ with const. number',...
         'Callback','h1 = gca;ho2=true;ho=true;plot_constnrbootfit_a2;watchoff(cfsmap)')

    % Set default colormap
    colormap(jet)
end  % This is the end of the figure setup.

% Load the data from the Coulomb data file
% Define colormap
% mColormap = gui_Colormap_Rastafari(256);
colormap(jet);

% Get the gridding
vY = linspace(rCfs.fMinLat,rCfs.fMaxLat,rCfs.nNy);
vY = fliplr(vY);
vX = linspace(rCfs.fMinLon,rCfs.fMaxLon,rCfs.nNx);

% Plot Coulomb stress map with seismicity
figure_w_normalized_uicontrolunits(cfsmap)
% Fix color scale for imagesc
vClims = [-2 2];
hCoulomb = imagesc(vX,vY,rCfs.mCfs,vClims);
shading interp;
set(gca,'Ydir','normal');
% Colorbar
hColor = colorbar;
chl = get(hColor,'Ylabel');
set(chl,'String','\Delta CFS [bar]','FontS',10,'Rot',270);

% Labeling
ylabel('Latitude [deg]');
xlabel('Longitude [deg]');

% Add rate change map
hold on;
normlap2=ones(length(ll),1)*nan;
% Relative rate change
normlap2(ll)= mRcGrid(:,15);
mRelchange = reshape(normlap2,length(yvect),length(xvect));
hRate = pcolor(xvect,yvect,mRelchange)
set(hRate, 'AlphaData', 0.6, 'AlphaDataMapping', 'none');
shading(gca,'flat')
% Plot seismicity
ploeq=plot(a.Longitude,a.Latitude,'Markersize',3,'Marker','o','Linestyle','none','Color',[0 0 0],'Tag','eq_plot');
hold off;


function [varargout] = rotate(axis, angle, varargin)
%align set alignment of the objects in the block
%
%   [...] = rotate(axis, angle, obj <, obj> ...);
%
%   Rotates the corresponding gradinet object(s) about the given axis by
%   the specified amount. Gradients parallel to the rotation axis and
%   non-gradient objects are not affected.
%   Possible rotation axes are 'x', 'y' or 'z'.
%
%   Returns either a cell-array of objects if one return parameter is
%   provided or an explicit list of objects if multiple parameters are
%   given. Can be used directly as a parameter of seq.addBlock().
%
%   See also  Sequence.addBlock
%
%   Maxim Zaitsev <maxim.zaitsev@uniklinik-freiburg.de>

axes={'x', 'y', 'z'};

% cycle through the objects and rotate gradients non-parallel to the
% given rotation axis. Rotated gradients assigned to the same axis are then
% added together.

% first create indexes of the objects to be bypassed or rotated
irotate1=[];
irotate2=[];
ibypass=[];
axes2rot=axes(~strcmp(axes,axis));
if length(axes2rot)~=2
    error('incorrect axis specification');
end

if 1==length(varargin) && iscell(varargin{1})
    va=varargin{1}; % we need this to allow for nested mr.rotate() calls
else
    va=varargin;
end

for i=1:length(va)
    event = va{i};
    if isempty(event)
        continue;
    end
    if  (~strcmp(event.type,'grad') && ...
            ~strcmp(event.type,'trap')) || ...
            strcmp(event.channel, axis)%['g' axis]
        ibypass=[ibypass i];
    else
        if strcmp(event.channel, axes2rot(1)) %['g' axes2rot(1)]
            irotate1=[irotate1 i];
        else
            if (strcmp(event.channel, axes2rot(2))) %['g' axes2rot(2)]
                irotate2=[irotate2 i];
            else
                ibypass=[ibypass i]; % should never happen
            end
        end
    end
end

% now every gradient to be rotated generates two new gradients, one on the
% original axis and one on the other from the axes2rot list

rotated1=cell(1,length(irotate1)+length(irotate2));
rotated2=cell(1,length(irotate1)+length(irotate2));
max_mag=0; % measure of the relevant amplitude
for i=1:length(irotate1)
    g=va{irotate1(i)};
    max_mag=max(max_mag, getGradAbsMag(g));
    rotated1{i}=mr.scaleGrad(g,cos(angle));
    g=mr.scaleGrad(g,sin(angle));
    g.channel=axes2rot{2};
    rotated2{i}=g;
end
o=length(irotate1);
for i=1:length(irotate2)
    g=va{irotate2(i)};
    max_mag=max(max_mag, getGradAbsMag(g));
    rotated2{i+o}=mr.scaleGrad(g,cos(angle));
    g=mr.scaleGrad(g,-sin(angle));
    g.channel=axes2rot{1};
    rotated1{i+o}=g;
end

% eliminate zero-amplitude gradients
thresh=1e-6*max_mag;
for i=length(rotated1):-1:1
    if getGradAbsMag(rotated1{i})<thresh
        rotated1(i)=[];
    end
end
for i=length(rotated2):-1:1
    if getGradAbsMag(rotated2{i})<thresh
        rotated2(i)=[];
    end
end

g=cell(1,2);
% now we add gradients on the corresponding axis together
if (length(rotated1)>1)
    g{1}=mr.addGradients(rotated1);
else
    if (~isempty(rotated1))
        g{1}=rotated1{1};
    end
end

if (length(rotated2)>1)
    g{2}=mr.addGradients(rotated2);
else
    if (~isempty(rotated2))
        g{2}=rotated2{1};
    end
end

% eliminate zero-amplitude gradients
for i=length(g):-1:1
    if isempty(g{i}) || getGradAbsMag(g{i})<thresh
        g(i)=[];
    end
end

% export
bypass=va(ibypass);
out={bypass{:},g{:}};

nout = nargout;
varargout = cell(1,nout);
if nout==1
    varargout{1}=out;
else
    nr=min(nout,length(out));
    if nout<length(out)
        warning('insufficient number of return parameters, some rotated gradient components might go lost');
    end
    for k=1:nr
        varargout{k}=out{k};
    end
end

end

function [out] = getGradAbsMag(grad)
    if strcmp(grad.type,'trap')
        out=abs(grad.amplitude);
    else
        out=max(abs(grad.waveform));
    end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   PARAMETERS
%
%   Authors: Arturo Gil
%   email:  date:   27/11/2023
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
function robot = parameters()

robot.name= 'SERIAL2_EXAMPLE';

robot.DH.theta= '[q(1) q(2)-pi/2 q(3) q(4) q(5) q(6)+pi]';
robot.DH.d='[0.630 0 0 1.8 0 0.3]';
robot.DH.a='[0.50 2.34 0.5 0 0 0]';
robot.DH.alpha= '[pi/2 0 pi/2 0 pi/2 0]';

robot.J=[];

robot.inversekinematic_fn = 'inversekinematic(robot, T)';

%number of degrees of freedom
robot.DOF = 6;

%rotational: 0, translational: 1
robot.kind=['R' 'R' 'R' 'R' 'R' 'R'];

%minimum and maximum rotation angle in rad
robot.maxangle =[deg2rad(-170) deg2rad(170); %Axis 1, minimum, maximum
                deg2rad(-65) deg2rad(85); %Axis 2, minimum, maximum
                deg2rad(-180) deg2rad(70); %Axis 3
                deg2rad(-300) deg2rad(300); %Axis 4:
                deg2rad(-120) deg2rad(120); %Axis 5
                deg2rad(-360) deg2rad(360)]; %Axis 6:

%maximum absolute speed of each joint rad/s or m/s
robot.velmax = [deg2rad(100); %Axis 1, rad/s
                deg2rad(90); %Axis 2, rad/s
                deg2rad(90); %Axis 3, rad/s
                deg2rad(170); %Axis 4, rad/s
                deg2rad(120); %Axis 5, rad/s
                deg2rad(190)];%Axis 6, rad/s

robot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time
            % end effectors maximum velocity
robot.linear_velmax = 1.0; %m/s, unavailable from datasheet

%base reference system
robot.T0 = eye(4);

%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION
%position, velocity and acceleration
robot=init_sim_variables(robot);
robot.path = pwd;

% GRAPHICS
robot.graphical.has_graphics=1;
robot.graphical.color = [255 102 51]./255;
%for transparency
robot.graphical.draw_transparent=0;
%draw DH systems
robot.graphical.draw_axes=1;
%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for
%bigger robots
robot.graphical.axes_scale=1;
%adjust for a default view of the robot
robot.axis=[-2 2 -2 2 0 2.5];
%read graphics files
robot = read_graphics(robot);

%DYNAMICS
robot.has_dynamics=0;


function [model, removedMets, removedRxns] = removeDeadEnds(model)
% Removes all dead end metabolites and reactions from the
% model
%
% USAGE:
%
%    [model, removedMets, removedRxns] = removeDeadEnds(model)
%
% INPUT:
%     model:          COBRA model structure
%
% OUTPUTS:
%    model:          COBRA model structure w/o dead end metabolites and
%                    reactions
%    removedMets:    List of removed metabolites
%    removedRxns:    List of removed reactions
%
% .. Author: - Markus Herrgard 8/29/06

removedMets = {};
removedRxns = {};

while (1)

    deadEnd = detectDeadEnds(model);

    if (length(deadEnd) == 0)
        break;
    end

    removedMets = union(removedMets,model.mets(deadEnd));
    if (length(deadEnd) > 1)
        deadRxns = model.rxns(find(sum(model.S(deadEnd,:) ~= 0) > 0));
    else
        deadRxns = model.rxns(find(model.S(deadEnd,:) ~= 0));
    end

    model = removeRxns(model,deadRxns);

    removedRxns = union(removedRxns,deadRxns);

end


function [ TP, FP, FN ] = measuresByConfidence( objects, min_confidence, all_TPs, all_FPs, TP_rep, FP )
%MEASURESBYCONFIDENCE Summary of this function goes here
%   Detailed explanation goes here

    countGT = 0;
    countFound = 0;

    % TP_rep: number of TP windows with repeated GT instances
    % TP: number of TP objects, without repeating GT instances

    nImgs = length(objects);
    for i = 1:nImgs

        %% Get TP valid samples and remove non-valid ones (by confidence)
        if(TP_rep > 0)
            this_pos = find(all_TPs(:,1) == i);
            more_conf = find(all_TPs(this_pos,4) >= min_confidence);

            nMoreConf = length(more_conf);
            nLess = length(this_pos) - nMoreConf;
            TP_rep = TP_rep - nLess;

            this_found = all_TPs(this_pos(more_conf),3); % label ids of detections with min_confidence
        else
            this_found = [];
        end

        %% Find unique TPs labels
        un_this_found = unique(this_found);
        nUnique = length(un_this_found);
        countFound = countFound + nUnique;
        lenGT = 0;

        for j = 1:length(objects(i).ground_truth)
            if(~isempty(objects(i).ground_truth(j).name))
                lenGT = lenGT+1;
            end
        end
        countGT = countGT + lenGT;
    end

    %% Remove non-valid FPs (by confidence)
    if(FP > 0)
        nLess = sum(all_FPs(:,4) < min_confidence);
        FP = FP - nLess;
    end

%     frac_NoObj = 1-countObjs/countTot;
%     detection_rate = countFound/countGT;

    FN = countGT - countFound;
    TP = countFound;

    % Add all repeated TPs to FPs
    FP =  FP + (TP_rep-TP);

end


function [E1,IESM_NewSpin,E2,DelE] = EnergyChange_3D_QPOTTS(IESM,Q);

E1 = Energy1_3D_QPOTTS(IESM);
IESM_NewSpin = IndexElementStateMatrix_3D_QPOTTS_NewSpin(IESM,Q);
E2 = Energy2_3D_QPOTTS(IESM_NewSpin);
DelE = E1-E2;

github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34985-monte-carlo-simulation-of-three-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 3D square-lattice - microstructure/EnergyChange_3D_QPOTTS.m


function test_failed = test_libltfat_fftshift(varargin)
test_failed = 0;

fprintf(' ===============  %s ================ \n',upper(mfilename));

definput.flags.complexity={'double','single'};
[flags]=ltfatarghelper({},definput,varargin);
dataPtr = [flags.complexity, 'Ptr'];

Larr = [1,9,11,110];

for do_complex = 0:1
    complexstring = '';
    if do_complex, complexstring = 'complex'; end
    funname = makelibraryname('fftshift',flags.complexity,do_complex);

    for L = Larr

            if do_complex
                z = cast((1:L)'+1i*(L:-1:1)',flags.complexity);
                zi = complex2interleaved(z);
                zout = randn(size(zi),flags.complexity);

                ziPtr = libpointer(dataPtr,zi);
                zoutPtr = libpointer(dataPtr,zout);
            else
                z = cast((1:L)',flags.complexity);
                zi = z;
                zout = randn(size(zi),flags.complexity);

                ziPtr = libpointer(dataPtr,zi);
                zoutPtr = libpointer(dataPtr,zout);
            end

            trueres = fftshift(z);

            status = calllib('libltfat',funname,ziPtr,L,zoutPtr);

            if do_complex
                res = norm(trueres - interleaved2complex(zoutPtr.Value));
            else
                res = norm(trueres - zoutPtr.Value);
            end

            [test_failed,fail]=ltfatdiditfail(res+status,test_failed,0);
            fprintf(['FFTSHIFT OP L:%3i, %s %s %s %s\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);

            status = calllib('libltfat',funname,ziPtr,L,ziPtr);

            if do_complex
                res = norm(trueres - interleaved2complex(ziPtr.Value));
            else
                res = norm(trueres - ziPtr.Value);
            end

            [test_failed,fail]=ltfatdiditfail(res+status,test_failed,0);
            fprintf(['FFTSHIFT IP L:%3i, %s %s %s %s\n'],L,flags.complexity,complexstring,ltfatstatusstring(status),fail);
    end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Spherical Harmonic Modeling and Analysis Toolkit (SPHARM-MAT) is a 3D
% shape modeling and analysis toolkit.
% It is a software package developed at Shenlab in Center for Neuroimaging,
% Indiana University (SpharmMat@gmail.com, http://www.iupui.edu/~shenlab/)
% It is available to the scientific community as copyright freeware
% under the terms of the GNU General Public Licence.
%
% Copyright 2009, 2010, ShenLab, Center for Neuroimaging, Indiana University
%
% This file is part of SPHARM-MAT.
%
% SPHARM-MAT is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SPHARM-MAT is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SPHARM-MAT. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

disp('Ex0501: Perform FOE Alignment')

SpharmMatDir = '../';
CodeDir = [SpharmMatDir 'code'];
addpath(CodeDir);

DataFolder = 'data';

%% (1) Input data directory
InDataDir = [SpharmMatDir DataFolder '/Ex0501/hip04_des'];

%% (2) List input file names
inFiles = dir([InDataDir '/*_des.mat']); inNames={};
for i=1:length(inFiles)
    inNames{end+1} = [InDataDir '/' inFiles(i).name];
end

%% (3) Display input objects (optional)
    %Available values for Space- 'object';'param';'both'
dispConfs.Space = 'object';
    % Available values for Mesh- 'orig';'quad32';'quad64';'quad128';'quad256';'quad512';'icosa1';'icosa2'; ...
    %    'icosa3';'icosa4';'icosa5';'icosa6'
dispConfs.Mesh = 'orig';
    % Available values for Shape- 'solid';'mesh';'both'
dispConfs.Shade = 'both';
    % Available values for Overlay- 'none';'adc_paramap'
dispConfs.Overlay = 'none';
    % Available values for Export- 'screen';'png';'both'
dispConfs.Export = 'png';
dispConfs.Degree = [];
dispConfs.Template = '';

SpharmMatUtilDisplayObjs(dispConfs, inNames, CodeDir);

%% (4) Perform FOE Alignment
    % Available values for CPoint- 'x';'y';'z'
confs.CPoint = 'y';
    % Available values for NPole- 'x';'y';'z'
confs.NPole = 'z';
confs.MaxSPHARMDegree = 12;
confs.OutDirectory = [SpharmMatDir DataFolder '/Ex0501/hip05_reg'];

if ~exist(confs.OutDirectory,'dir')
    mkdir(confs.OutDirectory);
end

outNames = SpharmMatAlignment(confs, inNames, 'AligFOE');

%% (5) Display output objects (optional)
    %Available values for Space- 'object';'param';'both'
dispConfs.Space = 'object';
    % Available values for Mesh- 'orig';'quad32';'quad64';'quad128';'quad256';'quad512';'icosa1';'icosa2'; ...
    %    'icosa3';'icosa4';'icosa5';'icosa6'
dispConfs.Mesh = 'quad64';
    % Available values for Shape- 'solid';'mesh';'both'
dispConfs.Shade = 'both';
    % Available values for Overlay- 'none';'adc_paramap'
dispConfs.Overlay = 'adc_paramap';
    % Available values for Export- 'screen';'png';'both'
dispConfs.Export = 'png';
dispConfs.Degree = 1;
dispConfs.Template = '';

SpharmMatUtilDisplayObjs(dispConfs, outNames, CodeDir);

dispConfs.Degree = 12;
SpharmMatUtilDisplayObjs(dispConfs, outNames, CodeDir);

rmpath(CodeDir);

clear;


function [fiberspool, fiberDiameter] =dtiCullFibers(fg, dt6filename, Tt, distanceCrit, fiberLenCrit, averLACrit)
% ER's idea of how to 'cull' fibers - Use with caution ...
%
% [fiberspool, fiberDiameter] = dtiCullFibers(fg, dt6filename, Tt, distanceCrit, fiberLenCrit, averLACrit)
%
% fg: Fiber group
% dt6filename:
% Tt:
% distanceCrit:  Separation between fibers
% fiberLenCrit: (mm)
% averLACrit:  (mm)
%
% Fibers are not removed (culled) from a fiber group if
%
% (1) Length of a trajectory > 10.0mm
% (2) Average linear anisotropy along fiber trajectory > 0.1
% (3) Fibers meeting these criteria have a between fiber distance >1 mm (on average).
%     Default threshold value is 1 mm;
%
% Although arguable, it is natural to set Tt to resampled data voxel size
% (as Zhang 2003 did), and . Zhang et al. (2003) IEEE Transactions on
% Vizualization and Computer Graphics 9(4)
%
%11/2008: ER wrote it
%
% (c) Stanford VISTA Team

totalNfibers=size(fg.fibers, 1);

if (~exist('fiberLenCrit','var') || isempty(fiberLenCrit))
    fiberLenCrit=10; %in mm
end

if(~exist('averLACrit','var') || isempty(averLACrit))
    averLACrit=0.1;%arbitrary
end

if(~exist('distanceCrit','var') || isempty(distanceCrit))
    distanceCrit = 1;% %distanceCrit=1.7*2;%for voxels of 2; 1.7*voxel Or do I mean voxels as in opts.stepSizeMm?
end

% What is Tt?
if(~exist('Tt','var') || isempty(Tt))
    Tt=1; %Tt=2;
end

%Deal with files with no subgroup field
if  ~isfield(fg, 'subgroup') || isempty(fg.subgroup)
    fg.subgroup=repmat(1, [1 size(fg.fibers, 1)]);
end

% (1) Fiber length: infer from number of points; length(fg.fibers{ii}). On
%average the distance between the neighbouring points is....opts.stepSizeMm= 1;

%Create a FG which consists of only fibers that are longer than fiberLenCrit
fg1=fg;
fiberLen = cellfun('length', fg.fibers);
fg1.fibers=fg.fibers(fiberLen>fiberLenCrit);
if ~isempty(fg.seeds)
    fg1.seeds=fg.seeds(fiberLen>fiberLenCrit, :);
end
fg1.subgroup=fg.subgroup(fiberLen>fiberLenCrit);

fg1.name=[fg.name '_>10mm'];
shortNfibers=size(fg.fibers, 1)-size(fg1.fibers, 1);
clear fg;
display(['Eliminated ' num2str(shortNfibers) ' fibers that were shorter than ' num2str(fiberLenCrit) ' mm']);

%(2) Linear anisotropy is defined in Westin, Peled, Gubjartsson, Kikinis,
%Jolesc (ISMRM, 1997): cl=(l1-l2)/(l1+l2+l3)
valName ='shapes'; interpMethod='trilin'; %(triplet of values indicating linearity, planarity and spherisity)
dt      = dtiLoadDt6(dt6filename);

%Create a FG which consists only of long fibers that have average LA of at
%least averLACrit
fg2 = fg1; fg2.seeds=[]; fg2.fibers=[]; fg2.subgroup=[];
fg2.name = [fg1.name '_la>' num2str(averLACrit)];

%Need to break the FG into pieces of 5000 so that dtiGetValFromFibers does not
%choke on it.
stepsize=5000;

fgtemp.seeds=[];

fprintf(1, ['Computing linear anisotropy for fibers (out of ' num2str(size(fg1.fibers, 1)) '): ']);
for group_of_fibers=1:stepsize:size(fg1.fibers, 1)

    fprintf(1, [num2str(group_of_fibers) ' to ' num2str(min(group_of_fibers+stepsize-1, size(fg1.fibers, 1))) ' ... ']);
    if ~isempty(fg1.seeds)
        fgtemp.seeds=fg1.seeds(group_of_fibers:min(group_of_fibers+stepsize-1, size(fg1.seeds, 1)), :);
    end
    fgtemp.fibers=fg1.fibers(group_of_fibers:min(group_of_fibers+stepsize-1, size(fg1.fibers, 1)));
    fgtemp.subgroup=fg1.subgroup(group_of_fibers:min(group_of_fibers+stepsize-1, size(fg1.fibers, 1)));

    val = dtiGetValFromFibers(dt.dt6, fgtemp, inv(dt.xformToAcpc), valName, interpMethod);
    shapes=cellfun(@mean, val, 'UniformOutput', 0);
    shapesC=vertcat(shapes{:});
    %shapesC(:, 1) %gives you linear anisotropy

    fg2.fibers=vertcat(fg2.fibers, fgtemp.fibers(shapesC(:, 1)>averLACrit));
    if ~isempty(fgtemp.seeds)
        fg2.seeds=vertcat(fg2.seeds, fgtemp.seeds(shapesC(:, 1)>averLACrit, :));
    end
    fg2.subgroup=horzcat(fg2.subgroup, fgtemp.subgroup(shapesC(:, 1)>averLACrit));

end
fprintf(1, '\n');
lowanisotropyNfibers=size(fg1.fibers, 1)-size(fg2.fibers, 1);
fprintf('Eliminated %d fibers that had linear anisotropy smaller than %.3f\n',...
    lowanisotropyNfibers, averLACrit);
clear fg1 fgtemp;

%Now, this approach has to be tested for robustness towards the order in
%which the fibers are tested. If a fiber B is considered too close to fiber
%A, fiber B is dropped (there is no creating an average representation of
%the two, as the latter might lead to weird drifft effects swipping
%streamsheets

% Shuffle the fibers to ensure the lack of effects that comes from
% systematic seed placement.
fg3 = dtiShuffleFibers(fg2);
clear fg2;

% This will be the selected fibers, I guess. (BW).  This method of creating
% the pool is odd and special cased.  It should be a general function.
fiberspool = fg3;
fiberspool.name = sprintf('%s-culled',fg3.name);
fiberspool.fibers = [];
fiberspool.seeds  = [];
fiberspool.subgroup = [];

% Always put one fiber (the first one) into the pool
fiberspool.fibers{1} = fg3.fibers{1};
if ~isempty(fg3.seeds)
    fiberspool.seeds = fg3.seeds(1, :);
end
% I guess for subgropu, too
fiberspool.subgroup = fg3.subgroup(1);

% Should be a mrvWaitbar?  It steps in 5000 fiber chunks.  Not sure why.
fprintf('Distance testing: %d fibers\n', size(fg3.fibers, 1));
stepSize = 5000;
for i=1:stepSize:size(fg3.fibers, 1) % Step over 5000 fibers at a time.

    % There is an index 'i', an index 'ii', and an index 'jj'. We can be
    % clearer. We compare the fibers in fg3 with each fibers in the pool We
    % add fibers from fg3 to the pool if they are not close to anything
    % already in the pool.
    for ii=i:min(i+(stepSize-1), size(fg3.fibers, 1))
        inpool = 1;   %Assume ii fiber in fg3 is in the keep pool
        for jj = 1:size(fiberspool.fibers, 1)

            % Compare the iith fiber in fg3 to each of the fibers in the
            % pool
            %
            % InterfiberZhangDistance should be renamed fgDistance.  That
            % function should have a switch to define which algorithm is
            % used, e.g. Zhang. The Dt level should be explained better.
            % Also, I think this algorithm is supposed to be using Dt + Tt,
            % not Dt.
            [Dt avgDt] = InterfiberZhangDistance(fg3.fibers{ii}, fiberspool.fibers{jj}, Tt);

            if Dt <= distanceCrit
                inpool=0; % Reject this fiber
                break
            end

        end

        % Add the new fiber to the pool.  It will be compared to the
        % remaining fibers in fg3.
        if inpool==1
            fiberspool.fibers=vertcat(fiberspool.fibers, fg3.fibers{ii});
            if ~isempty(fg3.seeds)
                fiberspool.seeds=vertcat(fiberspool.seeds, fg3.seeds(ii, :));
            end
            fiberspool.subgroup=horzcat(fiberspool.subgroup, fg3.subgroup(ii));
        end

    end
    fprintf('Distance testing: %d fibers of %d\n', ii, size(fg3.fibers, 1))
end

fprintf('Out of total %d fibers %d fibers remain\n',...
    totalNfibers,size(fiberspool.fibers, 1));
fprintf('Eliminated %d fibers because they were shorter than %d mm\n',...
    shortNfibers,fiberLenCrit);
fprintf('Eliminated %d fibers because linear anisotropy less than %d\n',...
    lowanisotropyNfibers, averLACrit);
fprintf('Eliminated %d fibers because they were adjacent to others\n',...
    size(fg3.fibers,1) - size(fiberspool.fibers, 1)) ;

% Add a comment
fg.cullingParams={'Tt', Tt, 'aboveThresDistanceCrit', distanceCrit};
fiberDiameter = Tt + distanceCrit;

return


function [A] = au2A(au)
% Convert length from astronomical units to angstroms.
% Chad A. Greene 2012
A = au*1.49597870691e+21;


function varargout = spectrumLabel(hAxesTarget)
%spectrumLabel   Add a spectrum to the X-Axis of a plot.
%
%    H = SPECTRUMLABEL(HTARGET) adds a spectrum colorbar and wavelength
%    labels to the X axis of the axes object HTARGET.  For plots whose X
%    values are in the range 300 to 830, the colorbar will show the ROYGBIV
%    spectrum based on the 1964 CIE 10-degree observer.  Values outside the
%    range will be shown as black.  H contains a handle to the axes object
%    containing the spectrum.
%
%    Examples:
%    ---------
%    % Show the D65 illuminant.
%    [lambda, D65] = illuminant('d65');
%    figure;
%    plot(lambda, D65)
%    title('D_{65} illuminant')
%    spectrumLabel(gca)
%
%    % Show the CIE 1964 10-degree observer color matching functions.
%    [lambda, x, y, z] = colorMatchFcn('1964_full');
%    figure;
%    plot(lambda, x, 'r', lambda, y, 'g', lambda, z, 'b')
%    title('CIE 1964 10-degree observer')
%    spectrumLabel(gca)
%
%    See also colorMatchFcn, illuminant.

%    Copyright 1993-2005 The MathWorks, Inc.

hFig = ancestor(hAxesTarget, 'figure');

% Add a new axes to the same figure as the target axes.
figure(hFig);
hAxesSpectrum = axes;
set(hAxesSpectrum, 'visible', 'off')

% Areas outside the visible spectrum are black.
set(hAxesSpectrum, 'color', [0 0 0])

% Position the axes as appropriate.
targetPosition = get(hAxesTarget, 'position');
spectrumPosition = [targetPosition(1), ...
                    targetPosition(2), targetPosition(3), 1];
set(hAxesSpectrum, 'position', spectrumPosition)
set(hAxesSpectrum, 'units', 'pixels')

spectrumPosition = get(hAxesSpectrum, 'position');
set(hAxesSpectrum, 'position', [spectrumPosition(1), ...
                                spectrumPosition(2) - 20, ...
                                spectrumPosition(3), ...
                                20])

% Line the X limits of the two axes up and display the spectrum.
set(hAxesSpectrum, 'xtick', get(hAxesTarget, 'xtick'))

[lambda, RGB] = createSpectrum('1964_full');
axes(hAxesSpectrum);
image(lambda, 1:size(RGB,1), RGB);

% Turn off the unneeded axes labels.
set(hAxesTarget, 'xtick', []);
set(hAxesSpectrum, 'ytick', []);

% Make the figure visible.
set(hAxesSpectrum, 'units', 'normalized')
set(hAxesSpectrum, 'visible', 'on')

% Return the handle if requested.
if (nargout == 1)

    varargout{1} = hAxesSpectrum;

end

% Add a callback to update the label if the X limits of the target changes.
% TO DO.


function B = fevalArrays( A, fHandle, varargin )
% Used to apply the same operation to a stack of array elements.
%
% The only constraint on the function specified in fHandle is that given
% two differrent input arrays a1 and a2, if a1 and a2 have the same
% dimensions then the outputs b1 and b2 must have the same dimensions. For
% long operations shows progress information.
%
% A can have arbitrary dimension.  Suppose A has size d1 x d2 ... x dn.
% Then for the purpose of this function A has dn elements, where
% A(:,:,...,i) is the ith element.  This function then applies the
% operation in fHandle, with paramters given in varargin, to each element
% in A. The results are returned in the array B, of size f1 x f2 x ... x fk
% x dn.  Each of the n element of B of the form B(:,:,...,i) is the the
% result of applying fHandle to A(:,:,...,i).  A may also be a cell array,
% see the last example.
%
% A limitation of fevalArrays is that it does not pass state information
% to fHandle.  For example, fHandle may want to know how many times it's
% been called.  This can be overcome by saving state information inside
% fHandle using 'persistent' variables.  For an example see imwrite2.
%
% USAGE
%  B = fevalArrays( A, fHandle, varargin )
%
% INPUTS
%  A        - input array
%  fHandle  - operation to apply to each 'element' of A
%  params   - [varargin] parameters for each operation specified by fHandle
%
% OUTPUTS
%  B        - output array
%
% EXAMPLE
%  B = fevalArrays( A, @rgb2gray );      % where A is MxNx3xR
%  B = fevalArrays( A, @imresize, .5 );  % where A is MxNxR
%  B = fevalArrays( A, @imNormalize );   % where A has arbitrary dims
%  B = fevalArrays( A, @(x) {imresize(x{1},.5)} ); % A is cell array
%
% See also FEVALIMAGES, FEVALMATS, ARRAYFUN
% IMWRITE2, PERSISTENT, TICSTATUS,
%
% Piotr's Image&Video Toolbox      Version 2.0
% Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see external/bsd.txt]

nd = ndims(A);  siz = size(A);  n = siz(end);
indsA = {':'}; indsA = indsA(ones(nd-1,1));

ticId = ticStatus('fevalArrays',[],60);
for i=1:n
  % apply fHandle to each element of A
  b = feval( fHandle, A(indsA{:},i), varargin{:} );
  if( i==1 )
    ndb = ndims(b);
    if(ndb==2 && size(b,2)==1); ndb=1; end
    onesNdb = ones(1,ndb);
    B = repmat( b, [onesNdb,n] );
    indsB = {':'}; indsB = indsB(onesNdb);
  else
    B(indsB{:},i) = b;
  end;
  tocStatus( ticId, i/n );
end


function str = num2sci(A,precision,units)
%% FUNCTION num2sci
% Converts a number to a string in scientific format (e.g. .00325 ==> 3.25m).
% Can optionally provide precision (number of significant digits) and/or unit
% string to append.  The default precision is 4 significant digits.
%
%
% Examples:
%
% str = num2sci(165.48e-3) returns str = '165.5 m'
% str = num2sci(165.48e-3,'V') returns str = '165.5 mV'
% str = num2sci(165.48e-3,'mV') returns str = '165.5 uV'
% str = num2sci(165.48e-3,3,'V') returns str = '165 mV'
% str = num2sci([1.5 2.5],{'V','mA'}) returns str = {'1.5 V' '2.5 mA'}
%
% See also: num2str
%
%
% Written By: Jason Kaeding
%       Date: 07/10/09

%% REVISION INFORMATION:
% 11/23/09 - JAK - Added code to check units for cases when a prefix exists
%                  inside the unit string.  Examples are "kg" or "mV".  In these
%                  cases, the prefix is removed, A is recomputed based on this
%                  prefix, and then a new prefix is determined and used.
% 03/03/10 - JAK - Fixed bug in 11/23 revision which did not convert "kg"
%                  properly.

%% Check inputs
error(nargchk(1,3,nargin,'struct'));

if iscell(A)
    error('num2sci:cellInput','Input cannot be a cell array.');
end

if ischar(A)
    str = A;
    return;
end

if isempty(A)
    str = '';
    return;
end

switch nargin
    case 1
        precision = 4;
        units = '';
    case 2
        if ischar(precision) || iscellstr(precision)
            units = precision;
            precision = 4;
        else
            units = '';
        end
    case 3
        if ~ischar(units) && ~iscellstr(units)
            error('Units must be a string');
        end
end

if iscellstr(units)
    if ~all(size(units) == size(A))
        error('num2cell:badUnitsDim',...
            'Units must be the same size as input matrix.');
    end
end

%% Set up SI prefixes
prefix_vector = {'y','z','a','f','p','n','u','m','',...
    'k','M','G','T','P','E','Z','Y'};
prefix_offset = 9;

%% De-exponentiate
exponents = floor(log10(abs(A))./3);
exponents(~isfinite(A)) = 0; % +/- Inf and NaN assign to zero (no prefix)
exponents(A==0) = 0; % log10(0) = -Inf, correct this to 0 = 0*10^0
exponents = max(exponents,-8); % cap finite at 10^-24
exponents = min(exponents,8); % cap finite at 10^24

% Check for prefix in units
% Cases to check:
% 1. [prefix][A-Z][\w]* for typical units
% 2. [prefix][mgs] for SI units such as m,kg,s
% 3. [prefix][b][iyp/]?[\w/]* for bit/byte types of units (include / for bits/s)
unit_exp = 0;
if ~isempty(units)
    unit_check_results = regexp(units,...
        ['^([',[prefix_vector{:}],'])([A-Z]\w*|[mgs]|b[iyp/]?[\w/]*)$'],...
        'tokens','once');
    if ischar(units)
        unit_exp = 0;
        if ~isempty(unit_check_results)
            unit_exp = find(strcmp(unit_check_results{1},prefix_vector),1) - 9; % offset is 9
            units = unit_check_results{2}; % un-prefixed units
        end
    else
        % Check one by one
        unit_exp = zeros(size(exponents));
        for ind = 1:numel(unit_check_results)
            if ~isempty(unit_check_results{ind})
                unit_exp(ind) = find(strcmp(unit_check_results{ind}{1},...
                    prefix_vector),1) - 9; % offset is 9
                units{ind} = unit_check_results{ind}{2}; % un-prefixed units
            end
        end
    end
end

% Compute new base numbers
A = A./(10.^(3.*exponents));
exponents = exponents + unit_exp;

%% Find prefix for each element
prefix = cellfun(@(x)prefix_vector{x},num2cell(exponents+prefix_offset),...
    'UniformOutput',false);

%% Execute num2str
str = cellfun(@(x)[num2str(x,precision),' '],num2cell(A),'UniformOutput',false);

%% Build final string
% 1. Combine number with prefix & units
% 2. Check for num2str anomalies resulting from %g use (e.g. 32.4e+005), fix
% 3. Remove space if last character
str = regexprep(strcat(str,prefix,units),{'(\d+)\.?(\d+)?e[+](\d+)','\s+$'},...
    {'$1$2${repmat(''0'',1,str2double($3)-length($2))}',''});

%% De-cellify if single element
if numel(str) == 1
    str = str{1};
end


% Test file for bndfun/createMap.m.

function pass = test_createMap(pref)

dom = [-2 7];
map = bndfun.createMap(dom);

pass(1) = all(map.For([-1 1]) == dom) && all(map.Inv(dom) == [-1 1]);

pass(2) = map.Der(1) == diff(dom)/2;

end


function [M] = spm_ADEM_M_set(M)
% Set indices and perform checks on hierarchical action models
% FORMAT [M] = spm_ADEM_M_set(M)
%
% for each level (i); required fields
%
%   M(i).g  = y(t)  = g(x,v,a,P)    {inline function, string or m-file}
%   M(i).f  = dx/dt = f(x,v,a,P)    {inline function, string or m-file}
%
% and
%
%   M(i).m  = number of inputs v(i + 1);
%   M(i).n  = number of states x(i);
%   M(i).l  = number of output v(i);
%   M(i).k  = number of action a(i);
%
% or
%
%   M(i).x  = hidden states;
%   M(i).v  = causal states;
%   M(i).a  = action states;
%
% for each level (i); optional fields
%
%   M(i).pE = prior expectation of p model-parameters
%   M(i).V  = precision (input noise)
%   M(i).W  = precision (state noise)
%   M(i).U  = precision (action)
%
%
% sets fields, checks internal consistency of model specification and sets
% estimation parameters.  If (V,W) are not specified infinite precision is
% assumed.
%--------------------------------------------------------------------------
%
%   M(1).E.s;     = smoothness (s.d. in time bins)
%   M(1).E.d;     = embedding order q(v)  (i.e., number of derivatives)
%   M(1).E.n;     = embedding order q(x)
%
% If the highest level involves any dynamic or static transformation
% of its inputs a further level is added with flat priors
%__________________________________________________________________________
% Copyright (C) 2008-2014 Wellcome Trust Centre for Neuroimaging

% Karl Friston
% $Id: spm_ADEM_M_set.m 5962 2014-04-17 12:47:43Z spm $

% order
%--------------------------------------------------------------------------
g      = length(M);

% set missing fields
%==========================================================================

% check for specification of hidden states
%--------------------------------------------------------------------------
if isfield(M,'f') && ~isfield(M,'n') && ~isfield(M,'x')
    msgbox('please specify hidden states or their number')
    error(' ')
end

% check supra-ordinate level and add one (with flat priors) if necessary
%--------------------------------------------------------------------------
try
    fcnchk(M(g).g);
    g      = g + 1;
    M(g).l = M(g - 1).m;
end
M(g).m = 0;
M(g).n = 0;

% default fields for static models (hidden states)
%--------------------------------------------------------------------------
if ~isfield(M,'f')
    [M.f] = deal(inline('sparse(0,1)','x','v','a','P'));
    [M.x] = deal(sparse(0,1));
    [M.n] = deal(0);
end
for i  = 1:g
    try
        fcnchk(M(i).f);
    catch
        M(i).f = inline('sparse(0,1)','x','v','a','P');
        M(i).x = sparse(0,1);
    end
end

% consistency and format check on states, parameters and functions
%==========================================================================

% prior expectation of parameters M.pE
%--------------------------------------------------------------------------
try
    M.pE;
catch
    % Assume fixed parameters
    %----------------------------------------------------------------------
    for i = 1:g
        M(i).pE = sparse(0,0);
    end
end

% get inputs
%--------------------------------------------------------------------------
try
    v  = M(g).v;
catch
    v  = sparse(0,1);
end
if isempty(v)
    try
        v = sparse(M(g - 1).m,1);
    end
end
if isempty(v)
    try
        v = sparse(M(g).l,1);
    end
end
M(g).l    = length(spm_vec(v));
M(g).v    = v;

% ensure action is specified
%--------------------------------------------------------------------------
for i = 1:g
    try
        a  = M(i).a;
    catch
        a  = sparse(0,1);
    end
    if isempty(a)
        try
            a = sparse(M(i).k,1);
        end
    end
    M(i).k    = length(spm_vec(a));
    M(i).a    = a;
end

% check functions
%--------------------------------------------------------------------------
for i = (g - 1):-1:1
    try
        x = M(i).x;
    catch
        x = sparse(M(i).n,1);
    end
    if isempty(x) && M(i).n
        x = sparse(M(i).n,1);
    end

    % check f(x,v,P)
    %----------------------------------------------------------------------
    try
        M(i).f = fcnchk(M(i).f);
        if nargin(M(i).f) ~= 4
            M(i).f = inline(char(M(i).f),'x','v','a','P');
        end
    end
    try
        f      = feval(M(i).f,x,v,a,M(i).pE);
        if length(spm_vec(x)) ~= length(spm_vec(f))
            errordlg(sprintf('please check nargout: G(%i).f(x,v,a,P)',i));
        end
    catch
        errordlg(sprintf('evaluation failure: G(%i).f(x,v,a,P)',i))
    end

    % check g(x,v,P)
    %----------------------------------------------------------------------
    try
        M(i).g = fcnchk(M(i).g);
        if nargin(M(i).g) ~= 4
            M(i).g = inline(char(M(i).g),'x','v','a','P');
        end
    end
    try
        M(i).m = length(spm_vec(v));
        v      = feval(M(i).g,x,v,a,M(i).pE);
        a      = M(i).a;
        M(i).k = length(spm_vec(a));
        M(i).l = length(spm_vec(v));
        M(i).n = length(spm_vec(x));

        M(i).a = a;
        M(i).v = v;
        M(i).x = x;

    catch
        errordlg(sprintf('evaluation failure: G(%i).g(x,v,a,P)',i))
    end
end

% remove empty levels
%--------------------------------------------------------------------------
try
    g  = find(~spm_vec(M.m),1);
    M  = M(1:g);
catch
    errordlg('please specify number of variables')
end

% number of x (hidden states)
%--------------------------------------------------------------------------
nx     = sum(spm_vec(M.n));

% check precisions
%==========================================================================
try, M.V;  catch, M(1).V  = []; end
try, M.W;  catch, M(1).W  = []; end

% check precisions
%--------------------------------------------------------------------------
for i = 1:g

    % check V and assume unit precision if improperly specified
    %----------------------------------------------------------------------
    if isvector(M(i).V), M(i).V = diag(M(i).V); end
    if length(M(i).V) ~= M(i).l
        try
            M(i).V = speye(M(i).l,M(i).l)*M(i).V(1);
        catch
            M(i).V = speye(M(i).l,M(i).l)*exp(32);
        end
    end

    % check W and assume unit precision if improperly specified
    %----------------------------------------------------------------------
    if isvector(M(i).W), M(i).W = diag(M(i).W); end
    if length(M(i).W) ~= M(i).n
        try
            M(i).W = speye(M(i).n,M(i).n)*M(i).W(1);
        catch
            M(i).W = speye(M(i).n,M(i).n)*exp(32);
        end
    end
end

% check restiction of precision for action (gain)
%==========================================================================
try, M(1).U;  catch, M(1).U = []; end

if isvector(M(1).U), M(1).U = diag(M(1).U); end
if length(M(1).U) ~= M(1).l
    try
        M(1).U = speye(M(1).l,M(1).l)*M(1).U(1);
    catch
        M(1).U = speye(M(1).l,M(1).l)*exp(2);
    end
end

% estimation parameters M(1).E.s, n,...
%==========================================================================
% E.s;                               % smoothness (seconds)
% E.dt;                              % time step
% E.d;                               % approximation order of q(x,v)
% E.n;                               % order of embedding (n >= d)

% temporal smoothness - s.d. of kernel
%--------------------------------------------------------------------------
try M(1).E.s;  catch, if nx, M(1).E.s = 1/2; else M(1).E.s = 0; end, end

% time step
%--------------------------------------------------------------------------
try M(1).E.dt; catch, M(1).E.dt = 1; end

% embedding orders
%--------------------------------------------------------------------------
try M(1).E.d;  catch, if nx, M(1).E.d = 2;  else M(1).E.d = 0;  end, end
try M(1).E.n;  catch, if nx, M(1).E.n = 6;  else M(1).E.n = 0;  end, end

M(1).E.d = min(M(1).E.d,M(1).E.n);

% checks on smoothness hyperparameter
%==========================================================================
for i = 1:g

    try, M(i).sv; catch,   M(i).sv = M(1).E.s; end
    try, M(i).sw; catch,   M(i).sw = M(1).E.s; end

    if ~isscalar(M(i).sv), M(i).sv = M(1).E.s; end
    if ~isscalar(M(i).sw), M(i).sw = M(1).E.s; end
end


function out = isempty(F)
%ISEMPTY   Empty boolean check for a SPHEREFUNV object.
%   ISEMPTY(F) returns 1 if every component of F is an empty SPHEREFUN, and
%   return 0 otherwise.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

if ( isempty( F.components) )
    out = 1;
    return
end

% Take isempty of each component:
out = cellfun(@isempty, F.components, 'UniformOutput', false);
out = all(cell2mat(out));

end


function varargout = spm_brainwarp(varargin)
% Part of nonlinear spatial normalisation - a compiled routine
%_______________________________________________________________________
% [Alpha,Beta,Var] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,...
%                                   dbasX,dbasY,dbasZ,T,fwhm,VW,VW2)
% VG    - Template volume(s) (see spm_vol)
% VF    - Object volume
% Affine    - The affine transformation which maps between the object
%     and template.
% basX  - Basis vectors in X. # rows must eq. VG(1)
% basY  - Basis vectors in Y. # rows must eq. VG(2)
% basZ  - Basis vectors in Z. # rows must eq. VG(3)
% dbasX - Derivatives of basis vectors in X. # rows must eq. VG(1)
% dbasY - Derivatives of basis vectors in Y. # rows must eq. VG(2)
% dbasZ - Derivatives of basis vectors in Z. # rows must eq. VG(3)
% T - The current parameter estimates.
% fwhm  - The approximate smoothness of the images.
% VW    - an optional weighting volume for determining which voxels
%         should be weighted more heavily in the fitting process.
%         This volume should have the same dimensions and position
%         as the volumes in VG.
% VW2   - another optional weighting volume for determining which voxels
%         should be weighted more heavily in the fitting process.
%         This volume should have the same dimensions and position
%         as the volumes in VF.
% Without the weighting volumes, all voxels are assigned weights that
% are uniformly one.
%
% Alpha - A*A - where A is the design matrix
% Beta  - A*b - where f is the object image
% Var   - the approximate chi^2 (corrected for number of resels).
%_______________________________________________________________________
%
% The voxels of g1, g2.. are sampled according to the smoothness of the
% image (fwhm). The corresponding voxels of f are determined according
% to the current parameter estimates and the affine transform.  See
% "spm_write_sn.m" for more details about how this is done.
%
%
%-----------------------------------------------------------------------
%
% The design matrix A is generated internally from:
%
% diag(w)*[diag(df/dx)*B diag(df/dy)*B diag(df/dz)*B ...
%      diag(g1)*[1 x y z] ...
%      diag(g2)*[1 x y z] ...]
%
% where df/dx, df/dy & df/dz are column vectors containing the gradient
%   of image f with respect to displacements in x, y & z
%   (in the space of g).
%
%   B is generated from kron(basZ,kron(basY,BasX)). Each column of
%   B is a basis image.
%
%   g1, g2.. are template images.
%
%   x, y & z are simply the spatial coordinates of the voxels of f.
%
%   s1, s2.. are the current estimates for the required scaling
%   factors. These are derived from T(3*prod(VG(1:3))+1),
%   T(3*prod(VG(1:3))+2)...
%
%       w is an optional vector of weights, where w = 1/(1/w1 + 1/w2)
%       where w1 and w2 are derived from the optional weighting images.
%
% The vector b contains [diag(w)*(f - diag(g1)*s1 - diag(g1)*x*s2 - ...)].
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id$

%-This is merely the help file for the compiled routine
error('spm_brainwarp.c not compiled - see Makefile')


function pass = test_constructor_inputs(pref)

if ( nargin == 0 )
    pref = chebfunpref();
end

% [TODO]: This test needs to be updated to include more exotic input options.

% Generate a few random points to use as test values.
seedRNG(6178);
xx = 2 * rand(100, 1) - 1;

% Test the vectorise flag:
try
    f = chebfun(@(x) x^2, pref, 'vectorize'); %#ok<NASGU>
    pass(1) = true;
catch
    pass(1) = false;
end

% Test the vectorise flag:
f = chebfun(@(x) sin(x), pref, 5);
pass(2) = ( length(f.funs{1}) == 5 );
% [TODO]: Change this once @CHEBFUN/LENGTH is implemented.

% Test the 'splitting on' flag.
f = chebfun(@(x) abs(x), 'splitting', 'on');
pass(3) = all(size(f.funs) == [1, 2]);

% Test the 'extrapolate' flag.
f = chebfun(@(x) sign(x), [0, 1], 'extrapolate', 'on');
pass(4) = get(f, 'ishappy');

% Test construction from an array of FUN objects:
f = chebfun({0, 1, 2, 3, 4, 5}, [0, 1, 2, 3, 4, 5, 6]);
g = chebfun(f.funs);
pass(5) = all(size(g.funs) == [1, 6]) && all(g.domain == 0:6);

% Test array-valued construction from an array of FUN objects:
f = chebfun({[0, 1], [2, 3], [4, 5]}, [0, 1, 2, 3]);
g = chebfun(f.funs);
pass(6) = all(size(g.funs) == [1, 3]) && all(g.domain == 0:3);

% Test fixed-length construction:
f = chebfun(@sin, 10);
pass(7) = numel(f.funs) == 1 && size(f.funs{1},1) == 10;

% Test equispaced construction:
f = chebfun(rand(10,3), 'equi');
pass(8) = numel(f.funs) == 1 && size(f.funs{1}, 1) > 10;

% Test construction from coefficients.
f = chebfun([1 ; 2 ; 3], 'coeffs');
pass(9) = isequal(f.funs{1}.onefun.coeffs, [1 ; 2 ; 3]);

% Test 'chebkind' and 'kind' flags.
f1 = chebfun(@(x) x, 'chebkind', '1st');
f3 = chebfun(@(x) x, 'chebkind', 1);
pass(10) = isa(f1.funs{1}.onefun, 'chebtech1') && ...
    isa(f3.funs{1}.onefun, 'chebtech1');

% Test construction from numeric string.
f = chebfun('1');
pass(11) = all(feval(f, linspace(-1, 1, 10)) == 1);

% Test 'trunc', flag.
f = chebfun(@abs, 'trunc', 10, 'splitting', 'on');
c = get(f, 'coeffs');
pass(12) = abs(-4/63/pi - c(9)) < 10*eps;

% Test construction from cells of strings:
f = chebfun({'x','x-1'}, [0 1 2]);
pass(13) = norm(feval(f, [.5, 1.5]) - .5) < eps;

% Test construction from a chebfun:
x = chebfun('x', [0, 5]);
f = chebfun(x);
pass(13) = all(domain(f) == [0 5] );

f = chebfun(x, [0 2]);
pass(14) = all(domain(f) == [0 2] );

% Test construction from a piecewise chebfun:
f = chebfun(chebfun({'x','x'}, [-1 0 1]));
x = [-.5, .5];
pass(15) = numel(f.funs) == 1  && norm(feval(f, x) - x) < eps;

% Test 'minSamples' flag.
f_op = @(x) -x - x.^2 + exp(-(50*(x - .5)).^4);
f1 = chebfun(f_op, 'minSamples', 17);
err1 = norm(feval(f1, xx) - f_op(xx), inf);
f2 = chebfun(f_op, 'minSamples', 33);
err2 = norm(feval(f2, xx) - f_op(xx), inf);
pass(16) = (err1 > 1e-3) && (err2 < 1e2*vscale(f2)*eps);

% Test support for "legacy" preferences.
f_op = @(x) sin(200*x);

f = chebfun(f_op, 'resampling', 'on');
pass(17) = ishappy(f);

warnstate = warning('off','CHEBFUN:CHEBFUN:constructor:notResolved');
f = chebfun(f_op, 'maxdegree', 129, 'tech', @chebtech2);
pass(18) = ~ishappy(f) && (length(f) == 129);
warning(warnstate);

f = chebfun(f_op, 'splitting', 'on', 'splitdegree', 65);
pass(19) = ishappy(f) && all(cellfun(@(fk) length(fk) <= 65, f.funs));

warnstate = warning('off','CHEBFUN:CHEBFUN:constructor:funNotResolved');
f = chebfun(f_op, 'splitting', 'on', 'splitLength', 65, 'splitMaxLength', 200);
pass(20) = ~ishappy(f) && (length(f) <= 65*4);
warning(warnstate);

% Test construction with a mixture of preference object and keyword inputs.
p = pref;
p.tech = @chebtech1;
f = chebfun(@(x) 1./x, [0 1], 'exps', [-1 0], p);
pass(21) = get(f, 'ishappy') && isa(f.funs{1}.onefun.smoothPart, 'chebtech1');
f = chebfun(@(x) 1./x, [0 1], p, 'exps', [-1 0]);
pass(22) = get(f, 'ishappy') && isa(f.funs{1}.onefun.smoothPart, 'chebtech1');

p = struct();
p.tech = @chebtech1;
f = chebfun(@(x) 1./x, [0 1], 'exps', [-1 0], p);
pass(23) = get(f, 'ishappy') && isa(f.funs{1}.onefun.smoothPart, 'chebtech1');
f = chebfun(@(x) 1./x, [0 1], p, 'exps', [-1 0]);
pass(24) = get(f, 'ishappy') && isa(f.funs{1}.onefun.smoothPart, 'chebtech1');

% Test the vectorise flag on an array-valued function:
try
    f = chebfun(@(x) [x^2 sin(x)*cos(x)], pref, 'vectorize'); %#ok<NASGU>
    pass(25) = true;
catch
    pass(25) = false;
end

% Test the 'eps' preference.
f = chebfun(@sin);
g = chebfun(@sin, 'eps', 1e-6);
pass(26) = length(g) < length(f);

% Test the use of 'coeffs' and 'chebkind' simultaneously.
c = (1:5).';
try
    chebfun(c, 'coeffs', 'chebkind', 1);
catch ME
    pass(27) = strcmpi(ME.message, [' ''coeffs'' and ''chebkind'' ' ...
        'should not be specified simultaneously.']);
end

try
    chebfun(c, 'chebkind', 2, 'coeffs');
catch ME
    pass(28) = strcmpi(ME.message, [' ''coeffs'' and ''chebkind'' ' ...
        'should not be specified simultaneously.']);
end

% Test construction from a chebfun row (transposed chebfun). The result
% should be a chebfun column (not transposed).
f = chebfun(@(x) cos(pi*x))';
g = chebfun(f);
pass(29) = g.isTransposed == 0;

end


%                               stopNow.m
%
% This function is used in the main loop of many solvers (i.e.solve*.m) to
% check if the stopping condition(time, residual and reconstruction error)
% has been met and thus loop should be breaked.
%
%
% Note:
% This function does not check for max iterations since the for-loop
% in the solver already gurantee it.
%
% Inputs:
%         opts(struct)                   :  consists of options. It is as
%                                           defined in solverPhaseRetrieval.
%                                           See its header or User Guide
%                                           for details.
%         currentResid(real number)      :  Definition depends on the
%                                           specific algorithm used see the
%                                           specific algorithm's file's
%                                           header for details.
%         currentReconError(real number) :  norm(xt-x)/norm(xt), where xt
%                                           is the m x 1 true signal,
%                                           x is the n x 1 estimated signal
%                                           at current iteration.
% Outputs:
%         ifStop(boolean)                :  If the stopping condition has
%                                           been met.
%
%
%
% PhasePack by Rohan Chandra, Ziyuan Zhong, Justin Hontz, Val McCulloch,
% Christoph Studer, & Tom Goldstein
% Copyright (c) University of Maryland, 2017

function ifStop = stopNow(opts, currentTime, currentResid, currentReconError)
    if currentTime >= opts.maxTime
        ifStop = true;
        return
    end
    if ~isempty(opts.xt)
            assert(~isempty(currentReconError),'If xt is provided, currentReconError must be provided.');
            ifStop = currentReconError < opts.tol;
    else
        assert(~isempty(currentResid),'If xt is not provided, currentResid must be provided.');
        ifStop = currentResid < opts.tol;
    end
end


classdef TestFindCirclesGrid
    %TestFindCirclesGrid

    methods (Static)
        function test_1
            img = imread(fullfile(mexopencv.root(),'test','acircles_pattern.png'));
            img = cv.resize(img, 0.5, 0.5);
            sz = [4 11];
            [centers,found] = cv.findCirclesGrid(img, sz, 'SymmetricGrid',false);
            validateattributes(centers, {'cell'}, {'vector'});
            cellfun(@(v) validateattributes(v, {'numeric'}, ...
                {'vector', 'numel',2, 'real'}), centers);
            validateattributes(found, {'logical'}, {'scalar'});
            if found
                assert(numel(centers) == prod(sz));
            end
        end

        function test_2
            img = imread(fullfile(mexopencv.root(),'test','acircles_pattern.png'));
            sz = [4 11];
            [centers,found] = cv.findCirclesGrid(img, sz, 'SymmetricGrid',false, ...
                'BlobDetector',{'SimpleBlobDetector', 'MaxArea',100000});
            validateattributes(centers, {'cell'}, {'vector'});
            cellfun(@(v) validateattributes(v, {'numeric'}, ...
                {'vector', 'numel',2, 'real'}), centers);
            validateattributes(found, {'logical'}, {'scalar'});
            if found
                assert(numel(centers) == prod(sz));
            end
        end

        function test_error_argnum
            try
                cv.findCirclesGrid();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


function varargout = quiver3( Z, F, varargin )
%QUIVER3  3-D quiver plot of a CHEBFUN2V at data mapped by a SEPARABLEAPPROX.
%
% QUIVER3(Z, F) plots velocity vectors at the equally spaced surface points
% specified by the SEPARABLEAPPROX Z. We use Z to map a uniform grid. F should be
% a CHEBFUN2V.
%
% QUIVER3(X, Y, Z, F) plots velocity vectors at (x,y,z), where X, Y, Z are
% SEPARABLEAPPROX objects which we use to to map a uniform grid. F should be a
% CHEBFUN2V.
%
% Alternative syntax for this command is:
% QUIVER3(X,Y,Z,[f;g;h]) or QUIVER3(X,Y,Z,f,g,h), where f, g, and h are
% SEPARABLEAPPROX objects.
%
% QUIVER(...,'numpts',N) plots arrows on a N x N uniform grid.
%
% This command is a wrapper to CHEBFUN2V/QUIVER3, and is required because
% SEPARABLEAPPROX methods take priority over CHEBFUN2V methods.
%
% See also CHEBFUN2V/QUIVER3.

% Copyright 2017 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

numpts = 20;

if ( ~isa(Z, 'separableApprox') )
    error('CHEBFUN:SEPARABLEAPPROX:quiver3:inputs1', ...
        'First argument to this command should be SEPARABLEAPPROX.');
end

if ( isempty(varargin) )
    varargin = {};
end

% Number of points to plot
j = 1; argin = {};
while ( ~isempty(varargin) )
    if ( strcmpi(varargin{1}, 'numpts') )
        numpts = varargin{2};
        varargin(1:2) = [];
    else
        argin{j} = varargin{1};
        varargin(1) = [];
        j = j+1;
    end
end
varargin = argin;

if ( isa(F, 'chebfun2v') )              % quiver(Z,F,...)
    zz = new_data_locations(Z, numpts);
    h = quiver3(zz, F, varargin{:});
elseif ( nargin > 3 )
    if ( isa(varargin{2}, 'chebfun2v') ) % quiver(X,Y,Z,F,...)
        xx = new_data_locations(Z, numpts);
        yy = new_data_locations(F, numpts);
        zz = new_data_locations(varargin{1}, numpts);
        h = quiver3( xx, yy, zz, varargin{2}, varargin{3:end} );
    elseif ( isa(Z, 'separableApprox') && isa(F, 'separableApprox') &&...
            isa(varargin{1}, 'separableApprox') &&...
            isa(varargin{2}, 'separableApprox') &&...
            ( nargin ==4 || ~isa(varargin{3}, 'separableApprox')) )
        FF = vertcat( vertcat(F, varargin{1}), varargin{2}) ;
        h = quiver3( Z, FF );     % call quiver3(Z,F,...)
    elseif ( ( nargin > 5 ) && isa(Z,'separableApprox') && isa(F,'separableApprox') &&...
            isa(varargin{1}, 'separableApprox') &&...
            isa(varargin{2}, 'separableApprox') &&...
            isa(varargin{3}, 'separableApprox') &&...
            isa(varargin{4}, 'separableApprox') &&...
            ( nargin == 6 || ~isa(varargin{5}, 'separableApprox')) )
        FF = vertcat( vertcat(varargin{2}, varargin{3}), varargin{4} );
        h = quiver3(Z, F, varargin{1}, FF, varargin{5:end} );  % call quiver3(X,Y,Z,F,...)
    else
        error('CHEBFUN:SEPARABLEAPPROX:quiver3:inputs2', ...
            'Unrecognised input arguments.');
    end
else
    error('CHEBFUN:SEPARABLEAPPROX:quiver3:inputs3', 'Unrecognised input arguments.');
end

if ( nargout > 0 )
    varargout = { h };
end

end

function newloc = new_data_locations(f1, numpts)
% Generate new arrow location if first two inputs are SEPARABLEAPPROX objects.

dom = f1.domain;

% mesh 'em up for the quiver arrows.
x = linspace(dom(1), dom(2), numpts);
y = linspace(dom(3), dom(4), numpts);

[xx, yy] = meshgrid(x, y);
newloc = feval(f1, xx, yy);      % use SEPARABLEAPPROX to generate data locations.

end


function result = glmnetCoef( object, s )

%--------------------------------------------------------------------------
% glmnetCoef.m: print coefficients from a "glmnet" object
%--------------------------------------------------------------------------
%
% USAGE:
%    glmnetCoef(fit);
%    glmnetCoef(fit, s);
%
% DETAILS:
%    glmnetCoef(fit, s) is equivalent to glmnetPredict(fit, "coefficients", [], s)
%    See glmnetPredict for more details.
%
% LICENSE: GPL-2
%
% DATE: 14 Jul 2009
%
% AUTHORS:
%    Algorithm was designed by Jerome Friedman, Trevor Hastie and Rob Tibshirani
%    Fortran code was written by Jerome Friedman
%    R wrapper (from which the MATLAB wrapper was adapted) was written by Trevor Hasite
%    MATLAB wrapper was written and maintained by Hui Jiang, jiangh@stanford.edu
%    Department of Statistics, Stanford University, Stanford, California, USA.
%
% REFERENCES:
%    Friedman, J., Hastie, T. and Tibshirani, R. (2009)
%    Regularization Paths for Generalized Linear Models via Coordinate Descent.
%    Journal of Statistical Software, 33(1), 2010
%
% SEE ALSO:
%    glmnet, glmnetSet, glmnetPrint, glmnetPredict and glmnetPlot methods.
%
% EXAMPLES:
%    x=randn(100,20);
%    y=randn(100,1);
%    fit1=glmnet(x,y);
%    glmnetCoef(fit1,0.01) % extract coefficients at a single value of lambda
%
% DEVELOPMENT: 14 Jul 2009: Original version of glmnet.m written.

%

if nargin < 2
    s = object.lambda;
end

result = glmnetPredict(object, 'coefficients', [], s);


function x = nonnegative( varargin ) %#ok

%NONNEGATIVE   The nonnegative orthant.
%   NONNEGATIVE(SX), where SX is a valid size vector, creates an array
%   of size SX and constrains each element to be nonnegative. Therefore,
%   given the declaration
%      variable x(sx)
%   the constraint
%      x == nonnegative(sx);
%   is equivalent to
%      x >= 0;
%   Obviously, the inequality form is simpler and is preferred in most
%   circumstances.
%
%   Disciplined convex programming information:
%       NONNEGATIVE is a cvx set specification. See the user guide for
%       details on how to use sets.

sx = cvx_get_dimlist( varargin ); %#ok
cvx_begin set
    variable x( sx ) nonnegative
cvx_end

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


%JOY2TR Update transform from joystick
%
% T = JOY2TR(T, OPTIONS) updates the SE(3) homogeneous transform (4x4)
% according to spatial velocities sourced from a connected joystick device.
%
% Options::
% 'delay',D     Pause for D seconds after reading (default 0.1)
% 'scale',S     A 2-vector which scales joystick translational and
%               rotational to rates (default [0.5m/s, 0.25rad/s])
% 'world'       Joystick motion is in the world frame
% 'tool'        Joystick motion is in the tool frame (default)
% 'rotate',R    Index of the button used to enable rotation (default 7)
%
% Notes::
% - Joystick axes 0,1,3 map to X,Y,Z or R,P,Y motion.
% - A joystick button enables the mapping to translation OR rotation.
% - A 'delay' of zero means no pause
% - If 'delay' is non-zero 'scale' maps full scale to m/s or rad/s.
% - If 'delay' is zero 'scale' maps full scale to m/sample or rad/sample.
%
% See also joystick.

% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB.  If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com

function Tout = joy2tr(T, varargin)

    % parse the options
    opt.delay = 0.1;
    opt.rotate = 7;
    opt.scale = [0.5 0.25];
    opt.frame = {'tool', 'world'};
    opt.min = 0.006;

    opt = tb_optparse(opt, varargin);

    % get the raw joystick output
    [j,b] = joystick();

    % update a 6-vector of translational and rotational velocities
    vel = zeros(1,6);
    if b(7) == 0
        % translation mode
        vel(1:2) = j(1:2);
        vel(3) = j(4);
    else
        % rotation mode
        vel(4:5) = j(1:2);
        vel(6) = j(4);
    end

    % values below threshold are set to zero
    vel(abs(vel) < opt.min) = 0;

    % apply scaling factors
    scale = opt.scale;

    if opt.delay > 0
        % normalize scaling factors by time
        pause(opt.delay);
        scale = scale * opt.delay;
    end

    vel(1:3) = vel(1:3) * scale(1);
    vel(4:6) = vel(4:6) * scale(2);

    % compute the incremental motion
    dT = transl(vel(1:3)) * rpy2tr(vel(4:6));

    % and apply it to the input transform
    switch opt.frame
        case 'tool'
            Tout = T * dT;
        case 'world'
            Tout = dT * T;
    end

    % normalize just to be safe
    Tout = trnorm(Tout);


classdef SO3FunComposition < SO3Fun
% a class representing a function on the rotation group as sum of other
% SO3Funs. Therefore the summands possibly are different subclasses of
% SO3Fun (e.g. SO3FunRBF, SO3FunCBF, SO3FunBingham, ...), which are stored as components.
%
% Syntax
%   SO3F = SO3FunComposition(F1,F2,F3)
%
% Input
%  F1,F2,F3 - @SO3Fun
%
% Output
%  SO3F - @SO3FunComposition
%
% Example
%
%   F1 = SO3FunCBF.example;
%   F2 = SO3FunRBF.example;
%   F2.CS = F1.CS;
%   SO3F = F1+F2
%
%

properties
  components = {}
end

properties (Dependent = true)
  bandwidth % harmonic degree
  % TODO: antipodal wird nicht gesetzt/verwendet
  antipodal
  SLeft
  SRight
  weights
end

methods
  function SO3F = SO3FunComposition(varargin)

    % construct cell array of all components
    components =[];
    isCompo = cellfun(@(x) isa(x,'SO3FunComposition'),varargin);
    if any(isCompo)
      isCompoComponents = cellfun(@(x) x.components,varargin(isCompo),'UniformOutput',false);
      components = [isCompoComponents{:}];
      varargin(isCompo) = [];
    end
    components = [components,varargin];

    % check for equal sizes
    if any(cellfun(@numel,components)~=1)
      error('The components have to be equalsized.')
    end

    % constant component
    c = 0;
    isConstant = cellfun(@isnumeric,components);
    if any(isConstant)
      c = c + sum([components{isConstant}]);
    end
    isUniform = cellfun(@(x) isa(x,'SO3FunRBF') && x.c0~=0 && isempty(x.weights),components);
    if any(isUniform)
      c = c + sum(cellfun(@(x) x.c0, components(isUniform)));
    end
    isRBFandUniform = cellfun(@(x) isa(x,'SO3FunRBF') && x.c0~=0 && ~isempty(x.weights),components);
    for ind = find(isRBFandUniform)
      c = c + components{ind}.c0;
      components{ind}.c0 = 0;
    end

    % fourier component
    Harm = 0;
    isHarmonic = cellfun(@(x) isa(x,'SO3FunHarmonic'),components);
    if any(isHarmonic)
      Harm = sum([components{isHarmonic}],2);
    end

    % write constant and fourier components
    SO3F.components = {};
    if c~=0
      % choose Symmetry (properties of ensureCompatibleSymmetries, i.e. symmetries have to be the same)
      if any(~isConstant & ~isUniform)
        CS = components{find(~isConstant & ~isUniform,1)}.CS;
        SS = components{find(~isConstant & ~isUniform,1)}.SS;
      else
        CS = crystalSymmetry;
        SS = specimenSymmetry;
      end
      SO3F.components = {c * uniformODF(CS,SS)};
    end
    if any(isHarmonic)
      SO3F.components = [SO3F.components,{Harm}];
    end

    % remaining components
    isRemaining = ~isConstant & ~isHarmonic & ~isUniform;
    if any(isRemaining)
      SO3F.components = [SO3F.components,components(isRemaining)];
    end

    % ensureCompatibleSymmetries
    if var(cellfun(@(x) x.CS.id ,SO3F.components)) ~=0 || ...
          var(cellfun(@(x) x.SS.id ,SO3F.components)) ~= 0
      error('Calculations with @SO3Fun''s are not supported if the symmetries are not compatible.')
    end

  end

  function f = eval(SO3F,rot,varargin)

%     if isa(rot,'orientation')
%       ensureCompatibleSymmetries(SO3F,rot)
%     end

    f = 0;
    for k = 1:length(SO3F.components)
      f = f + eval(SO3F.components{k},rot,varargin{:});
    end

    if isalmostreal(f)
      f = real(f);
    end

  end

  function w = get.weights(S3F)
    w = cellfun(@(x) mean(x,'all'), S3F.components);
  end

  function out = get.antipodal(S3F)
    out = all(cellfun(@(x) x.antipodal ,S3F.components));
  end

  function out = get.bandwidth(S3F)
    out =  max(cellfun(@(x) x.bandwidth,S3F.components));
  end

  function out = get.SLeft(S3F)
    out = S3F.components{1}.SLeft;
  end

  function out = get.SRight(S3F)
    out = S3F.components{1}.SRight;
  end

  function SO3F = set.SRight(SO3F,CS)
   for k=1:length(SO3F.components)
     SO3F.components{k}.SRight = CS;
   end
  end

  function SO3F = set.SLeft(SO3F,SS)
    for k=1:length(SO3F.components)
     SO3F.components{k}.SLeft = SS;
   end
  end

end

methods (Static = true)

  SO3F = example(varargin)

end

end


%islmatrix - Test if parameter is a logical matrix (>= 2 columns).
%
%  USAGE
%
%    test = islmatrix(x)
%
%    x              parameter to test
%
%  NOTE
%
%    To be considered logical, the matrix should contain only values 0 and 1, but it
%    does not need to actually be of class 'logical' (class(x) could be e.g. 'double').
%
%  SEE ALSO
%
%    See also islscalar, islvector, isdmatrix, isdvector, isdscalar, isivector, isiscalar,
%    isstring.
%

% Copyright (C) 2010-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

function test = islmatrix(x)

% Check number of parameters
if nargin < 1,
  error('Incorrect number of parameters (type ''help islmatrix'' for details).');
end

% Test: logical, two dimensions, two or more columns?
test = islogical(x) & length(size(x)) == 2 & size(x,2) >= 2;

function test = islogical(x)

test = builtin('islogical',x) | all(x(:)==0|x(:)==1);


function [new_center,cl]=update_centers(SD,II,E,K,num,center)
center;
for iter1=2:num,
    com=SD(:,iter1);
    i1=II(:,iter1);
    comp=[com,II(:,1),i1];
    if size(find(center),1)==num,
       aa=sortrows(comp);
       bb=flipud(aa);
    else
        for i=1:size(find(center),1)
            a=center(find(center));
            b(i,:)=comp(a(i),:);
        end
       aa=sortrows(b);
       bb=flipud(aa);
    end
    for iter2=1:size(bb,1),
        row=bb(iter2,2);
        column=bb(iter2,3);
        sum1=E(row,1);
        sum2=E(column,1);
        if sum1>sum2,
           center(column,:)=[0];
           comp(column,3)=[0];
        else
           center(row,:)=[0];
           comp(row,2)=[0];
        end
        new_center=find(center);
        kk=size(new_center,1);
        if kk==K,
            break;
        end
    end
    if kk==K
       break;
    end
end
for i=1:num,
    for j=1:K,
        ind2=find(II(i,:)==new_center(j));
        temp(j,:)=SD(i,ind2);
    end
    [a,b]=max(temp);
    cl(i,:)=new_center(b);
end


function t_opf_dc_bpmpd(quiet)
%T_OPF_DC_BPMPD  Tests for DC optimal power flow using BPMPD_MEX solver.

%   MATPOWER
%   Copyright (c) 2004-2021, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

if nargin < 1
    quiet = 0;
end

num_tests = 43;

t_begin(num_tests, quiet);

[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;

casefile = 't_case9_opf';
if quiet
    verbose = 0;
else
    verbose = 0;
end

t0 = 'DC OPF (BPMPD): ';
mpopt = mpoption('out.all', 0, 'verbose', verbose);
mpopt = mpoption(mpopt, 'opf.dc.solver', 'BPMPD');

%% run DC OPF
if have_feature('bpmpd')
    %% set up indices
    ib_data     = [1:BUS_AREA BASE_KV:VMIN];
    ib_voltage  = [VM VA];
    ib_lam      = [LAM_P LAM_Q];
    ib_mu       = [MU_VMAX MU_VMIN];
    ig_data     = [GEN_BUS QMAX QMIN MBASE:APF];
    ig_disp     = [PG QG VG];
    ig_mu       = (MU_PMAX:MU_QMIN);
    ibr_data    = (1:ANGMAX);
    ibr_flow    = (PF:QT);
    ibr_mu      = [MU_SF MU_ST];
    ibr_angmu   = [MU_ANGMIN MU_ANGMAX];

    %% get solved DC power flow case from MAT-file
    load soln9_dcopf;       %% defines bus_soln, gen_soln, branch_soln, f_soln

    %% run OPF
    t = t0;
    [baseMVA, bus, gen, gencost, branch, f, success, et] = rundcopf(casefile, mpopt);
    t_ok(success, [t 'success']);
    t_is(f, f_soln, 3, [t 'f']);
    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);
    t_is(   bus(:,ib_voltage),    bus_soln(:,ib_voltage),  3, [t 'bus voltage']);
    t_is(   bus(:,ib_lam    ),    bus_soln(:,ib_lam    ),  3, [t 'bus lambda']);
    t_is(   bus(:,ib_mu     ),    bus_soln(:,ib_mu     ),  2, [t 'bus mu']);
    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);
    t_is(   gen(:,ig_disp   ),    gen_soln(:,ig_disp   ),  3, [t 'gen dispatch']);
    t_is(   gen(:,ig_mu     ),    gen_soln(:,ig_mu     ),  3, [t 'gen mu']);
    t_is(branch(:,ibr_data  ), branch_soln(:,ibr_data  ), 10, [t 'branch data']);
    t_is(branch(:,ibr_flow  ), branch_soln(:,ibr_flow  ),  3, [t 'branch flow']);
    t_is(branch(:,ibr_mu    ), branch_soln(:,ibr_mu    ),  2, [t 'branch mu']);

    %%-----  test OPF with angle difference limits  -----
    t = [t0 'w/angle diff lims : '];
    mpc = loadcase(casefile);
    mpc.branch(4, ANGMAX) = 3;
    mpc.branch(7, ANGMIN) = -4.5;
    r = rundcopf(mpc, mpopt);
    [bus, gen, branch, f, success] = deal(r.bus, r.gen, r.branch, r.f, r.success);
    t_ok(success, [t 'success']);
    t_is(   f, 6456.7213, 3, [t 'f']);
    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);
    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);
    t_is(   gen(:,PG        ),    [99.98497;89.35133;125.66371], 4, [t 'gen dispatch']);
    t_is(branch(:,ibr_data  ), mpc.branch(:,ibr_data   ), 10, [t 'branch data']);
    e = zeros(size(branch, 1), 1);
    e(4) = 297.83776;
    e(7) = -26.94788;
    t_is(branch(:,MU_ANGMAX )-branch(:,MU_ANGMIN ), e, 4, [t 'branch ang diff mu']);

    t = [t0 'w/ignored angle diff lims : '];
    mpopt1 = mpoption(mpopt, 'opf.ignore_angle_lim', 1);
    r = rundcopf(mpc, mpopt1);
    [bus, gen, branch, f, success] = deal(r.bus, r.gen, r.branch, r.f, r.success);
    t_ok(success, [t 'success']);
    t_is(f, f_soln, 3, [t 'f']);
    t_is(   bus(:,ib_data   ),    bus_soln(:,ib_data   ), 10, [t 'bus data']);
    t_is(   bus(:,ib_voltage),    bus_soln(:,ib_voltage),  3, [t 'bus voltage']);
    t_is(   bus(:,ib_lam    ),    bus_soln(:,ib_lam    ),  3, [t 'bus lambda']);
    t_is(   bus(:,ib_mu     ),    bus_soln(:,ib_mu     ),  2, [t 'bus mu']);
    t_is(   gen(:,ig_data   ),    gen_soln(:,ig_data   ), 10, [t 'gen data']);
    t_is(   gen(:,ig_disp   ),    gen_soln(:,ig_disp   ),  3, [t 'gen dispatch']);
    t_is(   gen(:,ig_mu     ),    gen_soln(:,ig_mu     ),  3, [t 'gen mu']);
    t_is(branch(:,ibr_data  ), mpc.branch(:,ibr_data   ), 10, [t 'branch data']);
    t_is(branch(:,ibr_flow  ), branch_soln(:,ibr_flow  ),  3, [t 'branch flow']);
    t_is(branch(:,ibr_mu    ), branch_soln(:,ibr_mu    ),  2, [t 'branch mu']);

    %%-----  run OPF with extra linear user constraints & costs  -----
    %% two new z variables
    %%      0 <= z1, P3 - P1 <= z1
    %%      0 <= z2, P3 - P2 <= z2
    %% with A and N sized for DC opf
    mpc = loadcase(casefile);
    mpc.A = sparse([1;1;1;2;2;2],[10;12;13;12;11;14],[-1;1;-1;1;-1;-1],2,14);
    mpc.u = [0; 0];
    mpc.l = [-Inf; -Inf];
    mpc.zl = [0; 0];

    mpc.N = sparse([1;2], [13;14], [1;1], 2, 14);   %% new z variables only
    mpc.fparm = ones(2,1) * [1 0 0 1];              %% w = r = z
    mpc.H = sparse(2,2);                            %% no quadratic term
    mpc.Cw = [1000;1];

    t = [t0 'w/extra constraints & costs 1 : '];
    [r, success] = rundcopf(mpc, mpopt);
    t_ok(success, [t 'success']);
    t_is(r.gen(1, PG), 116.15974, 5, [t 'Pg1 = 116.15974']);
    t_is(r.gen(3, PG), 116.15974, 5, [t 'Pg3 = 116.15974']);
    t_is(r.var.val.z, [0; 0.3348], 4, [t 'user vars']);
    t_is(r.cost.usr, 0.3348, 4, [t 'user costs']);

    %% with A and N sized for AC opf
    mpc = loadcase(casefile);
    mpc.A = sparse([1;1;1;2;2;2],[19;21;25;21;20;26],[-1;1;-1;1;-1;-1],2,26);
    mpc.u = [0; 0];
    mpc.l = [-Inf; -Inf];
    mpc.zl = [0; 0];

    mpc.N = sparse([1;2], [25;26], [1;1], 2, 26);   %% new z variables only
    mpc.fparm = ones(2,1) * [1 0 0 1];              %% w = r = z
    mpc.H = sparse(2,2);                            %% no quadratic term
    mpc.Cw = [1000;1];

    t = [t0 'w/extra constraints & costs 2 : '];
    [r, success] = rundcopf(mpc, mpopt);
    t_ok(success, [t 'success']);
    t_is(r.gen(1, PG), 116.15974, 5, [t 'Pg1 = 116.15974']);
    t_is(r.gen(3, PG), 116.15974, 5, [t 'Pg3 = 116.15974']);
    t_is(r.var.val.z, [0; 0.3348], 4, [t 'user vars']);
    t_is(r.cost.usr, 0.3348, 4, [t 'user costs']);

    t = [t0 'infeasible : '];
    %% with A and N sized for DC opf
    mpc = loadcase(casefile);
    mpc.A = sparse([1;1], [10;11], [1;1], 1, 14);   %% Pg1 + Pg2
    mpc.u = Inf;
    mpc.l = 600;
    [r, success] = rundcopf(mpc, mpopt);
    t_ok(~success, [t 'no success']);

    %% OPF with all buses isolated
    t = [t0 'all buses isolated : '];
    mpc = loadcase(casefile);
    mpc.bus(:, BUS_TYPE) = NONE;
    try
        r = rundcopf(mpc, mpopt);
        t_is(r.success, 0, 12, [t 'success = 0']);
    catch
        t_ok(0, [t 'unexpected fatal error']);
    end
else
    t_skip(num_tests, 'BPMPD_MEX not available');
end

t_end;